// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/atom_resource_dispatcher_host_delegate.h"

#include "atom/browser/login_handler.h"
#include "atom/common/platform_util.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/escape.h"
#include "url/gurl.h"

using content::BrowserThread;

namespace atom {

AtomResourceDispatcherHostDelegate::AtomResourceDispatcherHostDelegate() {
}

bool AtomResourceDispatcherHostDelegate::HandleExternalProtocol(
    const GURL& url,
    int render_process_id,
    int render_view_id,
    bool is_main_frame,
    ui::PageTransition transition,
    bool has_user_gesture) {
  GURL escaped_url(net::EscapeExternalHandlerValue(url.spec()));
  BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
      base::Bind(
          base::IgnoreResult(platform_util::OpenExternal), escaped_url, false));
  return true;
}

content::ResourceDispatcherHostLoginDelegate*
AtomResourceDispatcherHostDelegate::CreateLoginDelegate(
    net::AuthChallengeInfo* auth_info,
    net::URLRequest* request) {
  return new LoginHandler(auth_info, request);
}

}  // namespace atom

// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/atom_resource_dispatcher_host_delegate.h"

#include "atom/browser/login_handler.h"
#include "atom/common/platform_util.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/escape.h"
#include "url/gurl.h"

using content::BrowserThread;

namespace atom {

AtomResourceDispatcherHostDelegate::AtomResourceDispatcherHostDelegate() {
}

bool AtomResourceDispatcherHostDelegate::HandleExternalProtocol(
    const GURL& url,
    int render_process_id,
    int render_view_id,
    bool is_main_frame,
    ui::PageTransition transition,
    bool has_user_gesture) {
  GURL escaped_url(net::EscapeExternalHandlerValue(url.spec()));
  BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
      base::Bind(
          base::IgnoreResult(platform_util::OpenExternal), escaped_url, true));
  return true;
}

content::ResourceDispatcherHostLoginDelegate*
AtomResourceDispatcherHostDelegate::CreateLoginDelegate(
    net::AuthChallengeInfo* auth_info,
    net::URLRequest* request) {
  return new LoginHandler(auth_info, request);
}

}  // namespace atom

Call OpenExternal with new true default to activate arg


/**
 * \file
 * \brief chip::lowLevelInitialization() implementation for STM32L0
 *
 * \author Copyright (C) 2017 Cezary Gapinski cezary.gapinski@gmail.com
 *
 * \par License
 * 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 "distortos/chip/lowLevelInitialization.hpp"

namespace distortos
{

namespace chip
{

/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/

void lowLevelInitialization()
{

}

}	// namespace chip

}	// namespace distortos

Add empty chip::lowLevelInitialization() for STM32L0


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

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include <stdio.h>
#include <string.h>
#include "tensorflow/lite/experimental/micro/debug_log.h"

// These are set by openmv py_tf.c code to redirect printing to an error message
// buffer...

static char *py_tf_putchar_buffer = NULL;
static size_t py_tf_putchar_buffer_len = 0;

extern "C" void DebugLog(const char* s) {
  for (size_t i = 0, j = strlen(s); i < j; i++) {
    if (py_tf_putchar_buffer_len) {
      *py_tf_putchar_buffer++ = s[i];
      py_tf_putchar_buffer_len--;
    } else {
      putchar(s[i]);
    }
  }
}

Update debug log to support redirection


class Solution {
public:
    string removeDuplicates(string s) {
        int index = 0;

        while (!s.empty() && index < (s.size()-1)) {
            if (s[index] == s[index+1]) {
                if ((index+2) < s.size()) {
                    s = s.substr(0, index) + s.substr(index+2);
                } else {
                    s = s.substr(0, index);
                }
                if (index > 0)
                    --index;
            } else {
                ++index;
            }
        }
        return s;
    }
};

Remove All Adjacent Duplicates In String


#include <OpenSim/OpenSim.h>

main() {
    // A study is the top level component that contains the model and other
    // computational components.
    Study inverseKinematicsStudy;

    Model model("subject_01.osim");
    inverseKinematicsStudy.addComponent(model);

    // A data Source component wraps a TimeSeriesTables and access rows by time
    // Each column is given its own Output by name unless specified otherwise
    Source markers("subject01_trial2.trc");
    // Source markers("subject01_trial2.trc", Vec2(0, 5)); // by range
    // Source markers("subject01_trial2.trc", {"aa, "ai", ac"}); //by name
    inverseKinematicsStudy.addComponent(markers);

    // InverseKinematicsSolver is wrapped by a component (or one itself?)
    // dependency on model, and marker inputs (outputs of a source) wired
    // upon connect
    InverseKinematics ik(model, markers);
    inverseKinematicsStudy.addComponent(ik);

    // Now handle IK Outputs
    // Extract the outputs from the model and the state via a reporter
    // Do not need to know type BUT cannot combine different types
    // Coordinates are doubles and modelMarkers are Vec3's
    OutputReporter coordinateReporter();
    OutputReporter modelMarkerReporter();
    // Output coordinates from IK
    for(const auto& coord: mode.getCoordinates())
        coordinateReporter.addOutput(coord.getOutput("value"));
    inverseKinematicsStudy.addComponent(coordinateReporter);
    // Output model marker locations from IK
    for (const auto& marker : mode.getMarkers())
        modelMarkerReporter.addOutputs(marker.getOutput("location"));
    inverseKinematicsStudy.addComponent(modelMarkerReporter);

    State& state = inverseKinematicsStudy.initSystem();

    // March through time to solve for the state's coordinates
    for (double t : markers.getTimes()) {
        state.setTime(t);
        ik.track(state);
        inverseKinematicsStudy.realizeReport(state);
    }

    // write results to file
    FileAdapter fileAdapter;
    fileAdapter.write("s01_tr2_IK.mot", coordinateReporter.getReport());
    fileAdapter.write("s01_tr2_markers.trc", modelMarkerReporter.getReport());
}

Add pseudo code for performing an Inverse Kinematics analysis. Perform IK without using a Tool or any Analyses.


#include <fstream>
#include <map>

using namespace std;

int main() {
    ifstream cin("milktemp.in");
    ofstream cout("milktemp.out");

    int num_cows, cold, comfortable, hot;
	cin >> num_cows >> cold >> comfortable >> hot;

	int cold_change = comfortable - cold;
	int hot_change = hot - comfortable;

	map<int, int> changes;
	for (int i = 0; i < num_cows; i++) {
		int cold_thresh, hot_thresh;
		cin >> cold_thresh >> hot_thresh;

		changes[cold_thresh] += cold_change;
		changes[hot_thresh + 1] += hot_change;
	}

	int current = num_cows * cold;
	int max = current;
	for (const auto &change : changes) {
		current += change.second;
		if (current > max)
			max = current;
	}

    cout << max << endl;

    return 0;
}

Add C++11 solution for Nov. 2013 Bronze Problem 2


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

class Base { // expected-error {{cannot define the implicit default assignment operator for 'class Base'}} \
             // expected-note {{synthesized method is first required here}}
  int &ref;  // expected-note {{declared at}}
};

class X  : Base {  // // expected-error {{cannot define the implicit default assignment operator for 'class X'}}
public:
  X();
  const int cint;  // expected-note {{declared at}}
};

struct Y  : X {
  Y();
  Y& operator=(const Y&);
  Y& operator=(volatile Y&);
  Y& operator=(const volatile Y&);
  Y& operator=(Y&);
};

class Z : Y {};

Z z1;
Z z2;

// Test1
void f(X x, const X cx) {
  x = cx;	// expected-note {{synthesized method is first required here}}
  x = cx;
  z1 = z2;
}

// Test2
class T {};
T t1;
T t2;

void g()
{
  t1 = t2;
}

// Test3
class V {
public:
  V();
  V &operator = (V &b);
};

class W : V {};
W w1, w2;

void h()
{
  w1 = w2;
}

// Test4

class B1 {
public:
  B1();
  B1 &operator = (B1 b);
};

class D1 : B1 {};
D1 d1, d2;

void i()
{
	d1 = d2;
}

Test case for my last patch.


/** @file
    @brief Implementation

    @date 2014

    @author
    Ryan Pavlik
    <ryan@sensics.com>
    <http://sensics.com>
*/

// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)

// Internal Includes
#include <osvr/Routing/PathNode.h>
#include <osvr/Routing/Constants.h>
#include <osvr/Routing/PathElementTools.h>

// Library/third-party includes
// - none

// Standard includes
#include <sstream>

namespace osvr {
namespace routing {
    const char *getTypeName(PathNode const &node) {
        return elements::getTypeName(node.value());
    }
    static inline void buildPathRecursively(PathNode const &node,
                                            std::ostream &os) {
        auto parent = node.getParent();
        if (parent) {
            buildPathRecursively(*parent, os);
        }
        if (!node.isRoot()) {
            os << getPathSeparator() << node.getName();
        }
    }
    std::string getFullPath(PathNode const &node) {
        std::ostringstream os;
        buildPathRecursively(node, os);
        return os.str();
    }
} // namespace routing
} // namespace osvr

/** @file
    @brief Implementation

    @date 2014

    @author
    Ryan Pavlik
    <ryan@sensics.com>
    <http://sensics.com>
*/

// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)

// Internal Includes
#include <osvr/Routing/PathNode.h>
#include <osvr/Routing/Constants.h>
#include <osvr/Routing/PathElementTools.h>

// Library/third-party includes
// - none

// Standard includes
#include <sstream>

namespace osvr {
namespace routing {
    const char *getTypeName(PathNode const &node) {
        return elements::getTypeName(node.value());
    }
    static inline void buildPathRecursively(PathNode const &node,
                                            std::ostream &os) {
        auto parent = node.getParent();
        if (parent) {
            buildPathRecursively(*parent, os);
        }
        if (!node.isRoot()) {
            os << getPathSeparator() << node.getName();
        }
    }
    std::string getFullPath(PathNode const &node) {
        /// Special case the root
        if (node.isRoot()) {
            return getPathSeparator();
        }
        std::ostringstream os;
        buildPathRecursively(node, os);
        return os.str();
    }
} // namespace routing
} // namespace osvr

Fix bug found by test.


#include "env_vars.hh"

namespace Kakoune
{

EnvVarMap get_env_vars()
{
    EnvVarMap env_vars;
    for (char** it = environ; *it; ++it)
    {
        const char* name = *it;
        const char* value = name;
        while (*value != 0 and *value != '=')
            ++value;
        env_vars[String{name, value}] = (*value == '=') ? value+1 : value;
    }
    return env_vars;
}

}

#include "env_vars.hh"

#if __APPLE__
extern char **environ;
#endif

namespace Kakoune
{

EnvVarMap get_env_vars()
{
    EnvVarMap env_vars;
    for (char** it = environ; *it; ++it)
    {
        const char* name = *it;
        const char* value = name;
        while (*value != 0 and *value != '=')
            ++value;
        env_vars[String{name, value}] = (*value == '=') ? value+1 : value;
    }
    return env_vars;
}

}

Define extern char **environ for OSX, which doesn't define it in a header


#include <algorithm>

#include "command.hh"
#include "common-args.hh"
#include "eval.hh"
#include "globals.hh"
#include "legacy.hh"
#include "shared.hh"
#include "store-api.hh"

namespace nix {

struct NixArgs : virtual MultiCommand, virtual MixCommonArgs
{
    NixArgs() : MultiCommand(*RegisterCommand::commands), MixCommonArgs("nix")
    {
        mkFlag('h', "help", "show usage information", [=]() {
            printHelp(programName, std::cout);
            throw Exit();
        });

        mkFlag(0, "version", "show version information", std::bind(printVersion, programName));
    }
};

void mainWrapped(int argc, char * * argv)
{
    initNix();
    initGC();

    string programName = baseNameOf(argv[0]);

    {
        auto legacy = (*RegisterLegacyCommand::commands)[programName];
        if (legacy) return legacy(argc, argv);
    }

    NixArgs args;

    args.parseCmdline(argvToStrings(argc, argv));

    assert(args.command);

    args.command->prepare();
    args.command->run();
}

}

int main(int argc, char * * argv)
{
    return nix::handleExceptions(argv[0], [&]() {
        nix::mainWrapped(argc, argv);
    });
}

#include <algorithm>

#include "command.hh"
#include "common-args.hh"
#include "eval.hh"
#include "globals.hh"
#include "legacy.hh"
#include "shared.hh"
#include "store-api.hh"

