/** @example user_touche.cpp
 Touche example.
 */

#include <ESP.h>

BinaryIntArraySerialStream stream(0, 115200, 160);
GestureRecognitionPipeline pipeline;

void setup()
{
    useInputStream(stream);

    pipeline.addFeatureExtractionModule(TimeseriesBuffer(1, 160));
    usePipeline(pipeline);
}

/** @example user_touche.cpp
 Touche example.
 */

#include <ESP.h>

BinaryIntArraySerialStream stream(0, 115200, 160);
GestureRecognitionPipeline pipeline;

void setup()
{
    useInputStream(stream);

    pipeline.addFeatureExtractionModule(TimeseriesBuffer(1, 160));
    pipeline.setClassifier(SVM(SVM::POLY_KERNEL, SVM::C_SVC, false, true, true, 0.1, 1.0, 0, 0.5, 2));
    usePipeline(pipeline);
}

Add SVM classifier to Touche example.

Add SVM classifier to Touche example.

It seems to do some (very) basic recognition successfully, so I’m
saying that this fixes #245, although I think it still needs lots of
work.


/**
 * Unit tests for base kernel class
 * @author Vyacheslav Kompan kompan.vo@phystech.edu
 * Copyright 2018 MIPT-MIPS
 */

#include "../kernel.h"
// Catch2
#include <catch.hpp>

TEST_CASE( "Kernel: Execute nothing")
{
    CHECK( Kernel::create_dummy_kernel()->execute() == Trap::SYSCALL);
    CHECK( Kernel::create_configured_kernel()->execute() == Trap::SYSCALL);
}

/**
 * Unit tests for base kernel class
 * @author Vyacheslav Kompan kompan.vo@phystech.edu
 * Copyright 2018 MIPT-MIPS
 */

#include "../kernel.h"
#include <catch.hpp>

TEST_CASE( "Kernel: Execute nothing")
{
    CHECK( Kernel::create_dummy_kernel()->execute() == Trap::SYSCALL);
    CHECK( Kernel::create_configured_kernel()->execute() == Trap::SYSCALL);
    CHECK_NOTHROW( Kernel::create_dummy_kernel()->set_simulator( nullptr));
    CHECK_NOTHROW( Kernel::create_dummy_kernel()->connect_memory( nullptr));
    CHECK_NOTHROW( Kernel::create_dummy_kernel()->add_replica_simulator( nullptr));
    CHECK_NOTHROW( Kernel::create_dummy_kernel()->add_replica_memory( nullptr));
}

Add unit tests for dummy kernel

Add unit tests for dummy kernel


// Copyright (c) 2014-2015 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/

#include <string>
#include <iostream>

#include <pegtl.hh>

namespace hello
{
   struct prefix : pegtl::string< 'H', 'e', 'l', 'l', 'o', ',', ' ' > {};
   struct name : pegtl::plus< pegtl::alpha > {};
   struct grammar : pegtl::seq< prefix, name, pegtl::one< '!' >, pegtl::eof > {};

   template< typename Rule >
   struct action
         : pegtl::nothing< Rule > {};

   template<> struct action< name >
   {
      static void apply( const pegtl::input & in, std::string & name )
      {
         name = in.string();
      }
   };
}

int main( int argc, char * argv[] )
{
   if ( argc > 1 ) {
      std::string name;
      pegtl::parse< hello::grammar, hello::action >( 1, argv, name );
      std::cout << "Good bye, " << name << "!" << std::endl;
   }
}

// Copyright (c) 2014-2015 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/

#include <string>
#include <iostream>

#include <pegtl.hh>

namespace hello
{
   struct prefix : pegtl::string< 'H', 'e', 'l', 'l', 'o', ',', ' ' > {};
   struct name : pegtl::plus< pegtl::alpha > {};
   struct grammar : pegtl::must< prefix,
                                 name,
                                 pegtl::one< '!' >,
                                 pegtl::eof > {};

   template< typename Rule >
   struct action
         : pegtl::nothing< Rule > {};

   template<> struct action< name >
   {
      static void apply( const pegtl::input & in,
                         std::string & name )
      {
         name = in.string();
      }
   };
}

int main( int argc, char * argv[] )
{
   if ( argc > 1 ) {
      std::string name;
      pegtl::parse< hello::grammar, hello::action >( 1,
                                                     argv,
                                                     name );
      std::cout << "Good bye, " << name << "!" << std::endl;
   }
}

Use top-level must<> instead of seq<>

Use top-level must<> instead of seq<>


#include "helper.h"
#include "../lib/triangle.h"

#include <catch.hpp>

TEST_CASE("Test Triangle normal", "[triangle]")
{
    static constexpr int NUM_SAMPLES = 100;

    for (int j = 0; j < NUM_SAMPLES; ++j) {
        Triangle triangle = random_triangle();

        Vec normal = triangle.normal;

        // Verify unit lenght of normal.
        float length = normal.Length();
        REQUIRE(length == Approx(1.f));

        // Verify normal is perpendicular to edges of triangle.
        float cos_u = normal * triangle.u.Normalize();
        float cos_v = normal * triangle.v.Normalize();
        REQUIRE(cos_u == Approx(0.f));
        REQUIRE(cos_v == Approx(0.f));
    }
}

#include "helper.h"
#include "../lib/triangle.h"

#include <catch.hpp>

TEST_CASE("Test Triangle normal", "[triangle]")
{
    static constexpr int NUM_SAMPLES = 100;

    for (int j = 0; j < NUM_SAMPLES; ++j) {
        Triangle triangle = random_triangle();

        Vec normal = triangle.normal;

        // Verify unit length of normal.
        float length = normal.Length();
        REQUIRE(length == Approx(1.f));

        // Verify normal is perpendicular to edges of triangle.
        float cos_u = normal * triangle.u.Normalize();
        float cos_v = normal * triangle.v.Normalize();
        REQUIRE(cos_u == Approx(0.f));
        REQUIRE(cos_v == Approx(0.f));
    }
}

TEST_CASE("Test interpolate triangle normal", "[triangle]")
{
    static constexpr int NUM_SAMPLES = 100;

    for (int j = 0; j < NUM_SAMPLES; ++j) {
        Triangle triangle = test_triangle( random_vec(), random_vec(),
            random_vec(), random_vec().Normalize(), random_vec().Normalize(),
            random_vec().Normalize());

        float r = uniform();
        float s = uniform();
        float t = uniform();
        while( r+s+t > 1.0f) {
          r = uniform();
          s = uniform();
          t = uniform();
        }
        Vec normal = triangle.interpolate_normal(r, s, t);

        // Verify unit length of normal.
        float length = normal.Length();
        REQUIRE(length == Approx(1.f));
    }
}

Test normal interpolation for triangle.

Test normal interpolation for triangle.

Former-commit-id: a46fef6e00bf1abf590189b3de39bab42928540b


#include "xchainer/device.h"

#include <future>

#include <gtest/gtest.h>
#include "xchainer/error.h"

namespace xchainer {

TEST(DeviceTest, SetCurrentDevice) {
    Device cpu = {"cpu"};
    Device cuda = {"cuda"};
    auto device = GetCurrentDevice();

    SetCurrentDevice("cpu");
    ASSERT_EQ(cpu, GetCurrentDevice());

    SetCurrentDevice(cuda);
    ASSERT_EQ(cuda, GetCurrentDevice());

    ASSERT_THROW(SetCurrentDevice("invalid_device"), DeviceError);

    SetCurrentDevice(device);
}

TEST(DeviceTest, ThreadLocal) {
    auto device = GetCurrentDevice();

    SetCurrentDevice("cpu");
    auto future = std::async(std::launch::async, [] {
        SetCurrentDevice("cuda");
        return GetCurrentDevice();
    });
    ASSERT_NE(GetCurrentDevice(), future.get());

    SetCurrentDevice(device);
}

}  // namespace

#include "xchainer/device.h"

#include <future>

#include <gtest/gtest.h>
#include "xchainer/error.h"

namespace xchainer {

// Device must be POD (plain old data) to be used as a thread local variable safely.
// ref. https://google.github.io/styleguide/cppguide.html#Static_and_Global_Variables
static_assert(std::is_pod<Device>::value, "Device must be POD");

TEST(DeviceTest, SetCurrentDevice) {
    Device cpu = {"cpu"};
    Device cuda = {"cuda"};
    auto device = GetCurrentDevice();

    SetCurrentDevice("cpu");
    ASSERT_EQ(cpu, GetCurrentDevice());

    SetCurrentDevice(cuda);
    ASSERT_EQ(cuda, GetCurrentDevice());

    ASSERT_THROW(SetCurrentDevice("invalid_device"), DeviceError);

    SetCurrentDevice(device);
}

TEST(DeviceTest, ThreadLocal) {
    auto device = GetCurrentDevice();

    SetCurrentDevice("cpu");
    auto future = std::async(std::launch::async, [] {
        SetCurrentDevice("cuda");
        return GetCurrentDevice();
    });
    ASSERT_NE(GetCurrentDevice(), future.get());

    SetCurrentDevice(device);
}

}  // namespace

Add tests to check Device is POD

Add tests to check Device is POD


// RUN: %clang  -g -S -emit-llvm %s -o - | FileCheck %s

namespace A {
#line 1 "foo.cpp"
namespace B {
int i;
}
}

// CHECK: [[FILE:![0-9]*]] {{.*}}debug-info-namespace.cpp"
// CHECK: [[VAR:![0-9]*]] = {{.*}}, metadata [[NS:![0-9]*]], metadata !"i", {{.*}} ; [ DW_TAG_variable ] [i]
// CHECK: [[NS]] = {{.*}}, metadata [[FILE2:![0-9]*]], null, metadata [[CTXT:![0-9]*]], {{.*}} ; [ DW_TAG_namespace ] [B] [line 1]
// CHECK: [[CTXT]] = {{.*}}, metadata [[FILE]], null, null, {{.*}} ; [ DW_TAG_namespace ] [A] [line 3]
// CHECK: {i32 {{[0-9]+}}, metadata [[FILE2]]{{.*}} ; [ DW_TAG_file_type ] [{{.*}}foo.cpp]

// FIXME: It is confused on win32 to generate file entry when dosish filename is given.
// REQUIRES: shell

// RUN: %clang  -g -S -emit-llvm %s -o - | FileCheck %s

namespace A {
#line 1 "foo.cpp"
namespace B {
int i;
}
}

// CHECK: [[FILE:![0-9]*]] {{.*}}debug-info-namespace.cpp"
// CHECK: [[VAR:![0-9]*]] = {{.*}}, metadata [[NS:![0-9]*]], metadata !"i", {{.*}} ; [ DW_TAG_variable ] [i]
// CHECK: [[NS]] = {{.*}}, metadata [[FILE2:![0-9]*]], metadata [[CTXT:![0-9]*]], {{.*}} ; [ DW_TAG_namespace ] [B] [line 1]
// CHECK: [[CTXT]] = {{.*}}, metadata [[FILE]], null, {{.*}} ; [ DW_TAG_namespace ] [A] [line 3]
// CHECK: [[FILE2]]} ; [ DW_TAG_file_type ] [{{.*}}foo.cpp]

// FIXME: It is confused on win32 to generate file entry when dosish filename is given.
// REQUIRES: shell

Revert "Update debug info test for schema change made to LLVM."

This reverts commit 5035c483b7fcbf0fa2a7afba24fa35a10995d195.

This schema change wasn't necessary after all. I'm going ith a different
solution that will hopefully use space more conservatively.

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


//
//  kern_start.cpp
//  CPUFriend
//
//  Copyright © 2017 Vanilla. All rights reserved.
//

#include <Headers/plugin_start.hpp>
#include <Headers/kern_api.hpp>

#include "kern_cpuf.hpp"

static CPUFriendPlugin cpuf;

static const char *bootargOff[] {
  "-cpufoff"
};

static const char *bootargDebug[] {
  "-cpufdbg"
};

static const char *bootargBeta[] {
  "-cpufbeta"
};

PluginConfiguration ADDPR(config) {
  xStringify(PRODUCT_NAME),
  parseModuleVersion(xStringify(MODULE_VERSION)),
  bootargOff,
  arrsize(bootargOff),
  bootargDebug,
  arrsize(bootargDebug),
  bootargBeta,
  arrsize(bootargBeta),
  KernelVersion::MountainLion,
  KernelVersion::HighSierra,
  []() {
    cpuf.init();
  }
};

//
//  kern_start.cpp
//  CPUFriend
//
//  Copyright © 2017 Vanilla. All rights reserved.
//

#include <Headers/plugin_start.hpp>
#include <Headers/kern_api.hpp>

#include "kern_cpuf.hpp"

static CPUFriendPlugin cpuf;

