#include "includes/SWidgets/SSearchArea.hpp"
#include "includes/SMainWindow.hpp"

SSearchArea::SSearchArea(const QIcon & icon, SMainWindow * parent) :
	QLineEdit(parent),
	m_parent(parent),
	m_icon(icon)
{
	setTextMargins(18, 0, 0, 0);
	connect(this, &SSearchArea::returnPressed, this, &SSearchArea::loadSearch);
}

void SSearchArea::paintEvent(QPaintEvent * event)
{
	QLineEdit::paintEvent(event);
	QPainter painter(this);
	m_icon.paint(&painter, (height() - 16) / 2, (height() - 16) / 2, 16, 16);
}

void SSearchArea::loadSearch()
{
	QString search{ text() };
	search.replace(" ", "+");
	m_parent->currentPage()->load(QUrl("http://www.google.com/search?q=" + search));
}

#include "includes/SWidgets/SSearchArea.hpp"
#include "includes/SMainWindow.hpp"

SSearchArea::SSearchArea(const QIcon & icon, SMainWindow * parent) :
	QLineEdit(parent),
	m_parent(parent),
	m_icon(icon)
{
	setTextMargins(18, 0, 0, 0);
    connect(this, &SSearchArea::returnPressed, this, &SSearchArea::loadSearch);
    setClearButtonEnabled(true);
}

void SSearchArea::paintEvent(QPaintEvent * event)
{
	QLineEdit::paintEvent(event);
	QPainter painter(this);
	m_icon.paint(&painter, (height() - 16) / 2, (height() - 16) / 2, 16, 16);
}

void SSearchArea::loadSearch()
{
	QString search{ text() };
	search.replace(" ", "+");
	m_parent->currentPage()->load(QUrl("http://www.google.com/search?q=" + search));
}

Add clear button on search area

Add clear button on search area


// RUN: %clangxx -O2 %s -o %t && %run %t 2>&1 | FileCheck %s

// XFAIL: android

#include <stdio.h>

// getauxval() used instead of sysconf() in GetPageSize() is defined starting
// glbc version 2.16.
#if defined(__GLIBC_PREREQ) && __GLIBC_PREREQ(2, 16)
extern "C" long sysconf(int name) {
  fprintf(stderr, "sysconf wrapper called\n");
  return 0;
}
#endif  // defined(__GLIBC_PREREQ) && __GLIBC_PREREQ(2, 16)

int main() {
  // All we need to check is that the sysconf() interceptor defined above was
  // not called. Should it get called, it will crash right there, any
  // instrumented code executed before sanitizer init is finished will crash
  // accessing non-initialized sanitizer internals. Even if it will not crash
  // in some configuration, it should never be called anyway.
  fprintf(stderr, "Passed\n");
  // CHECK-NOT: sysconf wrapper called
  // CHECK: Passed
  // CHECK-NOT: sysconf wrapper called
  return 0;
}

// RUN: %clangxx -O2 %s -o %t && %run %t 2>&1 | FileCheck %s

#include <stdio.h>

#if !defined(__GLIBC_PREREQ)
#define __GLIBC_PREREQ(a, b) 0
#endif

// getauxval() used instead of sysconf() in GetPageSize() is defined starting
// glbc version 2.16.
#if __GLIBC_PREREQ(2, 16)
extern "C" long sysconf(int name) {
  fprintf(stderr, "sysconf wrapper called\n");
  return 0;
}
#endif  // defined(__GLIBC_PREREQ) && __GLIBC_PREREQ(2, 16)

int main() {
  // All we need to check is that the sysconf() interceptor defined above was
  // not called. Should it get called, it will crash right there, any
  // instrumented code executed before sanitizer init is finished will crash
  // accessing non-initialized sanitizer internals. Even if it will not crash
  // in some configuration, it should never be called anyway.
  fprintf(stderr, "Passed\n");
  // CHECK-NOT: sysconf wrapper called
  // CHECK: Passed
  // CHECK-NOT: sysconf wrapper called
  return 0;
}

Fix one more test on Android.

[asan] Fix one more test on Android.

This change makes it pass both on libstdc++ and libc++-based toolchains.

The error was:
error: function-like macro '__GLIBC_PREREQ' is not defined
                               ^

git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@335936 91177308-0d34-0410-b5e6-96231b3b80d8


// xml_writer.cc            see license.txt for copyright and terms of use

#include "xml_writer.h"
#include "xmlhelp.h"            // xmlAttrDeQuote() etc.
#include "exc.h"                // xBase

bool sortNameMapDomainWhenSerializing = true;

XmlWriter::XmlWriter(IdentityManager &idmgr0, ostream *out0, int &depth0, bool indent0)
  : idmgr(idmgr0)
  , out(out0)
  , depth(depth0)
  , indent(indent0)
{}

// write N spaces to OUT.
inline void writeSpaces(ostream &out, size_t n)
{
  static char const spaces[] =
    "                                                  "
    "                                                  "
    "                                                  "
    "                                                  ";

  static size_t const max_spaces = sizeof spaces - 1;

  // If we're printing more than this many spaces it's pretty useless anyway,
  // since it's only for human viewing pleasure!
  while (n > max_spaces) {
    out.write(spaces, max_spaces);
    n -= max_spaces;
  }
  out.write(spaces, n);
}

void XmlWriter::newline() {
  assert(out != NULL);
  *out << '\n';
  // FIX: turning off indentation makes the output go way faster, so
  // this loop is worth optimizing, probably by printing chunks of 10
  // if you can or something logarithmic like that.
  if (indent) {
    writeSpaces(*out, depth);
  }
}

// xml_writer.cc            see license.txt for copyright and terms of use

#include "xml_writer.h"
#include "xmlhelp.h"            // xmlAttrDeQuote() etc.
#include "exc.h"                // xBase

bool sortNameMapDomainWhenSerializing = true;

XmlWriter::XmlWriter(IdentityManager &idmgr0, ostream *out0, int &depth0, bool indent0)
  : idmgr(idmgr0)
  , out(out0)
  , depth(depth0)
  , indent(indent0)
{}

// write N spaces to OUT.
inline void writeSpaces(ostream &out, size_t n)
{
  static char const spaces[] =
    "                                                  "
    "                                                  "
    "                                                  "
    "                                                  ";

  static size_t const max_spaces = sizeof spaces - 1;

  // If we're printing more than this many spaces it's pretty useless anyway,
  // since it's only for human viewing pleasure!
  while (n > max_spaces) {
    out.write(spaces, max_spaces);
    n -= max_spaces;
  }
  out.write(spaces, n);
}

void XmlWriter::newline() {
  xassert(out != NULL);
  *out << '\n';
  // FIX: turning off indentation makes the output go way faster, so
  // this loop is worth optimizing, probably by printing chunks of 10
  // if you can or something logarithmic like that.
  if (indent) {
    writeSpaces(*out, depth);
  }
}

Use xassert instead of assert

Use xassert instead of assert


#define BOOST_TEST_MODULE Utility_function_tests
#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_CASE( fieldListFromString_tests )
{

}

#define BOOST_TEST_MODULE Utility_function_tests
#include <boost/test/unit_test.hpp>

#include "easyprint"

template <typename T, typename DELIMITER>
std::string easyprint_test(T&& container, DELIMITER d ){
    std::stringstream ss;
    print_line(ss, std::forward<T>(container), d);
    return ss.str();
};

BOOST_AUTO_TEST_CASE( Print_Empty_container )
{
    default_delimiter d;
    BOOST_CHECK( easyprint_test(std::vector<int>({}), d) == "[]\n" );

    std::cout << easyprint_test(std::vector<int>({}), d) << std::endl;
}

Add first test, trigger Travis CI

Add first test, trigger Travis CI


#include <dlib/image_loader/png_loader.cpp>
#include <dlib/image_saver/save_png.cpp>

#include <dlib/image_loader/jpeg_loader.cpp>
#include <dlib/image_saver/save_jpeg.cpp>

#include <dlib/image_loader/jpeg_loader.cpp>
#include <dlib/image_saver/save_jpeg.cpp>

#include <dlib/image_loader/png_loader.cpp>
#include <dlib/image_saver/save_png.cpp>

Revert "Exchange the order to load jpeg and png"

This reverts commit a3d40600c6b609c6374a26135d4d3db3632e1e4f.


#include "UnitTest++/UnitTest++.h"

#include "StrongAI/AI/DarwinAI/DarwinAI.hpp"

class MyDarwinAI : public DarwinAI
{
    public:
        MyDarwinAI() :
            DarwinAI( 0, 1, 0, 1 )
        {
        }

        //Select for highest output
        float fitnessEval( NeuralNetAI& ai )
        {
            return ai.output().at( 0 );
        };
};

SUITE( DarwinAITest )
{
    TEST( smokeTest )
    {
        std::unique_ptr< DarwinAI > ai( new MyDarwinAI() );

        auto output = ai->output();
        CHECK_EQUAL( 1, output.size() );

        ai->learn( 1 );
    }
}

#include "UnitTest++/UnitTest++.h"

#include "StrongAI/AI/DarwinAI/DarwinAI.hpp"

class MyDarwinAI : public DarwinAI
{
    public:
        MyDarwinAI() :
            DarwinAI( 0, 1, 0, 1 )
        {
        }

        //Select for highest output
        float fitnessEval( NeuralNetAI& ai )
        {
            return ai.output().at( 0 );
        };

    private:
        friend cereal::access;
        template < class Archive >
        void serialize( Archive & ar )
        {
            ar( cereal::virtual_base_class< GeneralAI >( this ) );
        }
};

SUITE( DarwinAITest )
{
    TEST( smokeTest )
    {
        std::unique_ptr< DarwinAI > ai( new MyDarwinAI() );

        auto output = ai->output();
        CHECK_EQUAL( 1, output.size() );

        ai->learn( 1 );
    }

    TEST( saveAndLoad )
    {
        const std::string saveFileName = "MyDarwinAI.save";

        MyDarwinAI originalAI;
        MyDarwinAI cloneAI;

        GeneralAI::save< MyDarwinAI >( originalAI, saveFileName );
        GeneralAI::load< MyDarwinAI >( cloneAI,    saveFileName );

        const auto originalOutput = originalAI.output().front();
        const auto cloneOutput    = cloneAI.output().front();
        const double tolerance    = 0.01;
        CHECK_CLOSE( originalOutput, cloneOutput, tolerance );

        // Delete save file
        CHECK( !remove( saveFileName.data() ) ) ;
    }
}

Test DarwinAI save and load

Test DarwinAI save and load


// RUN: %clang_cc1 -x c++ -emit-llvm < %s | FileCheck %s

struct A { A(int); ~A(); };
int f(const A &);
// CHECK: call void @_ZN1AC1Ei
// CHECK-NEXT: call i32 @_Z1fRK1A
// CHECK-NEXT: call void @_ZN1AD1Ev
// CHECK: call void @_ZN1AC1Ei
// CHECK-NEXT: call i32 @_Z1fRK1A
// CHECK-NEXT: call void @_ZN1AD1Ev
template<typename T> void g() {
  int a[f(3)];
  int b[f(3)];
}
int main() { g<int>(); }

// RUN: %clang_cc1 -x c++ -triple x86_64-pc-linux-gnu -emit-llvm < %s | FileCheck %s

struct A { A(int); ~A(); };
int f(const A &);
// CHECK: call void @_ZN1AC1Ei
// CHECK-NEXT: call i32 @_Z1fRK1A
// CHECK-NEXT: call void @_ZN1AD1Ev
// CHECK: call void @_ZN1AC1Ei
// CHECK-NEXT: call i32 @_Z1fRK1A
// CHECK-NEXT: call void @_ZN1AD1Ev
template<typename T> void g() {
  int a[f(3)];
  int b[f(3)];
}
int main() { g<int>(); }

[VLA] Fix the test failure on msvc by specifying the triple.

Differential Revision: https://reviews.llvm.org/D24333

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@295127 91177308-0d34-0410-b5e6-96231b3b80d8


#include "U8Gettext.h"
#include <Arduino.h>

#define ENSURE(condition) do { if (!(condition)) {Serial.println("ENSURE failed at: "#condition); while(1); } } while(0)
#define SIZE_OF_ARRAY(array) (sizeof((array))/sizeof((array)[0]))
#define PTR_OFFSET_BYTES(ptr, nBytes) ((void*)(((char *)(ptr)) + (nBytes)))
#define PTR_OFFSET_BETWEEN(ptrBegin, ptrEnd) ((char*)(ptrEnd) - (char*)(ptrBegin))

extern const size_t gU8GettextLanguagesLength;
extern const U8GettextLanguage gU8GettextLanguages[];

static const char *
sU8GettextLanguage = "en_US";

const char *U8GettextSetLanguage(const char *language)
{
  const char * oldLanguage = sU8GettextLanguage;

  sU8GettextLanguage = language;
  return oldLanguage;
}

