/**
 * @file TestDistField.cpp
 * @brief Unit test of DistField class
 * @author cromod
 * @date september 2015
 */

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE TestDistField
#include <boost/test/unit_test.hpp>
#include <iostream>
#include "DistField.hpp"
#include "Exception.hpp"

using namespace Cromod::GeomAPI ;
using namespace Cromod::FieldAPI ;
using namespace Cromod::Tools ;
using namespace std ;

BOOST_AUTO_TEST_CASE( BasicTests )
{
    cout << "<<< Starting TestDistField >>>" << endl;

    cout << "- Default constructor test" << endl;
    try {
        DistField distfield;
    }
    catch(...) {
        BOOST_FAIL("Default constructor failure");
    }

    cout << "- Copy constructor test" << endl;
    DistField distfield;
    try {
        DistField new_distfield(distfield);
    }
    catch(...) {
        BOOST_FAIL("Copy constructor failure");
    }

    cout << "- Constructor test" << endl;
    Mesh mesh;
    try {
        DistField new_distfield(mesh);
    }
    catch(...) {
        BOOST_FAIL("Constructor failure");
    }

}

BOOST_AUTO_TEST_CASE( MethodTests )
{
    double listVal[13][2] = {{200.,-100.},{200.,50.},{150.,100.},{100.,100.},{100.,200.},{-100.,200.},{-100.,100.},
                                         {-200.,100.},{-200.,-100.},{-100.,-100.},{-100.,-200.},{100.,-200.},{100.,-100.}};
    vector<Point> listPoints;
    for(int i=0; i<13; i++) {
        Point point(listVal[i],2);
        listPoints.push_back(point);
    }
    Polygon polygon(listPoints);

    Mesh mesh;
    mesh.setPolygon(polygon);
    mesh.setStep(10.);
    mesh.setInitGrid();
    mesh.detectNode();

    double ptA[] = {200.,50.};
    double ptB[] = {150.,100.};
    Point pointA(ptA,2);
    Point pointB(ptB,2);
    Segment segment(pointA,pointB);

    DistField distfield(mesh);
    cout << "- setBoundaryCondition test" << endl;
    distfield.setBoundaryCondition(segment);
    cout << "- initialize test" << endl;
    distfield.initialize();
    cout << "- compute test" << endl;
    distfield.compute();
    cout << "- interpolate test" << endl;
    cout << "  distance = " << distfield.interpolate(75.,75.) << endl;

    cout << "<<< End of TestDistField >>>" << endl;
}

Add unit test of DistField class


#include <iostream>
#include <cmath>

using namespace std;

int main() {
    cout << uppercase << hexfloat;
    cout << sqrt(2) << endl;
    return 0;
}

Add solution for chapter 17 test 35


class Solution {
public:
    bool areAlmostEqual(string s1, string s2) {
        size_t index = 0, count = 0;
        std::vector<size_t> arr;
        while (index < s1.size()) {
            if (s1[index] != s2[index]) {
                ++count;
                if (count > 2)
                    return false;
                arr.emplace_back(index);
            }
            ++index;
        }
        if (count == 0)
            return true;
        if (count == 1)
            return false;
        if (s1[arr[0]] == s2[arr[1]] && s1[arr[1]] == s2[arr[0]])
            return true;
        return false;
    }
};

Check if One String Swap Can Make Strings Equal


//------------------------------------------------------------------------------
//  Clock.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include "Clock.h"
#if ORYOL_EMSCRIPTEN
#include <emscripten/emscripten.h>
#else
#include <chrono>
#endif

namespace Oryol {
namespace Time {

//------------------------------------------------------------------------------
TimePoint
Clock::Now() {
    #if ORYOL_EMSCRIPTEN
    // get int64 time in nanosecs (emscripten_now is ms)
    int64 t = int64(emscripten_get_now() * 1000 * 1000);
    #else
    using namespace std;
    chrono::time_point<chrono::high_resolution_clock, chrono::nanoseconds> now = chrono::high_resolution_clock::now();
    int64 t = now.time_since_epoch().count();
    #endif
    return TimePoint(t);
}

} // namespace Clock
} // namespace Oryol

//------------------------------------------------------------------------------
//  Clock.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include "Clock.h"
#if ORYOL_EMSCRIPTEN
#include <emscripten/emscripten.h>
#elif ORYOL_WINDOWS
#include <Windows.h>
#include <atomic>
#else
#include <chrono>
#endif

namespace Oryol {
namespace Time {

//------------------------------------------------------------------------------
TimePoint
Clock::Now() {
    #if ORYOL_EMSCRIPTEN
    // get int64 time in nanosecs (emscripten_now is ms)
    int64 t = int64(emscripten_get_now() * 1000 * 1000);
    #elif ORYOL_WINDOWS
    // VisualStudio2013's chrono::high_resolution_clock isn't actually high_resolution
    LARGE_INTEGER perfCount;
    static LARGE_INTEGER perfFreq;
    static std::atomic_flag perfFreqValid{ false };
    if (!perfFreqValid.test_and_set())
    {
        QueryPerformanceFrequency(&perfFreq);
    }
    QueryPerformanceCounter(&perfCount);
    int64 t = (perfCount.QuadPart * 1000000000) / perfFreq.QuadPart;
    #else
    using namespace std;
    chrono::time_point<chrono::high_resolution_clock, chrono::nanoseconds> now = chrono::high_resolution_clock::now();
    int64 t = now.time_since_epoch().count();
    #endif
    return TimePoint(t);
}

} // namespace Clock
} // namespace Oryol

Use QueryPerformanceCounter on Windows instead of std::chrono::high_frequency_clock, since this has only 1ms accuracy in VS2013


// RUN: %clang_cc1 -verify -Wunused -Wused-but-marked-unused -fsyntax-only %s

namespace ns_unused { typedef int Int_unused __attribute__((unused)); }
namespace ns_not_unused { typedef int Int_not_unused; }

void f() {
  ns_not_unused::Int_not_unused i1; // expected-warning {{unused variable}}
  ns_unused::Int_unused i0; // expected-warning {{'Int_unused' was marked unused but was used}}
}

Add missing test from r163874.


// 237. Delete Node in a Linked List
/**
 * Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
 *
 * Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4
 * after calling your function.
 *
 * Tags: Linked List
 *
 * Similar Problems: (E) Remove Linked List Elements
 *
 * Author: Kuang Qin
 */

#include <iostream>

using namespace std;

/**
 * Definition for singly-linked list.
 */
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
    ListNode(int x, ListNode *p) : val(x), next(p) {}
};

class Solution {
public:
    void deleteNode(ListNode* node) {
        *node = *(node->next);

        // equivalent to copy the values:
        // node->val = node->next->val;
        // node->next = node->next->next;
        return;
    }
};

int main() {
    ListNode node5(5), node4(4, &node5), node3(3, &node4), node2(2, &node3), node1(1, &node2);
    Solution sol;
    sol.deleteNode(&node3);
    for (ListNode *p = &node1; p != NULL; p = p->next) {
        cout << p->val << " ";
    }
    cout << endl;
    cin.get();

    return 0;
}

Add Solution for 237 Delete Node in a Linked List


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

#define private public
#include "../../JPetTaskLoader/JPetTaskLoader.h"

BOOST_AUTO_TEST_SUITE(FirstSuite)

BOOST_AUTO_TEST_CASE( my_test1 )
{
  BOOST_REQUIRE(1==0);
}

BOOST_AUTO_TEST_SUITE_END()

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

#define private public
#include "../../JPetTaskLoader/JPetTaskLoader.h"

BOOST_AUTO_TEST_SUITE(FirstSuite)

BOOST_AUTO_TEST_CASE(defaultConstrutocTest)
{
    /*JPetOptions::Options options = {
      {"inputFile", "data_files/cosm_barrel.hld.root"},
      {"inputFileType", "hld"},
      {"outputFile", "data_files/cosm_barrel.tslot.raw.out.root"},
      {"outputFileType", "tslot.raw"},
      {"firstEvent", "1"},
      {"lastEvent", "10"},
      {"progressBar", "false"}
    };

    JPetTaskLoader taskLoader;
    taskLoader.init(options);*/
}

BOOST_AUTO_TEST_SUITE_END()

Change unit test for JPetTaskLoader.


#include "Halide.h"

using namespace Halide;
using namespace Halide::Internal;

int main() {
    Var x("x"), y("y");
    Func f("f"), g("g"), h("h");
    f(x, y) = x + y;
    g(x, y) = 5;
    h(x, y) = f(x, y) + g(x, y);

    f.compute_root();
    f.in(g).compute_root();

    // This should cause an error since f.in(g) was called but 'f' is
    // never used in 'g'.
    h.realize(5, 5);

    return 0;
}

Add error test for func wrapper


// Copyright 2012-2013 Samplecount S.L.
//
// 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.

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-private-field"
#define CATCH_CONFIG_MAIN
#include <catch.hpp>
#pragma GCC diagnostic pop

#include "Methcla/Utility/MessageQueue.hpp"
#include "Methcla/Utility/Semaphore.hpp"

#include <atomic>

TEST_CASE("Methcla/Utility/Worker", "Check for queue overflow.")
{
    struct Command
    {
        void perform() { }
    };

    const size_t queueSize = 1024;

    Methcla::Utility::Worker<Command> worker(queueSize);

    for (size_t i=0; i < worker.maxCapacity(); i++) {
        worker.sendToWorker(Command());
    }

    REQUIRE_THROWS(worker.sendToWorker(Command()));
}

TEST_CASE("Methcla/Utility/WorkerThread", "Check that all commands pushed to a worker thread are executed.")
{
    struct Command
    {
        void perform()
        {
            (*m_count)++;
            m_sem->post();
        }

        std::atomic<size_t>* m_count;
        Methcla::Utility::Semaphore* m_sem;
    };

    const size_t queueSize = 1024;

    for (size_t threadCount=1; threadCount <= 4; threadCount++) {
        Methcla::Utility::WorkerThread<Command> worker(queueSize, threadCount);

        std::atomic<size_t> count(0);
        Methcla::Utility::Semaphore sem;

        for (size_t i=0; i < worker.maxCapacity(); i++) {
            Command cmd;
            cmd.m_count = &count;
            cmd.m_sem = &sem;
            worker.sendToWorker(cmd);
        }

        for (size_t i=0; i < worker.maxCapacity(); i++) {
            sem.wait();
        }
        REQUIRE(count.load() == worker.maxCapacity());
    }
}

Add some tests for worker thread implementation


#include <iostream>
#include <cstring>
#define MODULO 1000000007
#define MAX 1001
using namespace std;

long long mod_add(long long x, long long y)
{
	return (x + y) % MODULO;
}

long long mod_sub(long long x, long long y)
{
	return (x - y + MODULO) % MODULO;
}

long long mod_mult(long long x, long long y)
{
	return (x * y) % MODULO;
}

long long solve(int n, int  m)
{
	long long single_row[MAX];
	memset(single_row, 0, sizeof(single_row));
	single_row[1] = 1;
	single_row[2] = 2;
	single_row[3] = 4;
	single_row[4] = 8;
	for (int i = 5; i <= m; i++) {
		for (int j = 1; j <= 4; j++) {
			single_row[i] = mod_add(single_row[i], single_row[i - j]);
		}
	}
	long long raw_result[MAX];
	for (int i = 1; i <= m; i++) {
		long long res = 1;
		for (int j = 1; j <= n; j++) {
			res = mod_mult(res, single_row[i]);
		}
		raw_result[i] = res;
	}
	long long result_with_holes[MAX];
	long long final_result[MAX];
	final_result[1] = raw_result[1];
	for (int i = 2; i <= m; i++) {
		final_result[i] = raw_result[i];
		for (int j = 1; j <= i - 1; j++) {
			final_result[i] = mod_sub(final_result[i], mod_mult(final_result[j], raw_result[i - j]));
		}
	}
	return final_result[m];
}

