<commit_before>/** ==========================================================================
* 2012 by KjellKod.cc. This is PUBLIC DOMAIN to use at your own risk and comes
* with no warranties. This code is yours to share, use and modify with no
* strings attached and no restrictions or obligations.
*
* For more information see g3log/LICENSE or refer refer to http://unlicense.org
* ============================================================================*/

#include "g3log/loglevels.hpp"
#include <atomic>
#include <cassert>
#include <map>
#include <unordered_map>

namespace {
   namespace {
      /// As suggested in: http://stackoverflow.com/questions/13193484/how-to-declare-a-vector-of-atomic-in-c
      struct atomicbool {
       private:
         std::atomic<bool> value_;
       public:
         atomicbool(): value_ {false} {}
         atomicbool(const bool &value): value_ {value} {}
         atomicbool(const std::atomic<bool> &value) : value_ {value.load(std::memory_order_acquire)} {}
         atomicbool(const atomicbool &other): value_ {other.value_.load(std::memory_order_acquire)} {}
         atomicbool &operator=(const atomicbool &other) {
            value_.store(other.value_.load(std::memory_order_acquire), std::memory_order_release);
            return *this;
         }
         bool value() {return value_.load(std::memory_order_acquire);}
         std::atomic<bool>& get() {return value_;}
      };

   } // anonymous

}
namespace g3 {
   namespace internal {
      bool wasFatal(const LEVELS &level) {
         return level.value >= FATAL.value;
      }

#ifdef G3_DYNAMIC_LOGGING
      std::map<int, atomicbool> g_log_level_status = {{g3::kTraceValue, true}, {g3::kDebugValue, true}, {INFO.value, true}, {WARNING.value, true}, {ERROR.value, true}, {FATAL.value, true} };
      std::unordered_map<std::string, int> g_log_level_name = {{TRACE.text, g3::kTraceValue}, {DEBUG.text, g3::kDebugValue}, {INFO.text, INFO.value }, {WARNING.text, WARNING.value}, {ERROR.text, ERROR.value}, {FATAL.text, FATAL.value} };
#endif
   } // internal

#ifdef G3_DYNAMIC_LOGGING
   namespace only_change_at_initialization {
      void setLogLevel(LEVELS log_level, bool enabled) {
         int level = log_level.value;
         internal::g_log_level_status[level].get().store(enabled, std::memory_order_release);
      }

      std::string printLevels() {
         std::string levels;
         for (auto& v : internal::g_log_level_status) {
            levels += "value: " + std::to_string(v.first) + " status: " + std::to_string(v.second.value()) + "\n";
         }
         return levels;
      }

      void reset() {
         internal::g_log_level_status.clear();
         internal::g_log_level_status = std::map<int, atomicbool>{{g3::kTraceValue, true}, {g3::kDebugValue, true}, {INFO.value, true}, {WARNING.value, true}, {ERROR.value, true}, {FATAL.value, true}};
      }

      void disableAll() {
         internal::g_log_level_status.clear();
         internal::g_log_level_status = std::map<int, atomicbool>{{g3::kTraceValue, false}, {g3::kDebugValue, false}, {INFO.value, false}, {WARNING.value, false}, {ERROR.value, false}, {FATAL.value, false}};
      }

      void setLogLevel(const std::string &log_level) {
        auto it = internal::g_log_level_name.find(log_level);
        if (it!= internal::g_log_level_name.end()) {
          for(auto& v : internal::g_log_level_status) {
            if (v.first < it->second){
              internal::g_log_level_status[v.first].get().store(false, std::memory_order_release);
            }else {
              internal::g_log_level_status[v.first].get().store(true, std::memory_order_release);
            }
          }
        }
      }
   } // only_change_at_initialization

   bool isValidLevel(const std::string& log_level) {
     auto it = internal::g_log_level_name.find(log_level);
     return it != internal::g_log_level_name.end();
   }

   std::vector<std::string> getAllLevels() {
     std::vector<std::string> levels;
     for (auto& v : internal::g_log_level_name) {
       levels.push_back(v.first);
     }
     return levels;
   }
#endif

   bool logLevel(LEVELS log_level) {
#ifdef G3_DYNAMIC_LOGGING
      int level = log_level.value;
      bool status = internal::g_log_level_status[level].value();
      return status;
#endif
      return true;
   }

} // g3
<commit_msg>change getAllLevels - need order<commit_after>/** ==========================================================================
* 2012 by KjellKod.cc. This is PUBLIC DOMAIN to use at your own risk and comes
* with no warranties. This code is yours to share, use and modify with no
* strings attached and no restrictions or obligations.
*
* For more information see g3log/LICENSE or refer refer to http://unlicense.org
* ============================================================================*/

#include "g3log/loglevels.hpp"
#include <atomic>
#include <cassert>
#include <map>

namespace {
   namespace {
      /// As suggested in: http://stackoverflow.com/questions/13193484/how-to-declare-a-vector-of-atomic-in-c
      struct atomicbool {
       private:
         std::atomic<bool> value_;
       public:
         atomicbool(): value_ {false} {}
         atomicbool(const bool &value): value_ {value} {}
         atomicbool(const std::atomic<bool> &value) : value_ {value.load(std::memory_order_acquire)} {}
         atomicbool(const atomicbool &other): value_ {other.value_.load(std::memory_order_acquire)} {}
         atomicbool &operator=(const atomicbool &other) {
            value_.store(other.value_.load(std::memory_order_acquire), std::memory_order_release);
            return *this;
         }
         bool value() {return value_.load(std::memory_order_acquire);}
         std::atomic<bool>& get() {return value_;}
      };

   } // anonymous

}
namespace g3 {
   namespace internal {
      bool wasFatal(const LEVELS &level) {
         return level.value >= FATAL.value;
      }

#ifdef G3_DYNAMIC_LOGGING
      std::map<int, atomicbool> g_log_level_status = {{g3::kTraceValue, true}, {g3::kDebugValue, true}, {INFO.value, true}, {WARNING.value, true}, {ERROR.value, true}, {FATAL.value, true} };
      std::map<std::string, int> g_log_level_name = {{TRACE.text, g3::kTraceValue}, {DEBUG.text, g3::kDebugValue}, {INFO.text, INFO.value }, {WARNING.text, WARNING.value}, {ERROR.text, ERROR.value}, {FATAL.text, FATAL.value} };
      std::vector<std::string> g_log_all_levels = { TRACE.text, DEBUG.text, INFO.text, WARNING.text, ERROR.text, FATAL.text};
#endif
   } // internal

#ifdef G3_DYNAMIC_LOGGING
   namespace only_change_at_initialization {
      void setLogLevel(LEVELS log_level, bool enabled) {
         int level = log_level.value;
         internal::g_log_level_status[level].get().store(enabled, std::memory_order_release);
      }

      std::string printLevels() {
         std::string levels;
         for (auto& v : internal::g_log_level_status) {
            levels += "value: " + std::to_string(v.first) + " status: " + std::to_string(v.second.value()) + "\n";
         }
         return levels;
      }

      void reset() {
         internal::g_log_level_status.clear();
         internal::g_log_level_status = std::map<int, atomicbool>{{g3::kTraceValue, true}, {g3::kDebugValue, true}, {INFO.value, true}, {WARNING.value, true}, {ERROR.value, true}, {FATAL.value, true}};
      }

      void disableAll() {
         internal::g_log_level_status.clear();
         internal::g_log_level_status = std::map<int, atomicbool>{{g3::kTraceValue, false}, {g3::kDebugValue, false}, {INFO.value, false}, {WARNING.value, false}, {ERROR.value, false}, {FATAL.value, false}};
      }

      void setLogLevel(const std::string &log_level) {
        auto it = internal::g_log_level_name.find(log_level);
        if (it!= internal::g_log_level_name.end()) {
          for(auto& v : internal::g_log_level_status) {
            if (v.first < it->second){
              internal::g_log_level_status[v.first].get().store(false, std::memory_order_release);
            }else {
              internal::g_log_level_status[v.first].get().store(true, std::memory_order_release);
            }
          }
        }
      }
   } // only_change_at_initialization

   bool isValidLevel(const std::string& log_level) {
     auto it = internal::g_log_level_name.find(log_level);
     return it != internal::g_log_level_name.end();
   }

   std::vector<std::string> getAllLevels() {
     return internal::g_log_all_levels;
   }
#endif

   bool logLevel(LEVELS log_level) {
#ifdef G3_DYNAMIC_LOGGING
      int level = log_level.value;
      bool status = internal::g_log_level_status[level].value();
      return status;
#endif
      return true;
   }

} // g3
<|endoftext|>


<commit_before>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2014-2018 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <warn/push>
#include <warn/ignore/all>
#include <gtest/gtest.h>
#include <warn/pop>

#include <inviwo/core/common/inviwo.h>
#include <inviwo/core/util/glm.h>

#include <limits>
#include <type_traits>

