//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads
// UNSUPPORTED: c++98, c++03

// <atomic>

// constexpr atomic<T>::atomic(T value)

#include <atomic>
#include <type_traits>
#include <cassert>

struct UserType {
    int i;

    UserType() noexcept {}
    constexpr explicit UserType(int d) noexcept : i(d) {}

    friend bool operator==(const UserType& x, const UserType& y) {
        return x.i == y.i;
    }
};

template <class Tp>
void test() {
    typedef std::atomic<Tp> Atomic;
    static_assert(std::is_literal_type<Atomic>::value, "");
    constexpr Tp t(42);
    {
        constexpr Atomic a(t);
        assert(a == t);
    }
    {
        constexpr Atomic a{t};
        assert(a == t);
    }
    {
        constexpr Atomic a = ATOMIC_VAR_INIT(t);
        assert(a == t);
    }
}

int main()
{
    test<int>();
    test<UserType>();
}

//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads
// UNSUPPORTED: c++98, c++03

// NOTE: atomic<> of a TriviallyCopyable class is wrongly rejected by older
// clang versions. It was fixed right before the llvm 3.5 release. See PR18097.
// XFAIL: apple-clang-6.0, clang-3.4, clang-3.3

// <atomic>

// constexpr atomic<T>::atomic(T value)

#include <atomic>
#include <type_traits>
#include <cassert>

struct UserType {
    int i;

    UserType() noexcept {}
    constexpr explicit UserType(int d) noexcept : i(d) {}

    friend bool operator==(const UserType& x, const UserType& y) {
        return x.i == y.i;
    }
};

template <class Tp>
void test() {
    typedef std::atomic<Tp> Atomic;
    static_assert(std::is_literal_type<Atomic>::value, "");
    constexpr Tp t(42);
    {
        constexpr Atomic a(t);
        assert(a == t);
    }
    {
        constexpr Atomic a{t};
        assert(a == t);
    }
    {
        constexpr Atomic a = ATOMIC_VAR_INIT(t);
        assert(a == t);
    }
}

int main()
{
    test<int>();
    test<UserType>();
}

Mark this test as XFAIL with older compilers, since they hit PR18097

git-svn-id: 756ef344af921d95d562d9e9f9389127a89a6314@242967 91177308-0d34-0410-b5e6-96231b3b80d8


// RUN: %llvmgxx %s -S -emit-llvm -O2 -o - | grep -c {handle\\|_Unwind_Resume} | grep {\[14\]}

struct One { };
struct Two { };

void handle_unexpected () {
  try
  {
    throw;
  }
  catch (One &)
  {
    throw Two ();
  }
}

// RUN: %llvmgxx %s -S -emit-llvm -O2 -o - | ignore grep _Unwind_Resume | \
// RUN:   wc -l | grep {\[03\]}

struct One { };
struct Two { };

void handle_unexpected () {
  try
  {
    throw;
  }
  catch (One &)
  {
    throw Two ();
  }
}

Use "ignore" rather than grep tricks.

Use "ignore" rather than grep tricks.

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


/******************************************************************************
 *   Copyright (C) 2011 Frank Osterfeld <frank.osterfeld@gmail.com>           *
 *                                                                            *
 * 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. For licensing and distribution        *
 * details, check the accompanying file 'COPYING'.                            *
 *****************************************************************************/
#include "keychain_p.h"

#include <QSettings>

using namespace QKeychain;

QKeychain::Error Keychain::Private::readEntryImpl( QByteArray* pw,
                                                  const QString& key,
                                                  QString* err ) {
    Q_UNUSED( key )
    Q_ASSERT( pw );
    Q_ASSERT( err );
    return NotImplemented;
}

QKeychain::Error Keychain::Private::writeEntryImpl( const QString& key,
                                                   const QByteArray& data_,
                                                   QString* err ) {
    Q_ASSERT( err );
    return NotImplemented;
}

QKeychain::Error Keychain::Private::deleteEntryImpl( const QString& key,
                                                    QString* err ) {
    Q_ASSERT( err );
    err->clear();
    return NotImplemented;
}

QKeychain::Error Keychain::Private::entryExistsImpl( bool* exists,
                                                    const QString& key,
                                                    QString* err ) {
    Q_ASSERT( exists );
    Q_ASSERT( err );
    err->clear();
    *exists = false;
    return NotImplemented;
}

/******************************************************************************
 *   Copyright (C) 2011 Frank Osterfeld <frank.osterfeld@gmail.com>           *
 *                                                                            *
 * 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. For licensing and distribution        *
 * details, check the accompanying file 'COPYING'.                            *
 *****************************************************************************/
#include "keychain_p.h"

#include <QSettings>

using namespace QKeychain;

void ReadPasswordJob::Private::doStart() {
    q->emitFinishedWithError( NotImplemented, QString() );
}

void WritePasswordJob::Private::doStart() {
    q->emitFinishedWithError( NotImplemented, QString() );
}

Implement dbus stub for async API.

Implement dbus stub for async API.


// RUN: %clangxx_asan -O0 %s -o %t && %t

// Regression test for PR17138.

#include <assert.h>
#include <string.h>

int main() {
  char buf[1024];
  char *res = (char *)strerror_r(300, buf, sizeof(buf));
  assert(res != 0);
  return 0;
}

// RUN: %clangxx_asan -O0 %s -o %t && %t

// Regression test for PR17138.

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

int main() {
  char buf[1024];
  char *res = (char *)strerror_r(300, buf, sizeof(buf));
  printf("%p\n", res);
  return 0;
}

Remove a check from strerror_r test.

Remove a check from strerror_r test.

It's not always true: on Android, strerror_r with invalid errno
prints "Unknown error ..." to the buffer and returns 0.

This test now only checks that strerror_r does not crash.

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


//===- MRegisterInfo.cpp - Target Register Information Implementation -----===//
//
// This file implements the MRegisterInfo interface.
//
//===----------------------------------------------------------------------===//

#include "llvm/Target/MRegisterInfo.h"

MRegisterInfo::MRegisterInfo(const MRegisterDesc *D, unsigned NR,
                             regclass_iterator RCB, regclass_iterator RCE,
			     int CFSO, int CFDO)
  : Desc(D), NumRegs(NR), RegClassBegin(RCB), RegClassEnd(RCE) {
  assert(NumRegs < FirstVirtualRegister &&
         "Target has too many physical registers!");

  PhysRegClasses = new const TargetRegisterClass*[NumRegs];
  for (unsigned i = 0; i != NumRegs; ++i)
    PhysRegClasses[i] = 0;

  // Fill in the PhysRegClasses map
  for (MRegisterInfo::regclass_iterator I = regclass_begin(),
         E = regclass_end(); I != E; ++I)
    for (unsigned i=0; i < (*I)->getNumRegs(); ++i) {
      assert(PhysRegClasses[(*I)->getRegister(i)] == 0 &&
             "Register in more than one class?");
      PhysRegClasses[(*I)->getRegister(i)] = *I;
    }

  CallFrameSetupOpcode   = CFSO;
  CallFrameDestroyOpcode = CFDO;
}

MRegisterInfo::~MRegisterInfo() {
  delete[] PhysRegClasses;
}

//===- MRegisterInfo.cpp - Target Register Information Implementation -----===//
//
// This file implements the MRegisterInfo interface.
//
//===----------------------------------------------------------------------===//

#include "llvm/Target/MRegisterInfo.h"

MRegisterInfo::MRegisterInfo(const MRegisterDesc *D, unsigned NR,
                             regclass_iterator RCB, regclass_iterator RCE,
			     int CFSO, int CFDO)
  : Desc(D), NumRegs(NR), RegClassBegin(RCB), RegClassEnd(RCE) {
  assert(NumRegs < FirstVirtualRegister &&
         "Target has too many physical registers!");

  PhysRegClasses = new const TargetRegisterClass*[NumRegs];
  for (unsigned i = 0; i != NumRegs; ++i)
    PhysRegClasses[i] = 0;

  // Fill in the PhysRegClasses map
  for (MRegisterInfo::regclass_iterator I = regclass_begin(),
         E = regclass_end(); I != E; ++I)
    for (unsigned i = 0, e = (*I)->getNumRegs(); i != e; ++i) {
      unsigned Reg = (*I)->getRegister(i);
      assert(PhysRegClasses[Reg] == 0 && "Register in more than one class?");
      PhysRegClasses[Reg] = *I;
    }

  CallFrameSetupOpcode   = CFSO;
  CallFrameDestroyOpcode = CFDO;
}

MRegisterInfo::~MRegisterInfo() {
  delete[] PhysRegClasses;
}

Make it easier to debug by exposing a temporary

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


#include "FileSystem.h"
#include "android/AndroidServices.h"

#include <stdexcept>
#include <fstream>
#include <sstream>

#include <android/log.h>

namespace yarrar {
namespace filesystem {

void readFile(const std::string& relativePath, std::string& toBuffer)
{
    auto assetManager = yarrar::android::getAssetManager();
    AAsset* file = AAssetManager_open(assetManager, relativePath.c_str(), AASSET_MODE_BUFFER);
    if(!file)
    {
        throw std::runtime_error(std::string("failed to open file: ") + relativePath);
    }

    size_t len = AAsset_getLength(file);
    toBuffer.clear();
    toBuffer.resize(len);

    int ret = AAsset_read(file, &toBuffer.front(), len);
    if(ret <= 0)
    {
        throw std::runtime_error(std::string("failed to open file: ") + relativePath);
    }

    AAsset_close(file);
}

}
}

#include "FileSystem.h"
#include "android/AndroidServices.h"

#include <stdexcept>
#include <fstream>
#include <sstream>

namespace {

class AndroidFile
{
public:

    AndroidFile(const std::string& path):
        m_path(path),
        m_file(nullptr)
    {
        m_file = AAssetManager_open(yarrar::android::getAssetManager(), m_path.c_str(), AASSET_MODE_BUFFER);
        if(!m_file)
        {
            throw std::runtime_error(std::string("failed to open file: ") + m_path);
        }
    }

    ~AndroidFile()
    {
        AAsset_close(m_file);
    }

    void read(std::string& toBuffer)
    {
        if(!m_file)
        {
            throw std::runtime_error(std::string("file not opened: ") + m_path);
        }

        size_t len = AAsset_getLength(m_file);
        toBuffer.clear();
        toBuffer.resize(len);

        int ret = AAsset_read(m_file, &toBuffer.front(), len);
        if(ret <= 0)
        {
            throw std::runtime_error(std::string("read error in file: ") + m_path);
        }
    }

private:
    std::string m_path;
    AAsset* m_file;
};

}

namespace yarrar {
namespace filesystem {

void readFile(const std::string& relativePath, std::string& toBuffer)
{
    yarrar::android::log(std::string("Opening file: ") + relativePath);
    AndroidFile f(relativePath);
    f.read(toBuffer);
}

}
}

Change Android file reading to RAII.

Change Android file reading to RAII.


#include "pch.h"
#include "MidiNrpnParameterValueChangeMessage.h"

using namespace PeteBrown::Devices::Midi;

MidiNrpnParameterValueChangeMessage::MidiNrpnParameterValueChangeMessage()
{
	_rawData = ref new Windows::Storage::Streams::Buffer(TOTAL_BYTES_IN_MESSAGE);
	_rawData->Length = TOTAL_BYTES_IN_MESSAGE;

	_rawBytes = MidiMessageHelper::GetRawDataBytesFromBuffer(_rawData);

//	_type = Windows::Devices::Midi::MidiMessageType::None;
	_type = Windows::Devices::Midi::MidiMessageType::ControlChange;

	BuildBaseMessages();
}

//
//unsigned short MidiNrpnParameterValueChangeMessage::ParameterNumber::get()
//{
//
//}
//
//void MidiNrpnParameterValueChangeMessage::ParameterNumber::set(unsigned short value)
//{
//	// TODO: Set msb and lsb as well as backing store
//}
//
//
//
//unsigned short MidiNrpnParameterValueChangeMessage::Value::get()
//{
//
//}
//
//void MidiNrpnParameterValueChangeMessage::Value::set(unsigned short value)
//{
//	// TODO: Set msb and lsb as well as backing store
//}

#include "pch.h"
#include "MidiNrpnParameterValueChangeMessage.h"