namespace nix {

struct NixArgs : virtual MultiCommand, virtual MixCommonArgs
{
    NixArgs() : MultiCommand(*RegisterCommand::commands), MixCommonArgs("nix")
    {
        mkFlag('h', "help", "show usage information", [=]() {
            printHelp(programName, std::cout);
            std::cout << "\nNote: this program is EXPERIMENTAL and subject to change.\n";
            throw Exit();
        });

        mkFlag(0, "version", "show version information", std::bind(printVersion, programName));
    }
};

void mainWrapped(int argc, char * * argv)
{
    initNix();
    initGC();

    string programName = baseNameOf(argv[0]);

    {
        auto legacy = (*RegisterLegacyCommand::commands)[programName];
        if (legacy) return legacy(argc, argv);
    }

    NixArgs args;

    args.parseCmdline(argvToStrings(argc, argv));

    assert(args.command);

    args.command->prepare();
    args.command->run();
}

}

int main(int argc, char * * argv)
{
    return nix::handleExceptions(argv[0], [&]() {
        nix::mainWrapped(argc, argv);
    });
}

Add warning about "nix" being experimental


#include <iostream>
#include <thread>
#include <atomic>
#include <vector>

std::vector<int> data;
bool data_ready = false;

void reader_thread()
{
    int i = 1;
    while (!data_ready) // 1
    {
        std::cout << "Reader loop " << i << std::endl;
        ++i;
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }

    std::cout << "Data value: " << data[0] << std::endl; // 2
}

void writer_thread()
{
    // Pretend to do some work
    std::this_thread::sleep_for(std::chrono::milliseconds(10));

    data.push_back(42); // 3
    data_ready = true;  // 4
}

int main()
{
    std::thread reader(reader_thread);
    std::thread writer(writer_thread);

    writer.join();
    reader.join();

    std::cout << "Press any key to continue...\n";
    std::getchar();
}

#include <iostream>
#include <thread>
#include <atomic>
#include <vector>

std::vector<int> data;
bool data_ready = false;

void reader_thread()
{
    int i = 1;
    while (!data_ready) // 1
    {
        std::cout << "Reader loop " << i << std::endl;
        ++i;
    }

    std::cout << "Data value: " << data[0] << std::endl; // 2
}

void writer_thread()
{
    // Pretend to do some work
    std::this_thread::sleep_for(std::chrono::milliseconds(10));

    data.push_back(42); // 3
    data_ready = true;  // 4
}

int main()
{
    std::thread reader(reader_thread);
    std::thread writer(writer_thread);

    writer.join();
    reader.join();

    std::cout << "Press any key to continue...\n";
    std::getchar();
}

Update the ordering relationships example.


#include "grid.h"

#include "graphics/Renderer.h"
#include "jewel.h"
#include "cell.h"

namespace bejeweled {

Grid::Grid(int width, int height, graphics::Renderer &renderer) : width_(width), height_(height), grid_() {
  for (int i = 0; i < width_; ++i) {
    grid_.emplace_back();
    for (int j = 0; j < height_; ++j) {
      grid_[i].emplace_back();
    }
  }
  InitJewels(renderer);
}

void Grid::Render(graphics::Renderer &renderer) {
  for (int i = 0; i < width_; ++i) {
    for (int j = 0; j < height_; ++j) {
      grid_[i][j].Render(renderer);
    }
  }
}

void Grid::InitJewels(graphics::Renderer &renderer) {
  for (int i = 0; i < width_; ++i) {
    for (int j = 0; j < height_; ++j) {
      grid_[i][j].SetJewel(Jewel{renderer, JewelType::kRed, util::Point(32 * i, 32 * j)});
    }
  }
}

} //namespace bejeweled

#include "grid.h"

#include "graphics/Renderer.h"
#include "jewel.h"
#include "cell.h"

namespace bejeweled {

Grid::Grid(int width, int height, graphics::Renderer &renderer) : width_(width), height_(height), grid_() {
  for (int i = 0; i < width_; ++i) {
    grid_.emplace_back();
    for (int j = 0; j < height_; ++j) {
      grid_[i].emplace_back();
    }
  }
  InitJewels(renderer);
}

void Grid::Render(graphics::Renderer &renderer) {
  for (auto& column : grid_) {
    for (auto& cell : column) {
      cell.Render(renderer);
    }
  }
}

void Grid::InitJewels(graphics::Renderer &renderer) {
  for (int i = 0; i < width_; ++i) {
    for (int j = 0; j < height_; ++j) {
      grid_[i][j].SetJewel(Jewel{renderer, JewelType::kRed, util::Point(32 * i, 32 * j)});
    }
  }
}

} //namespace bejeweled

Use range based for loop instead of raw loop


class base {
public:
    virtual int foo(int a)
     { return 4 + a; }
    int bar(int a)
     { return a - 2; }
};

class sub final : public base {
public:
    virtual int foo(int a) override
     { return 8 + 2 * a; };
};

class sub2 final : public base {
public:
    virtual int foo(int a) override final
     { return 8 + 2 * a; };
};

int main(void)
{
    base b;
    sub s;

    return (b.foo(2) * 2 == s.foo(2)) ? 0 : 1;
}

class base {
public:
    virtual int foo(int a)
     { return 4 + a; }
    int bar(int a)
     { return a - 2; }
};

class sub final : public base {
public:
    virtual int foo(int a) override
     { return 8 + 2 * a; };
};

class sub2 final : public base {
public:
    virtual int foo(int a) override final
     { return 8 + 2 * a; };
};

int main(void)
{
    base b;
    sub s;
    sub2 t;

    return (b.foo(2) * 2 == s.foo(2) && b.foo(2) * 2 == t.foo(2) ) ? 0 : 1;
}

Test override and override final


#include "rapidjson/document.h"
#include "rapidjson/filereadstream.h"
#include <cstdio>
#include <iostream>

using namespace std;
using namespace rapidjson;

int main() {
    FILE* fp = std::fopen("./1.json", "r");
    char buffer[65536];
    FileReadStream frs(fp, buffer, sizeof(buffer));
    Document jobj;
    jobj.ParseStream(frs);

    const Value &coordinates = jobj["coordinates"];
    int len = coordinates.Size();
    double x = 0, y = 0, z = 0;

    for (SizeType i = 0; i < len; i++) {
      const Value &coord = coordinates[i];
      x += coord["x"].GetDouble();
      y += coord["y"].GetDouble();
      z += coord["z"].GetDouble();
    }

    std::cout << x / len << std::endl;
    std::cout << y / len << std::endl;
    std::cout << z / len << std::endl;

    fclose(fp);

    return 0;
}

#include "rapidjson/document.h"
#include "rapidjson/filereadstream.h"
#include <cstdio>
#include <iostream>

using namespace std;
using namespace rapidjson;

int main() {
    FILE* fp = std::fopen("./1.json", "r");
    char buffer[65536];
    FileReadStream frs(fp, buffer, sizeof(buffer));
    Document jobj;
    jobj.ParseStream(frs);

    const Value &coordinates = jobj["coordinates"];
    SizeType len = coordinates.Size();
    double x = 0, y = 0, z = 0;

    for (SizeType i = 0; i < len; i++) {
      const Value &coord = coordinates[i];
      x += coord["x"].GetDouble();
      y += coord["y"].GetDouble();
      z += coord["z"].GetDouble();
    }

    std::cout << x / len << std::endl;
    std::cout << y / len << std::endl;
    std::cout << z / len << std::endl;

    fclose(fp);

    return 0;
}

Change len to proper type in RapidJSON test


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

// <streambuf>

// template <class charT, class traits = char_traits<charT> >
// class basic_streambuf;

// void pbump(int n);

#include <sstream>
#include <cassert>
#include "test_macros.h"

struct SB : std::stringbuf
{
  SB() : std::stringbuf(std::ios::ate|std::ios::out) { }
  const char* pubpbase() const { return pbase(); }
  const char* pubpptr() const { return pptr(); }
};

int main()
{
#ifndef TEST_HAS_NO_EXCEPTIONS
    try {
#endif
    	std::string str(2147483648, 'a');
		SB sb;
		sb.str(str);
		assert(sb.pubpbase() <= sb.pubpptr());
#ifndef TEST_HAS_NO_EXCEPTIONS
	}
	catch (const std::bad_alloc &) {}
#endif
}

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

// <streambuf>

// template <class charT, class traits = char_traits<charT> >
// class basic_streambuf;

// void pbump(int n);
//
// REQUIRES: long_tests

#include <sstream>
#include <cassert>
#include "test_macros.h"

struct SB : std::stringbuf
{
  SB() : std::stringbuf(std::ios::ate|std::ios::out) { }
  const char* pubpbase() const { return pbase(); }
  const char* pubpptr() const { return pptr(); }
};

int main()
{
#ifndef TEST_HAS_NO_EXCEPTIONS
    try {
#endif
    	std::string str(2147483648, 'a');
		SB sb;
		sb.str(str);
		assert(sb.pubpbase() <= sb.pubpptr());
#ifndef TEST_HAS_NO_EXCEPTIONS
	}
	catch (const std::bad_alloc &) {}
#endif
}

Mark test as a long-test


#include <iostream>
#include "SDL/SDL.h"
#include "world.hpp"
namespace Polarity {
  World *world = nullptr;

  World::World():physics(b2Vec2(0.0f, -10.0f)),keyState(SDLK_LAST) {
    std::cerr << "World has started"<<std::endl;
    for (int i=0; i< SDLK_LAST; ++i) {
      keyState[i] = false;
    }
  }
  void World::init() {
      world = new World();
  }
  GameObject* World::addObject(Behavior *behavior, const b2BodyDef&bdef) {
      GameObject * object = new GameObject(&physics, behavior, bdef);
      objects.emplace_back(object);
      return objects.back().get();
  }
  bool World::isKeyDown(int keyCode) {
    return keyState[keyCode];
  }
  void World::keyEvent(int keyCode, bool pressed) {
    if (keyCode < SDLK_LAST) {
      keyState[keyCode] = pressed;
    }else {
      std::cerr << "Key code out of range "<<keyCode<<"\n";
    }
  }
  void World::tick() {
    for (auto &obj : objects) {
      obj->tick(this);
      std::cerr << obj->printPosition()<<std::endl;
    }
    //for(auto &gameObject:objects){
    //
    //}

    // Gets called every frame
  }
}

#include <iostream>
#include "SDL/SDL.h"
#include "world.hpp"
namespace Polarity {
  World *world = nullptr;

  World::World():physics(b2Vec2(0.0f, -10.0f)),keyState(SDLK_LAST) {
    std::cerr << "World has started"<<std::endl;
    for (int i=0; i< SDLK_LAST; ++i) {
      keyState[i] = false;
    }
  }
  void World::init() {
      world = new World();
  }
  GameObject* World::addObject(Behavior *behavior, const b2BodyDef&bdef) {
      GameObject * object = new GameObject(&physics, behavior, bdef);
      objects.emplace_back(object);
      return objects.back().get();
  }
  bool World::isKeyDown(int keyCode) {
    return keyState[keyCode];
  }
  void World::keyEvent(int keyCode, bool pressed) {
    if (keyCode < SDLK_LAST) {
      keyState[keyCode] = pressed;
    }else {
      std::cerr << "Key code out of range "<<keyCode<<"\n";
    }
  }
  void World::tick() {
    physics.Step(0.0166666, 1, 1);
    for (auto &obj : objects) {
      obj->tick(this);
      std::cerr << obj->printPosition()<<std::endl;
    }
    //for(auto &gameObject:objects){
    //
    //}

    // Gets called every frame
  }
}

Call physics engine with every tick


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

// the class BlockMatrixArray had no local type value_type that is
// needed in some places. in particular, this is needed for
// PreconditionBlockSSOR
//
// the test also didn't link before, due to some functions that were
// either missing or in the wrong place
//
// this test doesn't do anything particularly useful, it just makes sure that
// we can compile this kind of code

#include <base/logstream.h>
#include <lac/block_matrix_array.h>
#include <lac/sparse_matrix.h>
#include <lac/precondition_block.h>
#include <iostream>
#include <fstream>

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

  BlockMatrixArray<SparseMatrix<double> >::value_type i = 1.0;
  deallog << i << std::endl;

				   // the following did not compile
				   // right away
  PreconditionBlockSSOR<BlockMatrixArray<SparseMatrix<double> > > p;

  return 0;
}

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

// the class BlockMatrixArray had no local type value_type that is
// needed in some places. in particular, this is needed for
// PreconditionBlockSSOR
//
// this test doesn't do anything particularly useful, it just makes sure that
// we can compile this kind of code