static const char *bootargOff[] {
  "-cpufoff"
};

static const char *bootargDebug[] {
  "-cpufdbg"
};

static const char *bootargBeta[] {
  "-cpufbeta"
};

PluginConfiguration ADDPR(config) {
  xStringify(PRODUCT_NAME),
  parseModuleVersion(xStringify(MODULE_VERSION)),
  LiluAPI::AllowNormal | LiluAPI::AllowInstallerRecovery | LiluAPI::AllowSafeMode,
  bootargOff,
  arrsize(bootargOff),
  bootargDebug,
  arrsize(bootargDebug),
  bootargBeta,
  arrsize(bootargBeta),
  KernelVersion::MountainLion,
  KernelVersion::HighSierra,
  []() {
    cpuf.init();
  }
};

Update plugin requirements for 1.2.0

Update plugin requirements for 1.2.0


// 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 "remoting/host/capturer.h"

namespace remoting {

Capturer::Capturer()
    : width_(0),
      height_(0),
      pixel_format_(PixelFormatInvalid),
      bytes_per_pixel_(0),
      bytes_per_row_(0),
      current_buffer_(0) {
}

Capturer::~Capturer() {
}

void Capturer::GetDirtyRects(DirtyRects* rects) const {
  *rects = dirty_rects_;
}

int Capturer::GetWidth() const {
  return width_;
}

int Capturer::GetHeight() const {
  return height_;
}

PixelFormat Capturer::GetPixelFormat() const {
  return pixel_format_;
}

void Capturer::InvalidateRect(gfx::Rect dirty_rect) {
  inval_rects_.push_back(dirty_rect);
}

void Capturer::FinishCapture(Task* done_task) {
  done_task->Run();
  delete done_task;

  // Select the next buffer to be the current buffer.
  current_buffer_ = ++current_buffer_ % kNumBuffers;
}

}  // namespace remoting

// 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 "remoting/host/capturer.h"

namespace remoting {

Capturer::Capturer()
    : width_(0),
      height_(0),
      pixel_format_(PixelFormatInvalid),
      bytes_per_pixel_(0),
      bytes_per_row_(0),
      current_buffer_(0) {
}

Capturer::~Capturer() {
}

void Capturer::GetDirtyRects(DirtyRects* rects) const {
  *rects = dirty_rects_;
}

int Capturer::GetWidth() const {
  return width_;
}

int Capturer::GetHeight() const {
  return height_;
}

PixelFormat Capturer::GetPixelFormat() const {
  return pixel_format_;
}

void Capturer::InvalidateRect(gfx::Rect dirty_rect) {
  inval_rects_.push_back(dirty_rect);
}

void Capturer::FinishCapture(Task* done_task) {
  done_task->Run();
  delete done_task;

  // Select the next buffer to be the current buffer.
  current_buffer_ = (current_buffer_ + 1) % kNumBuffers;
}

}  // namespace remoting

Coverity: Fix undefined assignment evaluation order in remoting::Capturer::FinishCapture.

CID=10878
BUG=none
TEST=builds

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

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


#include <avr/io.h>
#include <avr/interrupt.h>
#include "AnalogAccel.h"

volatile Axis currentAxis = X;

ISR(ANALOG_COMP_vect) //To be executed once analog compare is completed
{
	//Do stuff...
}

AnalogAccel::AnalogAccel()
{
}

AnalogAccel::~AnalogAccel()
{
}

volatile Axis& AnalogAccel::currentAxis_ = currentAxis;

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/atomic.h>
#include "AnalogAccel.h"

volatile Axis currentAxis = X;

ISR(ANALOG_COMP_vect) //To be executed once analog compare is completed
{
	//Do stuff...
}

AnalogAccel::AnalogAccel()
{
	//Prescaler of 64 (12MHz / 64 == 187.5 kHz),
	//recommended value is 50-200kHz. Also: Enable interrupt,
	//enable auto-triggering, start conversion and turn the ADC on.
	ADCSRA |= _BV(ADPS1) | _BV(ADPS2) | _BV(ADIE) | _BV(ADATE) \
		| _BV(ADSC) | _BV(ADEN);

	//Free-running mode: takes measurements as long as the ADC is enabled
	ADCSRB = 0;

	//Disable digital input buffers for those pins (saves power)
	DIDR0 |= _BV(ADC0D) | _BV(ADC1D) | _BV(ADC2D);
}

AnalogAccel::~AnalogAccel()
{
	ADCSRA &= ~_BV(ADEN); //Disable the ADC (also disables the interrupt)
}

volatile Axis& AnalogAccel::currentAxis_ = currentAxis;

Set ADC control registers in constructor


/*
**  Copyright (C) 2012 Aldebaran Robotics
**  See COPYING for the license
*/
#include <cstring>

#include <qitype/signature.hpp>

namespace qi {

bool qi::Signature::isConvertibleTo(const qi::Signature& b) const
{
  if (size() != b.size())
    return false;
  static const char numeric[] = "bcCwWiIlLfd";
  static const char container[] = "[{";
  Signature::iterator s = begin();
  Signature::iterator d = b.begin();
  for (;s!=end() && d!= b.end(); ++s,++d)
  {
    if (d.type() == Type_Dynamic)
      continue; // Dynamic can convert to whatever
    // Main switch on source sig
    if (strchr(numeric, s.type()))
    { // Numeric
      if (!strchr(numeric, d.type()))
        return false;
    }
    else if (strchr(container, s.type()))
    { // Container, list or map
      if (d.type() != s.type())
        return false; // Must be same container
      if (!s.children().isConvertibleTo(d.children()))
        return false; // Just check subtype compatibility
    }
    else
      if (d.type() != s.type())
        return false;
  }
  assert(s==end() && d==b.end()); // we allready exited on size mismatch
  return true;
}

Signature Signature::fromType(Signature::Type t)
{
  char res[2] = { (char)t, 0};
  return Signature(res);
}

}

/*
**  Copyright (C) 2012 Aldebaran Robotics
**  See COPYING for the license
*/
#include <cstring>

#include <qitype/signature.hpp>

namespace qi {

bool qi::Signature::isConvertibleTo(const qi::Signature& b) const
{
  if (size() != b.size())
    return false;
  static const char numeric[] = "bcCwWiIlLfd";
  static const char container[] = "[{(";
  Signature::iterator s = begin();
  Signature::iterator d = b.begin();
  for (;s!=end() && d!= b.end(); ++s,++d)
  {
    if (d.type() == Type_Dynamic)
      continue; // Dynamic can convert to whatever
    // Main switch on source sig
    if (strchr(numeric, s.type()))
    { // Numeric
      if (!strchr(numeric, d.type()))
        return false;
    }
    else if (strchr(container, s.type()))
    { // Container, list or map
      if (d.type() != s.type())
        return false; // Must be same container
      if (!s.children().isConvertibleTo(d.children()))
        return false; // Just check subtype compatibility
    }
    else
      if (d.type() != s.type())
        return false;
  }
  assert(s==end() && d==b.end()); // we allready exited on size mismatch
  return true;
}

Signature Signature::fromType(Signature::Type t)
{
  char res[2] = { (char)t, 0};
  return Signature(res);
}

}

Signature::isConvertibleTo: Fix a lolbug, it never worked and returned true always.

Change-Id: I93ae42a1b36d175311b940af0baf9a4e3b61f83a
Reviewed-on: http://gerrit.aldebaran.lan:8080/7221
Reviewed-by: cgestes <ddb78fe00abb42f91254c16a0860e38eb0781789@aldebaran-robotics.com>
Tested-by: mnottale <e3ccf1b6558404e921a21fa09cebb1153b50ec36@aldebaran-robotics.com>


#include "modem/commands.h"

namespace firebase {
namespace modem {

bool StreamCommand::execute(const String& command,
                            InputStream* in, OutputStream* out) {
  if (in == nullptr || out == nullptr) {
    return false;
  }

  if (command != "BEGIN_STREAM") {
    return false;
  }

  std::string path = in->readLine().c_str();
  std::unique_ptr<FirebaseStream> stream(fbase().streamPtr(path));

  if (stream->error()) {
    out->print("-FAIL ");
    out->println(stream->error().message().c_str());
    return false;
  }

  bool running = true;
  while(running) {
    if (stream->available()) {
      std::string json;
      FirebaseStream::Event event = stream->read(json);
      out->print("+");
      out->print(FirebaseStream::EventToName(event).c_str());
      out->print(" ");
      // TODO(edcoyne): add json parsing and get real path.
      out->println("/dummy/path");
      out->println(json.length());
      out->println(json.c_str());
    } else if (in->available()) {
      String command = in->readLine();
      if (command == "END_STREAM") {
        out->println("+OK");
        running = false;
      } else {
        out->println("-FAIL Cannot call any command but END_STREAM.");
      }
    }
  }

  return true;
}

}  // modem
}  // firebase

#include "modem/commands.h"

namespace firebase {
namespace modem {

bool StreamCommand::execute(const String& command,
                            InputStream* in, OutputStream* out) {
  if (in == nullptr || out == nullptr) {
    return false;
  }

  if (command != "BEGIN_STREAM") {
    return false;
  }

  std::string path = in->readLine().c_str();
  std::unique_ptr<FirebaseStream> stream(fbase().streamPtr(path));

  if (stream->error()) {
    out->print("-FAIL ");
    out->println(stream->error().message().c_str());
    return false;
  }

  bool running = true;
  DynamicJsonBuffer buffer;
  while(running) {
    if (stream->available()) {
      std::string json;
      FirebaseStream::Event event = stream->read(json);
      out->print("+");
      out->print(FirebaseStream::EventToName(event).c_str());
      out->print(" ");
      const auto& object = buffer.parseObject(json.c_str());
      String data = object["data"];
      out->println(object["path"].asString());
      out->println(data.length());
      out->println(data);
    } else if (in->available()) {
      String command = in->readLine();
      if (command == "END_STREAM") {
        out->println("+OK");
        running = false;
      } else {
        out->println("-FAIL Cannot call any command but END_STREAM.");
      }
    }
  }

  return true;
}

}  // modem
}  // firebase

Add json parsing to modem streaming

Add json parsing to modem streaming


#include "helpers.h"

using namespace std;

void sendFail(UserHandler * handler, int errorcode, string topic, string message){
    JsonDict answer;

    JsonBool b = JsonBool(false);
    JsonString s = JsonString(message);
    answer.add("success", &b);
    answer.add("reason", &s);
    handler->writeToClient(topic, &answer);
}

#include "helpers.h"

using namespace std;

void sendFail(UserHandler * handler, int errorcode, string topic, string message){
    JsonDict answer;

    JsonBool b = JsonBool(false);
    JsonString s = JsonString(message);
    JsonInt i = JsonInt(errorcode);
    answer.add("success", &b);
    answer.add("reason", &s);
    answer.add("code", &i);
    handler->writeToClient(topic, &answer);
}

Add an error code with sendFail

Add an error code with sendFail


#include "python_script.h"

#include <cstdio>
#include <fstream>
#include <iterator>

#include <boost/log/trivial.hpp>

#include <boost/python.hpp>
#include <Python.h>

using namespace boost::python;
using namespace std;
using namespace swganh::scripting;

PythonScript::PythonScript(const string& filename)
        : filename_(filename)
{
    ReadFileContents();

    Py_Initialize();

	try
    {
		boost::python::object main = boost::python::object (boost::python::handle<>(boost::python::borrowed(
			PyImport_AddModule("__main__")
		)));

        globals_ = main.attr("__dict__");
        globals_["swganh"] = boost::python::import("py_swganh");
		globals_["context"] = dict();
    }
    catch (error_already_set &)
    {
        PyErr_Print();
    }
}

void PythonScript::Run()
{
	try
    {
#ifdef _DEBUG
        ReadFileContents();
#endif
		file_object_ = exec(filecontents_.c_str(), globals_, globals_);
    }
    catch (error_already_set &)
    {
        PyErr_Print();
    }
}

void PythonScript::ReadFileContents()
{
    ifstream filestream(filename_);
    filestream >> noskipws;

    filecontents_ = string(
        (istreambuf_iterator<char>(filestream)),
        istreambuf_iterator<char>());
}

#include "python_script.h"

#include <cstdio>
#include <fstream>
#include <iterator>

#include <boost/log/trivial.hpp>

#include <boost/python.hpp>
#include <Python.h>

using namespace boost::python;
using namespace std;
using namespace swganh::scripting;

PythonScript::PythonScript(const string& filename)
        : filename_(filename)
{
    ReadFileContents();

    Py_Initialize();

	try
    {
        PyRun_SimpleString("import sys; sys.path.append('.');");

		boost::python::object main = boost::python::object (boost::python::handle<>(boost::python::borrowed(
			PyImport_AddModule("__main__")
		)));

        globals_ = main.attr("__dict__");
        globals_["swganh"] = boost::python::import("py_swganh");
		globals_["context"] = dict();
    }
    catch (error_already_set &)
    {
        PyErr_Print();
    }
}

