<commit_before>/* =======================================================================
   Copyright (c) 2011, Institute for Microelectronics,
                       Institute for Analysis and Scientific Computing,
                       TU Wien.

                            -----------------
                     ViennaGrid - The Vienna Grid Library
                            -----------------

   Authors:      Karl Rupp                           rupp@iue.tuwien.ac.at
                 Josef Weinbub                    weinbub@iue.tuwien.ac.at

   (A list of additional contributors can be found in the PDF manual)

   License:      MIT (X11), see file LICENSE in the base directory
======================================================================= */

#ifndef VIENNAGRID_SEGMENT_ITERATORS_HPP
#define VIENNAGRID_SEGMENT_ITERATORS_HPP

#include <vector>
#include <list>
#include <map>
#include <stack>

#include "viennagrid/forwards.h"
#include "viennagrid/detail/domain_iterators.hpp"
#include "viennagrid/detail/element_iterators.hpp"
#include "viennagrid/segment.hpp"

namespace viennagrid
{

  template <typename IteratorType, typename ElementType>
  class on_segment_iterator : public std::iterator < std::forward_iterator_tag, ElementType >
  {
      typedef on_segment_iterator<IteratorType, ElementType>        self_type;

    public:
      on_segment_iterator(IteratorType const & it) : iter_(it) {}

      ElementType & operator*() const { return **iter_; }
      ElementType * operator->() const { return *iter_; }

      self_type & operator++() { ++iter_; return *this; }
      self_type operator++(int) { self_type tmp = *this; ++*this; return tmp; }

      bool operator==(const self_type & i) const { return iter_ == i.iter_; }
      bool operator!=(const self_type & i) const { return iter_ != i.iter_; }

    private:
      IteratorType iter_;
  };

  template <typename IteratorType, typename ElementType>
  class const_on_segment_iterator : public std::iterator < std::forward_iterator_tag, ElementType >
  {
      typedef const_on_segment_iterator<IteratorType, ElementType>        self_type;
    public:
      const_on_segment_iterator(IteratorType const & it) : iter_(it) {}

      const ElementType & operator*() const { return **iter_; }
      const ElementType * operator->() const { return *iter_; }

      self_type & operator++() { ++iter_; return *this; }
      self_type operator++(int) { self_type tmp = *this; ++*this; return tmp; }

      bool operator==(const self_type& i) const { return iter_ == i.iter_; }
      bool operator!=(const self_type& i) const { return iter_ != i.iter_; }

    private:
      IteratorType iter_;
  };

  //generic segment iterator
  template <typename Config,
            dim_type dim,
            dim_type cell_level = Config::cell_tag::topology_level>
  struct segment_iterators;

  //special case: cells:
  template <typename Config, dim_type cell_level>
  struct segment_iterators< Config, cell_level, cell_level>
  {
    typedef segment_t<Config>                     segment_type;
    typedef element_t<Config,
                    typename Config::cell_tag>    cell_type;

    typedef typename result_of::element_container<segment_type,
                                                  Config::cell_tag::topology_level>::type   container_type;

    typedef typename container_type::iterator          iterator;
    typedef typename container_type::const_iterator    const_iterator;
  };

  //non-const iteration:
  // interface function for container creation,
  // non-const:

  //container for iteration over a STL vector
  template <typename config_type, dim_type dim>
  class ncell_range < segment_t<config_type>, dim, false >
  {
      typedef segment_t<config_type>                        segment_type;
      typedef element_t< config_type,
                       typename topology::subcell_desc<typename config_type::cell_tag, dim>::element_tag
                     >                                                         element_type;

      typedef element_t< config_type,
                       typename config_type::cell_tag
                     >                                                         cell_type;

      //typedef std::vector< element_type >     container_type;
      typedef typename result_of::element_container<segment_type, dim>::type   container_type;

    public:
      //typedef typename container_type::iterator   iterator;
      typedef on_segment_iterator< typename container_type::iterator, element_type >   iterator;

      ncell_range() : cont_(NULL) {};

      ncell_range(ncell_proxy<segment_type> const & p) : cont_(p.get().template container<dim>()) {}

      ncell_range(segment_type & d) : cont_(d.template container<dim>()) {}

      ncell_range & operator=(ncell_proxy<segment_type> p)
      {
        cont_ = p.get().template container<dim>();
        return *this;
      }

      iterator begin() const { return iterator(cont_->begin()); }
      iterator end()   const { return iterator(cont_->end()); }

      std::size_t size() const { return cont_->size(); }

      element_type & operator[](std::size_t index)
      {
        //typedef typename assert_bracket_operator_access<container_type>::type  asserted_type;
        assert(index < size());
        typename container_type::iterator it = cont_->begin();
        for (std::size_t i=0; i<index; ++i)
          ++it;

        //return *((*cont_)[index]);
        return **it;
      }

      element_type const & operator[](std::size_t index) const
      {
        typedef typename assert_bracket_operator_access<container_type>::type  asserted_type;
        assert(index < size());
        return *((*cont_)[index]);
      }

      template <typename DomainType, dim_type dim2, bool b2>
      friend class const_ncell_range;

    private:
      container_type * cont_;
  };

  template <dim_type dim, typename DomainConfig>
  ncell_range<segment_t<DomainConfig>, dim>
  ncells(segment_t<DomainConfig> & d)
  {
    return ncell_range< segment_t<DomainConfig>, dim>(d);
  }

  template <typename DomainConfig>
  ncell_proxy< segment_t<DomainConfig> >
  ncells(segment_t<DomainConfig> & d)
  {
    return ncell_proxy< segment_t<DomainConfig> >(d);
  }

  //
  // const version
  //

  template <typename config_type, dim_type dim>
  class const_ncell_range < segment_t<config_type>, dim, false >
  {
      typedef segment_t<config_type>                        segment_type;
      typedef element_t< config_type,
                       typename topology::subcell_desc<typename config_type::cell_tag, dim>::element_tag
                     >                                                         element_type;

      typedef element_t< config_type,
                       typename config_type::cell_tag
                     >                                                         cell_type;

      //typedef std::vector< element_type >     container_type;
      typedef typename result_of::element_container<segment_type, dim>::type      container_type;

    public:
      //typedef typename container_type::const_iterator   iterator;
      typedef on_segment_iterator< typename container_type::const_iterator, const element_type >   iterator;

      const_ncell_range() : cont_(NULL) {};

      const_ncell_range(const_ncell_proxy< segment_type > const & p) : cont_(p.get().template container<dim>()) {}

      const_ncell_range(ncell_proxy< segment_type > const & p) : cont_(p.get().template container<dim>()) {}

      const_ncell_range(segment_type const & d) : cont_(d.template container<dim>()) {}

      const_ncell_range(ncell_range<segment_type, dim > const & other) : cont_(other.cont_) {}

      const_ncell_range & operator=(const_ncell_proxy< segment_type > const & p)
      {
        cont_ = p.get().template container<dim>();
        return *this;
      }

      iterator begin() const { return iterator(cont_->begin()); }
      iterator end()   const { return iterator(cont_->end()); }

      std::size_t size() const { return cont_->size(); }

      element_type & operator[](std::size_t index)
      {
        typedef typename assert_bracket_operator_access<container_type>::type  asserted_type;
        assert(index < size());
        return *((*cont_)[index]);
      }

      element_type const & operator[](std::size_t index) const
      {
        typedef typename assert_bracket_operator_access<container_type>::type  asserted_type;
        assert(index < size());
        return *((*cont_)[index]);
      }

    private:
      const container_type * cont_;
  };

  template <dim_type dim, typename DomainConfig>
  const_ncell_range< segment_t<DomainConfig>, dim>
  ncells(segment_t<DomainConfig> const & d)
  {
    return const_ncell_range< segment_t<DomainConfig>, dim>(d);
  }

  template <typename DomainConfig>
  const_ncell_proxy< segment_t<DomainConfig> >
  ncells(segment_t<DomainConfig> const & d)
  {
    return const_ncell_proxy< segment_t<DomainConfig> >(d);
  }

} //namespace
#endif

<commit_msg>Reverted operator[]-modification in segment_iterators.hpp. Was introduced with last commit for testing purposes.<commit_after>/* =======================================================================
   Copyright (c) 2011, Institute for Microelectronics,
                       Institute for Analysis and Scientific Computing,
                       TU Wien.

                            -----------------
                     ViennaGrid - The Vienna Grid Library
                            -----------------

   Authors:      Karl Rupp                           rupp@iue.tuwien.ac.at
                 Josef Weinbub                    weinbub@iue.tuwien.ac.at

   (A list of additional contributors can be found in the PDF manual)

   License:      MIT (X11), see file LICENSE in the base directory
======================================================================= */

#ifndef VIENNAGRID_SEGMENT_ITERATORS_HPP
#define VIENNAGRID_SEGMENT_ITERATORS_HPP

#include <vector>
#include <list>
#include <map>
#include <stack>

#include "viennagrid/forwards.h"
#include "viennagrid/detail/domain_iterators.hpp"
#include "viennagrid/detail/element_iterators.hpp"
#include "viennagrid/segment.hpp"

namespace viennagrid
{

  template <typename IteratorType, typename ElementType>
  class on_segment_iterator : public std::iterator < std::forward_iterator_tag, ElementType >
  {
      typedef on_segment_iterator<IteratorType, ElementType>        self_type;

    public:
      on_segment_iterator(IteratorType const & it) : iter_(it) {}

      ElementType & operator*() const { return **iter_; }
      ElementType * operator->() const { return *iter_; }

      self_type & operator++() { ++iter_; return *this; }
      self_type operator++(int) { self_type tmp = *this; ++*this; return tmp; }

      bool operator==(const self_type & i) const { return iter_ == i.iter_; }
      bool operator!=(const self_type & i) const { return iter_ != i.iter_; }

    private:
      IteratorType iter_;
  };

  template <typename IteratorType, typename ElementType>
  class const_on_segment_iterator : public std::iterator < std::forward_iterator_tag, ElementType >
  {
      typedef const_on_segment_iterator<IteratorType, ElementType>        self_type;
    public:
      const_on_segment_iterator(IteratorType const & it) : iter_(it) {}

      const ElementType & operator*() const { return **iter_; }
      const ElementType * operator->() const { return *iter_; }

      self_type & operator++() { ++iter_; return *this; }
      self_type operator++(int) { self_type tmp = *this; ++*this; return tmp; }

      bool operator==(const self_type& i) const { return iter_ == i.iter_; }
      bool operator!=(const self_type& i) const { return iter_ != i.iter_; }

    private:
      IteratorType iter_;
  };

  //generic segment iterator
  template <typename Config,
            dim_type dim,
            dim_type cell_level = Config::cell_tag::topology_level>
  struct segment_iterators;

  //special case: cells:
  template <typename Config, dim_type cell_level>
  struct segment_iterators< Config, cell_level, cell_level>
  {
    typedef segment_t<Config>                     segment_type;
    typedef element_t<Config,
                    typename Config::cell_tag>    cell_type;

    typedef typename result_of::element_container<segment_type,
                                                  Config::cell_tag::topology_level>::type   container_type;

    typedef typename container_type::iterator          iterator;
    typedef typename container_type::const_iterator    const_iterator;
  };

  //non-const iteration:
  // interface function for container creation,
  // non-const:

  //container for iteration over a STL vector
  template <typename config_type, dim_type dim>
  class ncell_range < segment_t<config_type>, dim, false >
  {
      typedef segment_t<config_type>                        segment_type;
      typedef element_t< config_type,
                       typename topology::subcell_desc<typename config_type::cell_tag, dim>::element_tag
                     >                                                         element_type;

      typedef element_t< config_type,
                       typename config_type::cell_tag
                     >                                                         cell_type;

      //typedef std::vector< element_type >     container_type;
      typedef typename result_of::element_container<segment_type, dim>::type   container_type;

    public:
      //typedef typename container_type::iterator   iterator;
      typedef on_segment_iterator< typename container_type::iterator, element_type >   iterator;

      ncell_range() : cont_(NULL) {};

      ncell_range(ncell_proxy<segment_type> const & p) : cont_(p.get().template container<dim>()) {}