#include <base/logstream.h>
#include <lac/block_matrix_array.h>
#include <lac/sparse_matrix.h>
#include <iostream>
#include <fstream>

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

  BlockMatrixArray<SparseMatrix<double> >::value_type i = 1.0;
  deallog << i << std::endl;

  return 0;
}

Reduce the test to its minimum.


// Copyright 2014 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 "config.h"
#include "modules/push_messaging/PushError.h"

#include "core/dom/ExceptionCode.h"
#include "wtf/OwnPtr.h"

namespace blink {

PassRefPtrWillBeRawPtr<DOMException> PushError::take(ScriptPromiseResolver*, WebType* webErrorRaw)
{
    OwnPtr<WebType> webError = adoptPtr(webErrorRaw);
    switch (webError->errorType) {
    case WebPushError::ErrorTypeAbort:
        return DOMException::create(AbortError, webError->message);
    case WebPushError::ErrorTypeNetwork:
        return DOMException::create(NetworkError, webError->message);
    case WebPushError::ErrorTypeNotFound:
        return DOMException::create(NotFoundError, webError->message);
    case WebPushError::ErrorTypeUnknown:
        return DOMException::create(UnknownError);
    }
    ASSERT_NOT_REACHED();
    return DOMException::create(UnknownError);
}

void PushError::dispose(WebType* webErrorRaw)
{
    delete webErrorRaw;
}

} // namespace blink

// Copyright 2014 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 "config.h"
#include "modules/push_messaging/PushError.h"

#include "core/dom/ExceptionCode.h"
#include "wtf/OwnPtr.h"

namespace blink {

PassRefPtrWillBeRawPtr<DOMException> PushError::take(ScriptPromiseResolver*, WebType* webErrorRaw)
{
    OwnPtr<WebType> webError = adoptPtr(webErrorRaw);
    switch (webError->errorType) {
    case WebPushError::ErrorTypeAbort:
        return DOMException::create(AbortError, webError->message);
    case WebPushError::ErrorTypeNetwork:
        return DOMException::create(NetworkError, webError->message);
    case WebPushError::ErrorTypeNotFound:
        return DOMException::create(NotFoundError, webError->message);
    case WebPushError::ErrorTypeUnknown:
        return DOMException::create(UnknownError, webError->message);
    }
    ASSERT_NOT_REACHED();
    return DOMException::create(UnknownError);
}

void PushError::dispose(WebType* webErrorRaw)
{
    delete webErrorRaw;
}

} // namespace blink

Use provided message for UnknownError.


#include "MainWindow.h"

#include <QBoxLayout>
#include <QLabel>
#include <QSpinBox>

#include <fiblib/Fibonacci.h>

MainWindow::MainWindow()
{
    // Create content widget
    QWidget * content = new QWidget(this);
    setCentralWidget(content);

    // Create layout
    QBoxLayout * boxLayout = new QVBoxLayout();
    content->setLayout(boxLayout);

    // Add title
    QLabel * title = new QLabel(content);
    title->setText("Please enter n:");
    boxLayout->addWidget(title);

    // Add input field
    QSpinBox * editNumber = new QSpinBox(content);
    editNumber->setMinimum(0);
    boxLayout->addWidget(editNumber);

    // Add result
    QLabel * result = new QLabel(content);
    result->setText("Fib(0) = 0");
    boxLayout->addWidget(result);

    // When input changes, calculate and output the fibonacci number
    connect(editNumber, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [result] (int n)
    {
        fiblib::Fibonacci fib;
        result->setText("Fib(" + QString::number(n) + ") = " + QString::number(fib(static_cast<unsigned int>(n))));
    });
}

MainWindow::~MainWindow()
{
}

#include "MainWindow.h"

#include <QBoxLayout>
#include <QLabel>
#include <QSpinBox>

#include <fiblib/Fibonacci.h>

MainWindow::MainWindow()
{
    // Create content widget
    QWidget * content = new QWidget(this);
    setCentralWidget(content);

    // Create layout
    QBoxLayout * layout = new QVBoxLayout();
    content->setLayout(layout);

    // Add title
    QLabel * title = new QLabel(content);
    title->setText("Please enter n:");
    layout->addWidget(title);

    // Add input field
    QSpinBox * editNumber = new QSpinBox(content);
    editNumber->setMinimum(0);
    layout->addWidget(editNumber);

    // Add result
    QLabel * result = new QLabel(content);
    result->setText("Fib(0) = 0");
    layout->addWidget(result);

    // When input changes, calculate and output the fibonacci number
    connect(editNumber, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [result] (int n)
    {
        fiblib::Fibonacci fib;
        result->setText("Fib(" + QString::number(n) + ") = " + QString::number(fib(n)));
    });
}

MainWindow::~MainWindow()
{
}

Revert "Remove simple to fix warnings"


#include <rusql/connection.hpp>
#include <assert.h>

int main(int argc, char *argv[]) {
	assert(argc == 5);
	try {
		rusql::connection(rusql::connection::connection_info(argv[1], argv[2], argv[3], argv[4]));
	} catch(...) {
		return 0;
	}
	return 1;
}

#include <rusql/connection.hpp>
#include <cassert>

int main(int argc, char *argv[]) {
	assert(argc == 5);
	try {
		rusql::connection(rusql::connection::connection_info(argv[1], argv[2], argv[3], argv[4]));
	} catch(...) {
		return 0;
	}
	return 1;
}

Change C header to C++ header


// 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 "printing/backend/print_backend.h"

namespace printing {

PrinterBasicInfo::PrinterBasicInfo() : printer_status(0) {}

PrinterBasicInfo::~PrinterBasicInfo() {}

PrinterCapsAndDefaults::PrinterCapsAndDefaults() {}

PrinterCapsAndDefaults::~PrinterCapsAndDefaults() {}

PrintBackend::~PrintBackend() {}

}  // namespace printing

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

#include "printing/backend/print_backend.h"

namespace printing {

PrinterBasicInfo::PrinterBasicInfo()
    : printer_status(0),
      is_default(false) {}

PrinterBasicInfo::~PrinterBasicInfo() {}

PrinterCapsAndDefaults::PrinterCapsAndDefaults() {}

PrinterCapsAndDefaults::~PrinterCapsAndDefaults() {}

PrintBackend::~PrintBackend() {}

}  // namespace printing

Initialize a variable in PrinterBasicInfo.


#include <QApplication>
#include <QIcon>
#include <QSettings>
#include <QString>

#include "mainwindow.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QCoreApplication::setOrganizationName("SheetMusicViewer");
    QCoreApplication::setApplicationName("SheetMusicViewer");

    QSettings settings;
    QString customIconTheme = settings.value("customIconTheme").toString();
    if (!customIconTheme.isNull() && !customIconTheme.isEmpty())
    {
        QIcon::setThemeName(customIconTheme);
    }
    else
    {
        settings.setValue("customIconTheme", QString());
    }

    QString customStyle = settings.value("customStyle").toString();
    if (!customStyle.isNull() && !customStyle.isEmpty())
    {
        QApplication::setStyle(customStyle);
    }
    else
    {
        settings.setValue("customStyle", QString());
    }

    MainWindow w;
    w.show();
    return a.exec();
}

#include <QApplication>
#include <QIcon>
#include <QProcess>
#include <QSettings>
#include <QString>

#include "mainwindow.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QCoreApplication::setOrganizationName("SheetMusicViewer");
    QCoreApplication::setApplicationName("SheetMusicViewer");

    QSettings settings;
    QString customIconTheme = settings.value("customIconTheme").toString();
    if (!customIconTheme.isNull() && !customIconTheme.isEmpty())
    {
        QIcon::setThemeName(customIconTheme);
    }
    else
    {
        settings.setValue("customIconTheme", QString());
    }

    QString customStyle = settings.value("customStyle").toString();
    if (!customStyle.isNull() && !customStyle.isEmpty())
    {
        QApplication::setStyle(customStyle);
    }
    else
    {
        settings.setValue("customStyle", QString());
    }

    QString quitCommand = settings.value("quitCommand").toString();
    if (quitCommand.isNull() || quitCommand.isEmpty())
    {
        settings.setValue("quitCommand", QString());
    }

    MainWindow w;
    w.show();
    int ret = a.exec();

    if ((ret == 0) && !quitCommand.isNull() && !quitCommand.isEmpty())
    {
        QProcess::execute(quitCommand);
    }

    return ret;
}

Add support for quit command


#include "gtest/gtest.h"
#include "test_convergence.h"

// TODO: Add more extensive testing
class LqrKalmanConvergenceTest: public ConvergenceTest {
    public:
        void simulate() {
            for(unsigned int i = 0; i < m_N; ++i) {
                auto u = m_lqr->control_calculate(m_x);
                m_x = m_bicycle->x_next(m_x, u);

                auto z = m_bicycle->y(m_x);
                z(0) += m_r0(m_gen);
                z(1) += m_r1(m_gen);

                m_kalman->time_update(u);
                m_kalman->measurement_update(z);
            }
        }
};

TEST_P(LqrKalmanConvergenceTest, ZeroReference) {
    simulate();
    test_state_near(m_kalman->x(), x_true());
}

INSTANTIATE_TEST_CASE_P(
    ConvergenceRange_1_9,
    LqrKalmanConvergenceTest,
    ::testing::Range(0.5, 9.5, 0.5));

#include "gtest/gtest.h"
#include "test_convergence.h"

// TODO: Add more extensive testing
class LqrKalmanConvergenceTest: public ConvergenceTest {
    public:
        void simulate() {
            for(unsigned int i = 0; i < m_N; ++i) {
                auto u = m_lqr->control_calculate(m_kalman->x());
                m_x = m_bicycle->x_next(m_x, u);

                auto z = m_bicycle->y(m_x);
                z(0) += m_r0(m_gen);
                z(1) += m_r1(m_gen);

                m_kalman->time_update(u);
                m_kalman->measurement_update(z);
            }
        }
};

TEST_P(LqrKalmanConvergenceTest, ZeroReference) {
    simulate();
    test_state_near(m_kalman->x(), x_true());
}

INSTANTIATE_TEST_CASE_P(
    ConvergenceRange_1_9,
    LqrKalmanConvergenceTest,
    ::testing::Range(0.5, 9.5, 0.5));

Use Kalman estimate in LQR-Kalman test


#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;
}
}

#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;
}
}

Revert "Vehicle ammo prefix VAMMOTYPE_ to VEQUIPMENTAMMOTYPE_"


#include "hapticbutton.h"
#include <QPainter>

HapticButton::HapticButton(const QString &label) :
    QWidget(0), m_label(label), m_checked(false), m_checkable(false)
{
    setMinimumSize(100, 100);
}

void HapticButton::mousePressEvent(QMouseEvent *)
{
    if (m_checkable) {
        m_checked = !m_checked;
        emit toggled(m_checked);
    } else {
        emit clicked();
    }
}

void HapticButton::paintEvent(QPaintEvent *)
{
    QPainter paint(this);

    QRect r(0, 0, width()-1, height()-1);
    paint.drawRoundedRect(r, 10, 10);
    paint.drawText(r, Qt::AlignCenter, m_label);
}

#include "hapticbutton.h"
#include <QPainter>

HapticButton::HapticButton(const QString &label) :
    QWidget(0), m_label(label), m_checked(false), m_checkable(false)
{
    setMinimumSize(100, 100);
}

void HapticButton::mousePressEvent(QMouseEvent *)
{
    if (m_checkable) {
        m_checked = !m_checked;
        emit toggled(m_checked);
    } else {
        emit clicked();
    }
}

void HapticButton::paintEvent(QPaintEvent *)
{
    QPainter paint(this);

    QRect r(1, 1, width()-2, height()-2);
    paint.drawRoundedRect(r, 10, 10);
    paint.drawText(r, Qt::AlignCenter, m_label);
}

Make buttons look slightly better on N8


#include <configure/utils/path.hpp>
#include <configure/error.hpp>

BOOST_AUTO_TEST_CASE(path)
{
	using namespace configure::utils;
	BOOST_CHECK_THROW(
	    relative_path("pif", "/paf"),
	    configure::error::InvalidPath
	);
	BOOST_CHECK_THROW(
	    relative_path("/pif", "paf"),
	    configure::error::InvalidPath
	);

	BOOST_CHECK_EQUAL(
	    relative_path("/pif", "/paf"),
	    "../pif"
	);

	BOOST_CHECK_EQUAL(
	    relative_path("/pif", "/pif"),
	    "."
	);
}