void PythonScript::Run()
{
	try
    {
#ifdef _DEBUG
        ReadFileContents();
#endif
        BOOST_LOG_TRIVIAL(info) << "Executing script: " << filename_;
		file_object_ = exec(filecontents_.c_str(), globals_, globals_);
    }
    catch (error_already_set &)
    {
        PyErr_Print();
    }
}

void PythonScript::ReadFileContents()
{
    ifstream filestream(filename_);
    filestream >> noskipws;

    filecontents_ = string(
        (istreambuf_iterator<char>(filestream)),
        istreambuf_iterator<char>());
}

Add the current directory to the path.

Add the current directory to the path.


#include "UIUtils.h"

#include <sstream>

#include "Settings.h"

std::vector<CPropertyPage *> UIUtils::pages = { };

CString UIUtils::Capitalize(std::wstring in) {
    CString cstr(in.c_str());
    return UIUtils::Capitalize(cstr);
}

CString UIUtils::Capitalize(CString in) {
    CString newString(in);
    CString firstLetter = newString.Left(1).MakeUpper();
    newString = firstLetter + newString.Mid(1);
    return newString;
}

int UIUtils::TextToInt(CWnd &wnd) {
    int num;
    CString text;
    wnd.GetWindowTextW(text);
    std::wistringstream wistr((LPCWSTR) text);
    wistr >> num;
    return num;
}

void UIUtils::SaveSettings(CPropertyPage &page) {
    HWND hWnd = NULL;
    for (CPropertyPage *page : pages) {
        HWND test = page->m_hWnd;
        if (IsWindow(test)) {
            hWnd = test;
        }
    }

    if (hWnd == page.m_hWnd) {
        OutputDebugString(L"Saving Settings XML\n");
        Settings::Instance()->Save();
    }
}

Add method to determine if the given prop page should save the settings

This avoids constantly re-writing the settings XML file


/* For symbol_thingey */
#define BOOST_CHRONO_VERSION 2
#include <boost/chrono/chrono.hpp>
#include <boost/chrono/chrono_io.hpp>

#define FUTURE_TRACE 0

#include <cps/future.h>
#include <iostream>

using namespace cps;

int
main(void)
{
	auto start = boost::chrono::high_resolution_clock::now();
	const int count = 100000;
	for(int i = 0; i < count; ++i) {
		auto f = future<std::string>::create_shared();
		auto expected = "happy";
		f->on_done([expected](const std::string &v) {
			// return future<std::string>::create_shared()->done("very happy");
		})->done(expected);
		// BOOST_CHECK(seq->as<std::string>()->get() == "very happy");
	}
	auto elapsed = boost::chrono::high_resolution_clock::now() - start;
	std::cout << "Average iteration: " << boost::chrono::symbol_format << (elapsed / (float)count) << std::endl;
	return 0;
}

/* For symbol_thingey */
#include <chrono>

#define FUTURE_TRACE 0
#include <cps/future.h>
#include <iostream>

using namespace cps;

int
main(void)
{
	auto start = std::chrono::high_resolution_clock::now();
	const int count = 100000;
	for(int i = 0; i < count; ++i) {
		auto f = future<std::string>::create_shared();
		auto expected = "happy";
		f->on_done([expected](const std::string &v) {
			// return future<std::string>::create_shared()->done("very happy");
		})->done(expected);
		// BOOST_CHECK(seq->as<std::string>()->get() == "very happy");
	}
	auto elapsed = std::chrono::high_resolution_clock::now() - start;
	std::cout
		<< "Average iteration: "
		<< (std::chrono::duration_cast<std::chrono::nanoseconds>(elapsed).count() / (float)count)
		<< " ns"
		<< std::endl;
	return 0;
}

Use std::chrono, to cleanse last vestiges of boost


//===- llvm/System/AIX/Path.cpp - AIX Path Implementation -------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Reid Spencer and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provides the AIX specific implementation of the Path class.
//
//===----------------------------------------------------------------------===//

//===----------------------------------------------------------------------===//
//=== WARNING: Implementation here must contain only AIX specific code
//===          and must not be generic UNIX code (see ../Unix/Path.cpp)
//===----------------------------------------------------------------------===//

// Include the generic unix implementation
#include "../Unix/Path.cpp"

namespace llvm {
using namespace sys;

bool
Path::is_valid() const {
  if (path.empty())
    return false;
  if (path.length() >= MAXPATHLEN)
    return false;
  return true;
}

}

// vim: sw=2 smartindent smarttab tw=80 autoindent expandtab

//===- llvm/System/AIX/Path.cpp - AIX Path Implementation -------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Reid Spencer and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provides the AIX specific implementation of the Path class.
//
//===----------------------------------------------------------------------===//

// Include the generic unix implementation
#include "../Unix/Path.cpp"

namespace llvm {
using namespace sys;

//===----------------------------------------------------------------------===//
//=== WARNING: Implementation here must contain only AIX specific code
//===          and must not be generic UNIX code (see ../Unix/Path.cpp)
//===----------------------------------------------------------------------===//

bool
Path::is_valid() const {
  if (path.empty())
    return false;
  if (path.length() >= MAXPATHLEN)
    return false;
  return true;
}

}

// vim: sw=2 smartindent smarttab tw=80 autoindent expandtab

Move a warning comment to where it should have been in the first place.

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


#include "s3d/cv/image_operation/input_output_adapter.h"

#include "s3d/cv/image_operation/image_operations.h"

namespace s3d {
namespace image_operation {

InputOutputAdapter::InputOutputAdapter(gsl::not_null<ImageOperations*> imageOperations)
  : operations_{imageOperations} {}

void InputOutputAdapter::setInputImages(const cv::Mat& leftImage, const cv::Mat& rightImage) {
  inputLeftImage = leftImage.clone();
  inputRightImage = rightImage.clone();
}

std::tuple<cv::Mat&, cv::Mat&> InputOutputAdapter::getOutputImages() {
  return { outputLeftImage, outputRightImage };
};

bool InputOutputAdapter::applyAllOperations() {
  copyInputToOutputs();
  if (!canApplyOperations()) {
    return false;
  }
  return operations_->applyAll(&outputLeftImage, &outputRightImage);
}

void InputOutputAdapter::copyInputToOutputs() {
  outputLeftImage = inputLeftImage.clone();
  outputRightImage = inputRightImage.clone();
}

bool InputOutputAdapter::canApplyOperations() {
  return !inputLeftImage.empty() && !inputRightImage.empty();
}

} // namespace s3d
} // namespace image_operation

#include "s3d/cv/image_operation/input_output_adapter.h"

#include "s3d/cv/image_operation/image_operations.h"

namespace s3d {
namespace image_operation {

InputOutputAdapter::InputOutputAdapter(gsl::not_null<ImageOperations*> imageOperations)
  : operations_{imageOperations} {}

void InputOutputAdapter::setInputImages(const cv::Mat& leftImage, const cv::Mat& rightImage) {
  inputLeftImage = leftImage.clone();
  inputRightImage = rightImage.clone();
}

std::tuple<cv::Mat&, cv::Mat&> InputOutputAdapter::getOutputImages() {
  return std::tuple<cv::Mat&, cv::Mat&>(outputLeftImage, outputRightImage);
};

bool InputOutputAdapter::applyAllOperations() {
  copyInputToOutputs();
  if (!canApplyOperations()) {
    return false;
  }
  return operations_->applyAll(&outputLeftImage, &outputRightImage);
}

void InputOutputAdapter::copyInputToOutputs() {
  outputLeftImage = inputLeftImage.clone();
  outputRightImage = inputRightImage.clone();
}

bool InputOutputAdapter::canApplyOperations() {
  return !inputLeftImage.empty() && !inputRightImage.empty();
}

} // namespace s3d
} // namespace image_operation

Fix ubuntu build fail tuple init list

Fix ubuntu build fail tuple init list


#ifdef HAVE_XIMGPROC

#include "ximgproc.h"
#include "SuperpixelSEEDS.h"
#include "SuperpixelSLIC.h"
#include "SuperpixelLSC.h"

NAN_MODULE_INIT(XImgproc::Init) {
	SuperpixelSEEDS::Init(target);
	SuperpixelSLIC::Init(target);
	SuperpixelLSC::Init(target);
}

#endif // HAVE_XIMGPROC

#ifdef HAVE_XIMGPROC

#include "ximgproc.h"
#include "SuperpixelSEEDS.h"
#include "SuperpixelSLIC.h"
#include "SuperpixelLSC.h"

NAN_MODULE_INIT(XImgproc::Init) {
	SuperpixelSEEDS::Init(target);
#if OPENCV_MINOR_VERSION > 0
	SuperpixelSLIC::Init(target);
	SuperpixelLSC::Init(target);
#endif
}

#endif // HAVE_XIMGPROC

Check for opencv version before using SuperpixelLSC/SLIC


// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

#include "input_sanitizer.h"

#include <regex>

namespace influxdb {
    namespace utility {
        constexpr const char* regex = R"((^[a-zA-Z0-9_\-]+$|"(?:[^\\"]|\\.)+"))";

        const std::regex check_identifier(regex);

        bool valid_identifier(std::string const & input)
        {
            return std::regex_match(input, check_identifier);
        }

        void throw_on_invalid_identifier(std::string const & input)
        {
            if (!valid_identifier(input))
                throw std::runtime_error(std::string("Invalid identifier: ") + input);
        }
    }

}

// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

#include "input_sanitizer.h"

#include <regex>

namespace influxdb {
    namespace utility {
        constexpr const char* regex = R"((^[a-zA-Z0-9_/\\.\-]+$|"(?:[^\\"]|\\.)+"))";

        const std::regex check_identifier(regex);

        bool valid_identifier(std::string const & input)
        {
            return std::regex_match(input, check_identifier);
        }

        void throw_on_invalid_identifier(std::string const & input)
        {
            if (!valid_identifier(input))
                throw std::runtime_error(std::string("Invalid identifier: ") + input);
        }
    }

}

Allow dot and slash as message identifier


#include "ros/ros.h"
#include "std_msgs/String.h"
#include "geometry_msgs/Twist.h"

int main(int argc, char **argv)
{

  ros::init(argc, argv, "publish_fromfile");

  ros::NodeHandle pubFromFileHandle;

  ros::Publisher pubFromFileObj = pubFromFileHandle.advertise<geometry_msgs::Twist>("publish_fromfile",100);

  /*!
   * TODO: make this configurable by command line arg
   */
  ros::Rate sendRate(10);

  while(ros::ok())
  {
    geometry_msgs::Twist currentOutputMsg;
    currentOutputMsg.linear.x=0.0;
    currentOutputMsg.angular.z=0.0;

    pubFromFileObj.publish(currentOutputMsg);

    ros::spinOnce();
    sendRate.sleep();
  }

  return 0;
}

// ROS includes
#include "ros/ros.h"
#include "geometry_msgs/Twist.h"
#include "ros/console.h"
#include "std_msgs/String.h"

// misc includes
#include "yaml-cpp/yaml.h"

int main(int argc, char **argv)
{

  // local variables for configurable params
  double rate_param;
  int msg_buffer_len=100;
  std::string topic_name("publish_fromfile");
  std::string input_file; // TODO: implement
  // local variables for local scope use
  const std::string node_name("publish_fromfile");

  // initialize ROS
  ros::init(argc, argv, node_name);
  // make sure to create the node handle with the node_name used to initialize
  // (so that param relative scope works)
  ros::NodeHandle pubFromFileHandle(node_name);
  pubFromFileHandle.param("rate",rate_param,1.0);
  ROS_INFO_STREAM("/" << node_name << "/rate value set " << rate_param);
  pubFromFileHandle.param<std::string>("topic_name",topic_name,"publish_fromfile");
  ROS_INFO_STREAM("/" << node_name << "/topic_name value set " << topic_name);
  pubFromFileHandle.param("msg_buffer_len",msg_buffer_len,msg_buffer_len);
  ROS_INFO_STREAM("/" << node_name << "/msg_buffer_len value set " << msg_buffer_len);

  ros::Publisher pubFromFileObj = pubFromFileHandle.advertise<geometry_msgs::Twist>(topic_name,msg_buffer_len);

  ros::Rate sendRate(rate_param);

  while(ros::ok())
  {
    geometry_msgs::Twist currentOutputMsg;
    currentOutputMsg.linear.x=0.0;
    currentOutputMsg.angular.z=0.0;

    pubFromFileObj.publish(currentOutputMsg);

    ros::spinOnce();
    sendRate.sleep();
  }

  return 0;
}