      ncell_range(segment_type & d) : cont_(d.template container<dim>()) {}

      ncell_range & operator=(ncell_proxy<segment_type> p)
      {
        cont_ = p.get().template container<dim>();
        return *this;
      }

      iterator begin() const { return iterator(cont_->begin()); }
      iterator end()   const { return iterator(cont_->end()); }

      std::size_t size() const { return cont_->size(); }

      element_type & operator[](std::size_t index)
      {
        typedef typename assert_bracket_operator_access<container_type>::type  asserted_type;
        assert(index < size());
        return *((*cont_)[index]);
      }

      element_type const & operator[](std::size_t index) const
      {
        typedef typename assert_bracket_operator_access<container_type>::type  asserted_type;
        assert(index < size());
        return *((*cont_)[index]);
      }

      template <typename DomainType, dim_type dim2, bool b2>
      friend class const_ncell_range;

    private:
      container_type * cont_;
  };

  template <dim_type dim, typename DomainConfig>
  ncell_range<segment_t<DomainConfig>, dim>
  ncells(segment_t<DomainConfig> & d)
  {
    return ncell_range< segment_t<DomainConfig>, dim>(d);
  }

  template <typename DomainConfig>
  ncell_proxy< segment_t<DomainConfig> >
  ncells(segment_t<DomainConfig> & d)
  {
    return ncell_proxy< segment_t<DomainConfig> >(d);
  }

  //
  // const version
  //

  template <typename config_type, dim_type dim>
  class const_ncell_range < segment_t<config_type>, dim, false >
  {
      typedef segment_t<config_type>                        segment_type;
      typedef element_t< config_type,
                       typename topology::subcell_desc<typename config_type::cell_tag, dim>::element_tag
                     >                                                         element_type;

      typedef element_t< config_type,
                       typename config_type::cell_tag
                     >                                                         cell_type;

      //typedef std::vector< element_type >     container_type;
      typedef typename result_of::element_container<segment_type, dim>::type      container_type;

    public:
      //typedef typename container_type::const_iterator   iterator;
      typedef on_segment_iterator< typename container_type::const_iterator, const element_type >   iterator;

      const_ncell_range() : cont_(NULL) {};

      const_ncell_range(const_ncell_proxy< segment_type > const & p) : cont_(p.get().template container<dim>()) {}

      const_ncell_range(ncell_proxy< segment_type > const & p) : cont_(p.get().template container<dim>()) {}

      const_ncell_range(segment_type const & d) : cont_(d.template container<dim>()) {}

      const_ncell_range(ncell_range<segment_type, dim > const & other) : cont_(other.cont_) {}

      const_ncell_range & operator=(const_ncell_proxy< segment_type > const & p)
      {
        cont_ = p.get().template container<dim>();
        return *this;
      }

      iterator begin() const { return iterator(cont_->begin()); }
      iterator end()   const { return iterator(cont_->end()); }

      std::size_t size() const { return cont_->size(); }

      element_type & operator[](std::size_t index)
      {
        typedef typename assert_bracket_operator_access<container_type>::type  asserted_type;
        assert(index < size());
        return *((*cont_)[index]);
      }

      element_type const & operator[](std::size_t index) const
      {
        typedef typename assert_bracket_operator_access<container_type>::type  asserted_type;
        assert(index < size());
        return *((*cont_)[index]);
      }

    private:
      const container_type * cont_;
  };

  template <dim_type dim, typename DomainConfig>
  const_ncell_range< segment_t<DomainConfig>, dim>
  ncells(segment_t<DomainConfig> const & d)
  {
    return const_ncell_range< segment_t<DomainConfig>, dim>(d);
  }

  template <typename DomainConfig>
  const_ncell_proxy< segment_t<DomainConfig> >
  ncells(segment_t<DomainConfig> const & d)
  {
    return const_ncell_proxy< segment_t<DomainConfig> >(d);
  }

} //namespace
#endif

<|endoftext|>


<commit_before>//========- unittests/Support/Host.cpp - Host.cpp tests --------------========//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/Host.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Program.h"

#include "gtest/gtest.h"

#define ASSERT_NO_ERROR(x)                                                     \
  if (std::error_code ASSERT_NO_ERROR_ec = x) {                                \
    SmallString<128> MessageStorage;                                           \
    raw_svector_ostream Message(MessageStorage);                               \
    Message << #x ": did not return errc::success.\n"                          \
            << "error number: " << ASSERT_NO_ERROR_ec.value() << "\n"          \
            << "error message: " << ASSERT_NO_ERROR_ec.message() << "\n";      \
    GTEST_FATAL_FAILURE_(MessageStorage.c_str());                              \
  } else {                                                                     \
  }

using namespace llvm;

class HostTest : public testing::Test {
  Triple Host;

protected:
  bool isSupportedArchAndOS() {
    // Initially this is only testing detection of the number of
    // physical cores, which is currently only supported/tested for
    // x86_64 Linux and Darwin.
    return (Host.getArch() == Triple::x86_64 &&
            (Host.isOSDarwin() || Host.getOS() == Triple::Linux));
  }

  HostTest() : Host(Triple::normalize(sys::getProcessTriple())) {}
};

TEST_F(HostTest, NumPhysicalCores) {
  int Num = sys::getHostNumPhysicalCores();

  if (isSupportedArchAndOS())
    ASSERT_GT(Num, 0);
  else
    ASSERT_EQ(Num, -1);
}

TEST(getLinuxHostCPUName, ARM) {
  StringRef CortexA9ProcCpuinfo = R"(
processor       : 0
model name      : ARMv7 Processor rev 10 (v7l)
BogoMIPS        : 1393.66
Features        : half thumb fastmult vfp edsp thumbee neon vfpv3 tls vfpd32
CPU implementer : 0x41
CPU architecture: 7
CPU variant     : 0x2
CPU part        : 0xc09
CPU revision    : 10

processor       : 1
model name      : ARMv7 Processor rev 10 (v7l)
BogoMIPS        : 1393.66
Features        : half thumb fastmult vfp edsp thumbee neon vfpv3 tls vfpd32
CPU implementer : 0x41
CPU architecture: 7
CPU variant     : 0x2
CPU part        : 0xc09
CPU revision    : 10

Hardware        : Generic OMAP4 (Flattened Device Tree)
Revision        : 0000
Serial          : 0000000000000000
)";

  EXPECT_EQ(sys::detail::getHostCPUNameForARM(CortexA9ProcCpuinfo),
            "cortex-a9");
  EXPECT_EQ(sys::detail::getHostCPUNameForARM("CPU implementer : 0x41\n"
                                              "CPU part        : 0xc0f"),
            "cortex-a15");
  // Verify that both CPU implementer and CPU part are checked:
  EXPECT_EQ(sys::detail::getHostCPUNameForARM("CPU implementer : 0x40\n"
                                              "CPU part        : 0xc0f"),
            "generic");
  EXPECT_EQ(sys::detail::getHostCPUNameForARM("CPU implementer : 0x51\n"
                                              "CPU part        : 0x06f"),
            "krait");
}

TEST(getLinuxHostCPUName, AArch64) {
  EXPECT_EQ(sys::detail::getHostCPUNameForARM("CPU implementer : 0x41\n"
                                              "CPU part        : 0xd03"),
            "cortex-a53");
  // Verify that both CPU implementer and CPU part are checked:
  EXPECT_EQ(sys::detail::getHostCPUNameForARM("CPU implementer : 0x40\n"
                                              "CPU part        : 0xd03"),
            "generic");
  EXPECT_EQ(sys::detail::getHostCPUNameForARM("CPU implementer : 0x51\n"
                                              "CPU part        : 0x201"),
            "kryo");

  // MSM8992/4 weirdness
  StringRef MSM8992ProcCpuInfo = R"(
Processor       : AArch64 Processor rev 3 (aarch64)
processor       : 0
processor       : 1
processor       : 2
processor       : 3
processor       : 4
processor       : 5
Features        : fp asimd evtstrm aes pmull sha1 sha2 crc32
CPU implementer : 0x41
CPU architecture: 8
CPU variant     : 0x0
CPU part        : 0xd03
CPU revision    : 3

Hardware        : Qualcomm Technologies, Inc MSM8992
)";

  EXPECT_EQ(sys::detail::getHostCPUNameForARM(MSM8992ProcCpuInfo),
            "cortex-a53");
}

#if defined(__APPLE__)
TEST_F(HostTest, getMacOSHostVersion) {
  using namespace llvm::sys;
  llvm::Triple HostTriple(getProcessTriple());
  if (!HostTriple.isMacOSX())
    return;

  SmallString<128> TestDirectory;
  ASSERT_NO_ERROR(fs::createUniqueDirectory("host_test", TestDirectory));
  SmallString<128> OutputFile(TestDirectory);
  path::append(OutputFile, "out");

  const char *SwVersPath = "/usr/bin/sw_vers";
  const char *argv[] = {SwVersPath, "-productVersion", nullptr};
  StringRef OutputPath = OutputFile.str();
  const StringRef *Redirects[] = {/*STDIN=*/nullptr, /*STDOUT=*/&OutputPath,
                                  /*STDERR=*/nullptr};
  int RetCode = ExecuteAndWait(SwVersPath, argv, /*env=*/nullptr, Redirects);
  ASSERT_EQ(0, RetCode);

  int FD = 0;
  ASSERT_NO_ERROR(fs::openFileForRead(OutputPath, FD));
  off_t Size = ::lseek(FD, 0, SEEK_END);
  ASSERT_NE(-1, Size);
  ::lseek(FD, 0, SEEK_SET);
  std::unique_ptr<char[]> Buffer = llvm::make_unique<char[]>(Size);
  ASSERT_EQ(::read(FD, Buffer.get(), Size), Size);
  ::close(FD);

  // Ensure that the two versions match.
  StringRef SystemVersion(Buffer.get(), Size);
  unsigned SystemMajor, SystemMinor, SystemMicro;
  ASSERT_EQ(llvm::Triple((Twine("x86_64-apple-macos") + SystemVersion))
                .getMacOSXVersion(SystemMajor, SystemMinor, SystemMicro),
            true);
  unsigned HostMajor, HostMinor, HostMicro;
  ASSERT_EQ(HostTriple.getMacOSXVersion(HostMajor, HostMinor, HostMicro), true);

  // Don't compare the 'Micro' version, as it's always '0' for the 'Darwin'
  // triples.
  ASSERT_EQ(std::tie(SystemMajor, SystemMinor), std::tie(HostMajor, HostMinor));

  ASSERT_NO_ERROR(fs::remove(OutputPath));
  ASSERT_NO_ERROR(fs::remove(TestDirectory.str()));
}
#endif
<commit_msg>[unittests] Fix up test after  rL313156<commit_after>//========- unittests/Support/Host.cpp - Host.cpp tests --------------========//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/Host.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Program.h"

#include "gtest/gtest.h"

#define ASSERT_NO_ERROR(x)                                                     \
  if (std::error_code ASSERT_NO_ERROR_ec = x) {                                \
    SmallString<128> MessageStorage;                                           \
    raw_svector_ostream Message(MessageStorage);                               \
    Message << #x ": did not return errc::success.\n"                          \
            << "error number: " << ASSERT_NO_ERROR_ec.value() << "\n"          \
            << "error message: " << ASSERT_NO_ERROR_ec.message() << "\n";      \
    GTEST_FATAL_FAILURE_(MessageStorage.c_str());                              \
  } else {                                                                     \
  }

using namespace llvm;

class HostTest : public testing::Test {
  Triple Host;

protected:
  bool isSupportedArchAndOS() {
    // Initially this is only testing detection of the number of
    // physical cores, which is currently only supported/tested for
    // x86_64 Linux and Darwin.
    return (Host.getArch() == Triple::x86_64 &&
            (Host.isOSDarwin() || Host.getOS() == Triple::Linux));
  }

  HostTest() : Host(Triple::normalize(sys::getProcessTriple())) {}
};

TEST_F(HostTest, NumPhysicalCores) {
  int Num = sys::getHostNumPhysicalCores();

  if (isSupportedArchAndOS())
    ASSERT_GT(Num, 0);
  else
    ASSERT_EQ(Num, -1);
}