using namespace PeteBrown::Devices::Midi;

MidiNrpnParameterValueChangeMessage::MidiNrpnParameterValueChangeMessage()
{
	_rawData = ref new Windows::Storage::Streams::Buffer(TOTAL_BYTES_IN_MESSAGE);
	_rawData->Length = TOTAL_BYTES_IN_MESSAGE;

	_rawBytes = MidiMessageHelper::GetRawDataBytesFromBuffer(_rawData);

	_type = Windows::Devices::Midi::MidiMessageType::None;
//	_type = Windows::Devices::Midi::MidiMessageType::ControlChange;

	BuildBaseMessages();
}

//
//unsigned short MidiNrpnParameterValueChangeMessage::ParameterNumber::get()
//{
//
//}
//
//void MidiNrpnParameterValueChangeMessage::ParameterNumber::set(unsigned short value)
//{
//	// TODO: Set msb and lsb as well as backing store
//}
//
//
//
//unsigned short MidiNrpnParameterValueChangeMessage::Value::get()
//{
//
//}
//
//void MidiNrpnParameterValueChangeMessage::Value::set(unsigned short value)
//{
//	// TODO: Set msb and lsb as well as backing store
//}

Change message type to None

Change message type to None


#include "robot_name.h"
#include <sstream>
#include <stdexcept>

using namespace std;

namespace robot_name
{

namespace
{

string next_prefix(string prefix)
{
    string next{prefix};
    const string letters{"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"};
    if (prefix[1] == letters.back()) {
        if (prefix[0] == letters.back()) {
            throw range_error("prefix combinations exhausted");
        }
        next[1] = letters[0];
        next[0] = letters[letters.find(next[0]) + 1];
    } else {
        next[1] = letters[letters.find(next[1]) + 1];
    }
    return next;
}

string generate_name()
{
    static string prefix = "AA";
    static int unit_number = 100;
    ostringstream buff;
    if (unit_number > 999) {
        prefix = next_prefix(prefix);
        unit_number = 100;
    }
    buff << prefix << unit_number++;
    return buff.str();
}

}

robot::robot()
    : name_(generate_name())
{
}

void robot::reset()
{
    name_ = generate_name();
}

}

#include "robot_name.h"
#include <iomanip>
#include <sstream>
#include <stdexcept>

using namespace std;

namespace robot_name
{

namespace
{

string next_prefix(string prefix)
{
    string next{prefix};
    const string letters{"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"};
    if (prefix[1] == letters.back()) {
        if (prefix[0] == letters.back()) {
            throw range_error("prefix combinations exhausted");
        }
        next[1] = letters[0];
        next[0] = letters[letters.find(next[0]) + 1];
    } else {
        next[1] = letters[letters.find(next[1]) + 1];
    }
    return next;
}

string generate_name()
{
    static string prefix = "AA";
    static int unit_number = 0;
    ostringstream buff;
    if (unit_number > 999) {
        prefix = next_prefix(prefix);
        unit_number = 0;
    }
    buff << prefix << setw(3) << setfill('0') << unit_number++;
    return buff.str();
}

}

robot::robot()
    : name_(generate_name())
{
}

void robot::reset()
{
    name_ = generate_name();
}

}

Increase number of robot names that can be generated.


#define __STDC_CONSTANT_MACROS

#include <stdlib.h>

extern "C" {
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libswscale/swscale.h>
}

#define CALC_FFMPEG_VERSION(a,b,c) ( a<<16 | b<<8 | c )

static void test()
{
  AVFormatContext* c = 0;
  AVCodec* avcodec = 0;
  AVFrame* frame = 0;

#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
  int err = avformat_open_input(&c, "", NULL, NULL);
#else
  int err = av_open_input_file(&c, "", NULL, 0, NULL);
#endif
}

int main() { test(); return 0; }

#define __STDC_CONSTANT_MACROS

#include <stdlib.h>

extern "C" {
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libswscale/swscale.h>
}

#define CALC_FFMPEG_VERSION(a,b,c) ( a<<16 | b<<8 | c )

static void test()
{
  AVFormatContext* c = 0;
  AVCodec* avcodec = 0;
  AVFrame* frame = 0;
  (void)avcodec;
  (void)frame;

#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
  int err = avformat_open_input(&c, "", NULL, NULL);
#else
  int err = av_open_input_file(&c, "", NULL, 0, NULL);
#endif
  (void)err;
}

int main() { test(); return 0; }

Fix ffmpeg detection with -D OPENCV_WARNINGS_ARE_ERRORS=ON option.


#include <iostream>
#include <string>
using std::string;
using std::cout;
using std::endl;

int main()
{
    string str("a simple string");

    // while
    decltype(str.size()) i = 0;
    while (i < str.size()) str[i++] = 'X';
    cout << str << endl;

    // for
    for (i = 0; i<str.size(); ++i) str[i] = 'Y';
    cout << str << endl;

    // I like range for.
    return 0;
}

#include <iostream>
#include <string>
using std::string;
using std::cout;
using std::endl;

int main()
{
    string str("a simple string");

    // while
    decltype(str.size()) i = 0;
    while (i < str.size()) str[i++] = 'X';
    cout << str << endl;

    // for
    for (i = 0; i < str.size(); str[i++] = 'Y');
    cout << str << endl;

    // I like range for.
    return 0;
}

Add the statement to expression in the FOR loop


//
//  shaderImageMask.cpp
//  shaderExample
//
//  Created by Alex Olivier on 6/6/14.
//
//  This example shows how to pass multiple textures
//  to a shader.  It uses one texture as a mask.

// Based on openFrameworks shader tutorials

#include "shaderImageMask.h"

shaderImageMask::shaderImageMask(string iFilename1, string iFilename2){

  // Create 2 image objects
  image1 = new ofxImageObject(iFilename1);
  image2 = new ofxImageObject(iFilename2);

  addChild(image1);
  addChild(image2);
}

// Destroy objects
shaderImageMask::~shaderImageMask(){

  removeChild(image1);
  removeChild(image2);

  delete image1;
  delete image2;

}

void shaderImageMask::idle(float iTime){

}

//  Override default method to set shader parameters
//  Pass 2 textures to our shaders
void shaderImageMask::setShaderParams(){

  // Pass one texture in as "tex0"
  // Pass second texture in as "mask"
  shader->setUniformTexture("tex0", *image1->tex, 1);
  shader->setUniformTexture("mask", *image2->tex, 2);

}

//
//  shaderImageMask.cpp
//  shaderExample
//
//  Created by Alex Olivier on 6/6/14.
//
//  This example shows how to pass multiple textures
//  to a shader.  It uses one texture as a mask.

// Based on openFrameworks shader tutorials

#include "shaderImageMask.h"

shaderImageMask::shaderImageMask(string iFilename1, string iFilename2){

  // Create 2 image objects
  image1 = new ofxImageObject(iFilename1);
  image2 = new ofxImageObject(iFilename2);

  addChild(image1);
  addChild(image2);
}

// Destroy objects
shaderImageMask::~shaderImageMask(){

  removeChild(image1);
  removeChild(image2);

  delete image1;
  delete image2;

}

void shaderImageMask::idle(float iTime){

}

//  Override default method to set shader parameters
//  Pass 2 textures to our shaders
void shaderImageMask::setShaderParams(){

  // Pass one texture in as "tex0"
  // Pass second texture in as "mask"
  shader->setUniformTexture("tex0", *image1->getTexture(), 1);
  shader->setUniformTexture("mask", *image2->getTexture(), 2);

}

Use getTexture method to access image tex


#include <thread>
#include <renderer.hpp>
#include <fensterchen.hpp>

int main(int argc, char* argv[])
{
  unsigned const width = 800;
  unsigned const height = 600;
  std::string const filename = "./checkerboard.ppm";

  Renderer app(width, height, filename);

  std::thread thr([&app]() { app.render(); });

  Window win(glm::ivec2(width,height));

  while (!win.shouldClose()) {
    if (win.isKeyPressed(GLFW_KEY_ESCAPE)) {
      win.stop();
    }

    glDrawPixels( width, height, GL_RGB, GL_FLOAT
                , app.colorbuffer().data());

    win.update();
  }

  thr.join();

  return 0;
}

#include <thread>
#include <renderer.hpp>
#include <fensterchen.hpp>

int main(int argc, char* argv[])
{
  unsigned const width = 600;
  unsigned const height = 600;
  std::string const filename = "./checkerboard.ppm";

  Renderer app(width, height, filename);

  std::thread thr([&app]() { app.render(); });

  Window win(glm::ivec2(width,height));

  while (!win.shouldClose()) {
    if (win.isKeyPressed(GLFW_KEY_ESCAPE)) {
      win.stop();
    }

    glDrawPixels( width, height, GL_RGB, GL_FLOAT
                , app.colorbuffer().data());

    win.update();
  }

  thr.join();

  return 0;
}

Set window size to 600x600.

Set window size to 600x600.


// ThermoFun includes
#include <Thermofun/ThermoFun.hpp>
using namespace ThermoFun;

int main()
{
    Database db("aq17.json");
}

// ThermoFun includes
#include <ThermoFun/ThermoFun.hpp>
using namespace ThermoFun;

int main()
{
    Database db("aq17.json");
}

Fix include header statement of test

Fix include header statement of test


/* Copyright 2014 Dietrich Epp.
   This file is part of Oubliette.  Oubliette is licensed under the terms
   of the 2-clause BSD license.  For more information, see LICENSE.txt. */
#include "stats.hpp"
namespace game {

const walking_stats stats::player = {
    600.0f,
    // Walking
    1200.0f, 120.0f, 300.0f, 150.0f, 3,
    // Jumping
    25, 200.0f, 250.0f, true
};

}

/* Copyright 2014 Dietrich Epp.
   This file is part of Oubliette.  Oubliette is licensed under the terms
   of the 2-clause BSD license.  For more information, see LICENSE.txt. */
#include "stats.hpp"
namespace game {

const walking_stats stats::player = {
    600.0f,
    // Walking
    1200.0f, 120.0f, 300.0f, 150.0f, 3,
    // Jumping
    25, 400.0f, 180.0f, true
};

}

Improve ability to make small jumps

Improve ability to make small jumps


//===-- main.cpp ------------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include <stdio.h>

class Point {
public:
    int x;
    int y;
    Point(int a, int b):
        x(a),
        y(b)
    {}
};

class Data {
public:
    int id;
    Point point;
    Data(int i):
        id(i),
        point(0, 0)
    {}
};

int main(int argc, char const *argv[]) {
    Data *data[1000];
    Data **ptr = data;
    for (int i = 0; i < 1000; ++i) {
        ptr[i] = new Data(i);
        ptr[i]->point.x = i;
        ptr[i]->point.y = i+1;
    }

    printf("Finished populating data.\n");
    for (int i = 0; i < 1000; ++i) {
        bool dump = argc > 1; // Set breakpoint here.
                              // Evaluate a couple of expressions (2*1000 = 2000 exprs):
                              // expr ptr[i]->point.x
                              // expr ptr[i]->point.y
        if (dump) {
            printf("data[%d] = %d (%d, %d)\n", i, ptr[i]->id, ptr[i]->point.x, ptr[i]->point.y);
        }
    }
    return 0;
}

//===-- main.cpp ------------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

class Point {
public:
    int x;
    int y;
    Point(int a, int b):
        x(a),
        y(b)
    {}
};

class Data {
public:
    int id;
    Point point;
    Data(int i):
        id(i),
        point(0, 0)
    {}
};

int main(int argc, char const *argv[]) {
    Data *data[1000];
    Data **ptr = data;
    for (int i = 0; i < 1000; ++i) {
        ptr[i] = new Data(i);
        ptr[i]->point.x = i;
        ptr[i]->point.y = i+1;
    }

    for (int i = 0; i < 1000; ++i) {
        bool dump = argc > 1; // Set breakpoint here.
                              // Evaluate a couple of expressions (2*1000 = 2000 exprs):
                              // expr ptr[i]->point.x
                              // expr ptr[i]->point.y
    }
    return 0;
}

[test] Fix a test that never compiled under -fmodules

This test #include's stdio.h, which, on at least two bots results in a
module import of MacTypes.h (due to weird SDK layering issues), which
causes the test to fail to compile.