Add ros console logging, implement params for ROS properties


/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF 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.
 */
#include "Version.hpp"

#include "CacheImpl.hpp"

namespace apache {
namespace geode {
namespace client {

int8_t Version::m_ordinal = 90;  // Geode 1.7.0

}  // namespace client
}  // namespace geode
}  // namespace apache

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF 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.
 */
#include "Version.hpp"

#include "CacheImpl.hpp"

namespace apache {
namespace geode {
namespace client {

int8_t Version::m_ordinal = 45;  // Geode 1.0.0

}  // namespace client
}  // namespace geode
}  // namespace apache

Revert "GEODE-5968: move protocol to the last release of Geode"

This reverts commit 5c29ba8b518594221aa4f285f39673a0d2fe6867.
This reverts commit c36abe5803b30dade41155b8a9bae04c81542929.


/**
	Responsible for creating and destroying the mentat reference

*/
#include "d2tmh.h"

cMentatFactory::cMentatFactory() {
	type = -1;
}

void cMentatFactory::deleteCurrent() {
	switch (type) {
		case ATREIDES:
			delete (cAtreidesMentat *)Mentat;
			break;
		case HARKONNEN:
			delete (cAtreidesMentat *)Mentat;
			break;
		case ORDOS:
			delete (cAtreidesMentat *)Mentat;
			break;
		case BENEGES:
			delete (cAtreidesMentat *)Mentat;
			break;
	}
}

void cMentatFactory::create(int mentatType) {
	if (type > -1) {
		if (mentatType != type) {
			deleteCurrent();
		}
	}
	/** It is safe to create a new Mentat now **/
	switch (mentatType) {
		case ATREIDES:
			Mentat = new cAtreidesMentat;
			break;
		case HARKONNEN:
			Mentat = new cHarkonnenMentat;
			break;
		case ORDOS:
			Mentat = new cOrdosMentat;
			break;
		case BENEGES:
			Mentat = new cBenegesMentat;
			break;
	}
	type = mentatType;
}

/**
	Responsible for creating and destroying the mentat reference

*/
#include "d2tmh.h"

cMentatFactory::cMentatFactory() {
	type = -1;
}

void cMentatFactory::deleteCurrent() {
	switch (type) {
		case ATREIDES:
			delete (cAtreidesMentat *)Mentat;
			break;
		case HARKONNEN:
			delete (cHarkonnenMentat *)Mentat;
			break;
		case ORDOS:
			delete (cOrdosMentat *)Mentat;
			break;
		case BENEGES:
			delete (cBenegesMentat *)Mentat;
			break;
	}
}

void cMentatFactory::create(int mentatType) {
	if (type > -1) {
		if (mentatType != type) {
			deleteCurrent();
		}
	}
	/** It is safe to create a new Mentat now **/
	switch (mentatType) {
		case ATREIDES:
			Mentat = new cAtreidesMentat;
			break;
		case HARKONNEN:
			Mentat = new cHarkonnenMentat;
			break;
		case ORDOS:
			Mentat = new cOrdosMentat;
			break;
		case BENEGES:
			Mentat = new cBenegesMentat;
			break;
	}
	type = mentatType;
}

Fix deletion of Mentats in MentatFactory


#include "ShaderProgram.hpp"

#include "Shader.hpp"

ShaderProgram::ShaderProgram(std::initializer_list<const Shader*> shaders) {
	shaderProgram = glCreateProgram();

	for (auto shader : shaders)
		glAttachShader(shaderProgram, shader->GetShaderID());

	glLinkProgram(shaderProgram);
}

ShaderProgram::~ShaderProgram() {
	glDeleteProgram(shaderProgram);
}

void ShaderProgram::Use() const {
	glUseProgram(shaderProgram);
}

GLuint ShaderProgram::GetAttributeLocation(const char* name) const {
	return glGetAttribLocation(shaderProgram, name);
}

GLuint ShaderProgram::GetUniformLocation(const char* name) const {
	return glGetUniformLocation(shaderProgram, name);
}

#include "ShaderProgram.hpp"

#include "Shader.hpp"

ShaderProgram::ShaderProgram(std::initializer_list<const Shader*> shaders) {
	shaderProgram = glCreateProgram();

	for (const Shader* shader : shaders)
		glAttachShader(shaderProgram, shader->GetShaderID());

	glLinkProgram(shaderProgram);

    for (const Shader* shader : shaders)
        glDetachShader(shaderProgram, shader->GetShaderID());
}

ShaderProgram::~ShaderProgram() {
	glDeleteProgram(shaderProgram);
}

void ShaderProgram::Use() const {
	glUseProgram(shaderProgram);
}

GLuint ShaderProgram::GetAttributeLocation(const char* name) const {
	return glGetAttribLocation(shaderProgram, name);
}

GLuint ShaderProgram::GetUniformLocation(const char* name) const {
	return glGetUniformLocation(shaderProgram, name);
}

Detach shaders after linking shader program.


// Copyright 2015 PDFium 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 "testing/embedder_test.h"
#include "testing/gtest/include/gtest/gtest.h"

class FPDFParserEmbeddertest : public EmbedderTest {
};

TEST_F(FPDFParserEmbeddertest, LoadError_454695) {
  // Test trailer dictionary with $$ze instead of Size.
  EXPECT_TRUE(OpenDocument("testing/resources/bug_454695.pdf"));
}

// Copyright 2015 PDFium 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 "../../../testing/embedder_test.h"
#include "testing/gtest/include/gtest/gtest.h"

class FPDFParserEmbeddertest : public EmbedderTest {
};

TEST_F(FPDFParserEmbeddertest, LoadError_454695) {
  // Test trailer dictionary with $$ze instead of Size.
  EXPECT_TRUE(OpenDocument("testing/resources/bug_454695.pdf"));
}

Update the path of header file to avoid a compiling error in chrome

BUG=N/A
R=tsepez@chromium.org

Review URL: https://codereview.chromium.org/1059233005


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

#include "chrome/browser/app_modal_dialog_queue.h"

#include "chrome/browser/browser_list.h"

void AppModalDialogQueue::AddDialog(AppModalDialog* dialog) {
  if (!active_dialog_) {
    ShowModalDialog(dialog);
    return;
  }
  app_modal_dialog_queue_.push(dialog);
}

void AppModalDialogQueue::ShowNextDialog() {
  if (!app_modal_dialog_queue_.empty()) {
    AppModalDialog* dialog = app_modal_dialog_queue_.front();
    app_modal_dialog_queue_.pop();
    ShowModalDialog(dialog);
  } else {
    active_dialog_ = NULL;
  }
}

void AppModalDialogQueue::ActivateModalDialog() {
  if (active_dialog_)
    active_dialog_->ActivateModalDialog();
}

void AppModalDialogQueue::ShowModalDialog(AppModalDialog* dialog) {
  dialog->ShowModalDialog();
  active_dialog_ = dialog;
}

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

#include "chrome/browser/app_modal_dialog_queue.h"

#include "chrome/browser/browser_list.h"

void AppModalDialogQueue::AddDialog(AppModalDialog* dialog) {
  if (!active_dialog_) {
    ShowModalDialog(dialog);
    return;
  }
  app_modal_dialog_queue_.push(dialog);
}

void AppModalDialogQueue::ShowNextDialog() {
  if (!app_modal_dialog_queue_.empty()) {
    AppModalDialog* dialog = app_modal_dialog_queue_.front();
    app_modal_dialog_queue_.pop();
    ShowModalDialog(dialog);
  } else {
    active_dialog_ = NULL;
  }
}

void AppModalDialogQueue::ActivateModalDialog() {
  if (active_dialog_)
    active_dialog_->ActivateModalDialog();
}

void AppModalDialogQueue::ShowModalDialog(AppModalDialog* dialog) {
  // Set active_dialog_ before showing it, because ShowModalDialog can wind up
  // calling ShowNextDialog in some cases, which will change active_dialog_.
  active_dialog_ = dialog;
  dialog->ShowModalDialog();
}

Set active_dialog_ before showing it, since showing a dialog can sometimes
actually move to the next one in the queue instead.

BUG=26398
TEST=Make sure alert/confirm boxes work properly. Make sure a background
    tab that shows a (delayed) alert box works. Same with a background
    browser. Especially make sure http://crbug.com/10699 doesn't recur.
Review URL: http://codereview.chromium.org/339094

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

Former-commit-id: d742548cbd85647132695cf7bb1b57e00273f6c3


#include "AutonomousCommandGroup.h"
#include "../RobotMap.h"

AutonomousCommandGroup::AutonomousCommandGroup()
{

}

#include "AutonomousCommandGroup.h"

#include "RaiseContainer.h"
#include "DownContainer.h"
#include "RaiseTrash.h"
#include "DownTrash.h"
#include "MoveContainer.h"
#include "../RobotMap.h"

AutonomousCommandGroup::AutonomousCommandGroup()
{
	AddSequential(new RaiseTrash());
	AddSequential(new DownTrash());
	AddSequential(new RaiseContainer());
	AddSequential(new MoveContainer());
	AddSequential(new DownContainer());
}

Set order of Autonomous Commands in CommandGroup


// Copyright (c) 2012-2013, the scalloc Project Authors.  All rights reserved.
// Please see the AUTHORS file for details.  Use of this source code is governed
// by a BSD license that can be found in the LICENSE file.

#include "allocators/global_sbrk_allocator.h"

#include <sys/mman.h>  // mmap

#include "log.h"

uintptr_t GlobalSbrkAllocator::current_;