TEST(getLinuxHostCPUName, ARM) {
  StringRef CortexA9ProcCpuinfo = R"(
processor       : 0
model name      : ARMv7 Processor rev 10 (v7l)
BogoMIPS        : 1393.66
Features        : half thumb fastmult vfp edsp thumbee neon vfpv3 tls vfpd32
CPU implementer : 0x41
CPU architecture: 7
CPU variant     : 0x2
CPU part        : 0xc09
CPU revision    : 10

processor       : 1
model name      : ARMv7 Processor rev 10 (v7l)
BogoMIPS        : 1393.66
Features        : half thumb fastmult vfp edsp thumbee neon vfpv3 tls vfpd32
CPU implementer : 0x41
CPU architecture: 7
CPU variant     : 0x2
CPU part        : 0xc09
CPU revision    : 10

Hardware        : Generic OMAP4 (Flattened Device Tree)
Revision        : 0000
Serial          : 0000000000000000
)";

  EXPECT_EQ(sys::detail::getHostCPUNameForARM(CortexA9ProcCpuinfo),
            "cortex-a9");
  EXPECT_EQ(sys::detail::getHostCPUNameForARM("CPU implementer : 0x41\n"
                                              "CPU part        : 0xc0f"),
            "cortex-a15");
  // Verify that both CPU implementer and CPU part are checked:
  EXPECT_EQ(sys::detail::getHostCPUNameForARM("CPU implementer : 0x40\n"
                                              "CPU part        : 0xc0f"),
            "generic");
  EXPECT_EQ(sys::detail::getHostCPUNameForARM("CPU implementer : 0x51\n"
                                              "CPU part        : 0x06f"),
            "krait");
}

TEST(getLinuxHostCPUName, AArch64) {
  EXPECT_EQ(sys::detail::getHostCPUNameForARM("CPU implementer : 0x41\n"
                                              "CPU part        : 0xd03"),
            "cortex-a53");
  // Verify that both CPU implementer and CPU part are checked:
  EXPECT_EQ(sys::detail::getHostCPUNameForARM("CPU implementer : 0x40\n"
                                              "CPU part        : 0xd03"),
            "generic");
  EXPECT_EQ(sys::detail::getHostCPUNameForARM("CPU implementer : 0x51\n"
                                              "CPU part        : 0x201"),
            "kryo");

  // MSM8992/4 weirdness
  StringRef MSM8992ProcCpuInfo = R"(
Processor       : AArch64 Processor rev 3 (aarch64)
processor       : 0
processor       : 1
processor       : 2
processor       : 3
processor       : 4
processor       : 5
Features        : fp asimd evtstrm aes pmull sha1 sha2 crc32
CPU implementer : 0x41
CPU architecture: 8
CPU variant     : 0x0
CPU part        : 0xd03
CPU revision    : 3

Hardware        : Qualcomm Technologies, Inc MSM8992
)";

  EXPECT_EQ(sys::detail::getHostCPUNameForARM(MSM8992ProcCpuInfo),
            "cortex-a53");
}

#if defined(__APPLE__)
TEST_F(HostTest, getMacOSHostVersion) {
  using namespace llvm::sys;
  llvm::Triple HostTriple(getProcessTriple());
  if (!HostTriple.isMacOSX())
    return;

  SmallString<128> TestDirectory;
  ASSERT_NO_ERROR(fs::createUniqueDirectory("host_test", TestDirectory));
  SmallString<128> OutputFile(TestDirectory);
  path::append(OutputFile, "out");

  const char *SwVersPath = "/usr/bin/sw_vers";
  const char *argv[] = {SwVersPath, "-productVersion", nullptr};
  StringRef OutputPath = OutputFile.str();
  const Optional<StringRef> Redirects[] = {/*STDIN=*/None,
                                           /*STDOUT=*/OutputPath,
                                           /*STDERR=*/None};
  int RetCode = ExecuteAndWait(SwVersPath, argv, /*env=*/nullptr, Redirects);
  ASSERT_EQ(0, RetCode);

  int FD = 0;
  ASSERT_NO_ERROR(fs::openFileForRead(OutputPath, FD));
  off_t Size = ::lseek(FD, 0, SEEK_END);
  ASSERT_NE(-1, Size);
  ::lseek(FD, 0, SEEK_SET);
  std::unique_ptr<char[]> Buffer = llvm::make_unique<char[]>(Size);
  ASSERT_EQ(::read(FD, Buffer.get(), Size), Size);
  ::close(FD);

  // Ensure that the two versions match.
  StringRef SystemVersion(Buffer.get(), Size);
  unsigned SystemMajor, SystemMinor, SystemMicro;
  ASSERT_EQ(llvm::Triple((Twine("x86_64-apple-macos") + SystemVersion))
                .getMacOSXVersion(SystemMajor, SystemMinor, SystemMicro),
            true);
  unsigned HostMajor, HostMinor, HostMicro;
  ASSERT_EQ(HostTriple.getMacOSXVersion(HostMajor, HostMinor, HostMicro), true);

  // Don't compare the 'Micro' version, as it's always '0' for the 'Darwin'
  // triples.
  ASSERT_EQ(std::tie(SystemMajor, SystemMinor), std::tie(HostMajor, HostMinor));

  ASSERT_NO_ERROR(fs::remove(OutputPath));
  ASSERT_NO_ERROR(fs::remove(TestDirectory.str()));
}
#endif
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/media/base/videoframe.h"

#include <string.h>

#include "libyuv/compare.h"
#include "libyuv/planar_functions.h"
#include "libyuv/scale.h"
#include "webrtc/base/arraysize.h"
#include "webrtc/base/checks.h"
#include "webrtc/base/logging.h"
#include "webrtc/media/base/videocommon.h"