Just don't #include stdio.h, as it's not needed for the test.

git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@323467 91177308-0d34-0410-b5e6-96231b3b80d8
(cherry picked from commit a8dbc9b1ea0560bcad050c21acb585d5e2a44a72)


#include <iostream>
#include "../../rltk/rltk.hpp"
#include <sstream>

bool tick(double duration_ms) {
	auto res = rltk::get_screen_size_px();
	std::stringstream ss;
	ss << "Frame duration: " << duration_ms << " ms. Resolution: " << res.first << "x" << res.second;
	rltk::cls_root();
	rltk::print_to_root(1, 1, ss.str());
	return false;
}

int main() {
	rltk::init(tick);
	rltk::run();
}

#include <iostream>
#include "../../rltk/rltk.hpp"
#include <sstream>

bool tick(double duration_ms) {
	auto res = rltk::get_screen_size_px();
	std::stringstream ss;
	ss << "Frame duration: " << duration_ms << " ms (" << (1000.0/duration_ms) << " FPS). Resolution: " << res.first << "x" << res.second;
	rltk::cls_root();
	rltk::print_to_root(1, 1, ss.str());
	return false;
}

int main() {
	rltk::init(tick);
	rltk::run();
}

Add simple FPS display to example.

Add simple FPS display to example.


#include <boost/optional.hpp>

#include "move.hh"
#include "../../../src/contents.hh"

namespace vick {
namespace move {

boost::optional< std::shared_ptr<change> > mvsot(contents& contents, boost::optional<int>) {
    contents.waiting_for_desired = false;
    contents.x = 0;
    for(auto x : contents.cont[contents.y]) {
        if(x == ' ' || x == '\t') contents.x++;
        else break;
    }
    return boost::none;
}

}
}

#include <boost/optional.hpp>

#include "move.hh"
#include "../../../src/contents.hh"

namespace vick {
namespace move {

boost::optional< std::shared_ptr<change> > mvsot(contents& contents, boost::optional<int>) {
    contents.waiting_for_desired = false;
    contents.x = 0;
    for(auto c : contents.cont[contents.y]) {
        if(c == ' ' || c == '\t') contents.x++;
        else break;
    }
    return boost::none;
}

}
}

Use iterator var for character as `c` instead of confusing `x` (using `contents.x` as well)


#include "nslog.h"

#include <node.h>
using namespace v8;

namespace {

Handle<Value> Log(const Arguments& args) {
  String::Utf8Value utf8_string(Local<String>::Cast(args[0]));
  nslog::Log(*utf8_string);
  return Undefined();
}

void Init(Handle<Object> exports) {
  NODE_SET_METHOD(exports, "log", Log);
}

}  // namespace

NODE_MODULE(nslog, Init)

#include "nslog.h"

#include "nan.h"
using namespace v8;

namespace {

NAN_METHOD(Log) {
  NanScope();

  String::Utf8Value utf8_string(Local<String>::Cast(args[0]));
  nslog::Log(*utf8_string);

  NanReturnUndefined();
}

void Init(Handle<Object> exports) {
  NODE_SET_METHOD(exports, "log", Log);
}

}  // namespace

NODE_MODULE(nslog, Init)

Use nan to wrap around V8 functions.

Use nan to wrap around V8 functions.


#include "logger.h"

Logger g_logger;

//------------------------------------------------------------------------------
LogViewer::LogViewer(QWidget* parent)
    : QPlainTextEdit(parent)
{ }

void LogViewer::connectLogger(Logger* logger)
{
    connect(logger, SIGNAL(logMessage(int, QString)),
            this, SLOT(appendLogMessage(int, QString)),
            Qt::QueuedConnection);
}

void LogViewer::appendLogMessage(int logLevel, QString msg)
{
    switch (logLevel)
    {
        case Logger::Warning:
            appendHtml("WARNING: " + msg);
            break;
        case Logger::Error:
            appendHtml("ERROR: " + msg);
            break;
        case Logger::Info:
            appendPlainText(msg);
            break;
    }
    ensureCursorVisible();
}

//------------------------------------------------------------------------------
std::ostream& operator<<(std::ostream& out, const QByteArray& s)
{
    out.write(s.constData(), s.size());
    return out;
}

std::ostream& operator<<(std::ostream& out, const QString& s)
{
    out << s.toUtf8();
    return out;
}

#include "logger.h"

Logger g_logger;

//------------------------------------------------------------------------------
LogViewer::LogViewer(QWidget* parent)
    : QPlainTextEdit(parent)
{ }

void LogViewer::connectLogger(Logger* logger)
{
    connect(logger, SIGNAL(logMessage(int, QString)),
            this, SLOT(appendLogMessage(int, QString)),
            Qt::QueuedConnection);
}

void LogViewer::appendLogMessage(int logLevel, QString msg)
{
    moveCursor(QTextCursor::End);
    switch (logLevel)
    {
        case Logger::Warning:
            appendHtml("WARNING: ");
            insertPlainText(msg);
            break;
        case Logger::Error:
            appendHtml("ERROR: ");
            insertPlainText(msg);
            break;
        case Logger::Info:
            appendPlainText(msg);
            break;
    }
    ensureCursorVisible();
}

//------------------------------------------------------------------------------
std::ostream& operator<<(std::ostream& out, const QByteArray& s)
{
    out.write(s.constData(), s.size());
    return out;
}

std::ostream& operator<<(std::ostream& out, const QString& s)
{
    out << s.toUtf8();
    return out;
}

Fix logging highlighting, visibility, and newlines

Avoid logging plain text messages using appendHtml(), otherwise newlines
will be stripped, and tags interpreted.  Also ensure that the cursor is
at the end of the log text to ensure the latest log statement is always
visible, and the wrong highlighting isn't inherited when inserting plain
text.


#include "game/state/rules/city/vammotype.h"
#include "game/state/gamestate.h"

namespace OpenApoc
{

const UString &VAmmoType::getPrefix()
{
	static UString prefix = "VAMMOTYPE_";
	return prefix;
}

const UString &VAmmoType::getTypeName()
{
	static UString name = "VAmmoType";
	return name;
}

sp<VAmmoType> VAmmoType::get(const GameState &state, const UString &id)
{
	auto it = state.vehicle_ammo.find(id);
	if (it == state.vehicle_ammo.end())
	{
		LogError("No vammo type matching ID \"%s\"", id);
		return nullptr;
	}
	return it->second;
}
}

#include "game/state/rules/city/vammotype.h"
#include "game/state/gamestate.h"

namespace OpenApoc
{

const UString &VAmmoType::getPrefix()
{
	static UString prefix = "VEQUIPMENTAMMOTYPE_";
	return prefix;
}

const UString &VAmmoType::getTypeName()
{
	static UString name = "VAmmoType";
	return name;
}

sp<VAmmoType> VAmmoType::get(const GameState &state, const UString &id)
{
	auto it = state.vehicle_ammo.find(id);
	if (it == state.vehicle_ammo.end())
	{
		LogError("No vammo type matching ID \"%s\"", id);
		return nullptr;
	}
	return it->second;
}
}

Revert "Revert "Vehicle ammo prefix VAMMOTYPE_ to  VEQUIPMENTAMMOTYPE_""

This reverts commit 9a77e12c4e6ceabdef5ba79b01c440bc005f4960.


#include<ros/ros.h>
#include<servo_msgs/IdBased.h>
#include<ics3/ics>

ics::ICS3* driver {nullptr};
ros::Publisher pub;

void move(const servo_msgs::IdBased::ConstPtr& msg) {
  servo_msgs::IdBased result;
  try {
    auto&& now_pos = driver->move(msg->id, ics::Angle::newDegree(msg->angle));
    result.angle = std::move(now_pos); // now_pos is universal reference, but now use after code it. use move
    result.id = msg->id;
    pub.publish(std::move(result));
  } catch (std::runtime_error e) {
    ROS_INFO("Communicate error: %s", e.what());
  }
}

int main(int argc, char** argv) {
  ros::init(argc, argv, "servo_krs_node");
  ros::NodeHandle pn {"~"};
  std::string path {"/dev/ttyUSB0"};
  pn.param<std::string>("path", path, path);
  ROS_INFO("Open servo motor path: %s", path.c_str());
  ics::ICS3 ics {std::move(path)};
  driver = &ics;
  ros::NodeHandle n {};
  ros::Subscriber sub {n.subscribe("cmd_krs", 100, move)};
  pub = n.advertise<servo_msgs::IdBased>("pose_krs", 10);
  ros::spin();
  return 0;
}

#include<ros/ros.h>
#include<servo_msgs/IdBased.h>
#include<ics3/ics>

ics::ICS3* driver {nullptr};
ros::Publisher pub;

void move(const servo_msgs::IdBased::ConstPtr& msg) {
  servo_msgs::IdBased result;
  try {
    auto now_pos = driver->move(msg->id, ics::Angle::newRadian(msg->angle));
    result.angle = std::move(now_pos);
    result.id = msg->id;
    pub.publish(std::move(result));
  } catch (std::runtime_error e) {
    ROS_INFO("Communicate error: %s", e.what());
  }
}

int main(int argc, char** argv) {
  ros::init(argc, argv, "servo_krs_node");
  ros::NodeHandle pn {"~"};
  std::string path {"/dev/ttyUSB0"};
  pn.param<std::string>("path", path, path);
  ROS_INFO("Open servo motor path: %s", path.c_str());
  ics::ICS3 ics {std::move(path)};
  driver = &ics;
  ros::NodeHandle n {};
  ros::Subscriber sub {n.subscribe("cmd_krs", 100, move)};
  pub = n.advertise<servo_msgs::IdBased>("pose_krs", 10);
  ros::spin();
  return 0;
}

Update with convert unit to radian

Update with convert unit to radian


#include "nodes/ui/float_info.h"

#include "elements/ui/float_info.h"

#include <QTableWidget>
#include <QGraphicsSimpleTextItem>

namespace nodes::ui {

FloatInfo::FloatInfo()
{
  QFont font{};
  font.setPixelSize(32);
  auto widget = new QGraphicsSimpleTextItem("0.0");
  widget->setFont(font);
  QPointF widgetPosition{};
  widgetPosition.rx() = -(widget->boundingRect().width() / 2.0);
  widgetPosition.ry() = -(widget->boundingRect().height() / 2.0);
  widget->setPos(widgetPosition);
  setCentralWidget(widget);

  m_info = widget;
}

void FloatInfo::refreshCentralWidget()
{
  if (!m_element || !m_element->inputs()[0].value) return;
  float const value{ std::get<float>(*m_element->inputs()[0].value) };
  m_info->setText(QString::number(value, 'f', 6));
}

void FloatInfo::showProperties()
{
  showCommonProperties();
  showInputsProperties();
  showOutputsProperties();
}

} // namespace nodes::ui

#include "nodes/ui/float_info.h"

#include "elements/ui/float_info.h"

#include <QTableWidget>
#include <QGraphicsSimpleTextItem>

namespace nodes::ui {

FloatInfo::FloatInfo()
{
  QFont font{};
  font.setPixelSize(32);
  auto widget = new QGraphicsSimpleTextItem("0.0");
  widget->setFont(font);
  QPointF widgetPosition{};
  widgetPosition.rx() = -(widget->boundingRect().width() / 2.0);
  widgetPosition.ry() = -(widget->boundingRect().height() / 2.0);
  widget->setPos(widgetPosition);
  setCentralWidget(widget);

  m_info = widget;
}

void FloatInfo::refreshCentralWidget()
{
  if (!m_element || !m_element->inputs()[0].value) return;
  float const value{ std::get<float>(*m_element->inputs()[0].value) };
  m_info->setText(QString::number(value, 'f', 2));
}

void FloatInfo::showProperties()
{
  showCommonProperties();
  showInputsProperties();
  showOutputsProperties();
}

} // namespace nodes::ui

Set float precision to 2 in FloatInfo

Set float precision to 2 in FloatInfo