#include <configure/utils/path.hpp>
#include <configure/error.hpp>

namespace fs = boost::filesystem;

BOOST_AUTO_TEST_CASE(path)
{
# define P1 "pif"
# define P2 "paf"
#ifdef _WIN32
# define ABS_P1 "c:\\pif"
# define ABS_P2 "c:/paf"
#else
# define ABS_P1 "/pif"
# define ABS_P2 "/paf"
#endif
	using namespace configure::utils;
	BOOST_CHECK_THROW(
	    relative_path(P1, ABS_P2),
	    configure::error::InvalidPath
	);
	BOOST_CHECK_THROW(
	    relative_path(ABS_P1, P2),
	    configure::error::InvalidPath
	);

	BOOST_CHECK_EQUAL(
	    relative_path(ABS_P1, ABS_P2),
	    fs::path("..") / P1
	);

	BOOST_CHECK_EQUAL(
	    relative_path(ABS_P2, ABS_P1),
	    fs::path("..") / P2
	);

	BOOST_CHECK_EQUAL(
	    relative_path(ABS_P1, ABS_P1),
	    "."
	);

	BOOST_CHECK_EQUAL(
	    relative_path(ABS_P2, ABS_P2),
	    "."
	);
}

Fix path test on windows


#include "wrangleplow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
  QApplication app(argc, argv);

  WranglePlow::MainWindow wrangleplow;
  wrangleplow.show();
  wrangleplow.resize(1024, 768);

  return app.exec();
}

#include "wrangleplow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
  QApplication app(argc, argv);

  WranglePlow::MainWindow wrangleplow;
  wrangleplow.show();
  wrangleplow.resize(1024, 768);
  wrangleplow.move(100, 100);

  return app.exec();
}

Move the window to a good location.


#include "./persistent_constraint_updater.h"
#include "./constraint_updater.h"

PersistentConstraintUpdater::PersistentConstraintUpdater(
    std::shared_ptr<ConstraintUpdater> constraintUpdater)
  : constraintUpdater(constraintUpdater)
{
}

void PersistentConstraintUpdater::updateConstraints(
    int labelId, Eigen::Vector2i anchorForBuffer,
    Eigen::Vector2i labelSizeForBuffer)
{
  constraintUpdater->clear();

  for (auto &placedLabelPair : placedLabels)
  {
    auto &placedLabel = placedLabelPair.second;
    constraintUpdater->drawConstraintRegionFor(
        anchorForBuffer, labelSizeForBuffer, placedLabel.anchorPosition,
        placedLabel.labelPosition, placedLabel.size);
  }

  placedLabels[labelId] = PlacedLabelInfo{ labelSizeForBuffer, anchorForBuffer,
                                           Eigen::Vector2i(-1, -1) };
}

void PersistentConstraintUpdater::setPosition(int labelId,
                                              Eigen::Vector2i position)
{
  placedLabels[labelId].labelPosition = position;
}

void PersistentConstraintUpdater::clear()
{
  placedLabels.clear();
}

#include "./persistent_constraint_updater.h"
#include <chrono>
#include <QLoggingCategory>
#include "./constraint_updater.h"

QLoggingCategory pcuChan("Placement.PersistentConstraintUpdater");

PersistentConstraintUpdater::PersistentConstraintUpdater(
    std::shared_ptr<ConstraintUpdater> constraintUpdater)
  : constraintUpdater(constraintUpdater)
{
}

void PersistentConstraintUpdater::updateConstraints(
    int labelId, Eigen::Vector2i anchorForBuffer,
    Eigen::Vector2i labelSizeForBuffer)
{
  auto startTime = std::chrono::high_resolution_clock::now();
  constraintUpdater->clear();

  for (auto &placedLabelPair : placedLabels)
  {
    auto &placedLabel = placedLabelPair.second;
    constraintUpdater->drawConstraintRegionFor(
        anchorForBuffer, labelSizeForBuffer, placedLabel.anchorPosition,
        placedLabel.labelPosition, placedLabel.size);
  }

  placedLabels[labelId] = PlacedLabelInfo{ labelSizeForBuffer, anchorForBuffer,
                                           Eigen::Vector2i(-1, -1) };

  auto endTime = std::chrono::high_resolution_clock::now();
  std::chrono::duration<float, std::milli> diff = endTime - startTime;

  qCInfo(pcuChan) << "updateConstraints took" << diff.count() << "ms";
}

void PersistentConstraintUpdater::setPosition(int labelId,
                                              Eigen::Vector2i position)
{
  placedLabels[labelId].labelPosition = position;
}

void PersistentConstraintUpdater::clear()
{
  placedLabels.clear();
}

Write PersistentConstraintUpdater::updateConstraints timing to log.


//===----------------------------------------------------------------------===//
//
//                     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: c++98, c++03

// The system unwind.h on OS X provides an incorrectly aligned _Unwind_Exception
// type. That causes these tests to fail. This XFAIL is my best attempt at
// working around this failure.
// XFAIL: darwin && libcxxabi-has-system-unwinder

// Test that the address of the exception object is properly aligned to the
// largest supported alignment for the system.

#include <cstdint>
#include <cassert>

#include <unwind.h>

struct __attribute__((aligned)) AlignedType {};
static_assert(alignof(AlignedType) == alignof(_Unwind_Exception),
  "_Unwind_Exception is incorrectly aligned. This test is expected to fail");

struct MinAligned {  };
static_assert(alignof(MinAligned) == 1 && sizeof(MinAligned) == 1, "");

int main() {
  for (int i=0; i < 10; ++i) {
    try {
      throw MinAligned{};
    } catch (MinAligned const& ref) {
      assert(reinterpret_cast<uintptr_t>(&ref) % alignof(AlignedType) == 0);
    }
  }
}

//===----------------------------------------------------------------------===//
//
//                     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: libcxxabi-no-exceptions
// UNSUPPORTED: c++98, c++03

// The system unwind.h on OS X provides an incorrectly aligned _Unwind_Exception
// type. That causes these tests to fail. This XFAIL is my best attempt at
// working around this failure.
// XFAIL: darwin && libcxxabi-has-system-unwinder

// Test that the address of the exception object is properly aligned to the
// largest supported alignment for the system.

#include <cstdint>
#include <cassert>

#include <unwind.h>

struct __attribute__((aligned)) AlignedType {};
static_assert(alignof(AlignedType) == alignof(_Unwind_Exception),
  "_Unwind_Exception is incorrectly aligned. This test is expected to fail");

struct MinAligned {  };
static_assert(alignof(MinAligned) == 1 && sizeof(MinAligned) == 1, "");

int main() {
  for (int i=0; i < 10; ++i) {
    try {
      throw MinAligned{};
    } catch (MinAligned const& ref) {
      assert(reinterpret_cast<uintptr_t>(&ref) % alignof(AlignedType) == 0);
    }
  }
}

Add missing UNSUPPORTED for -fno-exception mode


// RUN: %clang_cc1 -fsyntax-only -verify %s
class A { };

class B1 : A { };

class B2 : virtual A { };

class B3 : virtual virtual A { }; // expected-error{{duplicate 'virtual' in base specifier}}

class C : public B1, private B2 { };

class D;                // expected-note {{forward declaration of 'D'}}

class E : public D { }; // expected-error{{base class has incomplete type}}

typedef int I;

class F : public I { }; // expected-error{{base specifier must name a class}}

union U1 : public A { }; // expected-error{{unions cannot have base classes}}

union U2 {};

class G : public U2 { }; // expected-error{{unions cannot be base classes}}

typedef G G_copy;
typedef G G_copy_2;
typedef G_copy G_copy_3;

class H : G_copy, A, G_copy_2, // expected-error{{base class 'G_copy' (aka 'G') specified more than once as a direct base class}}
          public G_copy_3 { }; // expected-error{{base class 'G_copy' (aka 'G') specified more than once as a direct base class}}

struct J { char c; int i[]; };
struct K : J { }; // expected-error{{base class 'J' has a flexible array member}}

Add test case for r193923


#include <stingraykit/io/ByteDataConsumer.h>

namespace stingray
{

	ByteDataConsumer::ByteDataConsumer(ByteData consumer)
		:	_consumer(consumer)
	{ }

	size_t ByteDataConsumer::Process(ConstByteData data, const ICancellationToken&)
	{
		const size_t size = data.size();

		STINGRAYKIT_CHECK(size <= _consumer.size(), IndexOutOfRangeException(size, _consumer.size()));

		std::copy(data.data(), data.data() + size, _consumer.data());
		_consumer = ByteData(_consumer, size);

		return size;
	}

}

#include <stingraykit/io/ByteDataConsumer.h>

#include <string.h>

namespace stingray
{

	ByteDataConsumer::ByteDataConsumer(ByteData consumer)
		:	_consumer(consumer)
	{ }

	size_t ByteDataConsumer::Process(ConstByteData data, const ICancellationToken&)
	{
		const size_t size = data.size();

		STINGRAYKIT_CHECK(size <= _consumer.size(), IndexOutOfRangeException(size, _consumer.size()));

		memcpy(_consumer.data(), data.data(), size);
		_consumer = ByteData(_consumer, size);

		return size;
	}

}

Change std::copy to memcpy in critical places.


#include "qtquick1applicationviewer.h"
#include <QApplication>
#include <QDeclarativeComponent>
#include <QDeclarativeEngine>
#include <QDeclarativeContext>
#include "artworkimageprovider.h"

#include "qiscp.h"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QtQuick1ApplicationViewer viewer;

    qmlRegisterType<qiscp>("org.tal.qiscp", 1, 0, "QISCP");
    qmlRegisterUncreatableType<qiscpInputs>("org.tal.qiscp", 1, 0, "ISCPInputs", "ISCPInputs can not be created");

    viewer.engine()->addImageProvider(QLatin1String("artwork"), new ArtworkImageProvider());

    viewer.addImportPath(QLatin1String("modules"));
    viewer.setOrientation(QtQuick1ApplicationViewer::ScreenOrientationAuto);
    viewer.setMainQmlFile(QLatin1String("qml/test/main.qml"));
    viewer.showExpanded();

    return app.exec();
}

#include "qtquick1applicationviewer.h"
#include <QApplication>
#include <QDeclarativeComponent>
#include <QDeclarativeEngine>
#include <QDeclarativeContext>
#include "artworkimageprovider.h"

#include "qiscp.h"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QtQuick1ApplicationViewer viewer;

    qmlRegisterType<qiscp>("org.tal.qiscp", 1, 0, "QISCP");
    // qmlRegisterUncreatableType<qiscpInputs>("org.tal.qiscp", 1, 0, "ISCPInputs", "ISCPInputs can not be created");

    QDeclarativeContext *context = viewer.rootContext();
    context->setContextProperty("ISCPInputs", new qiscpInputs());

    viewer.engine()->addImageProvider(QLatin1String("artwork"), new ArtworkImageProvider());

    viewer.addImportPath(QLatin1String("modules"));
    viewer.setOrientation(QtQuick1ApplicationViewer::ScreenOrientationAuto);
    viewer.setMainQmlFile(QLatin1String("qml/test/main.qml"));
    viewer.showExpanded();

    return app.exec();
}

Use setContextProperty() to make the input helper available


#include "AConfig.h"
#if(HAS_STD_CALIBRATIONLASERS)
#include "Device.h"
#include "Pin.h"
#include "CalibrationLaser.h"
#include "Settings.h"

Pin claser("claser", CALIBRATIONLASERS_PIN, claser.analog, claser.out);

void CalibrationLaser::device_setup(){
    Settings::capability_bitarray |= (1 << CALIBRATION_LASERS_CAPABLE);
    claser.write(0);
}

void CalibrationLaser::device_loop(Command command){
    if( command.cmp("claser")){
      int value = command.args[1];
      claser.write(value);
    }

}
#endif

#include "AConfig.h"
#if(HAS_STD_CALIBRATIONLASERS)
#include "Device.h"
#include "Pin.h"
#include "CalibrationLaser.h"
#include "Settings.h"

Pin claser("claser", CALIBRATIONLASERS_PIN, claser.analog, claser.out);

void CalibrationLaser::device_setup(){
    Settings::capability_bitarray |= (1 << CALIBRATION_LASERS_CAPABLE);
    claser.write(0);
}

void CalibrationLaser::device_loop(Command command){
    if( command.cmp("claser")){
      int value = command.args[1];
      claser.write(value);
      claser.send(value);
    }

}
#endif