const char *U8GettextGetLanguage()
{
  return sU8GettextLanguage;
}

const char *U8Gettext(const char *str)
{
  // TODO Implementation
}

#include "U8Gettext.h"
#include <Arduino.h>

#define ENSURE(condition) do { if (!(condition)) {Serial.println("ENSURE failed at: "#condition); while(1); } } while(0)
#define SIZE_OF_ARRAY(array) (sizeof((array))/sizeof((array)[0]))
#define PTR_OFFSET_BYTES(ptr, nBytes) ((void*)(((char *)(ptr)) + (nBytes)))
#define PTR_OFFSET_BETWEEN(ptrBegin, ptrEnd) ((char*)(ptrEnd) - (char*)(ptrBegin))

extern const size_t gU8GettextLanguagesLength;
extern const U8GettextLanguage gU8GettextLanguages[];

static const char *
sU8GettextLanguage = "en_US";

static const U8GettextLanguage *
sLanguageInstance = NULL;

const char *U8GettextSetLanguage(const char *language)
{
  const char * oldLanguage = sU8GettextLanguage;

  sU8GettextLanguage = language;
  return oldLanguage;
}

const char *U8GettextGetLanguage()
{
  return sU8GettextLanguage;
}

const char *U8Gettext(const char *str)
{
  // TODO Implementation
  if (!sLanguageInstance) {
    return str;
  }
}

Return original string if current language instance is NULL


#include "game.h"

#include "button.h"
#include "screen.h"
#include "led.h"
#include "timer.h"
#include "const.h"
#include "logger.h"
#include "helper.h"
#include "controller.h"

namespace game {
  namespace {
    unsigned long startTime;
    const unsigned long GAME_TIME = 3000;
    unsigned int buttonsPressed = 0;

    void countDown() {
      screen::display("3");
      helper::waitTime(1000);
      screen::display("2");
      helper::waitTime(1000);
      screen::display("1");
      helper::waitTime(1000);
    }

    void runMain() {
      while (millis() - startTime < GAME_TIME) {

        //Generate random button
        int buttonNumber = random(0, constants::NUMBER_OF_LEDS - 1);

        //Turn on led and wait for button press
        led::turnOn(buttonNumber);

        while(not button::isPressed(buttonNumber)){
          controller::run();
        }

        led::turnOff(buttonNumber);

        //Increment counter
        buttonsPressed ++;
      }
    }
  }

  unsigned long getRemainingTime() {
    unsigned long remainingTime = GAME_TIME - (millis() - startTime);

    if (remainingTime > 0) {
      return remainingTime;
    }

    return 0;
  }

  void start() {
    countDown();

    startTime = millis();

    timer::start();
    runMain();
    timer::stop();

    screen::display(String(buttonsPressed) + " buttons pressed");
  }
}

#include "game.h"

#include "button.h"
#include "screen.h"
#include "led.h"
#include "timer.h"
#include "const.h"
#include "logger.h"
#include "helper.h"
#include "controller.h"

namespace game {
  namespace {
    const unsigned long GAME_TIME = 3000;

    unsigned long endTime;

    unsigned int buttonsPressed = 0;

    void countDown() {
      screen::display("3");
      helper::waitTime(1000);
      screen::display("2");
      helper::waitTime(1000);
      screen::display("1");
      helper::waitTime(1000);
    }

    void runMain() {
      while (millis() < endTime) {

        //Generate random button
        int buttonNumber = random(0, constants::NUMBER_OF_LEDS - 1);

        //Turn on led and wait for button press
        led::turnOn(buttonNumber);

        while(not button::isPressed(buttonNumber)){
          controller::run();
        }

        led::turnOff(buttonNumber);

        //Increment counter
        buttonsPressed ++;
      }
    }
  }

  unsigned long getRemainingTime() {
    unsigned long remainingTime = endTime - millis();

    if (remainingTime > 0) {
      return remainingTime;
    }

    return 0;
  }

  void start() {
    countDown();

    endTime = GAME_TIME + millis();

    timer::start();
    runMain();
    timer::stop();

    screen::display(String(buttonsPressed) + " buttons pressed");
  }
}

Replace start time with end time

Replace start time with end time


/**
 * @file example.cpp
 * @author Marcus Edel
 *
 * Simple random agent.
 */

#include <iostream>

#include "environment.hpp"

using namespace gym;

int main(int argc, char* argv[])
{
  const std::string environment = "CartPole-v0";
  const std::string host = "kurg.org";
  const std::string port = "4040";

  double totalReward = 0;
  size_t totalSteps = 0;

  Environment env(host, port, environment);
  env.compression(9);
  env.monitor.start("./dummy/", true, true);

  env.reset();
  env.render();

  while (1)
  {
    arma::mat action = env.action_space.sample();
    std::cout << "action: \n" << action << std::endl;

    env.step(action);

    totalReward += env.reward;
    totalSteps += 1;

    if (env.done)
    {
      break;
    }

    std::cout << "Current step: " << totalSteps << " current reward: "
      << totalReward << std::endl;
  }

  std::cout << "Instance: " << env.instance << " total steps: " << totalSteps
      << " reward: " << totalReward << std::endl;

  return 0;
}

/**
 * @file example.cpp
 * @author Marcus Edel
 *
 * Simple random agent.
 */

#include <iostream>

#include "environment.hpp"

using namespace gym;

int main(int argc, char* argv[])
{
  const std::string environment = "CartPole-v0";
  const std::string host = "kurg.org";
  const std::string port = "4040";

  double totalReward = 0;
  size_t totalSteps = 0;

  Environment env(host, port, environment);
  env.compression(9);
  env.monitor.start("./dummy/", true, true);

  env.reset();
  env.render();

  while (1)
  {
    arma::mat action = env.action_space.sample();
    std::cout << "action: \n" << action << std::endl;

    env.step(action);

    totalReward += env.reward;
    totalSteps += 1;

    if (env.done)
    {
      break;
    }

    std::cout << "Current step: " << totalSteps << " current reward: "
      << totalReward << std::endl;
  }

  std::cout << "Instance: " << env.instance << " total steps: " << totalSteps
      << " reward: " << totalReward << std::endl;

  std::cout << "Video: https://kurg.org/media/gym/" << env.instance
      << " (it might take some minutes before the video is accessible)."
      << std::endl;

  return 0;
}

Add information about the video url.

Add information about the video url.


#include "PatternMatcherOnig.h"

#include <cstring>

// Static member initiallization
PatternMatcherOnig::Mutex PatternMatcherOnig::mutex;

PatternMatcherOnig::PatternMatcherOnig( const char * regexp ) {
    int r;
    UChar * pattern = (UChar *) regexp;
    OnigErrorInfo einfo;

    {
        ScopedLock guard(mutex);
        r = onig_new(&reg, pattern, pattern + strlen(regexp),
                ONIG_OPTION_DEFAULT, ONIG_ENCODING_UTF8, ONIG_SYNTAX_DEFAULT, &einfo);
    }

    if( r != ONIG_NORMAL ) {
        char s[ONIG_MAX_ERROR_MESSAGE_LEN];
        onig_error_code_to_str((UChar*) s, r, &einfo);
        FATAL( "Onig pattern matcher error: %s\n", s);
    }
}

bool PatternMatcherOnig :: Match( const char * target ) const {
    int size = strlen(target);

    int r = onig_match(
        reg,
        (UChar *) target,
        (UChar *) target + size,
        (UChar *) target,
        NULL,
        ONIG_OPTION_NONE
    );

    return r >= 0;
}

PatternMatcherOnig :: ~PatternMatcherOnig(void) {
    onig_free(reg);
}

#include "PatternMatcherOnig.h"

#include <cstring>

// Static member initiallization
PatternMatcherOnig::Mutex PatternMatcherOnig::mutex;

PatternMatcherOnig::PatternMatcherOnig( const char * regexp ) {
    int r;
    UChar * pattern = (UChar *) regexp;
    OnigErrorInfo einfo;

    {
        ScopedLock guard(mutex);
        r = onig_new(&reg, pattern, pattern + strlen(regexp),
                ONIG_OPTION_DEFAULT, ONIG_ENCODING_UTF8, ONIG_SYNTAX_DEFAULT, &einfo);
    }

    if( r != ONIG_NORMAL ) {
        char s[ONIG_MAX_ERROR_MESSAGE_LEN];
        onig_error_code_to_str((UChar*) s, r, &einfo);
        FATAL( "Onig pattern matcher error: %s\n", s);
    }
}

bool PatternMatcherOnig :: Match( const char * target ) const {
    int size = strlen(target);

    int r = onig_search(
        reg,
        (UChar *) target,
        (UChar *) target + size,
        (UChar *) target,
        (UChar *) target + size,
        NULL,
        ONIG_OPTION_NONE
    );

    return r >= 0;
}

PatternMatcherOnig :: ~PatternMatcherOnig(void) {
    onig_free(reg);
}

Use search instead of match in pattern matcher.

Using `onig_match` essentially added an implicit "^" to the beginning of
the regular expression.


#include "HaxeRuntime.h"
#include "IntPtr.h"
#include "HaxeInit.h"
#include <uhx/GcRef.h>

::uhx::GcRef::GcRef() {
  check_hx_init();
  this->ref = ::uhx::expose::GcRefStatic::init();
}

::uhx::GcRef::~GcRef() {
  ::uhx::expose::GcRefStatic::destruct(this->ref);
}

::uhx::GcRef::GcRef(const GcRef& rhs) {
  this->ref = ::uhx::expose::GcRefStatic::init();
  this->set(const_cast<GcRef&>(rhs).get());
}

void ::uhx::GcRef::set(unreal::UIntPtr val) {
  ::uhx::expose::GcRefStatic::set(this->ref, val);
}

unreal::UIntPtr uhx::GcRef::get() const {
  return ::uhx::expose::GcRefStatic::get(this->ref);
}

#include "HaxeRuntime.h"
#include "CoreMinimal.h"
#include "IntPtr.h"
#include "HaxeInit.h"
#include "uhx/GcRef.h"
#include "CoreGlobals.h"

::uhx::GcRef::GcRef() {
  if (!GIsRetrievingVTablePtr) {
    check_hx_init();
    this->ref = ::uhx::expose::GcRefStatic::init();
  } else {
    this->ref = 0;
  }
}

::uhx::GcRef::~GcRef() {
  if (this->ref != 0) {
    ::uhx::expose::GcRefStatic::destruct(this->ref);
  }
}

::uhx::GcRef::GcRef(const GcRef& rhs) {
  if (rhs.ref != 0) {
    this->ref = ::uhx::expose::GcRefStatic::init();
    this->set(const_cast<GcRef&>(rhs).get());
  } else {
    this->ref = 0;
  }
}

void ::uhx::GcRef::set(unreal::UIntPtr val) {
  if (this->ref == 0) {
    check_hx_init();
    this->ref = ::uhx::expose::GcRefStatic::init();
  }
  ::uhx::expose::GcRefStatic::set(this->ref, val);
}

unreal::UIntPtr uhx::GcRef::get() const {
  if (this->ref == 0) {
    return 0;
  }
  return ::uhx::expose::GcRefStatic::get(this->ref);
}

[CL-14405] Update to latest perforce change
Change 14405 by waneck@wnk-asus-win-ls on 2017/12/07 17:29:14

[unreal.hx] Fix some hot reload issues by delaying the init calls when calling the vtable constructor


#include <iostream>

#include "reader.h"

namespace
{

class Repl
{
  std::istream& in_;
  std::ostream& out_;
  std::string prompt_ = "mclisp> ";
  mclisp::Reader reader_;

  public:
    explicit Repl(std::istream& in=std::cin, std::ostream& out=std::cout):
      in_(in), out_(out), reader_(in_) {};

    int loop();
};

int Repl::loop()
{
  std::ostringstream oss;
  while (oss.str() != "QUIT" && oss.str() != "(QUIT . NIL)")
  {
    out_ << prompt_;
    oss.str("");
    oss.clear();
    const mclisp::Sexp& exp = reader_.Read();
    oss << exp;
    out_ << exp << std::endl;
  }
  return 0;
}

}; //end namespace

int main()
{
  Repl repl;
  return repl.loop();
}

#include <iostream>

#include "reader.h"

namespace
{

class Repl
{
  std::istream& in_;
  std::ostream& out_;
  std::string prompt_ = "mclisp> ";
  mclisp::Reader reader_;

  public:
    explicit Repl(std::istream& in=std::cin, std::ostream& out=std::cout):
      in_(in), out_(out), reader_(in_) {};