/* Copyright (c) 2013-2014 Jeffrey Pfau
 *
 * 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 "GBAApp.h"

#include "GameController.h"

#include <QFileOpenEvent>

extern "C" {
#include "platform/commandline.h"
}

using namespace QGBA;

GBAApp::GBAApp(int& argc, char* argv[])
	: QApplication(argc, argv)
	, m_window(&m_configController)
{
#ifdef BUILD_SDL
	SDL_Init(SDL_INIT_NOPARACHUTE);
#endif

    QApplication::setApplicationName(PROJECT_NAME);
    QApplication::setApplicationVersion(PROJECT_VERSION);

	GBAArguments args = {};
    if (m_configController.parseArguments(&args, argc, argv)) {
    	m_window.argumentsPassed(&args);
    } else {
    	m_window.loadConfig();
    }
	freeArguments(&args);

    m_window.show();
}

bool GBAApp::event(QEvent* event) {
	if (event->type() == QEvent::FileOpen) {
		m_window.controller()->loadGame(static_cast<QFileOpenEvent*>(event)->file());
		return true;
	}
	return QApplication::event(event);
}

/* Copyright (c) 2013-2014 Jeffrey Pfau
 *
 * 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 "GBAApp.h"

#include "GameController.h"

#include <QFileOpenEvent>

extern "C" {
#include "platform/commandline.h"
}

using namespace QGBA;

GBAApp::GBAApp(int& argc, char* argv[])
	: QApplication(argc, argv)
	, m_window(&m_configController)
{
#ifdef BUILD_SDL
	SDL_Init(SDL_INIT_NOPARACHUTE);
#endif

    QApplication::setApplicationName(PROJECT_NAME);
    QApplication::setApplicationVersion(PROJECT_VERSION);

    m_window.show();

	GBAArguments args = {};
    if (m_configController.parseArguments(&args, argc, argv)) {
		m_window.argumentsPassed(&args);
    } else {
		m_window.loadConfig();
    }
	freeArguments(&args);
}

bool GBAApp::event(QEvent* event) {
	if (event->type() == QEvent::FileOpen) {
		m_window.controller()->loadGame(static_cast<QFileOpenEvent*>(event)->file());
		return true;
	}
	return QApplication::event(event);
}

Qt: Fix window geometry on launch when window is still hidden


//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads

// <shared_mutex>

// template <class Mutex> class shared_lock;

// shared_lock(mutex_type& m, adopt_lock_t);

#include <shared_mutex>
#include <cassert>

int main()
{
#if _LIBCPP_STD_VER > 11
    std::shared_timed_mutex m;
    m.lock();
    std::shared_lock<std::shared_timed_mutex> lk(m, std::adopt_lock);
    assert(lk.mutex() == &m);
    assert(lk.owns_lock() == true);
#endif  // _LIBCPP_STD_VER > 11
}

//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads

// <shared_mutex>

// template <class Mutex> class shared_lock;

// shared_lock(mutex_type& m, adopt_lock_t);

#include <shared_mutex>
#include <cassert>

int main()
{
#if _LIBCPP_STD_VER > 11
    std::shared_timed_mutex m;
    m.lock_shared();
    std::shared_lock<std::shared_timed_mutex> lk(m, std::adopt_lock);
    assert(lk.mutex() == &m);
    assert(lk.owns_lock() == true);
#endif  // _LIBCPP_STD_VER > 11
}

Fix PR23041. Use lock_shared() as opposed to lock() in shared_lock test.

git-svn-id: 756ef344af921d95d562d9e9f9389127a89a6314@233367 91177308-0d34-0410-b5e6-96231b3b80d8


#include "sipnondialogclient.h"

#include <QDebug>

SIPNonDialogClient::SIPNonDialogClient(SIPTransactionUser *tu): SIPClientTransaction (tu)
{}

void SIPNonDialogClient::set_remoteURI(SIP_URI& uri)
{
  remoteUri_ = uri;
}

void SIPNonDialogClient::getRequestMessageInfo(RequestType type,
                                               std::shared_ptr<SIPMessageInfo>& outMessage)
{
  SIPClientTransaction::getRequestMessageInfo(type, outMessage);

  if (type == SIP_REGISTER)
  {
    outMessage->expires = 600; // TODO: Implement resending
  }
}

bool SIPNonDialogClient::processResponse(SIPResponse& response,
                                         std::shared_ptr<SIPDialogState> state)
{
  // TODO
  Q_UNUSED(response);
  Q_UNUSED(state);

  if (getOngoingRequest() == SIP_REGISTER)
  {
    qDebug() << "Got a response for REGISTER! TODO: Processing not implemented!";
  }
  return false;
}

void SIPNonDialogClient::startTransaction(RequestType type)
{
  SIPClientTransaction::startTransaction(type);
}

void SIPNonDialogClient::registerToServer()
{
  startTransaction(SIP_REGISTER);
  emit sendNondialogRequest(remoteUri_, SIP_REGISTER);
}

#include "sipnondialogclient.h"

#include <QDebug>

SIPNonDialogClient::SIPNonDialogClient(SIPTransactionUser *tu): SIPClientTransaction (tu)
{}

void SIPNonDialogClient::set_remoteURI(SIP_URI& uri)
{
  remoteUri_ = uri;
}

void SIPNonDialogClient::getRequestMessageInfo(RequestType type,
                                               std::shared_ptr<SIPMessageInfo>& outMessage)
{
  SIPClientTransaction::getRequestMessageInfo(type, outMessage);

  if (type == SIP_REGISTER)
  {
    outMessage->expires = 600; // TODO: Implement resending

    if (!outMessage->vias.empty())
    {
      outMessage->vias.back().alias = true;
      outMessage->vias.back().rport = true;
    }
  }
}

bool SIPNonDialogClient::processResponse(SIPResponse& response,
                                         std::shared_ptr<SIPDialogState> state)
{
  // TODO
  Q_UNUSED(response);
  Q_UNUSED(state);

  if (getOngoingRequest() == SIP_REGISTER)
  {
    qDebug() << "Got a response for REGISTER! TODO: Processing not implemented!";
  }
  return false;
}

void SIPNonDialogClient::startTransaction(RequestType type)
{
  SIPClientTransaction::startTransaction(type);
}

void SIPNonDialogClient::registerToServer()
{
  startTransaction(SIP_REGISTER);
  emit sendNondialogRequest(remoteUri_, SIP_REGISTER);
}

feature(Transaction): Send alias and rport parameters to proxy.


// 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 "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/WebKit/chromium/public/WebView.h"
#include "webkit/tools/test_shell/test_shell_test.h"

using WebKit::WebView;

class WebViewTest : public TestShellTest {
};

TEST_F(WebViewTest, GetContentAsPlainText) {
  WebView* view = test_shell_->webView();
  ASSERT_TRUE(view != 0);

  view->setIsActive(true);
  EXPECT_TRUE(view->isActive());

  view->setIsActive(false);
  EXPECT_FALSE(view->isActive());

  view->setIsActive(true);
  EXPECT_TRUE(view->isActive());
}

// TODO(viettrungluu): add more tests

// 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 "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/WebKit/chromium/public/WebView.h"
#include "webkit/tools/test_shell/test_shell_test.h"

using WebKit::WebView;

class WebViewTest : public TestShellTest {
};

TEST_F(WebViewTest, ActiveState) {
  WebView* view = test_shell_->webView();
  ASSERT_TRUE(view != 0);

  view->setIsActive(true);
  EXPECT_TRUE(view->isActive());

  view->setIsActive(false);
  EXPECT_FALSE(view->isActive());

  view->setIsActive(true);
  EXPECT_TRUE(view->isActive());
}

// TODO(viettrungluu): add more tests

Rename unit test: WebViewTest.GetContentAsPlainText -> WebViewTest.ActiveState.

I'm responsible for misnaming it in the first place (cut-and-paste error). Oops.

BUG=23501
TEST=none

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

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


#include "bitfield.h"

unsigned long getBitField(uint8_t* data, int start_bit, int num_bits) {
  unsigned long ret = 0;

  int start_byte = start_bit / 8;

  if (num_bits <= 8 ) {
      // Bit fields are positioned according to big-endian bit layout, but
      // inside the bit field, values are represented as little-endian.
      // Therefore, to get the bit field, we just need to convert to big-endian
      // bit ordering to find the field, and directly use the value we find in
      // the field.
      int bit_position = start_bit % 8;
      ret = data[start_byte];
      int end_bit = bit_position + num_bits;
      ret = ret >> (8 - end_bit);
  } else {
      int end_byte = (start_bit + num_bits) / 8;

      // The lowest byte address contains the most significant bit.
      for (int i = start_byte; i <= end_byte; i++) {
          ret = ret << 8;
          ret = ret | data[i];
      }

      //Calculates value to shift bitfield of interest to LSB
      ret = ret >> (8 - ((start_bit + num_bits) % 8));
  }

  // Mask out any other bits besides those in the bitfield.
  unsigned long bitmask = (unsigned long)((0x1 << num_bits) - 1);
  return ret & bitmask;
}

#include "bitfield.h"

unsigned long getBitField(uint8_t* data, int startBit, int numBits) {
  unsigned long ret = 0;

  int startByte = startBit / 8;

  if (numBits <= 8 ) {
      // Bit fields are positioned according to big-endian bit layout, but
      // inside the bit field, values are represented as little-endian.
      // Therefore, to get the bit field, we just need to convert to big-endian
      // bit ordering to find the field, and directly use the value we find in
      // the field.
      int bitPosition = startBit % 8;
      ret = data[startByte];
      int endBit = bitPosition + numBits;
      ret = ret >> (8 - endBit);
  } else {
      int endByte = (startBit + numBits) / 8;

      // The lowest byte address contains the most significant bit.
      for (int i = startByte; i <= endByte; i++) {
          ret = ret << 8;
          ret = ret | data[i];
      }

      //Calculates value to shift bitfield of interest to LSB
      ret = ret >> (8 - ((startBit + numBits) % 8));
  }

  // Mask out any other bits besides those in the bitfield.
  unsigned long bitmask = (unsigned long)((0x1 << numBits) - 1);
  return ret & bitmask;
}

Revert naming change - we're using camelCase everywhere else.


// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <Rosetta/Enchants/Enchant.hpp>

namespace RosettaStone
{
Enchant::Enchant(Effect& effect)
{
    effects.emplace_back(effect);
}

Enchant::Enchant(std::vector<Effect>& effects)
{
    effects = effects;
}

void Enchant::ActivateTo(Character* character)
{
    for (auto& effect : effects)
    {
        effect.Apply(character);
    }
}
}  // namespace RosettaStone

// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <Rosetta/Enchants/Enchant.hpp>

namespace RosettaStone
{
Enchant::Enchant(Effect& effect)
{
    effects.emplace_back(effect);
}

Enchant::Enchant(std::vector<Effect>& _effects)
{
    effects = _effects;
}

void Enchant::ActivateTo(Character* character)
{
    for (auto& effect : effects)
    {
        effect.Apply(character);
    }
}
}  // namespace RosettaStone

fix: Correct argument name of constructor (effects -> _effects)


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

#include <iostream>

#include "environment.hpp"

using namespace gym;

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

  double totalReward = 0;
  size_t totalSteps = 0;

  Environment env(host, port, environment);
  env.reset();

  while (1)
  {
    env.step(env.action_space.sample());
    env.render();
    totalReward += env.reward;
    totalSteps += 1;

    if (env.done)
    {
      break;
    }
  }

  std::cout << "Total steps: " << totalSteps << " reward: " << totalReward
      << std::endl;

  return 0;
}

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

#include <iostream>

#include "environment.hpp"

using namespace gym;

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

  double totalReward = 0;
  size_t totalSteps = 0;

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

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

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

    env.step(action);

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

    if (env.done)
    {
      break;
    }

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

  std::cout << "Total steps: " << totalSteps << " reward: " << totalReward
      << std::endl;

  return 0;
}

Use demo server as default and record performance.


// 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/test/ui/ui_test.h"

class LocaleTestsDa : public UITest {
 public:
  LocaleTestsDa() : UITest() {
    launch_arguments_.AppendSwitchWithValue(L"lang", L"da");
  }
};

class LocaleTestsHe : public UITest {
 public:
  LocaleTestsHe() : UITest() {
    launch_arguments_.AppendSwitchWithValue(L"lang", L"he");
  }
};

class LocaleTestsZhTw : public UITest {
 public:
  LocaleTestsZhTw() : UITest() {
    launch_arguments_.AppendSwitchWithValue(L"lang", L"zh-tw");
  }
};

#if defined(OS_WIN) || defined(OS_LINUX)
// These 3 tests started failing between revisions 13115 and 13120.
// See bug 9758.
TEST_F(LocaleTestsDa, TestStart) {
  // Just making sure we can start/shutdown cleanly.
}

TEST_F(LocaleTestsHe, TestStart) {
  // Just making sure we can start/shutdown cleanly.
}

TEST_F(LocaleTestsZhTw, TestStart) {
  // Just making sure we can start/shutdown cleanly.
}
#endif

// 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/test/ui/ui_test.h"

class LocaleTestsDa : public UITest {
 public:
  LocaleTestsDa() : UITest() {
    launch_arguments_.AppendSwitchWithValue(L"lang", L"da");
  }
};

class LocaleTestsHe : public UITest {
 public:
  LocaleTestsHe() : UITest() {
    launch_arguments_.AppendSwitchWithValue(L"lang", L"he");
  }
};

class LocaleTestsZhTw : public UITest {
 public:
  LocaleTestsZhTw() : UITest() {
    launch_arguments_.AppendSwitchWithValue(L"lang", L"zh-TW");
  }
};

#if defined(OS_WIN) || defined(OS_LINUX)
// These 3 tests started failing between revisions 13115 and 13120.
// See bug 9758.
TEST_F(LocaleTestsDa, TestStart) {
  // Just making sure we can start/shutdown cleanly.
}

TEST_F(LocaleTestsHe, TestStart) {
  // Just making sure we can start/shutdown cleanly.
}

TEST_F(LocaleTestsZhTw, TestStart) {
  // Just making sure we can start/shutdown cleanly.
}
#endif

Change zh-tw to zh-TW when it's used to find the locale data pack on Linux (case-sensitive file system).

BUG=8647
TEST=Pass ui test on Linux
TBR=tony

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

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

Former-commit-id: 8d555edb07749e964ff328987812c596bfc4ff5a


//===-- main.cpp ------------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

void bar(int const *foo) {
  __builtin_trap(); // Set break point at this line.
}

int main() {
  int foo[] = {1,2,3};
  bar(foo);
}

//===-- main.cpp ------------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

bool bar(int const *foo) {
  return foo != 0; // Set break point at this line.
}

int main() {
  int foo[] = {1,2,3};
  return bar(foo);
}

Fix rdar-13338477 test-case for Linux.
- Using __builtin_trap confuses the stack unwinder
- __builtin_trap specific test will be added shortly

git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@181441 91177308-0d34-0410-b5e6-96231b3b80d8


// RUN: grep -Ev "// *[A-Z-]+:" %s > %t.cpp
// RUN: remove-cstr-calls . %t.cpp --
// RUN: FileCheck -input-file=%t.cpp %s
// REQUIRES: shell

namespace std {
template<typename T> class allocator {};
template<typename T> class char_traits {};
template<typename C, typename T, typename A> struct basic_string {
  basic_string();
  basic_string(const C *p, const A& a = A());
  const C *c_str() const;
};
typedef basic_string<char, std::char_traits<char>, std::allocator<char> > string;
}
namespace llvm { struct StringRef { StringRef(const char *p); }; }

void f1(const std::string &s) {
  f1(s.c_str());
  // CHECK: void f1
  // CHECK-NEXT: f1(s)
}
void f2(const llvm::StringRef r) {
  std::string s;
  f2(s.c_str());
  // CHECK: std::string s;
  // CHECK-NEXT: f2(s)
}
void f3(const llvm::StringRef &r) {
  std::string s;
  f3(s.c_str());
  // CHECK: std::string s;
  // CHECK: f3(s)
}

// RUN: grep -Ev "// *[A-Z-]+:" %s > %t.cpp
// RUN: remove-cstr-calls . %t.cpp --
// RUN: FileCheck -input-file=%t.cpp %s
// REQUIRES: shell

namespace std {
template<typename T> class allocator {};
template<typename T> class char_traits {};
template<typename C, typename T, typename A> struct basic_string {
  basic_string();
  basic_string(const C *p, const A& a = A());
  const C *c_str() const;
};
typedef basic_string<char, std::char_traits<char>, std::allocator<char> > string;
}
namespace llvm {
struct StringRef {
  StringRef(const char *p);
  StringRef(const std::string &);
};
}

void f1(const std::string &s) {
  f1(s.c_str());
  // CHECK: void f1
  // CHECK-NEXT: f1(s)
}
void f2(const llvm::StringRef r) {
  std::string s;
  f2(s.c_str());
  // CHECK: std::string s;
  // CHECK-NEXT: f2(s)
}
void f3(const llvm::StringRef &r) {
  std::string s;
  f3(s.c_str());
  // CHECK: std::string s;
  // CHECK: f3(s)
}

Fix a remove-cstr-calls test that fails checking of the produced code.

git-svn-id: a34e9779ed74578ad5922b3306b3d80a0c825546@184314 91177308-0d34-0410-b5e6-96231b3b80d8


// 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 "ppapi/proxy/ppapi_messages.h"

#include "base/file_path.h"
#include "ipc/ipc_channel_handle.h"
#include "ppapi/c/dev/pp_file_info_dev.h"
#include "ppapi/c/ppb_var.h"

// This actually defines the implementations of all the IPC message functions.
#define MESSAGES_INTERNAL_IMPL_FILE "ppapi/proxy/ppapi_messages_internal.h"
#include "ipc/ipc_message_impl_macros.h"

Add a blank line to force this file to be recompiled on Mac on the bots.

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

Former-commit-id: 30212b62da779717dbf5b35a8bd0a4fdbf930d27


#include <Nazara/Audio.hpp>
#include <Nazara/Core.hpp>
#include <Nazara/Graphics.hpp>
#include <Nazara/Lua.hpp>
#include <Nazara/Network.hpp>
#include <Nazara/Noise.hpp>
#include <Nazara/Physics.hpp>
#include <Nazara/Renderer.hpp>
#include <Nazara/Utility.hpp>
#include <NDK/Application.hpp>
#include <iostream>

int main(int argc, char* argv[])
{
	// This "example" has only one purpose: Giving an empty project for you to test whatever you want
	// If you wish to have multiple test projects, you only have to copy/paste this directory and change the name in the build.lua
	Ndk::Application application(argc, argv);

	// Do what you want here

	return EXIT_SUCCESS;
}

#include <Nazara/Audio.hpp>
#include <Nazara/Core.hpp>
#include <Nazara/Graphics.hpp>
#include <Nazara/Lua.hpp>
#include <Nazara/Network.hpp>
#include <Nazara/Noise.hpp>
#include <Nazara/Physics2D.hpp>
#include <Nazara/Physics3D.hpp>
#include <Nazara/Renderer.hpp>
#include <Nazara/Utility.hpp>
#include <NDK/Application.hpp>
#include <iostream>

int main(int argc, char* argv[])
{
	// This "example" has only one purpose: Giving an empty project for you to test whatever you want
	// If you wish to have multiple test projects, you only have to copy/paste this directory and change the name in the build.lua
	Ndk::Application application(argc, argv);

	// Do what you want here

	return EXIT_SUCCESS;
}

Example: Fix compilation of Tut00 after Physics change


// RUN: %clang_analyze_cc1 -analyzer-checker=optin.osx.OSObjectCStyleCast %s -verify
#include "os_object_base.h"

struct OSArray : public OSObject {
  unsigned getCount();
};

struct A {
  int x;
};
struct B : public A {
  unsigned getCount();
};

unsigned warn_on_explicit_downcast(OSObject * obj) {
  OSArray *a = (OSArray *) obj; // expected-warning{{C-style cast of OSObject. Use OSDynamicCast instead}}
  return a->getCount();
}

void no_warn_on_upcast(OSArray *arr) {
  OSObject *obj = (OSObject *) arr;
  obj->retain();
  obj->release();
}

unsigned no_warn_on_dynamic_cast(OSObject *obj) {
  OSArray *a = OSDynamicCast(OSArray, obj);
  return a->getCount();
}

unsigned long no_warn_on_primitive_conversion(OSArray *arr) {
  return (unsigned long) arr;
}

unsigned no_warn_on_other_type_cast(A *a) {
  B *b = (B *) a;
  return b->getCount();
}

// RUN: %clang_analyze_cc1 -analyzer-checker=optin.osx.OSObjectCStyleCast %s -verify
#include "os_object_base.h"

struct OSArray : public OSObject {
  unsigned getCount();
};

struct A {
  int x;
};
struct B : public A {
  unsigned getCount();
};

unsigned warn_on_explicit_downcast(OSObject * obj) {
  OSArray *a = (OSArray *) obj; // expected-warning{{C-style cast of OSObject. Use OSDynamicCast instead}}
  return a->getCount();
}

void no_warn_on_upcast(OSArray *arr) {
  OSObject *obj = (OSObject *) arr;
  obj->retain();
  obj->release();
}

unsigned no_warn_on_dynamic_cast(OSObject *obj) {
  OSArray *a = OSDynamicCast(OSArray, obj);
  return a->getCount();
}

__SIZE_TYPE__ no_warn_on_primitive_conversion(OSArray *arr) {
  return (__SIZE_TYPE__) arr;
}

unsigned no_warn_on_other_type_cast(A *a) {
  B *b = (B *) a;
  return b->getCount();
}

Fix test to pass on LLP64 targets

Fix test to pass on LLP64 targets

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


// Ouzel by Elviss Strazdins

#include "RenderTarget.hpp"
#include "Graphics.hpp"
#include "Texture.hpp"

namespace ouzel::graphics
{
    RenderTarget::RenderTarget(Graphics& initGraphics,
                               const std::vector<Texture*>& initColorTextures,
                               Texture* initDepthTexture):
        resource{*initGraphics.getDevice()},
        colorTextures{initColorTextures},
        depthTexture{initDepthTexture}
    {
        std::set<std::size_t> colorTextureIds;

        for (const auto& colorTexture : colorTextures)
            colorTextureIds.insert(colorTexture ? colorTexture->getResource() : 0);

        initGraphics.addCommand(std::make_unique<InitRenderTargetCommand>(resource,
                                                                          colorTextureIds,
                                                                          depthTexture ? depthTexture->getResource() : RenderDevice::ResourceId(0)));
    }
}

// Ouzel by Elviss Strazdins

#include "RenderTarget.hpp"
#include "Graphics.hpp"
#include "Texture.hpp"

namespace ouzel::graphics
{
    RenderTarget::RenderTarget(Graphics& initGraphics,
                               const std::vector<Texture*>& initColorTextures,
                               Texture* initDepthTexture):
        resource{*initGraphics.getDevice()},
        colorTextures{initColorTextures},
        depthTexture{initDepthTexture}
    {
        std::set<RenderDevice::ResourceId> colorTextureIds;

        for (const auto& colorTexture : colorTextures)
            colorTextureIds.insert(colorTexture ? colorTexture->getResource() : 0);

        initGraphics.addCommand(std::make_unique<InitRenderTargetCommand>(resource,
                                                                          colorTextureIds,
                                                                          depthTexture ? depthTexture->getResource() : RenderDevice::ResourceId(0)));
    }
}

Use ResourceId instead of size_t

Use ResourceId instead of size_t


#include "grune/grammars/anbncn.hpp"
#include "grune/grammars/turtle.hpp"
#include "grune/grammars/tom_dick_and_harry.hpp"
#include "grune-yaml/grune-yaml.hpp"

#include <fstream>

#define MAKE_SAMPLE(name) \
    do { \
        std::ofstream out(#name ".yaml"); \
        out << YAML::Node(grune::grammars::name()) << std::endl; \
    } while(0)

int main()
{
    MAKE_SAMPLE(anbncn);
    MAKE_SAMPLE(cyclic_manhattan_turtle);
    MAKE_SAMPLE(tom_dick_and_harry);
}

#include "grune/grammars/anbncn.hpp"
#include "grune/grammars/turtle.hpp"
#include "grune/grammars/tom_dick_and_harry.hpp"
#include "grune-yaml/grune-yaml.hpp"

#include <fstream>

#define MAKE_SAMPLE_IMPL(name) \
    do { \
        std::ofstream out(#name ".yaml"); \
        out << YAML::Node(grune::grammars::name()) << std::endl; \
    } while(0)

#ifndef COVERITY_BUILD
#define MAKE_SAMPLE(name) MAKE_SAMPLE_IMPL(name)
#else
#include <coverity-test-separation.h>
#define MAKE_SAMPLE(name) \
    do { \
        COVERITY_TS_START_TEST(#name); \
        MAKE_SAMPLE_IMPL(name); \
        COVERITY_TS_END_TEST(); \
    } while(0)
#endif

int main()
{
#ifdef COVERITY_BUILD
    COVERITY_TS_SET_SUITE_NAME("grune-yaml/make-samples");
#endif
    MAKE_SAMPLE(anbncn);
    MAKE_SAMPLE(cyclic_manhattan_turtle);
    MAKE_SAMPLE(tom_dick_and_harry);
}

Add test separation for YAML make-samples


// REQUIRES: x86-registered-target,x86-64-registered-target
// RUN: %clang_cc1 -triple x86_64-apple-darwin -S %s -o %t-64.s
// RUN: FileCheck -check-prefix CHECK-LP64 --input-file=%t-64.s %s
// RUN: %clang_cc1 -triple i386-apple-darwin -S %s -o %t-32.s
// RUN: FileCheck -check-prefix CHECK-LP32 --input-file=%t-32.s %s

struct A {};

struct B
{
  operator A&();
};

struct D : public B {
  operator A();
};

extern B f();
extern D d();

int main() {
	const A& rca = f();
	const A& rca2 = d();
}

// CHECK-LP64: callq    __ZN1BcvR1AEv
// CHECK-LP64: callq    __ZN1BcvR1AEv

// CHECK-LP32: calll     L__ZN1BcvR1AEv
// CHECK-LP32: calll     L__ZN1BcvR1AEv

// RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm %s -o - | \
// RUN: FileCheck %s
// RUN: %clang_cc1 -triple i386-apple-darwin -emit-llvm %s -o - | \
// RUN: FileCheck %s

struct A {};

struct B
{
  operator A&();
};

struct D : public B {
  operator A();
};

extern B f();
extern D d();

int main() {
	const A& rca = f();
	const A& rca2 = d();
}

// CHECK: call %struct.A* @_ZN1BcvR1AEv
// CHECK: call %struct.A* @_ZN1BcvR1AEv

Check IR on this test.

Check IR on this test.

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


#include <iostream>
#include <string>
#include <vector>

#include "Window.h"
#include "ProceduralRenderer.h"

#include <glbinding/gl/gl.h>
#include <glbinding/Binding.h>

using namespace gl;

int main() {
    Window w;
    w.init("procedural");

    glbinding::Binding::initialize();
    std::cout << "OpenGL Version: " << glGetString(GL_VERSION) << std::endl;
    w.initAfterGL();

    std::vector<std::string> includes {"gradient", "chess"};
    auto renderer = std::make_unique<ProceduralRenderer>(includes);

    w.setRenderer(std::move(renderer));
    w.loop();

    return 0;
}

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <sstream>

#include "Window.h"
#include "ProceduralRenderer.h"

#include <glbinding/gl/gl.h>
#include <glbinding/Binding.h>

using namespace gl;

std::map<std::string, std::string> parseArguments(int argc, char * argv[])
{
    std::vector<std::string> arguments;
    for (int i = 0; i < argc; ++i)
    {
        arguments.push_back(argv[i]);
    }

    std::map<std::string, std::string> options;
    for (auto& argument : arguments)
    {
        const auto equalPosition = argument.find("=");
        if (argument.substr(0, 2) == "--" && equalPosition != std::string::npos)
        {
            const auto key = argument.substr(2, equalPosition - 2);
            const auto value = argument.substr(equalPosition + 1);
            options[key] = value;
        }
    }
    return options;
}

int main(int argc, char * argv[]) {
    const auto options = parseArguments(argc, argv);

    Window w;
    if (options.find("gl") != options.end())
    {
        const auto version = options.at("gl");
        const auto dotPosition = version.find(".");
        if (dotPosition != std::string::npos)
        {
            int major, minor;
            std::istringstream(version.substr(0, dotPosition)) >> major;
            std::istringstream(version.substr(dotPosition + 1)) >> minor;
            w.requestGLVersion(major, minor);
        }
    }
    w.init("procedural");

    glbinding::Binding::initialize();
    std::cout << "OpenGL Version: " << glGetString(GL_VERSION) << std::endl;
    w.initAfterGL();

    std::vector<std::string> includes {"gradient", "chess"};
    auto renderer = std::make_unique<ProceduralRenderer>(includes);

    w.setRenderer(std::move(renderer));
    w.loop();

    return 0;
}

Add argument for requesting specific OpenGl version


// RUN: clang-cc -fsyntax-only -verify %s

namespace N { };

namespace A = N;

int B; // expected-note {{previous definition is here}}
namespace B = N; // expected-error {{redefinition of 'B' as different kind of symbol}}

namespace C { } // expected-note {{previous definition is here}}
namespace C = N; // expected-error {{redefinition of 'C'}}

int i;
namespace D = i; // expected-error {{expected namespace name}}

namespace E = N::Foo; // expected-error {{expected namespace name}}

namespace F {
  namespace A { namespace B { } } // expected-note {{candidate found by name lookup is 'F::A::B'}}
  namespace B { } // expected-note {{candidate found by name lookup is 'F::B'}}
  using namespace A;
  namespace D = B; // expected-error {{reference to 'B' is ambiguous}}
}

namespace G {
  namespace B = N;
}

namespace H {
  namespace A1 { }
  namespace A2 { }

  // These all point to A1.
  namespace B = A1; // expected-note {{previous definition is here}}
  namespace B = A1;
  namespace C = B;
  namespace B = C;

  namespace B = A2; // expected-error {{redefinition of 'B' as different kind of symbol}}
}

namespace I {
  namespace A1 { int i; }

  namespace A2 = A1;
}

int f() {
  return I::A2::i;
}

namespace J {
  namespace A {
    namespace B { void func (); }
  }

  namespace C = A;

  using namespace C::B;

  void g() {
    func();
  }
}

Check in test for namespace aliases+using directives.

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


#include "list.h"
#include "gtest/gtest.h"
#include <string>

class listTest : public testing::Test {
 protected:
  virtual void SetUp() {
    // NOT YET IMPLEMENTED
  }
  virtual void TearDown() {}
  // setup fixtures
  list<int> list_1;
  list<int> list_2;
  list<std::string> list_str;
};

TEST(listNodeTest, DefaultCtor) {
  int element_1 = 100;
  std::string element_2("Hello world");
  listNode<int> node_1(element_1);
  listNode<std::string> node_2(element_2);
  EXPECT_EQ(element_1, node_1.element_);
  EXPECT_EQ(element_2, node_2.element_);
  EXPECT_EQ(nullptr, node_2.prev_);
  EXPECT_EQ(nullptr, node_2.next_);
  // test the move constructor for node:
  listNode<int> node_3(std::move(element_1));
  listNode<std::string> node_4(std::move(element_2));
  EXPECT_EQ(100, node_3.element_);
  EXPECT_EQ("Hello world", node_4.element_);
  EXPECT_TRUE(element_2.empty());
}

TEST_F(listTest, DefaultCtor) {
  list<int> list_temp;
  EXPECT_EQ(0u, list_temp.size());
}

#include "list.h"
#include "gtest/gtest.h"
#include <string>

class listTest : public testing::Test {
 protected:
  virtual void SetUp() {
    // NOT YET IMPLEMENTED
  }
  virtual void TearDown() {}
  // setup fixtures
  list<int> list_1;
  list<int> list_2;
  list<std::string> list_str;
};

// test the helper class listNodeTest
// this is a canonical example of writing testable code:
// to test private members, just write another helper class
// and make its data public
TEST(listNodeTest, DefaultCtor) {
  int element_1 = 100;
  std::string element_2("Hello world");
  listNode<int> node_1(element_1);
  listNode<std::string> node_2(element_2);
  EXPECT_EQ(element_1, node_1.element_);
  EXPECT_EQ(element_2, node_2.element_);
  EXPECT_EQ(nullptr, node_2.prev_);
  EXPECT_EQ(nullptr, node_2.next_);
  // test the move constructor for node:
  listNode<int> node_3(std::move(element_1));
  listNode<std::string> node_4(std::move(element_2));
  EXPECT_EQ(100, node_3.element_);
  EXPECT_EQ("Hello world", node_4.element_);
  EXPECT_TRUE(element_2.empty());
}

TEST_F(listTest, DefaultCtor) {
  list<int> list_temp;
  EXPECT_EQ(0u, list_temp.size());
}

Add more documentation for listNodeTest

list: Add more documentation for listNodeTest


/*
 *
 * Copyright 2019 gRPC authors.
 *
 * 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 <stdbool.h>
#include <stdint.h>

#include "src/core/lib/slice/b64.h"
#include "include/grpc/support/alloc.h"

bool squelch = true;
bool leak_check = true;

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  if (size < 2) return 0;
  const bool url_safe = static_cast<uint8_t>(0x100) < data[0];
  const bool multiline = static_cast<uint8_t>(0x100) < data[1];
  char* res = grpc_base64_encode(reinterpret_cast<const char*>(data + 2),
                                 size - 2, url_safe, multiline);
  gpr_free(res);
  return 0;
}

/*
 *
 * Copyright 2019 gRPC authors.
 *
 * 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 <stdbool.h>
#include <stdint.h>

#include "include/grpc/support/alloc.h"
#include "src/core/lib/slice/b64.h"

bool squelch = true;
bool leak_check = true;

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  if (size < 2) return 0;
  const bool url_safe = static_cast<uint8_t>(0x100) < data[0];
  const bool multiline = static_cast<uint8_t>(0x100) < data[1];
  char* res = grpc_base64_encode(reinterpret_cast<const char*>(data + 2),
                                 size - 2, url_safe, multiline);
  gpr_free(res);
  return 0;
}

Fix include order for clang_format.

Fix include order for clang_format.


#include "jsonparser.h"

JSONParser::JSONParser(QObject *parent) :
    QObject(parent)
{
    clearData();
}

void JSONParser::clearData()
{
    p_data = "{ ";
}

void JSONParser::addVariable(const QString name, int value)
{
    p_data.append("\"");
    p_data.append(name);
    p_data.append("\":");
    p_data.append(QString::number(value));
    p_data.append(",");
}

void JSONParser::setData(QString &value)
{
    if(value != p_data)
    {
        p_data = value;
        emit dataChanged();
    }
}

QString JSONParser::data() {
    QString result = p_data.remove(p_data.length() - 1, 1);
    result.append(" }");

    return result;
}

#include "jsonparser.h"

JSONParser::JSONParser(QObject *parent) :
    QObject(parent)
{
    clearData();
}

void JSONParser::clearData()
{
    p_data = "{ ";
}

void JSONParser::addVariable(const QString name, int value)
{
    p_data.append("\"");
    p_data.append(name);
    p_data.append("\":");
    p_data.append(QString::number(value));
    p_data.append(",");
}

void JSONParser::setData(QString &value)
{
    if(value != p_data)
    {
        p_data = value;
        emit dataChanged();
    }
}

QString JSONParser::data() {
    QString result = p_data;
    result.remove(result.length() - 1, 1);
    result.append(" }");

    return result;
}

Fix C++: getter changed data - JSONPARSER


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

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

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

// chpl_error() ends execution
void chpl_error(const char* message, int32_t lineno, c_string filename) {
  __coverity_panic__();
}

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

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

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

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

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

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

Fix unrecognized types in Coverity Scan model chpl_*error() decls.


// RUN: clang-cc -emit-llvm -triple x86_64-apple-darwin10 -o - %s | FileCheck %s
template<typename T>
struct X {
  static T member1;
  static T member2;
  static T member3;
};

template<typename T>
T X<T>::member1;

template<typename T>
T X<T>::member2 = 17;

// CHECK: @_ZN1XIiE7member1E = global i32 0
template int X<int>::member1;

// CHECK: @_ZN1XIiE7member2E = global i32 17
template int X<int>::member2;

// For implicit instantiation of
long& get(bool Cond) {
  // CHECK: @_ZN1XIlE7member1E = weak global i64 0
  // CHECK: @_ZN1XIlE7member2E = weak global i64 17
  return Cond? X<long>::member1 : X<long>::member2;
}

// RUN: clang-cc -emit-llvm -triple x86_64-apple-darwin10 -o - %s | FileCheck %s
template<typename T>
struct X {
  static T member1;
  static T member2;
  static T member3;
};

template<typename T>
T X<T>::member1;

template<typename T>
T X<T>::member2 = 17;

// CHECK: @_ZN1XIiE7member1E = global i32 0
template int X<int>::member1;

// CHECK: @_ZN1XIiE7member2E = global i32 17
template int X<int>::member2;

// For implicit instantiation of
long& get(bool Cond1, bool Cond2) {
  // CHECK: @_ZN1XIlE7member1E = weak global i64 0
  // CHECK: @_ZN1XIlE7member2E = weak global i64 17
  // CHECK: @_ZN1XIlE7member3E = external global i64
  return Cond1? X<long>::member1
       : Cond2? X<long>::member2
              : X<long>::member3;
}

Check the implicit instantiation of a static data member of a class
template that has no out-of-line definition.

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


#include "caffe2/operators/scale_op.h"

namespace caffe2 {

REGISTER_CPU_OPERATOR(Scale, ScaleOp<float, CPUContext>);
OPERATOR_SCHEMA(Scale)
  .NumInputs(1)
  .NumOutputs(1)
  .AllowInplace({{0, 0}})
  .SetDoc(R"DOC(
Scale takes one input data (Tensor<float>) and produces one output data
(Tensor<float>) whose value is the input data tensor scaled element-wise.
)DOC")
  .Arg("scale", "(float, default 1.0) the scale to apply.");

class GetScaleGradient : public GradientMakerBase {
  using GradientMakerBase::GradientMakerBase;
  vector<OperatorDef> GetGradientDefs() override {
    return SingleGradientDef(
        "Scale", "",
        vector<string>{GO(0)},
        vector<string>{GI(0)},
        Def().arg());
  }
};
REGISTER_GRADIENT(Scale, GetScaleGradient);
}  // namespace caffe2

#include "caffe2/operators/scale_op.h"

namespace caffe2 {

REGISTER_CPU_OPERATOR(Scale, ScaleOp<float, CPUContext>);
OPERATOR_SCHEMA(Scale)
  .NumInputs(1)
  .NumOutputs(1)
  .AllowInplace({{0, 0}})
  .SetDoc(R"DOC(
Scale takes one input data (Tensor<float>) and produces one output data
(Tensor<float>) whose value is the input data tensor scaled element-wise.
)DOC")
  .Arg("scale", "(float, default 1.0) the scale to apply.");

class GetScaleGradient : public GradientMakerBase {
  using GradientMakerBase::GradientMakerBase;
  vector<OperatorDef> GetGradientDefs() override {
    // CopyArguments is true by default so the "scale" arg is going to be copied
    return SingleGradientDef(
        "Scale", "", vector<string>{GO(0)}, vector<string>{GI(0)});
  }
};
REGISTER_GRADIENT(Scale, GetScaleGradient);
}  // namespace caffe2

Fix warning in ScaleOp grad

Fix warning in ScaleOp grad

Summary: #accept2ship

Reviewed By: Yangqing

Differential Revision: D4386362

fbshipit-source-id: 634410e73034ac31b7f2bec39f41c52ea9935e3a


/*
 * This source file is part of MyGUI. For the latest info, see http://mygui.info/
 * Distributed under the MIT License
 * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT)
 */