Revert "Revert "Adding laser indicator""


#include "KeyboardHotkeyProcessor.h"

#include <string>

#include "SyntheticKeyboard.h"
#include "HotkeyInfo.h"
#include "Logger.h"

std::unordered_map<std::wstring, unsigned short>
    KeyboardHotkeyProcessor::mediaKeyMap = CreateKeyMap();

void KeyboardHotkeyProcessor::ProcessHotkeys(HotkeyInfo &hki) {
    if (hki.action != HotkeyInfo::MediaKey || hki.args.size() != 1) {
        return;
    }

    std::wstring arg = hki.args[0];
    unsigned short vk = mediaKeyMap[arg];
    CLOG(L"Simulating media keypress: %s", arg.c_str());
    SyntheticKeyboard::SimulateKeypress(vk);
}

std::unordered_map<std::wstring, unsigned short>
        KeyboardHotkeyProcessor::CreateKeyMap() {
    std::unordered_map<std::wstring, unsigned short> map;
    for (unsigned int i = 0; i < HotkeyInfo::MediaKeyNames.size(); ++i) {
        map[HotkeyInfo::MediaKeyNames[i]] = HotkeyInfo::MediaKeyVKs[i];
    }
    return map;
}

#include "KeyboardHotkeyProcessor.h"

#include <string>

#include "SyntheticKeyboard.h"
#include "HotkeyInfo.h"
#include "Logger.h"

std::unordered_map<std::wstring, unsigned short>
    KeyboardHotkeyProcessor::mediaKeyMap = CreateKeyMap();

void KeyboardHotkeyProcessor::ProcessHotkeys(HotkeyInfo &hki) {
    /* These hotkeys *require* exactly one argument: */
    if (hki.args.size() != 1) {
        return;
    }

    switch (hki.action) {
    case HotkeyInfo::MediaKey: {
        std::wstring &arg = hki.args[0];
        unsigned short vk = mediaKeyMap[arg];
        CLOG(L"Media key: %s", arg.c_str());
        SyntheticKeyboard::SimulateKeypress(vk);
        break;
    }

    case HotkeyInfo::VirtualKey: {

        break;
    }
    }
}

std::unordered_map<std::wstring, unsigned short>
        KeyboardHotkeyProcessor::CreateKeyMap() {
    std::unordered_map<std::wstring, unsigned short> map;
    for (unsigned int i = 0; i < HotkeyInfo::MediaKeyNames.size(); ++i) {
        map[HotkeyInfo::MediaKeyNames[i]] = HotkeyInfo::MediaKeyVKs[i];
    }
    return map;
}

Reorganize KB HK processor for new VK hotkeys


#include "RawTextGraphInput.hh"

/*
  name
  |V|
  [|V| names]
  |E|
  [|E| lines formatted like start end type distance]
 */

template <typename V>
void RawTextGraphInput<V>::input(string path) {

  ifstream ifs(path, ifstream::in);

  int v, e;
  string title;

  // Graph title fetching

  ifs >> title;

  this->graph_.setName(title);

  // Vertices fetching

  ifs >> v;

  for (int i = 0; i < v; i++) {
    ifs >> title;
    this->graph_.addVertex(title);
  }

  // Edges fetching

  unsigned int start, end;
  string type;
  EdgeType t;
  V dist;

  ifs >> e;

  for (int i = 0; i < e; i++) {
    ifs >> start >> end >> type >> dist;
    if (type == "Train")
      t = EdgeType::Train;
    else if (type == "Road")
      t = EdgeType::Road;
    else
      t = EdgeType::Plane;

    this->graph_.addEdge(t, dist, start, end);
  }
}

template class RawTextGraphInput<double>;

#include "RawTextGraphInput.hh"

/*
  name
  |V|
  [|V| names]
  |E|
  [|E| lines formatted like start end type distance]
 */

template <typename V>
void RawTextGraphInput<V>::input(string path) {

  ifstream ifs(path, ifstream::in);

  int v, e;
  string title;

  // Graph title fetching

  ifs >> title;

  this->graph_.setName(title);

  // Vertices fetching

  ifs >> v;
  getline(ifs, title); // wtf

  for (int i = 0; i < v; i++) {
    getline(ifs, title);
    std::cout << "Found " << title << std::endl;
    this->graph_.addVertex(title);
  }

  // Edges fetching

  unsigned int start, end;
  string type;
  EdgeType t;
  V dist;

  ifs >> e;

  for (int i = 0; i < e; i++) {
    ifs >> start >> end >> type >> dist;
    if (type == "Train")
      t = EdgeType::Train;
    else if (type == "Road")
      t = EdgeType::Road;
    else
      t = EdgeType::Plane;

    this->graph_.addEdge(t, dist, start, end);
  }
}

template class RawTextGraphInput<double>;

Fix a parsing issue when a vertex has space in its name


#include <typeinfo>

class A {
    virtual void x() { }
};

class B : public A {
    void x() override { }
};

int main() {
    A a;
    B *b = dynamic_cast<B *>(&a);
    (void)b;
    return 0;
}

#include <typeinfo>

class I {
public:
    virtual ~I() { }
    virtual void x() { }
};

class A : public I {
    void x() override { }
};

class B : public I {
    void x() override { }
};

int main() {
    I *a = new A();
    B *b = dynamic_cast<B *>(a);
    (void)b;
    delete a;
    return 0;
}

Fix enableRtti test with GCC.


#include "Bootil/Bootil.h"

using namespace Bootil;

int main( int argc, char** argv )
{
	CommandLine::Set( argc, argv );

	BString strInFolder = CommandLine::GetArg( 0, "" );
	BString strOutFolder = CommandLine::GetArg( 1, strInFolder );

	if (strInFolder == "")
		Output::Error("Usage: gluaextract <in> [out]");

	String::List files;
	String::List folders;
	File::Find( &files, &folders, strInFolder + "/*.lua", false );

	Output::Msg( "Converting %i files.\n", files.size() );

	BOOTIL_FOREACH_CONST(f, files, String::List)
	{
		AutoBuffer inBuf;
		File::Read(strInFolder + "/" + *f, inBuf);

		// Extract using LZMA (first 4 bytes are junk)
		AutoBuffer outBuf;
		Compression::LZMA::Extract(inBuf.GetBase(4), inBuf.GetSize()-4, outBuf);

		File::Write(strOutFolder + "/" + *f, outBuf);
	}

	return 0;
}

#include "Bootil/Bootil.h"

using namespace Bootil;

int main( int argc, char** argv )
{
	Debug::SuppressPopups( true );
	CommandLine::Set( argc, argv );

	Console::FGColorPush( Console::Green );
    Output::Msg( "GMod Lua Cache Extractor 1.0\n\n" );
    Console::FGColorPop();

	BString strInFolder = CommandLine::GetArg( 0, "" );
	BString strOutFolder = CommandLine::GetArg( 1, strInFolder );

	if (strInFolder == "")
		Output::Error("Usage: gluaextract <in> [out]");

	String::List files;
	String::List folders;
	File::Find( &files, &folders, strInFolder + "/*.lua", false );
	File::CreateFolder(strOutFolder);

	Output::Msg( "Converting %i files.\n", files.size() );

	BOOTIL_FOREACH_CONST(f, files, String::List)
	{
		AutoBuffer inBuf;
		File::Read(strInFolder + "/" + *f, inBuf);

		// Extract using LZMA (first 4 bytes are junk)
		AutoBuffer outBuf;
		Compression::LZMA::Extract(inBuf.GetBase(4), inBuf.GetSize()-4, outBuf);

		File::Write(strOutFolder + "/" + *f, outBuf);
	}

	return 0;
}

Create output folder if does not exist. Suppress debug popups.


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

#include "base/test/thread_test_helper.h"

#include "base/location.h"

namespace base {

ThreadTestHelper::ThreadTestHelper(MessageLoopProxy* target_thread)
    : test_result_(false),
      target_thread_(target_thread),
      done_event_(false, false) {
}

bool ThreadTestHelper::Run() {
  if (!target_thread_->PostTask(FROM_HERE, NewRunnableMethod(
          this, &ThreadTestHelper::RunInThread))) {
    return false;
  }
  done_event_.Wait();
  return test_result_;
}

void ThreadTestHelper::RunTest() { set_test_result(true); }

ThreadTestHelper::~ThreadTestHelper() {}

void ThreadTestHelper::RunInThread() {
  RunTest();
  done_event_.Signal();
}

}  // namespace base

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

#include "base/test/thread_test_helper.h"

#include "base/bind.h"
#include "base/location.h"

namespace base {

ThreadTestHelper::ThreadTestHelper(MessageLoopProxy* target_thread)
    : test_result_(false),
      target_thread_(target_thread),
      done_event_(false, false) {
}

bool ThreadTestHelper::Run() {
  if (!target_thread_->PostTask(
          FROM_HERE, base::Bind(&ThreadTestHelper::RunInThread, this))) {
    return false;
  }
  done_event_.Wait();
  return test_result_;
}

void ThreadTestHelper::RunTest() { set_test_result(true); }

ThreadTestHelper::~ThreadTestHelper() {}

void ThreadTestHelper::RunInThread() {
  RunTest();
  done_event_.Signal();
}

}  // namespace base

Convert NewRunnableMethod() to base::Bind() in base::TestThreadHelper.


/******************************************************************************/
/*
  Author  - Ming-Lun "Allen" Chou
  Web     - http://AllenChou.net
  Twitter - @TheAllenChou
 */
/******************************************************************************/

#include "sidnet/sidnet.h"
#include "sidnet/sidserver.h"

static bool s_shouldExit = false;

int main(int argc, const char** argv)
{
  // default config
  const char *cfgPath = "sidserver.cfg";
  int port = 2266;

  FILE *pCfgFile = std::fopen(cfgPath, "r");
  if (pCfgFile)
  {
    std::fscanf(pCfgFile, "%d", &port);
  }
  else if (pCfgFile = std::fopen(cfgPath, "w+"))
  {
    std::fprintf(pCfgFile, "%d", port);
  }
  if (pCfgFile)
  {
    std::fclose(pCfgFile);
  }

  int err = 0;

  err = sidnet::Init();
  if (err)
    return err;

  sidnet::SidServer server;
  err = server.Start(port);
  if (!err)
    return err;

  while (!s_shouldExit)
  {

  }

  sidnet::ShutDown();

  return 0;
}

/******************************************************************************/
/*
  Author  - Ming-Lun "Allen" Chou
  Web     - http://AllenChou.net
  Twitter - @TheAllenChou
 */
/******************************************************************************/

#include "sidnet/sidnet.h"
#include "sidnet/sidserver.h"

static bool s_shouldExit = false;

int main(int argc, const char** argv)
{
  // default config
  const char *cfgPath = "sidserver.cfg";
  int port = 2266;

  FILE *pCfgFile = std::fopen(cfgPath, "r");
  if (pCfgFile)
  {
    std::fscanf(pCfgFile, "%d", &port);
  }
  else if (pCfgFile = std::fopen(cfgPath, "w+"))
  {
    std::fprintf(pCfgFile, "%d", port);
  }
  if (pCfgFile)
  {
    std::fclose(pCfgFile);
  }

  int err = 0;

  err = sidnet::Init();
  if (err)
    return err;

  sidnet::SidServer server;
  err = server.Start(port);
  if (err)
    return err;

  while (!s_shouldExit)
  {

  }

  sidnet::ShutDown();

  return 0;
}

Fix incorrect error code handling.


#include "compiler/build_tables/item_set_closure.h"
#include <algorithm>
#include <set>
#include "tree_sitter/compiler.h"
#include "compiler/build_tables/follow_sets.h"
#include "compiler/build_tables/item.h"
#include "compiler/prepared_grammar.h"

namespace tree_sitter {
    using std::set;
    using rules::ISymbol;
    using std::vector;

    namespace build_tables {
        const ParseItemSet item_set_closure(const ParseItem &item,
                                            const PreparedGrammar &grammar) {
            ParseItemSet result;
            vector<ParseItem> items_to_add = { item };
            while (!items_to_add.empty()) {
                const ParseItem &item = items_to_add.back();
                items_to_add.pop_back();
                auto insertion_result = result.insert(item);
                if (insertion_result.second) {
                    for (const auto &pair : follow_sets(item, grammar)) {
                        const ISymbol &non_terminal = pair.first;
                        const set<ISymbol> &terminals = pair.second;
                        for (const auto &terminal : terminals) {
                            ParseItem next_item(non_terminal, grammar.rule(non_terminal), 0, terminal);
                            items_to_add.push_back(next_item);
                        }
                    }
                }
            }
            return result;
        }
    }
}