namespace inviwo {

using namespace util;

template <typename T, typename std::enable_if<std::is_floating_point<T>::value, int>::type = 0>
T minv() {
    return T{0.0};
}

template <typename T, typename std::enable_if<!std::is_floating_point<T>::value, int>::type = 0>
T minv() {
    return std::numeric_limits<T>::lowest();
}

template <typename T, typename std::enable_if<std::is_floating_point<T>::value, int>::type = 0>
T maxv() {
    return T{1.0};
}

template <typename T, typename std::enable_if<!std::is_floating_point<T>::value, int>::type = 0>
T maxv() {
    return std::numeric_limits<T>::max();
}

template <typename To, typename From>
void testmax() {
    auto res = glm_convert_normalized<To>(maxv<From>());
    EXPECT_EQ(maxv<To>(), res);
}

template <typename To, typename From>
void testmin() {
    auto res = glm_convert_normalized<To>(minv<From>());
    EXPECT_EQ(minv<To>(), res);
}

#define CONV_TEST(Name, From, To)                             \
    TEST(ConversionTests, Min##Name) { testmin<To, From>(); } \
    TEST(ConversionTests, Max##Name) { testmax<To, From>(); }

/* Mathematica code to generate tests.

types = {"float", "double", "unsigned char", "unsigned short", "unsigned int",
    "unsigned long long",
   "signed char", "signed short", "signed int", "signed long long"};
pairs = Tuples[types, {2}];
StringJoin[
 Map["CONV_TEST(" <> StringReplace[#[[1]], " " -> "_"] <> "2" <>
    StringReplace[#[[2]], " " -> "_"] <> ", " <> #[[1]] <> ", " <> #[[2]] <>
    ")\n" &, pairs]]

*/

// Floating point to higer precision ints fails since:
// 1.0 * longlong::max() can't be represented exactly as a double...
// hence it will not be equal to longlong::max() when casted to a longlong...

CONV_TEST(float2float, float, float)
CONV_TEST(float2double, float, double)
CONV_TEST(float2unsigned_char, float, unsigned char)
CONV_TEST(float2unsigned_short, float, unsigned short)
// CONV_TEST(float2unsigned_int, float, unsigned int)
// CONV_TEST(float2unsigned_long_long, float, unsigned long long)
CONV_TEST(float2signed_char, float, signed char)
CONV_TEST(float2signed_short, float, signed short)
// CONV_TEST(float2signed_int, float, signed int)
// CONV_TEST(float2signed_long_long, float, signed long long)

CONV_TEST(double2float, double, float)
CONV_TEST(double2double, double, double)
CONV_TEST(double2unsigned_char, double, unsigned char)
CONV_TEST(double2unsigned_short, double, unsigned short)
CONV_TEST(double2unsigned_int, double, unsigned int)
// CONV_TEST(double2unsigned_long_long, double, unsigned long long)
CONV_TEST(double2signed_char, double, signed char)
CONV_TEST(double2signed_short, double, signed short)
CONV_TEST(double2signed_int, double, signed int)
// CONV_TEST(double2signed_long_long, double, signed long long)

CONV_TEST(unsigned_char2float, unsigned char, float)
CONV_TEST(unsigned_char2double, unsigned char, double)
CONV_TEST(unsigned_char2unsigned_char, unsigned char, unsigned char)
CONV_TEST(unsigned_char2unsigned_short, unsigned char, unsigned short)
CONV_TEST(unsigned_char2unsigned_int, unsigned char, unsigned int)
CONV_TEST(unsigned_char2unsigned_long_long, unsigned char, unsigned long long)
CONV_TEST(unsigned_char2signed_char, unsigned char, signed char)
CONV_TEST(unsigned_char2signed_short, unsigned char, signed short)
// CONV_TEST(unsigned_char2signed_int, unsigned char, signed int)
// CONV_TEST(unsigned_char2signed_long_long, unsigned char, signed long long)

CONV_TEST(unsigned_short2float, unsigned short, float)
CONV_TEST(unsigned_short2double, unsigned short, double)
CONV_TEST(unsigned_short2unsigned_char, unsigned short, unsigned char)
CONV_TEST(unsigned_short2unsigned_short, unsigned short, unsigned short)
CONV_TEST(unsigned_short2unsigned_int, unsigned short, unsigned int)
CONV_TEST(unsigned_short2unsigned_long_long, unsigned short, unsigned long long)
CONV_TEST(unsigned_short2signed_char, unsigned short, signed char)
CONV_TEST(unsigned_short2signed_short, unsigned short, signed short)
// CONV_TEST(unsigned_short2signed_int, unsigned short, signed int)
// CONV_TEST(unsigned_short2signed_long_long, unsigned short, signed long long)

CONV_TEST(unsigned_int2float, unsigned int, float)
CONV_TEST(unsigned_int2double, unsigned int, double)
CONV_TEST(unsigned_int2unsigned_char, unsigned int, unsigned char)
CONV_TEST(unsigned_int2unsigned_short, unsigned int, unsigned short)
CONV_TEST(unsigned_int2unsigned_int, unsigned int, unsigned int)
CONV_TEST(unsigned_int2unsigned_long_long, unsigned int, unsigned long long)
CONV_TEST(unsigned_int2signed_char, unsigned int, signed char)
CONV_TEST(unsigned_int2signed_short, unsigned int, signed short)
CONV_TEST(unsigned_int2signed_int, unsigned int, signed int)
// CONV_TEST(unsigned_int2signed_long_long, unsigned int, signed long long)

CONV_TEST(unsigned_long_long2float, unsigned long long, float)
CONV_TEST(unsigned_long_long2double, unsigned long long, double)
CONV_TEST(unsigned_long_long2unsigned_char, unsigned long long, unsigned char)
CONV_TEST(unsigned_long_long2unsigned_short, unsigned long long, unsigned short)
CONV_TEST(unsigned_long_long2unsigned_int, unsigned long long, unsigned int)
CONV_TEST(unsigned_long_long2unsigned_long_long, unsigned long long, unsigned long long)
CONV_TEST(unsigned_long_long2signed_char, unsigned long long, signed char)
CONV_TEST(unsigned_long_long2signed_short, unsigned long long, signed short)
CONV_TEST(unsigned_long_long2signed_int, unsigned long long, signed int)
CONV_TEST(unsigned_long_long2signed_long_long, unsigned long long, signed long long)

CONV_TEST(signed_char2float, signed char, float)
CONV_TEST(signed_char2double, signed char, double)
CONV_TEST(signed_char2unsigned_char, signed char, unsigned char)
CONV_TEST(signed_char2unsigned_short, signed char, unsigned short)
CONV_TEST(signed_char2unsigned_int, signed char, unsigned int)
CONV_TEST(signed_char2unsigned_long_long, signed char, unsigned long long)

CONV_TEST(signed_char2signed_char, signed char, signed char)
CONV_TEST(signed_char2signed_short, signed char, signed short)
CONV_TEST(signed_char2signed_int, signed char, signed int)
CONV_TEST(signed_char2signed_long_long, signed char, signed long long)

CONV_TEST(signed_short2float, signed short, float)
CONV_TEST(signed_short2double, signed short, double)
CONV_TEST(signed_short2unsigned_char, signed short, unsigned char)
CONV_TEST(signed_short2unsigned_short, signed short, unsigned short)
CONV_TEST(signed_short2unsigned_int, signed short, unsigned int)
CONV_TEST(signed_short2unsigned_long_long, signed short, unsigned long long)
CONV_TEST(signed_short2signed_char, signed short, signed char)
CONV_TEST(signed_short2signed_short, signed short, signed short)
CONV_TEST(signed_short2signed_int, signed short, signed int)
CONV_TEST(signed_short2signed_long_long, signed short, signed long long)

CONV_TEST(signed_int2float, signed int, float)
CONV_TEST(signed_int2double, signed int, double)
CONV_TEST(signed_int2unsigned_char, signed int, unsigned char)
CONV_TEST(signed_int2unsigned_short, signed int, unsigned short)
CONV_TEST(signed_int2unsigned_int, signed int, unsigned int)
CONV_TEST(signed_int2unsigned_long_long, signed int, unsigned long long)
CONV_TEST(signed_int2signed_char, signed int, signed char)
CONV_TEST(signed_int2signed_short, signed int, signed short)
CONV_TEST(signed_int2signed_int, signed int, signed int)
CONV_TEST(signed_int2signed_long_long, signed int, signed long long)

CONV_TEST(signed_long_long2float, signed long long, float)
CONV_TEST(signed_long_long2double, signed long long, double)
CONV_TEST(signed_long_long2unsigned_char, signed long long, unsigned char)
CONV_TEST(signed_long_long2unsigned_short, signed long long, unsigned short)
CONV_TEST(signed_long_long2unsigned_int, signed long long, unsigned int)
CONV_TEST(signed_long_long2unsigned_long_long, signed long long, unsigned long long)

// CONV_TEST(signed_long_long2signed_char, signed long long, signed char) can't grow long long
// CONV_TEST(signed_long_long2signed_short, signed long long, signed short)
// CONV_TEST(signed_long_long2signed_int, signed long long, signed int)

CONV_TEST(signed_long_long2signed_long_long, signed long long, signed long long)

}  // namespace inviwo<commit_msg>Clang: tmp fix<commit_after>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2014-2018 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <warn/push>
#include <warn/ignore/all>
#include <gtest/gtest.h>
#include <warn/pop>

#include <inviwo/core/common/inviwo.h>
#include <inviwo/core/util/glm.h>

#include <limits>
#include <type_traits>

namespace inviwo {

using namespace util;

template <typename T, typename std::enable_if<std::is_floating_point<T>::value, int>::type = 0>
T minv() {
    return T{0.0};
}

template <typename T, typename std::enable_if<!std::is_floating_point<T>::value, int>::type = 0>
T minv() {
    return std::numeric_limits<T>::lowest();
}

template <typename T, typename std::enable_if<std::is_floating_point<T>::value, int>::type = 0>
T maxv() {
    return T{1.0};
}

template <typename T, typename std::enable_if<!std::is_floating_point<T>::value, int>::type = 0>
T maxv() {
    return std::numeric_limits<T>::max();
}

template <typename To, typename From>
void testmax() {
    auto res = glm_convert_normalized<To>(maxv<From>());
    EXPECT_EQ(maxv<To>(), res);
}

template <typename To, typename From>
void testmin() {
    auto res = glm_convert_normalized<To>(minv<From>());
    EXPECT_EQ(minv<To>(), res);
}

#define CONV_TEST(Name, From, To)                             \
    TEST(ConversionTests, Min##Name) { testmin<To, From>(); } \
    TEST(ConversionTests, Max##Name) { testmax<To, From>(); }

/* Mathematica code to generate tests.

types = {"float", "double", "unsigned char", "unsigned short", "unsigned int",
    "unsigned long long",
   "signed char", "signed short", "signed int", "signed long long"};
pairs = Tuples[types, {2}];
StringJoin[
 Map["CONV_TEST(" <> StringReplace[#[[1]], " " -> "_"] <> "2" <>
    StringReplace[#[[2]], " " -> "_"] <> ", " <> #[[1]] <> ", " <> #[[2]] <>
    ")\n" &, pairs]]

*/

// Floating point to higer precision ints fails since:
// 1.0 * longlong::max() can't be represented exactly as a double...
// hence it will not be equal to longlong::max() when casted to a longlong...

CONV_TEST(float2float, float, float)
CONV_TEST(float2double, float, double)
CONV_TEST(float2unsigned_char, float, unsigned char)
CONV_TEST(float2unsigned_short, float, unsigned short)
// CONV_TEST(float2unsigned_int, float, unsigned int)
// CONV_TEST(float2unsigned_long_long, float, unsigned long long)
CONV_TEST(float2signed_char, float, signed char)
CONV_TEST(float2signed_short, float, signed short)
// CONV_TEST(float2signed_int, float, signed int)
// CONV_TEST(float2signed_long_long, float, signed long long)

CONV_TEST(double2float, double, float)
CONV_TEST(double2double, double, double)
CONV_TEST(double2unsigned_char, double, unsigned char)
CONV_TEST(double2unsigned_short, double, unsigned short)
CONV_TEST(double2unsigned_int, double, unsigned int)
// CONV_TEST(double2unsigned_long_long, double, unsigned long long)
CONV_TEST(double2signed_char, double, signed char)
CONV_TEST(double2signed_short, double, signed short)
CONV_TEST(double2signed_int, double, signed int)
// CONV_TEST(double2signed_long_long, double, signed long long)

CONV_TEST(unsigned_char2float, unsigned char, float)
CONV_TEST(unsigned_char2double, unsigned char, double)
CONV_TEST(unsigned_char2unsigned_char, unsigned char, unsigned char)
CONV_TEST(unsigned_char2unsigned_short, unsigned char, unsigned short)
CONV_TEST(unsigned_char2unsigned_int, unsigned char, unsigned int)
CONV_TEST(unsigned_char2unsigned_long_long, unsigned char, unsigned long long)
CONV_TEST(unsigned_char2signed_char, unsigned char, signed char)
CONV_TEST(unsigned_char2signed_short, unsigned char, signed short)
// CONV_TEST(unsigned_char2signed_int, unsigned char, signed int)
// CONV_TEST(unsigned_char2signed_long_long, unsigned char, signed long long)

CONV_TEST(unsigned_short2float, unsigned short, float)
CONV_TEST(unsigned_short2double, unsigned short, double)
CONV_TEST(unsigned_short2unsigned_char, unsigned short, unsigned char)
CONV_TEST(unsigned_short2unsigned_short, unsigned short, unsigned short)
CONV_TEST(unsigned_short2unsigned_int, unsigned short, unsigned int)
CONV_TEST(unsigned_short2unsigned_long_long, unsigned short, unsigned long long)
CONV_TEST(unsigned_short2signed_char, unsigned short, signed char)
CONV_TEST(unsigned_short2signed_short, unsigned short, signed short)
// CONV_TEST(unsigned_short2signed_int, unsigned short, signed int)
// CONV_TEST(unsigned_short2signed_long_long, unsigned short, signed long long)

CONV_TEST(unsigned_int2float, unsigned int, float)
CONV_TEST(unsigned_int2double, unsigned int, double)
CONV_TEST(unsigned_int2unsigned_char, unsigned int, unsigned char)
CONV_TEST(unsigned_int2unsigned_short, unsigned int, unsigned short)
CONV_TEST(unsigned_int2unsigned_int, unsigned int, unsigned int)
CONV_TEST(unsigned_int2unsigned_long_long, unsigned int, unsigned long long)
CONV_TEST(unsigned_int2signed_char, unsigned int, signed char)
CONV_TEST(unsigned_int2signed_short, unsigned int, signed short)
// CONV_TEST(unsigned_int2signed_int, unsigned int, signed int) # clang failure
// CONV_TEST(unsigned_int2signed_long_long, unsigned int, signed long long)

CONV_TEST(unsigned_long_long2float, unsigned long long, float)
CONV_TEST(unsigned_long_long2double, unsigned long long, double)
CONV_TEST(unsigned_long_long2unsigned_char, unsigned long long, unsigned char)
CONV_TEST(unsigned_long_long2unsigned_short, unsigned long long, unsigned short)
CONV_TEST(unsigned_long_long2unsigned_int, unsigned long long, unsigned int)
CONV_TEST(unsigned_long_long2unsigned_long_long, unsigned long long, unsigned long long)
CONV_TEST(unsigned_long_long2signed_char, unsigned long long, signed char)
CONV_TEST(unsigned_long_long2signed_short, unsigned long long, signed short)
// CONV_TEST(unsigned_long_long2signed_int, unsigned long long, signed int) # clang failure
// CONV_TEST(unsigned_long_long2signed_long_long, unsigned long long, signed long long) # clang failure

CONV_TEST(signed_char2float, signed char, float)
CONV_TEST(signed_char2double, signed char, double)
CONV_TEST(signed_char2unsigned_char, signed char, unsigned char)
CONV_TEST(signed_char2unsigned_short, signed char, unsigned short)
CONV_TEST(signed_char2unsigned_int, signed char, unsigned int)
CONV_TEST(signed_char2unsigned_long_long, signed char, unsigned long long)

CONV_TEST(signed_char2signed_char, signed char, signed char)
CONV_TEST(signed_char2signed_short, signed char, signed short)
CONV_TEST(signed_char2signed_int, signed char, signed int)
CONV_TEST(signed_char2signed_long_long, signed char, signed long long)

CONV_TEST(signed_short2float, signed short, float)
CONV_TEST(signed_short2double, signed short, double)
CONV_TEST(signed_short2unsigned_char, signed short, unsigned char)
CONV_TEST(signed_short2unsigned_short, signed short, unsigned short)
CONV_TEST(signed_short2unsigned_int, signed short, unsigned int)
CONV_TEST(signed_short2unsigned_long_long, signed short, unsigned long long)
CONV_TEST(signed_short2signed_char, signed short, signed char)
CONV_TEST(signed_short2signed_short, signed short, signed short)
CONV_TEST(signed_short2signed_int, signed short, signed int)
CONV_TEST(signed_short2signed_long_long, signed short, signed long long)

CONV_TEST(signed_int2float, signed int, float)
CONV_TEST(signed_int2double, signed int, double)
CONV_TEST(signed_int2unsigned_char, signed int, unsigned char)
CONV_TEST(signed_int2unsigned_short, signed int, unsigned short)
CONV_TEST(signed_int2unsigned_int, signed int, unsigned int)
CONV_TEST(signed_int2unsigned_long_long, signed int, unsigned long long)
CONV_TEST(signed_int2signed_char, signed int, signed char)
CONV_TEST(signed_int2signed_short, signed int, signed short)
CONV_TEST(signed_int2signed_int, signed int, signed int)
CONV_TEST(signed_int2signed_long_long, signed int, signed long long)

CONV_TEST(signed_long_long2float, signed long long, float)
CONV_TEST(signed_long_long2double, signed long long, double)
CONV_TEST(signed_long_long2unsigned_char, signed long long, unsigned char)
CONV_TEST(signed_long_long2unsigned_short, signed long long, unsigned short)
CONV_TEST(signed_long_long2unsigned_int, signed long long, unsigned int)
CONV_TEST(signed_long_long2unsigned_long_long, signed long long, unsigned long long)

// CONV_TEST(signed_long_long2signed_char, signed long long, signed char) can't grow long long
// CONV_TEST(signed_long_long2signed_short, signed long long, signed short)
// CONV_TEST(signed_long_long2signed_int, signed long long, signed int)

CONV_TEST(signed_long_long2signed_long_long, signed long long, signed long long)

}  // namespace inviwo<|endoftext|>


<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "mkeyboardstatetracker.h"
#include "mkeyboardstatetracker_p.h"
#include <QVariant>
#include <QCoreApplication>

#ifdef HAVE_CONTEXTSUBSCRIBER
#include "contextproperty.h"
#endif

#include <MDebug>

namespace {
    const QString keyboardPresent("/maemo/InternalKeyboard/Present");
}

MKeyboardStateTracker *MKeyboardStateTrackerPrivate::tracker = 0;

MKeyboardStateTrackerPrivate::MKeyboardStateTrackerPrivate(MKeyboardStateTracker *controller) :
#ifdef HAVE_CONTEXTSUBSCRIBER
    keyboardOpenProperty(0),
    isSubscribed(false),
#elif defined(M_OS_MAEMO5)
    keyboardOpenConf("/system/osso/af/slide-open"),
#endif
    q_ptr(controller),
    present(false)
{
    Q_Q(MKeyboardStateTracker);
#ifdef HAVE_CONTEXTSUBSCRIBER
    checkKeyboardPresent();
    if (present) {
        keyboardOpenProperty = new ContextProperty(QString("/maemo/InternalKeyboard/Open"));
        QObject::connect(keyboardOpenProperty, SIGNAL(valueChanged()),
                     q, SIGNAL(stateChanged()));
    }
#elif defined(M_OS_MAEMO5)
    QObject::connect(&keyboardOpenConf, SIGNAL(valueChanged()),
                     q, SIGNAL(stateChanged()));
#endif

    initContextSubscriber();
}

void MKeyboardStateTrackerPrivate::initContextSubscriber()
{
#ifdef HAVE_CONTEXTSUBSCRIBER
    if (!present)
        return;
    //waiting for properties to synchronize
    keyboardOpenProperty->waitForSubscription(true);
    isSubscribed = true;
#elif defined(M_OS_MAEMO5)
    present = true;
#endif
}

#ifdef HAVE_CONTEXTSUBSCRIBER
void MKeyboardStateTrackerPrivate::checkKeyboardPresent()
{
    ContextProperty keyboardPresentProperty(keyboardPresent);
    keyboardPresentProperty.waitForSubscription(true);
    present = keyboardPresentProperty.value().toBool();
}
#endif

void MKeyboardStateTrackerPrivate::subscribe()
{
#ifdef HAVE_CONTEXTSUBSCRIBER
    if (present)
        keyboardOpenProperty->subscribe();
#endif
}

void MKeyboardStateTrackerPrivate::unsubscribe()
{
#ifdef HAVE_CONTEXTSUBSCRIBER
    if (present) {
        keyboardOpenProperty->unsubscribe();
        isSubscribed = false;
    }
#endif
}

MKeyboardStateTracker::MKeyboardStateTracker() :
    d_ptr(new MKeyboardStateTrackerPrivate(this))
{
    setParent(QCoreApplication::instance()); //get collected when needed.
}

MKeyboardStateTracker *MKeyboardStateTracker::instance()
{
    if (!MKeyboardStateTrackerPrivate::tracker)
        MKeyboardStateTrackerPrivate::tracker = new MKeyboardStateTracker();
    return MKeyboardStateTrackerPrivate::tracker;
}

MKeyboardStateTracker::~MKeyboardStateTracker()
{
    if (this == MKeyboardStateTrackerPrivate::tracker)
        MKeyboardStateTrackerPrivate::tracker = 0;
    delete d_ptr;
}

bool MKeyboardStateTracker::isPresent() const
{
    Q_D(const MKeyboardStateTracker);

    return d->present;
}

bool MKeyboardStateTracker::isOpen() const
{
    bool val = false;
    Q_D(const MKeyboardStateTracker);
    if (d->present) {
#ifdef HAVE_CONTEXTSUBSCRIBER
        MKeyboardStateTrackerPrivate* trackerPriv = const_cast<MKeyboardStateTrackerPrivate*>(d);
        if (!d->isSubscribed) {
            trackerPriv->subscribe();
            trackerPriv->initContextSubscriber();
        }
        val = d->keyboardOpenProperty->value().toBool();
#elif defined(M_OS_MAEMO5)
        val = d->keyboardOpenConf.value().toBool();
#endif
    }
    return val;
}
<commit_msg>Fixes: Build break without context subscriber.<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "mkeyboardstatetracker.h"
#include "mkeyboardstatetracker_p.h"
#include <QVariant>
#include <QCoreApplication>

#ifdef HAVE_CONTEXTSUBSCRIBER
#include "contextproperty.h"
#endif

#include <MDebug>

namespace {
    const QString keyboardPresent("/maemo/InternalKeyboard/Present");
}

MKeyboardStateTracker *MKeyboardStateTrackerPrivate::tracker = 0;

MKeyboardStateTrackerPrivate::MKeyboardStateTrackerPrivate(MKeyboardStateTracker *controller) :
#ifdef HAVE_CONTEXTSUBSCRIBER
    keyboardOpenProperty(0),
    isSubscribed(false),
#elif defined(M_OS_MAEMO5)
    keyboardOpenConf("/system/osso/af/slide-open"),
#endif
    q_ptr(controller),
    present(false)
{
    Q_Q(MKeyboardStateTracker);
#ifdef HAVE_CONTEXTSUBSCRIBER
    checkKeyboardPresent();
    if (present) {
        keyboardOpenProperty = new ContextProperty(QString("/maemo/InternalKeyboard/Open"));
        QObject::connect(keyboardOpenProperty, SIGNAL(valueChanged()),
                     q, SIGNAL(stateChanged()));
    }
#elif defined(M_OS_MAEMO5)
    QObject::connect(&keyboardOpenConf, SIGNAL(valueChanged()),
                     q, SIGNAL(stateChanged()));
#else
    Q_UNUSED(q);
#endif

    initContextSubscriber();
}

void MKeyboardStateTrackerPrivate::initContextSubscriber()
{
#ifdef HAVE_CONTEXTSUBSCRIBER
    if (!present)
        return;
    //waiting for properties to synchronize
    keyboardOpenProperty->waitForSubscription(true);
    isSubscribed = true;
#elif defined(M_OS_MAEMO5)
    present = true;
#endif
}

#ifdef HAVE_CONTEXTSUBSCRIBER
void MKeyboardStateTrackerPrivate::checkKeyboardPresent()
{
    ContextProperty keyboardPresentProperty(keyboardPresent);
    keyboardPresentProperty.waitForSubscription(true);
    present = keyboardPresentProperty.value().toBool();
}
#endif

void MKeyboardStateTrackerPrivate::subscribe()
{
#ifdef HAVE_CONTEXTSUBSCRIBER
    if (present)
        keyboardOpenProperty->subscribe();
#endif
}

void MKeyboardStateTrackerPrivate::unsubscribe()
{
#ifdef HAVE_CONTEXTSUBSCRIBER
    if (present) {
        keyboardOpenProperty->unsubscribe();
        isSubscribed = false;
    }
#endif
}

MKeyboardStateTracker::MKeyboardStateTracker() :
    d_ptr(new MKeyboardStateTrackerPrivate(this))
{
    setParent(QCoreApplication::instance()); //get collected when needed.
}

MKeyboardStateTracker *MKeyboardStateTracker::instance()
{
    if (!MKeyboardStateTrackerPrivate::tracker)
        MKeyboardStateTrackerPrivate::tracker = new MKeyboardStateTracker();
    return MKeyboardStateTrackerPrivate::tracker;
}

MKeyboardStateTracker::~MKeyboardStateTracker()
{
    if (this == MKeyboardStateTrackerPrivate::tracker)
        MKeyboardStateTrackerPrivate::tracker = 0;
    delete d_ptr;
}

bool MKeyboardStateTracker::isPresent() const
{
    Q_D(const MKeyboardStateTracker);

    return d->present;
}

bool MKeyboardStateTracker::isOpen() const
{
    bool val = false;
    Q_D(const MKeyboardStateTracker);
    if (d->present) {
#ifdef HAVE_CONTEXTSUBSCRIBER
        MKeyboardStateTrackerPrivate* trackerPriv = const_cast<MKeyboardStateTrackerPrivate*>(d);
        if (!d->isSubscribed) {
            trackerPriv->subscribe();
            trackerPriv->initContextSubscriber();
        }
        val = d->keyboardOpenProperty->value().toBool();
#elif defined(M_OS_MAEMO5)
        val = d->keyboardOpenConf.value().toBool();
#endif
    }
    return val;
}
<|endoftext|>


<commit_before>/*
 * SessionTexEngine.cpp
 *
 * Copyright (C) 2009-11 by RStudio, Inc.
 *
 * This program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "SessionTexEngine.hpp"

#include <boost/foreach.hpp>

#include <core/Error.hpp>
#include <core/FilePath.hpp>

#include <core/system/Environment.hpp>
#include <core/system/Process.hpp>
#include <core/system/ShellUtils.hpp>

#include <r/RExec.hpp>
#include <r/RRoutines.hpp>

#include <session/SessionModuleContext.hpp>

// TODO: why does R texi2dvi set LC_COLLATE=C?

// TODO: respect getOption("texi2dvi") and fallback appropriately?

// TODO: investigate other texi2dvi and pdflatex options
//         -- shell-escape
//         -- clean
//         -- alternative output file location

// TODO: emulate texi2dvi on linux to workaround debian tilde
//       escaping bug (http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=534458)

// TODO: should we wrap PDFLATEX in a script?

using namespace core;

namespace session {
namespace modules {
namespace tex {
namespace engine {

namespace {

FilePath texBinaryPath(const std::string& name)
{
   std::string which;
   Error error = r::exec::RFunction("Sys.which", name).call(&which);
   if (error)
   {
      LOG_ERROR(error);
      return FilePath();
   }
   else
   {
      return FilePath(which);
   }
}

// this function attempts to emulate the behavior of tools::texi2dvi
// in appending extra paths to TEXINPUTS, BIBINPUTS, & BSTINPUTS
core::system::Option texEnvVar(const std::string& name,
                               const FilePath& extraPath,
                               bool ensureForwardSlashes)
{
   std::string value = core::system::getenv(name);
   if (value.empty())
      value = ".";

   if (ensureForwardSlashes)
      boost::algorithm::replace_all(value, "\\", "/");

   core::system::addToPath(&value, extraPath.absolutePath());
   core::system::addToPath(&value, ""); // trailing : required by tex

   return std::make_pair(name, value);
}

core::system::Option pdfLatexEnvVar()
{
   std::string pdfLatexCmd =
      string_utils::utf8ToSystem(texBinaryPath("pdflatex").absolutePath());
   pdfLatexCmd += " --file-line-error --synctex=-1";
   return std::make_pair("PDFLATEX", pdfLatexCmd);
}

core::system::Options texEnvironmentVars()
{
   // custom environment for tex
   core::system::Options envVars;

   // TODO: R texi2dvi sets LC_COLLATE=C before calling texi2dvi, why?
   envVars.push_back(std::make_pair("LC_COLLATE", "C"));

   // first determine the R share directory
   std::string rHomeShare;
   r::exec::RFunction rHomeShareFunc("R.home", "share");
   Error error = rHomeShareFunc.call(&rHomeShare);
   if (error)
   {
      LOG_ERROR(error);
      return core::system::Options();
   }
   FilePath rHomeSharePath(rHomeShare);
   if (!rHomeSharePath.exists())
   {
      LOG_ERROR(core::pathNotFoundError(rHomeShare, ERROR_LOCATION));
      return core::system::Options();
   }

   // R texmf path
   FilePath rTexmfPath(rHomeSharePath.complete("texmf"));

   // fixup tex related environment variables to point to the R
   // tex, bib, and bst directories

   envVars.push_back(texEnvVar("TEXINPUTS",
                               rTexmfPath.childPath("tex/latex"),
                               true));

   envVars.push_back(texEnvVar("BIBINPUTS",
                               rTexmfPath.childPath("bibtex/bib"),
                               false));

   envVars.push_back(texEnvVar("BSTINPUTS",
                               rTexmfPath.childPath("bibtex/bst"),
                               false));

   // define a custom variation of PDFLATEX that includes the
   // command line parameters we need
   envVars.push_back(pdfLatexEnvVar());

   return envVars;
}

shell_utils::ShellArgs texShellArgs()
{
   shell_utils::ShellArgs args;

   args << "--pdf";
   args << "--quiet";

   return args;
}

Error executeTexToPdf(const FilePath& texProgramPath,
                      const core::system::Options& envVars,
                      const shell_utils::ShellArgs& args,
                      const FilePath& texFilePath)
{
   // copy extra environment variables
   core::system::Options env;
   core::system::environment(&env);
   BOOST_FOREACH(const core::system::Option& var, envVars)
   {
      core::system::setenv(&env, var.first, var.second);
   }

   // setup args
   shell_utils::ShellArgs procArgs;
   procArgs << args;
   procArgs << texFilePath.filename();

   // set options
   core::system::ProcessOptions procOptions;
   procOptions.terminateChildren = true;
   procOptions.environment = env;
   procOptions.workingDir = texFilePath.parent();

   // setup callbacks
   core::system::ProcessCallbacks cb;
   cb.onStdout = boost::bind(module_context::consoleWriteOutput, _2);
   cb.onStderr = boost::bind(module_context::consoleWriteError, _2);

   // run the program
   using namespace core::shell_utils;
   return module_context::processSupervisor().runProgram(
                                             texProgramPath.absolutePath(),
                                             procArgs,
                                             procOptions,
                                             cb);
}

SEXP rs_texToPdf(SEXP filePathSEXP)
{
   FilePath texFilePath =
         module_context::resolveAliasedPath(r::sexp::asString(filePathSEXP));

   Error error = executeTexToPdf(texBinaryPath("texi2dvi"),
                                 texEnvironmentVars(),
                                 texShellArgs(),
                                 texFilePath);
   if (error)
      module_context::consoleWriteError(error.summary() + "\n");

   return R_NilValue;
}

} // anonymous namespace

Error initialize()
{
   R_CallMethodDef runTexToPdfMethodDef;
   runTexToPdfMethodDef.name = "rs_texToPdf" ;
   runTexToPdfMethodDef.fun = (DL_FUNC) rs_texToPdf ;
   runTexToPdfMethodDef.numArgs = 1;
   r::routines::addCallMethod(runTexToPdfMethodDef);

   return Success();
}

} // namespace engine
} // namespace tex
} // namespace modules
} // namesapce session

<commit_msg>correct command line parametes for MikTeX version of texi2dvi<commit_after>/*
 * SessionTexEngine.cpp
 *
 * Copyright (C) 2009-11 by RStudio, Inc.
 *
 * This program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "SessionTexEngine.hpp"

#include <boost/foreach.hpp>

#include <core/Error.hpp>
#include <core/FilePath.hpp>

#include <core/system/Environment.hpp>
#include <core/system/Process.hpp>
#include <core/system/ShellUtils.hpp>

#include <r/RExec.hpp>
#include <r/RRoutines.hpp>

#include <session/SessionModuleContext.hpp>

// TODO: why does R texi2dvi set LC_COLLATE=C?

// TODO: respect getOption("texi2dvi") and fallback appropriately?

// TODO: investigate other texi2dvi and pdflatex options
//         -- shell-escape
//         -- clean
//         -- alternative output file location

// TODO: emulate texi2dvi on linux to workaround debian tilde
//       escaping bug (http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=534458)

// TODO: should we wrap PDFLATEX in a script?

// TODO: verify we got all of the shell/path escaping right
*/

using namespace core;

namespace session {
namespace modules {
namespace tex {
namespace engine {

namespace {

struct RTexmfPaths
{
   bool empty() const { return texInputsPath.empty(); }

   FilePath texInputsPath;
   FilePath bibInputsPath;
   FilePath bstInputsPath;
};

RTexmfPaths rTexmfPaths()
{
   // first determine the R share directory
   std::string rHomeShare;
   r::exec::RFunction rHomeShareFunc("R.home", "share");
   Error error = rHomeShareFunc.call(&rHomeShare);
   if (error)
   {
      LOG_ERROR(error);
      return RTexmfPaths();
   }
   FilePath rHomeSharePath(rHomeShare);
   if (!rHomeSharePath.exists())
   {
      LOG_ERROR(core::pathNotFoundError(rHomeShare, ERROR_LOCATION));
      return RTexmfPaths();
   }

   // R texmf path
   FilePath rTexmfPath(rHomeSharePath.complete("texmf"));
   if (!rTexmfPath.exists())
   {
      LOG_ERROR(core::pathNotFoundError(rTexmfPath.absolutePath(),
                                        ERROR_LOCATION));
      return RTexmfPaths();
   }

   // populate and return struct
   RTexmfPaths texmfPaths;
   texmfPaths.texInputsPath = rTexmfPath.childPath("tex/latex");
   texmfPaths.bibInputsPath = rTexmfPath.childPath("bibtex/bib");
   texmfPaths.bstInputsPath = rTexmfPath.childPath("bibtex/bst");
   return texmfPaths;
}

FilePath texBinaryPath(const std::string& name)
{
   std::string which;
   Error error = r::exec::RFunction("Sys.which", name).call(&which);
   if (error)
   {
      LOG_ERROR(error);
      return FilePath();
   }
   else
   {
      return FilePath(which);
   }
}

// this function attempts to emulate the behavior of tools::texi2dvi
// in appending extra paths to TEXINPUTS, BIBINPUTS, & BSTINPUTS
core::system::Option texEnvVar(const std::string& name,
                               const FilePath& extraPath,
                               bool ensureForwardSlashes)
{
   std::string value = core::system::getenv(name);
   if (value.empty())
      value = ".";

   // TODO: R texi2dvi does this for TEXINPUTS but not for BIBINPUTS and
   // BSTINPUTS, why?
   if (ensureForwardSlashes)
      boost::algorithm::replace_all(value, "\\", "/");

   core::system::addToPath(&value, extraPath.absolutePath());
   core::system::addToPath(&value, ""); // trailing : required by tex

   return std::make_pair(name, value);
}

core::system::Option pdfLatexEnvVar()
{
   std::string pdfLatexCmd =
      string_utils::utf8ToSystem(texBinaryPath("pdflatex").absolutePath());
   pdfLatexCmd += " --file-line-error --synctex=-1";
   return std::make_pair("PDFLATEX", pdfLatexCmd);
}

core::system::Options texEnvironmentVars(const std::string&)
{
   // custom environment for tex
   core::system::Options envVars;

   // these behaviors are from R texi2dvi -- not sure why the are important
#ifndef _WIN32
   envVars.push_back(std::make_pair("TEXINDY", "false"));
   envVars.push_back(std::make_pair("LC_COLLATE", "C"));
#endif

   RTexmfPaths texmfPaths = rTexmfPaths();
   if (!texmfPaths.empty())
   {
      envVars.push_back(texEnvVar("TEXINPUTS", texmfPaths.texInputsPath, true));
      envVars.push_back(texEnvVar("BIBINPUTS", texmfPaths.bibInputsPath,false));
      envVars.push_back(texEnvVar("BSTINPUTS", texmfPaths.bstInputsPath,false));
   }

   // define a custom variation of PDFLATEX that includes the
   // command line parameters we need
   envVars.push_back(pdfLatexEnvVar());

   return envVars;
}

shell_utils::ShellArgs texShellArgs(const std::string& texVersionInfo)
{
   shell_utils::ShellArgs args;

   args << "--pdf";
   args << "--quiet";

#ifdef _WIN32
   if (texVersionInfo.find("MiKTeX") != std::string::npos)
   {
      // TODO: R texi2dvi doesn't include BIBINPUTS here, why?
      RTexmfPaths texmfPaths = rTexmfPaths();
      if (!texmfPaths.empty())
      {
         std::string texInputs = texmfPaths.texInputsPath.absolutePath();
         boost::algorithm::replace_all(texInputs, "\\", "/");
         args << "-I" << texInputs;

         std::string bstInputs = texmfPaths.bstInputsPath.absolutePath();
         boost::algorithm::replace_all(bstInputs, "\\", "/");
         args << "-I" << bstInputs;
      }
   }
#endif

   return args;
}

Error executeTexToPdf(const FilePath& texProgramPath,
                      const core::system::Options& envVars,
                      const shell_utils::ShellArgs& args,
                      const FilePath& texFilePath)
{
   // copy extra environment variables
   core::system::Options env;
   core::system::environment(&env);
   BOOST_FOREACH(const core::system::Option& var, envVars)
   {
      core::system::setenv(&env, var.first, var.second);
   }

   // setup args
   shell_utils::ShellArgs procArgs;
   procArgs << args;
   procArgs << texFilePath.filename();

   // set options
   core::system::ProcessOptions procOptions;
   procOptions.terminateChildren = true;
   procOptions.environment = env;
   procOptions.workingDir = texFilePath.parent();

   // setup callbacks
   core::system::ProcessCallbacks cb;
   cb.onStdout = boost::bind(module_context::consoleWriteOutput, _2);
   cb.onStderr = boost::bind(module_context::consoleWriteError, _2);

   // run the program
   using namespace core::shell_utils;
   return module_context::processSupervisor().runProgram(
                                             texProgramPath.absolutePath(),
                                             procArgs,
                                             procOptions,
                                             cb);
}

SEXP rs_texToPdf(SEXP filePathSEXP)
{
   FilePath texFilePath =
         module_context::resolveAliasedPath(r::sexp::asString(filePathSEXP));

   // get the path to the texi2dvi binary
   FilePath texi2dviPath = texBinaryPath("texi2dvi");
   if (texi2dviPath.empty())
   {
      module_context::consoleWriteError("can't find texi2dvi\n");
      return R_NilValue;
   }

   // get version info from it
   core::system::ProcessResult result;
   Error error = core::system::runProgram(
                            texi2dviPath.absolutePath(),
                            core::shell_utils::ShellArgs() << "--version",
                            "",
                            core::system::ProcessOptions(),
                            &result);
   if (error)
   {
      module_context::consoleWriteError(error.summary() + "\n");
      return R_NilValue;
   }
   else if (result.exitStatus != EXIT_SUCCESS)
   {
      module_context::consoleWriteError(result.stdErr);
      return R_NilValue;
   }

   error = executeTexToPdf(texi2dviPath,
                           texEnvironmentVars(result.stdOut),
                           texShellArgs(result.stdOut),
                           texFilePath);
   if (error)
      module_context::consoleWriteError(error.summary() + "\n");

   return R_NilValue;
}

} // anonymous namespace

Error initialize()
{
   R_CallMethodDef runTexToPdfMethodDef;
   runTexToPdfMethodDef.name = "rs_texToPdf" ;
   runTexToPdfMethodDef.fun = (DL_FUNC) rs_texToPdf ;
   runTexToPdfMethodDef.numArgs = 1;
   r::routines::addCallMethod(runTexToPdfMethodDef);

   return Success();
}

} // namespace engine
} // namespace tex
} // namespace modules
} // namesapce session

<|endoftext|>


<commit_before>/** This file is part of Qt Media Hub**

Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).*
All rights reserved.

Contact:  Nokia Corporation qmh-development@qt-project.org

You may use this file under the terms of the BSD license
as follows:

Redistribution and use in source and binary forms, with or
without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

* Neither the name of Nokia Corporation and its Subsidiary(-ies)
nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior
written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/

#include "mainwindow.h"
#include "mediaserver.h"
#include "globalsettings.h"
#include "skin.h"
#include "skinmanager.h"
#include "libraryinfo.h"

#include <QNetworkProxy>
#include <QNetworkConfigurationManager>
#include <QNetworkSession>

#include <QGuiApplication>
#include <QtCore/private/qabstractanimation_p.h>

static QNetworkSession *g_networkSession = 0;

static void setupNetwork(GlobalSettings *settings)
{
    QNetworkProxy proxy;
    if (settings->isEnabled(GlobalSettings::Proxy)) {
        QString proxyHost(settings->value(GlobalSettings::ProxyHost).toString());
        int proxyPort = settings->value(GlobalSettings::ProxyPort).toInt();
        proxy.setType(QNetworkProxy::HttpProxy);
        proxy.setHostName(proxyHost);
        proxy.setPort(proxyPort);
        QNetworkProxy::setApplicationProxy(proxy);
        qWarning() << "Using proxy host" << proxyHost << "on port" << proxyPort;
    }

    // Set Internet Access Point
    QNetworkConfigurationManager mgr;
    QList<QNetworkConfiguration> activeConfigs = mgr.allConfigurations();
    if (activeConfigs.count() <= 0)
        return;

    QNetworkConfiguration cfg = activeConfigs.at(0);
    foreach(QNetworkConfiguration config, activeConfigs) {
        if (config.type() == QNetworkConfiguration::UserChoice) {
            cfg = config;
            break;
        }
    }

    g_networkSession = new QNetworkSession(cfg);
    g_networkSession->open();
    g_networkSession->waitForOpened(-1);
}

static void logMessageHandler(QtMsgType type,
                              const QMessageLogContext &,
                              const QString &msg)
{
    QString logPath(LibraryInfo::logPath() + "/qmh-log");

    switch(type)
    {
        case QtDebugMsg:
        case QtWarningMsg:
            logPath += "-debug.log";
            break;
        default:
            logPath += "-error.log";
            break;
    }

    QFile logFile(logPath);
    logFile.open(QIODevice::WriteOnly);
    logFile.write(msg.toLatin1());
    logFile.close();
}

int main(int argc, char** argv)
{
    QGuiApplication app(argc, argv);
    app.setApplicationName("sasquatch");
    app.setOrganizationName("MediaTrolls");
    app.setOrganizationDomain("sasquatch.com");

    GlobalSettings *settings = new GlobalSettings(&app);

    if (app.arguments().contains("--help") || app.arguments().contains("-help") || app.arguments().contains("-h")) {
        printf("Usage: sasquatch [-option value] [-option=value]\n"
               "\n"
               "Options (default):\n");

        for (int i = 0; i < GlobalSettings::OptionLength; ++i) {
            printf("  -%-20s %s \t (%s)\n",
                   qPrintable(settings->name((GlobalSettings::Option)i)),
                   qPrintable(settings->doc((GlobalSettings::Option)i)),
                   qPrintable(settings->value((GlobalSettings::Option)i).toString()));
        }

        printf("\n");

        // try to print skin specific settings
        settings->parseArguments(app.arguments());

        SkinManager *skinManager = new SkinManager(settings);
        if (skinManager->skins().contains(settings->value(GlobalSettings::Skin).toString())) {
            Skin *skin = skinManager->skins().value(settings->value(GlobalSettings::Skin).toString());
            if (!skin->parseManifest())
                return 1;

            printf("\n"
                   "Skin '%s' Options (default):\n", qPrintable(skin->name()));

            Settings *skinSettings = skin->settings();
            foreach (const QString &key, skinSettings->keys()) {
                printf("  -%-20s %s \t (%s)\n",
                       qPrintable(key),
                       qPrintable(skinSettings->doc(key)),
                       qPrintable(skinSettings->value(key).toString()));
            }
        }

        printf("\n");

        return 0;
    }

    // settings store order, commandline arguments rule
    settings->loadConfigFile();
    settings->parseArguments(app.arguments());

    setupNetwork(settings);

    bool redirectDebugging = settings->isEnabled(GlobalSettings::RedirectDebugOutput);
    if (redirectDebugging) qInstallMessageHandler(logMessageHandler);

    MainWindow *mainWindow = 0;
    MediaServer *mediaServer = 0;

    if (!settings->isEnabled(GlobalSettings::Headless)) {
        mainWindow = new MainWindow(settings);
        mainWindow->setSkin(settings->value(GlobalSettings::Skin).toString());
        mainWindow->show();
#if defined Q_OS_MAC
        if (settings->isEnabled(GlobalSettings::UnifiedTimer)) QUnifiedTimer::instance(true)->setConsistentTiming(true);
#endif
    } else {
        mediaServer = new MediaServer(settings);
    }

    int ret = app.exec();

    g_networkSession->close();

    delete mainWindow;
    delete mediaServer;

    return ret;
}
<commit_msg>Remove uneeded private header<commit_after>/** This file is part of Qt Media Hub**

Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).*
All rights reserved.

Contact:  Nokia Corporation qmh-development@qt-project.org

You may use this file under the terms of the BSD license
as follows:

Redistribution and use in source and binary forms, with or
without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

* Neither the name of Nokia Corporation and its Subsidiary(-ies)
nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior
written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/

#include "mainwindow.h"
#include "mediaserver.h"
#include "globalsettings.h"
#include "skin.h"
#include "skinmanager.h"
#include "libraryinfo.h"

#include <QNetworkProxy>
#include <QNetworkConfigurationManager>
#include <QNetworkSession>

#include <QGuiApplication>

static QNetworkSession *g_networkSession = 0;

static void setupNetwork(GlobalSettings *settings)
{
    QNetworkProxy proxy;
    if (settings->isEnabled(GlobalSettings::Proxy)) {
        QString proxyHost(settings->value(GlobalSettings::ProxyHost).toString());
        int proxyPort = settings->value(GlobalSettings::ProxyPort).toInt();
        proxy.setType(QNetworkProxy::HttpProxy);
        proxy.setHostName(proxyHost);
        proxy.setPort(proxyPort);
        QNetworkProxy::setApplicationProxy(proxy);
        qWarning() << "Using proxy host" << proxyHost << "on port" << proxyPort;
    }

    // Set Internet Access Point
    QNetworkConfigurationManager mgr;
    QList<QNetworkConfiguration> activeConfigs = mgr.allConfigurations();
    if (activeConfigs.count() <= 0)
        return;

    QNetworkConfiguration cfg = activeConfigs.at(0);
    foreach(QNetworkConfiguration config, activeConfigs) {
        if (config.type() == QNetworkConfiguration::UserChoice) {
            cfg = config;
            break;
        }
    }

    g_networkSession = new QNetworkSession(cfg);
    g_networkSession->open();
    g_networkSession->waitForOpened(-1);
}

static void logMessageHandler(QtMsgType type,
                              const QMessageLogContext &,
                              const QString &msg)
{
    QString logPath(LibraryInfo::logPath() + "/qmh-log");

    switch(type)
    {
        case QtDebugMsg:
        case QtWarningMsg:
            logPath += "-debug.log";
            break;
        default:
            logPath += "-error.log";
            break;
    }

    QFile logFile(logPath);
    logFile.open(QIODevice::WriteOnly);
    logFile.write(msg.toLatin1());
    logFile.close();
}

int main(int argc, char** argv)
{
    QGuiApplication app(argc, argv);
    app.setApplicationName("sasquatch");
    app.setOrganizationName("MediaTrolls");
    app.setOrganizationDomain("sasquatch.com");

    GlobalSettings *settings = new GlobalSettings(&app);

    if (app.arguments().contains("--help") || app.arguments().contains("-help") || app.arguments().contains("-h")) {
        printf("Usage: sasquatch [-option value] [-option=value]\n"
               "\n"
               "Options (default):\n");

        for (int i = 0; i < GlobalSettings::OptionLength; ++i) {
            printf("  -%-20s %s \t (%s)\n",
                   qPrintable(settings->name((GlobalSettings::Option)i)),
                   qPrintable(settings->doc((GlobalSettings::Option)i)),
                   qPrintable(settings->value((GlobalSettings::Option)i).toString()));
        }

        printf("\n");

        // try to print skin specific settings
        settings->parseArguments(app.arguments());

        SkinManager *skinManager = new SkinManager(settings);
        if (skinManager->skins().contains(settings->value(GlobalSettings::Skin).toString())) {
            Skin *skin = skinManager->skins().value(settings->value(GlobalSettings::Skin).toString());
            if (!skin->parseManifest())
                return 1;

            printf("\n"
                   "Skin '%s' Options (default):\n", qPrintable(skin->name()));

            Settings *skinSettings = skin->settings();
            foreach (const QString &key, skinSettings->keys()) {
                printf("  -%-20s %s \t (%s)\n",
                       qPrintable(key),
                       qPrintable(skinSettings->doc(key)),
                       qPrintable(skinSettings->value(key).toString()));
            }
        }

        printf("\n");

        return 0;
    }

    // settings store order, commandline arguments rule
    settings->loadConfigFile();
    settings->parseArguments(app.arguments());

    setupNetwork(settings);

    bool redirectDebugging = settings->isEnabled(GlobalSettings::RedirectDebugOutput);
    if (redirectDebugging) qInstallMessageHandler(logMessageHandler);

    MainWindow *mainWindow = 0;
    MediaServer *mediaServer = 0;

    if (!settings->isEnabled(GlobalSettings::Headless)) {
        mainWindow = new MainWindow(settings);
        mainWindow->setSkin(settings->value(GlobalSettings::Skin).toString());
        mainWindow->show();
#if defined Q_OS_MAC
        if (settings->isEnabled(GlobalSettings::UnifiedTimer)) QUnifiedTimer::instance(true)->setConsistentTiming(true);
#endif
    } else {
        mediaServer = new MediaServer(settings);
    }

    int ret = app.exec();

    g_networkSession->close();

    delete mainWindow;
    delete mediaServer;

    return ret;
}
<|endoftext|>


<commit_before>// Copyright (c) 2016 The Bitcoin Core developers
// Copyright (c) 2016-2019 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <iostream>

#include "bench.h"
#include "bloom.h"
#include "crypto/ripemd160.h"
#include "crypto/sha1.h"
#include "crypto/sha256.h"
#include "crypto/sha512.h"
#include "hashwrapper.h"
#include "random.h"
#include "uint256.h"
#include "utiltime.h"

/* Number of bytes to hash per iteration */
static const uint64_t BUFFER_SIZE = 1000 * 1000;

static void RIPEMD160(benchmark::State &state)
{
    uint8_t hash[CRIPEMD160::OUTPUT_SIZE];
    std::vector<uint8_t> in(BUFFER_SIZE, 0);
    while (state.KeepRunning())
        CRIPEMD160().Write(in.data(), in.size()).Finalize(hash);
}

static void SHA1(benchmark::State &state)
{
    uint8_t hash[CSHA1::OUTPUT_SIZE];
    std::vector<uint8_t> in(BUFFER_SIZE, 0);
    while (state.KeepRunning())
        CSHA1().Write(in.data(), in.size()).Finalize(hash);
}

static void SHA256(benchmark::State &state)
{
    uint8_t hash[CSHA256::OUTPUT_SIZE];
    std::vector<uint8_t> in(BUFFER_SIZE, 0);
    while (state.KeepRunning())
        CSHA256().Write(in.data(), in.size()).Finalize(hash);
}

static void SHA256_32b(benchmark::State &state)
{
    std::vector<uint8_t> in(32, 0);
    while (state.KeepRunning())
    {
        for (int i = 0; i < 1000000; i++)
        {
            CSHA256().Write(in.data(), in.size()).Finalize(&in[0]);
        }
    }
}

static void SHA256D64_1024(benchmark::State &state)
{
    std::vector<uint8_t> in(64 * 1024, 0);
    while (state.KeepRunning())
    {
        SHA256D64(in.data(), in.data(), 1024);
    }
}

static void SHA512(benchmark::State &state)
{
    uint8_t hash[CSHA512::OUTPUT_SIZE];
    std::vector<uint8_t> in(BUFFER_SIZE, 0);
    while (state.KeepRunning())
        CSHA512().Write(in.data(), in.size()).Finalize(hash);
}

static void SipHash_32b(benchmark::State &state)
{
    uint256 x;
    while (state.KeepRunning())
    {
        for (int i = 0; i < 1000000; i++)
        {
            *((uint64_t *)x.begin()) = SipHashUint256(0, i, x);
        }
    }
}

static void FastRandom_32bit(benchmark::State &state)
{
    FastRandomContext rng(true);
    uint32_t x = 0;
    while (state.KeepRunning())
    {
        for (int i = 0; i < 1000000; i++)
        {
            x += rng.rand32();
        }
    }
}

static void FastRandom_1bit(benchmark::State &state)
{
    FastRandomContext rng(true);
    uint32_t x = 0;
    while (state.KeepRunning())
    {
        for (int i = 0; i < 1000000; i++)
        {
            x += rng.randbool();
        }
    }
}

BENCHMARK(RIPEMD160);
BENCHMARK(SHA1);
BENCHMARK(SHA256);
BENCHMARK(SHA512);

BENCHMARK(SHA256_32b);
BENCHMARK(SHA256D64_1024);
BENCHMARK(SipHash_32b);
BENCHMARK(FastRandom_32bit);
BENCHMARK(FastRandom_1bit);
<commit_msg>Changing &vec[0] to vec.data()<commit_after>// Copyright (c) 2016 The Bitcoin Core developers
// Copyright (c) 2016-2019 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <iostream>

#include "bench.h"
#include "bloom.h"
#include "crypto/ripemd160.h"
#include "crypto/sha1.h"
#include "crypto/sha256.h"
#include "crypto/sha512.h"
#include "hashwrapper.h"
#include "random.h"
#include "uint256.h"
#include "utiltime.h"

/* Number of bytes to hash per iteration */
static const uint64_t BUFFER_SIZE = 1000 * 1000;

static void RIPEMD160(benchmark::State &state)
{
    uint8_t hash[CRIPEMD160::OUTPUT_SIZE];
    std::vector<uint8_t> in(BUFFER_SIZE, 0);
    while (state.KeepRunning())
        CRIPEMD160().Write(in.data(), in.size()).Finalize(hash);
}

static void SHA1(benchmark::State &state)
{
    uint8_t hash[CSHA1::OUTPUT_SIZE];
    std::vector<uint8_t> in(BUFFER_SIZE, 0);
    while (state.KeepRunning())
        CSHA1().Write(in.data(), in.size()).Finalize(hash);
}

static void SHA256(benchmark::State &state)
{
    uint8_t hash[CSHA256::OUTPUT_SIZE];
    std::vector<uint8_t> in(BUFFER_SIZE, 0);
    while (state.KeepRunning())
        CSHA256().Write(in.data(), in.size()).Finalize(hash);
}

static void SHA256_32b(benchmark::State &state)
{
    std::vector<uint8_t> in(32, 0);
    while (state.KeepRunning())
    {
        for (int i = 0; i < 1000000; i++)
        {
            CSHA256().Write(in.data(), in.size()).Finalize(in.data());
        }
    }
}

static void SHA256D64_1024(benchmark::State &state)
{
    std::vector<uint8_t> in(64 * 1024, 0);
    while (state.KeepRunning())
    {
        SHA256D64(in.data(), in.data(), 1024);
    }
}

static void SHA512(benchmark::State &state)
{
    uint8_t hash[CSHA512::OUTPUT_SIZE];
    std::vector<uint8_t> in(BUFFER_SIZE, 0);
    while (state.KeepRunning())
        CSHA512().Write(in.data(), in.size()).Finalize(hash);
}

static void SipHash_32b(benchmark::State &state)
{
    uint256 x;
    while (state.KeepRunning())
    {
        for (int i = 0; i < 1000000; i++)
        {
            *((uint64_t *)x.begin()) = SipHashUint256(0, i, x);
        }
    }
}

static void FastRandom_32bit(benchmark::State &state)
{
    FastRandomContext rng(true);
    uint32_t x = 0;
    while (state.KeepRunning())
    {
        for (int i = 0; i < 1000000; i++)
        {
            x += rng.rand32();
        }
    }
}

static void FastRandom_1bit(benchmark::State &state)
{
    FastRandomContext rng(true);
    uint32_t x = 0;
    while (state.KeepRunning())
    {
        for (int i = 0; i < 1000000; i++)
        {
            x += rng.randbool();
        }
    }
}

BENCHMARK(RIPEMD160);
BENCHMARK(SHA1);
BENCHMARK(SHA256);
BENCHMARK(SHA512);

BENCHMARK(SHA256_32b);
BENCHMARK(SHA256D64_1024);
BENCHMARK(SipHash_32b);
BENCHMARK(FastRandom_32bit);
BENCHMARK(FastRandom_1bit);
<|endoftext|>


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

#include <bench/bench.h>
#include <policy/policy.h>
#include <rpc/blockchain.h>
#include <txmempool.h>

#include <univalue.h>

#include <list>
#include <vector>

static void AddTx(const CTransactionRef &tx, const CAmount &nFee, CTxMemPool &pool)
{
    int64_t nTime = 0;
    double dPriority = 10.0;
    unsigned int nHeight = 1;
    bool spendsCoinbase = false;
    unsigned int sigOpCost = 4;
    LockPoints lp;
    pool.addUnchecked(tx->GetHash(), CTxMemPoolEntry(tx, nFee, nTime, dPriority, nHeight, pool.HasNoInputsOf(tx),
                                         tx->GetValueOut(), spendsCoinbase, sigOpCost, lp));
}

static void RpcMempool(benchmark::State &state)
{
    CTxMemPool pool(CFeeRate(1000));

    for (int i = 0; i < 1000; ++i)
    {
        CMutableTransaction tx = CMutableTransaction();
        tx.vin.resize(1);
        tx.vin[0].scriptSig = CScript() << OP_1;
        tx.vout.resize(1);
        tx.vout[0].scriptPubKey = CScript() << OP_1 << OP_EQUAL;
        tx.vout[0].nValue = i * CENT;
        const CTransactionRef tx_r{MakeTransactionRef(tx)};
        AddTx(tx_r, /* fee */ i * CENT, pool);
    }

    while (state.KeepRunning())
    {
        (void)mempoolToJSON(true);
    }
}

BENCHMARK(RpcMempool, 40);
<commit_msg>This will come in handy in a short while for benchmarking new UniValue code changes/optimizations.<commit_after>// Copyright (c) 2011-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <bench/bench.h>
#include <policy/policy.h>
#include <rpc/blockchain.h>
#include <txmempool.h>

#include <univalue.h>

#include <list>
#include <vector>

static void AddTx(const CTransactionRef &tx, const CAmount &nFee, CTxMemPool &pool)
{
    int64_t nTime = 0;
    double dPriority = 10.0;
    unsigned int nHeight = 1;
    bool spendsCoinbase = false;
    unsigned int sigOpCost = 4;
    LockPoints lp;
    pool.addUnchecked(tx->GetHash(), CTxMemPoolEntry(tx, nFee, nTime, dPriority, nHeight, pool.HasNoInputsOf(tx),
                                         tx->GetValueOut(), spendsCoinbase, sigOpCost, lp));
}

static void RpcMempool(benchmark::State &state)
{
    CTxMemPool pool(CFeeRate(1000));

    for (int i = 0; i < 1000; ++i)
    {
        CMutableTransaction tx = CMutableTransaction();
        tx.vin.resize(1);
        tx.vin[0].scriptSig = CScript() << OP_1;
        tx.vout.resize(1);
        tx.vout[0].scriptPubKey = CScript() << OP_1 << OP_EQUAL;
        tx.vout[0].nValue = i * CENT;
        const CTransactionRef tx_r{MakeTransactionRef(tx)};
        AddTx(tx_r, /* fee */ i * CENT, pool);
    }

    while (state.KeepRunning())
    {
        (void)mempoolToJSON(true);
    }
}

static void RpcMempool10k(benchmark::State &state)
{
    CTxMemPool pool(CFeeRate(1000));

    const size_t nTx = 10000, nIns = 10, nOuts = 10;

    for (size_t i = 0; i < nTx; ++i)
    {
        CMutableTransaction tx = CMutableTransaction();
        tx.vin.resize(nIns);
        for (size_t j = 0; j < nIns; ++j)
        {
            tx.vin[j].scriptSig = CScript() << OP_1;
        }
        tx.vout.resize(nOuts);
        for (size_t j = 0; j < nOuts; ++j)
        {
            tx.vin[j].scriptSig = CScript() << OP_1;
            tx.vout[j].scriptPubKey = CScript() << OP_1 << OP_EQUAL;
            tx.vout[j].nValue = int64_t(i * j) * CENT;
        }
        const CTransactionRef tx_r{MakeTransactionRef(tx)};
        AddTx(tx_r, /* fee */ int64_t(i) * CENT, pool);
    }

    while (state.KeepRunning())
    {
        (void)mempoolToJSON(true);
    }
}

BENCHMARK(RpcMempool, 40);
BENCHMARK(RpcMempool10k, 10);
<|endoftext|>


<commit_before>#include <ncurses.h>
#include <iostream>
#include <unistd.h>

#include "display/Screen.h"
#include "display/Window.h"
#include "display/WindowManager.h"
#include "map/Level.h"
#include "map/filters/DrunkardsWalkFilter.h"
#include "actor/Actor.h"
#include "core/Rand.h"

void pause_curses(Screen& screen)
{
	screen.pause();

	std::cout << "Paused ncurses..." << std::endl;

	sleep(4);

	std::cout << "Resuming..." << std::endl;

	sleep(1);
}

int main()
{
	Screen screen;

	int screen_y = screen.getHeight();
	int screen_x = screen.getWidth();

	//Make a map double the screen size
	int map_y = screen_y * 2;
	int map_x = screen_x * 2;
	//Generate a map
	Level cave(map_x, map_y);
	DrunkardsWalkFilter walk;
	walk.setSeed(time(NULL));
	walk.apply(cave);
	//Find a random FloorTile to put our PC on
	int pc_x, pc_y;
	Actor pc('@', "PC", 0x01);
	Rand rand(time(NULL));
	do {
		pc_x = rand.randInt(0, cave.getWidth()-1);
		pc_y = rand.randInt(0, cave.getHeight()-1);
	} while(cave[pc_x][pc_y] != FloorTile);
	cave[pc_x][pc_y].addActor(&pc);
	//Now put the map into our map window...
	Window level_window(&cave);
	//...and create a viewport looking into it.
	Window map(&level_window, screen_x-20, screen_y-3, 20, 3);

	Window top(screen_x, 3, 0, 0);
	Window left(20, screen_y-2, 0, 2);

	top.addBorder();
	left.addBorder();
	//map.addBorder(); //Dare I try it?
	//Push our windows into our WindowManager
	WindowManager wm;
	wm.addWindow(&top);
	wm.addWindow(&left);
	wm.addWindow(&map);

	wm.getWindow(0)->add(1, 0, "Message Panel");
	wm.getWindow(1)->add(1, 0, "Stat Panel");

	//Center the map viewport on the PC
	map.center(pc_x, pc_y);

	//Let's display some map display stats
	//Display our view's X and Y coordinates
	wm.getWindow(1)->add(1, 2, "View Position:");
	wm.getWindow(1)->add(1, 3, "X:     ");
	wm.getWindow(1)->addInt(4, 3, map.getViewX());
	wm.getWindow(1)->add(1, 4, "Y:     ");
	wm.getWindow(1)->addInt(4, 4, map.getViewY());

	//Display map size
	wm.getWindow(1)->add(1, 6, "Map Size:");
	wm.getWindow(1)->add(1, 7, "W:");
	wm.getWindow(1)->addInt(4, 7, cave.getWidth());
	wm.getWindow(1)->add(1, 8, "H:");
	wm.getWindow(1)->addInt(4, 8, cave.getHeight());

	//Display viewport size
	wm.getWindow(1)->add(1, 9, "View Size:");
	wm.getWindow(1)->add(1, 10, "W:");
	wm.getWindow(1)->addInt(4, 10, map.getViewWidth());
	wm.getWindow(1)->add(1, 11, "H:");
	wm.getWindow(1)->addInt(4, 11, map.getViewHeight());

	//Display PC's location
	wm.getWindow(1)->add(1, 12, "PC Position:");
	wm.getWindow(1)->add(1, 13, "X:     ");
	wm.getWindow(1)->addInt(4, 13, pc_x);
	wm.getWindow(1)->add(1, 14, "Y:     ");
	wm.getWindow(1)->addInt(4, 14, pc_y);

	//Now display everything
	wm.refresh();

	//Now we enter the "game loop"
	int ch;
	int32_t dx, dy;
	bool run = true;
	while(run)
	{
		ch = getch();

		//Display the key code
		wm.getWindow(0)->add(8, 1, "     ");
		wm.getWindow(0)->addInt(8, 1, ch);

		dx = 0;
		dy = 0;

		wm.getWindow(0)->add(1, 1, "     ");
		switch(ch)
		{
			case KEY_UP:
				wm.getWindow(0)->add(1, 1, "Up");
				dy = -1;
				break;
			case KEY_DOWN:
				wm.getWindow(0)->add(1, 1, "Down");
				dy = 1;
				break;
			case KEY_LEFT:
				wm.getWindow(0)->add(1, 1, "Left");
				dx = -1;
				break;
			case KEY_RIGHT:
				wm.getWindow(0)->add(1, 1, "Right");
				dx = 1;
				break;
			case 'p':
			case 'P':
				pause_curses(screen);
				break;
			case 'q':
			case 'Q':
				run = false;
				break;
		}

		//Move the viewport
		map.moveBy(dx, dy);

		//Display our view's X and Y coordinates
		wm.getWindow(1)->add(1, 3, "X:     ");
		wm.getWindow(1)->addInt(4, 3, map.getViewX());
		wm.getWindow(1)->add(1, 4, "Y:     ");
		wm.getWindow(1)->addInt(4, 4, map.getViewY());

		//Refresh the display
		wm.refresh();
	}
}
<commit_msg>Player can now move the PC around on the screen.<commit_after>#include <ncurses.h>
#include <iostream>
#include <unistd.h>

#include "display/Screen.h"
#include "display/Window.h"
#include "display/WindowManager.h"
#include "map/Level.h"
#include "map/filters/DrunkardsWalkFilter.h"
#include "actor/Actor.h"
#include "core/Rand.h"

void pause_curses(Screen& screen)
{
	screen.pause();

	std::cout << "Paused ncurses..." << std::endl;

	sleep(4);

	std::cout << "Resuming..." << std::endl;

	sleep(1);
}

bool move_pc(Actor& pc, Level& level, int& pc_x, int& pc_y, int dx, int dy)
{
	int new_x = pc_x + dx;
	int new_y = pc_y + dy;

	//Make sure it's in bounds
	if(0 <= new_x && new_x < level.getWidth() && 0 <= new_y && new_y < level.getHeight())
	{
		//Make sure it's passable terrain
		if(level[new_x][new_y].getPassable())
		{
			//Remove the PC from its old position
			level[pc_x][pc_y].removeActor();

			//Adjust PC's x,y coordinates
			pc_x += dx;
			pc_y += dy;

			//Place the PC at the new x,y coordinates
			level[pc_x][pc_y].addActor(&pc);

			return true;
		}
	}
	return false;
}

int main()
{
	Screen screen;

	int screen_y = screen.getHeight();
	int screen_x = screen.getWidth();

	//Make a map double the screen size
	int map_y = screen_y * 2;
	int map_x = screen_x * 2;
	//Generate a map
	Level cave(map_x, map_y);
	DrunkardsWalkFilter walk;
	walk.setSeed(time(NULL));
	walk.apply(cave);
	//Find a random FloorTile to put our PC on
	int pc_x, pc_y;
	Actor pc('@', "PC", 0x01);
	Rand rand(time(NULL));
	do {
		pc_x = rand.randInt(0, cave.getWidth()-1);
		pc_y = rand.randInt(0, cave.getHeight()-1);
	} while(cave[pc_x][pc_y] != FloorTile);
	cave[pc_x][pc_y].addActor(&pc);
	//Now put the map into our map window...
	Window level_window(&cave);
	//...and create a viewport looking into it.
	Window map(&level_window, screen_x-20, screen_y-3, 20, 3);

	Window top(screen_x, 3, 0, 0);
	Window left(20, screen_y-2, 0, 2);

	top.addBorder();
	left.addBorder();
	//map.addBorder(); //Dare I try it?
	//Push our windows into our WindowManager
	WindowManager wm;
	wm.addWindow(&top);
	wm.addWindow(&left);
	wm.addWindow(&map);

	wm.getWindow(0)->add(1, 0, "Message Panel");
	wm.getWindow(1)->add(1, 0, "Stat Panel");

	//Center the map viewport on the PC
	map.center(pc_x, pc_y);

	//Let's display some map display stats
	//Display our view's X and Y coordinates
	wm.getWindow(1)->add(1, 2, "View Position:");
	wm.getWindow(1)->add(1, 3, "X:     ");
	wm.getWindow(1)->addInt(4, 3, map.getViewX());
	wm.getWindow(1)->add(1, 4, "Y:     ");
	wm.getWindow(1)->addInt(4, 4, map.getViewY());

	//Display map size
	wm.getWindow(1)->add(1, 6, "Map Size:");
	wm.getWindow(1)->add(1, 7, "W:");
	wm.getWindow(1)->addInt(4, 7, cave.getWidth());
	wm.getWindow(1)->add(1, 8, "H:");
	wm.getWindow(1)->addInt(4, 8, cave.getHeight());

	//Display viewport size
	wm.getWindow(1)->add(1, 9, "View Size:");
	wm.getWindow(1)->add(1, 10, "W:");
	wm.getWindow(1)->addInt(4, 10, map.getViewWidth());
	wm.getWindow(1)->add(1, 11, "H:");
	wm.getWindow(1)->addInt(4, 11, map.getViewHeight());

	//Display PC's location
	wm.getWindow(1)->add(1, 12, "PC Position:");
	wm.getWindow(1)->add(1, 13, "X:     ");
	wm.getWindow(1)->addInt(4, 13, pc_x);
	wm.getWindow(1)->add(1, 14, "Y:     ");
	wm.getWindow(1)->addInt(4, 14, pc_y);

	//Now display everything
	wm.refresh();

	//Now we enter the "game loop"
	int ch;
	int dx, dy;
	bool run = true;
	while(run)
	{
		ch = getch();

		//Display the key code
		wm.getWindow(0)->add(8, 1, "     ");
		wm.getWindow(0)->addInt(8, 1, ch);

		dx = 0;
		dy = 0;

		wm.getWindow(0)->add(1, 1, "     ");
		switch(ch)
		{
			case KEY_UP:
				wm.getWindow(0)->add(1, 1, "Up");
				dy = -1;
				break;
			case KEY_DOWN:
				wm.getWindow(0)->add(1, 1, "Down");
				dy = 1;
				break;
			case KEY_LEFT:
				wm.getWindow(0)->add(1, 1, "Left");
				dx = -1;
				break;
			case KEY_RIGHT:
				wm.getWindow(0)->add(1, 1, "Right");
				dx = 1;
				break;
			case '8':
				move_pc(pc, cave, pc_x, pc_y, 0, -1);
				break;
			case '2':
				move_pc(pc, cave, pc_x, pc_y, 0, 1);
				break;
			case '4':
				move_pc(pc, cave, pc_x, pc_y, -1, 0);
				break;
			case '6':
				move_pc(pc, cave, pc_x, pc_y, 1, 0);
				break;
			case 'c':
			case 'C':
				wm.getWindow(2)->center(pc_x, pc_y);
				break;
			case 'p':
			case 'P':
				pause_curses(screen);
				break;
			case 'q':
			case 'Q':
				run = false;
				break;
		}

		//Move the viewport
		map.moveBy(dx, dy);

		//Display our view's X and Y coordinates
		wm.getWindow(1)->add(1, 3, "X:     ");
		wm.getWindow(1)->addInt(4, 3, map.getViewX());
		wm.getWindow(1)->add(1, 4, "Y:     ");
		wm.getWindow(1)->addInt(4, 4, map.getViewY());

		//Re-display PC's position
		wm.getWindow(1)->add(1, 13, "X:     ");
		wm.getWindow(1)->addInt(4, 13, pc_x);
		wm.getWindow(1)->add(1, 14, "Y:     ");
		wm.getWindow(1)->addInt(4, 14, pc_y);

		//Refresh the display
		wm.refresh();
	}
}
<|endoftext|>


<commit_before>
#include "testing_utilities/almost_equals.hpp"

#include <sstream>

#include "geometry/grassmann.hpp"
#include "geometry/quaternion.hpp"
#include "glog/logging.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "numerics/unbounded_arrays.hpp"
#include "quantities/bipm.hpp"
#include "quantities/cgs.hpp"
#include "quantities/named_quantities.hpp"
#include "quantities/numbers.hpp"
#include "quantities/quantities.hpp"
#include "quantities/si.hpp"
#include "quantities/uk.hpp"

namespace principia {
namespace testing_utilities {

using geometry::Bivector;
using geometry::Quaternion;
using geometry::R3Element;
using geometry::R3x3Matrix;
using geometry::Vector;
using geometry::Trivector;
using numerics::UnboundedLowerTriangularMatrix;
using numerics::UnboundedUpperTriangularMatrix;
using numerics::UnboundedVector;
using quantities::Length;
using quantities::MagneticFlux;
using quantities::Speed;
using quantities::bipm::Knot;
using quantities::cgs::Maxwell;
using quantities::uk::Foot;
using testing::Ne;
using testing::Eq;
using testing::Not;
namespace si = quantities::si;

namespace {
struct World;
}  // namespace

class AlmostEqualsTest : public testing::Test {};

TEST_F(AlmostEqualsTest, Dimensionless) {
  double const y = e;
  EXPECT_THAT(y, AlmostEquals(e, 0));
  EXPECT_THAT(y, Not(AlmostEquals(e, 1)));
  EXPECT_THAT(2 * y, Not(AlmostEquals(y, 4)));
  double const δy = e / 100.0;
  double e_accumulated = 0.0;
  for (int i = 1; i <= 100.0; ++i) {
    e_accumulated += δy;
  }
  EXPECT_THAT(e_accumulated, Ne(e));
  EXPECT_THAT(e_accumulated, Not(AlmostEquals(e, 0)));
  EXPECT_THAT(e_accumulated, AlmostEquals(e, 1));
}

TEST_F(AlmostEqualsTest, Quantity) {
  Speed v1 = 1 * Knot;
  Speed const v2 = v1;
  EXPECT_THAT(v2, AlmostEquals(v1, 0));
  EXPECT_THAT(2 * v2, Not(AlmostEquals(v1, 4)));
  Speed const δv = v1 / 100.0;
  Speed v_accumulated;
  for (int i = 1; i <= 100.0; ++i) {
    v_accumulated += δv;
  }
  EXPECT_THAT(v_accumulated, Ne(v1));
  EXPECT_THAT(v_accumulated, AlmostEquals(v1, 4));
}

TEST_F(AlmostEqualsTest, R3Element) {
  R3Element<Speed> const v1 = {1 * Knot, 2 * Knot, 3 * Knot};
  R3Element<Speed> const v2 = v1;
  EXPECT_THAT(v2, AlmostEquals(v1, 0));
  EXPECT_THAT(2 * v2, Not(AlmostEquals(v1, 4)));
  R3Element<Speed> const δv = v1 / 100;
  R3Element<Speed> v_accumulated;
  for (int i = 1; i <= 100; ++i) {
    v_accumulated += δv;
  }
  EXPECT_THAT(v_accumulated, Ne(v1));
  EXPECT_THAT(v_accumulated, AlmostEquals(v1, 8));
}

TEST_F(AlmostEqualsTest, R3x3Matrix) {
  R3x3Matrix<Speed> const m1({1 * Knot, 2 * Knot, 3 * Knot},
                             {4 * Knot, -5 * Knot, 7 * Knot},
                             {10 * Knot, 2 * Knot, -30 * Knot});
  R3x3Matrix<Speed> const m2 = m1;
  EXPECT_THAT(m2, AlmostEquals(m1, 0));
  EXPECT_THAT(2 * m2, Not(AlmostEquals(m1, 4)));
  R3x3Matrix<Speed> const δm = m1 / 100;
  R3x3Matrix<Speed> m_accumulated;
  for (int i = 1; i <= 100; ++i) {
    m_accumulated += δm;
  }
  EXPECT_THAT(m_accumulated, Ne(m1));
  EXPECT_THAT(m_accumulated, AlmostEquals(m1, 16));
}

TEST_F(AlmostEqualsTest, Quaternion) {
  Quaternion const q1 = {1, {2, 3, 4}};
  Quaternion const q2 = q1;
  EXPECT_THAT(q2, AlmostEquals(q1, 0));
  EXPECT_THAT(2 * q2, Not(AlmostEquals(q1, 4)));
  Quaternion const δq = q1 / 100;
  Quaternion q_accumulated;
  for (int i = 1; i <= 100; ++i) {
    q_accumulated += δq;
  }
  EXPECT_THAT(q_accumulated, Ne(q1));
  EXPECT_THAT(q_accumulated, AlmostEquals(q1, 11));
}

TEST_F(AlmostEqualsTest, Vector) {
  Vector<Length, World> const v1({1 * Foot, 2 * Foot, 3 * Foot});
  Vector<Length, World> const v2 = v1;
  EXPECT_THAT(v2, AlmostEquals(v1, 0));
  EXPECT_THAT(2 * v2, Not(AlmostEquals(v1, 4)));
  Vector<Length, World> const δv = v1 / 100;
  Vector<Length, World> v_accumulated;
  for (int i = 1; i <= 100; ++i) {
    v_accumulated += δv;
  }
  EXPECT_THAT(v_accumulated, Ne(v1));
  EXPECT_THAT(v_accumulated, AlmostEquals(v1, 14));
}

TEST_F(AlmostEqualsTest, Bivector) {
  Bivector<double, World> const v1({4, -5, 6});
  Bivector<double, World> const v2 = v1;
  EXPECT_THAT(v2, AlmostEquals(v1, 0));
  EXPECT_THAT(2 * v2, Not(AlmostEquals(v1, 4)));
  Bivector<double, World> const δv = v1 / 100;
  Bivector<double, World> v_accumulated;
  for (int i = 1; i <= 100; ++i) {
    v_accumulated += δv;
  }
  EXPECT_THAT(v_accumulated, Ne(v1));
  EXPECT_THAT(v_accumulated, AlmostEquals(v1, 11));
}

TEST_F(AlmostEqualsTest, Trivector) {
  Trivector<MagneticFlux, World> const v1(2 * Maxwell);
  Trivector<MagneticFlux, World> const v2 = v1;
  EXPECT_THAT(v2, AlmostEquals(v1, 0));
  EXPECT_THAT(2 * v2, Not(AlmostEquals(v1, 4)));
  Trivector<MagneticFlux, World> const δv = v1 / 100;
  Trivector<MagneticFlux, World> v_accumulated;
  for (int i = 1; i <= 100; ++i) {
    v_accumulated += δv;
  }
  EXPECT_THAT(v_accumulated, Ne(v1));
  EXPECT_THAT(v_accumulated, AlmostEquals(v1, 9));
}

TEST_F(AlmostEqualsTest, UnboundedVector) {
  UnboundedVector<double> const v1({1, 2, 3});
  UnboundedVector<double> const v2 = v1;
  EXPECT_THAT(v2, AlmostEquals(v1, 0));
  EXPECT_THAT(v2, Not(AlmostEquals(v1, 4)));
  double const δv = v1[1] / 100;
  UnboundedVector<double> v_accumulated({1, 0, 3});
  for (int i = 1; i <= 100; ++i) {
    v_accumulated[1] += δv;
  }
  EXPECT_THAT(v_accumulated, Ne(v1));
  EXPECT_THAT(v_accumulated, AlmostEquals(v1, 3));
}

TEST_F(AlmostEqualsTest, UnboundedLowerTriangularMatrix) {
  UnboundedLowerTriangularMatrix<double> const m1({1,
                                                   2, 3,
                                                   4, 5, 6});
  UnboundedLowerTriangularMatrix<double> const m2 = m1;
  EXPECT_THAT(m2, AlmostEquals(m1, 0));
  EXPECT_THAT(m2, Not(AlmostEquals(m1, 4)));
  double const δv = m1[1][0] / 100;
  UnboundedLowerTriangularMatrix<double> m_accumulated({1,
                                                        0, 3,
                                                        4, 5, 6});
  for (int i = 1; i <= 100; ++i) {
    m_accumulated[1][0] += δv;
  }
  EXPECT_THAT(m_accumulated, Ne(m1));
  EXPECT_THAT(m_accumulated, AlmostEquals(m1, 3));
}

TEST_F(AlmostEqualsTest, UnboundedUpperTriangularMatrix) {
  UnboundedUpperTriangularMatrix<double> const m1({1, 2, 3,
                                                      4, 5,
                                                         6});
  UnboundedUpperTriangularMatrix<double> const m2 = m1;
  EXPECT_THAT(m2, AlmostEquals(m1, 0));
  EXPECT_THAT(m2, Not(AlmostEquals(m1, 4)));
  double const δv = m1[0][1] / 100;
  UnboundedUpperTriangularMatrix<double> m_accumulated({1, 0, 3,
                                                           4, 5,
                                                              6});
  for (int i = 1; i <= 100; ++i) {
    m_accumulated[0][1] += δv;
  }
  EXPECT_THAT(m_accumulated, Ne(m1));
  EXPECT_THAT(m_accumulated, AlmostEquals(m1, 3));
}

TEST_F(AlmostEqualsTest, Describe) {
  Speed v1 = 1 * si::Unit<Speed>;
  {
    std::ostringstream out;
    AlmostEquals(v1, 2, 6).impl().DescribeTo(&out);
    EXPECT_EQ("is within 2 to 6 ULPs of +1.00000000000000000e+00 m s^-1",
              out.str());
  }
  {
    std::ostringstream out;
    AlmostEquals(v1, 2, 6).impl().DescribeNegationTo(&out);
    EXPECT_EQ("is not within 2 to 6 ULPs of +1.00000000000000000e+00 m s^-1",
              out.str());
  }
}

}  // namespace testing_utilities
}  // namespace principia
<commit_msg>Fix errors found by Clang.<commit_after>
#include "testing_utilities/almost_equals.hpp"

#include <sstream>

#include "geometry/grassmann.hpp"
#include "geometry/quaternion.hpp"
#include "glog/logging.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "numerics/unbounded_arrays.hpp"
#include "quantities/bipm.hpp"
#include "quantities/cgs.hpp"
#include "quantities/named_quantities.hpp"
#include "quantities/numbers.hpp"
#include "quantities/quantities.hpp"
#include "quantities/si.hpp"
#include "quantities/uk.hpp"

namespace principia {
namespace testing_utilities {

using geometry::Bivector;
using geometry::Quaternion;
using geometry::R3Element;
using geometry::R3x3Matrix;
using geometry::Vector;
using geometry::Trivector;
using numerics::UnboundedLowerTriangularMatrix;
using numerics::UnboundedUpperTriangularMatrix;
using numerics::UnboundedVector;
using quantities::Length;
using quantities::MagneticFlux;
using quantities::Speed;
using quantities::bipm::Knot;
using quantities::cgs::Maxwell;
using quantities::uk::Foot;
using testing::Ne;
using testing::Eq;
using testing::Not;
namespace si = quantities::si;

namespace {
struct World;
}  // namespace

class AlmostEqualsTest : public testing::Test {};

TEST_F(AlmostEqualsTest, Dimensionless) {
  double const y = e;
  EXPECT_THAT(y, AlmostEquals(e, 0));
  EXPECT_THAT(y, Not(AlmostEquals(e, 1)));
  EXPECT_THAT(2 * y, Not(AlmostEquals(y, 4)));
  double const δy = e / 100.0;
  double e_accumulated = 0.0;
  for (int i = 1; i <= 100.0; ++i) {
    e_accumulated += δy;
  }
  EXPECT_THAT(e_accumulated, Ne(e));
  EXPECT_THAT(e_accumulated, Not(AlmostEquals(e, 0)));
  EXPECT_THAT(e_accumulated, AlmostEquals(e, 1));
}

TEST_F(AlmostEqualsTest, Quantity) {
  Speed v1 = 1 * Knot;
  Speed const v2 = v1;
  EXPECT_THAT(v2, AlmostEquals(v1, 0));
  EXPECT_THAT(2 * v2, Not(AlmostEquals(v1, 4)));
  Speed const δv = v1 / 100.0;
  Speed v_accumulated;
  for (int i = 1; i <= 100.0; ++i) {
    v_accumulated += δv;
  }
  EXPECT_THAT(v_accumulated, Ne(v1));
  EXPECT_THAT(v_accumulated, AlmostEquals(v1, 4));
}

TEST_F(AlmostEqualsTest, R3Element) {
  R3Element<Speed> const v1 = {1 * Knot, 2 * Knot, 3 * Knot};
  R3Element<Speed> const v2 = v1;
  EXPECT_THAT(v2, AlmostEquals(v1, 0));
  EXPECT_THAT(2 * v2, Not(AlmostEquals(v1, 4)));
  R3Element<Speed> const δv = v1 / 100;
  R3Element<Speed> v_accumulated;
  for (int i = 1; i <= 100; ++i) {
    v_accumulated += δv;
  }
  EXPECT_THAT(v_accumulated, Ne(v1));
  EXPECT_THAT(v_accumulated, AlmostEquals(v1, 8));
}

TEST_F(AlmostEqualsTest, R3x3Matrix) {
  R3x3Matrix<Speed> const m1({1 * Knot, 2 * Knot, 3 * Knot},
                             {4 * Knot, -5 * Knot, 7 * Knot},
                             {10 * Knot, 2 * Knot, -30 * Knot});
  R3x3Matrix<Speed> const m2 = m1;
  EXPECT_THAT(m2, AlmostEquals(m1, 0));
  EXPECT_THAT(2 * m2, Not(AlmostEquals(m1, 4)));
  R3x3Matrix<Speed> const δm = m1 / 100;
  R3x3Matrix<Speed> m_accumulated;
  for (int i = 1; i <= 100; ++i) {
    m_accumulated += δm;
  }
  EXPECT_THAT(m_accumulated, Ne(m1));
  EXPECT_THAT(m_accumulated, AlmostEquals(m1, 16));
}

TEST_F(AlmostEqualsTest, Quaternion) {
  Quaternion const q1 = {1, {2, 3, 4}};
  Quaternion const q2 = q1;
  EXPECT_THAT(q2, AlmostEquals(q1, 0));
  EXPECT_THAT(2 * q2, Not(AlmostEquals(q1, 4)));
  Quaternion const δq = q1 / 100;
  Quaternion q_accumulated;
  for (int i = 1; i <= 100; ++i) {
    q_accumulated += δq;
  }
  EXPECT_THAT(q_accumulated, Ne(q1));
  EXPECT_THAT(q_accumulated, AlmostEquals(q1, 11));
}

TEST_F(AlmostEqualsTest, Vector) {
  Vector<Length, World> const v1({1 * Foot, 2 * Foot, 3 * Foot});
  Vector<Length, World> const v2 = v1;
  EXPECT_THAT(v2, AlmostEquals(v1, 0));
  EXPECT_THAT(2 * v2, Not(AlmostEquals(v1, 4)));
  Vector<Length, World> const δv = v1 / 100;
  Vector<Length, World> v_accumulated;
  for (int i = 1; i <= 100; ++i) {
    v_accumulated += δv;
  }
  EXPECT_THAT(v_accumulated, Ne(v1));
  EXPECT_THAT(v_accumulated, AlmostEquals(v1, 14));
}

TEST_F(AlmostEqualsTest, Bivector) {
  Bivector<double, World> const v1({4, -5, 6});
  Bivector<double, World> const v2 = v1;
  EXPECT_THAT(v2, AlmostEquals(v1, 0));
  EXPECT_THAT(2 * v2, Not(AlmostEquals(v1, 4)));
  Bivector<double, World> const δv = v1 / 100;
  Bivector<double, World> v_accumulated;
  for (int i = 1; i <= 100; ++i) {
    v_accumulated += δv;
  }
  EXPECT_THAT(v_accumulated, Ne(v1));
  EXPECT_THAT(v_accumulated, AlmostEquals(v1, 11));
}

TEST_F(AlmostEqualsTest, Trivector) {
  Trivector<MagneticFlux, World> const v1(2 * Maxwell);
  Trivector<MagneticFlux, World> const v2 = v1;
  EXPECT_THAT(v2, AlmostEquals(v1, 0));
  EXPECT_THAT(2 * v2, Not(AlmostEquals(v1, 4)));
  Trivector<MagneticFlux, World> const δv = v1 / 100;
  Trivector<MagneticFlux, World> v_accumulated;
  for (int i = 1; i <= 100; ++i) {
    v_accumulated += δv;
  }
  EXPECT_THAT(v_accumulated, Ne(v1));
  EXPECT_THAT(v_accumulated, AlmostEquals(v1, 9));
}

TEST_F(AlmostEqualsTest, UnboundedVector) {
  UnboundedVector<double> const v1({1, 2, 3});
  UnboundedVector<double> const v2 = v1;
  EXPECT_THAT(v2, AlmostEquals(v1, 0));
  EXPECT_THAT(v2, Not(AlmostEquals(v1, 4)));
  double const δv = v1[1] / 100;
  UnboundedVector<double> v_accumulated({1, 0, 3});
  for (int i = 1; i <= 100; ++i) {
    v_accumulated[1] += δv;
  }
  EXPECT_THAT(v_accumulated, AlmostEquals(v1, 3));
}

TEST_F(AlmostEqualsTest, UnboundedLowerTriangularMatrix) {
  UnboundedLowerTriangularMatrix<double> const m1({1,
                                                   2, 3,
                                                   4, 5, 6});
  UnboundedLowerTriangularMatrix<double> const m2 = m1;
  EXPECT_THAT(m2, AlmostEquals(m1, 0));
  EXPECT_THAT(m2, Not(AlmostEquals(m1, 4)));
  double const δv = m1[1][0] / 100;
  UnboundedLowerTriangularMatrix<double> m_accumulated({1,
                                                        0, 3,
                                                        4, 5, 6});
  for (int i = 1; i <= 100; ++i) {
    m_accumulated[1][0] += δv;
  }
  EXPECT_THAT(m_accumulated, AlmostEquals(m1, 3));
}

TEST_F(AlmostEqualsTest, UnboundedUpperTriangularMatrix) {
  UnboundedUpperTriangularMatrix<double> const m1({1, 2, 3,
                                                      4, 5,
                                                         6});
  UnboundedUpperTriangularMatrix<double> const m2 = m1;
  EXPECT_THAT(m2, AlmostEquals(m1, 0));
  EXPECT_THAT(m2, Not(AlmostEquals(m1, 4)));
  double const δv = m1[0][1] / 100;
  UnboundedUpperTriangularMatrix<double> m_accumulated({1, 0, 3,
                                                           4, 5,
                                                              6});
  for (int i = 1; i <= 100; ++i) {
    m_accumulated[0][1] += δv;
  }
  EXPECT_THAT(m_accumulated, AlmostEquals(m1, 3));
}

TEST_F(AlmostEqualsTest, Describe) {
  Speed v1 = 1 * si::Unit<Speed>;
  {
    std::ostringstream out;
    AlmostEquals(v1, 2, 6).impl().DescribeTo(&out);
    EXPECT_EQ("is within 2 to 6 ULPs of +1.00000000000000000e+00 m s^-1",
              out.str());
  }
  {
    std::ostringstream out;
    AlmostEquals(v1, 2, 6).impl().DescribeNegationTo(&out);
    EXPECT_EQ("is not within 2 to 6 ULPs of +1.00000000000000000e+00 m s^-1",
              out.str());
  }
}

}  // namespace testing_utilities
}  // namespace principia
<|endoftext|>