namespace cricket {

size_t VideoFrame::ConvertToRgbBuffer(uint32_t to_fourcc,
                                      uint8_t* buffer,
                                      size_t size,
                                      int stride_rgb) const {
  const size_t needed = std::abs(stride_rgb) * static_cast<size_t>(height());
  if (size < needed) {
    LOG(LS_WARNING) << "RGB buffer is not large enough";
    return needed;
  }

  if (libyuv::ConvertFromI420(
          video_frame_buffer()->DataY(), video_frame_buffer()->StrideY(),
          video_frame_buffer()->DataU(), video_frame_buffer()->StrideU(),
          video_frame_buffer()->DataV(), video_frame_buffer()->StrideV(),
          buffer, stride_rgb, width(), height(), to_fourcc)) {
    LOG(LS_ERROR) << "RGB type not supported: " << to_fourcc;
    return 0;  // 0 indicates error
  }
  return needed;
}

static const size_t kMaxSampleSize = 1000000000u;
// Returns whether a sample is valid.
bool VideoFrame::Validate(uint32_t fourcc,
                          int w,
                          int h,
                          const uint8_t* sample,
                          size_t sample_size) {
  if (h < 0) {
    h = -h;
  }
  // 16384 is maximum resolution for VP8 codec.
  if (w < 1 || w > 16384 || h < 1 || h > 16384) {
    LOG(LS_ERROR) << "Invalid dimensions: " << w << "x" << h;
    return false;
  }
  uint32_t format = CanonicalFourCC(fourcc);
  int expected_bpp = 8;
  switch (format) {
    case FOURCC_I400:
    case FOURCC_RGGB:
    case FOURCC_BGGR:
    case FOURCC_GRBG:
    case FOURCC_GBRG:
      expected_bpp = 8;
      break;
    case FOURCC_I420:
    case FOURCC_I411:
    case FOURCC_YU12:
    case FOURCC_YV12:
    case FOURCC_M420:
    case FOURCC_NV21:
    case FOURCC_NV12:
      expected_bpp = 12;
      break;
    case FOURCC_I422:
    case FOURCC_YV16:
    case FOURCC_YUY2:
    case FOURCC_UYVY:
    case FOURCC_RGBP:
    case FOURCC_RGBO:
    case FOURCC_R444:
      expected_bpp = 16;
      break;
    case FOURCC_I444:
    case FOURCC_YV24:
    case FOURCC_24BG:
    case FOURCC_RAW:
      expected_bpp = 24;
      break;

    case FOURCC_ABGR:
    case FOURCC_BGRA:
    case FOURCC_ARGB:
      expected_bpp = 32;
      break;

    case FOURCC_MJPG:
    case FOURCC_H264:
      expected_bpp = 0;
      break;
    default:
      expected_bpp = 8;  // Expect format is at least 8 bits per pixel.
      break;
  }
  size_t expected_size = (w * expected_bpp + 7) / 8 * h;
  // For compressed formats, expect 4 bits per 16 x 16 macro.  I420 would be
  // 6 bits, but grey can be 4 bits.
  if (expected_bpp == 0) {
    expected_size = ((w + 15) / 16) * ((h + 15) / 16) * 4 / 8;
  }
  if (sample == NULL) {
    LOG(LS_ERROR) << "NULL sample pointer."
                  << " format: " << GetFourccName(format)
                  << " bpp: " << expected_bpp
                  << " size: " << w << "x" << h
                  << " expected: " << expected_size
                  << " " << sample_size;
    return false;
  }
  // TODO(fbarchard): Make function to dump information about frames.
  uint8_t four_samples[4] = {0, 0, 0, 0};
  for (size_t i = 0; i < arraysize(four_samples) && i < sample_size; ++i) {
    four_samples[i] = sample[i];
  }
  if (sample_size < expected_size) {
    LOG(LS_ERROR) << "Size field is too small."
                  << " format: " << GetFourccName(format)
                  << " bpp: " << expected_bpp
                  << " size: " << w << "x" << h
                  << " " << sample_size
                  << " expected: " << expected_size
                  << " sample[0..3]: " << static_cast<int>(four_samples[0])
                  << ", " << static_cast<int>(four_samples[1])
                  << ", " << static_cast<int>(four_samples[2])
                  << ", " << static_cast<int>(four_samples[3]);
    return false;
  }
  if (sample_size > kMaxSampleSize) {
    LOG(LS_WARNING) << "Size field is invalid."
                    << " format: " << GetFourccName(format)
                    << " bpp: " << expected_bpp
                    << " size: " << w << "x" << h
                    << " " << sample_size
                    << " expected: " << 2 * expected_size
                    << " sample[0..3]: " << static_cast<int>(four_samples[0])
                    << ", " << static_cast<int>(four_samples[1])
                    << ", " << static_cast<int>(four_samples[2])
                    << ", " << static_cast<int>(four_samples[3]);
    return false;
  }
  // Show large size warning once every 100 frames.
  // TODO(fbarchard): Make frame counter atomic for thread safety.
  static int large_warn100 = 0;
  size_t large_expected_size = expected_size * 2;
  if (expected_bpp >= 8 &&
      (sample_size > large_expected_size || sample_size > kMaxSampleSize) &&
      large_warn100 % 100 == 0) {
    ++large_warn100;
    LOG(LS_WARNING) << "Size field is too large."
                    << " format: " << GetFourccName(format)
                    << " bpp: " << expected_bpp
                    << " size: " << w << "x" << h
                    << " bytes: " << sample_size
                    << " expected: " << large_expected_size
                    << " sample[0..3]: " << static_cast<int>(four_samples[0])
                    << ", " << static_cast<int>(four_samples[1])
                    << ", " << static_cast<int>(four_samples[2])
                    << ", " << static_cast<int>(four_samples[3]);
  }

  // TODO(fbarchard): Add duplicate pixel check.
  // TODO(fbarchard): Use frame counter atomic for thread safety.
  static bool valid_once = true;
  if (valid_once) {
    valid_once = false;
    LOG(LS_INFO) << "Validate frame passed."
                 << " format: " << GetFourccName(format)
                 << " bpp: " << expected_bpp
                 << " size: " << w << "x" << h
                 << " bytes: " << sample_size
                 << " expected: " << expected_size
                 << " sample[0..3]: " << static_cast<int>(four_samples[0])
                 << ", " << static_cast<int>(four_samples[1])
                 << ", " << static_cast<int>(four_samples[2])
                 << ", " << static_cast<int>(four_samples[3]);
  }
  return true;
}

}  // namespace cricket
<commit_msg>add convert_from.h include for ConvertFromI420<commit_after>/*
 *  Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/media/base/videoframe.h"

#include <string.h>

#include "libyuv/convert_from.h"
#include "libyuv/compare.h"
#include "libyuv/planar_functions.h"
#include "libyuv/scale.h"
#include "webrtc/base/arraysize.h"
#include "webrtc/base/checks.h"
#include "webrtc/base/logging.h"
#include "webrtc/media/base/videocommon.h"

namespace cricket {

size_t VideoFrame::ConvertToRgbBuffer(uint32_t to_fourcc,
                                      uint8_t* buffer,
                                      size_t size,
                                      int stride_rgb) const {
  const size_t needed = std::abs(stride_rgb) * static_cast<size_t>(height());
  if (size < needed) {
    LOG(LS_WARNING) << "RGB buffer is not large enough";
    return needed;
  }

  if (libyuv::ConvertFromI420(
          video_frame_buffer()->DataY(), video_frame_buffer()->StrideY(),
          video_frame_buffer()->DataU(), video_frame_buffer()->StrideU(),
          video_frame_buffer()->DataV(), video_frame_buffer()->StrideV(),
          buffer, stride_rgb, width(), height(), to_fourcc)) {
    LOG(LS_ERROR) << "RGB type not supported: " << to_fourcc;
    return 0;  // 0 indicates error
  }
  return needed;
}

static const size_t kMaxSampleSize = 1000000000u;
// Returns whether a sample is valid.
bool VideoFrame::Validate(uint32_t fourcc,
                          int w,
                          int h,
                          const uint8_t* sample,
                          size_t sample_size) {
  if (h < 0) {
    h = -h;
  }
  // 16384 is maximum resolution for VP8 codec.
  if (w < 1 || w > 16384 || h < 1 || h > 16384) {
    LOG(LS_ERROR) << "Invalid dimensions: " << w << "x" << h;
    return false;
  }
  uint32_t format = CanonicalFourCC(fourcc);
  int expected_bpp = 8;
  switch (format) {
    case FOURCC_I400:
    case FOURCC_RGGB:
    case FOURCC_BGGR:
    case FOURCC_GRBG:
    case FOURCC_GBRG:
      expected_bpp = 8;
      break;
    case FOURCC_I420:
    case FOURCC_I411:
    case FOURCC_YU12:
    case FOURCC_YV12:
    case FOURCC_M420:
    case FOURCC_NV21:
    case FOURCC_NV12:
      expected_bpp = 12;
      break;
    case FOURCC_I422:
    case FOURCC_YV16:
    case FOURCC_YUY2:
    case FOURCC_UYVY:
    case FOURCC_RGBP:
    case FOURCC_RGBO:
    case FOURCC_R444:
      expected_bpp = 16;
      break;
    case FOURCC_I444:
    case FOURCC_YV24:
    case FOURCC_24BG:
    case FOURCC_RAW:
      expected_bpp = 24;
      break;

    case FOURCC_ABGR:
    case FOURCC_BGRA:
    case FOURCC_ARGB:
      expected_bpp = 32;
      break;

    case FOURCC_MJPG:
    case FOURCC_H264:
      expected_bpp = 0;
      break;
    default:
      expected_bpp = 8;  // Expect format is at least 8 bits per pixel.
      break;
  }
  size_t expected_size = (w * expected_bpp + 7) / 8 * h;
  // For compressed formats, expect 4 bits per 16 x 16 macro.  I420 would be
  // 6 bits, but grey can be 4 bits.
  if (expected_bpp == 0) {
    expected_size = ((w + 15) / 16) * ((h + 15) / 16) * 4 / 8;
  }
  if (sample == NULL) {
    LOG(LS_ERROR) << "NULL sample pointer."
                  << " format: " << GetFourccName(format)
                  << " bpp: " << expected_bpp
                  << " size: " << w << "x" << h
                  << " expected: " << expected_size
                  << " " << sample_size;
    return false;
  }
  // TODO(fbarchard): Make function to dump information about frames.
  uint8_t four_samples[4] = {0, 0, 0, 0};
  for (size_t i = 0; i < arraysize(four_samples) && i < sample_size; ++i) {
    four_samples[i] = sample[i];
  }
  if (sample_size < expected_size) {
    LOG(LS_ERROR) << "Size field is too small."
                  << " format: " << GetFourccName(format)
                  << " bpp: " << expected_bpp
                  << " size: " << w << "x" << h
                  << " " << sample_size
                  << " expected: " << expected_size
                  << " sample[0..3]: " << static_cast<int>(four_samples[0])
                  << ", " << static_cast<int>(four_samples[1])
                  << ", " << static_cast<int>(four_samples[2])
                  << ", " << static_cast<int>(four_samples[3]);
    return false;
  }
  if (sample_size > kMaxSampleSize) {
    LOG(LS_WARNING) << "Size field is invalid."
                    << " format: " << GetFourccName(format)
                    << " bpp: " << expected_bpp
                    << " size: " << w << "x" << h
                    << " " << sample_size
                    << " expected: " << 2 * expected_size
                    << " sample[0..3]: " << static_cast<int>(four_samples[0])
                    << ", " << static_cast<int>(four_samples[1])
                    << ", " << static_cast<int>(four_samples[2])
                    << ", " << static_cast<int>(four_samples[3]);
    return false;
  }
  // Show large size warning once every 100 frames.
  // TODO(fbarchard): Make frame counter atomic for thread safety.
  static int large_warn100 = 0;
  size_t large_expected_size = expected_size * 2;
  if (expected_bpp >= 8 &&
      (sample_size > large_expected_size || sample_size > kMaxSampleSize) &&
      large_warn100 % 100 == 0) {
    ++large_warn100;
    LOG(LS_WARNING) << "Size field is too large."
                    << " format: " << GetFourccName(format)
                    << " bpp: " << expected_bpp
                    << " size: " << w << "x" << h
                    << " bytes: " << sample_size
                    << " expected: " << large_expected_size
                    << " sample[0..3]: " << static_cast<int>(four_samples[0])
                    << ", " << static_cast<int>(four_samples[1])
                    << ", " << static_cast<int>(four_samples[2])
                    << ", " << static_cast<int>(four_samples[3]);
  }

  // TODO(fbarchard): Add duplicate pixel check.
  // TODO(fbarchard): Use frame counter atomic for thread safety.
  static bool valid_once = true;
  if (valid_once) {
    valid_once = false;
    LOG(LS_INFO) << "Validate frame passed."
                 << " format: " << GetFourccName(format)
                 << " bpp: " << expected_bpp
                 << " size: " << w << "x" << h
                 << " bytes: " << sample_size
                 << " expected: " << expected_size
                 << " sample[0..3]: " << static_cast<int>(four_samples[0])
                 << ", " << static_cast<int>(four_samples[1])
                 << ", " << static_cast<int>(four_samples[2])
                 << ", " << static_cast<int>(four_samples[3]);
  }
  return true;
}

}  // namespace cricket
<|endoftext|>


<commit_before>#include "RMHD_converter.hpp"
#include <string>
#include <iostream>

RMHD_converter::RMHD_converter(
        int n0, int n1, int n2,
        int N0, int N1, int N2,
        int nfiles)
{
    if (nprocs % nfiles != 0)
    {
        std::cerr <<
            "Number of output files incompatible with number of processes.\n"
            "Aborting.\n" << std::endl;
        exit(EXIT_FAILURE);
    }
    int n[7];

    // first 3 arguments are dimensions for input array
    // i.e. actual dimensions for the Fourier representation.
    // NOT real space grid dimensions
    // the input array is read in as a 2D array,
    // since the first dimension must be a multiple of nprocs
    // (which is generally an even number)
    n[0] = n0*n1;
    n[1] = n2;
    this->f0c = new field_descriptor(2, n, MPI_COMPLEX8, MPI_COMM_WORLD);

    // f1c will be pointing at the input array after it has been
    // transposed in 2D, therefore we have this correspondence:
    // f0c->sizes[0] = f1c->sizes[1]*f1c->sizes[2]
    n[0] = n2;
    n[1] = n0;
    n[2] = n1;
    this->f1c = new field_descriptor(3, n, MPI_COMPLEX8, MPI_COMM_WORLD);

    // the description for the fully transposed field
    n[0] = n2;
    n[1] = n1;
    n[2] = n0;
    this->f2c = new field_descriptor(3, n, MPI_COMPLEX8, MPI_COMM_WORLD);

    // following 3 arguments are dimensions for real space grid dimensions
    // f3r and f3c will be allocated in this call
    fftwf_get_descriptors_3D(
            N0, N1, N2,
            &this->f3r, &this->f3c);

    //allocate fields
    this->c0  = fftwf_alloc_complex(this->f0c->local_size);
    this->c12 = fftwf_alloc_complex(this->f1c->local_size);
    // 4 instead of 2, because we have 2 fields to write
    this->r3  = fftwf_alloc_real( 4*this->f3c->local_size);
    // all FFTs are going to be inplace
    this->c3  = (fftwf_complex*)this->r3;

    // allocate plans
    this->complex2real0 = fftwf_mpi_plan_dft_c2r_3d(
            f3r->sizes[0], f3r->sizes[1], f3r->sizes[2],
            this->c3, this->r3,
            MPI_COMM_WORLD,
            FFTW_ESTIMATE);
    this->complex2real1 = fftwf_mpi_plan_dft_c2r_3d(
            f3r->sizes[0], f3r->sizes[1], f3r->sizes[2],
            this->c3 + this->f3c->local_size,
            this->r3 + 2*this->f3c->local_size,
            MPI_COMM_WORLD,
            FFTW_PATIENT);

    // various descriptions for the real data
    n[0] = N0*2;
    n[1] = N1;
    n[2] = N2;
    this->f4r = new field_descriptor(3, n, MPI_REAL4, MPI_COMM_WORLD);

    this->s = new Morton_shuffler(N0, N1, N2, 2, nfiles);
}

RMHD_converter::~RMHD_converter()
{
    delete this->f0c;
    delete this->f1c;
    delete this->f2c;
    delete this->f3c;
    delete this->f3r;
    delete this->f4r;

    delete this->s;

    fftwf_free(this->c0);
    fftwf_free(this->c12);
    fftwf_free(this->r3);

    fftwf_destroy_plan(this->complex2real0);
    fftwf_destroy_plan(this->complex2real1);
}

int RMHD_converter::convert(
        const char *ifile0,
        const char *ifile1,
        const char *ofile)
{
    //read first field
    this->f0c->read(ifile0, (void*)this->c0);
    this->f0c->transpose(this->c0, this->c12);
    this->f1c->transpose(this->c12);
    fftwf_copy_complex_array(
            this->f2c, this->c12,
            this->f3c, this->c3);
    fftwf_execute(this->complex2real0);
    proc_print_err_message("0 field read and transformed");

    //read second field
    this->f0c->read(ifile1, (void*)this->c0);
    this->f0c->transpose(this->c0, this->c12);
    this->f1c->transpose(this->c12);
    fftwf_copy_complex_array(
            this->f2c, this->c12,
            this->f3c, this->c3 + this->f3c->local_size);
    fftwf_execute(this->complex2real1);
    proc_print_err_message("1 field read and transformed");

    fftwf_clip_zero_padding(this->f4r, this->r3);
    proc_print_err_message("clipped zero padding");

    // new array where mixed components will be placed
    float *rtmp = fftwf_alloc_real( 2*this->f3r->local_size);

    // mix components
    this->f3r->interleave(this->r3, rtmp, 2);
    proc_print_err_message("interleaved array");

    this->s->shuffle(rtmp, this->r3, ofile);
    proc_print_err_message("did zshuffle");

    fftwf_free(rtmp);
    return EXIT_SUCCESS;
}

<commit_msg>remove debug messages<commit_after>#include "RMHD_converter.hpp"
#include <string>
#include <iostream>

RMHD_converter::RMHD_converter(
        int n0, int n1, int n2,
        int N0, int N1, int N2,
        int nfiles)
{
    if (nprocs % nfiles != 0)
    {
        std::cerr <<
            "Number of output files incompatible with number of processes.\n"
            "Aborting.\n" << std::endl;
        exit(EXIT_FAILURE);
    }
    int n[7];

    // first 3 arguments are dimensions for input array
    // i.e. actual dimensions for the Fourier representation.
    // NOT real space grid dimensions
    // the input array is read in as a 2D array,
    // since the first dimension must be a multiple of nprocs
    // (which is generally an even number)
    n[0] = n0*n1;
    n[1] = n2;
    this->f0c = new field_descriptor(2, n, MPI_COMPLEX8, MPI_COMM_WORLD);

    // f1c will be pointing at the input array after it has been
    // transposed in 2D, therefore we have this correspondence:
    // f0c->sizes[0] = f1c->sizes[1]*f1c->sizes[2]
    n[0] = n2;
    n[1] = n0;
    n[2] = n1;
    this->f1c = new field_descriptor(3, n, MPI_COMPLEX8, MPI_COMM_WORLD);

    // the description for the fully transposed field
    n[0] = n2;
    n[1] = n1;
    n[2] = n0;
    this->f2c = new field_descriptor(3, n, MPI_COMPLEX8, MPI_COMM_WORLD);

    // following 3 arguments are dimensions for real space grid dimensions
    // f3r and f3c will be allocated in this call
    fftwf_get_descriptors_3D(
            N0, N1, N2,
            &this->f3r, &this->f3c);

    //allocate fields
    this->c0  = fftwf_alloc_complex(this->f0c->local_size);
    this->c12 = fftwf_alloc_complex(this->f1c->local_size);
    // 4 instead of 2, because we have 2 fields to write
    this->r3  = fftwf_alloc_real( 4*this->f3c->local_size);
    // all FFTs are going to be inplace
    this->c3  = (fftwf_complex*)this->r3;

    // allocate plans
    this->complex2real0 = fftwf_mpi_plan_dft_c2r_3d(
            f3r->sizes[0], f3r->sizes[1], f3r->sizes[2],
            this->c3, this->r3,
            MPI_COMM_WORLD,
            FFTW_ESTIMATE);
    this->complex2real1 = fftwf_mpi_plan_dft_c2r_3d(
            f3r->sizes[0], f3r->sizes[1], f3r->sizes[2],
            this->c3 + this->f3c->local_size,
            this->r3 + 2*this->f3c->local_size,
            MPI_COMM_WORLD,
            FFTW_PATIENT);

    // various descriptions for the real data
    n[0] = N0*2;
    n[1] = N1;
    n[2] = N2;
    this->f4r = new field_descriptor(3, n, MPI_REAL4, MPI_COMM_WORLD);

    this->s = new Morton_shuffler(N0, N1, N2, 2, nfiles);
}

RMHD_converter::~RMHD_converter()
{
    delete this->f0c;
    delete this->f1c;
    delete this->f2c;
    delete this->f3c;
    delete this->f3r;
    delete this->f4r;

    delete this->s;

    fftwf_free(this->c0);
    fftwf_free(this->c12);
    fftwf_free(this->r3);

    fftwf_destroy_plan(this->complex2real0);
    fftwf_destroy_plan(this->complex2real1);
}

int RMHD_converter::convert(
        const char *ifile0,
        const char *ifile1,
        const char *ofile)
{
    //read first field
    this->f0c->read(ifile0, (void*)this->c0);
    this->f0c->transpose(this->c0, this->c12);
    this->f1c->transpose(this->c12);
    fftwf_copy_complex_array(
            this->f2c, this->c12,
            this->f3c, this->c3);
    fftwf_execute(this->complex2real0);

    //read second field
    this->f0c->read(ifile1, (void*)this->c0);
    this->f0c->transpose(this->c0, this->c12);
    this->f1c->transpose(this->c12);
    fftwf_copy_complex_array(
            this->f2c, this->c12,
            this->f3c, this->c3 + this->f3c->local_size);
    fftwf_execute(this->complex2real1);

    fftwf_clip_zero_padding(this->f4r, this->r3);

    // new array where mixed components will be placed
    float *rtmp = fftwf_alloc_real( 2*this->f3r->local_size);

    // mix components
    this->f3r->interleave(this->r3, rtmp, 2);

    this->s->shuffle(rtmp, this->r3, ofile);

    fftwf_free(rtmp);
    return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>#include "stdafx.h"
#include <wininet.h>

#include "ruby/ext/rho/rhoruby.h"
#include "rubyext/WebView.h"
#include "common/RhodesApp.h"
#include "common/StringConverter.h"
#include "MainWindow.h"

using namespace rho;
using namespace rho::common;
extern "C" {
HWND getMainWnd();

void rho_webview_refresh(int index)
{
    rho_webview_navigate(RHODESAPP().getCurrentUrl().c_str(),0);
}

void rho_webview_navigate(const char* url, int index)
{
    String strUrl = RHODESAPP().canonicalizeRhoUrl(url);
    ::PostMessage( getMainWnd(), WM_COMMAND, IDM_NAVIGATE, (LPARAM)_tcsdup(convertToStringW(strUrl).c_str()) );
}

void rho_webview_navigate_back()
{
    ::PostMessage( getMainWnd(), WM_COMMAND, IDM_NAVIGATE_BACK, (LPARAM)0 );
}

const char* rho_webview_execute_js(const char* js, int index)
{
    String strJS = "javascript:";
    strJS += js;

	RAWTRACEC1("Execute JS: %s", js);

    rho_webview_navigate(strJS.c_str(), index);
	return "";
}

const char* rho_webview_current_location(int index)
{
    return RHODESAPP().getCurrentUrl(index).c_str();
}

int rho_webview_active_tab()
{
	return 0;
}

void rho_webview_set_menu_items(VALUE valMenu)
{
    rho_rhodesapp_setViewMenu(valMenu);
}

void rho_webview_full_screen_mode(int enable)
{
    ::PostMessage( getMainWnd(), WM_COMMAND, ID_FULLSCREEN, (LPARAM)enable );
}

void rho_webview_set_cookie(const char *url, const char *cookie)
{
	URL_COMPONENTSA uri;
	::memset(&uri, 0, sizeof(uri));
	uri.dwStructSize = sizeof(uri);
	uri.dwSchemeLength = 1;
	uri.dwHostNameLength = 1;
	uri.dwUrlPathLength = 1;
	if (!::InternetCrackUrlA(url, ::strlen(url), 0, &uri)) {
		RAWLOG_ERROR1("WebView.set_cookie: can not parse url: %s", url);
		return;
	}

	std::string nurl(uri.lpszScheme, uri.dwSchemeLength);
	nurl += "://";
	nurl += std::string(uri.lpszHostName, uri.dwHostNameLength);
	nurl += std::string(uri.lpszUrlPath, uri.dwUrlPathLength);

	for (const char *c = cookie;;) {
		const char *s = c;
		for (; *s != ';' && *s != '\0'; ++s);
		std::string c1(c, s - c);
		if (!::InternetSetCookieA(nurl.c_str(), NULL, c1.c_str()))
			RAWLOG_ERROR1("WebView.set_cookie: can not set cookie for url %s", nurl.c_str());
		if (*s == '\0')
			break;
		for (c = s + 1; *c == ' '; ++c);
	}

}

}

<commit_msg>fix wm build<commit_after>#include "stdafx.h"
#include <wininet.h>

#include "ruby/ext/rho/rhoruby.h"
#include "rubyext/WebView.h"
#include "common/RhodesApp.h"
#include "common/StringConverter.h"
#include "MainWindow.h"

using namespace rho;
using namespace rho::common;
extern "C" {
HWND getMainWnd();

void rho_webview_refresh(int index)
{
    rho_webview_navigate(RHODESAPP().getCurrentUrl().c_str(),0);
}

void rho_webview_navigate(const char* url, int index)
{
    String strUrl = RHODESAPP().canonicalizeRhoUrl(url);
    ::PostMessage( getMainWnd(), WM_COMMAND, IDM_NAVIGATE, (LPARAM)_tcsdup(convertToStringW(strUrl).c_str()) );
}

void rho_webview_navigate_back()
{
    ::PostMessage( getMainWnd(), WM_COMMAND, IDM_NAVIGATE_BACK, (LPARAM)0 );
}

const char* rho_webview_execute_js(const char* js, int index)
{
    String strJS = "javascript:";
    strJS += js;

	//RAWTRACEC1("Execute JS: %s", js);

    rho_webview_navigate(strJS.c_str(), index);
	return "";
}

const char* rho_webview_current_location(int index)
{
    return RHODESAPP().getCurrentUrl(index).c_str();
}

int rho_webview_active_tab()
{
	return 0;
}

void rho_webview_set_menu_items(VALUE valMenu)
{
    rho_rhodesapp_setViewMenu(valMenu);
}

void rho_webview_full_screen_mode(int enable)
{
    ::PostMessage( getMainWnd(), WM_COMMAND, ID_FULLSCREEN, (LPARAM)enable );
}

void rho_webview_set_cookie(const char *url, const char *cookie)
{
	URL_COMPONENTSA uri;
	::memset(&uri, 0, sizeof(uri));
	uri.dwStructSize = sizeof(uri);
	uri.dwSchemeLength = 1;
	uri.dwHostNameLength = 1;
	uri.dwUrlPathLength = 1;
	if (!::InternetCrackUrlA(url, ::strlen(url), 0, &uri)) {
		RAWLOG_ERROR1("WebView.set_cookie: can not parse url: %s", url);
		return;
	}

	std::string nurl(uri.lpszScheme, uri.dwSchemeLength);
	nurl += "://";
	nurl += std::string(uri.lpszHostName, uri.dwHostNameLength);
	nurl += std::string(uri.lpszUrlPath, uri.dwUrlPathLength);

	for (const char *c = cookie;;) {
		const char *s = c;
		for (; *s != ';' && *s != '\0'; ++s);
		std::string c1(c, s - c);
		if (!::InternetSetCookieA(nurl.c_str(), NULL, c1.c_str()))
			RAWLOG_ERROR1("WebView.set_cookie: can not set cookie for url %s", nurl.c_str());
		if (*s == '\0')
			break;
		for (c = s + 1; *c == ' '; ++c);
	}

}

}

<|endoftext|>


<commit_before>/*
  ==============================================================================

    This file was auto-generated!

    It contains the basic framework code for a JUCE plugin editor.

  ==============================================================================
*/