#include "MyGUI_ControllerRepeatClick.h"

namespace MyGUI
{
	ControllerRepeatClick::ControllerRepeatClick() :
		mInit(0.5),
		mStep(0.1),
		mTimeLeft(0)
	{
	}

	ControllerRepeatClick::~ControllerRepeatClick()
	{
	}

	bool ControllerRepeatClick::addTime(MyGUI::Widget* _widget, float _time)
	{
		if(mTimeLeft == 0)
			mTimeLeft = mInit;

		mTimeLeft -= _time;
		while (mTimeLeft <= 0)
		{
			mTimeLeft += mStep;
			eventRepeatClick(_widget, this);
		}
		return true;
	}

	void ControllerRepeatClick::setRepeat(float init, float step)
	{
		mInit = init;
		mStep = step;
	}

	void ControllerRepeatClick::setProperty(const std::string& _key, const std::string& _value)
	{
	}

	void ControllerRepeatClick::prepareItem(MyGUI::Widget* _widget)
	{
	}
}

/*
 * This source file is part of MyGUI. For the latest info, see http://mygui.info/
 * Distributed under the MIT License
 * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT)
 */

#include "MyGUI_ControllerRepeatClick.h"

namespace MyGUI
{
	ControllerRepeatClick::ControllerRepeatClick() :
		mInit(0.5),
		mStep(0.1),
		mTimeLeft(0)
	{
	}