    int loop();
};

int Repl::loop()
{
  std::ostringstream oss;
  while (oss.str() != "QUIT" && oss.str() != "(QUIT . NIL)")
  {
    out_ << prompt_;
    oss.str("");
    oss.clear();
    const mclisp::ConsCell *exp = reader_.Read();
    oss << *exp;
    out_ << *exp << std::endl;
  }
  return 0;
}

}; //end namespace

int main()
{
  Repl repl;
  return repl.loop();
}

Update REPL to read/print a ConsCell * rather than a Sexp&.


// Source : https://oj.leetcode.com/problems/container-with-most-water/
// Author : Hao Chen
// Date   : 2014-06-22

/**********************************************************************************
*
* Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai).
* n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0).
*
* Find two lines, which together with x-axis forms a container, such that the container contains the most water.
*
* Note: You may not slant the container.
*
*
**********************************************************************************/

class Solution {
public:
    int maxArea(vector<int> &height) {
        int area = 0;
        int i = 0;
        int j = height.size()-1;

        while(i<j){
            int a = (j-i)* (height[i]>height[j] ? height[j] : height[i]);
            area = a>area ? a : area;
            height[i]>height[j] ? j-- : i++;
        }

        return area;
    }
};

// Source : https://oj.leetcode.com/problems/container-with-most-water/
// Author : Hao Chen
// Date   : 2014-06-22

/**********************************************************************************
*
* Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai).
* n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0).
*
* Find two lines, which together with x-axis forms a container, such that the container contains the most water.
*
* Note: You may not slant the container.
*
*
**********************************************************************************/

class Solution {
public:
    int maxArea(vector<int> &height) {

        int maxArea = 0;
        // two pointers scan from two sides to middle
        int left = 0;
        int right = height.size()-1;

        int area;
        while ( left < right ){
            //calculate the area
            area = (right - left) * ( height[left] < height[right] ? height[left] : height[right]);
            //tracking the maxium area
            maxArea = area > maxArea ? area : maxArea;
            // because the area is decided by the shorter edge
            // so we increase the area is to increase the shorter edge
            height[left] < height[right] ? left++ : right-- ;
        }

        return maxArea;
    }
};

Add comments for "Container With Most Water"


// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include <vespa/vespalib/testkit/testapp.h>
#include <vespa/vespalib/util/clock.h>
#include <vespa/fastos/thread.h>

using vespalib::Clock;
using vespalib::duration;
using vespalib::steady_time;

TEST("Test that clock is ticking forward") {

    Clock clock(0.050);
    FastOS_ThreadPool pool(0x10000);
    ASSERT_TRUE(pool.NewThread(clock.getRunnable(), nullptr) != nullptr);
    steady_time start = clock.getTimeNS();
    std::this_thread::sleep_for(1s);
    steady_time stop = clock.getTimeNS();
    EXPECT_TRUE(stop > start);
    std::this_thread::sleep_for(1s);
    clock.stop();
    steady_time stop2 = clock.getTimeNS();
    EXPECT_TRUE(stop2 > stop);
    EXPECT_TRUE(vespalib::count_ms(stop2 - stop) > 1000);
}

TEST_MAIN() { TEST_RUN_ALL(); }

// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include <vespa/vespalib/testkit/testapp.h>
#include <vespa/vespalib/util/clock.h>
#include <vespa/fastos/thread.h>

using vespalib::Clock;
using vespalib::duration;
using vespalib::steady_time;
using vespalib::steady_clock;

void waitForMovement(steady_time start, Clock & clock, vespalib::duration timeout) {
    steady_time startOsClock = steady_clock::now();
    while ((clock.getTimeNS() <= start) && ((steady_clock::now() - startOsClock) < timeout)) {
        std::this_thread::sleep_for(1ms);
    }
}

TEST("Test that clock is ticking forward") {

    Clock clock(0.050);
    FastOS_ThreadPool pool(0x10000);
    ASSERT_TRUE(pool.NewThread(clock.getRunnable(), nullptr) != nullptr);
    steady_time start = clock.getTimeNS();
    waitForMovement(start, clock, 10s);
    steady_time stop = clock.getTimeNS();
    EXPECT_TRUE(stop > start);
    std::this_thread::sleep_for(1s);
    start = clock.getTimeNS();
    waitForMovement(start, clock, 10s);
    clock.stop();
    steady_time stop2 = clock.getTimeNS();
    EXPECT_TRUE(stop2 > stop);
    EXPECT_TRUE(vespalib::count_ms(stop2 - stop) > 1000);
}

TEST_MAIN() { TEST_RUN_ALL(); }

Make the test deterministic by waiting for clock to tick at least once.


/**
 * Author: Denis Anisimov 2015
 *
 * Implementation of telegram bot
 *
 */

#include "telegram_bot.h"

#include <chrono>
#include <thread>

#include <cpprest/http_client.h>

constexpr char kTelegramEndpoint[] = "https://api.telegram.org/bot";

TelegramBot::TelegramBot(std::string token)
: token_(token),
  bot_url_(kTelegramEndpoint + token) {}

void TelegramBot::Run() {
  if (!TestMe()) {
    return;
  }

  using namespace std::literals;
  while((true)) {
    std::this_thread::sleep_for(2s);
  }
}

bool TelegramBot::TestMe() {
  bool result{false};
  web::http::client::http_client client(U(bot_url_));
  client.request(web::http::methods::GET, web::http::uri_builder(U("/getMe")).to_string())
  .then([&result](web::http::http_response response) {
    result = (response.status_code() == 200);
  })
  .wait();
  return result;
}

/**
 * Author: Denis Anisimov 2015
 *
 * Implementation of telegram bot
 *
 */

#include "telegram_bot.h"

#include <chrono>
#include <thread>

#include <cpprest/http_client.h>

constexpr char kTelegramEndpoint[] = "https://api.telegram.org/bot";

TelegramBot::TelegramBot(std::string token)
: token_(token),
  bot_url_(kTelegramEndpoint + token) {}

void TelegramBot::Run() {
  if (!TestMe()) {
    std::cout << "Bot self-test using getMe method failed." << std::endl;
    return;
  }

  using namespace std::literals;
  while((true)) {
    std::this_thread::sleep_for(2s);
  }
}

bool TelegramBot::TestMe() {
  bool result{false};
  web::http::client::http_client client(U(bot_url_));
  client.request(web::http::methods::GET, web::http::uri_builder(U("/getMe")).to_string())
  .then([&result](web::http::http_response response) {
    result = (response.status_code() == 200);
  })
  .wait();
  return result;
}

Add message on self-test failure

Add message on self-test failure


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

#include "base/system_monitor.h"

namespace base {

void SystemMonitor::ProcessWmPowerBroadcastMessage(int event_id) {
  PowerEvent power_event;
  switch (event_id) {
    case PBT_APMPOWERSTATUSCHANGE:
      power_event = POWER_STATE_EVENT;
      break;
    case PBT_APMRESUMEAUTOMATIC:
      power_event = RESUME_EVENT;
      break;
    case PBT_APMSUSPEND:
      power_event = SUSPEND_EVENT;
      break;
    default:
      DCHECK(false);
  }
  ProcessPowerMessage(power_event);
}

// Function to query the system to see if it is currently running on
// battery power.  Returns true if running on battery.
bool SystemMonitor::IsBatteryPower() {
  SYSTEM_POWER_STATUS status;
  if (!GetSystemPowerStatus(&status)) {
    LOG(ERROR) << "GetSystemPowerStatus failed: " << GetLastError();
    return false;
  }
  return (status.ACLineStatus == 0);
}

} // namespace base

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

#include "base/system_monitor.h"

namespace base {

void SystemMonitor::ProcessWmPowerBroadcastMessage(int event_id) {
  PowerEvent power_event;
  switch (event_id) {
    case PBT_APMPOWERSTATUSCHANGE:  // The power status changed.
      power_event = POWER_STATE_EVENT;
      break;
    case PBT_APMRESUMEAUTOMATIC:  // Non-user initiated resume from suspend.
    case PBT_APMRESUMESUSPEND:    // User initiated resume from suspend.
      power_event = RESUME_EVENT;
      break;
    case PBT_APMSUSPEND:  // System has been suspended.
      power_event = SUSPEND_EVENT;
      break;
    default:
      return;

    // Other Power Events:
    // PBT_APMBATTERYLOW - removed in Vista.
    // PBT_APMOEMEVENT - removed in Vista.
    // PBT_APMQUERYSUSPEND - removed in Vista.
    // PBT_APMQUERYSUSPENDFAILED - removed in Vista.
    // PBT_APMRESUMECRITICAL - removed in Vista.
    // PBT_POWERSETTINGCHANGE - user changed the power settings.
  }
  ProcessPowerMessage(power_event);
}

// Function to query the system to see if it is currently running on
// battery power.  Returns true if running on battery.
bool SystemMonitor::IsBatteryPower() {
  SYSTEM_POWER_STATUS status;
  if (!GetSystemPowerStatus(&status)) {
    LOG(ERROR) << "GetSystemPowerStatus failed: " << GetLastError();
    return false;
  }
  return (status.ACLineStatus == 0);
}

} // namespace base

Update comments and remove bogus DCHECK in windows-specific broadcasted power message status.

Review URL: http://codereview.chromium.org/16220

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@7398 0039d316-1c4b-4281-b951-d872f2087c98


/**
 * \file dynamiclibrary.cpp
 * \author Thibault Schueller <ryp.sqrt@gmail.com>
 * \brief DynamicLibrary class
 */

#include "dynamiclibrary.hpp"
#include "exception/dynlibexception.hpp"

DynamicLibrary::DynamicLibrary(const std::string& file)
:   _file(file),
    _handle(nullptr)
{}

void DynamicLibrary::open(RelocationMode mode)
{
    char*   err;

    if (!(_handle = dlopen(_file.c_str(), static_cast<int>(mode))))
    {
        if ((err = dlerror()))
            throw (DynLibException(std::string("dlopen(): ") + err));
        else
            throw (DynLibException("dlopen(): Unknown error"));
    }
}

void DynamicLibrary::close()
{
    if (dlclose(_handle))
        throw (DynLibException(std::string("dlclose(): ") + dlerror()));
}

void* DynamicLibrary::getSymbol(const std::string& symbol)
{
    void*   sym;
    char*   err;

    sym = dlsym(_handle, symbol.c_str());
    if ((err = dlerror()))
        throw (DynLibException(std::string("dlsym(): ") + err));
    return (sym);
}

const std::string &DynamicLibrary::getFilePath() const
    {
    return _file;
    }

/**
 * \file dynamiclibrary.cpp
 * \author Thibault Schueller <ryp.sqrt@gmail.com>
 * \brief DynamicLibrary class
 */

#include "dynamiclibrary.hpp"
#include "exception/dynlibexception.hpp"

DynamicLibrary::DynamicLibrary(const std::string& file)
:   _file(file),
    _handle(nullptr)
{}

void DynamicLibrary::open(RelocationMode mode)
{
    char*   err;

    if (!(_handle = dlopen(_file.c_str(), static_cast<int>(mode) | RTLD_NODELETE)))
    {
        if ((err = dlerror()))
            throw (DynLibException(std::string("dlopen(): ") + err));
        else
            throw (DynLibException("dlopen(): Unknown error"));
    }
}

void DynamicLibrary::close()
{
    if (dlclose(_handle))
        throw (DynLibException(std::string("dlclose(): ") + dlerror()));
}

void* DynamicLibrary::getSymbol(const std::string& symbol)
{
    void*   sym;
    char*   err;

    sym = dlsym(_handle, symbol.c_str());
    if ((err = dlerror()))
        throw (DynLibException(std::string("dlsym(): ") + err));
    return (sym);
}

const std::string &DynamicLibrary::getFilePath() const
    {
    return _file;
    }

Add RTLD_NODELETE flag when closing dynamic library.

This has the effect to prevent nasty bug with object destructor
not being available (eg logger object created from modules,
or expectiong propagated from module).


#include <cuda_runtime_api.h>
#include <stdio.h>

int main(void)
{
  int num_devices = 0;
  cudaGetDeviceCount(&num_devices);
  if(num_devices > 0)
  {
    cudaDeviceProp properties;
    cudaGetDeviceProperties(&properties, 0);
    printf("--gpu-architecture=sm_%d%d", properties.major, properties.minor);
    return 0;
  } // end if

  return -1;
}

#include <cuda_runtime_api.h>
#include <stdio.h>
#include <stdlib.h>

void usage(const char *name)
{
  printf("usage: %s [device_id]\n", name);
}

int main(int argc, char **argv)
{
  int num_devices = 0;
  int device_id = 0;
  if(argc == 2)
  {
    device_id = atoi(argv[1]);
  }
  else if(argc > 2)
  {
    usage(argv[0]);
    exit(-1);
  }

  cudaGetDeviceCount(&num_devices);
  if(num_devices > device_id)
  {
    cudaDeviceProp properties;
    cudaGetDeviceProperties(&properties, device_id);
    printf("--gpu-architecture=sm_%d%d", properties.major, properties.minor);
    return 0;
  } // end if
  else
  {
    printf("No available device with id %d\n", device_id);
  }

  return -1;
}