#include "PluginProcessor.h"
#include "PluginEditor.h"

//==============================================================================
GroovinatorAudioProcessorEditor::GroovinatorAudioProcessorEditor (GroovinatorAudioProcessor& p)
:   AudioProcessorEditor (&p),
    processor (p),
    _originalRhythmBgRect(GroovinatorUIRhythmComponent::kOriginalRhythm, processor.getRhythmHandler()),
    _targetRhythmBgRect(GroovinatorUIRhythmComponent::kTargetRhythm, processor.getRhythmHandler())
{
    // Make sure that before the constructor has finished, you've set the
    // editor's size to whatever you need it to be.
    setSize (400, 300);

    // Test slider (pitch-shift, rate, etc. depending on the need...)
    _testSlider.setSliderStyle(Slider::LinearVertical);
    //_testSlider.setRange(-24.0, 24.0); // Semitones
    _testSlider.setRange(0.1, 3.0); // Rate
    _testSlider.setTextBoxStyle(Slider::TextBoxBelow, false, 50, 20);
    //_testSlider.showTextBox();
    _testSlider.setPopupDisplayEnabled(true, this);
    //_testSlider.setTextValueSuffix(" (test)");
    //_testSlider.setValue(0.0); // Semitones
    _testSlider.setValue(1.0); // Rate
    _testSlider.addListener(this);

    // Playhead info label
    _playHeadInfoLabel.setText("", dontSendNotification);
    _playHeadInfoLabel.setJustificationType(Justification::centred);

    // Debug label
    _debugLabel.setFont(10.0f);
    _debugLabel.setText("", dontSendNotification);

    //==============================================================================
    //Rhythm

    // Rectangles
    //_originalRhythmBgRect

    // Num steps
    _originalNumStepsSlider.setSliderStyle(Slider::IncDecButtons);
    _originalNumStepsSlider.setRange(1, 99, 1);
    _originalNumStepsSlider.setTextBoxStyle(Slider::TextBoxLeft, false, 30, 20);
    _originalNumStepsSlider.setIncDecButtonsMode(Slider::incDecButtonsDraggable_AutoDirection);
    _originalNumStepsSlider.setValue(8);
    _originalNumStepsSlider.addListener(this);
    _originalNumStepsLabel.setText("# steps", dontSendNotification);

    _targetNumStepsSlider.setSliderStyle(Slider::IncDecButtons);
    _targetNumStepsSlider.setRange(1, 99, 1);
    _targetNumStepsSlider.setTextBoxStyle(Slider::TextBoxLeft, false, 30, 20);
    _targetNumStepsSlider.setIncDecButtonsMode(Slider::incDecButtonsDraggable_AutoDirection);
    _targetNumStepsSlider.setValue(8);
    _targetNumStepsSlider.addListener(this);
    _targetNumStepsLabel.setText("# steps", dontSendNotification);

    // Add components to editor
    addAndMakeVisible(&_testSlider);
    addAndMakeVisible(&_playHeadInfoLabel);
    addAndMakeVisible(&_debugLabel);
    addAndMakeVisible(&_originalNumStepsSlider);
    addAndMakeVisible(&_originalNumStepsLabel);
    addAndMakeVisible(&_targetNumStepsSlider);
    addAndMakeVisible(&_targetNumStepsLabel);
    addAndMakeVisible(&_originalRhythmBgRect);
    addAndMakeVisible(&_targetRhythmBgRect);

    // Start timer
    startTimer(50);
}