	ControllerRepeatClick::~ControllerRepeatClick()
	{
	}

	bool ControllerRepeatClick::addTime(MyGUI::Widget* _widget, float _time)
	{
		if(mTimeLeft == 0)
			mTimeLeft = mInit;

		if (mStep <= 0)
			return true;

		mTimeLeft -= _time;
		while (mTimeLeft <= 0)
		{
			mTimeLeft += mStep;
			eventRepeatClick(_widget, this);
		}
		return true;
	}

	void ControllerRepeatClick::setRepeat(float init, float step)
	{
		mInit = init;
		mStep = step;
	}

	void ControllerRepeatClick::setProperty(const std::string& _key, const std::string& _value)
	{
	}

	void ControllerRepeatClick::prepareItem(MyGUI::Widget* _widget)
	{
	}
}

Fix ControllerRepeatClick potential infinite loop for bad step values


// Copyright 2016 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.

// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com

#include "core/fpdfapi/fpdf_page/cpdf_contentmarkitem.h"

#include "core/fpdfapi/fpdf_parser/include/cpdf_dictionary.h"

CPDF_ContentMarkItem::CPDF_ContentMarkItem() {
  m_ParamType = None;
}

CPDF_ContentMarkItem::CPDF_ContentMarkItem(const CPDF_ContentMarkItem& src) {
  m_MarkName = src.m_MarkName;
  m_ParamType = src.m_ParamType;
  if (m_ParamType == DirectDict) {
    m_pParam = ToDictionary(src.m_pParam->Clone());
  } else {
    m_pParam = src.m_pParam;
  }
}