#include "compiler/build_tables/item_set_closure.h"
#include <algorithm>
#include <set>
#include "tree_sitter/compiler.h"
#include "compiler/build_tables/follow_sets.h"
#include "compiler/build_tables/item.h"
#include "compiler/prepared_grammar.h"

namespace tree_sitter {
    using std::set;
    using rules::ISymbol;
    using std::vector;

    namespace build_tables {
        const ParseItemSet item_set_closure(const ParseItem &item,
                                            const PreparedGrammar &grammar) {
            ParseItemSet result;
            vector<ParseItem> items_to_add = { item };
            while (!items_to_add.empty()) {
                ParseItem item = items_to_add.back();
                items_to_add.pop_back();
                auto insertion_result = result.insert(item);
                if (insertion_result.second) {
                    for (const auto &pair : follow_sets(item, grammar)) {
                        const ISymbol &non_terminal = pair.first;
                        const set<ISymbol> &terminals = pair.second;
                        for (const auto &terminal : terminals) {
                            ParseItem next_item(non_terminal, grammar.rule(non_terminal), 0, terminal);
                            items_to_add.push_back(next_item);
                        }
                    }
                }
            }
            return result;
        }
    }
}

Fix dangling reference error on gcc


#include <memory>
#include "film/color.h"
#include "textures/texture.h"
#include "material/lambertian.h"
#include "material/oren_nayer.h"
#include "material/matte_material.h"
#include "material/specular_reflection.h"
#include "material/fresnel.h"

MatteMaterial::MatteMaterial(const Texture *diffuse, float roughness)
	: diffuse(diffuse), roughness(roughness)
{}
BSDF MatteMaterial::get_bsdf(const DifferentialGeometry &dg) const {
	BSDF bsdf{dg};
	Colorf kd = diffuse->sample(dg).normalized();
	if (roughness == 0){
		bsdf.add(std::make_unique<Lambertian>(kd));
	}
	else {
		bsdf.add(std::make_unique<OrenNayer>(kd, roughness));
		bsdf.add(std::make_unique<SpecularReflection>(kd, std::make_unique<FresnelNoOp>()));
	}
	return bsdf;
}

#include <memory>
#include "film/color.h"
#include "textures/texture.h"
#include "material/lambertian.h"
#include "material/oren_nayer.h"
#include "material/matte_material.h"
#include "material/specular_reflection.h"
#include "material/fresnel.h"

MatteMaterial::MatteMaterial(const Texture *diffuse, float roughness)
	: diffuse(diffuse), roughness(roughness)
{}
BSDF MatteMaterial::get_bsdf(const DifferentialGeometry &dg) const {
	BSDF bsdf{dg};
	Colorf kd = diffuse->sample(dg).normalized();
	if (roughness == 0){
		bsdf.add(std::make_unique<Lambertian>(kd));
	}
	else {
		bsdf.add(std::make_unique<OrenNayer>(kd, roughness));
	}
	return bsdf;
}

Revert MatteMaterial to its standard form


#include "file_scrubber.hpp"

#include <stdio.h>
#include <iostream>

#include "string_utils.hpp"
#include "error.hpp"

using std::ifstream;

namespace mocc {
    FileScrubber::FileScrubber(const char* fName, const char* commentFlag):
    	stream_(fName),
    	flag_(commentFlag){

            if( !stream_.good() ) {
                Error("Failed to open file.");
            }

        }

    FileScrubber::~FileScrubber(){}

    std::string FileScrubber::getline(){
    	while(!stream_.eof()){
    		std::string line;
    		std::getline(stream_, line);
    		// Strip the comments
    		unsigned int commentPos = line.find(flag_, 0);
    		if(commentPos != std::string::npos){
    			line.erase(commentPos, std::string::npos);
    		}
    		// Remove whitespace
    		line = trim(line);
    		// If the result isnt empty, return the line.
    		if(!line.empty()){
    			return line;
    		}
    	}
    	return "";
    }
}

#include "file_scrubber.hpp"

#include <stdio.h>
#include <iostream>

#include "string_utils.hpp"
#include "error.hpp"

using std::ifstream;

namespace mocc {
    FileScrubber::FileScrubber(const char* fName, const char* commentFlag):
    	stream_(fName),
    	flag_(commentFlag){

            if( !stream_.good() ) {
                Error("Failed to open file.");
            }

        }

    FileScrubber::~FileScrubber(){}

    std::string FileScrubber::getline(){
    	while(!stream_.eof()){
    		std::string line;
    		std::getline(stream_, line);
    		// Strip the comments
    		size_t commentPos = line.find(flag_, 0);
    		if(commentPos != std::string::npos){
    			line.erase(commentPos, std::string::npos);
    		}
    		// Remove whitespace
    		line = trim(line);
    		// If the result isnt empty, return the line.
    		if(!line.empty()){
    			return line;
    		}
    	}
    	return "";
    }
}

Fix overflow issue in file scrubber. npos is big


#include "listener.h"
#include "log.h"
#include "buffers.h"

void conditionalEnqueue(QUEUE_TYPE(uint8_t)* queue, uint8_t* message,
        int messageSize) {
    if(queue_available(queue) < messageSize + 2) {
        debug("Dropped incoming CAN message -- send queue (at %p) full\r\n",
                queue);
        return;
    }

    for(int i = 0; i < messageSize; i++) {
        QUEUE_PUSH(uint8_t, queue, (uint8_t)message[i]);
    }
    QUEUE_PUSH(uint8_t, queue, (uint8_t)'\r');
    QUEUE_PUSH(uint8_t, queue, (uint8_t)'\n');
}

void sendMessage(Listener* listener, uint8_t* message, int messageSize) {
    // TODO the more we enqueue here, the slower it gets - cuts the rate by
    // almost half to do it with 2 queues. we could either figure out how to
    // share a queue or make the enqueue function faster. right now I believe it
    // enqueues byte by byte, which could obviously be improved.
    if(listener->usb->configured) {
        conditionalEnqueue(&listener->usb->sendQueue, message, messageSize);
    } else {
        conditionalEnqueue(&listener->serial->sendQueue, message, messageSize);
    }
}

void processListenerQueues(Listener* listener) {
    // Must always process USB, because this function usually runs the MCU's USB
    // task that handles SETUP and enumeration.
    processInputQueue(listener->usb);
    if(!listener->usb->configured) {
        processInputQueue(listener->serial);
    }
}

#include "listener.h"
#include "log.h"
#include "buffers.h"

void conditionalEnqueue(QUEUE_TYPE(uint8_t)* queue, uint8_t* message,
        int messageSize) {
    if(queue_available(queue) < messageSize + 2) {
        debug("Dropped incoming CAN message -- send queue (at %p) full\r\n",
                queue);
        return;
    }

    for(int i = 0; i < messageSize; i++) {
        QUEUE_PUSH(uint8_t, queue, (uint8_t)message[i]);
    }
    QUEUE_PUSH(uint8_t, queue, (uint8_t)'\r');
    QUEUE_PUSH(uint8_t, queue, (uint8_t)'\n');
}

void sendMessage(Listener* listener, uint8_t* message, int messageSize) {
    if(listener->usb->configured) {
        conditionalEnqueue(&listener->usb->sendQueue, message, messageSize);
    } else {
        conditionalEnqueue(&listener->serial->sendQueue, message, messageSize);
    }
}

void processListenerQueues(Listener* listener) {
    // Must always process USB, because this function usually runs the MCU's USB
    // task that handles SETUP and enumeration.
    processInputQueue(listener->usb);
    if(!listener->usb->configured) {
        processInputQueue(listener->serial);
    }
}

Remove TODO - problem was debug() printing, not enqueing.


#include "removegrain.h"
#include "clense.h"
#include "repair.h"
#include "vertical_cleaner.h"

const AVS_Linkage *AVS_linkage = nullptr;

extern "C" __declspec(dllexport) const char* __stdcall AvisynthPluginInit3(IScriptEnvironment* env, const AVS_Linkage* const vectors) {
    AVS_linkage = vectors;

    env->AddFunction("RemoveGrain", "c[mode]i[modeU]i[modeV]i[planar]b", Create_RemoveGrain, 0);
    env->AddFunction("Repair", "cc[mode]i[modeU]i[modeV]i[planar]b", Create_Repair, 0);
    env->AddFunction("Clense", "c[previous]c[next]c[grey]b", Create_Clense, 0);
    env->AddFunction("ForwardClense", "c[grey]b", Create_ForwardClense, 0);
    env->AddFunction("BackwardClense", "c[grey]b", Create_BackwardClense, 0);
    env->AddFunction("VerticalCleaner", "c[mode]i[modeU]i[modeV]i", Create_VerticalCleaner, 0);
    return "Itai, onii-chan!";
}

#include "removegrain.h"
#include "clense.h"
#include "repair.h"
#include "vertical_cleaner.h"

const AVS_Linkage *AVS_linkage = nullptr;

extern "C" __declspec(dllexport) const char* __stdcall AvisynthPluginInit3(IScriptEnvironment* env, const AVS_Linkage* const vectors) {
    AVS_linkage = vectors;

    env->AddFunction("RemoveGrain", "c[mode]i[modeU]i[modeV]i[planar]b", Create_RemoveGrain, 0);
    env->AddFunction("Repair", "cc[mode]i[modeU]i[modeV]i[planar]b", Create_Repair, 0);
    env->AddFunction("Clense", "c[previous]c[next]c[grey]b", Create_Clense, 0);
    env->AddFunction("ForwardClense", "c[grey]b", Create_ForwardClense, 0);
    env->AddFunction("BackwardClense", "c[grey]b", Create_BackwardClense, 0);
    env->AddFunction("VerticalCleaner", "c[mode]i[modeU]i[modeV]i[planar]b", Create_VerticalCleaner, 0);
    return "Itai, onii-chan!";
}

Add planar parameter to VerticalCleaner registration


#include <Halide.h>
#include "vzero.h"
#include <stdio.h>
using namespace Halide;

// RUN: rm -f vzero.stdout; ./vzero.out; llvm-dis -o vzero.stdout vzero.bc; FileCheck %s < vzero.stdout

int main(int argc, char **argv) {
  Target target;
  setupHexagonTarget(target);
  target.set_feature(Target::HVX_64);
  //CHECK: call{{.*}}@llvm.hexagon.V6.vd0
  testBzero<uint32_t>(target);

  printf ("Done\n");

  return 0;
}

#include <Halide.h>
#include "vzero.h"
#include <stdio.h>
using namespace Halide;

// RUN: rm -f vzero.stdout; ./vzero.out; llvm-dis -o vzero.stdout vzero.bc; FileCheck %s < vzero.stdout

int main(int argc, char **argv) {
  Target target;
  setupHexagonTarget(target, Target::HVX_64);
  //CHECK: call{{.*}}@llvm.hexagon.V6.vd0
  testBzero<uint32_t>(target);

  printf ("Done\n");

  return 0;
}

Fix error in setting both HVX_64 and HVX_128 at same time


// RUN: %clangxx_asan -O2 %s -o %t && %t 2>&1 | %symbolize | FileCheck %s

// Test how well we unwind in presence of qsort in the stack
// (i.e. if we can unwind through a function compiled w/o frame pointers).
// https://code.google.com/p/address-sanitizer/issues/detail?id=137
#include <stdlib.h>
#include <stdio.h>

int global_array[10];
volatile int one = 1;

extern "C"
int QsortCallback(const void *a, const void *b) {
  char *x = (char*)a;
  char *y = (char*)b;
  printf("Calling QsortCallback\n");
  global_array[one * 10] = 0;  // BOOM
  return (int)*x - (int)*y;
}

__attribute__((noinline))
void MyQsort(char *a, size_t size) {
  printf("Calling qsort\n");
  qsort(a, size, sizeof(char), QsortCallback);
  printf("Done\n");  // Avoid tail call.
}

int main() {
  char a[2] = {1, 2};
  MyQsort(a, 2);
}

// CHECK: ERROR: AddressSanitizer: global-buffer-overflow
// CHECK: #0{{.*}} in QsortCallback
// CHECK: is located 0 bytes to the right of global variable 'global_array

// RUN: %clangxx_asan -O2 %s -o %t && %t 2>&1 | %symbolize | FileCheck %s