GroovinatorAudioProcessorEditor::~GroovinatorAudioProcessorEditor()
{
}

//==============================================================================
void GroovinatorAudioProcessorEditor::paint (Graphics& g)
{
    // (Our component is opaque, so we must completely fill the background with a solid colour)
    g.fillAll (getLookAndFeel().findColour (ResizableWindow::backgroundColourId));

    // TODO: Use LookAndFeel for all the colors etc.

    // Title
    g.setColour (Colours::white);
    g.setFont (24.0f);
    g.drawFittedText ("G R O O V I N A T O R", 0, 0, getWidth(), 30, Justification::centred, 1);

    // Rhythm boxes
    //g.setColour(Colours::darkslategrey);
    //g.fillRect(_originalRhythmBgRect);
    //g.fillRect(_targetRhythmBgRect);
}

void GroovinatorAudioProcessorEditor::resized()
{
    // This is generally where you'll want to lay out the positions of any
    // subcomponents in your editor..
    _testSlider.setBounds(5, 80, 10, (getHeight()/2));
    _playHeadInfoLabel.setBounds(0, 40, getWidth(), 20);
    _debugLabel.setBounds(0, getHeight()-60, getWidth(), 60);

    // Rhythm components
    // Component positions will generally go in the format:
    // .setBounds(<componentName>X, <original/target>RhythmY + <componentName>YOffset, <componentName>Width, <componentName>Height)
    double originalRhythmY = 80;
    double targetRhythmY = originalRhythmY + 100;

    double rhythmBgRectX = 20;
    double rhythmBgRectYOffset = 0;
    double rhythmBgRectWidth = (getWidth() - (2*rhythmBgRectX)) * 0.8;
    double rhythmBgRectHeight = 75;

    double numStepsWidth = 60;
    double numStepsX = getWidth() - rhythmBgRectX - numStepsWidth; // rhythmBgRectX + rhythmBgRectWidth + 10;

    double numStepsLabelYOffset = 0;
    double numStepsLabelWidth = numStepsWidth;
    double numStepsLabelHeight = 20;

    double numStepsSliderYOffset = 20;
    double numStepsSliderWidth = numStepsWidth;
    double numStepsSliderHeight = 50;

    _originalRhythmBgRect.setBounds(rhythmBgRectX, originalRhythmY + rhythmBgRectYOffset, rhythmBgRectWidth, rhythmBgRectHeight);
    _targetRhythmBgRect.setBounds(rhythmBgRectX, targetRhythmY + rhythmBgRectYOffset, rhythmBgRectWidth, rhythmBgRectHeight);

    _originalNumStepsLabel.setBounds(numStepsX, originalRhythmY + numStepsLabelYOffset, numStepsLabelWidth, numStepsLabelHeight);
    _originalNumStepsSlider.setBounds(numStepsX, originalRhythmY + numStepsSliderYOffset, numStepsSliderWidth, numStepsSliderHeight);
    _targetNumStepsLabel.setBounds(numStepsX, targetRhythmY + numStepsLabelYOffset, numStepsLabelWidth, numStepsLabelHeight);
    _targetNumStepsSlider.setBounds(numStepsX, targetRhythmY + numStepsSliderYOffset, numStepsSliderWidth, numStepsSliderHeight);
}

//
void GroovinatorAudioProcessorEditor::sliderValueChanged(Slider* slider)
{
    double v = slider->getValue();
    if (slider == &_testSlider)
    {
        processor.setTestSliderValue(v);
        printf("test slider changed\n");
    }
    else if (slider == &_originalNumStepsSlider)
    {
        GroovinatorRhythmHandler& rhythmHandler = processor.getRhythmHandler();
        rhythmHandler.setOriginalNumSteps((int) v);
        printf("%s\n", rhythmHandler.getOriginalRhythmStr().c_str());
        _originalRhythmBgRect.setRhythmHandler(rhythmHandler);
        printf("original num steps slider changed\n");
    }
    else if (slider == &_targetNumStepsSlider)
    {
        GroovinatorRhythmHandler& rhythmHandler = processor.getRhythmHandler();
        rhythmHandler.setTargetNumSteps((int) v);
        printf("%s\n", rhythmHandler.getTargetRhythmStr().c_str());
        _targetRhythmBgRect.setRhythmHandler(rhythmHandler);
        printf("target num steps slider changed\n");
    }
}

void GroovinatorAudioProcessorEditor::timerCallback()
{
    // Set playhead info label text
    //_playHeadInfoLabel.setText(String(processor.getHostBpm(), 0), sendNotification);
    String playHeadLabelText;
    if (processor.getHasPlayHeadBeenSet())
    {
        AudioPlayHead::CurrentPositionInfo playHeadInfo = processor.getPlayHeadInfo();

        playHeadLabelText << "BPM: "                  << String((int)playHeadInfo.bpm)
                          << " | Meter: "             << String(playHeadInfo.timeSigNumerator)
                                                      << "/" << String(playHeadInfo.timeSigDenominator)

                          //<< " | Position: "          << String(processor.getPlayHeadBarNum())
                          //                            << "." << String(processor.getPlayHeadRelativePulseNum());

                          << " | Position: "          << String(playHeadInfo.ppqPosition, 2)
                          << " | Last Bar Start: "    << String((int)playHeadInfo.ppqPositionOfLastBarStart);

                          //<< " | Time: " << String((int)playHeadInfo.timeInSeconds)
                          //<< "s (" << String(playHeadInfo.timeInSamples) << " samples)";
    }
    else
    {
        playHeadLabelText = "Start playback to make playhead info available";
    }
    _playHeadInfoLabel.setText(playHeadLabelText, sendNotification);

    // Set debug label text
    String debugLabelText;
    GroovinatorRhythmHandler rhythmHandler = processor.getRhythmHandler();

    debugLabelText  << "/* "

                    // Audio
                    << "sampsPerMeasure=" << String(processor.calculateNumSamplesPerMeasure())
                    //<< ", pulses per measure: " << String(processor.calculateNumPulsesPerMeasure())
                    << ", posSamps=" << String(processor.calculatePlayHeadRelativePositionInSamples())
                    << ", mostRecentSamp=" << String(processor.getMostRecentMeasureBufferSample())
                    << ", diff=" << String(processor.getMostRecentMeasureBufferSample()-processor.calculatePlayHeadRelativePositionInSamples())
                    //<< ", soundTouchTempo=" << String(processor.getSoundTouchTempo())
                    << ", measureBufSz=" << String(processor.getMeasureBufferSize())
                    << "\n"
                    << ", measureNum=" << String(processor.getMeasuresElapsed())
                    << ", ioRatio=" << String(processor.getSoundTouchInputOutputRatio(), 2)

                    // Rhythm
                    << ", origRhythm=" << String(GroovinatorRhythmHandler::rhythmToString(GroovinatorRhythmHandler::generateEuclideanRhythm(3, rhythmHandler.getOriginalNumSteps())))
                    << ", trgtRhythm=" << String(GroovinatorRhythmHandler::rhythmToString(GroovinatorRhythmHandler::generateEuclideanRhythm(3, rhythmHandler.getTargetNumSteps())))

                    << " */";
    _debugLabel.setText(debugLabelText, sendNotification);
}
<commit_msg>call repaint() to update ui upon changing num steps<commit_after>/*
  ==============================================================================

    This file was auto-generated!

    It contains the basic framework code for a JUCE plugin editor.

  ==============================================================================
*/

#include "PluginProcessor.h"
#include "PluginEditor.h"

//==============================================================================
GroovinatorAudioProcessorEditor::GroovinatorAudioProcessorEditor (GroovinatorAudioProcessor& p)
:   AudioProcessorEditor (&p),
    processor (p),
    _originalRhythmBgRect(GroovinatorUIRhythmComponent::kOriginalRhythm, processor.getRhythmHandler()),
    _targetRhythmBgRect(GroovinatorUIRhythmComponent::kTargetRhythm, processor.getRhythmHandler())
{
    // Make sure that before the constructor has finished, you've set the
    // editor's size to whatever you need it to be.
    setSize (400, 300);

    // Test slider (pitch-shift, rate, etc. depending on the need...)
    _testSlider.setSliderStyle(Slider::LinearVertical);
    //_testSlider.setRange(-24.0, 24.0); // Semitones
    _testSlider.setRange(0.1, 3.0); // Rate
    _testSlider.setTextBoxStyle(Slider::TextBoxBelow, false, 50, 20);
    //_testSlider.showTextBox();
    _testSlider.setPopupDisplayEnabled(true, this);
    //_testSlider.setTextValueSuffix(" (test)");
    //_testSlider.setValue(0.0); // Semitones
    _testSlider.setValue(1.0); // Rate
    _testSlider.addListener(this);

    // Playhead info label
    _playHeadInfoLabel.setText("", dontSendNotification);
    _playHeadInfoLabel.setJustificationType(Justification::centred);

    // Debug label
    _debugLabel.setFont(10.0f);
    _debugLabel.setText("", dontSendNotification);

    //==============================================================================
    //Rhythm

    // Rectangles
    //_originalRhythmBgRect

    // Num steps
    _originalNumStepsSlider.setSliderStyle(Slider::IncDecButtons);
    _originalNumStepsSlider.setRange(1, 99, 1);
    _originalNumStepsSlider.setTextBoxStyle(Slider::TextBoxLeft, false, 30, 20);
    _originalNumStepsSlider.setIncDecButtonsMode(Slider::incDecButtonsDraggable_AutoDirection);
    _originalNumStepsSlider.setValue(8);
    _originalNumStepsSlider.addListener(this);
    _originalNumStepsLabel.setText("# steps", dontSendNotification);

    _targetNumStepsSlider.setSliderStyle(Slider::IncDecButtons);
    _targetNumStepsSlider.setRange(1, 99, 1);
    _targetNumStepsSlider.setTextBoxStyle(Slider::TextBoxLeft, false, 30, 20);
    _targetNumStepsSlider.setIncDecButtonsMode(Slider::incDecButtonsDraggable_AutoDirection);
    _targetNumStepsSlider.setValue(8);
    _targetNumStepsSlider.addListener(this);
    _targetNumStepsLabel.setText("# steps", dontSendNotification);

    // Add components to editor
    addAndMakeVisible(&_testSlider);
    addAndMakeVisible(&_playHeadInfoLabel);
    addAndMakeVisible(&_debugLabel);
    addAndMakeVisible(&_originalNumStepsSlider);
    addAndMakeVisible(&_originalNumStepsLabel);
    addAndMakeVisible(&_targetNumStepsSlider);
    addAndMakeVisible(&_targetNumStepsLabel);
    addAndMakeVisible(&_originalRhythmBgRect);
    addAndMakeVisible(&_targetRhythmBgRect);

    // Start timer
    startTimer(50);
}