CPDF_ContentMarkItem::~CPDF_ContentMarkItem() {
  if (m_ParamType == DirectDict && m_pParam)
    m_pParam->Release();
}

FX_BOOL CPDF_ContentMarkItem::HasMCID() const {
  if (m_pParam &&
      (m_ParamType == DirectDict || m_ParamType == PropertiesDict)) {
    return m_pParam->KeyExist("MCID");
  }
  return FALSE;
}

// Copyright 2016 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.

// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com

#include "core/fpdfapi/fpdf_page/cpdf_contentmarkitem.h"

#include "core/fpdfapi/fpdf_parser/include/cpdf_dictionary.h"

CPDF_ContentMarkItem::CPDF_ContentMarkItem()
    : m_ParamType(None), m_pParam(nullptr) {}

CPDF_ContentMarkItem::CPDF_ContentMarkItem(const CPDF_ContentMarkItem& src) {
  m_MarkName = src.m_MarkName;
  m_ParamType = src.m_ParamType;
  if (m_ParamType == DirectDict) {
    m_pParam = ToDictionary(src.m_pParam->Clone());
  } else {
    m_pParam = src.m_pParam;
  }
}

CPDF_ContentMarkItem::~CPDF_ContentMarkItem() {
  if (m_ParamType == DirectDict && m_pParam)
    m_pParam->Release();
}

FX_BOOL CPDF_ContentMarkItem::HasMCID() const {
  if (m_pParam &&
      (m_ParamType == DirectDict || m_ParamType == PropertiesDict)) {
    return m_pParam->KeyExist("MCID");
  }
  return FALSE;
}

Add a missing initialisation for CPDF_ContentMarkItem.

R=dsinclair@chromium.org
BUG=chromium:605491

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


#include "ofMain.h"
#include "ofApp.h"

int main()
{
	ofSetupOpenGL(600, 500, OF_WINDOW);
	ofRunApp(new ofApp());
}

#include "ofMain.h"
#include "ofApp.h"

int main()
{
#ifdef TARGET_RASPBERRY_PI
	ofSetupOpenGL(600, 500, OF_FULLSCREEN);
#else
    ofSetupOpenGL(600, 500, OF_WINDOW);
#endif
	ofRunApp(new ofApp());
}

Add fullscreen for Raspberry Pi

Add fullscreen for Raspberry Pi


#include <iostream>
#include <tcp/tcp_server.hpp>
#include <sstream>

int main(int argc, char** argv)
{
  //initialize default port number and max connection cout
  int port = 12001, max_connection_count= 1000;

  // check if there are any passed arguments
  if(argc > 1)
  {
    // initialize string stream from argument
    std::istringstream arg_stream(argv[1]);

    // bind arguments stream to port int variable if valid
    if ( !(arg_stream >> port) )
      std::cerr << "Invalid number " << argv[1] << '\n';
  }

  // create server instance with specified port number
  TcpServer server(port);

  //start listening to connections
  server.Listen(max_connection_count);

  return 0;
}

#include <iostream>
#include <tcp/tcp_server.hpp>
#include <sstream>

int main(int argc, char** argv)
{
  //initialize default port number and max connection cout
  int port = 12001, max_connection_count= 1000;

  // check if there are any passed arguments
  if(argc > 1)
  {
    // initialize string stream from argument
    std::istringstream arg_stream(argv[1]);

    // bind arguments stream to port int variable if valid
    if ( !(arg_stream >> port) )
      std::cerr << "Invalid number " << argv[1] << '\n';
  }

  // create server instance with specified port number
  TcpServer server(port);

  //start listening to connections
  int result = server.Listen(max_connection_count);
  if(result != 0)
    cout << "Faild to start server !" << std::endl;

  return 0;
}

Update tcp server demo add error msg

Update tcp server demo add error msg


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isValidBSTInternal(TreeNode* root, int minVal, int maxVal)
    {
        if (root == NULL) {
            return true;
        }

	return (root->val > minVal &&
		root->val < maxVal &&
		isValidBSTInternal(root->left, minVal, root->val) &&
		isValidBSTInternal(root->right, root->val, maxVal));
    }

    bool isValidBST(TreeNode* root) {
        int minVal, maxVal;
        return isValidBSTInternal(root, LONG_MIN, LONG_MAX);
    }
};

#include <cstddef>
#include <climits>
/**
 * Definition for a binary tree node.
 */
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
    bool isValidBSTInternal(TreeNode* root, int minVal, int maxVal)
    {
        if (root == NULL) {
            return true;
        }

	return (root->val > minVal &&
		root->val < maxVal &&
		isValidBSTInternal(root->left, minVal, root->val) &&
		isValidBSTInternal(root->right, root->val, maxVal));
    }

    bool isValidBST(TreeNode* root) {

        return isValidBSTInternal(root, INT_MIN, INT_MAX);
    }
};

Clean up of the code.

Clean up of the code.


/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include "AsynchronousEventBeat.h"

namespace facebook {
namespace react {

AsynchronousEventBeat::AsynchronousEventBeat(
    RunLoopObserver::Unique uiRunLoopObserver,
    RuntimeExecutor runtimeExecutor)
    : EventBeat({}),
      uiRunLoopObserver_(std::move(uiRunLoopObserver)),
      runtimeExecutor_(std::move(runtimeExecutor)) {
  uiRunLoopObserver_->setDelegate(this);
  uiRunLoopObserver_->enable();
}

void AsynchronousEventBeat::activityDidChange(
    RunLoopObserver::Delegate const *delegate,
    RunLoopObserver::Activity activity) const noexcept {
  assert(delegate == this);
  induce();
}

void AsynchronousEventBeat::induce() const {
  if (!isRequested_) {
    return;
  }

  // Here we know that `this` object exists because the caller has a strong
  // pointer to `owner`. To ensure the object will exist inside
  // `runtimeExecutor_` callback, we need to copy the  pointer there.
  auto weakOwner = uiRunLoopObserver_->getOwner();

  runtimeExecutor_([this, weakOwner](jsi::Runtime &runtime) mutable {
    auto owner = weakOwner.lock();
    if (!owner) {
      return;
    }

    if (!isRequested_) {
      return;
    }

    this->beat(runtime);
  });
}

} // namespace react
} // namespace facebook