int main()
{
	int T;
	cin >> T;
	while (T--) {
		int n, m;
		cin >> n >> m;
		cout << solve(n, m) << endl;
	}
	return 0;
}

Add the solution to "Lego Blocks".


// Chapter 27, exercise 8: write out every character on your keyboard together
// with its integer value; then, write the characters out in the order deter-
// mined by their integer value

#include<iostream>
#include<string>
#include<algorithm>

using namespace std;

void print(const string& s)
{
    for (int i = 0; i<s.size(); ++i)
        cout << '\'' << s[i] << "\': " << (int)unsigned char(s[i]) << '\n';
}

bool comp_char(char a, char b)
{
    return unsigned char(a) < unsigned char(b);
}

int main()
{
    string s = R"(+"*%&/()=?`1234567890'^@#|~![]${}><\;:_,.-)";
    s += "QWERTZUIOPASDFGHJKLYXCVBNMqwertzuiopasdfghjklyxcvbnm";
    print(s);
    sort(s.begin(),s.end(),comp_char);
    cout << "\nAnd sorted:\n";
    print(s);
}

Add Chapter 27, exercise 8


#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <random>

static std::random_device rd;
static std::mt19937 gen(rd());
static std::uniform_int_distribution<> dist(5, 30);
static std::uniform_int_distribution<> negator(0, 1);
static std::uniform_int_distribution<> dir(1, 15);

struct animal {
private:
    int answer;
public:
    animal(): answer(dist(gen)) { /*std::cout << answer << '\n';*/ }
    bool guess(int g) const {
        if(g >= answer) {
            std::cout << "Caught one!\n";
            return true;
        }
        return false;
    }
};

struct player {
private:
    const unsigned max_animals = 20;
    std::vector<animal> animals{max_animals};
    int answer = 0;
    int up = dir(gen);
    int down = dir(gen);
    int left = dir(gen);
    int right = dir(gen);
public:
    player() = default;
    void guess() {
        // get command
        std::string temp;
        std::cin >> temp;

        // update total
        if(temp == "up") {
            answer += negator(gen) ? -up : up;
        }
        else if(temp == "down") {
            answer += negator(gen) ? -down : down;
        }
        else if(temp == "right") {
            answer += negator(gen) ? -right : right;
        }
        else if(temp == "left") {
            answer += negator(gen) ? -left : left;
        }

        if(answer < 0) {
            answer = 0;
        }

        // refresh command values
        up = dir(gen);
        down = dir(gen);
        left = dir(gen);
        right = dir(gen);

        // herd the animals guessed correctly
        animals.erase(std::remove_if(std::begin(animals), std::end(animals), [this](const animal& x) {
            return x.guess(answer);
        }), std::end(animals));
    }

    void status() {
        std::cout << "[" << max_animals - animals.size() << "/" << max_animals << "] animals herded" << std::endl;
    }

    bool won() {
        return animals.empty();
    }
};

int main() {
    player p;
    std::cout << "The animals have escaped! Try to herd them using the four directions:\n";
    std::cout << "- up\n"
                 "- down\n"
                 "- left\n"
                 "- right\n";
    while(true) {
        p.guess();
        p.status();

        if(p.won()) {
            std::cout << "You win!\n";
            return 0;
        }
    }
}

Add alternative game, you know


// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -emit-llvm -o - %s | FileCheck %s

// PR6141
template<typename T>
struct X {
  X();
  template<typename U> X(X<U>);
  X(const X<T>&);
};

void f(X<int>) { }

struct Y : X<int> { };
struct Z : X<float> { };

// CHECK: define i32 @main()
int main() {
  // CHECK: call void @_ZN1YC1Ev
  // CHECK: call void @_ZN1XIiEC1ERKS0_
  // CHECK: call void @_Z1f1XIiE
  f(Y());
  // CHECK: call void @_ZN1ZC1Ev
  // CHECK: call void @_ZN1XIfEC1ERKS0_
  // CHECK: call void @_ZN1XIiEC1IfEES_IT_E
  // CHECK: call void @_Z1f1XIiE
  f(Z());
}

Add test case for PR6141, which was fixed a few days ago


#include <gtest/gtest.h>
#include "tcpserver.hpp"

using namespace OpenSofa;

namespace
{
  TEST(TCPServerTest, CanBeCreated)
  {
    Server * server = new TCPServer();
    delete server;
  }
}

Add test file for tcpserver


/*
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

#ifndef __ANDROID__
#error "This file should only be compiled for Android."
#endif

#include <jni/fbjni/References.h>
#include <jni/fbjni/CoreClasses.h>

namespace facebook {
namespace jni {
namespace internal {

static int32_t getApiLevel() {
  auto cls = findClassLocal("android/os/Build$VERSION");
  auto fld = cls->getStaticField<int32_t>("SDK_INT");
  if (fld) {
    return cls->getStaticFieldValue(fld);
  }
  return 0;
}

bool doesGetObjectRefTypeWork() {
  static auto level = getApiLevel();
  return level >= 14;
}

}
}
}

Build first-party C++ deps of OSS React Native with Buck


#include <iostream>

void foo() {
    std::cout << __PRETTY_FUNCTION__ << "\n";
    std::cout << " ";
}

template <typename Arg>
void foo(Arg arg) {
    std::cout << __PRETTY_FUNCTION__ << "\n";
    std::cout << arg << " ";
}

template <typename First, typename... Args>
void foo(First first, Args... args) {
    std::cout << __PRETTY_FUNCTION__ << "\n";
    foo(first);
    foo(args...);
}

int main() {
    std::string one = "One";
    const char* two = "Two";
    float three = 3.33333333;

    foo();
    std::cout << std::endl;

    foo(one, two);
    std::cout << std::endl;

    foo(one, two, three);
    std::cout << std::endl;

    foo(1, 2, three, 4, 5.7, 6/2, "lalalala");

    return 0;
}

Add variadic template arguments example in c++17.


//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include "catch.hpp"

#include "dll/conv_layer.hpp"
#include "dll/dense_layer.hpp"
#include "dll/conv_rbm.hpp"
#include "dll/dbn.hpp"
#include "dll/scale_layer.hpp"
#include "dll/mp_layer.hpp"
#include "dll/avgp_layer.hpp"
#include "dll/stochastic_gradient_descent.hpp"

#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"

TEST_CASE("fast/cdbn/sgd/1", "[dbn][mnist][sgd]") {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::conv_rbm_desc_square<1, 28, 10, 12, dll::momentum, dll::batch_size<10>, dll::weight_type<float>>::layer_t,
            dll::rbm_desc<12 * 12 * 10, 10, dll::momentum, dll::batch_size<10>, dll::hidden<dll::unit_type::SOFTMAX>>::layer_t>,
        dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 1, 28, 28>>(500);
    REQUIRE(!dataset.training_images.empty());

    mnist::binarize_dataset(dataset);

    auto dbn = std::make_unique<dbn_t>();

    //dbn->pretrain(dataset.training_images, 20);

    //auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 50);
    //std::cout << "ft_error:" << ft_error << std::endl;
    //CHECK(ft_error < 5e-2);

    //auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    //std::cout << "test_error:" << test_error << std::endl;
    //REQUIRE(test_error < 0.2);
}

Prepare test case for dbn_fast


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

// <list>

// template <class T, class Alloc>
//   void swap(list<T,Alloc>& x, list<T,Alloc>& y);

#if _LIBCPP_DEBUG2 >= 1
#define _LIBCPP_ASSERT(x, m) ((x) ? (void)0 : std::exit(0))
#endif

#include <list>
#include <cassert>

#include <__debug>

int main()
{
#if _LIBCPP_DEBUG2 >= 1
    {
        int a1[] = {1, 3, 7, 9, 10};
        int a2[] = {0, 2, 4, 5, 6, 8, 11};
        std::list<int> c1(a1, a1+sizeof(a1)/sizeof(a1[0]));
        std::list<int> c2(a2, a2+sizeof(a2)/sizeof(a2[0]));
        std::list<int>::iterator i1 = c1.begin();
        std::list<int>::iterator i2 = c2.begin();
        swap(c1, c2);
        c1.erase(i2);
        c2.erase(i1);
        std::list<int>::iterator j = i1;
        c1.erase(i1);
        assert(false);
    }
#endif
}

Fix bug in __libcpp_db::__iterator_copy. Add debug test for swaping lists.


#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 + 1) {
            debug("Dropped incoming CAN message -- send queue full\r\n");
            return;
    }

    for(int i = 0; i < messageSize; i++) {
        QUEUE_PUSH(uint8_t, queue, (uint8_t)message[i]);
    }
    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 full\r\n");
            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);
    }
}

Use \r in messages so they look decent in serial output.


//=======================================================================
// Copyright Baptiste Wicht 2011-2013.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <iostream>

namespace boost {

void throw_exception(std::exception const & e){
    throw e;
}

} // namespace boost

Fix glitch with Clang and boost


#include "command.h"
#include "timer.h"

#include <ctime>
#include <unistd.h>

using namespace MR;
using namespace App;

void usage ()
{
  DESCRIPTION
    + "test timer interface";

  REQUIRES_AT_LEAST_ONE_ARGUMENT = false;
}

void run ()
{

  Timer timer;

  CONSOLE ("printing Timer::current_time() at 10ms intervals:");
  for (size_t n = 0; n < 10; ++n) {
    CONSOLE ("  current timestamp: " + str(Timer::current_time(), 16)
        + " (from C time(): " + str(time(NULL)) + ")");
    usleep (10000);
  }

  CONSOLE ("execution took " + str(timer.elapsed()) + " seconds");
  timer.start();

  CONSOLE ("testing IntervalTimer with 10 x 0.2s intervals:");
  IntervalTimer itimer (0.2);
  for (size_t n = 0; n < 10; ++n) {
    while (!itimer);
    CONSOLE ("  tick");
  }

  CONSOLE ("execution took " + str(timer.elapsed()) + " seconds");
}

Add command to test timer (to be deleted on next commit)


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

void choice(int);
int choice(bool);

void test() {
  // Result of ! must be type bool.
  int i = choice(!1);
}

Add missing test case for operator ! result type.


#include <iostream>
#include <random>

#define MAX_NUM_ROWS 10
#define NUM_ITERS 1000
#define BLOCK_SIZE 512 // cache line size in bits.
#define NUM_BLOCKS 10000
#define NUM_DOCS BLOCK_SIZE * NUM_BLOCKS

// DESIGN NOTE: tried using go, but the publicly available binomial rng is approximately 10x slower.
// TODO: change conventions to match BitFunnel coding conventions.

int run_once(std::mt19937& gen, std::binomial_distribution<int>& base_dist, int num_rows) {
    int num_accesses;

    // TODO: reduce int to int16_t?
    // TODO: check to see if doing these allocations inside run_once matters for performance.
    // We could hoist this out and just clear the vectors in here.
    std::vector<std::vector<int>> universe(num_rows, std::vector<int>(NUM_BLOCKS));
    for (int j = 0; j < universe[0].size(); ++j) {
        universe[0][j] = base_dist(gen);
        ++num_accesses;
    }

    for (int i = 1; i < universe.size(); ++i) {
        for (int j = 0; j < universe[0].size(); ++j) {
            if (universe[i-1][j] == 0) {
                universe[i][j] = 0;
            } else {
                ++num_accesses;
                int row_num_set = base_dist(gen);
                float previous_fraction = static_cast<float>(universe[i-1][j]) / 512.0;
                std::binomial_distribution<int> intersection_dist(row_num_set,previous_fraction);
                universe[i][j] = intersection_dist(gen);
            }
        }
    }
    return num_accesses;
}

int main()
{
    std::random_device rd;
    std::mt19937 gen(rd());
    std::binomial_distribution<int> base_dist(511, 0.2);

    for (int i = 2; i < MAX_NUM_ROWS; ++i) {
        for (int j = 0; j < NUM_ITERS; ++j) {
            std::cout << run_once(gen, base_dist, i) << ",";
        }
        std::cout << std::endl;
    }
    return 0;
}

Add initial 5-minute hack simulation script.


// Chapter 21, Exercise 6: implement the Fruit example (set) using a
// set<Fruit*,Fruit_comparison> (pointers instead of copies), i.e., define a
// comparison operation for Fruit*

#include "../lib_files/std_lib_facilities.h"
#include<set>

//------------------------------------------------------------------------------

struct Fruit {
    string name;
    int count;
    double unit_price;
    Fruit(string n, int c, double up = 0.0)
        :name(n), count(c), unit_price(up) { }
};

//------------------------------------------------------------------------------

ostream& operator<<(ostream& os, const Fruit* f)
{
    os << setw(7) << left << f->name;
    os << f->count << '\t' << f->unit_price;
    return os;
}

//------------------------------------------------------------------------------

struct Fruit_comparison {
    bool operator()(const Fruit* a, const Fruit* b) const
    {
        return a->name < b->name;
    }
};

//------------------------------------------------------------------------------

int main()
try {
    set<Fruit*,Fruit_comparison> inventory;
    inventory.insert(new Fruit("Quince",5));    // test default parameter
    inventory.insert(new Fruit("Apple",200,0.37));
    inventory.insert(new Fruit("Orange",150,0.45));
    inventory.insert(new Fruit("Grape",13,0.99));
    inventory.insert(new Fruit("Kiwi",512,1.15));
    inventory.insert(new Fruit("Plum",750,2.33));

    typedef set<Fruit*,Fruit_comparison>::const_iterator Si;
    for (Si p = inventory.begin(); p!=inventory.end(); ++p) cout << *p << '\n';

    // Clean up
    for (Si p = inventory.begin(); p!=inventory.end(); ++p) delete *p;
}
catch (Range_error& re) {
    cerr << "bad index: " << re.index << "\n";
}
catch (exception& e) {
    cerr << "exception: " << e.what() << endl;
}
catch (...) {
    cerr << "exception\n";
}

//------------------------------------------------------------------------------

Add Chapter 21, exercise 6


#include <stdio.h>

typedef struct _NODE {
  int data;
  _NODE* left;
  _NODE* right;
} NODE;

NODE* newNode(int data) {
  NODE* node = new NODE();
  node->data = data;
  node->left = nullptr;
  node->right = nullptr;

  return node;
}

void leftViewUtil(NODE* root, int level, int* max_level) {
  if (root == nullptr) return;

  printf("level : [%d] max_level : [%d] \n", level, *max_level);
  if (*max_level < level) {
    printf("%d \n", root->data);
    *max_level = level;
  }

  leftViewUtil(root->left, level + 1, max_level);
  leftViewUtil(root->right, level + 1, max_level);
}

void leftView(NODE* root) {
  int max_level = 0;
  leftViewUtil(root, 1, &max_level);
}

int main(int argc, char const* argv[]) {
  NODE* root = newNode(12);
  root->left = newNode(10);
  root->right = newNode(30);
  root->right->left = newNode(25);
  root->right->right = newNode(40);

  leftView(root);
  return 0;
}

Print Left View of the tree.


#include "base64inputstream.h"
#include <stdio.h>
using namespace jstreams;
using namespace std;

int
main(int argc, char** argv) {
   for (int i=1; i<argc; ++i) {
       string out = Base64InputStream::decode(argv[i], strlen(argv[i]));
       printf("%s\n", out.c_str());
   }
   return 0;
}

Add small test program for base64 decoding.


#include <iostream>
#include <stack>

using std::cout;
using std::endl;
using std::stack;

class Queue {
    stack<int> stackIn, stackOut;

    void transfer() {
      while (!stackIn.empty()) {
        stackOut.push(stackIn.top());
        stackIn.pop();
      }
    }
public:

    bool empty() {
      return stackIn.empty() && stackOut.empty();
    }

    int front() {
      if (stackOut.empty()) {
        transfer();
      }

      return stackOut.top();
    }

    void pop() {
      if (stackOut.empty()) {
        transfer();
      }

      stackOut.pop();
    }

    void push(int n) {
      stackIn.push(n);
    }

};

int main() {
  Queue q;

  q.push(1);
  q.push(2);

  cout << q.front() << endl;
  q.pop();

  q.push(3);

  cout << q.front() << endl;
  q.pop();

  q.push(4);
  q.push(5);
  q.push(6);

  cout << q.front() << endl;
  q.pop();

  cout << q.front() << endl;
  q.pop();

  cout << q.front() << endl;
  q.pop();

  cout << q.front() << endl;
  q.pop();

  return 0;
}

Add queue implemented with 2 stacks


// 141 Linked List Cycle
/**
* Given a linked list, determine if it has a cycle in it.
*
* Follow up:
* Can you solve it without using extra space?
*
* Tag:     Linked List, Two Pointers
*
* Author:  Yanbin Lu
*/

#include <stddef.h>
#include <vector>
#include <string.h>
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <map>

using namespace std;
struct ListNode {
     int val;
     ListNode *next;
     ListNode(int x) : val(x), next(NULL) {}
 };

class Solution {
public:
    bool hasCycle(ListNode *head) {
        ListNode* slow = head;
        ListNode* fast = head;
        while(fast && fast->next){
            fast = fast->next->next;
            slow = slow->next;
            if(fast == slow) return true;
        }
        return false;
    }
};

int main()
{
	// creat a cycle list
	ListNode* list = new ListNode(3);
	list->next = new ListNode(2);
	list->next->next = new ListNode(1);
	list->next->next->next = new ListNode(4);
	list->next->next->next->next = list;

	Solution* sol = new Solution();
	cout<<sol->hasCycle(list)<<std::endl;

	char c;
	std::cin>>c;

	return 0;
}

Add 141 Linked List Cycle


// RUN: rm -rf %T/coverage-basic
// RUN: mkdir %T/coverage-basic && cd %T/coverage-basic
// RUN: %clangxx_asan -fsanitize-coverage=1 %s -o test.exe
// RUN: env ASAN_OPTIONS=coverage=1 %run test.exe
//
// RUN: %sancov print *.sancov | FileCheck %s
#include <stdio.h>

void foo() { fprintf(stderr, "FOO\n"); }
void bar() { fprintf(stderr, "BAR\n"); }

int main(int argc, char **argv) {
  if (argc == 2) {
    foo();
    bar();
  } else {
    bar();
    foo();
  }
}

// CHECK: 0x{{[0-9a-f]*}}
// CHECK: 0x{{[0-9a-f]*}}
// CHECK: 0x{{[0-9a-f]*}}
// CHECK-NOT: 0x{{[0-9a-f]*}}

Add a test that makes sure coverage works at least in the simple cases


/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* next;
    Node* random;

    Node(int _val) {
        val = _val;
        next = NULL;
        random = NULL;
    }
};
*/

class Solution {
public:
    Node* copyRandomList(Node* head) {
        if (!head) return nullptr;
        Node* temp = head;
        while (temp) {
            Node *node = new Node(temp->val);
            node->next = temp->next;
            temp->next = node;
            temp = node->next;
        }
        temp = head;
        while (temp) {
            temp->next->random = (temp->random) ? temp->random->next : nullptr;
            temp = temp->next->next;
        }
        Node* dummy = head->next;
        temp = head->next;
        while (head) {
            head->next = temp->next;
            head = head->next;
            if (!head) break;
            temp->next = head->next;
            temp = temp->next;
        }
        return dummy;
    }
};

Copy List with Random Pointer


// 454. 4Sum II
/**
 * Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.
 *
 * To make problem a bit easier, all A, B, C, D have same length of N where 0 <= N <= 500. All integers are in the range of -2^28 to 2^28 - 1
 * and the result is guaranteed to be at most 2^31 - 1.
 *
 * Example:
 *
 * Input:
 * A = [ 1, 2]
 * B = [-2,-1]
 * C = [-1, 2]
 * D = [ 0, 2]
 *
 * Output:
 * 2
 *
 * Explanation:
 * The two tuples are:
 * 1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
 * 2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0
 *
 * Tags: Binary Search, Hash Table
 *
 * Similar Problems: (M) 4Sum
 *
 * Author: Kuang Qin
 */

#include <iostream>
#include <vector>
#include <unordered_map>

using namespace std;

class Solution {
public:
    int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
        int n = A.size();

        // only count is needed, use a hash map for faster search
        unordered_map<int, int> map;

        int sum = 0;
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                sum = -(A[i] + B[j]);
                map[sum]++; // create hash map using the -sum of A and B
            }
        }

        int res = 0;
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                sum = C[i] + D[j];
                if (map.find(sum) != map.end()) // look up in hash map using the sum of C and D
                    res += map[sum];
            }
        }

        return res;
    }
};

int main()
{
    vector<int> A = {1, 2};
    vector<int> B = {-2, -1};
    vector<int> C = {-1, 2};
    vector<int> D = {0, 2};
    Solution sol;
    int res = sol.fourSumCount(A, B, C, D);
    cout << res << endl;
    cin.get();

    return 0;
}

Add Solution for 454 4Sum II


/*
 * Copyright 2010, NagaChaitanya Vellanki
 *
 * Author NagaChaitanya Vellanki
 *
 * Print k digits of decimal representation of 1/n for n > 1
 */

#include <inttypes.h>
#include <iostream>
#include <cstdlib>

using namespace std;

int main() {
  int32_t n = 0;
  int32_t k = 1;

  cout << "Enter n(n > 1) and number of digits k (k >= 1)" << endl;
  cin >> n >> k;

  if((n <= 1) || (k < 1)) {
    exit(0);
  }

  int32_t i = 0;
  int32_t rem = 1;
  while(i < k) {
    cout << (10 * rem) / n;
    rem = (10 * rem) % n;
    i++;
  }

  return 0;
}

Add Printing k digits of 1/n


#include <iostream>
#include <cstring>

using namespace std;

class Ticket {
    int seat;
    int price;

public:

    Ticket(int _seat) : seat(_seat) {
        if (seat >= 1 && seat <= 30)
            price = 70;
        else if (seat >= 31 && seat <= 70)
            price = 55;
        else if (seat >= 71 && seat <= 100)
            price = 30;
        else if (seat >= 101 && seat <= 150)
            price = 15;
        else
            price = 0;
    }

    int getSeat() {
        return seat;
    }

    int getPrice() {
        return price;
    }

    void print() {
        cout << "Seat " << seat << " with price " << price << endl;
    }
};

class Guest {
    char name[32];
    Ticket ticket;

public:

    Guest(const char _name[], Ticket _ticket) : ticket(_ticket) {
        strcpy(name, _name);
    }

    bool receivesGift() {
        return ticket.getSeat() >= 1 && ticket.getSeat() <= 30;
    }

    void print() {
        cout << "Name: " << name << endl;
        ticket.print();
    }
};

int main() {
    Guest guests[5] = {
        Guest("Ivan", Ticket(2)),
        Guest("Ivanko", Ticket(29)),
        Guest("Georgi", Ticket(58)),
        Guest("Petar", Ticket(102)),
        Guest("Yordan", Ticket(17))
    };

    for (int i = 0; i < 5; i++)
        if (guests[i].receivesGift())
            guests[i].print();

    return 0;
}

Add sample solution to the first problem for the first test


/*
 * This test demonstrates that putting a console into selection mode does not
 * block the low-level console APIs, even though it blocks WriteFile.
 */

#define _WIN32_WINNT 0x0501
#include "../Shared/DebugClient.cc"
#include <windows.h>
#include <stdio.h>

const int SC_CONSOLE_MARK = 0xFFF2;

CALLBACK DWORD writerThread(void*)
{
  CHAR_INFO xChar, fillChar;
  memset(&xChar, 0, sizeof(xChar));
  xChar.Char.AsciiChar = 'X';
  xChar.Attributes = 7;
  memset(&fillChar, 0, sizeof(fillChar));
  fillChar.Char.AsciiChar = ' ';
  fillChar.Attributes = 7;
  COORD oneCoord = { 1, 1 };
  COORD zeroCoord = { 0, 0 };

  while (true) {
    SMALL_RECT writeRegion = { 5, 5, 5, 5 };
    WriteConsoleOutput(GetStdHandle(STD_OUTPUT_HANDLE),
                       &xChar, oneCoord,
                       zeroCoord,
                       &writeRegion);
    Sleep(500);
    SMALL_RECT scrollRect = { 1, 1, 20, 20 };
    COORD destCoord = { 0, 0 };
    ScrollConsoleScreenBuffer(GetStdHandle(STD_OUTPUT_HANDLE),
                              &scrollRect,
                              NULL,
                              destCoord,
                              &fillChar);
  }
}

int main()
{
  CreateThread(NULL, 0, writerThread, NULL, 0, NULL);
  Trace("marking console");
  HWND hwnd = GetConsoleWindow();
  PostMessage(hwnd, WM_SYSCOMMAND, SC_CONSOLE_MARK, 0);

  Sleep(2000);

  Trace("reading output");
  CHAR_INFO buf[1];
  COORD bufSize = { 1, 1 };
  COORD zeroCoord = { 0, 0 };
  SMALL_RECT readRect = { 0, 0, 0, 0 };
  ReadConsoleOutput(GetStdHandle(STD_OUTPUT_HANDLE),
		    buf,
		    bufSize,
		    zeroCoord,
		    &readRect);
  Trace("done reading output");

  Sleep(2000);

  PostMessage(hwnd, WM_CHAR, 27, 0x00010001);

  Sleep(1100);

  return 0;
}

Add another windows test case.


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

#include "base/android/jni_registrar.h"

#include "base/logging.h"
#include "base/android/jni_android.h"

namespace base {
namespace android {

bool RegisterNativeMethods(JNIEnv* env,
                           const RegistrationMethod* method,
                           size_t count) {
  const RegistrationMethod* end = method + count;
  while (method != end) {
    if (!method->func(env) < 0) {
      DLOG(ERROR) << method->name << " failed registration!";
      return false;
    }
    method++;
  }
  return true;
}

}  // namespace android
}  // namespace base

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

#include "base/android/jni_registrar.h"

#include "base/logging.h"
#include "base/android/jni_android.h"

namespace base {
namespace android {

bool RegisterNativeMethods(JNIEnv* env,
                           const RegistrationMethod* method,
                           size_t count) {
  const RegistrationMethod* end = method + count;
  while (method != end) {
    if (!method->func(env)) {
      DLOG(ERROR) << method->name << " failed registration!";
      return false;
    }
    method++;
  }
  return true;
}

}  // namespace android
}  // namespace base

Fix Android RegisterNativeMethods failure logic


#include "cell_refine.hpp"

#include <viennagrid/algorithm/refine.hpp>

/***************
 * CELL_REFINE *
 ***************/

// Triangular

tuple TriangularCartesian2D_Domain_cell_refine(TriangularCartesian2D_Domain domain_in, TriangularCartesian2D_Segmentation segmentation_in, bool (*predicate)(const TriangularCartesian2D_Cell &))
{
	TriangularCartesian2D_Domain          domain_out;
	TriangularCartesian2D_Segmentation    segmentation_out(domain_out);

	// Vector of marks/flags that indicate which cells should be refined

	CellRefinementFlagContainerType     cell_refinement_flag_container;

	viennagrid::result_of::field<CellRefinementFlagContainerType,
	                             TriangularCartesian2D_Cell_t>::type    cell_refinement_flag_field(cell_refinement_flag_container);

	// Marks which edges should be refined
	TriangularCartesian2D_CellRange_t cells = viennagrid::elements(domain_in.get_domain());
	for (TriangularCartesian2D_CellRange_t::iterator it = cells.begin();
		                                         it != cells.end();
		                                       ++it)
	{
		if (predicate(TriangularCartesian2D_Cell(*it)))
			cell_refinement_flag_field(*it) = true;
	}

	// Refine marked edges
	viennagrid::cell_refine(domain_in.get_domain(),
	                        segmentation_in.get_segmentation(),
	                        domain_out.get_domain(),
	                        segmentation_out.get_segmentation(),
	                        cell_refinement_flag_field);

	// Return refined domain and segmentation as a tuple: (refined_domain, refined_segmentation)
	return make_tuple<TriangularCartesian2D_Domain, TriangularCartesian2D_Segmentation>(domain_out, segmentation_out);
}

Implement cell-refinement of triangular cartesian 2D cells.


//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <deque>

#include "dll_test.hpp"

#include "dll/dense_layer.hpp"
#include "dll/scale_layer.hpp"
#include "dll/dbn.hpp"
#include "dll/stochastic_gradient_descent.hpp"

#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"

TEST_CASE("dbn/ae/1", "[rbm][dbn][mnist][sgd][ae]") {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::rbm_desc<28 * 28, 200, dll::momentum, dll::batch_size<25>>::rbm_t,
            dll::rbm_desc<200, 28 * 28, dll::momentum, dll::batch_size<25>>::rbm_t
        >, dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(1000);
    REQUIRE(!dataset.training_images.empty());

    dll_test::mnist_scale(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->display();

    dbn->pretrain(dataset.training_images, 50);

    dbn->learning_rate = 0.1;

    auto ft_error = dbn->fine_tune_ae(dataset.training_images, 50);
    std::cout << "ft_error:" << ft_error << std::endl;

    CHECK(ft_error < 5e-2);

    auto test_error = dll::test_set_ae(*dbn, dataset.test_images);
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.1);
}

Add test for autoencoder with RBM pretraining


// 6. ZigZag Conversion
/**
 * The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
 * (you may want to display this pattern in a fixed font for better legibility)
 *
 * P   A   H   N
 * A P L S I I G
 * Y   I   R
 *
 * And then read line by line: "PAHNAPLSIIGYIR"
 * Write the code that will take a string and make this conversion given a number of rows:
 *
 * string convert(string text, int nRows);
 *
 * convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
 *
 * Tags: String
 *
 * Author: Kuang Qin
 */

#include <iostream>
#include <string>

using namespace std;

class Solution {
public:
    string convert(string s, int numRows) {
        if (numRows <= 1) {
            return s;
        }

        string res;

        // P   | A   | H   | N
        // A P | L S | I I | G
        // Y   | I   | R   |
        // each row has 2 elements except the first row and the last row in one period
        int period = 2 * numRows - 2;
        for (int i = 0; i < numRows; i++) {         // build each row
            for (int j = i; j < s.size(); j += period) {    // build string in each period
                res += s[j];

                // 0     : 0                            |
                // 1     : 1                   p - 1    |
                // .       .                  .         |
                // .       .                 .          |
                // .       .                .           |
                // i     : j            p - i           |
                // .       .           .                |
                // .       .          .                 |
                // .       .         .                  |
                // n - 2 : n - 2    p - (n - 2)         |
                // n - 1 : n - 1                        |
                // calculate the position of the second element
                int k = j - i + period - i;

                // if not the first or last row append the second element
                if (i != 0 && i != numRows - 1 && k < s.size()) {
                    res += s[k];
                }
            }
        }

        return res;
    }
};

int main() {
    string s = "PAYPALISHIRING";
    Solution sol;
    string res = sol.convert(s, 3);
    cout << res << endl;
    cin.get();

    return 0;
}

Add Solution 006 ZigZag Conversion


//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

// <streambuf>

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

// streamsize xsputn(const char_type* s, streamsize n);

// Test https://bugs.llvm.org/show_bug.cgi?id=14074. The bug is really inside
// basic_streambuf, but I can't seem to reproduce without going through one
// of its derived classes.

#include <cassert>
#include <cstddef>
#include <cstdio>
#include <fstream>
#include <sstream>
#include <string>
#include "platform_support.h"

// Count the number of bytes in a file -- make sure to use only functionality
// provided by the C library to avoid relying on the C++ library, which we're
// trying to test.
static std::size_t count_bytes(char const* filename) {
    std::FILE* f = std::fopen(filename, "rb");
    std::size_t count = 0;
    while (std::fgetc(f) != EOF)
        ++count;
    return count;
}

int main(int, char**) {
    {
        // with basic_stringbuf
        std::basic_stringbuf<char> buf;
        std::streamsize sz = buf.sputn("\xFF", 1);
        assert(sz == 1);
        assert(buf.str().size() == 1);
    }
    {
        // with basic_filebuf
        std::string temp = get_temp_file_name();
        {
            std::basic_filebuf<char> buf;
            buf.open(temp.c_str(), std::ios_base::out);
            std::streamsize sz = buf.sputn("\xFF", 1);
            assert(sz == 1);
        }
        assert(count_bytes(temp.c_str()) == 1);
        std::remove(temp.c_str());
    }

    return 0;
}

Add a test for PR14074


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

// test bad_array_length

#include <new>
#include <type_traits>
#include <cassert>

int main()
{
#if __LIBCPP_STD_VER > 11
    static_assert((std::is_base_of<std::bad_alloc, std::bad_array_length>::value),
                  "std::is_base_of<std::bad_alloc, std::bad_array_length>::value");
    static_assert(std::is_polymorphic<std::bad_array_length>::value,
                 "std::is_polymorphic<std::bad_array_length>::value");
    std::bad_array_length b;
    std::bad_array_length b2 = b;
    b2 = b;
    const char* w = b2.what();
    assert(w);
#endif
}

Test for 'bad_array_length'; got left out of initial commit


#include <stdio.h>

using namespace std;
const double EPS = 1e-15;

/*
 * Return
 * -1  if x < y
 *  0  if x == y
 *  1  if x > y
 */
int cmp (double x, double y){
    return (x <= y + EPS) ? (x + EPS < y) ? -1 : 0 : 1;
}

int main(){
    double d1 = 0.00000000000212;
    double d2 = 0.00000000000213;
    int res = cmp(d1,d2);
    if (res == 0){
        printf("Equal \n");
    }else if(res == 1){
        printf("Greater\n");
    }else {
        printf("Less \n");
    }

}

Implement useful function to compare double in order to prevent problems with precision.


// g++ -o span01 -Wall -Wextra -pedantic -std=c++14 -I GSL/include span01.cpp
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>

#include <gsl/span>

// See e.g. http://codexpert.ro/blog/2016/03/07/guidelines-support-library-review-spant/
template <typename T>
void write_data_pass_by_const_ref(gsl::span<T> const & s, std::string const & filename)
{
    std::ofstream file(filename);
    std::copy(std::begin(s), std::end(s),
              std::ostream_iterator<T>(file, "\n"));
}

// See e.g. https://github.com/Microsoft/GSL/issues/380#issuecomment-250842034
template <typename T>
void write_data_pass_by_value(gsl::span<T> const s, std::string const & filename)
{
    std::ofstream file(filename);
    std::copy(std::begin(s), std::end(s),
              std::ostream_iterator<T>(file, "\n"));
}

int main()
{
    std::vector<int> v {1, 2, 3, 4, 5};
    write_data_pass_by_const_ref(gsl::make_span(v), "vector_const_ref.txt");
    write_data_pass_by_value(gsl::make_span(v), "vector_value.txt");
}

Add an example using gsl::span<T>


// A nested loop.
#include <stdio.h>

int main() {
  int n;
  scanf("%d", &n);

  int *A = new int[n];
  int *B = new int[n];

  for (int i = 0; i < n; ++i) {
    scanf("%d", &A[i]);
  }

  for (int i = 0; i < n; ++i) {
    scanf("%d", &B[i]);
  }

  int sum = 0;
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < n; ++j) {
      sum += A[i] * B[j];
    }
  }
  printf("%d\n", sum);

  delete[] A;
  delete[] B;
}

Add nested loop example specimen 5


#include "server.h"

using namespace SeaSocks;

int main(int argc, const char* argv[]) {
	Server server;
	server.serve("src/web", 9090);
	return 0;
}

#include "server.h"

/*
 * TODOs:
 * * Add logging
 * * Connection class does *everything*. Work out better division of labour; server should do more, connection should just be connection stuff, handlers for data?
 * * sort out buffers and buffering
 * * work out what state to hang on to; handle multiple WS endpoints
 * * work out threading model for asynch message passing.
 * * Fix bloody SO_REUSEADDR
 */

using namespace SeaSocks;

int main(int argc, const char* argv[]) {
	Server server;
	server.serve("src/web", 9090);
	return 0;
}

Add a list of TODOs


//=======================================================================
// Copyright (c) 2014-2020 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#define ETL_COUNTERS
#define ETL_GPU_POOL

#include "dll/neural/dense/dense_layer.hpp"
#include "dll/neural/rnn/rnn_layer.hpp"
#include "dll/neural/recurrent/recurrent_last_layer.hpp"
#include "dll/network.hpp"
#include "dll/datasets.hpp"

int main(int /*argc*/, char* /*argv*/ []) {
    // Load the dataset
    auto dataset = dll::make_mnist_dataset_nc(dll::batch_size<200>{}, dll::scale_pre<255>{});

    constexpr size_t time_steps      = 28;
    constexpr size_t sequence_length = 28;
    constexpr size_t hidden_units    = 200;

    // Build the network

    using network_t = dll::network_desc<
        dll::network_layers<
            dll::rnn_layer<time_steps, sequence_length, hidden_units>,
            dll::recurrent_last_layer<time_steps, hidden_units>,
            dll::dense_layer<hidden_units, 10, dll::softmax>
        >
        , dll::updater<dll::updater_type::ADAM>      // Adam
        , dll::batch_size<200>                       // The mini-batch size
        , dll::no_batch_display                      // Disable pretty print of each every batch
        , dll::no_epoch_error                        // Disable computation of the error at each epoch
    >::network_t;

    auto net = std::make_unique<network_t>();

    // Display the network and dataset
    net->display_pretty();
    dataset.display_pretty();

    // Train the network for performance sake
    net->train(dataset.train(), 5);

    // Test the network on test set
    net->evaluate(dataset.test());

    // Show where the time was spent
    dll::dump_timers_pretty();

    // Show ETL performance counters
    etl::dump_counters_pretty();

    return 0;
}

Add a RNN perf workbench


// Lexicographic-compare
// C++11

#include <tuple>

class foo
{
	public:
		foo(int n_, char c_, double d_)
			: n{n_}, c{c_}, d{d_}
		{}

		friend bool operator<(const foo& lh, const foo& rh)
		{
			return	  std::tie(lh.n, lh.c, lh.d)
				< std::tie(rh.n, rh.c, rh.d);
		}
	private:
		int n;
		char c;
		double d;
};

// Implement compare of multiple members with std::tie
//
// Getting an order relation right with 3 elements or more is
// tedious and easy to get wrong. Fortunately the standard
// library does it with tuples. The function template std::tie()
// creates a tuple with references to its arguments.
//
// The class `foo`, on [6-22] has three member variables `n`, `c` and `d`
// declared on [19-21].
//
// The less-than operator on [13-17] compares two `foo`s on the member
// `n` first, on the member `c` if the `n`s are equal, and finally on
// `d` if both the `n`s and `c`s are equal.
//
// The formatting [14-15] to align the left hand and right hand
// arguments straight below each others makes it easier to spot
// mistakes as assymetries.
//
// It is not necessary to declare the less-than operator as a friend
// function [13], it can be implemented as a member function as well,
// but this is a common idiom.

int main()
{
	foo f1(1, 'a', 3.14);
	foo f2(1, 'b', 2.78);

	if (f1 < f2)
	{
		return 1;
	}
}

Add lexicographical compare with tie


/////////////////////////////////////////////////////////////////////////////
// This file is part of EasyRPG.
//
// EasyRPG is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// EasyRPG is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with EasyRPG Player. If not, see <http://www.gnu.org/licenses/>.
/////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include "rpg_chipset.h"

////////////////////////////////////////////////////////////
/// Constructor
////////////////////////////////////////////////////////////
RPG::Chipset::Chipset() {
	ID = 0;
	name = "";
	chipset_name = "";
	animation_type = 0;
	animation_speed = 0;
}

/////////////////////////////////////////////////////////////////////////////
// This file is part of EasyRPG.
//
// EasyRPG is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// EasyRPG is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with EasyRPG Player. If not, see <http://www.gnu.org/licenses/>.
/////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include "rpg_chipset.h"

////////////////////////////////////////////////////////////
/// Constructor
////////////////////////////////////////////////////////////
RPG::Chipset::Chipset() {
	ID = 0;
	name = "";
	chipset_name = "";
	terrain_data.resize(162, 1);
	animation_type = 0;
	animation_speed = 0;
}

Set default value for terrain_data field


#include <cmath>

#include <iostream>
#include <random>
#include <thread>

#include "gflags/gflags.h"
#include "glog/logging.h"

#include "driver/engine.hpp"
#include "lib/abstract_data_loader.hpp"
#include "lib/labeled_sample.hpp"
#include "lib/parser.hpp"

using namespace csci5570;

using Sample = double;
using DataStore = std::vector<Sample>;

DEFINE_string(config_file, "", "The config file path");
DEFINE_string(input, "", "The hdfs input url");

int main(int argc, char** argv) {
  gflags::ParseCommandLineFlags(&argc, &argv, true);
  google::InitGoogleLogging(argv[0]);
  FLAGS_stderrthreshold = 0;
  FLAGS_colorlogtostderr = true;

  LOG(INFO) << FLAGS_config_file;

  Node node{0, "localhost", 12353};
  Engine engine(node, {node});

  // 1. Start system
  engine.StartEverything();

  // 1.1 Create table
  const auto kTableId = engine.CreateTable<double>(ModelType::SSP, StorageType::Map);  // table 0

  // 1.2 Load data
  engine.Barrier();

  // 2. Start training task
  MLTask task;
  task.SetWorkerAlloc({{0, 3}});  // 3 workers on node 0
  task.SetTables({kTableId});     // Use table 0
  task.SetLambda([kTableId](const Info& info) {
    LOG(INFO) << info.DebugString();

    KVClientTable<double> table = info.CreateKVClientTable<double>(kTableId);

    for (int i = 0; i < 1e8; ++i) {
      std::vector<Key> keys{1};

      std::vector<double> ret;
      table.Get(keys, &ret);
      LOG(INFO) << ret[0];

      std::vector<double> vals{0.5};
      table.Add(keys, vals);

      table.Clock();
    }
  });

  engine.Run(task);

  // 3. Stop
  engine.StopEverything();
  return 0;
}

Add a simple example application


// A simple program that computes the square root of a number
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <iostream>
#include <allegro5/allegro.h>

#include "TutorialConfig.h"

int main (int argc, char *argv[])
{
  if (argc < 2)
    {
    fprintf(stdout,"%s Version %d.%d\n", argv[0],
            Tutorial_VERSION_MAJOR,
            Tutorial_VERSION_MINOR);
    fprintf(stdout,"Usage: %s number\n",argv[0]);
    return 1;
    }

  if(al_init() != true)
  {
	  std::cerr << "Fatal error, Allegro has not being found!"
	  << std::endl;
	  return 2;
  } else {
	  std::cout << "Allegro was found!" << std::endl;
  }

  double inputValue = atof(argv[1]);

#ifdef USE_MYMATH
  double outputValue = mysqrt(inputValue);
#else
  double outputValue = sqrt(inputValue);
#endif

  fprintf(stdout,"The square root of %g is %g\n",
          inputValue, outputValue);
  return 0;
}

Add sample code file for Cmake tests


//
//  main.cpp
//  CPP
//
//  Created by Mgen on 8/27/16.
//  Copyright © 2016 Mgen. All rights reserved.
//

#include <iostream>
#include <vector>
#include <algorithm>
#include <set>

using namespace std;

// runs a binary search on a given array, returns the insert position of a given integer
int findInsertPosition(vector<int>& nums, int target) {
    int i = 0, j = nums.size() - 1;
    while (i < j) {
        int mid = i + (j - i) / 2;
        if (target <= nums[mid]) {
            j = mid;
        } else {
            i = mid + 1;
        }
    }
    return i;
}

// runs a binary search in O(log n) and finds k closest elements in O(k).
multiset<int> binarySearch(vector<int> nums, int target, int k) {
    multiset<int> result;
    // sort the array
    sort(nums.begin(), nums.end());

    // assume target exists and k <= nums.size()
    int idx = findInsertPosition(nums, target);
    // insert the most closest element into the set
    result.insert(nums[idx]);
    int i = idx - 1, j = idx + 1;
    // find the other k - 1 closest elements
    while (result.size() < k) {
        if (j >= nums.size() - 1 || target - nums[i] < nums[j] - target) {
            result.insert(nums[i--]);
        } else {
            result.insert(nums[j++]);
        }
    }
    return result;
}

void printSet(multiset<int>& set) {
    for (auto n: set) {
        cout << n << " ";
    }
    cout << endl;
}

int main() {
    vector<int> sortedNums = {1, 2, 3, 4, 6, 6, 10};
    multiset<int> result;

    // find 4 closest element to 6
    result = binarySearch(sortedNums, 6, 4);
    printSet(result);
    // find 5 closest element to 5
    result = binarySearch(sortedNums, 5, 5);
    printSet(result);
    return 0;
}

Implement a binary search on a sorted array


struct x {
  x() : a(4) ; // expected-error {{expected '{'}}
};

struct y {
  int a;
  y() : a(4) ; // expected-error {{expected '{'}}
};

Add a test for PR3733.


class Solution {
public:
    bool checkValid(vector<vector<int>>& matrix) {
        for (int i = 0; i < matrix.size(); ++i) {
            std::vector<int> check(matrix.size()+1, 0);
            for (int j = 0; j < matrix[0].size(); ++j) {
                if (check[matrix[i][j]] == 1) return false;
                check[matrix[i][j]] = 1;
            }
        }

        for (int j = 0; j < matrix[0].size(); ++j) {
            std::vector<int> check(matrix.size()+1, 0);
            for (int i = 0; i < matrix.size(); ++i) {
                if (check[matrix[i][j]] == 1) return false;
                check[matrix[i][j]] = 1;
            }
        }
        return true;
    }
};

Check if Every Row and Column Contains All Numbers


/**
 * [Link:] https://leetcode.com/problems/invert-binary-tree/
 */

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if(!root)
            return root;
        if(!root->left && !root->right)
            return root;
        TreeNode* tmp = root->left;
        root->left  = invertTree(root->right);
        root->right = invertTree(tmp);
        return root;
    }
};

Add solution for 226. Invert Binary Tree.


// RUN: %clang_cc1 -fsyntax-only -verify %s

struct ConstCopy {
  ConstCopy();
  ConstCopy &operator=(const ConstCopy&);
};

struct NonConstCopy {
  NonConstCopy();
  NonConstCopy &operator=(NonConstCopy&);
};

struct VirtualInheritsNonConstCopy : virtual NonConstCopy {
  VirtualInheritsNonConstCopy();
  VirtualInheritsNonConstCopy &operator=(const VirtualInheritsNonConstCopy&);
};

struct ImplicitNonConstCopy1 : NonConstCopy {  // expected-note{{the implicit copy assignment operator}}
  ImplicitNonConstCopy1();
};

struct ImplicitNonConstCopy2 { // expected-note{{the implicit copy assignment operator}}
  ImplicitNonConstCopy2();
  NonConstCopy ncc;
};

struct ImplicitNonConstCopy3 { // expected-note{{the implicit copy assignment operator}}
  ImplicitNonConstCopy3();
  NonConstCopy ncc_array[2][3];
};

struct ImplicitNonConstCopy4 : VirtualInheritsNonConstCopy {
  ImplicitNonConstCopy4();
};

void test_non_const_copy(const ImplicitNonConstCopy1 &cincc1,
                         const ImplicitNonConstCopy2 &cincc2,
                         const ImplicitNonConstCopy3 &cincc3,
                         const ImplicitNonConstCopy4 &cincc4,
                         const VirtualInheritsNonConstCopy &vincc) {
  (void)sizeof(ImplicitNonConstCopy1() = cincc1); // expected-error{{no viable overloaded '='}}
  (void)sizeof(ImplicitNonConstCopy2() = cincc2); // expected-error{{no viable overloaded '='}}
  (void)sizeof(ImplicitNonConstCopy3() = cincc3); // expected-error{{no viable overloaded '='}}
  (void)sizeof(ImplicitNonConstCopy4() = cincc4); // okay
  (void)sizeof(VirtualInheritsNonConstCopy() = vincc);
}

Test implicit declaration of copy assignment operator with non-const argument


#include<iostream>
#include "bfs.h"  // My implementation of breadth first search
#include<vector>

// tests Bfs traversal, distances and paths

void testBfs(){

	// edges
	std::vector<std::vector<int> > edges = {	{1,5},
												{3,5},
												{2,4},
												{1,4},
												{5,7},
												{7,6},
												{2,6}

											};

	int n = 8;	// no. of vertices
	int m = 7;	// no. of edges
	int s = 1;	// source vertex

	Bfs bfs(n, m, edges, s);

	// print traversal

	std::cout<<"Traversal: ";
	bfs.traverse();

	// print distances of vertices from source

	std::cout<<"\nDistances:\n";
	bfs.printDistances();

	// print path from source to all vertices

	std::cout<<"Paths: \n";
	bfs.printAllPaths();

	// deallocate vertices
	bfs.deallocateVertices();
}

int main(){

	// call testBfs

	testBfs();

	return 0;
}

Add test program for breadth first search


#include <bits/stdc++.h>
#define endl '\n'
using namespace std;
const int M_MAX = 20; // Máximo size del String 1
const int N_MAX = 20; // Máximo size del String 2
int m, n; // Size de Strings 1 y 2
string X; // String 1
string Y; // String 2
int memo[M_MAX + 1][N_MAX + 1];
int lcs (int m, int n) {
  for (int i = 0; i <= m; i++) {
    for (int j = 0; j <= n; j++) {
      if (i == 0 || j == 0) memo[i][j] = 0;
      else if (X[i - 1] == Y[j - 1]) memo[i][j] = memo[i - 1][j - 1] + 1;
      else memo[i][j] = max(memo[i - 1][j], memo[i][j - 1]);
    }
  }
  return memo[m][n];
}
int main(){
  X = "XMJYAUZ";
  Y = "MZJAWXU";
  cout << lcs(X.size(), Y.size()) <<endl;
  //Sol = MJAU
  return 0;
}

Add algorithm to fing the len of longest common subsequenc..


Add Chapter 21, Try This 1


/**
 * This test checks whether we detect a deadlock arising from a parent thread
 * trying to join a child who requires a lock held by its parent in order to
 * finish.
 */

#include <d2mock.hpp>

int main(int argc, char const* argv[]) {
    d2mock::mutex G;

    d2mock::thread t1([&] {
        G.lock();
        G.unlock();
    });

    d2mock::thread t0([&] {
        t1.start();
        // if t0 acquires G before t1 does, t1 can never be joined
        G.lock();
        t1.join();
        G.unlock();
    });

    auto test_main = [&] {
        t0.start();
        t0.join();
    };

    // Right now, we have no way of encoding these kinds of deadlocks,
    // and we're obviously not detecting them too. For now, we'll always
    // make the test fail.
#if 1
    return EXIT_FAILURE;
#else
    return d2mock::check_scenario(test_main, argc, argv, {
                {
                    // t0 holds G, and waits for t1 to join
                    {t0, G, join(t1)},
                    // t1 waits for G, and will never be joined
                    {t1, G}
                }
            });
#endif
}

Add a scenario showing a kind of deadlock that is unsupported right now.


static_assert(2 + 2 == 4, "Simple maths");

// RUN: c-index-test -test-load-source all -fno-delayed-template-parsing -std=c++11 %s | FileCheck %s
// CHECK: load-staticassert.cpp:2:1: StaticAssert=:2:1 (Definition) Extent=[2:1 - 2:42]
// CHECK: load-staticassert.cpp:2:15: BinaryOperator= Extent=[2:15 - 2:25]
// CHECK: load-staticassert.cpp:2:15: BinaryOperator= Extent=[2:15 - 2:20]
// CHECK: load-staticassert.cpp:2:15: IntegerLiteral= Extent=[2:15 - 2:16]
// CHECK: load-staticassert.cpp:2:19: IntegerLiteral= Extent=[2:19 - 2:20]
// CHECK: load-staticassert.cpp:2:24: IntegerLiteral= Extent=[2:24 - 2:25]
// CHECK: load-staticassert.cpp:2:27: StringLiteral="Simple maths" Extent=[2:27 - 2:41]

Test that static_assert is properly visited in liblcang


/**
 * Remove Nth Node From End of List
 * Double pointer.
 *
 * cpselvis(cpselvis@gmail.com)
 * August 18th, 2016
 */
#include<iostream>
using namespace std;

struct ListNode {
  int val;
  ListNode *next;
  ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
  ListNode* removeNthFromEnd(ListNode* head, int n) {
    ListNode *fast = head, *slow = head;
    while (n --)
    {
      fast = fast -> next;
    }

    while (fast == NULL)
    {
      return head -> next;
    }

    while (fast -> next != NULL)
    {
      fast = fast -> next;
      slow = slow -> next;
    }

    slow -> next = slow -> next -> next;
    return head;
  }
};

int main(int argc, char **argv)
{
  Solution s;
  ListNode *p = new ListNode(1);
  // p -> next = new ListNode(2);
  // p -> next -> next = new ListNode(3);
  ListNode *ret = s.removeNthFromEnd(p, 1);
  cout << ret -> val << endl;
}

Remove nth element from the end of list.


/**
 ******************************************************************************
 * Xenia : Xbox 360 Emulator Research Project                                 *
 ******************************************************************************
 * Copyright 2015 Ben Vanik. All rights reserved.                             *
 * Released under the BSD license - see LICENSE in the root for more details. *
 ******************************************************************************
 */

#include "xenia/base/exception_handler.h"

#include "xenia/base/assert.h"
#include "xenia/base/math.h"
#include "xenia/base/platform_linux.h"

namespace xe {

// This can be as large as needed, but isn't often needed.
// As we will be sometimes firing many exceptions we want to avoid having to
// scan the table too much or invoke many custom handlers.
constexpr size_t kMaxHandlerCount = 8;

// All custom handlers, left-aligned and null terminated.
// Executed in order.
std::pair<ExceptionHandler::Handler, void*> handlers_[kMaxHandlerCount];

void ExceptionHandler::Install(Handler fn, void* data) {
  //TODO(dougvj) stub
}

void ExceptionHandler::Uninstall(Handler fn, void* data) {
  //TODO(dougvj) stub
}

}  // namespace xe

Add stub exception handler backend for linux


// Chapter 20, Try This 8: same as Try This 7, but with an array of int, a
// vector<int> and a list<int>, with the value { 1, 2, 3, 4, 5 }.

#include "../lib_files/std_lib_facilities.h"

// requires size of array as it decays to a pointer
void ai_func(const int ai[], int sz)
{
    cout << "Number of elements in ai: " << sz << "\n";
}

void vi_func(const vector<int>& vi)
{
    cout << "Number of elements in vi: " << vi.size() << "\n";
}

void li_func(const list<int>& li)
{
    cout << "Number of elements in li: " << li.size() << "\n";
}

int main()
try {
    int ai[] = { 1, 2, 3, 4, 5 };
    ai_func(ai,sizeof(ai)/sizeof(*ai));

    vector<int> vi;
    for (int i = 1; i<6; ++i) vi.push_back(i);
    vi_func(vi);

    list<int> li;
    for (int i = 1; i<6; ++i) li.push_back(i);
    li_func(li);
}
catch (Range_error& re) {
    cerr << "bad index: " << re.index << "\n";
}
catch (exception& e) {
    cerr << "exception: " << e.what() << endl;
}
catch (...) {
    cerr << "exception\n";
}

Add Chapter 20, Try This 8


#include <iostream>
using namespace std;

struct Queue {
    int *array;
    int front, rear;
    int size;
};

Queue* createQueue(int size) {
    Queue *queue = new Queue();
    if (!queue) return NULL;

    queue->front = queue->rear = -1;
    queue->size = size;
    queue->array = new int[queue->size];

    if (!queue->array) return NULL;

    return queue;
}

bool isFull(Queue* queue) {
    return (queue && ((queue->rear + 1) % queue->size == queue->front));
}

bool isEmpty(Queue* queue) {
    return (queue && queue->front == -1);
}

void enqueue(Queue *queue, int data) {
    if (isFull(queue)) return;

    queue->rear = (queue->rear + 1) % queue->size;
    queue->array[queue->rear] = data;

    if (queue->front == -1)
        queue->front = queue->rear;
}

int dequeue(Queue *queue) {
    if (isEmpty(queue)) return -1;

    int data = queue->array[queue->front];

    if (queue->front == queue->rear)
        queue->front = queue->rear = -1;
    else
        queue->front = (queue->front + 1) % queue->size;
    return data;
}

void deleteQueue(Queue *queue) {
    if (isEmpty(queue)) return;
    delete [] queue->array;
    delete queue;
}

void printQueue(Queue *queue) {
    if (isEmpty(queue)) return;

    for (int i = queue->front; i <= queue->rear; i++) {
        cout<<queue->array[i]<<" ";
    }
    cout<<endl;
}

size_t size(Queue *queue) {
    return isEmpty(queue) ? 0 : (queue->size - (queue->front + queue->rear+1)) % queue->size;
}

int main() {
    Queue *queue = createQueue(10);
    enqueue(queue, 1);
    enqueue(queue, 2);
    enqueue(queue, 3);
    enqueue(queue, 4);
    enqueue(queue, 5);
    enqueue(queue, 6);
    enqueue(queue, 7);
    enqueue(queue, 8);
    enqueue(queue, 9);
    enqueue(queue, 10);
    enqueue(queue, 11);

    printQueue(queue);

    int del = 5;
    cout<<"Dequeue 5 elements\n";
    while (del--) {
        cout<<dequeue(queue)<<" ";
    }
    cout<<endl;
    cout<<"Enqueue 12,13,14,15 \n";
    enqueue(queue, 12);
    enqueue(queue, 13);
    enqueue(queue, 14);
    enqueue(queue, 15);

    cout<<"Size of queue: "<<size(queue)<<endl;
    printQueue(queue);

    del = 6;
    cout<<"Dequeue 6 elements\n";
    while (del--) {
        cout<<dequeue(queue)<<" ";
    }
    cout<<endl;

    cout<<"Size of queue: "<<size(queue)<<endl;
    printQueue(queue);

    deleteQueue(queue);

    return 0;
}

Implement queue using circular array


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

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

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

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

#include "tensorflow/core/lib/gtl/optional.h"

namespace tensorflow {
namespace gtl {

nullopt_t::init_t nullopt_t::init;
extern const nullopt_t nullopt{nullopt_t::init};

}  // namespace gtl
}  // namespace tensorflow

Add cc file with definition of tensorflow::gtl::nullopt.


// RUN: c-index-test -test-load-source all %s 2>&1 | FileCheck %s

// This test case previously just crashed the frontend.

struct abc *P;
int main(

// CHECK: StructDecl=abc:5:8 Extent=[5:1 - 5:11]
// CHECK: VarDecl=P:5:13 (Definition) Extent=[5:8 - 5:14]
// CHECK: VarDecl=main:6:5 (Definition) Extent=[6:1 - 6:9]

Add test case for crash reported in <rdar://problem/8236270> (which has since been fixed in trunk).


#include <gtest/gtest.h>
#include "LRUCache.hxx"

TEST(LRUCache, InsertPair)
{
    LRUCache<int, std::string, 3> cache;

    auto pairResult = cache.insert(std::make_pair<int, std::string>(1, "1"));
    EXPECT_EQ(std::string("1"), pairResult.first->second);
    EXPECT_TRUE(pairResult.second);
    EXPECT_EQ(1, cache.size());

    pairResult = cache.insert(std::make_pair<int, std::string>(2, "2"));
    EXPECT_EQ(std::string("2"), pairResult.first->second);
    EXPECT_TRUE(pairResult.second);
    EXPECT_EQ(2, cache.size());

    pairResult = cache.insert(std::make_pair<int, std::string>(3, "3"));
    EXPECT_EQ(std::string("3"), pairResult.first->second);
    EXPECT_TRUE(pairResult.second);
    EXPECT_EQ(3, cache.size());

    pairResult = cache.insert(std::make_pair<int, std::string>(4, "4"));
    EXPECT_EQ(std::string("4"), pairResult.first->second);
    EXPECT_TRUE(pairResult.second);
    EXPECT_EQ(3, cache.size());
}

TEST(LRUCache, BracketOperator)
{
    LRUCache<int, std::string, 5> cache;

    cache.insert(std::make_pair<int, std::string>(1, "1"));
    auto& value = cache[1];
    EXPECT_EQ(std::string("1"), value);
}

Add unit tests covering operator[] and insert


#include <istream>
#include <fstream>
#include <set>
#include <vector>
#include <array>
#include <algorithm>
#include <iterator>

using namespace std;

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

	int size;
	cin >> size;

	set<int> options;
	for (int i = 0; i < 2; i++) {
		int a, b, c;
		cin >> a >> b >> c;

		// creates permutations of allowable combinations and turns them into
		// an integer so that set can compare them and only retain uniques

		// the indexes here start at -3 and end at +1 because the input starts
		// at 1 but here we want it to start at 0
		for (int i = a - 3; i <= a + 1; i++) {
			for (int j = b - 3; j <= b + 1; j++) {
				for (int k = c - 3; k <= c + 1; k++) {
					options.insert(((((i % size) + size) % size) << 0) +
								   ((((j % size) + size) % size) << 8) +
								   ((((k % size) + size) % size) << 16));
				}
			}
		}
	}

	// the size of the set is the number of unique combinations
	cout << options.size() << endl;

	return 0;
}

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


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

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

#include <Utils/TestUtils.hpp>
#include "gtest/gtest.h"

#include <hspp/Cards/Minion.hpp>
#include <hspp/Managers/GameAgent.hpp>
#include <hspp/Tasks/SimpleTasks/ControlTask.hpp>

using namespace Hearthstonepp;
using namespace SimpleTasks;
using namespace TestUtils;

TEST(ControlTask, GetTaskID)
{
    const ControlTask control(EntityType::TARGET);
    EXPECT_EQ(control.GetTaskID(), +TaskID::CONTROL);
}

Add unit test for ControlTask


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "glsl_optimizer.h"

static glslopt_ctx* gContext = 0;

#include <emscripten/val.h>

#define str(str) std::string(str)

static bool compileShader2(const char* originalShader, bool vertexShader)
{
	if( !originalShader )
		return false;

	const glslopt_shader_type type = vertexShader ? kGlslOptShaderVertex : kGlslOptShaderFragment;

	glslopt_shader* shader = glslopt_optimize(gContext, type, originalShader, 0);
	if( !glslopt_get_status(shader) )
	{
		const char* failed_log = glslopt_get_log(shader);
		// printf( "Failed to compile:\n\n%s\n", failed_log);
		emscripten::val::global("HLSLParser").call<void>("onError", str("Failed to compiled: ") + str(failed_log));
		return false;
	}

	const char* optimizedShader = glslopt_get_output(shader);
	// printf("Out: %s\n", optimizedShader);

	emscripten::val::global("HLSLParser").call<void>("onSuccess", str(optimizedShader));

	return true;
}

extern "C" {

    int optimize_glsl(char* source, char* type)
    {

		bool vertexShader = false;
		glslopt_target languageTarget = kGlslTargetOpenGL;

		// fragment shader
		vertexShader = false;

		// ES 2
		languageTarget = kGlslTargetOpenGLES20;
		//kGlslTargetOpenGLES20  kGlslTargetOpenGLES30 kGlslTargetOpenGL

		if( !source )
			return printf("Must give a source");

		gContext = glslopt_initialize(languageTarget);

		if( !gContext )
		{
			printf("Failed to initialize glslopt!\n");
			return 1;
		}

		int result = 0;
		if( !compileShader2(source, vertexShader) )
			result = 1;

		glslopt_cleanup(gContext);

		return result;
	}

}

Add entry file building glsl optimzier for emscripten


#include "classad/classad_distribution.h"

#include <string>
#include <string.h>
#include <sys/types.h>

/* This is the driver for the classad fuzz tester.
 * Note this is intentionally not in the cmake file, it should not be built
 * by default.
 *
 * To use, compile all of classads with clang -fsanitize=fuzzer-nolink,address
 * then recompile this one file with clang -fsanitize=fuzzer
 * This adds a magic main function here.
 * Then, just run ./a.out and let it run for a long time.
 */

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *input, size_t len) {

	classad::ClassAdParser parser;
	classad::ExprTree  *tree;
	std::string s(input, input + len);

	tree = parser.ParseExpression(s);
	delete tree;

	return 0;
}

Add fuzzing driver to classads HTCONDOR-814


#include <Arduino.h>
#include "sdplib.h"
#include "Wire.h"

#define IRQ_PIN 4

SDPclass sdp;

double diff_pressure, temperature;
bool sdpFlag = false;

// Interrupt routine
void SDP_isr(void){
  sdpFlag = true;
}

void setup(){

  while(!Serial){
  Serial.begin(115200);
}
  pinMode(IRQ_PIN, INPUT_PULLUP);
  attachInterrupt(IRQ_PIN, SDP_isr, FALLING); // active when low, so we seek for change to low

  Wire.begin();
  sdp.begin();
  sdp.getAddress();
  sdp.startContinuousMeasurement(SDP_TEMPCOMP_DIFFERENTIAL_PRESSURE, SDP_AVERAGING_TILL_READ);
}

void loop(){

  if(sdpFlag == true){
    diff_pressure = sdp.getDiffPressure();
    temperature = sdp.getTemperature();
    sdpFlag = false;
  }

}

Add example to read SDP3x using isr


// Standard headers
#include <memory>
#include <iostream>

// External headers
#include "gmock/gmock.h"

// Internal headers
#include "InputArgs.hpp"

// Alias
using ::testing::DoubleNear;

const double PI = 3.141592653589793238462643;

class ASetOfInputArguments : public testing::Test {
};

TEST_F(ASetOfInputArguments, NonZeroNumberOfThreads) {
  std::unique_ptr<const char *[]> argv (
    new const char *[6] { "Cosine", "2", "f", "10", "1", "d" }
  );

  InputArgs args(6, argv.get());

  ASSERT_TRUE(args.n_threads == 2
    and args.stop_criteria   == 'f'
    and args.precision       == 10
    and args.cosine          == 1
    and args.debug_level     == 'd');
}

TEST_F(ASetOfInputArguments, ZeroNumberOfThreads) {
  std::unique_ptr<const char *[]> argv (
    new const char *[6] { "Cosine", "0", "f", "10", "1", "d" }
  );

  InputArgs args(6, argv.get());

  ASSERT_TRUE(args.n_threads == std::thread::hardware_concurrency()
    and args.stop_criteria   == 'f'
    and args.precision       == 10
    and args.cosine          == 1
    and args.debug_level     == 'd');
}

Add tests for 'InputArg' class


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

// <functional>

// See https://llvm.org/bugs/show_bug.cgi?id=20002

#include <functional>
#include <type_traits>

using Fn = std::function<void()>;
struct S : Fn { using function::function; };

int main() {
    S f1( Fn{} );
    S f2(std::allocator_arg, std::allocator<void>{}, Fn{});
}

Add missed test in r276090.


#include <stdio.h>
#include <Halide.h>

using namespace Halide;

int main(int argc, char **argv) {
    Var x, y;

    Func pred("pred");
    pred(x, y) = x < y;

    Func selector("selector");
    selector(x, y) = select(pred(x, y), 1, 0);

    // Load a vector of 8 bools
    pred.compute_root();
    selector.compute_root().vectorize(x, 8);

    RDom range(0, 100, 0, 100);
    int32_t result = evaluate<int32_t>(lambda(sum(selector(range.x, range.y))));

    assert(result == 4950);

    printf("Success!\n");
    return 0;
}

Add a test to cover the bug that was fixed recently where bool in memory is a byte, but a bool vector inside llvm is bitpacked so loading 8 bools would load a byte, not 8-bytes, if vectorized.


#include "board.h"
#include <aery32/gpio.h>
#include <aery32/delay.h>
#include <aery32/intc.h>

using namespace aery;

void isrhandler(void)
{
	gpio_toggle_pin(LED);
	delay_ms(100); /* Reduce glitch */
	porta->ifrc = (1 << 0); /* Remember to clear the interrupt */
}

int main(void)
{
	init_board();

	/* GPIO pins 0-13 can be "wired" to int group 2, see datasheet p. 42 */
	gpio_init_pin(AVR32_PIN_PA00, GPIO_INPUT|GPIO_PULLUP|GPIO_INT_PIN_CHANGE);

	/* Init interrupt controller */
	intc_init();
	intc_register_isrhandler(
		&isrhandler, /* Function pointer to the ISR handler */
		2,           /* Interrupt group number */
		0            /* Priority level */
	);

	/* Enable interrupts globally */
	intc_enable_globally();

	for(;;) {
		/*
		 * Now try to connect PA00 to GND and then disconnecting it
		 * to let pull-up make the pin state high again. The LED should
		 * toggle on the pin change.
		 */

	}

	return 0;
}

Add new example: external interrupt on pin change


#include "condor_auth_passwd.h"
#include "classad/classad.h"
#include "classad/sink.h"
#include "match_prefix.h"
#include "CondorError.h"
#include "condor_config.h"

void print_usage(const char *argv0) {
	fprintf(stderr, "Usage: %s -identity USER@UID_DOMAIN [-token VALUE]\n\n"
		"Generates a derived key from the local master password and prints its contents to stdout.\n", argv0);
	exit(1);
}

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

	if (argc < 3) {
		print_usage(argv[0]);
	}

	std::string identity;
	std::string token;
	for (int i = 1; i < argc; i++) {
		if (is_dash_arg_prefix(argv[i], "identity", 2)) {
			i++;
			if (!argv[i]) {
				fprintf(stderr, "%s: -identity requires a condor identity as an argument", argv[0]);
				exit(1);
			}
			identity = argv[i];
		}
		else if (is_dash_arg_prefix(argv[i], "token", 1)) {
			i++;
			if (!argv[i]) {
				fprintf(stderr, "%s: -token requires an argument", argv[0]);
				exit(1);
			}
			token = argv[i];
		} else if (is_dash_arg_prefix(argv[i], "help", 1)) {
			print_usage(argv[0]);
			exit(1);
		} else {
			fprintf(stderr, "%s: Invalid command line argument: %s", argv[0], argv[i]);
			print_usage(argv[0]);
			exit(1);
		}
	}

	config();

	classad::ClassAd result_ad;
	CondorError err;
	if (!Condor_Auth_Passwd::generate_derived_key(identity, token, result_ad, &err)) {
		fprintf(stderr, "Failed to generate a derived key.\n");
		fprintf(stderr, "%s\n", err.getFullText(true).c_str());
		exit(2);
	}

	classad::ClassAdUnParser unp;
	std::string result;
	unp.Unparse(result, &result_ad);
	printf("%s\n", result.c_str());
	return 0;
}

Add executable allowing generation of the keyfile.


// https://leetcode.com/problems/delete-node-in-a-linked-list/
// Since node given is not a tail. We could do a trick: copy the contents of
// the next node, then connect to the next of next, delete the next node.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    void deleteNode(ListNode* node) {
        if (node->next != nullptr) {
            ListNode* tmp = node->next;
            node->val = tmp->val;
            node->next = tmp->next;
            delete tmp;
        } else {
            // we are assured node is not the tail.
            throw std::invalid_argument(to_string(reinterpret_cast<intptr_t>(node)) + " points to a tail.");
        }
    }
};

Add a solution to problem 237: Delete Node in a Linked List.


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

#include "base/rand_util.h"

#include <nacl/nacl_random.h>

#include "base/basictypes.h"
#include "base/logging.h"

namespace {

void GetRandomBytes(void* output, size_t num_bytes) {
  CHECK_EQ(0, nacl_secure_random_init());
  char* output_ptr = static_cast<char*>(output);
  while (num_bytes > 0) {
    size_t nread;
    const int error = nacl_secure_random(output_ptr, num_bytes, &nread);
    CHECK_EQ(error, 0);
    CHECK_LE(nread, num_bytes);
    output_ptr += nread;
    num_bytes -= nread;
  }
}

}  // namespace

namespace base {

// NOTE: This function must be cryptographically secure. http://crbug.com/140076
uint64 RandUint64() {
  uint64 result;
  GetRandomBytes(&result, sizeof(result));
  return result;
}

void RandBytes(void* output, size_t output_length) {
  GetRandomBytes(output, output_length);
}

}  // namespace base

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

#include "base/rand_util.h"

#include <nacl/nacl_random.h>

#include "base/basictypes.h"
#include "base/logging.h"

namespace {

void GetRandomBytes(void* output, size_t num_bytes) {
  char* output_ptr = static_cast<char*>(output);
  while (num_bytes > 0) {
    size_t nread;
    const int error = nacl_secure_random(output_ptr, num_bytes, &nread);
    CHECK_EQ(error, 0);
    CHECK_LE(nread, num_bytes);
    output_ptr += nread;
    num_bytes -= nread;
  }
}

}  // namespace

namespace base {

// NOTE: This function must be cryptographically secure. http://crbug.com/140076
uint64 RandUint64() {
  uint64 result;
  GetRandomBytes(&result, sizeof(result));
  return result;
}

void RandBytes(void* output, size_t output_length) {
  GetRandomBytes(output, output_length);
}

}  // namespace base

Stop using the nacl_secure_random_init() which is deprecated.


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

using namespace Halide;

int main(int argc, char **argv) {
    Var x, y, c;

    Func f, g;

    f(x, y) = x;
    g(x, y) = f(x-1, y+1) + f(x, y-1);
    f.store_root().compute_at(g, y).fold_storage(y, 2);

    Image<int> im = g.realize(100, 1000);

    printf("Should have gotten a bad fold!\n");
    return -1;
}

Add test for a bad fold.


/*
  Copyright © 2015 Jesse 'Jeaye' Wilkerson
  See licensing at:
    http://opensource.org/licenses/BSD-3-Clause

  File: test/src/value/main.cpp
  Author: Jesse 'Jeaye' Wilkerson
*/

#include <jeayeson/jeayeson.hpp>
#include <jest/jest.hpp>

#include "map/ctor.hpp"

int main()
{
  jest::worker const j{};
  return j();
}

Add the start of a new value test suite


#include <iostream>
using namespace std;

long merge(long *a, long start, long mid, long end)
{
	long sum = 0;
	long *temp = new long[end - start + 1];
	long i = mid, j = end;
	long k = end - start;
	while (i >= start && j >= mid + 1) {
		if (a[i] > a[j]) {
			temp[k--] = a[i--];
			sum += j - mid;
		}
		else {
			temp[k--] = a[j--];
		}
	}
	while (i >= start) {
		temp[k--] = a[i--];
	}
	while (j >= mid + 1) {
		temp[k--] = a[j--];
	}
	k = 0;
	for (long i = start; i <= end; i++) {
		a[i] = temp[k++];
	}
	return sum;
}

long count(long *a, long start, long end)
{
	long sum = 0;
	if (start < end) {
		long mid = start + (end - start) / 2;
		sum += count(a, start, mid);
		sum += count(a, mid + 1, end);
		sum += merge(a, start, mid, end);
	}
	return sum;
}

int main()
{
	int T;
	cin >> T;
	while (T--) {
		long n;
		cin >> n;
		long *a = new long[n];
		for (long i = 0; i < n; i++) {
			cin >> a[i];
		}
		cout << count(a, 0, n - 1) << endl;
	}
	return 0;
}

Add the solution to "Insertion Sort Advanced Analysis".


//128. Longest Consecutive Sequence
/*
*Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
*
*For example,
*Given [100, 4, 200, 1, 3, 2],
*The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
*
*Your algorithm should run in O(n) complexity.
*
*Tag: Array, Union Find
*
*Author: Linsen Wu
*/

#include "stdafx.h"
#include <vector>
#include <unordered_set>

using namespace std;

class Solution {
public:
    int longestConsecutive(vector<int> &nums) {
        if(nums.empty()) return 0;
        unordered_set<int> ht;
        for(int i=0; i<nums.size(); i++)
            ht.insert(nums[i]);

        int maxLen = 1;
        for(int i=0; i<nums.size(); i++) {
            if(ht.empty()) break;
            int curLen = 0;
            int curnums = nums[i];

            while(ht.count(curnums)) {
                ht.erase(curnums);
                curLen++;
                curnums++;
            }

            curnums = nums[i]-1;
            while(ht.count(curnums)) {
                ht.erase(curnums);
                curLen++;
                curnums--;
            }

            maxLen = max(maxLen, curLen);
        }

        return maxLen;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    return 0;
}

Add solution for 128 Longest Consecutive Sequence


#include<iostream>
#include<cstdlib>

using namespace std;

class Node{
	public:

	int data;
	Node *next;

	Node(){}

	Node(int d){
		data=d;
		next=NULL;
	}

	Node *insertNode(Node *head, int d){
		Node *np=new Node(d);
		Node *tmp=head;

		if(head==NULL)
			return np;
		else
			while(tmp->next)
				tmp=tmp->next;

		tmp->next=np;

		return head;
	}

	Node *deleteNode(Node *head, int pos){
		Node *tmp=head;
		int c=1;

		if(pos==1){
			head=tmp->next;
			free(tmp);
		}
		else{
			while(c!=pos-1){
				tmp=tmp->next;
				c++;
			}

			Node *tm=tmp->next;
			tmp->next=tmp->next->next;
			free(tm);
		}

		return head;
	}

	void displayList(Node *head){
		Node *tmp=head;

		cout<<"Elements of the list are:\n";
		while(tmp!=NULL){
			cout<<tmp->data<<"\n";
			tmp=tmp->next;
		}
	}
};

int main()
{
	int n,p,pos,d;
        Node np;
        Node *head=NULL;

        cout<<"Enter the size of linked list: ";
        cin>>n;

        for(int i=0;i<n;i++){
                        cout<<"\nEnter element "<<i+1<<": ";
                        cin>>p;
                        head=np.insertNode(head,p);
                }

        cout<<"\nEnter the position where you wish to delete the element: ";
        cin>>pos;

        if(pos>n)
                cout<<"\nSorry! The position you entered is out of bounds.\n";
        else
                head=np.deleteNode(head,pos);

        np.displayList(head);
}

Add code to delete node in linked list


/*
 * Copyright 2019 The Project Oak Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdlib.h>
#include "VmkModule1.h"
#include "verilated.h"
#include "verilated_vcd_c.h"

int main(int argc, char **argv) {
	Verilated::commandArgs(argc, argv);

	VmkModule1 *counter4 = new VmkModule1;

    VerilatedVcdC* vcd_trace = new VerilatedVcdC;

    Verilated::traceEverOn(true);
    counter4->trace(vcd_trace, 99);
    vcd_trace->open("counter4_tb.vcd");

    vluint64_t time = 0;

    counter4->CLK = 0;
    counter4->RST_N = 0;
    counter4->EN_count_value = 1;
    counter4->eval();
    vcd_trace->dump(time);

    counter4->CLK = 1;
    counter4->eval();
    time += 10;
    vcd_trace->dump(time);

    counter4->CLK = 0;
    counter4->RST_N = 1;
    time += 10;
    counter4->eval();
    vcd_trace->dump(time);

	for (int i = 1; i < 20; ++ i) {
		counter4->CLK = 1;
		counter4->eval();
        time += 10;
        vcd_trace->dump(time);
		counter4->CLK = 0;
		counter4->eval();
        time += 10;
        vcd_trace->dump(time);
	}
    vcd_trace->close();
    exit(EXIT_SUCCESS);
}

Add missing C++ test bench driver


// RUN: c-index-test -test-load-source-reparse 2 all %s -Xclang -add-plugin -Xclang clang-include-fixer -fspell-checking -Xclang -plugin-arg-clang-include-fixer -Xclang -input=%p/Inputs/fake_yaml_db.yaml 2>&1 | FileCheck %s

foo f;

// CHECK: yamldb_plugin.cpp:3:1: error: unknown type name 'foo'; did you mean 'foo'?
// CHECK: Number FIX-ITs = 1
// CHECK: FIX-IT: Replace [3:1 - 3:4] with "foo"
// CHECK: yamldb_plugin.cpp:3:1: note: Add '#include "foo.h"' to provide the missing declaration [clang-include-fixer]
// CHECK: Number FIX-ITs = 1
// CHECK: FIX-IT: Replace [3:1 - 3:4] with "#include "foo.h"

Add a test for the full round trip through libclang and the plugin.