Add an optional device_id command line argument.

--HG--
extra : convert_revision : svn%3A83215879-3e5a-4751-8c9d-778f44bb06a5/trunk%40345


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

#include "base/cancellation_flag.h"

#include "base/logging.h"

namespace base {

void CancellationFlag::Set() {
#if !defined(NDEBUG)
  DCHECK(set_on_ == PlatformThread::CurrentId());
#endif
  base::subtle::Release_Store(&flag_, 1);
}

bool CancellationFlag::IsSet() const {
  return base::subtle::Acquire_Load(&flag_) != 0;
}

}  // namespace base

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

#include "base/cancellation_flag.h"

#include "base/logging.h"

namespace base {

void CancellationFlag::Set() {
#if !defined(NDEBUG)
  DCHECK_EQ(set_on_, PlatformThread::CurrentId());
#endif
  base::subtle::Release_Store(&flag_, 1);
}

bool CancellationFlag::IsSet() const {
  return base::subtle::Acquire_Load(&flag_) != 0;
}

}  // namespace base

Replace a DCHECK with DCHECK_EQ.

Replace a DCHECK with DCHECK_EQ.

BUG=none
TEST=none
Review URL: http://codereview.chromium.org/2919013

git-svn-id: http://src.chromium.org/svn/trunk/src@52429 4ff67af0-8c30-449e-8e8b-ad334ec8d88c

Former-commit-id: dc76e08a5d10b0866111ed79414dbafbd247fd96


// infoware - C++ System information Library
//
// Written in 2017 by nabijaczleweli <nabijaczleweli@gmail.com> and ThePhD <phdofthehouse@gmail.com>
//
// To the extent possible under law, the author(s) have dedicated all copyright and related
// and neighboring rights to this software to the public domain worldwide. This software is
// distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>

#ifdef __APPLE__

#include "infoware/cpu.hpp"
#include "infoware/detail/scope.hpp"
#include <cstdlib>
#include <cstring>
#include <stdio.h>

std::int64_t iware::cpu::frequency() noexcept {
	const auto sysctl_output = popen("sysctl hw.cpufrequency", "r");
	if(!sysctl_output)
		return 0;
	iware::detail::quickscope_wrapper sysctl_closer{[&]() { pclose(sysctl_output); }};

	char buf[64]{};  // We're expecting somewhere on the order of strlen("hw.cpufrequency: 3100000000") == 27
	if(!fgets(buf, sizeof(buf), sysctl_output))
		return 0;

	const char* colon = std::strchr(buf, ':');
	if(!colon)
		return 0;

	return static_cast<std::int64_t>(std::strtoull(colon + 1, nullptr, 10));
}

#endif

// infoware - C++ System information Library
//
// Written in 2017 by nabijaczleweli <nabijaczleweli@gmail.com> and ThePhD <phdofthehouse@gmail.com>
//
// To the extent possible under law, the author(s) have dedicated all copyright and related
// and neighboring rights to this software to the public domain worldwide. This software is
// distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>

#ifdef __APPLE__

#include "infoware/cpu.hpp"
#include "infoware/detail/sysctl.hpp"

std::int64_t iware::cpu::frequency() noexcept {
	const auto ctl_data = iware::detail::sysctl("hw.cpufrequency");
	if(ctl_data.empty())
		return 0;

	const auto data = iware::detail::deconstruct_sysctl_int(ctl_data);
	if(!data.first)
		return 0;

	return data.second;
}

#endif

Use sysctl syscall in iware::cpu::frequency() on Darwin

Ref: #13


// Copyright (C) 2015 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

#include "sstream"
#include "qtUtilities.h"
#include "CQValidatorUnit.h"

CQValidatorUnit::CQValidatorUnit(QLineEdit * parent, const char * name):
  CQValidator< QLineEdit >(parent, &QLineEdit::text, name)
{
}

QValidator::State CQValidatorUnit::validate(QString & input, int & pos) const
{
  State CurrentState = Invalid;

  bool success = false;
  std::istringstream buffer(TO_UTF8(input));
  CUnitParser Parser(&buffer);
  success = (Parser.yyparse() == 0);

  if (success)
    {
      setColor(Acceptable);
      CurrentState = Acceptable;
    }

  if (CurrentState != Acceptable)
    {
      setColor(Invalid);
      CurrentState = Intermediate;
    }

  return CurrentState;
}

// Copyright (C) 2015 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

#include "sstream"
#include "qtUtilities.h"
#include "CQValidatorUnit.h"
#include "utilities/CCopasiException.h"

CQValidatorUnit::CQValidatorUnit(QLineEdit * parent, const char * name):
  CQValidator< QLineEdit >(parent, &QLineEdit::text, name)
{
}

QValidator::State CQValidatorUnit::validate(QString & input, int & pos) const
{
  State CurrentState = Invalid;

  bool success = false;
  std::istringstream buffer(TO_UTF8(input));
  CUnitParser Parser(&buffer);

  try
  {
    success = (Parser.yyparse() == 0);
  }
  catch (CCopasiException & /*exception*/)
  {
    success = false;
  }

  if (success)
    {
      setColor(Acceptable);
      CurrentState = Acceptable;
    }
  else
    {
      setColor(Invalid);
      CurrentState = Intermediate;
    }

  return CurrentState;
}

Handle the exception thrown when the parser gets invalid input (rather than getting stuck, and not proceeding to color the background)


#include "mainwindow.h"
#include "ui_mainwindow.h"

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

MainWindow::~MainWindow()
{
    delete ui;
}

#include "mainwindow.h"
#include "ui_mainwindow.h"

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

    setWindowTitle("CRC Calculator ver " + QString::number(MAJOR_VERSION) + '.' + QString::number(MINOR_VERSION));
}

MainWindow::~MainWindow()
{
    delete ui;
}

Add Main Window Title + version

Add Main Window Title + version


#include "usbCamera.h"

enum Default {
        DEFAULT_CAMERA_INDEX = 0,
        DEFAULT_FPS = 1
    };

USBCamera::USBCamera(int frameRate, int cameraIndex, string hostname):
    it(nh),
    videoStream(cameraIndex) {

        nh.param<int>("cameraIndex", cameraIndex, DEFAULT_CAMERA_INDEX);
        nh.param<int>("fps", fps, frameRate);

        if (not videoStream.isOpened()) {
            ROS_ERROR_STREAM("Failed to open camera device!");
            ros::shutdown();
        }

        ros::Duration period = ros::Duration(1. / fps);

        rawImgPublish = it.advertise((hostname + "/camera/image"), 2);

        rosImage = boost::make_shared<cv_bridge::CvImage>();
        rosImage->encoding = sensor_msgs::image_encodings::RGB8;

        timer = nh.createTimer(period, &USBCamera::capture, this);
}

void USBCamera::capture(const ros::TimerEvent& te) {
        videoStream >> cvImageColor;

        cv::resize(cvImageColor, cvImageLR, cv::Size(320,240), cv::INTER_LINEAR);

        rosImage->image = cvImageLR;
        if (not rosImage->image.empty()) {
            rosImage->header.stamp = ros::Time::now();
            rawImgPublish.publish(rosImage->toImageMsg());
        }
    }

USBCamera::~USBCamera(){
    videoStream.release();
}

#include "usbCamera.h"

enum Default {
        DEFAULT_CAMERA_INDEX = 0,
        DEFAULT_FPS = 1
    };

USBCamera::USBCamera(int frameRate, int cameraIndex, string hostname):
    it(nh),
    videoStream(cameraIndex) {

        nh.param<int>("cameraIndex", cameraIndex, DEFAULT_CAMERA_INDEX);
        nh.param<int>("fps", fps, frameRate);

        if (not videoStream.isOpened()) {
            ROS_ERROR_STREAM("Failed to open camera device!");
            ros::shutdown();
        }

        ros::Duration period = ros::Duration(1. / fps);

        rawImgPublish = it.advertise((hostname + "/camera/image"), 2);

        rosImage = boost::make_shared<cv_bridge::CvImage>();
        rosImage->encoding = sensor_msgs::image_encodings::BGR8;

        timer = nh.createTimer(period, &USBCamera::capture, this);
}

void USBCamera::capture(const ros::TimerEvent& te) {
        videoStream >> cvImageColor;

        cv::resize(cvImageColor, cvImageLR, cv::Size(320,240), cv::INTER_LINEAR);

        rosImage->image = cvImageLR;
        if (not rosImage->image.empty()) {
            rosImage->header.stamp = ros::Time::now();
            rawImgPublish.publish(rosImage->toImageMsg());
        }
    }

USBCamera::~USBCamera(){
    videoStream.release();
}

Revert to BGR color on camera to accommodate OpenCV


/**
 * @file compressor_test.cpp
 * @author Chase Geigle
 */

#include <array>
#include <iostream>
#include <fstream>
#include "util/gzstream.h"

using namespace meta;

int main(int argc, char** argv)
{
    if (argc < 3)
    {
        std::cerr << "Usage: " << argv[0] << " input output" << std::endl;
        return 1;
    }

    std::array<char, 1024> buffer;

    {
        std::ifstream file{argv[1], std::ios::in | std::ios::binary};
        util::gzofstream output{argv[2]};
        while (file)
        {
            file.read(&buffer[0], 1024);
            output.write(&buffer[0], file.gcount());
        }
    }

    {
        util::gzifstream input{argv[2]};
        std::ofstream output{std::string{argv[2]} + ".decompressed",
                             std::ios::out | std::ios::binary};
        std::string in;
        while (std::getline(input, in))
        {
            output << in << "\n";
        }
    }

    return 0;
}

/**
 * @file compressor_test.cpp
 * @author Chase Geigle
 */

#include <array>
#include <iostream>
#include <fstream>
#include "io/gzstream.h"

using namespace meta;

int main(int argc, char** argv)
{
    if (argc < 3)
    {
        std::cerr << "Usage: " << argv[0] << " input output" << std::endl;
        return 1;
    }

    std::array<char, 1024> buffer;

    {
        std::ifstream file{argv[1], std::ios::in | std::ios::binary};
        io::gzofstream output{argv[2]};
        while (file)
        {
            file.read(&buffer[0], 1024);
            output.write(&buffer[0], file.gcount());
        }
    }

    {
        io::gzifstream input{argv[2]};
        std::ofstream output{std::string{argv[2]} + ".decompressed",
                             std::ios::out | std::ios::binary};

        while (input)
        {
            input.read(&buffer[0], 1024);
            output.write(&buffer[0], input.gcount());
        }
    }

    return 0;
}

Fix dummy compressor-test executable for util -> io move.


#include "startuplaunch.h"

#include <QDesktopServices>

StartupLaunch::StartupLaunch()
{
}

bool StartupLaunch::addOnStartup(QString name, QString executable, QString comments)
{
    qWarning() << " add to startup not yet implemented on macx";
    return false;
}

bool StartupLaunch::removeFromStartup(QString name)
{
    qWarning() << " remove from startup not yet implemented on macx";
    return false;
}

bool StartupLaunch::isOnStartup(QString name)
{
    qWarning() << " is on startup not yet implemented on macx";
    return false;
}

#include "startuplaunch.h"

#include <QDesktopServices>

StartupLaunch::StartupLaunch()
{
}

bool StartupLaunch::addOnStartup(QString name, QString executable, QString comments)
{
    QString autostartPath = QDesktopServices::storageLocation(QDesktopServices::HomeLocation)+"/Library/LaunchAgents";
    if(false==QDir().exists(autostartPath))
        QDir().mkdir(autostartPath);
    QString filepath = autostartPath+"/"+name.toLower()+".plist";
    QFile file(filepath);
    if(false==file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate))
    {
        qWarning() << "Startuplaunch : impossible to open " << filepath;
        return false;
    }
    QTextStream out(&file);
    out << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << endl
        << "<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd\">" << endl
        << "<plist version=\"1.0\">" << endl
        << "<dict>" << endl
        << "<key>Label</key>" << endl
        << "<string>me.boxti.boxtime</string>" << endl
        << "<key>RunAtLoad</key>" << endl
        << "<true/>" << endl
        << "<key>Program</key>" << endl
        << "<string>/Applications/boxtime.app/Contents/MacOS/boxtime</string>" << endl
        << "</dict>" << endl
        << "</plist>" << endl;
    file.close();
    qDebug() << name << " added to startup " << executable;
    return true;
}

bool StartupLaunch::removeFromStartup(QString name)
{
    qDebug() << name << " removed from startup";
    return QFile::remove(QDesktopServices::storageLocation(QDesktopServices::HomeLocation)+QString("/Library/LaunchAgents/")+name.toLower()+QString(".plist"));
}