// Test how well we unwind in presence of qsort in the stack
// (i.e. if we can unwind through a function compiled w/o frame pointers).
// https://code.google.com/p/address-sanitizer/issues/detail?id=137
#include <stdlib.h>
#include <stdio.h>

int global_array[10];
volatile int one = 1;

extern "C"
int QsortCallback(const void *a, const void *b) {
  char *x = (char*)a;
  char *y = (char*)b;
  printf("Calling QsortCallback\n");
  global_array[one * 10] = 0;  // BOOM
  return (int)*x - (int)*y;
}

__attribute__((noinline))
void MyQsort(char *a, size_t size) {
  printf("Calling qsort\n");
  qsort(a, size, sizeof(char), QsortCallback);
  printf("Done\n");  // Avoid tail call.
}

int main() {
  char a[2] = {1, 2};
  MyQsort(a, 2);
}

// CHECK: ERROR: AddressSanitizer: global-buffer-overflow
// CHECK: #0{{.*}} in {{_?}}QsortCallback
// CHECK: is located 0 bytes to the right of global variable 'global_array

Allow leading underscore in function name to please output tests on Mac


// RUN: %clangxx_tsan %s -o %t
// RUN: %run %t 2>&1 | FileCheck %s --implicit-check-not='ThreadSanitizer'

#include <dispatch/dispatch.h>

#import <memory>
#import <stdatomic.h>

_Atomic(long) destructor_counter = 0;

struct MyStruct {
  virtual ~MyStruct() {
    usleep(10000);
    atomic_fetch_add_explicit(&destructor_counter, 1, memory_order_relaxed);
  }
};

int main(int argc, const char *argv[]) {
  fprintf(stderr, "Hello world.\n");

  dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
  dispatch_group_t g = dispatch_group_create();

  for (int i = 0; i < 100; i++) {
    std::shared_ptr<MyStruct> shared(new MyStruct());

    dispatch_group_async(g, q, ^{
      shared.get(); // just to make sure the object is captured by the block
    });
  }

  dispatch_group_wait(g, DISPATCH_TIME_FOREVER);

  if (destructor_counter != 100) {
    abort();
  }

  fprintf(stderr, "Done.\n");
}

// CHECK: Hello world.
// CHECK: Done.

// RUN: %clangxx_tsan %s %link_libcxx_tsan -o %t
// RUN: %run %t 2>&1 | FileCheck %s --implicit-check-not='ThreadSanitizer'

#include <dispatch/dispatch.h>

#include <memory>
#include <stdatomic.h>
#include <cstdio>

_Atomic(long) destructor_counter = 0;

struct MyStruct {
  virtual ~MyStruct() {
    usleep(10000);
    atomic_fetch_add_explicit(&destructor_counter, 1, memory_order_relaxed);
  }
};

int main(int argc, const char *argv[]) {
  fprintf(stderr, "Hello world.\n");

  dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
  dispatch_group_t g = dispatch_group_create();

  for (int i = 0; i < 100; i++) {
    std::shared_ptr<MyStruct> shared(new MyStruct());

    dispatch_group_async(g, q, ^{
      shared.get(); // just to make sure the object is captured by the block
    });
  }

  dispatch_group_wait(g, DISPATCH_TIME_FOREVER);

  if (destructor_counter != 100) {
    abort();
  }

  fprintf(stderr, "Done.\n");
}

// CHECK: Hello world.
// CHECK: Done.

Make test work on Linux


#include <map>
#include <string>

#include <boost/assign/list_of.hpp>

#include <AlpinoCorpus/CorpusInfo.hh>

namespace alpinocorpus {

CorpusInfo const ALPINO_CORPUS_INFO(
    boost::assign::list_of("node"),
    "node",
    "word");

CorpusInfo const TUEBA_DZ_CORPUS_INFO(
    boost::assign::list_of("node")("ne")("word"),
    "word",
    "form");

std::map<std::string, CorpusInfo> const PREDEFINED_CORPORA =
    boost::assign::map_list_of
      ("alpino_ds", ALPINO_CORPUS_INFO)
      ("tueba_tree", TUEBA_DZ_CORPUS_INFO);

CorpusInfo const FALLBACK_CORPUS_INFO = ALPINO_CORPUS_INFO;

CorpusInfo predefinedCorpusOrFallback(std::string const &type)
{
    std::map<std::string, CorpusInfo>::const_iterator iter =
        alpinocorpus::PREDEFINED_CORPORA.find(type);
    if (iter != alpinocorpus::PREDEFINED_CORPORA.end())
        return iter->second;

    return alpinocorpus::FALLBACK_CORPUS_INFO;
}

}

#include <map>
#include <string>

#include <boost/assign/list_of.hpp>

#include <AlpinoCorpus/CorpusInfo.hh>

namespace alpinocorpus {

CorpusInfo const ALPINO_CORPUS_INFO(
    boost::assign::list_of("node"),
    "node",
    "word");

CorpusInfo const TUEBA_DZ_CORPUS_INFO(
    boost::assign::list_of("node")("ne")("word"),
    "word",
    "form");

CorpusInfo const CONLLX_CORPUS_INFO(
    boost::assign::list_of("word"),
    "word",
    "form");

std::map<std::string, CorpusInfo> const PREDEFINED_CORPORA =
    boost::assign::map_list_of
      ("alpino_ds", ALPINO_CORPUS_INFO)
      ("tueba_tree", TUEBA_DZ_CORPUS_INFO)
      ("conllx_ds", CONLLX_CORPUS_INFO);

CorpusInfo const FALLBACK_CORPUS_INFO = ALPINO_CORPUS_INFO;

CorpusInfo predefinedCorpusOrFallback(std::string const &type)
{
    std::map<std::string, CorpusInfo>::const_iterator iter =
        alpinocorpus::PREDEFINED_CORPORA.find(type);
    if (iter != alpinocorpus::PREDEFINED_CORPORA.end())
        return iter->second;

    return alpinocorpus::FALLBACK_CORPUS_INFO;
}

}

Add corpus info for conllx_ds.


// ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2014 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //

#include <QtTest>
#include <DO/Graphics/DerivedQObjects/OpenGLWindow.hpp>

using namespace DO;

class TestOpenGLWindow: public QObject
{
  Q_OBJECT
private slots:
  void test_OpenGLWindow_construction()
  {
    int width = 50;
    int height = 50;
    QString windowName = "painting window";
    int x = 200;
    int y = 300;

    OpenGLWindow *window = new OpenGLWindow(width, height,
                                            windowName,
                                            x, y);

  }

};

QTEST_MAIN(TestOpenGLWindow)
#include "test_opengl_window.moc"

// ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2014 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //

#include <QtTest>
#include <DO/Graphics/DerivedQObjects/OpenGLWindow.hpp>

using namespace DO;

class TestOpenGLWindow: public QObject
{
  Q_OBJECT
private slots:
  void test_OpenGLWindow_construction()
  {
    int width = 50;
    int height = 50;
    QString windowName = "painting window";
    int x = 200;
    int y = 300;

    OpenGLWindow *window = new OpenGLWindow(width, height,
                                            windowName,
                                            x, y);

    delete window;
  }

};

QTEST_MAIN(TestOpenGLWindow)
#include "test_opengl_window.moc"

Destroy window at the end of the test case.


#include "../include/Common.h"
#include "../include/StoreGreetings.h"

#include <random>
#include <string>

std::string random_greeting() {
    std::random_device rand;
    std::default_random_engine rand_eng(rand());
    std::uniform_int_distribution<int> uniform_dist(0, STORE_GREETINGS.size());
    size_t index = uniform_dist(rand_eng);
    return STORE_GREETINGS[index];
}

#include "../include/Common.h"
#include "../include/StoreGreetings.h"

#include <random>
#include <string>

std::string random_greeting() {
    std::random_device rand;
    std::default_random_engine rand_eng(rand());
    std::uniform_int_distribution<int> uniform_dist(0, STORE_GREETINGS.size()-1);
    size_t index = uniform_dist(rand_eng);
    return STORE_GREETINGS[index];
}

Fix index range for random shop message


#include <mart-netlib/unix.hpp>

#include <mart-common/PrintWrappers.h>

#include <catch2/catch.hpp>

#include <filesystem>
#include <iostream>

TEST_CASE( "unix_domain_socket_simple_member_check1", "[.][net][unix_domain_socket]" )
{

	mart::nw::un::Socket sock1;
	mart::nw::un::Socket sock2(                    //
		mart::ConstString( "./__tmp__/sock2.local" ), //
		mart::ConstString( "./__tmp__/sock2.remote" ) //
	);
}

#include <mart-netlib/unix.hpp>

#include <mart-common/PrintWrappers.h>

#include <catch2/catch.hpp>

#include <filesystem>
#include <iostream>

TEST_CASE( "unix_domain_socket_simple_member_check1", "[.][net][unix_domain_socket]" )
{

	mart::nw::un::Socket sock1;
	mart::nw::un::Socket sock2(                    //
		mart::ConstString( "sock.local" ), //
		mart::ConstString( "sock.remote" ) //
	);
}

Use more suitable path for unix domain sockets in testcode


#include "mini_stdint.h"

#define WEAK __attribute__((weak))

extern "C" {

extern int __android_log_vprint(int, const char *, const char *, __builtin_va_list);

WEAK int halide_printf(void *user_context, const char * fmt, ...) {
    __builtin_va_list args;
    __builtin_va_start(args,fmt);
    int result = __android_log_vprint(7, "halide", fmt, args);
    __builtin_va_end(args);
    return result;
}

}

#include "mini_stdint.h"

#define WEAK __attribute__((weak))

extern "C" {

extern int __android_log_vprint(int, const char *, const char *, __builtin_va_list);

#define ANDROID_LOG_INFO 4

WEAK int halide_printf(void *user_context, const char * fmt, ...) {
    __builtin_va_list args;
    __builtin_va_start(args,fmt);
    int result = __android_log_vprint(ANDROID_LOG_INFO, "halide", fmt, args);
    __builtin_va_end(args);
    return result;
}

}

Make halide_printf output to LOG_INFO, not LOG_FATAL


// RUN: %clang_cc1 -std=c++1z %s -emit-llvm -o - | FileCheck %s

template<typename T> struct A {
  A(T = 0);
  A(void*);
};

template<typename T> A(T*) -> A<long>;
A() -> A<int>;

// CHECK-LABEL: @_Z1fPi(
void f(int *p) {
  // CHECK: @_ZN1AIiEC
  A a{};

  // CHECK: @_ZN1AIlEC
  A b = p;

  // CHECK: @_ZN1AIxEC
  A c = 123LL;
}

// RUN: %clang_cc1 -std=c++1z %s -triple %itanium_abi_triple -emit-llvm -o - | FileCheck %s

template<typename T> struct A {
  A(T = 0);
  A(void*);
};

template<typename T> A(T*) -> A<long>;
A() -> A<int>;

// CHECK-LABEL: @_Z1fPi(
void f(int *p) {
  // CHECK: @_ZN1AIiEC
  A a{};

  // CHECK: @_ZN1AIlEC
  A b = p;

  // CHECK: @_ZN1AIxEC
  A c = 123LL;
}

Add a triple to codegen test.


#include "catch.hpp"

#include "Interpreter.hpp"

TEST_CASE("Allocation", "Make sure we can allocate a scheme interpreter")
{
  script::Interpreter eval;
}

#include "catch.hpp"

#include "Interpreter.hpp"

TEST_CASE("Allocation", "Make sure we can allocate a scheme interpreter")
{
  script::Interpreter eval;
  REQUIRE(eval.isValid() == true);
}

Make sure our interpreter is valid after construction.


#include <map>
#include <ncurses.h>
#include <string>
#include <typeinfo>
#include <vector>

#include "configuration.hh"
#include "file_contents.hh"
#include "key_listeners.hh"
#include "show_message.hh"
#include "hooks.hh"

void loop() {
    add_listeners();
    add_hook(Hook::REFRESH,hook_show_message);

    while(true) {
        char ch(getch());
        clear_message();
        if(!get_contents()->m(ch)) {
            show_message((std::string("Didn't recognize key press: ")
                          + ch).c_str());
        }
    }
}

#include <map>
#include <ncurses.h>
#include <string>
#include <typeinfo>
#include <vector>

#include "configuration.hh"
#include "file_contents.hh"
#include "key_listeners.hh"
#include "show_message.hh"
#include "hooks.hh"
#include "to_str.hh"