void GlobalSbrkAllocator::InitModule() {
  size_t size = 1UL << 35;  // 32GiB
  void* p = mmap(0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
  if (p == MAP_FAILED) {
    ErrorOut("mmap failed");
  }
  current_ = reinterpret_cast<uintptr_t>(p);
}

// Copyright (c) 2012-2013, the scalloc Project Authors.  All rights reserved.
// Please see the AUTHORS file for details.  Use of this source code is governed
// by a BSD license that can be found in the LICENSE file.

#include "allocators/global_sbrk_allocator.h"

#include <sys/mman.h>  // mmap

#include "log.h"

uintptr_t GlobalSbrkAllocator::current_;

void GlobalSbrkAllocator::InitModule() {
#ifdef __x86_64__
  size_t size = 1UL << 35;  // 32GiB
#endif
#ifdef __i386__
  size_t size = 1UL << 31;
#endif

  void* p = mmap(0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
  if (p == MAP_FAILED) {
    ErrorOut("mmap failed");
  }
  current_ = reinterpret_cast<uintptr_t>(p);
}

Add large sbrk support for 32 bit platforms.

Signed-off-by: Michael Lippautz <0d543840881a2c189b4f7636b15eebd6a8f60ace@gmail.com>


// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#include "vm/version.h"

#include "vm/cpu.h"
#include "vm/os.h"

namespace dart {

// TODO(iposva): Avoid racy initialization.
static const char* formatted_version = NULL;

const char* Version::String() {
  if (formatted_version == NULL) {
    const char* os = OS::Name();
    const char* arch = CPU::Id();
    formatted_version = OS::SCreate(NULL, "%s on \"%s_%s\"", str_, os, arch);
  }
  return formatted_version;
}

const char* Version::SnapshotString() {
  return snapshot_hash_;
}

const char* Version::CommitString() {
  return commit_;
}

const char* Version::SdkHash() {
  return git_short_hash_;
}

const char* Version::snapshot_hash_ = "{{SNAPSHOT_HASH}}";
const char* Version::str_ = "{{VERSION_STR}} ({{CHANNEL}}) ({{COMMIT_TIME}})";
const char* Version::commit_ = "{{VERSION_STR}}";
const char* Version::git_short_hash_ = "{{GIT_HASH}}";

}  // namespace dart

// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#include "platform/atomic.h"

#include "vm/cpu.h"
#include "vm/os.h"
#include "vm/version.h"

namespace dart {

// We use require-release semantics to ensure initializing stores to the string
// are visible when the string becomes visible.
static AcqRelAtomic<const char*> formatted_version = nullptr;

const char* Version::String() {
  if (formatted_version.load() == nullptr) {
    const char* os = OS::Name();
    const char* arch = CPU::Id();
    char* version_string =
        OS::SCreate(nullptr, "%s on \"%s_%s\"", str_, os, arch);
    const char* expect_old_is_null = nullptr;
    if (!formatted_version.compare_exchange_strong(expect_old_is_null,
                                                   version_string)) {
      free(version_string);
    }
  }
  return formatted_version.load();
}

const char* Version::SnapshotString() {
  return snapshot_hash_;
}

const char* Version::CommitString() {
  return commit_;
}

const char* Version::SdkHash() {
  return git_short_hash_;
}

const char* Version::snapshot_hash_ = "{{SNAPSHOT_HASH}}";
const char* Version::str_ = "{{VERSION_STR}} ({{CHANNEL}}) ({{COMMIT_TIME}})";
const char* Version::commit_ = "{{VERSION_STR}}";
const char* Version::git_short_hash_ = "{{GIT_HASH}}";

}  // namespace dart

[vm] Use atomic to avoid racy version string initialization

This addresses an already existent TODO in the code.

Issue https://github.com/dart-lang/sdk/issues/46610

TEST=This fixes TSAN reports on iso-stress builder.

Change-Id: Ie21c0a17ae51070783da9bc934ef2827acde6378
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/206760
Reviewed-by: Tess Strickland <cce218d042444252b7ac446d60910fca7732559c@google.com>
Commit-Queue: Martin Kustermann <a35dd5b79fac84b2bb3b026a16b8becc55af5961@google.com>


// Test for disabling LSan at link-time.
// RUN: LSAN_BASE="use_stacks=0:use_registers=0"
// RUN: %clangxx_lsan %s -o %t
// RUN: %env_lsan_opts=$LSAN_BASE %run %t
// RUN: %env_lsan_opts=$LSAN_BASE not %run %t foo 2>&1 | FileCheck %s

#include <sanitizer/lsan_interface.h>

int argc_copy;

extern "C" {
int __attribute__((used)) __lsan_is_turned_off() {
  return (argc_copy == 1);
}
}

int main(int argc, char *argv[]) {
  volatile int *x = new int;
  *x = 42;
  argc_copy = argc;
  return 0;
}

// CHECK: SUMMARY: {{(Leak|Address)}}Sanitizer: 4 byte(s) leaked in 1 allocation(s)

// Test for disabling LSan at link-time.
// RUN: LSAN_BASE="use_stacks=0:use_registers=0"
// RUN: %clangxx_lsan %s -o %t
// RUN: %env_lsan_opts=$LSAN_BASE %run %t
// RUN: %env_lsan_opts=$LSAN_BASE not %run %t foo 2>&1 | FileCheck %s
//
// UNSUPPORTED: darwin

#include <sanitizer/lsan_interface.h>

int argc_copy;

extern "C" {
int __attribute__((used)) __lsan_is_turned_off() {
  return (argc_copy == 1);
}
}

int main(int argc, char *argv[]) {
  volatile int *x = new int;
  *x = 42;
  argc_copy = argc;
  return 0;
}

// CHECK: SUMMARY: {{(Leak|Address)}}Sanitizer: 4 byte(s) leaked in 1 allocation(s)

Revert "Prevent DCE on __lsan_is_turned_off and re-enable test case"

This doesn't fix the failing test. Leave in the comment and the
attribute, since the used attribute is still required.

This partially reverts commit r312824

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


#include "MicroBit.h"

extern "C" {
    void mp_run(void);

    void microbit_display_event(void);
}

static void event_listener(MicroBitEvent evt) {
    if (evt.value == MICROBIT_DISPLAY_EVT_ANIMATION_COMPLETE) {
        microbit_display_event();
    }
}

void app_main() {
    /*
    // debugging: print memory layout
    extern uint32_t __data_start__, __data_end__;
    extern uint32_t __bss_start__, __bss_end__;
    extern uint32_t __HeapLimit, __StackLimit, __StackTop;
    printf("__data_start__ = %p\r\n", &__data_start__);
    printf("__data_end__   = %p\r\n", &__data_end__);
    printf("__bss_start_ _ = %p\r\n", &__bss_start__);
    printf("__bss_end__    = %p\r\n", &__bss_end__);
    printf("__HeapLimit    = %p\r\n", &__HeapLimit);
    printf("__StackLimit   = %p\r\n", &__StackLimit);
    printf("__StackTop     = %p\r\n", &__StackTop);
    */

    uBit.MessageBus.listen(MICROBIT_ID_DISPLAY,
        MICROBIT_DISPLAY_EVT_ANIMATION_COMPLETE, event_listener);
    while (1) {
        mp_run();
    }
}

#include "MicroBit.h"

extern "C" {
    void mp_run(void);

    void microbit_display_event(void);
}

static void event_listener(MicroBitEvent evt) {
    if (evt.value == MICROBIT_DISPLAY_EVT_ANIMATION_COMPLETE) {
        microbit_display_event();
    }
}

void app_main() {
    /*
    // debugging: print memory layout
    extern uint32_t __data_start__, __data_end__;
    extern uint32_t __bss_start__, __bss_end__;
    extern uint32_t __HeapLimit, __StackLimit, __StackTop;
    printf("__data_start__ = %p\r\n", &__data_start__);
    printf("__data_end__   = %p\r\n", &__data_end__);
    printf("__bss_start_ _ = %p\r\n", &__bss_start__);
    printf("__bss_end__    = %p\r\n", &__bss_end__);
    printf("__HeapLimit    = %p\r\n", &__HeapLimit);
    printf("__StackLimit   = %p\r\n", &__StackLimit);
    printf("__StackTop     = %p\r\n", &__StackTop);
    */

    currentFiber->flags |= MICROBIT_FIBER_FLAG_DO_NOT_PAGE;

    uBit.MessageBus.listen(MICROBIT_ID_DISPLAY,
        MICROBIT_DISPLAY_EVT_ANIMATION_COMPLETE, event_listener,
        MESSAGE_BUS_LISTENER_REENTRANT | MESSAGE_BUS_LISTENER_NONBLOCKING);

    while (1) {
        mp_run();
    }
}

Update to use new DAL feature where stack is not paged.


#include <bts/blockchain/address.hpp>
#include <bts/blockchain/pts_address.hpp>
#include <bts/blockchain/types.hpp>
#include <bts/utilities/key_conversion.hpp>
#include <fc/crypto/elliptic.hpp>
#include <fc/io/json.hpp>
#include <fc/reflect/variant.hpp>
#include <fc/filesystem.hpp>
#include <fc/variant_object.hpp>
#include <fc/exception/exception.hpp>

#include <iostream>

using namespace bts::blockchain;

int main( int argc, char** argv )
{

    if( argc == 2 )
    {
        fc::ecc::private_key k;
        try{
            auto key = bts::blockchain::public_key_type(std::string(argv[1]));
            auto obj = fc::mutable_variant_object();

            obj["public_key"] = public_key_type(key);
            obj["native_address"] = bts::blockchain::address(key);
            obj["pts_address"] = bts::blockchain::pts_address(key);

            std::cout << fc::json::to_pretty_string(obj);
            return 0;

        } catch (fc::exception e) {
            std::cout << e.to_detail_string();
        }
    }
    return -1;
}

#include <bts/blockchain/address.hpp>
#include <bts/blockchain/pts_address.hpp>
#include <bts/blockchain/types.hpp>
#include <bts/utilities/key_conversion.hpp>
#include <fc/crypto/elliptic.hpp>
#include <fc/io/json.hpp>
#include <fc/reflect/variant.hpp>
#include <fc/filesystem.hpp>
#include <fc/variant_object.hpp>
#include <fc/exception/exception.hpp>

#include <iostream>

using namespace bts::blockchain;

int main( int argc, char** argv )
{
    if( argc == 2 )
    {
        try
        {
            bts::blockchain::public_key_type key(argv[1]);
            fc::mutable_variant_object obj;

            obj["public_key"] = key;
            obj["native_address"] = bts::blockchain::address((fc::ecc::public_key_data)key);
            obj["pts_address"] = bts::blockchain::pts_address((fc::ecc::public_key)key);

            std::cout << fc::json::to_pretty_string(obj);
            return 0;

        }
        catch (fc::exception e)
        {
            std::cout << e.to_detail_string();
        }
    }
    return -1;
}

Fix compile errors on win32, update Qt submodule to fix compile errors there


/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.

Licensed 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.
==============================================================================*/

#include "tensorflow/core/kernels/cwise_ops_common.h"

namespace tensorflow {
REGISTER2(UnaryOp, CPU, "Tan", functor::tan, float, double);

#if GOOGLE_CUDA
REGISTER2(UnaryOp, GPU, "Tan", functor::tan, float, double);
#endif

#ifdef TENSORFLOW_USE_SYCL
REGISTER2(UnaryOp, SYCL, "Tan", functor::tan, float, double);
#endif  // TENSORFLOW_USE_SYCL
}  // namespace tensorflow

/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.

Licensed 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.
==============================================================================*/

#include "tensorflow/core/kernels/cwise_ops_common.h"

namespace tensorflow {
REGISTER4(UnaryOp, CPU, "Tan", functor::tan, float, double, complex64, complex128);

#if GOOGLE_CUDA
REGISTER2(UnaryOp, GPU, "Tan", functor::tan, float, double);
#endif

#ifdef TENSORFLOW_USE_SYCL
REGISTER2(UnaryOp, SYCL, "Tan", functor::tan, float, double);
#endif  // TENSORFLOW_USE_SYCL
}  // namespace tensorflow

Add complex support for tan

Add complex support for tan

At the moment tan in tensorflow supports float and double, but
not complex types.

This fix adds the support for tan, and removes related TODO in
the test

Signed-off-by: Yong Tang <765086fe2e0c1f980161f127fec596800f327f62@outlook.com>


#include <cstring>
#include <iostream>

#include <UnitTest++/UnitTest++.h>
#include <UnitTest++/TestReporterStdout.h>

using std::cerr;
using std::endl;
using std::strcmp;

/*
  Function object returning true for a specified test name
 */
struct MatchTestName {
  const char * const tname;
  MatchTestName (const char* tn) : tname {tn} {};
  bool operator () (const UnitTest::Test* const test) const { return strcmp(test->m_details.testName, tname) == 0; }
};

/*
  Locate and run all tests
 */
int main(int argc, const char* argv[]) {
  if (argc < 2)
    return UnitTest::RunAllTests();
  else if (argc >= 2){
    UnitTest::TestReporterStdout reporter;
    UnitTest::TestRunner runner (reporter);
    if (argc == 2)
      return runner.RunTestsIf (UnitTest::Test::GetTestList(),
                                argv[1],
                                UnitTest::True(),
                                0);
    else if (argc == 3)
      return runner.RunTestsIf (UnitTest::Test::GetTestList(),
                                argv[1],
                                MatchTestName(argv[2]),
                                0);
    else
      cerr << "Usage: tester [suite [test]]" << endl;
  }
}

#include <cstring>
#include <iostream>

#include <UnitTest++/UnitTest++.h>
#include <UnitTest++/TestReporterStdout.h>

using std::cerr;
using std::endl;
using std::strcmp;

/*
  Function object returning true for a specified test name
 */
struct MatchTestName {
  const char * const tname;
  MatchTestName (const char* tn) : tname {tn} {};
  bool operator () (const UnitTest::Test* const test) const { return strcmp(test->m_details.testName, tname) == 0; }
};

/*
  Runs a specific suite/test if a suite, or a suite and a test, is provided,
  or all tests if none are provided.

  To execute, run ./tester [suite [test]]
 */
int main(int argc, const char* argv[]) {
  if (argc < 2)
    return UnitTest::RunAllTests();
  else if (argc >= 2){
    UnitTest::TestReporterStdout reporter;
    UnitTest::TestRunner runner (reporter);
    if (argc == 2)
      return runner.RunTestsIf (UnitTest::Test::GetTestList(),
                                argv[1],
                                UnitTest::True(),
                                0);
    else if (argc == 3)
      return runner.RunTestsIf (UnitTest::Test::GetTestList(),
                                argv[1],
                                MatchTestName(argv[2]),
                                0);
    else
      cerr << "Usage: ./tester [suite [test]]" << endl;
  }
}

Update documentation for main() in tester


// Copyright (C) 2012-2016 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "MentionsVariousOtherTypes.hpp"
#include <autowiring/autowiring.h>

MentionsVariousOtherTypes::MentionsVariousOtherTypes(void) {
  AutoRequired<AutoPacketFactory>();
}

// Copyright (C) 2012-2016 Leap Motion, Inc. All rights reserved.
#include "MentionsVariousOtherTypes.hpp"
#include <autowiring/autowiring.h>

MentionsVariousOtherTypes::MentionsVariousOtherTypes(void) {
  AutoRequired<AutoPacketFactory>();
}

Remove PCH that seems to hit a rogue extern "C" on Travis


// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "auto_id.h"

using namespace autowiring;

// Index that will be given to the next auto_id instance.  Zero is reserved.
static int s_index = 1;

const auto_id_block auto_id_t<void>::s_block{
  0,
  &typeid(void),
  &typeid(s<void>),
  0,
  0,
  nullptr,
  nullptr
};

const auto_id_t_init<void, true> auto_id_t_init<void, true>::init;
const auto_id_t_init<void, false> auto_id_t_init<void, false>::init;

int autowiring::CreateIndex(void) {
  return s_index++;
}

std::shared_ptr<CoreObject> auto_id_block::NullToObj(const std::shared_ptr<void>&) AUTO_NOEXCEPT
{
  return nullptr;
}

std::shared_ptr<void> auto_id_block::NullFromObj(const std::shared_ptr<CoreObject>&) AUTO_NOEXCEPT
{
  return nullptr;
}

// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "auto_id.h"

using namespace autowiring;

// Index that will be given to the next auto_id instance.  Zero is reserved.
static int s_index = 1;

const auto_id_block auto_id_t<void>::s_block{
  0,
  &typeid(void),
  &typeid(s<void>),
  0,
  0,
  nullptr,
  nullptr
};

const auto_id_t_init<void, true> auto_id_t_init<void, true>::init{};
const auto_id_t_init<void, false> auto_id_t_init<void, false>::init{};

int autowiring::CreateIndex(void) {
  return s_index++;
}

std::shared_ptr<CoreObject> auto_id_block::NullToObj(const std::shared_ptr<void>&) AUTO_NOEXCEPT
{
  return nullptr;
}

std::shared_ptr<void> auto_id_block::NullFromObj(const std::shared_ptr<CoreObject>&) AUTO_NOEXCEPT
{
  return nullptr;
}

Use initializer syntax to satisfy clang

Use initializer syntax to satisfy clang


#include "comb.h"

int main()
{
//  for(int i=0;i<6;i++){
    sweep(20*2*pi,0.7*2*pi,1,400000,1000,1/pow(10,10),0,10,16,50,600,15,0,0.001,"Gaussian");
    sweep(20*2*pi,0.7*2*pi,1,400000,1000,1/pow(10,10),0,10,17,50,600,15,0,0.001,"Gaussian");
//  }
      //gamma2(Hz),line width(GHz),sweep steps, total steps, power(uW/cm2),convergence condition,convergence threshold,convergency steps,ADM order,n1 interval,n2 interval,Matrix self multiplication,laser detune,A Factor
      // The last argument is the function type "Sinc" for Sinc Function other for Gaussian function

//0.7*2*pi;//0.0052227*2*pi;//

system("./mail.py");
return 0;

}

#include "comb.h"
#include <ctime>

int main()
{

  fstream file1;
  file1.open("./Data/result.txt",ios::out | ios::trunc);
  file1<<"Function\t"<<"Order\t"<<"Steps\t"<<endl;

  for(int i=1;i<6;i++){
   for(int j=1;j<4;j++){
    time_t T1 = clock(),T2;
    sweep(20*2*pi,0.7*2*pi,1,400000,1000,1/pow(10,10),0,10,12-i,10*j,600,15,0,0.001,"Gaussian");
    T2 = clock();
    file1<<"Gaussian\t"<<12-i<<"\t"<<10*j<<"\t"<<(T2-T1)<<endl;
    sweep(20*2*pi,0.7*2*pi,1,400000,1000,1/pow(10,10),0,10,12-i,10*j,600,15,0,0.001,"Sinc");
    T1 = clock();
    file1<<"sinc\t"<<12-i<<"\t"<<10*j<<"\t"<<(T1-T2)<<endl;
   }
  }

      //gamma2(Hz),line width(GHz),sweep steps, total steps, power(uW/cm2),convergence condition,convergence threshold,convergency steps,ADM order,n1 interval,n2   interval,Matrix self multiplication,laser detune,A Factor
      // The last argument is the function type "Sinc" for Sinc Function other for Gaussian function

//0.7*2*pi;//0.0052227*2*pi;//

system("./mail.py");

return 0;

}

Add benchmark feature in main functin.

Add benchmark feature in main functin.


#include "mock/unittest_utils.hpp"

#include <stdlib.h>

#include "errors.hpp"
#include <boost/bind.hpp>

#include "arch/timing.hpp"
#include "arch/runtime/starter.hpp"
#include "utils.hpp"            // randint

namespace mock {

temp_file_t::temp_file_t(const char *tmpl) {
    size_t len = strlen(tmpl);
    filename.init(len + 1);
    memcpy(filename.data(), tmpl, len+1);
    int fd = mkstemp(filename.data());
    guarantee_err(fd != -1, "Couldn't create a temporary file");
    close(fd);
}

temp_file_t::~temp_file_t() {
    unlink(filename.data());
}

void let_stuff_happen() {
    nap(100);
}

int randport() {
    return 10000 + randint(20000);
}

void run_in_thread_pool(const boost::function<void()>& fun, int num_workers) {
    ::run_in_thread_pool(fun, num_workers);
}

}  // namespace mock

#include "mock/unittest_utils.hpp"

#include <stdlib.h>

#include "errors.hpp"
#include <boost/bind.hpp>

#include "arch/timing.hpp"
#include "arch/runtime/starter.hpp"
#include "utils.hpp"            // randint

namespace mock {

temp_file_t::temp_file_t(const char *tmpl) {
    size_t len = strlen(tmpl);
    filename.init(len + 1);
    memcpy(filename.data(), tmpl, len+1);
    int fd = mkstemp(filename.data());
    guarantee_err(fd != -1, "Couldn't create a temporary file");
    close(fd);
}

temp_file_t::~temp_file_t() {
    unlink(filename.data());
}

void let_stuff_happen() {
#ifdef VALGRIND
    nap(2000);
#else
    nap(100);
#endif
}

int randport() {
    return 10000 + randint(20000);
}

void run_in_thread_pool(const boost::function<void()>& fun, int num_workers) {
    ::run_in_thread_pool(fun, num_workers);
}

}  // namespace mock

Make let_stuff_happen() wait longer under valgrind.


#include <boost/test/unit_test.hpp>

#include "../uint256.h"

extern void SHA256Transform(void* pstate, void* pinput, const void* pinit);

BOOST_AUTO_TEST_SUITE(miner_tests)

BOOST_AUTO_TEST_CASE(sha256transform_equality)
{
    unsigned int pSHA256InitState[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};

    unsigned char pstate[32];
    unsigned char pinput[32];

    int i;

    for (i = 0; i < 32; i++) {
        pinput[i] = i;
        pstate[i] = 0;
    }

    uint256 hash;

    SHA256Transform(&hash, pinput, pSHA256InitState);

		BOOST_TEST_MESSAGE(hash.GetHex());

    uint256 hash_reference("0x2df5e1c65ef9f8cde240d23cae2ec036d31a15ec64bc68f64be242b1da6631f3");

    BOOST_CHECK(hash == hash_reference);
}

BOOST_AUTO_TEST_SUITE_END()

#include <boost/test/unit_test.hpp>

#include "../uint256.h"

extern void SHA256Transform(void* pstate, void* pinput, const void* pinit);

BOOST_AUTO_TEST_SUITE(miner_tests)

BOOST_AUTO_TEST_CASE(sha256transform_equality)
{
    unsigned int pSHA256InitState[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};

    unsigned char pstate[32];
    unsigned char pinput[64];

    int i;

    for (i = 0; i < 32; i++) {
        pinput[i] = i;
        pinput[i+32] = 0;
    }

    uint256 hash;

    SHA256Transform(&hash, pinput, pSHA256InitState);

    BOOST_TEST_MESSAGE(hash.GetHex());

    uint256 hash_reference("0x2df5e1c65ef9f8cde240d23cae2ec036d31a15ec64bc68f64be242b1da6631f3");

    BOOST_CHECK(hash == hash_reference);
}

BOOST_AUTO_TEST_SUITE_END()

Fix miner_test unit test bug

Fix miner_test unit test bug


// RUN: %clangxx -shared -o /dev/null -v -fxray-instrument %s -###
// RUN: %clangxx -shared -o /dev/null -v -fxray-instrument %s -### 2>&1 | \
// RUN:     FileCheck %s --check-prefix=SHARED
// RUN: %clangxx -static -o /dev/null -v -fxray-instrument %s -### -DMAIN
// RUN: %clangxx -static -o /dev/null -v -fxray-instrument %s -### 2>&1 -DMAIN \
// RUN:     | FileCheck %s --check-prefix=STATIC
//
// SHARED-NOT: {{clang_rt\.xray-}}
// STATIC: {{clang_rt\.xray-}}
//
// REQUIRES: enable_shared
int foo() { return 42; }

#ifdef MAIN
int main() { return foo(); }
#endif

// RUN: %clangxx -shared -o /dev/null -v -fxray-instrument %s -###
// RUN: %clangxx -shared -o /dev/null -v -fxray-instrument %s -### 2>&1 | \
// RUN:     FileCheck %s --check-prefix=SHARED
// RUN: %clangxx -static -o /dev/null -v -fxray-instrument %s -### -DMAIN
// RUN: %clangxx -static -o /dev/null -v -fxray-instrument %s -### 2>&1 -DMAIN \
// RUN:     | FileCheck %s --check-prefix=STATIC
//
// SHARED-NOT: {{clang_rt\.xray-}}
// STATIC: {{clang_rt\.xray-}}
//
// REQUIRES: linux, enable_shared
int foo() { return 42; }

#ifdef MAIN
int main() { return foo(); }
#endif

Revert part of r. 325746 D43378

Revert part of r. 325746 D43378

test/Driver/XRay/xray-shared-noxray.cpp fails on !Linux hosts.

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


#include "ZulipAboutDialog.h"

#include "ui_ZulipAboutDialog.h"
#include "Config.h"

#include <QFile>
#include <QDebug>

ZulipAboutDialog::ZulipAboutDialog(QWidget *parent) :
    QDialog(parent), m_ui(new Ui::ZulipAboutDialog)
{
    m_ui->setupUi(this);

    QFile html(":/about.html");
    if (!html.open(QIODevice::ReadOnly)) {
        qWarning() << "Failed to read from qrc:/about.html";
    } else {
        QString contents = QString::fromUtf8(html.readAll());
        // Add version string

        QString license;
#ifdef SSO_BUILD
        license = "the Zulip Enterprise License Agreement";
#else
        license = "the license described in the Zulip Terms of Service";
#endif
        contents = contents.replace("{{ZULIP_VERSION_STRING}}", ZULIP_VERSION_STRING);
        contents = contents.replace("{{ZULIP_LICENSE_AGREEMENT}}", license);
        m_ui->webView->loadHTML(contents);
    }
}

ZulipAboutDialog::~ZulipAboutDialog()
{
}

#include "ZulipAboutDialog.h"

#include "ui_ZulipAboutDialog.h"
#include "Config.h"
#include "ZulipApplication.h"
#include "ZulipWindow.h"

#include <QFile>
#include <QDebug>

ZulipAboutDialog::ZulipAboutDialog(QWidget *parent) :
    QDialog(parent), m_ui(new Ui::ZulipAboutDialog)
{
    m_ui->setupUi(this);

    connect(m_ui->webView, SIGNAL(linkClicked(QUrl)), APP->mainWindow(), SLOT(linkClicked(QUrl)));

    QFile html(":/about.html");
    if (!html.open(QIODevice::ReadOnly)) {
        qWarning() << "Failed to read from qrc:/about.html";
    } else {
        QString contents = QString::fromUtf8(html.readAll());
        // Add version string

        QString license;
#ifdef SSO_BUILD
        license = "the Zulip Enterprise License Agreement";
#else
        license = "the license described in the Zulip Terms of Service";
#endif
        contents = contents.replace("{{ZULIP_VERSION_STRING}}", ZULIP_VERSION_STRING);
        contents = contents.replace("{{ZULIP_LICENSE_AGREEMENT}}", license);
        m_ui->webView->loadHTML(contents);
    }
}

ZulipAboutDialog::~ZulipAboutDialog()
{
}

Fix Terms URL in about dialog to open in browser


#include "ProxyImage.h"
#include "StringHelper.h"

#include <sprite2/S2_Texture.h>

namespace gum
{

ProxyImage::ProxyImage(int id, int w, int h, int format)
{
	Init(id, w, h, format);
}

ProxyImage::~ProxyImage()
{
// 	m_id = 0; // avoid release in Image
// 	          // managed by other
}

void ProxyImage::Init(int id, int w, int h, int format)
{
	m_width  = w;
	m_height = h;
	m_format = format;
	m_id     = id;

	m_filepath = GetFilepath(id);

	m_s2_tex->Init(w, h, id);
}

std::string ProxyImage::GetFilepath(int id)
{
	return "_proxy" + StringHelper::ToString(id);
}

}

#include "ProxyImage.h"
#include "StringHelper.h"

#include <sprite2/S2_Texture.h>

namespace gum
{

ProxyImage::ProxyImage(int id, int w, int h, int format)
{
	Init(id, w, h, format);
}

ProxyImage::~ProxyImage()
{
	m_id = 0; // avoid release in Image
	          // managed by other
}

void ProxyImage::Init(int id, int w, int h, int format)
{
	m_width  = w;
	m_height = h;
	m_format = format;
	m_id     = id;

	m_filepath = GetFilepath(id);

	m_s2_tex->Init(w, h, id);
}

std::string ProxyImage::GetFilepath(int id)
{
	return "_proxy" + StringHelper::ToString(id);
}

}

Revert "[FIXED] proxy img dtor"

Revert "[FIXED] proxy img dtor"

This reverts commit 626c82e812fe5dcb218a8dbbd021b04c2ed605ce.


#include "HttpClient.h"

#include <mbedtls/ssl.h>
#include <mbedtls/x509.h>

namespace ceema {
    CURLcode HttpClient::ssl_ctx_callback_mbedtls(CURL *curl, void *ssl_ctx, void *client_ptr) {
        HttpClient& client = *static_cast<HttpClient*>(client_ptr);

        if (client.m_cert.empty()) {
            return CURLE_OK;
        }

        LOG_DEBUG(logging::loggerRoot, "Inserting SSL cert");
        CURLcode status = CURLE_OK;

        auto mbed_ctx = static_cast<mbedtls_ssl_config*>(ssl_ctx);

        mbedtls_x509_crt cacert;
        mbedtls_x509_crt_init( &cacert );

        if (mbedtls_x509_crt_parse(
                &cacert,
                reinterpret_cast<const unsigned char*>(client.m_cert.c_str()),
                client.m_cert.size()) != 0) {
            status = CURLE_SSL_CERTPROBLEM;
        } else {
            mbedtls_ssl_conf_ca_chain(mbed_ctx, &cacert, nullptr);
        }

        return status;
    }
}

#include "HttpClient.h"

#include <mbedtls/ssl.h>
#include <mbedtls/x509.h>

namespace ceema {
    CURLcode HttpClient::ssl_ctx_callback_mbedtls(CURL *curl, void *ssl_ctx, void *client_ptr) {
        HttpClient& client = *static_cast<HttpClient*>(client_ptr);

        if (client.m_cert.empty()) {
            return CURLE_OK;
        }

        LOG_DEBUG(logging::loggerRoot, "Inserting SSL cert");
        CURLcode status = CURLE_OK;

        auto mbed_ctx = static_cast<mbedtls_ssl_config*>(ssl_ctx);

        mbedtls_x509_crt cacert;
        mbedtls_x509_crt_init( &cacert );

        if (mbedtls_x509_crt_parse(
                &cacert,
                reinterpret_cast<const unsigned char*>(client.m_cert.c_str()),
                client.m_cert.size() + 1) != 0) {
            status = CURLE_SSL_CERTPROBLEM;
        } else {
            mbedtls_ssl_conf_ca_chain(mbed_ctx, &cacert, nullptr);
        }

        return status;
    }
}

Fix error in size for parsing the certificate by mbedtls_x509_crt_parse


#include "common.h"

void siren_ary_to_xyz(VALUE ary, Standard_Real& x, Standard_Real& y, Standard_Real& z)
{
  x = 0.0; y = 0.0; z = 0.0;

  Check_Type(ary, T_ARRAY);

  int len = RARRAY_LEN(ary);
  if (len > 0) {
    x = NUM2DBL(RARRAY_AREF(ary, 0));
  }
  if (len > 1) {
    y = NUM2DBL(RARRAY_AREF(ary, 1));
  }
  if (len > 2) {
    z = NUM2DBL(RARRAY_AREF(ary, 2));
  }
  return;
}

#include "common.h"

void siren_ary_to_xyz(VALUE ary, Standard_Real& x, Standard_Real& y, Standard_Real& z)
{
  x = 0.0; y = 0.0; z = 0.0;

  int len = RARRAY_LEN(ary);
  if (len > 0) {
    x = NUM2DBL(RARRAY_AREF(ary, 0));
  }
  if (len > 1) {
    y = NUM2DBL(RARRAY_AREF(ary, 1));
  }
  if (len > 2) {
    z = NUM2DBL(RARRAY_AREF(ary, 2));
  }
  return;
}

Fix bug. support implicit cast Vec to Array again.


#include "KAI/Console/Console.h"

#include <iostream>

#ifdef WIN32
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#endif

using namespace std;

USING_NAMESPACE_KAI

//static Color _color;

int main(int argc, char **argv)
{
	KAI_UNUSED_2(argc, argv);

	cout << "pyro v0.1" << endl;

	Console console;
	console.SetLanguage(Language::Pi);

	Process::trace = 0;
	console.GetExecutor()->SetTraceLevel(0);

	return console.Run();
}

#include <KAI/Console/Console.h>
#include <iostream>

using namespace std;

USING_NAMESPACE_KAI

int main(int argc, char **argv)
{
	KAI_UNUSED_2(argc, argv);

	cout << "KAI v0.1" << endl;

	Console console;
	console.SetLanguage(Language::Pi);

	// the higher the number, the greater the verbosity of debug output
	Process::trace = 0;
	console.GetExecutor()->SetTraceLevel(0);

	// start the REPL
	return console.Run();
}

Remove explicit WIN32 references from Console app.

Former-commit-id: 1621bff1d97d47fe91419641ff983a6ec3ee5626
Former-commit-id: ecc138236b570f5dc9f92082f539917fb2b53460
Former-commit-id: a34bc0c537cfba14b168de78b2e2ded3f0f5f3c0


#include "Rotate.hpp"

#include "../../../Libraries/bullet3/src/LinearMath/btTransform.h"
#include <Scenes/Entity.hpp>
#include <Engine/Engine.hpp>
#include <Physics/Colliders/Collider.hpp>
#include <Maths/Maths.hpp>

namespace test
{
	Rotate::Rotate(const Vector3 &direction, const int &test) :
		m_direction(direction),
		m_test(test),
		m_rotation(Vector3())
	{
	}

	void Rotate::Start()
	{
	}

	void Rotate::Update()
	{
		m_rotation += m_direction * Engine::Get()->GetDelta().AsSeconds();
		Transform &transform = GetParent()->GetLocalTransform();
		transform.SetRotation(m_rotation);

		if (m_test == 1)
		{
			Quaternion rotation = Quaternion(m_rotation.m_x, m_rotation.m_y, m_rotation.m_z);
			transform.SetRotation(rotation.ToEuler());
		}
		else if (m_test == 2)
		{
			btTransform transform1 = Collider::Convert(transform);
			transform = Collider::Convert(transform1, transform.GetScaling());
		}
	}

	void Rotate::Decode(const Metadata &metadata)
	{
		m_direction = metadata.GetChild<Vector3>("Direction");
	}

	void Rotate::Encode(Metadata &metadata) const
	{
		metadata.SetChild<Vector3>("Direction", m_direction);
	}
}

#include "Rotate.hpp"

#include <bullet/LinearMath/btTransform.h>
#include <Scenes/Entity.hpp>
#include <Engine/Engine.hpp>
#include <Physics/Colliders/Collider.hpp>
#include <Maths/Maths.hpp>

namespace test
{
	Rotate::Rotate(const Vector3 &direction, const int &test) :
		m_direction(direction),
		m_test(test),
		m_rotation(Vector3())
	{
	}

	void Rotate::Start()
	{
	}

	void Rotate::Update()
	{
		m_rotation += m_direction * Engine::Get()->GetDelta().AsSeconds();
		Transform &transform = GetParent()->GetLocalTransform();
		transform.SetRotation(m_rotation);

		if (m_test == 1)
		{
			Quaternion rotation = Quaternion(m_rotation.m_x, m_rotation.m_y, m_rotation.m_z);
			transform.SetRotation(rotation.ToEuler());
		}
		else if (m_test == 2)
		{
			btTransform transform1 = Collider::Convert(transform);
			transform = Collider::Convert(transform1, transform.GetScaling());
		}
	}

	void Rotate::Decode(const Metadata &metadata)
	{
		m_direction = metadata.GetChild<Vector3>("Direction");
	}

	void Rotate::Encode(Metadata &metadata) const
	{
		metadata.SetChild<Vector3>("Direction", m_direction);
	}
}

Fix tests include for bullet

Fix tests include for bullet

It was trying to point to the git submodule, causing a build error if using system libs.


#include <iostream>

#include "libport/cli.hh"
#include "libport/sysexits.hh"
#include "libport/program-name.hh"

namespace libport
{
  void
  usage_error (const std::string& opt, const std::string& err)
  {
    std::cerr << program_name << ": " << opt << ": " << err << std::endl
	      << libport::exit (EX_USAGE);
  }

  void
  required_argument (const std::string& opt)
  {
    usage_error (opt, "requires an argument");
  }

  void
  missing_argument (const std::string& opt)
  {
    usage_error (opt, "missing argument");
  }

  void
  invalid_option (const std::string& opt)
  {
    usage_error (opt, "invalid option");
  }

  void
  invalid_option_val (const std::string& opt, const std::string& arg)
  {
    usage_error (opt, "invalid argument: " + arg);
  }

}

#include <iostream>

#include "libport/cli.hh"
#include "libport/sysexits.hh"
#include "libport/program-name.hh"

namespace libport
{
  void
  usage_error (const std::string& opt, const std::string& err)
  {
    std::cerr
      << program_name << ": " << opt << ": " << err
      << std::endl
      << "Try `" << program_name << " --help' for more information."
      << std::endl
      << libport::exit (EX_USAGE);
  }

  void
  required_argument (const std::string& opt)
  {
    usage_error (opt, "requires an argument");
  }

  void
  missing_argument (const std::string& opt)
  {
    usage_error (opt, "missing argument");
  }

  void
  invalid_option (const std::string& opt)
  {
    usage_error (opt, "invalid option");
  }

  void
  invalid_option_val (const std::string& opt, const std::string& arg)
  {
    usage_error (opt, "invalid argument: " + arg);
  }

}

Improve error message on bad options.

Improve error message on bad options.

	* lib/libport/cli.cc: here.


// Standard headers
#include "InputArgs.hpp"

InputArgs::InputArgs(int argc, char const *const *argv)
    : argstream(argv, argv + argc) {
  read_input();
  process_input();
}

void InputArgs::process_input() {
  if (n_threads == 0)
    n_threads = std::thread::hardware_concurrency();
}

void InputArgs::read_input() {
  argstream[1] >> n_threads;
  argstream[2] >> stop_criteria;
  argstream[3] >> precision;
  argstream[4] >> angle;

  if (argstream.size() >= 5)
    argstream[5] >> debug_level;
}

// Standard headers
#include "InputArgs.hpp"

InputArgs::InputArgs(int argc, char const *const *argv)
    : argstream(argv, argv + argc) {
  read_input();
  process_input();
}

void InputArgs::process_input() {
  if (n_threads == 0)
    n_threads = std::thread::hardware_concurrency();
}

void InputArgs::read_input() {
  argstream[1] >> n_threads;
  argstream[2] >> stop_criteria;
  argstream[3] >> precision;
  argstream[4] >> angle;

  if (argstream.size() > 5)
    argstream[5] >> debug_level;
}

Correct check of number of arguments

Correct check of number of arguments


#include "misc_util.h"

namespace dlib {

    void string_fmt_time(std::string& ret) {
        time_t now = time(NULL);
        struct tm *t = localtime(&now);
        while(!strftime((char *)ret.data(), ret.capacity(), "%Y:%m:%d %H:%M", t))
            ret.reserve(ret.size() << 1);
    }

}

#include "misc_util.h"

namespace dlib {

    void string_fmt_time(std::string& ret) {
        time_t now = time(NULL);
        struct tm *t = localtime(&now);
        while(!strftime((char *)ret.data(), ret.capacity(), "%Y:%m:%d %H:%M", t))
            ret.reserve(ret.capacity() ? ret.capacity() << 1: 16);
    }

}

Fix mistake of using size instead of capacity.


#include <iostream>
#include <fstream>
#include "huffman.hpp"

using namespace algorithm;

static enum
{
    E_SUCCESS = 0,
    E_ARGUMENT_NOT_PROVIDED,
    E_FILE_NOT_FOUND,
}
StatusType;

int
main(const int argc, const char * argv[])
{
    if(argc < 2)
    {
        fprintf(stderr, "Usage: %s [file name]\n", argv[0]);
        return E_ARGUMENT_NOT_PROVIDED;
    }

    std::string f_name = argv[1];

    std::ifstream f(f_name, std::ios::binary);
    if(! f.is_open())
    {
        fprintf(stderr, "Error: File '%s' not found.\n", f_name.c_str());
        return E_FILE_NOT_FOUND;
    }

    Huffman huffman;
    huffman.CollectRuns(f);
    huffman.PrintAllRuns(stdout);

    f.close();

    return E_SUCCESS;
}

#include <iostream>
#include <fstream>
#include "include/huffman.hpp"

using namespace algorithm;

static enum
{
    E_SUCCESS = 0,
    E_ARGUMENT_NOT_PROVIDED,
    E_FILE_NOT_FOUND,
}
StatusType;

int
main(const int argc, const char * argv[])
{
    if(argc < 2)
    {
        fprintf(stderr, "Usage: %s [file name]\n", argv[0]);
        return E_ARGUMENT_NOT_PROVIDED;
    }

    std::string f_name = argv[1];

    std::ifstream f(f_name, std::ios::binary);
    if(! f.is_open())
    {
        fprintf(stderr, "Error: File '%s' not found.\n", f_name.c_str());
        return E_FILE_NOT_FOUND;
    }

    Huffman huffman;
    huffman.CollectRuns(f);
    huffman.PrintAllRuns(stdout);

    f.close();

    return E_SUCCESS;
}

Fix the path of header file

Fix the path of header file


int main(int argc, char **argv) {
  return 0;
}

#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sysexits.h>
#include <unistd.h>

char* getinput(char *buffer, size_t buflen) {
  printf("$$ ");
  return fgets(buffer, buflen, stdin);
}

int main(int argc, char **argv) {
  char buf[1024];
  pid_t pid;
  int status;

  while (getinput(buf, sizeof(buf))) {
    buf[strlen(buf) - 1] = '\0';

    if ((pid = fork()) == -1) {
      fprintf(stderr, "shell: can't fork: %s\n", strerror(errno));
      continue;
    } else if (pid == 0) {
      execlp(buf, buf, (char*) 0);
      fprintf(stderr, "shell: couldn't exec %s: %s\n", buf, strerror(errno));
      exit(EX_DATAERR);
    }

    if ((pid = waitpid(pid, &status, 0)) < 0) {
      fprintf(stderr, "shell: waitpid error: %s\n", strerror(errno));
    }
  }

  exit(EX_OK);

  return 0;
}

Add execution of simple programs

Add execution of simple programs


// https://github.com/KubaO/stackoverflown/tree/master/questions/lambda-list-37615204
#include <QtWidgets>

class Widget : public QWidget {
   struct Buyable {
      void buy(int) const {}
   };
   QList<Buyable> m_list;
   QList<QList<QWidget*>> m_widgets;
   int m_amountMultiplier = 2;
public:
   Widget() {
      auto button = [this]{ return new QPushButton(this); };
      for (int i = 0; i < 5; ++i) {
         m_list << Buyable();
         m_widgets << QList<QWidget*>{button(), button(), button()};
      }
   }
   void test() {
      Q_ASSERT(m_list.size() == m_widgets.size());
      for (int i = 0; i < m_list.size(); ++i) {
         connect(static_cast<QAbstractButton*>(m_widgets.at(i).at(2)),
                 &QAbstractButton::clicked,
                 [this, i]() {
            m_list.at(i).buy(m_amountMultiplier);}
         );
      }
   }
};

int main() {}

// https://github.com/KubaO/stackoverflown/tree/master/questions/lambda-list-37615204
#include <QtWidgets>

struct Building {
   void buy() {}
};

class Class : public QObject {
   QList<Building> m_buildings;
   QList<QList<QWidget*>> m_widgets;
public:
   Class() {
      for (int i = 0; i<m_buildings.size(); ++i)
         connect(static_cast<QAbstractButton*>(m_widgets.at(i).at(2)), &QAbstractButton::clicked, [=] {
            m_buildings[i].buy();
         });
   }
};

int main() {}

Update to match edited question.

Update to match edited question.


#include "scene.h"
#include "mesh.h"
#include "material.h"
#include <glm/gtc/matrix_transform.hpp>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>

Scene::Scene()
{

}

Scene::~Scene()
{
    for(auto it = m_meshes.begin(); it != m_meshes.end(); ++it)
    {
        delete *it;
    }
}

bool Scene::load(const char* fileName)
{
    Assimp::Importer importer;
    const aiScene* scene = importer.ReadFile(fileName,
            aiProcess_Triangulate |
            aiProcess_JoinIdenticalVertices |
            aiProcess_SortByPType);
    if(!scene)
    {
        std::cerr << "Error loading mesh " << fileName << ": " << importer.GetErrorString() << std::endl;
        return false;
    }

    for (int m = 0; m < scene->mNumMeshes; ++m) {
        const aiMesh* aiM = scene->mMeshes[m];

        Mesh* mesh = new Mesh();;
        if (!mesh->load(aiM))
        {
            return false;
        }
        m_meshes.push_back(mesh);
    }

    return true;
}

void Scene::render(Material* mat)
{
    for (auto it = m_meshes.begin(); it != m_meshes.end(); ++it)
    {
        mat->setUniform("model", (*it)->getModelMatrix());
        (*it)->render();
    }
}

#include "scene.h"
#include "mesh.h"
#include "material.h"
#include <glm/gtc/matrix_transform.hpp>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>

Scene::Scene()
{

}

Scene::~Scene()
{
    for(auto it = m_meshes.begin(); it != m_meshes.end(); ++it)
    {
        delete *it;
    }
}

bool Scene::load(const char* fileName)
{
    Assimp::Importer importer;
    const aiScene* scene = importer.ReadFile(fileName,
            aiProcess_Triangulate |
            aiProcess_JoinIdenticalVertices |
            aiProcess_SortByPType);
    if(!scene)
    {
        std::cerr << "Error loading scene " << fileName << ": " << importer.GetErrorString() << std::endl;
        return false;
    }

    for (int m = 0; m < scene->mNumMeshes; ++m) {
        const aiMesh* aiM = scene->mMeshes[m];

        Mesh* mesh = new Mesh();
        if (!mesh->load(aiM))
        {
            delete mesh;
            return false;
        }
        m_meshes.push_back(mesh);
    }

    return true;
}

void Scene::render(Material* mat)
{
    for (auto it = m_meshes.begin(); it != m_meshes.end(); ++it)
    {
        mat->setUniform("model", (*it)->getModelMatrix());
        (*it)->render();
    }
}

Fix potential memory leak in vertex shading example


// This file extends the QWebView class to add additional functionality.

#include "stdafx.h"
using namespace std;
void QWebViewWithHooks::watch(string selector, Getter getter, Callback callback){
	int uuid = watchUuid++;
	watches.push_back(make_tuple(QString::fromStdString(selector), getter, callback, uuid) );
	watchValues[uuid] = "";
	//TODO: Change to return unwatch function. However, quite lazy.
}

void QWebViewWithHooks::keyReleaseEvent(QKeyEvent * ev)
{
	// Look for all watches and get values that are changed.
	// If there is a change, call the callback.
	for(auto it = watches.begin(); it != watches.end(); ++it) {
		auto selector = get<0>(*it);
		auto getter = get<1>(*it);
		auto callback = get<2>(*it);
		auto uuid = get<3>(*it);
		auto element = this->page()->mainFrame()->findFirstElement(selector);
		auto currentValue = getter(element).toStdString();
		if(currentValue != watchValues[uuid] || ev->key() == Qt::Key_Enter || ev->key() == Qt::Key_Return)
		{
			watchValues[uuid] = currentValue;
			callback(currentValue, ev);
		}
	}
}

// This file extends the QWebView class to add additional functionality.

#include "stdafx.h"
using namespace std;
void QWebViewWithHooks::watch(string selector, Getter getter, Callback callback){
	int uuid = watchUuid++;
	watches.push_back(make_tuple(QString::fromStdString(selector), getter, callback, uuid) );
	watchValues[uuid] = "";
	//TODO: Change to return unwatch function. However, quite lazy.
}

void QWebViewWithHooks::keyReleaseEvent(QKeyEvent * ev)
{
	// Look for all watches and get values that are changed.
	// If there is a change, call the callback.
	for(auto it = watches.begin(); it != watches.end(); ++it) {
		auto selector = get<0>(*it);
		auto getter = get<1>(*it);
		auto callback = get<2>(*it);
		auto uuid = get<3>(*it);
		auto element = this->page()->mainFrame()->findFirstElement(selector);
		auto currentValue = getter(element).toStdString();
		if(currentValue != watchValues[uuid])
		{
			watchValues[uuid] = currentValue;
			callback(currentValue, ev);
		}
	}
}

[UI] Fix tack poh's merge conflict which he is aware of but doesn't want to fix.


/*
 * Chemharp, an efficient IO library for chemistry file formats
 * Copyright (C) 2015 Guillaume Fraux
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/
*/

#include "chemharp-python.hpp"

void register_trajectory() {
    /* Trajectory class *******************************************************/
    py::class_<Trajectory, boost::noncopyable>("Trajectory",
            py::init<string, py::optional<string, string>>())
        .def("read_next_step", &Trajectory::read_next_step)
        .def("read_at_step", &Trajectory::read_at_step)
        .def("write_step", &Trajectory::write_step)
        .def("done", &Trajectory::done)
        .def("close", &Trajectory::close)
        .def("nsteps", &Trajectory::nsteps)
        .def("topology",
            static_cast<void (Trajectory::*)(const Topology&)>(&Trajectory::topology))
        .def("topology",
            static_cast<void (Trajectory::*)(const string&)>(&Trajectory::topology))
    ;
}

/*
 * Chemharp, an efficient IO library for chemistry file formats
 * Copyright (C) 2015 Guillaume Fraux
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/
*/

#include "chemharp-python.hpp"

void register_trajectory() {
    /* Trajectory class *******************************************************/
    py::class_<Trajectory, boost::noncopyable>("Trajectory",
            py::init<string, py::optional<string, string>>())
        .def("read", &Trajectory::read)
        .def("read_at", &Trajectory::read_at)
        .def("write", &Trajectory::write)
        .def("done", &Trajectory::done)
        .def("close", &Trajectory::close)
        .def("nsteps", &Trajectory::nsteps)
        .def("topology",
            static_cast<void (Trajectory::*)(const Topology&)>(&Trajectory::topology))
        .def("topology",
            static_cast<void (Trajectory::*)(const string&)>(&Trajectory::topology))
    ;
}

Update the Python interface with the new names


/*
 * URELogger.cc
 *
 * Copyright (C) 2016 OpenCog Foundation
 *
 * Author: Nil Geisweiller
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "URELogger.h"

using namespace opencog;

// Create and return the single instance
Logger& opencog::ure_logger()
{
	auto bc_logger_instantiate = []() {
		Logger tmp;
		tmp.set_component("URE");
		return tmp;
	};
	static Logger bc_instance(bc_logger_instantiate());
    return bc_instance;
}

/*
 * URELogger.cc
 *
 * Copyright (C) 2016 OpenCog Foundation
 *
 * Author: Nil Geisweiller
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "URELogger.h"

using namespace opencog;

// Create and return the single instance
Logger& opencog::ure_logger()
{
	auto ure_logger_instantiate = []() {
		Logger tmp;
		tmp.set_component("URE");
		return tmp;
	};
	static Logger ure_instance(ure_logger_instantiate());
    return ure_instance;
}

Rename bc_* by ure_* in ure_logger()

Rename bc_* by ure_* in ure_logger()


#include <iostream>

using namespace std;

class BankAccount {
  char clientName[23];
  char id[15];
  double account;

public:

  BankAccount(const char _clientName[], const char _id[], double _account) {
    strcpy(clientName, _clientName);
    strcpy(id, _id);
    account = _account;
  }

  void print() {
    cout << "Name: " << clientName << '\n' <<
            "Account ID: " << id << '\n' <<
            "Account: " << account << '\n';
  }

  void transfer(double amount) {
    account += amount;
  }

  void draw(double amount) {
    account -= amount;
  }
};

int main() {
  BankAccount bankAccount("Ivan", "1", 2000);
  bankAccount.print();

  bankAccount.transfer(300);
  bankAccount.print();

  bankAccount.draw(500);
  bankAccount.print();

  return 0;
}

#include <iostream>

using namespace std;

class BankAccount {
  char clientName[23];
  char id[15];
  double account;

public:

  BankAccount(const char _clientName[], const char _id[], double _account) {
    strcpy(clientName, _clientName);
    strcpy(id, _id);
    account = _account;
  }

  void print() {
    cout << "Name: " << clientName << '\n' <<
            "Account ID: " << id << '\n' <<
            "Account: " << account << '\n';
  }

  void transfer(double amount) {
    account += amount;
  }

  void draw(double amount) {
    if (account >= amount) {
      account -= amount;
    }
  }
};

int main() {
  BankAccount bankAccount("Ivan", "1", 2000);
  bankAccount.print();

  bankAccount.transfer(300);
  bankAccount.print();

  bankAccount.draw(500);
  bankAccount.print();

  return 0;
}

Add validation for draw method. Don't draw amount if there is not enough in account