bool StartupLaunch::isOnStartup(QString name)
{
    return QFile::exists(QDesktopServices::storageLocation(QDesktopServices::HomeLocation)+QString("/Library/LaunchAgents/")+name.toLower()+QString(".desktopplist"));
}

Add basic implementation for MacOS X

Add basic implementation for MacOS X


fs: Make default Device::init() set intialized flag.


#include "webrtc/base/thread.h"
#include "webrtc/p2p/base/basicpacketsocketfactory.h"
#include "webrtc/api/peerconnectioninterface.h"
#include "webrtc/api/test/fakeconstraints.h"
#include "webrtc/media/engine/webrtcvideocapturerfactory.h"

int main(int argc, char* argv[]) {
  // something from base
  rtc::Thread* thread = rtc::Thread::Current();

  // something from p2p
  std::unique_ptr<rtc::BasicPacketSocketFactory> socket_factory(
    new rtc::BasicPacketSocketFactory());

  // something from api
  rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
    peer_connection_factory = webrtc::CreatePeerConnectionFactory();

  // something from api/test
  webrtc::FakeConstraints constraints;

  // something from media/engine
  cricket::WebRtcVideoDeviceCapturerFactory factory;
  cricket::VideoCapturer* capturer = factory.Create(cricket::Device("", 0));

  return 0;
}

#include "webrtc/rtc_base/thread.h"
#include "webrtc/p2p/base/basicpacketsocketfactory.h"
#include "webrtc/api/peerconnectioninterface.h"
#include "webrtc/api/test/fakeconstraints.h"
#include "webrtc/media/engine/webrtcvideocapturerfactory.h"

int main(int argc, char* argv[]) {
  // something from base
  rtc::Thread* thread = rtc::Thread::Current();

  // something from p2p
  std::unique_ptr<rtc::BasicPacketSocketFactory> socket_factory(
    new rtc::BasicPacketSocketFactory());

  // something from api
  rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
    peer_connection_factory = webrtc::CreatePeerConnectionFactory();

  // something from api/test
  webrtc::FakeConstraints constraints;

  // something from media/engine
  cricket::WebRtcVideoDeviceCapturerFactory factory;
  std::unique_ptr<cricket::VideoCapturer> capturer = factory.Create(cricket::Device("", 0));

  return 0;
}

Fix test for current head changes.

Fix test for current head changes.


//Copyright (c) 2015 Ultimaker B.V.
//UltiScanTastic is released under the terms of the AGPLv3 or higher.

#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>

/*!
 * \brief Runs the test cases.
 */
int main(int argc,char** argv)
{
    CppUnit::TextUi::TestRunner runner;
    CppUnit::TestFactoryRegistry& registry = CppUnit::TestFactoryRegistry::getRegistry();
    runner.addTest(registry.makeTest());
    //return runner.run("",false);
    bool success = runner.run("", false);
    return success ? 0 : 1;
}

//Copyright (c) 2015 Ultimaker B.V.
//UltiScanTastic is released under the terms of the AGPLv3 or higher.

#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>

/*!
 * \brief Runs the test cases.
 */
int main(int argc,char** argv)
{
    CppUnit::TextUi::TestRunner runner;
    CppUnit::TestFactoryRegistry& registry = CppUnit::TestFactoryRegistry::getRegistry();
    runner.addTest(registry.makeTest());
    bool success = runner.run("", false);
    return success ? 0 : 1;
}

Remove old try for return code

Remove old try for return code

Directly returning the boolean didn't work.


#include <bits/stdc++.h>
#define NUM_NODES 8

using namespace std;

vector < int > g[NUM_NODES];
int vis[NUM_NODES];
enum {WHITE, GRAY, BLACK};

/*
 * o -> origin
 */
void dfs(int o){
    vis [o] = GRAY; //semi-visited
    for (int i = 0; i < g[o].size(); i++){
        int v = g[o][i];
        if (vis[v] == WHITE) dfs(v); // visit neighbors
    }
    cout << o << endl;
    vis[o] = BLACK; //visited;
}

int main(){

    g[0].push_back(1);
    g[0].push_back(2);
    g[0].push_back(3);
    g[1].push_back(4);
    g[1].push_back(5);
    g[2].push_back(6);
    g[3].push_back(7);

    dfs(0);

    return 0;
}

#include <bits/stdc++.h>
#define NUM_NODES 20

using namespace std;

vector < int > g[NUM_NODES];
int vis[NUM_NODES];
enum {WHITE, GRAY, BLACK};

/*
 * o -> origin
 */
void dfs(int o){
    vis [o] = GRAY; //semi-visited
    for (int i = 0; i < g[o].size(); i++){
        int v = g[o][i];
        if (vis[v] == GRAY) cout << "There is a cycle. to " << o <<  endl;
        if (vis[v] == WHITE) dfs(v); // visit neighbors
    }
    cout << o << endl;
    vis[o] = BLACK; //visited;
}

int main(){

    g[0].push_back(1);
    g[0].push_back(2);
    g[0].push_back(3);
    g[1].push_back(4);
    g[1].push_back(5);
    g[2].push_back(6);
    g[3].push_back(7);
    g[4].push_back(0);
    g[6].push_back(0);

    dfs(0);

    return 0;
}

Implement awesome form to detect cycles in a graph.


#include <iostream>
#include <cassert>
#include <cmath>

using namespace std;

int main ( int argc, char *argv[] )
{
    assert ( argc == 2 );
    unsigned long maxnumber = atol(argv[1]);

    // Create the sieve end initialize all numbers as prime (true)
    bool *numbers = new bool[maxnumber+1];
    for ( unsigned long n = 0; n<=maxnumber; ++n )
        numbers[n] = true;

    // Set 0 and 1 as not-prime
    numbers[0] = false;
    numbers[1] = false;

    // Lets count the found primes
    unsigned long count = 0;

    for ( unsigned long n = 2; n<=maxnumber; ++n )
    {
        if ( numbers[n] )
        {
            // We found a new prime
            cout << n << " " << endl;

            // Count it
            ++count;

            // Delete all multiples
            for ( unsigned long m = 2*n; m<=maxnumber; m+=n )
                numbers[m] = false;
        }
    }
    cout << endl;
    cout << "We found " << count << " primes." << endl;

    delete [] numbers;

    return 0;
}

#include <iostream>
#include <cassert>
#include <cmath>

using namespace std;

int main ( int argc, char *argv[] )
{
    unsigned long maxnumber = 0;

    if ( 2 == argc )
        maxnumber = atol(argv[1]);
    else
    {
        cout << "Enter the highest number to test: ";
        cin >> maxnumber;
    }

    // Create the sieve end initialize all numbers as prime (true)
    bool *numbers = new bool[maxnumber+1];
    for ( unsigned long n = 0; n<=maxnumber; ++n )
        numbers[n] = true;

    // Set 0 and 1 as not-prime
    numbers[0] = false;
    numbers[1] = false;

    // Lets count the found primes
    unsigned long count = 0;

    for ( unsigned long n = 2; n<=maxnumber; ++n )
    {
        if ( numbers[n] )
        {
            // We found a new prime
            cout << n << " " << endl;

            // Count it
            ++count;

            // Delete all multiples
            for ( unsigned long m = 2*n; m<=maxnumber; m+=n )
                numbers[m] = false;
        }
    }
    cout << endl;
    cout << "We found " << count << " primes." << endl;

    delete [] numbers;

    return 0;
}

Sieve-of-Eratosthenes: Read max number either from command line argument or ask user.


#include "MyOpenCVIF.hpp"

MyOpenCVIF::MyOpenCVIF() :
  m_FPSCounter(),
  m_humanDetector("/usr/local/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml")
{
}

void MyOpenCVIF::ProcessFrame(Mat& frame)
{
  m_FPSCounter.ProcessFrame(frame);
  m_systemMonitor.ProcessFrame(frame);
  m_humanDetector.ProcessFrame(frame);
  m_HUD.ProcessFrame(frame);
}

#include "MyOpenCVIF.hpp"

MyOpenCVIF::MyOpenCVIF() :
  m_FPSCounter(),
  m_humanDetector("/usr/local/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml")
{
}

void MyOpenCVIF::ProcessFrame(Mat& frame)
{
  m_FPSCounter.ProcessFrame(frame);
  //m_systemMonitor.ProcessFrame(frame);
  //m_humanDetector.ProcessFrame(frame);
  m_HUD.ProcessFrame(frame);
}

Comment out sample HumanDetector and SystemMonitor to show performance


#include "Pool.h"

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

const float Pool::BALL_RADIUS = 0.5/40;

void Pool::setWhiteBall(Vec2 whiteBall)
{
    this->whiteBall = whiteBall;
}
void Pool::setTargetBall(Vec2 targetBall)
{
    this->targetBall = targetBall;
}
void Pool::setPocket(Vec2 pocket)
{
    this->pocket = pocket;
}

float Pool::getHitAngle()
{
    std::cout << whiteBall.getString() << std::endl;
    //Calculating the angle of the vector that the target needs to travel
    Vec2 targetDiff = pocket - targetBall;

    float targetAngle = targetDiff.getAngle();

    //Calculating where the white needs to be when it hits
    Vec2 whiteTarget(BALL_RADIUS * cos(targetAngle - M_PI), BALL_RADIUS * sin(targetAngle - M_PI));
    whiteTarget += targetBall;

    Vec2 finalDiff = whiteTarget - whiteBall;

    return finalDiff.getAngle();

}
Vec2 Pool::getWhiteBall()
{
    return whiteBall;
}

#include "Pool.h"

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

const float Pool::BALL_RADIUS = 0.5/40;

void Pool::setWhiteBall(Vec2 whiteBall)
{
    this->whiteBall = whiteBall;
}
void Pool::setTargetBall(Vec2 targetBall)
{
    this->targetBall = targetBall;
}
void Pool::setPocket(Vec2 pocket)
{
    this->pocket = pocket;
}

float Pool::getHitAngle()
{
    std::cout << whiteBall.getString() << std::endl;
    //Calculating the angle of the vector that the target needs to travel
    Vec2 targetDiff = pocket - targetBall;

    float targetAngle = targetDiff.getAngle();

    //Calculating where the white needs to be when it hits
    Vec2 whiteTarget(BALL_RADIUS * 2 * cos(targetAngle - M_PI), BALL_RADIUS * 2 * sin(targetAngle - M_PI));
    whiteTarget += targetBall;

    Vec2 finalDiff = whiteTarget - whiteBall;

    return finalDiff.getAngle();

}
Vec2 Pool::getWhiteBall()
{
    return whiteBall;
}

Fix bug in ball collision code where line would be placed incorrectly


/**
 * Coverity Scan model
 *
 * Manage false positives by giving coverity some hints.
 *
 * Updates to this file must be manually submitted by an admin to:
 *
 *   https://scan.coverity.com/projects/1222
 *
 */

// When tag is 1 or 2, let coverity know that execution is halting. Those
// tags correspond to INT_FATAL and USR_FATAL respectively.
//
// INT_FATAL, et al, work by calling setupError and then
// handleError. setupError simply sets some static globals, then handleError
// looks at those to decide how to error. For example, when INT_FATAL calls
// handleError it will abort execution because exit_immediately is true.
//
// Here we're fibbing to coverity by telling it that setupError results in
// abort (as opposed to handleError), but the effect should be the same.
void setupError(const char *filename, int lineno, int tag) {
  if (tag == 1 || tag == 2) {
    __coverity_panic__();
  }
}

//==============================
// runtime
//

// chpl_error() ends execution
// Note: this signature doesn't match the real one precisely, but it's
//       close enough.
void chpl_error(const char* message, int lineno, const char* filename) {
  __coverity_panic__();
}

// chpl_internal_error() ends execution
void chpl_internal_error(const char* message) {
  __coverity_panic__();
}

/**
 * Coverity Scan model
 *
 * Manage false positives by giving coverity some hints.
 *
 * Updates to this file must be manually submitted by an admin to:
 *
 *   https://scan.coverity.com/projects/1222
 *
 */

// When tag is 1 or 2, let coverity know that execution is halting. Those
// tags correspond to INT_FATAL and USR_FATAL respectively.
//
// INT_FATAL, et al, work by calling setupError and then
// handleError. setupError simply sets some static globals, then handleError
// looks at those to decide how to error. For example, when INT_FATAL calls
// handleError it will abort execution because exit_immediately is true.
//
// Here we're fibbing to coverity by telling it that setupError results in
// abort (as opposed to handleError), but the effect should be the same.
void setupError(const char *filename, int lineno, int tag) {
  if (tag == 1 || tag == 2) {
    __coverity_panic__();
  }
}

//==============================
// runtime
//

//
// exit() ends execution
//
void exit(int status) {
  __coverity_panic__();
}