void loop() {
    add_listeners();
    add_hook(Hook::REFRESH,hook_show_message);

    while(true) {
        char ch = getch();
        clear_message();
        if(!get_contents()->m(ch)) {
            show_message((std::string("Didn't recognize key press: ")
                          + ch).c_str());
        } else {
            show_message((std::string("x,y: (")
                          + int_to_str(get_contents()->x) + ','
                          + int_to_str(get_contents()->y) + ')').c_str());
        }
        get_contents()->refreshmaxyx();
        print_contents(get_contents());
    }
}

Fix ``loop'' as that refresh entire screen every keypress


#include <gtest/gtest.h>
#include <gmock/gmock-matchers.h>

#include "rendering/renderablezindexcomparer.hpp"

#include "__mocks__/rendering/renderablemock.hpp"

using testing::ElementsAre;

TEST(RenderableZIndexComparer_Compare, If_first_z_index_is_less_than_second_z_index_Then_true_is_returned)
{
	qrw::RenderableZIndexComparer comparer;

	RenderableMock a(0);
	a.setZIndex(12);

	RenderableMock b(0);
	b.setZIndex(13);

	ASSERT_TRUE(comparer(&a, &b));
	ASSERT_FALSE(comparer(&b, &a));
}

TEST(RenderableZIndexComparer_Compare, Is_compatible_to_std_sort)
{
	// Arrange
	qrw::RenderableZIndexComparer comparer;

	RenderableMock a(0);
	a.setZIndex(12);

	RenderableMock b(0);
	b.setZIndex(13);

	RenderableMock c(0);
	c.setZIndex(14);

	std::vector<qrw::Renderable*> renderables = {&b, &c, &a};

	// Act
	std::sort(renderables.begin(), renderables.end(), comparer);

	// Assert
	ASSERT_THAT(renderables, ElementsAre(&a, &b, &c));
}

#include <gtest/gtest.h>
#include <gmock/gmock-matchers.h>

#include "rendering/renderablezindexcomparer.hpp"

#include "__mocks__/rendering/renderablemock.hpp"

using ::testing::ElementsAre;

TEST(RenderableZIndexComparer_Compare, If_first_z_index_is_less_than_second_z_index_Then_true_is_returned)
{
	qrw::RenderableZIndexComparer comparer;

	RenderableMock a(0);
	a.setZIndex(12);

	RenderableMock b(0);
	b.setZIndex(13);

	ASSERT_TRUE(comparer(&a, &b));
	ASSERT_FALSE(comparer(&b, &a));
}

TEST(RenderableZIndexComparer_Compare, Is_compatible_to_std_sort)
{
	// Arrange
	qrw::RenderableZIndexComparer comparer;

	RenderableMock a(0);
	a.setZIndex(12);

	RenderableMock b(0);
	b.setZIndex(13);

	RenderableMock c(0);
	c.setZIndex(14);

	std::vector<qrw::Renderable*> renderables = {&b, &c, &a};

	// Act
	std::sort(renderables.begin(), renderables.end(), comparer);

	// Assert
	ASSERT_THAT(renderables, ElementsAre(&a, &b, &c));
}

Fix broken build on ci


#include "coincontroltreewidget.h"
#include "coincontroldialog.h"

CoinControlTreeWidget::CoinControlTreeWidget(QWidget *parent) :
    QTreeWidget(parent)
{

}

void CoinControlTreeWidget::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Space) // press spacebar -> select checkbox
    {
        event->ignore();
        int COLUMN_CHECKBOX = 0;
        this->currentItem()->setCheckState(COLUMN_CHECKBOX, ((this->currentItem()->checkState(COLUMN_CHECKBOX) == Qt::Checked) ? Qt::Unchecked : Qt::Checked));
    }
    else if (event->key() == Qt::Key_Escape) // press esc -> close dialog
    {
        event->ignore();
        CoinControlDialog *coinControlDialog = (CoinControlDialog*)this->parentWidget();
        coinControlDialog->done(QDialog::Accepted);
    }
    else
    {
        this->QTreeWidget::keyPressEvent(event);
    }
}

#include "coincontroltreewidget.h"
#include "coincontroldialog.h"

CoinControlTreeWidget::CoinControlTreeWidget(QWidget *parent) :
    QTreeWidget(parent)
{

}

void CoinControlTreeWidget::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Space) // press spacebar -> select checkbox
    {
        event->ignore();
        int COLUMN_CHECKBOX = 0;
        if(this->currentItem())
            this->currentItem()->setCheckState(COLUMN_CHECKBOX, ((this->currentItem()->checkState(COLUMN_CHECKBOX) == Qt::Checked) ? Qt::Unchecked : Qt::Checked));
    }
    else if (event->key() == Qt::Key_Escape) // press esc -> close dialog
    {
        event->ignore();
        CoinControlDialog *coinControlDialog = (CoinControlDialog*)this->parentWidget();
        coinControlDialog->done(QDialog::Accepted);
    }
    else
    {
        this->QTreeWidget::keyPressEvent(event);
    }
}

Fix crash: CoinControl "space" bug


#include <vector>

#include "proc-service.h"

// Stub out run_child_proc function, for testing purposes.

void base_process_service::run_child_proc(const char * const *args, const char *working_dir,
        const char *logfile, bool on_console, int wpipefd, int csfd, int socket_fd,
        int notify_fd, int forced_notify_fd, const char * notify_var, uid_t uid, gid_t gid,
        const std::vector<service_rlimits> &rlimits) noexcept
{

}

#include <vector>

#include "proc-service.h"

// Stub out run_child_proc function, for testing purposes.

void base_process_service::run_child_proc(run_proc_params params) noexcept
{

}

Fix test stub for run_child_proc.


// This is the main function for the NATIVE version of this project.

#include <iostream>

#include "../QSWorld.h"

int main()
{
  std::cout << "Hello World!" << std::endl;
  QSWorld world;
}

// This is the main function for the NATIVE version of this project.

#include <iostream>

#include "../QSWorld.h"

int main()
{
  std::cout << "Hello World!" << std::endl;
  QSWorld world(20, 20, 5);

  for (size_t ud = 0; ud < 100; ud++) {
    world.Update();
  }
  world.Print();
}

Build native QSWorld and run it for 100 updates; no muts yet.


#include "adalgluggi.h"
#include "ui_adalgluggi.h"

#include <QDebug>
adalgluggi::adalgluggi(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::adalgluggi)
{
    ui->setupUi(this);
}

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

void adalgluggi::on_velar_clicked()
{
    qDebug () << "Vélar hnappur clicked";
}

void adalgluggi::on_folk_clicked()
{
    qDebug () << "Folk hnappur clicked";
}

void adalgluggi::on_haetta_clicked()
{

}

#include "adalgluggi.h"
#include "ui_adalgluggi.h"

#include <QDebug>
adalgluggi::adalgluggi(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::adalgluggi)
{
    ui->setupUi(this);
}

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

void adalgluggi::on_velar_clicked()
{
    qDebug () << "Vélar hnappur clicked";
}

void adalgluggi::on_folk_clicked()
{
    qDebug () << "Folk hnappur clicked";
}

void adalgluggi::on_haetta_clicked()
{
    vector<tolvufolk> folk = _fService.getTolvufolk();
    qDebug () << folk.size();
}

Test kóði í hætta hnapp


/* Copyright (c) 2013-2019 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 "RotatedHeaderView.h"

#include <QPainter>

using namespace QGBA;

RotatedHeaderView::RotatedHeaderView(Qt::Orientation orientation, QWidget* parent)
	: QHeaderView(orientation, parent)
{
}

void RotatedHeaderView::paintSection(QPainter* painter, const QRect& rect, int logicalIndex) const {
	painter->save();
	painter->translate(rect.x() + rect.width(), rect.y());
	painter->rotate(90);
	QHeaderView::paintSection(painter, QRect(0, 0, rect.height(), rect.width()), logicalIndex);
	painter->restore();
}

QSize RotatedHeaderView::sectionSizeFromContents(int logicalIndex) const {
	return QHeaderView::sectionSizeFromContents(logicalIndex).transposed();
}

/* Copyright (c) 2013-2019 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 "RotatedHeaderView.h"

#include <QPainter>

using namespace QGBA;

RotatedHeaderView::RotatedHeaderView(Qt::Orientation orientation, QWidget* parent)
	: QHeaderView(orientation, parent)
{
	int margin = 2 * style()->pixelMetric(QStyle::PM_HeaderMargin, 0, this);
	setMinimumSectionSize(fontMetrics().height() + margin);
}

void RotatedHeaderView::paintSection(QPainter* painter, const QRect& rect, int logicalIndex) const {
	painter->save();
	painter->translate(rect.x() + rect.width(), rect.y());
	painter->rotate(90);
	QHeaderView::paintSection(painter, QRect(0, 0, rect.height(), rect.width()), logicalIndex);
	painter->restore();
}

QSize RotatedHeaderView::sectionSizeFromContents(int logicalIndex) const {
	return QHeaderView::sectionSizeFromContents(logicalIndex).transposed();
}

Fix logging config section width


#include "Halide.h"
#include <stdint.h>
#include <stdio.h>
#include <cmath>

using namespace Halide;

// FIXME: Why aren't we using a unit test framework for this?
// See Issue #898
void h_assert(bool condition, const char* msg) {
    if (!condition) {
        printf("FAIL: %s\n", msg);
        abort();
    }
}

int main() {
    // Number is larger than can be represented in half and won't be rounded
    // down to the largest representable value in half(65504).  but should be
    // representable in single precision
    const int32_t largeNum = 65536;
    h_assert(!std::isnan(largeNum), "largeNum should not be NaN");
    h_assert(!std::isinf(largeNum), "largeNum should not be inf");

    // This should fail as it triggers overflow
    float16_t fail = float16_t::make_from_signed_int(largeNum, RoundingMode::ToNearestTiesToEven);

    // Supress -Wunused-but-set-variable
    fail.is_infinity();

    printf("Should not be reached!\n");
    return 0;
}

#include "Halide.h"
#include <stdint.h>
#include <stdio.h>
#include <cmath>

using namespace Halide;

// FIXME: Why aren't we using a unit test framework for this?
// See Issue #898
void h_assert(bool condition, const char* msg) {
    if (!condition) {
        printf("FAIL: %s\n", msg);
        abort();
    }
}

int main() {
    // Number is larger than can be represented in half and won't be rounded
    // down to the largest representable value in half(65504).  but should be
    // representable in single precision
    const int32_t largeNum = 65536;

    // This should fail as it triggers overflow
    float16_t fail = float16_t::make_from_signed_int(largeNum, RoundingMode::ToNearestTiesToEven);

    // Supress -Wunused-but-set-variable
    fail.is_infinity();

    printf("Should not be reached!\n");
    return 0;
}

Remove isnan of an int


#include <shogun/base/init.h>
#include <shogun/lib/common.h>
#include <shogun/lib/GCArray.h>
#include <shogun/kernel/Kernel.h>
#include <shogun/kernel/GaussianKernel.h>

#include <stdio.h>

using namespace shogun;

const int l=10;

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

	// create array of kernels
	CGCArray<CKernel*> kernels(l);

	// fill array with kernels
	for (int i=0; i<l; i++)
		kernels.set(new CGaussianKernel(10, 1.0), i);

	// print kernels
	for (int i=0; i<l; i++)
	{
		CKernel* kernel = kernels.get(i);
		printf("kernels[%d]=%p\n", i, kernel);
		SG_UNREF(kernel);
	}

	exit_shogun();

	return 0;
}

#include <shogun/base/init.h>
#include <shogun/lib/common.h>
#include <shogun/lib/GCArray.h>
#include <shogun/kernel/Kernel.h>
#include <shogun/kernel/GaussianKernel.h>

#include <stdio.h>

using namespace shogun;

const int l=10;

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

	// we need this scope, because exit_shogun() must not be called
	// before the destructor of CGCArray<CKernel*> kernels!
	{
		// create array of kernels
		CGCArray<CKernel*> kernels(l);

		// fill array with kernels
		for (int i=0; i<l; i++)
			kernels.set(new CGaussianKernel(10, 1.0), i);

		// print kernels
		for (int i=0; i<l; i++)
		{
			CKernel* kernel = kernels.get(i);
			printf("kernels[%d]=%p\n", i, kernel);
			SG_UNREF(kernel);
		}

	}

	exit_shogun();

	return 0;
}

Fix libshogun example (preventing segfault when shogun_exit() is called before kernel objects are destroyed)