GroovinatorAudioProcessorEditor::~GroovinatorAudioProcessorEditor()
{
}

//==============================================================================
void GroovinatorAudioProcessorEditor::paint (Graphics& g)
{
    // (Our component is opaque, so we must completely fill the background with a solid colour)
    g.fillAll (getLookAndFeel().findColour (ResizableWindow::backgroundColourId));

    // TODO: Use LookAndFeel for all the colors etc.

    // Title
    g.setColour (Colours::white);
    g.setFont (24.0f);
    g.drawFittedText ("G R O O V I N A T O R", 0, 0, getWidth(), 30, Justification::centred, 1);

    // Rhythm boxes
    //g.setColour(Colours::darkslategrey);
    //g.fillRect(_originalRhythmBgRect);
    //g.fillRect(_targetRhythmBgRect);
}

void GroovinatorAudioProcessorEditor::resized()
{
    // This is generally where you'll want to lay out the positions of any
    // subcomponents in your editor..
    _testSlider.setBounds(5, 80, 10, (getHeight()/2));
    _playHeadInfoLabel.setBounds(0, 40, getWidth(), 20);
    _debugLabel.setBounds(0, getHeight()-60, getWidth(), 60);

    // Rhythm components
    // Component positions will generally go in the format:
    // .setBounds(<componentName>X, <original/target>RhythmY + <componentName>YOffset, <componentName>Width, <componentName>Height)
    double originalRhythmY = 80;
    double targetRhythmY = originalRhythmY + 100;

    double rhythmBgRectX = 20;
    double rhythmBgRectYOffset = 0;
    double rhythmBgRectWidth = (getWidth() - (2*rhythmBgRectX)) * 0.8;
    double rhythmBgRectHeight = 75;

    double numStepsWidth = 60;
    double numStepsX = getWidth() - rhythmBgRectX - numStepsWidth; // rhythmBgRectX + rhythmBgRectWidth + 10;

    double numStepsLabelYOffset = 0;
    double numStepsLabelWidth = numStepsWidth;
    double numStepsLabelHeight = 20;

    double numStepsSliderYOffset = 20;
    double numStepsSliderWidth = numStepsWidth;
    double numStepsSliderHeight = 50;

    _originalRhythmBgRect.setBounds(rhythmBgRectX, originalRhythmY + rhythmBgRectYOffset, rhythmBgRectWidth, rhythmBgRectHeight);
    _targetRhythmBgRect.setBounds(rhythmBgRectX, targetRhythmY + rhythmBgRectYOffset, rhythmBgRectWidth, rhythmBgRectHeight);

    _originalNumStepsLabel.setBounds(numStepsX, originalRhythmY + numStepsLabelYOffset, numStepsLabelWidth, numStepsLabelHeight);
    _originalNumStepsSlider.setBounds(numStepsX, originalRhythmY + numStepsSliderYOffset, numStepsSliderWidth, numStepsSliderHeight);
    _targetNumStepsLabel.setBounds(numStepsX, targetRhythmY + numStepsLabelYOffset, numStepsLabelWidth, numStepsLabelHeight);
    _targetNumStepsSlider.setBounds(numStepsX, targetRhythmY + numStepsSliderYOffset, numStepsSliderWidth, numStepsSliderHeight);
}

//
void GroovinatorAudioProcessorEditor::sliderValueChanged(Slider* slider)
{
    double v = slider->getValue();
    if (slider == &_testSlider)
    {
        processor.setTestSliderValue(v);
        printf("test slider changed\n");
    }
    else if (slider == &_originalNumStepsSlider)
    {
        GroovinatorRhythmHandler& rhythmHandler = processor.getRhythmHandler();
        rhythmHandler.setOriginalNumSteps((int) v);
        _originalRhythmBgRect.setRhythmHandler(rhythmHandler);
        _originalRhythmBgRect.repaint();

        printf("%s\n", rhythmHandler.getOriginalRhythmStr().c_str());
        printf("original num steps slider changed\n");
    }
    else if (slider == &_targetNumStepsSlider)
    {
        GroovinatorRhythmHandler& rhythmHandler = processor.getRhythmHandler();
        rhythmHandler.setTargetNumSteps((int) v);
        _targetRhythmBgRect.setRhythmHandler(rhythmHandler);
        _targetRhythmBgRect.repaint();

        printf("%s\n", rhythmHandler.getTargetRhythmStr().c_str());
        printf("target num steps slider changed\n");
    }
}

void GroovinatorAudioProcessorEditor::timerCallback()
{
    // Set playhead info label text
    //_playHeadInfoLabel.setText(String(processor.getHostBpm(), 0), sendNotification);
    String playHeadLabelText;
    if (processor.getHasPlayHeadBeenSet())
    {
        AudioPlayHead::CurrentPositionInfo playHeadInfo = processor.getPlayHeadInfo();

        playHeadLabelText << "BPM: "                  << String((int)playHeadInfo.bpm)
                          << " | Meter: "             << String(playHeadInfo.timeSigNumerator)
                                                      << "/" << String(playHeadInfo.timeSigDenominator)

                          //<< " | Position: "          << String(processor.getPlayHeadBarNum())
                          //                            << "." << String(processor.getPlayHeadRelativePulseNum());

                          << " | Position: "          << String(playHeadInfo.ppqPosition, 2)
                          << " | Last Bar Start: "    << String((int)playHeadInfo.ppqPositionOfLastBarStart);

                          //<< " | Time: " << String((int)playHeadInfo.timeInSeconds)
                          //<< "s (" << String(playHeadInfo.timeInSamples) << " samples)";
    }
    else
    {
        playHeadLabelText = "Start playback to make playhead info available";
    }
    _playHeadInfoLabel.setText(playHeadLabelText, sendNotification);

    // Set debug label text
    String debugLabelText;
    GroovinatorRhythmHandler rhythmHandler = processor.getRhythmHandler();

    debugLabelText  << "/* "

                    // Audio
                    << "sampsPerMeasure=" << String(processor.calculateNumSamplesPerMeasure())
                    //<< ", pulses per measure: " << String(processor.calculateNumPulsesPerMeasure())
                    << ", posSamps=" << String(processor.calculatePlayHeadRelativePositionInSamples())
                    << ", mostRecentSamp=" << String(processor.getMostRecentMeasureBufferSample())
                    << ", diff=" << String(processor.getMostRecentMeasureBufferSample()-processor.calculatePlayHeadRelativePositionInSamples())
                    //<< ", soundTouchTempo=" << String(processor.getSoundTouchTempo())
                    << ", measureBufSz=" << String(processor.getMeasureBufferSize())
                    << "\n"
                    << ", measureNum=" << String(processor.getMeasuresElapsed())
                    << ", ioRatio=" << String(processor.getSoundTouchInputOutputRatio(), 2)

                    // Rhythm
                    << ", origRhythm=" << String(GroovinatorRhythmHandler::rhythmToString(GroovinatorRhythmHandler::generateEuclideanRhythm(3, rhythmHandler.getOriginalNumSteps())))
                    << ", trgtRhythm=" << String(GroovinatorRhythmHandler::rhythmToString(GroovinatorRhythmHandler::generateEuclideanRhythm(3, rhythmHandler.getTargetNumSteps())))

                    << " */";
    _debugLabel.setText(debugLabelText, sendNotification);
}
<|endoftext|>


<commit_before>// Time:  O(n)
// Space: O(h)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int kthSmallest(TreeNode* root, int k) {
        stack<TreeNode *> s;
        TreeNode *cur = root;
        int rank = 0;
        while (!s.empty() || cur) {
            if (cur) {
                s.emplace(cur);
                cur = cur->left;
            } else {
                cur = s.top();
                s.pop();
                if (++rank == k) {
                    return cur->val;
                }
                cur = cur->right;
            }
        }

        return INT_MIN;
    }
};
<commit_msg>Update kth-smallest-element-in-a-bst.cpp<commit_after>// Time:  O(min(h, k))
// Space: O(h)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int kthSmallest(TreeNode* root, int k) {
        stack<TreeNode *> s;
        TreeNode *cur = root;
        int rank = 0;
        while (!s.empty() || cur) {
            if (cur) {
                s.emplace(cur);
                cur = cur->left;
            } else {
                cur = s.top();
                s.pop();
                if (++rank == k) {
                    return cur->val;
                }
                cur = cur->right;
            }
        }

        return INT_MIN;
    }
};
<|endoftext|>


<commit_before>//PROBLEM 3: LARGEST PRIME FACTOR
/*
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
*/

#include <iostream>

bool isPrime(int number)
{
	bool TEMP = true;
	if (number == 2){
		return TEMP;
	}
	else if (!(number % 2)|(number==1)) //if the number is even then is not prime
	{
		TEMP = false;
		return TEMP;
	}
	else
	{
		for (int i = 2; i <= (number / 2); i++)
		{
			if (!(number%i))
			{
				TEMP = false;
			}

		}

		return TEMP;
	}

}

int main()
{
	int a = 1;
	while (a != 0)
	{
		std::cin >> a;
		if (isPrime(a))
		{
			std::cout << "TRUE" << std::endl;
		}
		else{
			std::cout << "FALSE" << std::endl;
		}
	}

	std::cin.get();
	return 0;
}

<commit_msg>c++ p3 - complete but taking too long<commit_after>//PROBLEM 3: LARGEST PRIME FACTOR
/*
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
*/

#include <iostream>
#include "math.h"

bool isPrime(int number)
{
	bool TEMP = true;

	if (number == 2)// 2 is prime but it's left out by the algorithm
	{
		return TEMP;
	}
	else if (!(number % 2)|(number==1)) //if the number is even then is not prime
	{
		TEMP = false;
		return TEMP;
	}
	else
	{
		for (int i = 2; i <= (number / 2); i++)//if the number is divisible then is not prime
		{
			if (!(number%i))
			{
				TEMP = false;
			}

		}

		return TEMP;
	}

}

int main()
{
	/*  TEST FOR PRIME NUMBER FUNCTION
	int a = 1;
	while (a != 0)
	{
		std::cin >> a;
		if (isPrime(a))
		{
			std::cout << "TRUE" << std::endl;
		}
		else{
			std::cout << "FALSE" << std::endl;
		}
	}
	*/

	//APPROACH #1
	long double FINAL_NUMBER = 600851475143;
	long double largestPrime = 0;

	for (int i = 1; i < FINAL_NUMBER/2; i++)
	{
		if (fmod(FINAL_NUMBER, i) == 0)
		{
			std::cout <<std::endl<< "FACTOR FOUND: " << i << std::endl;
			if (isPrime(i))
			{
				std::cout << "     #prime!" << std::endl;
				largestPrime = i;
			}
			std::cout << "     ...looking for more factors..." << std::endl;
		}
	}

	/*
	//APPROACH #2
	long double FINAL_NUMBER = 600851475143;
	long double largestPrime = 0;
	long double counter = floor(FINAL_NUMBER/6);
	std::cout << "     ...looking for factors..." << std::endl;

	while (largestPrime <= 0)
	{

		counter--;
		std::cout << counter<<std::endl;
		if (fmod(FINAL_NUMBER, counter) == 0)
		{
			std::cout << std::endl << "FACTOR FOUND: " << counter << std::endl;
			if (isPrime(counter))
			{
				std::cout << "     #prime!" << std::endl;
				largestPrime = counter;
			}
			std::cout << "     ...looking for more factors..." << std::endl;
		}

	}
	*/

	std::cout << "ANSWER is " << largestPrime << std::endl;
	std::cin.get();
	return 0;
}

<|endoftext|>


<commit_before>#include "uspeech.h"
/**
 * Constructor
 */
signal::signal(int port){
	int pin = port;
}
/**
 * Calibration of background based on averaging
 */
void signal::calibrate(){
	calib = (analogRead(pin)+analogRead(pin)+analogRead(pin)+analogRead(pin))/4; //acquire background noise
}
/**
 * Sampling of the sound: Based on storing values minus average background noise
 */
void signal::sample(){
	int i = 0;
	while ( i < 32){
		arr[i] = analogRead(pin)-calib;
		i++;
	}

}
/**
 * An estimate of background noise
 */