Add exit() as program terminator; remove chpl_error(), chpl_internal_error().

I had thought Coverity would assume that exit() in C code would halt the
program, but indications are that it does not.  If it did, then Coverity
would see that chpl_error() and chpl_internal_error() both caused
program termination, because both call chpl_exit_any(), which calls
chpl_exit_common(), which calls exit().  Coverity did not seem to be
picking this up, and it also failed to respond to the modelling file
telling it that chpl_error() and chpl_internal_error() caused a halt.
I've found an indication on the web that Coverity does not by default
assume that exit() cause a halt, so here I'm saying so explicitly.


/*****************************************************************************
 * Licensed to Qualys, Inc. (QUALYS) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * QUALYS licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ****************************************************************************/

/**
 * @file
 * @brief IronBee++ Internals -- ModuleDelegate implementation.
 * @internal
 *
 * @author Christopher Alfeld <calfeld@qualys.com>
 **/

#include <ironbeepp/module_delegate.hpp>

namespace IronBee {

ModuleDelegate::ModuleDelegate( Module m ) :
    m_module( m )
{
    // nop
}

void ModuleDelegate::context_open( Context context )
{
    // nop
}

void ModuleDelegate::context_close( Context context )
{
    // nop
}

void ModuleDelegate::context_destroy( Context context )
{
    // nop
}

} // IronBee

/*****************************************************************************
 * Licensed to Qualys, Inc. (QUALYS) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * QUALYS licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ****************************************************************************/

/**
 * @file
 * @brief IronBee++ Internals -- ModuleDelegate implementation.
 * @internal
 *
 * @author Christopher Alfeld <calfeld@qualys.com>
 **/

#include <ironbeepp/module_delegate.hpp>

namespace IronBee {

ModuleDelegate::ModuleDelegate( Module m ) :
    m_module( m )
{
    // nop
}

void ModuleDelegate::context_open( Context context ) const
{
    // nop
}

void ModuleDelegate::context_close( Context context ) const
{
    // nop
}

void ModuleDelegate::context_destroy( Context context ) const
{
    // nop
}

} // IronBee

IronBee++/ModuleDelegate: Change that should have been included with earlier commit.


#include <gtest/gtest.h>

int main(int argc, char **argv) {
  testing::InitGoogleTest(&argc, argv);

  return RUN_ALL_TESTS();
}

#include <gtest/gtest.h>
#if defined (WIN32)
#include <windows.h>
#include <tchar.h>
#else
#include <string.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

#include "codec_def.h"
#include "codec_app_def.h"
#include "codec_api.h"

class CodecTest : public ::testing::Test {
 public:
  CodecTest() : decoder_(NULL) {}

  ~CodecTest() {
    if (decoder_) DestroyDecoder(decoder_);
  }

  void SetUp() {
    long rv = CreateDecoder(&decoder_);
    ASSERT_EQ(0, rv);
    ASSERT_TRUE(decoder_);
  }

protected:
  ISVCDecoder *decoder_;
};

TEST_F(CodecTest, JustInit) {
}

int main(int argc, char **argv) {
  testing::InitGoogleTest(&argc, argv);

  return RUN_ALL_TESTS();
}

Add a trivial init test

Add a trivial init test


#include "common/application_info.h"

#include "base/file_version_info.h"
#include "base/memory/scoped_ptr.h"
#include "base/utf_string_conversions.h"

namespace brightray {

std::string GetApplicationName() {
  auto info = make_scoped_ptr(FileVersionInfo::CreateFileVersionInfoForModule(GetModuleHandle(nullptr)));
  return UTF16ToUTF8(info->product_name());
}

std::string GetApplicationVersion() {
  auto info = make_scoped_ptr(FileVersionInfo::CreateFileVersionInfoForModule(GetModuleHandle(nullptr)));
  return UTF16ToUTF8(info->product_version());
}

}

#include "common/application_info.h"

#include "base/file_version_info.h"
#include "base/memory/scoped_ptr.h"
#include "base/strings/utf_string_conversions.h"

namespace brightray {

std::string GetApplicationName() {
  auto info = make_scoped_ptr(FileVersionInfo::CreateFileVersionInfoForModule(GetModuleHandle(nullptr)));
  return UTF16ToUTF8(info->product_name());
}

std::string GetApplicationVersion() {
  auto info = make_scoped_ptr(FileVersionInfo::CreateFileVersionInfoForModule(GetModuleHandle(nullptr)));
  return UTF16ToUTF8(info->product_version());
}

}

Update utf_string_conversions.h path in another place


// RUN: %clang_cc1 -fsyntax-only -verify -Wold-style-cast %s

void test1() {
  long x = (long)12; // expected-warning {{use of old-style cast}}
  (long)x; // expected-warning {{use of old-style cast}} expected-warning {{expression result unused}}
  (void**)x; // expected-warning {{use of old-style cast}} expected-warning {{expression result unused}}
  long y = static_cast<long>(12);
  (void)y;
  typedef void VOID;
  (VOID)y;
}

// RUN: %clang_cc1 -triple x86_64-apple-darwin -fsyntax-only -verify -Wold-style-cast %s

void test1() {
  long x = (long)12; // expected-warning {{use of old-style cast}}
  (long)x; // expected-warning {{use of old-style cast}} expected-warning {{expression result unused}}
  (void**)x; // expected-warning {{use of old-style cast}} expected-warning {{expression result unused}}
  long y = static_cast<long>(12);
  (void)y;
  typedef void VOID;
  (VOID)y;
}

Add a triple to fix this test on Windows

The warning from cmake-clang-x64-msc16-R was:

  test\SemaCXX\old-style-cast.cpp Line 6: cast to 'void **' from smaller integer type 'long'

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@195813 91177308-0d34-0410-b5e6-96231b3b80d8


#include "aboutdialog.h"
#include "qt/decoration.h"
#include "ui_aboutdialog.h"
#include "clientmodel.h"

AboutDialog::AboutDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::AboutDialog)
{
    ui->setupUi(this);
    ui->copyrightLabel->setText("Copyright 2009-2021 The Bitcoin/Peercoin/Black-Coin/Gridcoin developers");

    resize(GRC::ScaleSize(this, width(), height()));
}

void AboutDialog::setModel(ClientModel *model)
{
    if(model)
    {
        ui->versionLabel->setText(model->formatFullVersion());
    }
}

AboutDialog::~AboutDialog()
{
    delete ui;
}

void AboutDialog::on_buttonBox_accepted()
{
    close();
}

#include "aboutdialog.h"
#include "qt/decoration.h"
#include "ui_aboutdialog.h"
#include "clientmodel.h"

AboutDialog::AboutDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::AboutDialog)
{
    ui->setupUi(this);
    ui->copyrightLabel->setText("Copyright 2009-2022 The Bitcoin/Peercoin/Black-Coin/Gridcoin developers");

    resize(GRC::ScaleSize(this, width(), height()));
}

void AboutDialog::setModel(ClientModel *model)
{
    if(model)
    {
        ui->versionLabel->setText(model->formatFullVersion());
    }
}

AboutDialog::~AboutDialog()
{
    delete ui;
}

void AboutDialog::on_buttonBox_accepted()
{
    close();
}

Update copyright year to 2022 for Gridcoin About dialog box


// RUN: %clangxx_msan -O0 %s -o %t && %run %t

#include <assert.h>
#include <execinfo.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

__attribute__((noinline))
void f() {
  void *buf[10];
  int sz = backtrace(buf, sizeof(buf) / sizeof(*buf));
  assert(sz > 0);
  for (int i = 0; i < sz; ++i)
    if (!buf[i])
      exit(1);
  char **s = backtrace_symbols(buf, sz);
  assert(s > 0);
  for (int i = 0; i < sz; ++i)
    printf("%d\n", (int)strlen(s[i]));
}

int main(void) {
  f();
  return 0;
}

// RUN: %clangxx_msan -O0 %s -o %t && %run %t

#include <assert.h>
#include <execinfo.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

__attribute__((noinline))
void f() {
  void *buf[10];
  int sz = backtrace(buf, sizeof(buf) / sizeof(*buf));
  assert(sz > 0);
  for (int i = 0; i < sz; ++i)
    if (!buf[i])
      exit(1);
  char **s = backtrace_symbols(buf, sz);
  assert(s != 0);
  for (int i = 0; i < sz; ++i)
    printf("%d\n", (int)strlen(s[i]));
}

int main(void) {
  f();
  return 0;
}

Fix typo (ordered comparison between pointer and 0).

git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@284886 91177308-0d34-0410-b5e6-96231b3b80d8


#include "ros/ros.h"
#include "servo_msgs/KrsServoDegree.h"

#include <string>

#include "krs_servo_driver.hpp"

class KrsServoNode {
public:
  KrsServoNode();
  explicit KrsServoNode(ros::NodeHandle& nh, const char* path);

private:
  void krsServoDegreeCallback(const servo_msgs::KrsServoDegree::ConstPtr& msg);

  ros::Subscriber sub;
  KrsServoDriver krs;
};

int main(int argc, char** argv) {
  ros::init(argc, argv, "krs_servo_node");
  ros::NodeHandle nh;

  std::string path;
  nh.param<std::string>("serial_path", path, "/dev/ttyUSB0")

  KrsServoNode ksn(nh, path.c_str());

  ros::spin();
  return 0;
}

KrsServoNode::KrsServoNode()
  : krs()
{}

KrsServoNode::KrsServoNode(ros::NodeHandle& nh, const char* path)
  : krs(path)
{
  sub = nh.subscribe("cmd_krs", 16, &KrsServoNode::krsServoDegreeCallback, this);
}

void KrsServoNode::krsServoDegreeCallback(const servo_msgs::KrsServoDegree::ConstPtr& msg) {
  krs.sendAngle(msg->id, msg->angle);
}

#include "ros/ros.h"
#include "servo_msgs/KrsServoDegree.h"

#include <string>

#include "krs_servo_driver.hpp"

class KrsServoNode {
public:
  KrsServoNode();
  explicit KrsServoNode(ros::NodeHandle& nh, const char* path);

private:
  void krsServoDegreeCallback(const servo_msgs::KrsServoDegree::ConstPtr& msg);

  ros::Subscriber sub;
  KrsServoDriver krs;
};

int main(int argc, char** argv) {
  ros::init(argc, argv, "krs_servo_node");
  ros::NodeHandle nh;

  std::string path;
  nh.param<std::string>("serial_path", path, "/dev/ttyUSB0");

  KrsServoNode ksn(nh, path.c_str());

  ros::spin();
  return 0;
}

KrsServoNode::KrsServoNode()
  : krs()
{}

KrsServoNode::KrsServoNode(ros::NodeHandle& nh, const char* path)
  : krs(path)
{
  sub = nh.subscribe("cmd_krs", 16, &KrsServoNode::krsServoDegreeCallback, this);
}

void KrsServoNode::krsServoDegreeCallback(const servo_msgs::KrsServoDegree::ConstPtr& msg) {
  krs.sendAngle(msg->id, msg->angle);
}

Fix main func of krs_servo node. forget ';';


#include <stan/math/rev.hpp>
#include <gtest/gtest.h>
#include <vector>

TEST(ProbDistributionsNegBinomial2, derivatives_lccdf) {
  using stan::math::neg_binomial_2_lccdf;
  using stan::math::var;

  std::vector<double> N{1, 2, 3};
  double alpha_dbl = 8;
  double beta_dbl = 1.5;

  var alpha(alpha_dbl);
  var beta(beta_dbl);

  var val = neg_binomial_2_lccdf(N, alpha, beta);
  std::vector<var> x{alpha, beta};
  std::vector<double> gradients;
  val.grad(x, gradients);

  double epsilon = 1e-5;

  double grad_diff1 = (neg_binomial_2_lccdf(N, alpha_dbl + epsilon, beta_dbl)
                       - neg_binomial_2_lccdf(N, alpha_dbl - epsilon, beta_dbl))
                      / (2 * epsilon);
  EXPECT_FLOAT_EQ(grad_diff1, gradients[0]);

  double grad_diff2 = (neg_binomial_2_lccdf(N, alpha_dbl, beta_dbl + epsilon)
                       - neg_binomial_2_lccdf(N, alpha_dbl, beta_dbl - epsilon))
                      / (2 * epsilon);
  EXPECT_FLOAT_EQ(grad_diff2, gradients[1]);
}

#include <stan/math/rev.hpp>
#include <gtest/gtest.h>
#include <vector>