/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include "AsynchronousEventBeat.h"

#include <react/debug/react_native_assert.h>

namespace facebook {
namespace react {

AsynchronousEventBeat::AsynchronousEventBeat(
    RunLoopObserver::Unique uiRunLoopObserver,
    RuntimeExecutor runtimeExecutor)
    : EventBeat({}),
      uiRunLoopObserver_(std::move(uiRunLoopObserver)),
      runtimeExecutor_(std::move(runtimeExecutor)) {
  uiRunLoopObserver_->setDelegate(this);
  uiRunLoopObserver_->enable();
}

void AsynchronousEventBeat::activityDidChange(
    RunLoopObserver::Delegate const *delegate,
    RunLoopObserver::Activity activity) const noexcept {
  react_native_assert(delegate == this);
  induce();
}

void AsynchronousEventBeat::induce() const {
  if (!isRequested_) {
    return;
  }

  // Here we know that `this` object exists because the caller has a strong
  // pointer to `owner`. To ensure the object will exist inside
  // `runtimeExecutor_` callback, we need to copy the  pointer there.
  auto weakOwner = uiRunLoopObserver_->getOwner();

  runtimeExecutor_([this, weakOwner](jsi::Runtime &runtime) mutable {
    auto owner = weakOwner.lock();
    if (!owner) {
      return;
    }

    if (!isRequested_) {
      return;
    }

    this->beat(runtime);
  });
}

} // namespace react
} // namespace facebook

ReactCommon/renderer/scheduler: Migrate uses of NDEBUG to REACT_NATIVE_DEBUG + react_native_assert

Summary:
For better cross-platform consistency, migrate usages of NDEBUG to REACT_NATIVE_DEBUG. See flags.h for explanation.

Changelog: [Internal]

Reviewed By: PeteTheHeat

Differential Revision: D26695253

fbshipit-source-id: b0ff02416ab208dfd71f71c2b3d83009f40be0a9


#include <gtest/gtest.h>

#include "Vector2f.h"

TEST(Vector2fTest, VectorAddition) {
	Vector2f v1(0, 0);
	Vector2f v2(1, 2);
	Vector2f v3(3, 4);

	Vector2f result = v1 + v1;
	EXPECT_FLOAT_EQ(0.0f, result.x);
	EXPECT_FLOAT_EQ(0.0f, result.y);

	result = v2 + v1;
	EXPECT_FLOAT_EQ(v2.x, result.x);
	EXPECT_FLOAT_EQ(v2.y, result.y);

	result = v2 + v3;
	EXPECT_FLOAT_EQ(4.0f, result.x);
	EXPECT_FLOAT_EQ(6.0f, result.y);
	// TEST
	EXPECT_FLOAT_EQ(7.0f, result.y);
}

#include <gtest/gtest.h>

#include "Vector2f.h"

Vector2f v1(0,0);
Vector2f v2(1, 2);
Vector2f v3(3, 4);
Vector2f v4(-5, 6);

TEST(Vector2fTest, VectorAddition) {

	Vector2f result = v1 + v1;
	EXPECT_FLOAT_EQ(0.0f, result.x);
	EXPECT_FLOAT_EQ(0.0f, result.y);

	result = v2 + v1;
	EXPECT_FLOAT_EQ(v2.x, result.x);
	EXPECT_FLOAT_EQ(v2.y, result.y);

	result = v2 + v3;
	EXPECT_FLOAT_EQ(4.0f, result.x);
	EXPECT_FLOAT_EQ(6.0f, result.y);

	result = v3 + v4;
	EXPECT_FLOAT_EQ(-2.0f, result.x);
	EXPECT_FLOAT_EQ(10.0f, result.y);
}

TEST(Vector2fTest, VectorDot) {

	EXPECT_FLOAT_EQ(0.0f, v1.dot(v1));
	EXPECT_FLOAT_EQ(11.0f, v2.dot(v3));
}

Add more unit tests for vector

Add more unit tests for vector


#include "cpptoml.h"

#include <iostream>
#include <cassert>

int main(int argc, char** argv)
{
    if (argc < 2)
    {
        std::cout << "Usage: " << argv[0] << " filename" << std::endl;
        return 1;
    }
    cpptoml::toml_group g = cpptoml::parse_file(argv[1]);
    std::cout << g << std::endl;
    return 0;
}

#include "cpptoml.h"

#include <iostream>
#include <cassert>

int main(int argc, char** argv)
{
    if (argc < 2)
    {
        std::cout << "Usage: " << argv[0] << " filename" << std::endl;
        return 1;
    }

    try
    {
        cpptoml::toml_group g = cpptoml::parse_file(argv[1]);
        std::cout << g << std::endl;
    }
    catch (const cpptoml::toml_parse_exception& e)
    {
        std::cerr << "Failed to parse " << argv[1] << ": " << e.what() << std::endl;
        return 1;
    }

    return 0;
}

Handle parsing errors in the example.

Handle parsing errors in the example.

Aborting on invalid input is not especially user-friendly, even for a simple
example.


#include "Game/CannonBall.h"

CannonBall::CannonBall(const QPixmap & pixmap, QVector2D velocity, QVector2D position, Player owner, QGraphicsItem * parent) : Entity(pixmap, owner, parent), m_initialVelocity(velocity), m_initialPosition(position), m_gravity(9.8), m_timeSinceShot(0)
{
	setScale(0.1);
	setPos(m_initialPosition.toPointF());
}

void CannonBall::updateEntity(double deltaTime)
{
    m_timeSinceShot += deltaTime/1000.0 * 2.0;

	double x = m_initialPosition.x() + m_initialVelocity.x() * m_timeSinceShot;
	double y = m_initialPosition.y() - m_initialVelocity.y() * m_timeSinceShot + 0.5 * m_gravity * m_timeSinceShot * m_timeSinceShot;

	setPos(x, y);
}

#include "Game/CannonBall.h"

CannonBall::CannonBall(const QPixmap & pixmap, QVector2D velocity, QVector2D position, Player owner, QGraphicsItem * parent) : Entity(pixmap, owner, parent), m_initialVelocity(velocity), m_initialPosition(position), m_gravity(9.8), m_timeSinceShot(0)
{
	setScale(0.1);
	setPos(m_initialPosition.toPointF());
}

void CannonBall::updateEntity(double deltaTime)
{
    m_timeSinceShot += deltaTime/1000.0 * 2.0;

	double x = m_initialPosition.x() + m_initialVelocity.x() * m_timeSinceShot;
	double y = m_initialPosition.y() - m_initialVelocity.y() * m_timeSinceShot + 0.5 * m_gravity * m_timeSinceShot * m_timeSinceShot;

	setPos(x, y);

   update(boundingRect());
}

Call update in update entity

Call update in update entity


// Check the value profiling instrinsics emitted by instrumentation.

// RUN: %clangxx %s -o - -emit-llvm -S -fprofile-instr-generate -mllvm -enable-value-profiling -fexceptions -target %itanium_abi_triple | FileCheck %s

void (*foo) (void);

int main(int argc, const char *argv[]) {
// CHECK:  [[REG1:%[0-9]+]] = load void ()*, void ()** @foo, align 4
// CHECK-NEXT:  [[REG2:%[0-9]+]] = ptrtoint void ()* [[REG1]] to i64
// CHECK-NEXT:  call void @__llvm_profile_instrument_target(i64 [[REG2]], i8* bitcast ({{.*}}* @__profd_main to i8*), i32 0)
// CHECK-NEXT:  invoke void [[REG1]]()
  try {
    foo();
  } catch (int) {}
  return 0;
}

// CHECK: declare void @__llvm_profile_instrument_target(i64, i8*, i32)

// Check the value profiling instrinsics emitted by instrumentation.

// RUN: %clangxx %s -o - -emit-llvm -S -fprofile-instr-generate -mllvm -enable-value-profiling -fexceptions -target %itanium_abi_triple | FileCheck %s

void (*foo) (void);

int main(int argc, const char *argv[]) {
// CHECK:  [[REG1:%[0-9]+]] = load void ()*, void ()** @foo
// CHECK-NEXT:  [[REG2:%[0-9]+]] = ptrtoint void ()* [[REG1]] to i64
// CHECK-NEXT:  call void @__llvm_profile_instrument_target(i64 [[REG2]], i8* bitcast ({{.*}}* @__profd_main to i8*), i32 0)
// CHECK-NEXT:  invoke void [[REG1]]()
  try {
    foo();
  } catch (int) {}
  return 0;
}

// CHECK: declare void @__llvm_profile_instrument_target(i64, i8*, i32)

Test case fix for r264783

[PGO] Test case fix for r264783

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


#include <lightex/utils/file_utils.h>

#include <fstream>
#include <iostream>

namespace lightex {
namespace utils {

bool ReadDataFromFile(const std::string& path, std::string* output) {
  if (!output) {
    std::cerr << "Error: output pointer points to invalid memory." << std::endl;
    return false;
  }

  std::ifstream in(path);
  if (!in) {
    std::cerr << "Error: failed to open input file for reading: " << path << "." << std::endl;
    return false;
  }

  in.unsetf(std::ios::skipws);  // Avoids white space skipping.
  std::copy(std::istream_iterator<char>(in), std::istream_iterator<char>(), std::back_inserter(*output));

  return true;
}
}  // namespace utils
}  // namespace lightex

#include <lightex/utils/file_utils.h>

#include <fstream>
#include <iostream>
#include <iterator>

namespace lightex {
namespace utils {

bool ReadDataFromFile(const std::string& path, std::string* output) {
  if (!output) {
    std::cerr << "Error: output pointer points to invalid memory." << std::endl;
    return false;
  }

  std::ifstream in(path);
  if (!in) {
    std::cerr << "Error: failed to open input file for reading: " << path << "." << std::endl;
    return false;
  }

  in.unsetf(std::ios::skipws);  // Avoids white space skipping.
  std::copy(std::istream_iterator<char>(in), std::istream_iterator<char>(), std::back_inserter(*output));

  return true;
}
}  // namespace utils
}  // namespace lightex

Fix VS2015 build: istream_iterator is not a member of std


// Copyright (c) 2012 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 "ui/gfx/transform_util.h"

#include "ui/gfx/point.h"
#include "testing/gtest/include/gtest/gtest.h"

TEST(TransformUtilTest, GetScaleTransform) {
  const gfx::Point kAnchor(20, 40);
  const float kScale = 0.5f;

  gfx::Transform scale = gfx::GetScaleTransform(kAnchor, kScale);

  const int kOffset = 10;
  for (int sign_x = -1; sign_x <= 1; ++sign_x) {
    for (int sign_y = -1; sign_y <= 1; ++sign_y) {
      gfx::Point test(kAnchor.x() + sign_x * kOffset,
                      kAnchor.y() + sign_y * kOffset);
      scale.TransformPoint(test);

      EXPECT_EQ(gfx::Point(kAnchor.x() + sign_x * kOffset * kScale,
                           kAnchor.y() + sign_y * kOffset * kScale),
                test);
    }
  }
}

// Copyright (c) 2012 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 "ui/gfx/transform_util.h"

#include "ui/gfx/point.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace gfx {
namespace {

TEST(TransformUtilTest, GetScaleTransform) {
  const Point kAnchor(20, 40);
  const float kScale = 0.5f;

  Transform scale = GetScaleTransform(kAnchor, kScale);

  const int kOffset = 10;
  for (int sign_x = -1; sign_x <= 1; ++sign_x) {
    for (int sign_y = -1; sign_y <= 1; ++sign_y) {
      Point test(kAnchor.x() + sign_x * kOffset,
                 kAnchor.y() + sign_y * kOffset);
      scale.TransformPoint(test);

      EXPECT_EQ(Point(kAnchor.x() + sign_x * kOffset * kScale,
                      kAnchor.y() + sign_y * kOffset * kScale),
                test);
    }
  }
}

}  // namespace
}  // namespace gfx

ui/gfx: Move transform_util unittest into gfx namespace.

TEST=ui_unittests
TBR=sky@chromium.org

Review URL: https://chromiumcodereview.appspot.com/11369173

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