unsigned int signal::power(){
	unsigned int j = 0;
	char i = 0;
	while(i<32){

		j+=abs(arr[i]);
		i++;
	}
	return j;
}
/**
 * power/abs(sum of derivative)
 */
unsigned int signal::complexity(int power){
	unsigned int j = 0;
	int i = 1;
	while(i<32){
		j+=abs(arr[i]-arr[i-1]);
		i++;
	}
	return (j*100)/power;
}

unsigned long signal::fpowerex(int sum, int xtra){

	int i = sum;
	unsigned long j = abs(arr[i-1]*(xtra/10));
	int p;
	while(i<32){
		int k = 0;
		p = 0;
		while(k<sum){
			p+=abs(arr[i-k]);
			k++;
		}
		j+=p/sum+p/(xtra/10);
		i++;
		//Serial.println(j);
	}
	return j;
}
/**
* Point of maximum amplitude
*/
unsigned int signal::maxPower(){
    int i =0;
    unsigned int max = 0;
    while (i<32){
        if(max<abs(arr[i])){
            max = abs(arr[i]);
        }
        i++;
    }
    return max;
}
int signal::snr(int power){
	int i =0,j=0;
	int mean =power/32;
	while(i <32){
		j+=sq(arr[i]-mean);
		i++;
	}
	return sqrt(j/mean)/power;
}
<commit_msg>Added avgPower method; AVGpower is used for zerocrossing point<commit_after>#include "uspeech.h"
/**
 * Constructor
 */
signal::signal(int port){
	int pin = port;
}
/**
 * Calibration of background based on averaging
 */
void signal::calibrate(){
	calib = (analogRead(pin)+analogRead(pin)+analogRead(pin)+analogRead(pin))/4; //acquire background noise
}
/**
 * Sampling of the sound: Based on storing values minus average background noise
 */
void signal::sample(){
	int i = 0;
	while ( i < 32){
		arr[i] = analogRead(pin)-calib;
		i++;
	}

}
/**
 * An estimate of background noise
 */
unsigned int signal::power(){
	unsigned int j = 0;
	char i = 0;
	while(i<32){

		j+=abs(arr[i]);
		i++;
	}
	return j;
}
/**
 * power/abs(sum of derivative)
 */
unsigned int signal::complexity(int power){
	unsigned int j = 0;
	int i = 1;
	while(i<32){
		j+=abs(arr[i]-arr[i-1]);
		i++;
	}
	return (j*100)/power;
}

unsigned long signal::fpowerex(int sum, int xtra){

	int i = sum;
	unsigned long j = abs(arr[i-1]*(xtra/10));
	int p;
	while(i<32){
		int k = 0;
		p = 0;
		while(k<sum){
			p+=abs(arr[i-k]);
			k++;
		}
		j+=p/sum+p/(xtra/10);
		i++;
		//Serial.println(j);
	}
	return j;
}
/**
* Point of maximum amplitude
*/
unsigned int signal::maxPower(){
    int i =0;
    unsigned int max = 0;
    while (i<32){
        if(max<abs(arr[i])){
            max = abs(arr[i]);
        }
        i++;
        avgPower+=arr[i];
    }
    avgPower /= 32;
    return max;
}
int signal::snr(int power){
	int i =0,j=0;
	int mean =power/32;
	while(i <32){
		j+=sq(arr[i]-mean);
		i++;
	}
	return sqrt(j/mean)/power;
}
<|endoftext|>


<commit_before>#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/boost/graph/graph_traits_Polyhedron_3.h>
#include <CGAL/Polyhedron_items_with_id_3.h>
#include <CGAL/IO/Polyhedron_iostream.h>
#include <CGAL/mesh_segmentation.h>
#include <CGAL/property_map.h>
#include <iostream>
#include <fstream>
#include <string>

typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef CGAL::Polyhedron_3<K, CGAL::Polyhedron_items_with_id_3>  Polyhedron;

// Property map associating a facet with an integer as id to an
// element in a vector stored internally
template<class ValueType>
struct Facet_with_id_pmap
    : public boost::put_get_helper<ValueType&,
             Facet_with_id_pmap<ValueType> >
{
    typedef Polyhedron::Facet_const_handle key_type;
    typedef ValueType value_type;
    typedef value_type& reference;
    typedef boost::lvalue_property_map_tag category;

    Facet_with_id_pmap(
      std::vector<ValueType>& internal_vector
    ) : internal_vector(internal_vector) { }
    reference operator[](key_type key) const
    { return internal_vector[key->id()]; }
private:
    std::vector<ValueType>& internal_vector;
};

int main(int argc,char* argv[])
{
	typedef Polyhedron::Facet_iterator                   Facet_iterator;
    typedef Polyhedron::Halfedge_around_facet_circulator Halfedge_facet_circulator;

std::string location;
std::string filePath;
    // create and read Polyhedron
    if (argc==1){
		// TODO: Petteri, maybe change the paths when providing no arguments to something else
    	location= "/home/highschoolintern/Desktop/TestReconstruction2/testReconstruction_4slicesPhysical_reconstruction_isolatedRemoved_decimated.off";
    	filePath= "/home/highschoolintern/Desktop/SDFPropertyMap/build";

    }else {
    	location= argv[1];
    	filePath= argv[2];
    }

   std::cout << location.c_str() << "\n";

   Polyhedron mesh;
    std::ifstream input(location.c_str());
    if ( !input || !(input >> mesh) || mesh.empty() ) {
      std::cerr << "Not a valid off file." << std::endl;

      return EXIT_FAILURE;
    }

    // assign id field for each facet
    std::size_t facet_id = 0;
    for(Polyhedron::Facet_iterator facet_it = mesh.facets_begin();
      facet_it != mesh.facets_end(); ++facet_it, ++facet_id) {
        facet_it->id() = facet_id;

    }

    for (  Facet_iterator i = mesh.facets_begin(); i != mesh.facets_end(); ++i) {
        Halfedge_facet_circulator j = i->facet_begin();
        // Facets in polyhedral surfaces are at least triangles.
        CGAL_assertion( CGAL::circulator_size(j) >= 3);
        //std::cout << CGAL::circulator_size(j) << ' ';
        do {
           // std::cout << ' ' << std::distance(mesh.vertices_begin(), j->vertex());

        } while ( ++j != i->facet_begin());
        //std::cout << std::endl;
    }

// create a property-map for SDF values
    std::vector<double> sdf_values(mesh.size_of_facets());
    Facet_with_id_pmap<double> sdf_property_map(sdf_values);
    CGAL::sdf_values(mesh, sdf_property_map);

// access SDF values (with constant-complexity)
std::ofstream SDF(filePath.c_str());
SDF.open("SDFVals.txt");

    for(Polyhedron::Facet_const_iterator facet_it = mesh.facets_begin();
      facet_it != mesh.facets_end(); ++facet_it) {
        std::cout << sdf_property_map[facet_it] << " \n";
   SDF << sdf_property_map[facet_it] << std::endl;
    }
    SDF.close();
    std::cout << std::endl; // Printing the SDF values

    std::ofstream SDFfile;

    // create a property-map for segment-ids
    std::vector<std::size_t> segment_ids(mesh.size_of_facets());
    Facet_with_id_pmap<std::size_t> segment_property_map(segment_ids);
    CGAL::segmentation_from_sdf_values(mesh, sdf_property_map, segment_property_map);

    // access segment-ids (with constant-complexity)
    for(Polyhedron::Facet_const_iterator facet_it = mesh.facets_begin();
      facet_it != mesh.facets_end(); ++facet_it) {
        std::cout << segment_property_map[facet_it] << " ";
    }
    std::cout << std::endl; // Printing the SDF Segment IDs

        // These IDs could be saved to disk maybe as well, and used in piecewise denoising or something?

    SDFfile.close();

}

<commit_msg>indentation fix<commit_after>#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/boost/graph/graph_traits_Polyhedron_3.h>
#include <CGAL/Polyhedron_items_with_id_3.h>
#include <CGAL/IO/Polyhedron_iostream.h>
#include <CGAL/mesh_segmentation.h>
#include <CGAL/property_map.h>
#include <iostream>
#include <fstream>
#include <string>

typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef CGAL::Polyhedron_3<K, CGAL::Polyhedron_items_with_id_3>  Polyhedron;

// Property map associating a facet with an integer as id to an
// element in a vector stored internally
template<class ValueType>
struct Facet_with_id_pmap
    : public boost::put_get_helper<ValueType&,
             Facet_with_id_pmap<ValueType> >
{
    typedef Polyhedron::Facet_const_handle key_type;
    typedef ValueType value_type;
    typedef value_type& reference;
    typedef boost::lvalue_property_map_tag category;

    Facet_with_id_pmap(
      std::vector<ValueType>& internal_vector
    ) : internal_vector(internal_vector) { }
    reference operator[](key_type key) const
    { return internal_vector[key->id()]; }
private:
    std::vector<ValueType>& internal_vector;
};

int main(int argc,char* argv[])
{
	typedef Polyhedron::Facet_iterator                   Facet_iterator;
    typedef Polyhedron::Halfedge_around_facet_circulator Halfedge_facet_circulator;

    std::string location;
    std::string filePath;

    // create and read Polyhedron
    if (argc==1){
		// TODO: Petteri, maybe change the paths when providing no arguments to something else
    	location= "/home/highschoolintern/Desktop/TestReconstruction2/testReconstruction_4slicesPhysical_reconstruction_isolatedRemoved_decimated.off";
    	filePath= "/home/highschoolintern/Desktop/SDFPropertyMap/build";

    }else {
    	location= argv[1];
    	filePath= argv[2];
    }

   std::cout << location.c_str() << "\n";

   Polyhedron mesh;
    std::ifstream input(location.c_str());
    if ( !input || !(input >> mesh) || mesh.empty() ) {
      std::cerr << "Not a valid off file." << std::endl;

      return EXIT_FAILURE;
    }

    // assign id field for each facet
    std::size_t facet_id = 0;
    for(Polyhedron::Facet_iterator facet_it = mesh.facets_begin();
      facet_it != mesh.facets_end(); ++facet_it, ++facet_id) {
        facet_it->id() = facet_id;

    }

    for (  Facet_iterator i = mesh.facets_begin(); i != mesh.facets_end(); ++i) {
        Halfedge_facet_circulator j = i->facet_begin();
        // Facets in polyhedral surfaces are at least triangles.
        CGAL_assertion( CGAL::circulator_size(j) >= 3);
        //std::cout << CGAL::circulator_size(j) << ' ';
        do {
           // std::cout << ' ' << std::distance(mesh.vertices_begin(), j->vertex());

        } while ( ++j != i->facet_begin());
        //std::cout << std::endl;
    }

// create a property-map for SDF values
    std::vector<double> sdf_values(mesh.size_of_facets());
    Facet_with_id_pmap<double> sdf_property_map(sdf_values);
    CGAL::sdf_values(mesh, sdf_property_map);

// access SDF values (with constant-complexity)
std::ofstream SDF(filePath.c_str());
SDF.open("SDFVals.txt");

    for(Polyhedron::Facet_const_iterator facet_it = mesh.facets_begin();
      facet_it != mesh.facets_end(); ++facet_it) {
        std::cout << sdf_property_map[facet_it] << " \n";
   SDF << sdf_property_map[facet_it] << std::endl;
    }
    SDF.close();
    std::cout << std::endl; // Printing the SDF values

    std::ofstream SDFfile;

    // create a property-map for segment-ids
    std::vector<std::size_t> segment_ids(mesh.size_of_facets());
    Facet_with_id_pmap<std::size_t> segment_property_map(segment_ids);
    CGAL::segmentation_from_sdf_values(mesh, sdf_property_map, segment_property_map);

    // access segment-ids (with constant-complexity)
    for(Polyhedron::Facet_const_iterator facet_it = mesh.facets_begin();
      facet_it != mesh.facets_end(); ++facet_it) {
        std::cout << segment_property_map[facet_it] << " ";
    }
    std::cout << std::endl; // Printing the SDF Segment IDs

        // These IDs could be saved to disk maybe as well, and used in piecewise denoising or something?

    SDFfile.close();

}

<|endoftext|>