TEST(ProbDistributionsNegBinomial2, derivatives_lccdf) {
  using stan::math::neg_binomial_2_lccdf;
  using stan::math::var;

  std::vector<double> N{1, 2, 3};
  double alpha_dbl = 8;
  double beta_dbl = 1.5;

  var alpha(alpha_dbl);
  var beta(beta_dbl);

  var val = neg_binomial_2_lccdf(N, alpha, beta);
  std::vector<var> x{alpha, beta};
  std::vector<double> gradients;
  val.grad(x, gradients);

  double epsilon = 1e-6;

  double grad_diff1 = (neg_binomial_2_lccdf(N, alpha_dbl + epsilon, beta_dbl)
                       - neg_binomial_2_lccdf(N, alpha_dbl - epsilon, beta_dbl))
                      / (2 * epsilon);
  EXPECT_FLOAT_EQ(grad_diff1, gradients[0]);

  double grad_diff2 = (neg_binomial_2_lccdf(N, alpha_dbl, beta_dbl + epsilon)
                       - neg_binomial_2_lccdf(N, alpha_dbl, beta_dbl - epsilon))
                      / (2 * epsilon);
  EXPECT_FLOAT_EQ(grad_diff2, gradients[1]);
}

Revert test, other precision changes make it work.... still weird.


#include <OSGBaseInitFunctions.h>
#include <OSGNode.h>
#include <OSGNodeCore.h>
//#include <OSGRefPtr.h>

int main (int argc, char **argv)
{
    OSG::osgInit(argc, argv);

    // Test getting pointers
    OSG::NodeRecPtr node_ptr = OSG::Node::create();
#ifdef OSG_MT_FIELDCONTAINERPTRX
    OSG::Node* node_cptr = get_pointer(node_ptr);
#else
    OSG::Node* node_cptr = node_ptr;
#endif

#ifdef OSG_MT_FIELDCONTAINERPTRX
    OSG::NodeRecPtr node_rptr(OSG::Node::create());
    node_cptr = get_pointer(node_rptr);
#endif

    node_ptr = NULL;
}

#include <OSGBaseInitFunctions.h>
#include <OSGNode.h>
#include <OSGNodeCore.h>
//#include <OSGRefPtr.h>

int main (int argc, char **argv)
{
    OSG::osgInit(argc, argv);

    // Test getting pointers
    OSG::NodeRecPtr node_ptr = OSG::Node::create();
#ifdef OSG_MT_FIELDCONTAINERPTRX
    OSG::Node* node_cptr = get_pointer(node_ptr);
#else
    OSG::Node* node_cptr = node_ptr;
#endif

#ifdef OSG_MT_FIELDCONTAINERPTRX
    OSG::NodeRecPtr node_rptr(OSG::Node::create());
    node_cptr = get_pointer(node_rptr);
#endif

   // Test Weak ref count ptrs
   {
      OSG::NodeRecPtr node_ptr(OSG::Node::create());
      OSG::NodeWeakPtr node_weak(node_ptr);
      OSG_ASSERT(NULL != node_ptr);
      OSG_ASSERT(NULL != node_weak);

      node_ptr = NULL;

      OSG_ASSERT(NULL == node_ptr);
      OSG_ASSERT(NULL == node_weak);
    }

   {
      OSG::NodeMTRecPtr node_ptr(OSG::Node::create());
      OSG::NodeMTWeakPtr node_weak(node_ptr);
      OSG_ASSERT(NULL != node_ptr);
      OSG_ASSERT(NULL != node_weak);

      node_ptr = NULL;

      OSG_ASSERT(NULL == node_ptr);
      OSG_ASSERT(NULL == node_weak);
    }

    node_ptr = NULL;
}

Add a test to show bug in MTWeakPtr types.

git-svn-id: 6c7e10cdde2c115f53707ba8ec4efe535f92d362@1831 4683daeb-ad0f-0410-a623-93161e962ae5


// RUN: %clang_cc1 -analyze -analyzer-checker=core -analyzer-output=text -verify %s

struct S {
  int *x;
  int y;
};

S &getSomeReference();
void test(S *p) {
  S &r = *p;   //expected-note {{'r' initialized here}}
  if (p) return;
               //expected-note@-1{{Taking false branch}}
               //expected-note@-2{{Assuming 'p' is null}}
  r.y = 5; // expected-warning {{Access to field 'y' results in a dereference of a null pointer (loaded from variable 'r')}}
           // expected-note@-1{{Access to field 'y' results in a dereference of a null pointer (loaded from variable 'r')}}
}

void testRefParam(int *ptr) {
	int &ref = *ptr; // expected-note {{'ref' initialized here}}
	if (ptr)
    // expected-note@-1{{Assuming 'ptr' is null}}
    // expected-note@-2{{Taking false branch}}
		return;

	extern void use(int &ref);
	use(ref); // expected-warning{{Forming reference to null pointer}}
            // expected-note@-1{{Forming reference to null pointer}}
}

[analyzer] Add test case for reference to null pointer param check

This tests that we track the original Expr if getDerefExpr fails.

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@176754 91177308-0d34-0410-b5e6-96231b3b80d8


#include "one_to_one_test.h"

using namespace std;

OneToOneTest::OneToOneTest() {}

TestError OneToOneTest::setUp() {
    auto & im = InstanceManager::getInstance();

    im.startMs();

    left = im.nextNonColidingApp();
    right = im.nextNonColidingApp();

    left->run();
    right->run();
    std::this_thread::sleep_for(std::chrono::milliseconds(500));

    importPath = "one-to-one-import.dat";
    exportPath = "one-to-one-export.dat";

    auto err = generateFile(importPath, (1 << 20) * 2);
    if (!err.first) {
        return err;
    }

    return TestError{true, ""};
}

TestError OneToOneTest::tearDown() {
    InstanceManager::getInstance().clear();
    return TestError{true, ""};
}

TestError OneToOneTest::run() {
    if (!left->importFile(importPath)) {
        return TestError{false, ""};
    }

    if (!left->exportFile(importPath, exportPath)) {
        return TestError{false, ""};
    }

    auto err = removeFile(importPath);
    if (!err.first) {
        return err;
    }

    return filesEqual(importPath, exportPath);
}

#include "one_to_one_test.h"

using namespace std;

OneToOneTest::OneToOneTest() {}

TestError OneToOneTest::setUp() {
    auto & im = InstanceManager::getInstance();

    im.startMs();

    left = im.nextNonColidingApp();
    right = im.nextNonColidingApp();

    left->run();
    right->run();
    std::this_thread::sleep_for(std::chrono::milliseconds(500));

    importPath = "one-to-one-import.dat";
    exportPath = "one-to-one-export.dat";

    auto err = generateFile(importPath, (1 << 20) * 2);
    if (!err.first) {
        return err;
    }

    string toRemove = this->importPath;
    atDtor.push_back([toRemove] {
        removeFile(toRemove);
    });

    return TestError{true, ""};
}

TestError OneToOneTest::tearDown() {
    InstanceManager::getInstance().clear();
    return TestError{true, ""};
}

TestError OneToOneTest::run() {
    if (!left->importFile(importPath)) {
        return TestError{false, ""};
    }

    if (!left->exportFile(importPath, exportPath)) {
        return TestError{false, ""};
    }

    auto result = filesEqual(importPath, exportPath);

    removeFile(exportPath);

    return result;
}

Fix file remove for 1 to 1 test

Fix file remove for 1 to 1 test


#define BOOST_TEST_MODULE Gridcoin Test Suite
#include <boost/test/unit_test.hpp>

#include "db.h"
#include "main.h"
#include "wallet.h"

CWallet* pwalletMain;
CClientUIInterface uiInterface;

extern bool fPrintToConsole;
extern void noui_connect();

struct TestingSetup {
    TestingSetup() {
        fPrintToDebugger = true; // don't want to write to debug.log file
        fUseFastIndex = true; // Don't verify block hashes when loading
        noui_connect();
        bitdb.MakeMock();
        LoadBlockIndex(true);
        bool fFirstRun;
        pwalletMain = new CWallet("wallet.dat");
        pwalletMain->LoadWallet(fFirstRun);
        RegisterWallet(pwalletMain);
    }
    ~TestingSetup()
    {
        delete pwalletMain;
        pwalletMain = NULL;
        bitdb.Flush(true);
    }
};

BOOST_GLOBAL_FIXTURE(TestingSetup);

void Shutdown(void* parg)
{
  exit(0);
}

void StartShutdown()
{
  exit(0);
}

#define BOOST_TEST_MODULE Gridcoin Test Suite
#include <boost/test/unit_test.hpp>

#include "db.h"
#include "main.h"
#include "wallet.h"

CWallet* pwalletMain;
CClientUIInterface uiInterface;

extern bool fPrintToConsole;
extern void noui_connect();

struct TestingSetup {
    TestingSetup() {
        fPrintToDebugger = true; // don't want to write to debug.log file
        fUseFastIndex = true; // Don't verify block hashes when loading
        noui_connect();
        bitdb.MakeMock();
        bool fFirstRun;
        pwalletMain = new CWallet("wallet.dat");
        pwalletMain->LoadWallet(fFirstRun);
        RegisterWallet(pwalletMain);
    }
    ~TestingSetup()
    {
        delete pwalletMain;
        pwalletMain = NULL;
        bitdb.Flush(true);
    }
};

BOOST_GLOBAL_FIXTURE(TestingSetup);

void Shutdown(void* parg)
{
  exit(0);
}

void StartShutdown()
{
  exit(0);
}

Remove chain loading on test init.

Remove chain loading on test init.


#include "projet.h"
#include <QtDebug>
#include <QProcess>

Projet::Projet(QString &name, QDir &workspace, QFile &video, int frequence)
{
    if(workspace.exists())
    {
        if(video.exists())
        {
            if(workspace.mkdir(name))
            {
                _project = new QDir(workspace.path()+"/"+name);
                qDebug() << _project->path();
                _project->mkdir("input");
                video.copy(_project->path()+"/input/video");
                _video = new QFile(_project->path()+"/input/video");

                QProcess process;
                process.startDetached("avconv -i " + _project->path() +"/input/video -vsync 1 -r 8 -y " + _project->path() + "/input/img%d.jpg");
            }
            else
            {
                throw QString("Ce projet existe déjà");
            }
        }
        else
        {
            throw QString("La vidéo n'existe pas");
        }
    }
    else
    {
        throw QString("Le workspace n'existe pas");
    }
}

#include "projet.h"
#include <QtDebug>
#include <QProcess>

Projet::Projet(QString &name, QDir &workspace, QFile &video, int frequence)
{
    if(workspace.exists())
    {
        if(video.exists())
        {
            if(workspace.mkdir(name))
            {
                _project = new QDir(workspace.path()+"/"+name);
                qDebug() << _project->path();
                _project->mkdir("input");
                video.copy(_project->path()+"/input/video");
                _video = new QFile(_project->path()+"/input/video");

                QProcess process;
                process.startDetached("avconv -i " + _project->path() +"/input/video -vsync 1 -r " +  QString::number(frequence) + " -y " + _project->path() + "/input/img%d.jpg");
            }
            else
            {
                throw QString("Ce projet existe déjà");
            }
        }
        else
        {
            throw QString("La vidéo n'existe pas");
        }
    }
    else
    {
        throw QString("Le workspace n'existe pas");
    }
}

Add frequence to image extraction

Add frequence to image extraction


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

#include "content/browser/renderer_host/render_view_host_observer.h"

#include "content/browser/renderer_host/render_view_host.h"

RenderViewHostObserver::RenderViewHostObserver(RenderViewHost* render_view_host)
    : render_view_host_(render_view_host),
      routing_id_(render_view_host->routing_id()) {
  render_view_host_->AddObserver(this);
}

RenderViewHostObserver::~RenderViewHostObserver() {
  if (render_view_host_)
    render_view_host_->RemoveObserver(this);
}

void RenderViewHostObserver::RenderViewHostDestroyed() {
  delete this;
}

bool RenderViewHostObserver::OnMessageReceived(const IPC::Message& message) {
  return false;
}

bool RenderViewHostObserver::Send(IPC::Message* message) {
  if (!render_view_host_) {
    delete message;
    return false;
  }

  return render_view_host_->Send(message);
}

void RenderViewHostObserver::RenderViewHostDestruction() {
  render_view_host_->RemoveObserver(this);
  RenderViewHostDestroyed();
  render_view_host_ = NULL;
}

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

#include "content/browser/renderer_host/render_view_host_observer.h"

#include "content/browser/renderer_host/render_view_host.h"

RenderViewHostObserver::RenderViewHostObserver(RenderViewHost* render_view_host)
    : render_view_host_(render_view_host),
      routing_id_(render_view_host->routing_id()) {
  render_view_host_->AddObserver(this);
}

RenderViewHostObserver::~RenderViewHostObserver() {
  if (render_view_host_)
    render_view_host_->RemoveObserver(this);
}

void RenderViewHostObserver::RenderViewHostDestroyed() {
  delete this;
}

bool RenderViewHostObserver::OnMessageReceived(const IPC::Message& message) {
  return false;
}

bool RenderViewHostObserver::Send(IPC::Message* message) {
  if (!render_view_host_) {
    delete message;
    return false;
  }

  return render_view_host_->Send(message);
}

void RenderViewHostObserver::RenderViewHostDestruction() {
  render_view_host_ = NULL;
  RenderViewHostDestroyed();
}

Fix heap corruption that occurs when RenderViewHostObserver calls RenderViewHost to unregister when the latter is in its destructor.

TBR=dmichael
Review URL: http://codereview.chromium.org/6813043

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@80946 0039d316-1c4b-4281-b951-d872f2087c98


#include "read_private.h"

int buffered_io::init() {
	int ret;

	for (int i = 0; i < num; i++) {
		fds[i] = open(file_names[i], flags);
		if (fds[i] < 0) {
			perror("open");
			exit (1);
		}
		ret = posix_fadvise(fds[i], 0, 0, POSIX_FADV_RANDOM);
		if (ret < 0) {
			perror("posix_fadvise");
			exit(1);
		}
	}
	return 0;
}

ssize_t buffered_io::access(char *buf, off_t offset, ssize_t size, int access_method) {
	int fd = get_fd(offset);
#ifdef STATISTICS
	if (access_method == READ)
		num_reads++;
	struct timeval start, end;
	gettimeofday(&start, NULL);
#endif
	ssize_t ret;
	if (access_method == WRITE)
		ret = pwrite(fd, buf, size, offset);
	else
		ret = pread(fd, buf, size, offset);
#ifdef STATISTICS
	gettimeofday(&end, NULL);
	read_time += ((long) end.tv_sec - start.tv_sec) * 1000000 + end.tv_usec - start.tv_usec;
#endif
	return ret;
}

#include "read_private.h"

int buffered_io::init() {
	int ret;

	for (int i = 0; i < num; i++) {
		fds[i] = open(file_names[i], flags);
		if (fds[i] < 0) {
			perror("open");
			exit (1);
		}
		ret = posix_fadvise(fds[i], 0, 0, POSIX_FADV_RANDOM);
		if (ret < 0) {
			perror("posix_fadvise");
			exit(1);
		}
	}
	return 0;
}

ssize_t buffered_io::access(char *buf, off_t offset, ssize_t size, int access_method) {
	int fd = get_fd(offset);
#ifdef STATISTICS
	if (access_method == READ)
		num_reads++;
	struct timeval start, end;
	gettimeofday(&start, NULL);
#endif
	ssize_t ret;
	if (access_method == WRITE)
		ret = pwrite(fd, buf, size, offset);
	else
		ret = pread(fd, buf, size, offset);
	if (ret < 0) {
		perror("pread");
		abort();
	}
#ifdef STATISTICS
	gettimeofday(&end, NULL);
	read_time += ((long) end.tv_sec - start.tv_sec) * 1000000 + end.tv_usec - start.tv_usec;
#endif
	return ret;
}

Abort if read syscall fails.

Abort if read syscall fails.

It may help debug.


// RUN: %llvmgxx %s -S -o - | grep '%XX = global int 4'

struct S {
  int  A[2];
};

int XX = (int)&(((struct S*)0)->A[1]);

// RUN: %llvmgxx %s -S -o - | not grep 'llvm.global_ctor'

struct S {
  int  A[2];
};

int XX = (int)&(((struct S*)0)->A[1]);

Adjust this test to pass after recent CFE changes.  We now generate:

%XX = global int cast (int* getelementptr ([2 x int]* getelementptr (%struct.S* null, int 0, uint 0), int 0, int 1) to int)

which is the literal translation of the testcase :)

git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@20247 91177308-0d34-0410-b5e6-96231b3b80d8


#include "../Physics/Shape.hpp"
#include "../Util/Json.hpp"
#include "Shape.hpp"

namespace Component {
    Json::Value Shape::Save() const {
        Json::Value component;

        Json::Value concreteShape;
        switch (shape->GetKind()) {
            case ::Physics::Shape::Kind::Sphere: {
                auto sphereData = shape->GetSphereData();
                concreteShape["radius"] = sphereData->radius;
                component["sphere"] = concreteShape;
                break;
            }
            case ::Physics::Shape::Kind::Plane: {
                auto planeData = shape->GetPlaneData();
                concreteShape["normal"] = Json::SaveVec3(planeData->normal);
                concreteShape["planeCoeff"] = planeData->planeCoeff;
                component["plane"] = concreteShape;
                break;
            }
        }

        return component;
    }

    std::shared_ptr<::Physics::Shape> Shape::GetShape() const {
        return shape;
    }

    void Shape::SetShape(std::shared_ptr<::Physics::Shape> shape) {
        this->shape = shape;
    }
}

#include <Utility/Log.hpp>
#include "../Physics/Shape.hpp"
#include "../Util/Json.hpp"
#include "Shape.hpp"

namespace Component {
    Json::Value Shape::Save() const {
        Json::Value component;

        Json::Value concreteShape;
        switch (shape->GetKind()) {
            case Physics::Shape::Kind::Sphere: {
                auto sphereData = shape->GetSphereData();
                concreteShape["radius"] = sphereData->radius;
                component["sphere"] = concreteShape;
                break;
            }
            case Physics::Shape::Kind::Plane: {
                auto planeData = shape->GetPlaneData();
                concreteShape["normal"] = Json::SaveVec3(planeData->normal);
                concreteShape["planeCoeff"] = planeData->planeCoeff;
                component["plane"] = concreteShape;
                break;
            }
            case Physics::Shape::Kind::Box: {
                auto boxData = shape->GetBoxData();
                concreteShape["width"] = boxData->width;
                concreteShape["height"] = boxData->height;
                concreteShape["depth"] = boxData->depth;
                component["box"] = concreteShape;
                break;
            }
            default:
                Log(Log::ERR) << "Component::Shape::Save: Unsupported shape `" << static_cast<uint32_t>(shape->GetKind()) << "`.\n";
        }

        return component;
    }

    std::shared_ptr<Physics::Shape> Shape::GetShape() const {
        return shape;
    }

    void Shape::SetShape(std::shared_ptr<Physics::Shape> shape) {
        this->shape = shape;
    }
}

Save box shape to JSON.

Save box shape to JSON.


#include "./coordinate_system_node.h"
#include <Eigen/Core>

CoordinateSystemNode::CoordinateSystemNode()
{
  persistable = false;

  x = std::make_shared<Graphics::Connector>(Eigen::Vector3f(0, 0, 0),
                                            Eigen::Vector3f(1, 0, 0));
  x->color = Eigen::Vector4f(1, 0, 0, 1);

  y = std::make_shared<Graphics::Connector>(Eigen::Vector3f(0, 0, 0),
                                            Eigen::Vector3f(0, 1, 0));
  y->color = Eigen::Vector4f(0, 1, 0, 1);

  z = std::make_shared<Graphics::Connector>(Eigen::Vector3f(0, 0, 0),
                                            Eigen::Vector3f(0, 0, 1));
  z->color = Eigen::Vector4f(0, 0, 1, 1);
}

CoordinateSystemNode::~CoordinateSystemNode()
{
}

void CoordinateSystemNode::render(Graphics::Gl *gl,
                                  std::shared_ptr<Graphics::Managers> managers,
                                  RenderData renderData)
{
  x->render(gl, managers, renderData);
  y->render(gl, managers, renderData);
  z->render(gl, managers, renderData);
}

#include "./coordinate_system_node.h"
#include <Eigen/Core>

CoordinateSystemNode::CoordinateSystemNode()
{
  persistable = false;

  x = std::make_shared<Graphics::Connector>(Eigen::Vector3f(0, 0, 0),
                                            Eigen::Vector3f(1, 0, 0));
  x->color = Eigen::Vector4f(1, 0, 0, 1);

  y = std::make_shared<Graphics::Connector>(Eigen::Vector3f(0, 0, 0),
                                            Eigen::Vector3f(0, 1, 0));
  y->color = Eigen::Vector4f(0, 1, 0, 1);

  z = std::make_shared<Graphics::Connector>(Eigen::Vector3f(0, 0, 0),
                                            Eigen::Vector3f(0, 0, 1));
  z->color = Eigen::Vector4f(0, 0, 1, 1);

  obb = Math::Obb(Eigen::Vector3f(0, 0, 0), Eigen::Vector3f(1, 1, 1),
                  Eigen::Matrix3f::Identity());
}

CoordinateSystemNode::~CoordinateSystemNode()
{
}

void CoordinateSystemNode::render(Graphics::Gl *gl,
                                  std::shared_ptr<Graphics::Managers> managers,
                                  RenderData renderData)
{
  x->render(gl, managers, renderData);
  y->render(gl, managers, renderData);
  z->render(gl, managers, renderData);
}

Initialize bounding box for coordinate system node.


/*

Name: Velvet
Author: Alvy Piper (no contact email currently)
CSGO adaptation: aixxe <aixxe@skyenet.org>
Copyright: 2015
Usage: More complex than GreenTea and also SDKless. A simple internal cheat with bunnyhop and norecoil, written for CSPromod BETA 1.10b for fun.
Using content created by: Casual_Hacker ( http://www.unknowncheats.me/forum/member239231.html ), NanoCat, and Valve.

Any content creator that wants their work removed can contact me on UnknownCheats for now. ( http://www.unknowncheats.me/forum/member334125.html )

Feel free to redistribute, modify, and share. Please give credit where it is due, though.

*/

#include "velvet.h"

using namespace velvet;

void inject() //TODO: Change this with init::finalize in DLLMain.
{
	init::finalize();
}

bool __stdcall entry(HINSTANCE inst, DWORD reason, LPVOID reserved)
{
	if (reason == 1)
	{
		DisableThreadLibraryCalls(inst);
		CreateThread(0, 0, (LPTHREAD_START_ROUTINE) inject, 0, 0, 0);
	}
	TerminateThread(inject, 0);
	return 1;
}

/*

Name: Velvet
Author: Alvy Piper (no contact email currently)
CSGO adaptation: aixxe <aixxe@skyenet.org>
Copyright: 2015
Usage: More complex than GreenTea and also SDKless. A simple internal cheat with bunnyhop and norecoil, written for CSPromod BETA 1.10b for fun.
Using content created by: Casual_Hacker ( http://www.unknowncheats.me/forum/member239231.html ), NanoCat, and Valve.

Any content creator that wants their work removed can contact me on UnknownCheats for now. ( http://www.unknowncheats.me/forum/members/334125.html )

Feel free to redistribute, modify, and share. Please give credit where it is due, though.

*/

#include "velvet.h"

using namespace velvet;

void inject() //TODO: Change this with init::finalize in DLLMain.
{
	init::finalize();
}

bool __stdcall entry(HINSTANCE inst, DWORD reason, LPVOID reserved)
{
	if (reason == 1)
	{
		DisableThreadLibraryCalls(inst);
		CreateThread(0, 0, (LPTHREAD_START_ROUTINE) inject, 0, 0, 0);
	}
	TerminateThread(inject, 0);
	return 1;
}

Fix contact link (Thanks SippieCup)

Fix contact link (Thanks SippieCup)


//----------------------------  parameter_handler_1.cc  ---------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 2002, 2003 by the deal.II authors and Anna Schneebeli
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------  parameter_handler_1.cc  ---------------------------

// check the Patterns::List pattern

#include <base/logstream.h>
#include <base/parameter_handler.h>
#include <fstream>

void check (const char *p)
{
  ParameterHandler prm;
  prm.declare_entry ("test_1", "-1,0",
                     Patterns::List(Patterns::Integer(-1,1),2,3));

  std::ifstream in(p);
  prm.read_input (in);

  deallog << "test_1=" << prm.get ("test_1") << std::endl;
}

int main ()
{
  std::ofstream logfile("parameter_handler_1.output");
  deallog.attach(logfile);
  deallog.depth_console(0);

  check ("parameter_handler_1.prm1");

  return 0;
}

//----------------------------  parameter_handler_1.cc  ---------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 2002, 2003 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------  parameter_handler_1.cc  ---------------------------

// check the Patterns::List pattern

#include <base/logstream.h>
#include <base/parameter_handler.h>
#include <fstream>

void check (const char *p)
{
  ParameterHandler prm;
  prm.declare_entry ("test_1", "-1,0",
                     Patterns::List(Patterns::Integer(-1,1),2,3));

  std::ifstream in(p);
  prm.read_input (in);

  deallog << "test_1=" << prm.get ("test_1") << std::endl;
}

int main ()
{
  std::ofstream logfile("parameter_handler_1.output");
  deallog.attach(logfile);
  deallog.depth_console(0);

  check ("parameter_handler_1.prm1");

  return 0;
}

Remove incorrect credit of authorship.

Remove incorrect credit of authorship.

git-svn-id: 31d9d2f6432a47c86a3640814024c107794ea77c@7586 0785d39b-7218-0410-832d-ea1e28bc413d