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

[libc++] Add a test for PR14074

PR14074 was fixed in r165884, but no tests were added.

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


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

git-svn-id: 273b07cebdae5845b4a75aae04570b978db9eb50@190614 91177308-0d34-0410-b5e6-96231b3b80d8


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

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

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

[mg] 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

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

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

[Example] 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

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.

Add a test for PR3733.

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


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

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


#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

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] Test that static_assert is properly visited in liblcang

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


/**
 * 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

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

Implement queue using circular array

Signed-off-by: WajahatSiddiqui <3c3ea4adfdf19decee174766aef6add34b32b7f0@gmail.com>


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

If you ODR-use nullopt, you currently get a linker error.  Oops.

PiperOrigin-RevId: 172387553


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

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


#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

[WIP] test: 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

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

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.

Add missed test in r276090.

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


#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.

Former-commit-id: aedfad7bcbc248e545e7666d1a2b0cd74407c6a7


#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.

BUG=https://code.google.com/p/nativeclient/issues/detail?id=3881

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

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


#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.

Add test for a bad fold.

Former-commit-id: 9185511590542db408c42d13df49a5b7c5e8d2d1


/*
  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

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

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

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"

[include-fixer] Add a test for the full round trip through libclang and the plugin.

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


// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.

#include "mfem.hpp"
#include "catch.hpp"

using namespace mfem;

TEST_CASE("OperatorChebyshevSmoother", "[Chebyshev symmetry]")
{
   for (int order = 2; order < 5; ++order)
   {
      const int cheb_order = 2;

      Mesh mesh(4, 4, 4, Element::HEXAHEDRON, true);
      FiniteElementCollection *fec = new H1_FECollection(order, 3);
      FiniteElementSpace fespace(&mesh, fec);
      Array<int> ess_bdr(mesh.bdr_attributes.Max());
      ess_bdr = 1;
      Array<int> ess_tdof_list;
      fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list);

      BilinearForm aform(&fespace);
      aform.SetAssemblyLevel(AssemblyLevel::PARTIAL);
      aform.AddDomainIntegrator(new DiffusionIntegrator);
      aform.Assemble();
      OperatorPtr opr;
      opr.SetType(Operator::ANY_TYPE);
      aform.FormSystemMatrix(ess_tdof_list, opr);
      Vector diag(fespace.GetTrueVSize());
      aform.AssembleDiagonal(diag);

      Solver* smoother = new OperatorChebyshevSmoother(opr.Ptr(), diag, ess_tdof_list,
                                                       cheb_order);

      int n = smoother->Width();
      Vector left(n);
      Vector right(n);
      int seed = (int) time(0);
      left.Randomize(seed);
      right.Randomize(seed + 2);

      // test that x^T S y = y^T S x
      Vector out(n);
      out = 0.0;
      smoother->Mult(right, out);
      double forward_val = left * out;
      smoother->Mult(left, out);
      double transpose_val = right * out;

      double error = fabs(forward_val - transpose_val) / fabs(forward_val);
      std::cout << "Order " << order << " symmetry error: " << error << std::endl;
      REQUIRE(error < 1.e-13);

      delete smoother;
   }
}

Add unit test for symmetry of OperatorChebyshevSmoother


#include "gsl/gsl-lite.hpp"
#include "nonstd/span.hpp"

int main()
{
    const int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, };

    { using gsl::span;    span<const int> spn( arr ); }
    { using nonstd::span; span<const int> spn( arr ); }
}

// cl -nologo -EHsc -Dspan_FEATURE_MAKE_SPAN -I../include -I../../span-lite/include 03-gsl-span.cpp && 03-gsl-span
// g++ -Wall        -Dspan_FEATURE_MAKE_SPAN -I../include -I../../span-lite/include -o 03-gsl-span 03-gsl-span.cpp && 03-gsl-span

[skip ci] Add example that uses both gsl lite and span lite


/*
 * Part of HTTPP.
 *
 * Distributed under the 3-clause BSD licence (See LICENCE.TXT file at the
 * project root).
 *
 * Copyright (c) 2013 Thomas Sanchez.  All rights reserved.
 *
 */

#include "httpp/http/Utils.hpp"

#include <boost/algorithm/string.hpp>
#include <iostream>

namespace HTTPP
{
namespace HTTP
{

static const std::string CLOSE = "Close";
static const std::string KEEPALIVE = "Keep-Alive";

void setShouldConnectionBeClosed(const Request& request, Response& response)
{
    auto headers = request.getSortedHeaders();
    auto const& connection = headers["Connection"];

    if (boost::iequals(connection, CLOSE))
    {
        response.connectionShouldBeClosed(true);
        return;
    }

    if (boost::iequals(connection, KEEPALIVE))
    {
        response.connectionShouldBeClosed(false);
        return;
    }

    if (request.major == 1 && request.minor == 1)
    {
        response.connectionShouldBeClosed(false);
        return;
    }

    response.connectionShouldBeClosed(true);
    return;
}

} // namespace HTTP
} // namespace HTTPP

/*
 * Part of HTTPP.
 *
 * Distributed under the 3-clause BSD licence (See LICENCE.TXT file at the
 * project root).
 *
 * Copyright (c) 2013 Thomas Sanchez.  All rights reserved.
 *
 */

#include "httpp/http/Utils.hpp"

#include <boost/algorithm/string.hpp>
#include <iostream>

namespace HTTPP
{
namespace HTTP
{

static const std::string CLOSE = "Close";
static const std::string KEEPALIVE = "Keep-Alive";

void setShouldConnectionBeClosed(const Request& request, Response& response)
{
    auto headers = request.getSortedHeaders();
    auto const& connection = headers["Connection"];

    if (boost::iequals(connection, CLOSE))
    {
        response.connectionShouldBeClosed(true);
        return;
    }

    if (boost::iequals(connection, KEEPALIVE))
    {
        response.connectionShouldBeClosed(false);
        response.addHeader("Connection", KEEPALIVE);
        return;
    }

    if (request.major == 1 && request.minor == 1)
    {
        response.connectionShouldBeClosed(false);
        return;
    }

    response.connectionShouldBeClosed(true);
    return;
}

} // namespace HTTP
} // namespace HTTPP

Fix timeouts when using keepalive in apache bench.

Set `Connection: Keep-Alive` header in response when keepalive
connection requested. According to HTTP 1.1 it is not required, because
keepalive is the default, but ab does not comply to the standard here.
So lets set it explicitly.


#include <gtest/gtest.h>
#include <platform.h>

#include "util.h"

/** Pony code that parses, but is erroneous. Typically type check errors and
 * things used is invalid contexts.
 *
 * We build all the way up to and including code gen and check that we do not
 * assert, segfault, etc but that the build fails and at least one error is
 * reported.
 *
 * There is definite potential for overlap with other tests but this is also a
 * suitable location for tests which don't obviously belong anywhere else.
 */

class BadPonyTest : public PassTest
{
protected:
  void test(const char* src)
  {
    DO(test_error(src, "ir"));
    ASSERT_NE(0, get_error_count());
  }
};

// Cases from reported issues

TEST_F(BadPonyTest, DontCareInFieldType)
{
  // From issue #207
  const char* src =
    "class Abc\n"
    "  var _test1: (_)";

  DO(test(src));
}

TEST_F(BadPonyTest, ClassInOtherClassProvidesList)
{
  // From issue #218
  const char* src =
    "class Named\n"
    "class Dog is Named\n"

    "actor Main\n"
    "  new create(env: Env) =>\n"
    "    None";

  DO(test(src));
}

TEST_F(BadPonyTest, TypeParamMissingForTypeInProvidesList)
{
  // From issue #219
  const char* src =
    "trait Bar[A]\n"
    "  fun bar(a: A) =>\n"
    "    None\n"

    "trait Foo is Bar // here also should be a type argument, like Bar[U8]\n"
    "  fun foo() =>\n"
    "    None\n"

    "actor Main\n"
    "  new create(env: Env) =>\n"
    "    None";

  DO(test(src));
}

TEST_F(BadPonyTest, DontCareInIntLiteralType)
{
  // From issue #222
  const char* src =
    "actor Main\n"
    "  new create(env: Env) =>\n"
    "    let crashme: (_, I32) = (4, 4)";

  DO(test(src));
}

Add unit tests for parsable, but erroneous programs


#include <cassert>
#include <vector>
using namespace std;

class WidgetRepairs {
public:
  int days(vector<int> arrs, int numPerDay) {
    int ans = 0;
    int stack = 0;
    for (int d : arrs) {
      stack += d;
      if (stack > 0) {
        ans++;
      }
      stack -= numPerDay;
      if (stack < 0) {
        stack = 0;
      }
    }
    while (stack > 0) {
      stack -= numPerDay;
      ans++;
    }
    return ans;
  }
};

int main()
{
  WidgetRepairs wr;
  vector<int> v1 = { 10, 0, 0, 4, 20 };
  assert (wr.days(v1, 8) == 6);
  return 0;
}

Solve SRM 150, Div 2, Problem WidgetRepairs


//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Baozeng Ding <sploving1@gmail.com>
// author:  Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//------------------------------------------------------------------------------

#include "cling/Interpreter/RuntimeExceptions.h"

#include "clang/Basic/SourceLocation.h"
#include "clang/Sema/Sema.h"
#include "clang/Sema/SemaDiagnostic.h"

namespace cling {
  namespace runtime {
    cling_null_deref_exception::cling_null_deref_exception(
      void* Loc, clang::Sema* S) : m_Location(*(unsigned *)Loc), m_Sema(S){}

    cling_null_deref_exception::~cling_null_deref_exception() {}

    void cling_null_deref_exception::what() throw() {
        clang::DiagnosticsEngine& Diag = m_Sema->getDiagnostics();
        Diag.Report(clang::SourceLocation::getFromRawEncoding(m_Location),
                                              clang::diag::warn_null_arg);
    }
  } // end namespace runtime
} // end namespace cling

Add forgotten to commit file.

Add forgotten to commit file.


// lower_bound/upper_bound example
#include <iostream>     // cout
#include <algorithm>    // lower_bound, upper_bound, sort
#include <vector>       // vector
using namespace std;
int main () {
  int myints[] = {10,20,30,30,20,10,10,20};
  vector<int> v(myints,myints+8);           // 10 20 30 30 20 10 10 20

  sort (v.begin(), v.end());                // 10 10 10 20 20 20 30 30

  vector<int>::iterator low,up;
  low=lower_bound (v.begin(), v.end(), 20); //          ^
  up= upper_bound (v.begin(), v.end(), 20); //                   ^

  cout << "lower_bound at position " << (low- v.begin()) << '\n';
  cout << "upper_bound at position " << (up - v.begin()) << '\n';
  /*
lower_bound at position 3
upper_bound at position 6
   *

  return 0;
}

Add useful script for lower and upper bound over an array.


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

using namespace Halide;

int main(int argc, char **argv) {
    Func f, g;
    Var x;

    f(x) = x;
    g(x) = f(x) + f(2*x);

    g.gpu_tile(x, 16);
    f.compute_at(g, Var::gpu_blocks()).gpu_threads(x);

    // The amount of shared memory required varies with x

    Image<int> out = g.realize(100);
    for (int x = 0; x < 100; x++) {
        int correct = 3*x;
        if (out(x) != correct) {
            printf("out(%d) = %d instead of %d\n",
                   x, out(x), correct);
            return -1;
        }
    }

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

Test for shared allocations and thread blocks that depend on blockidx

Former-commit-id: c34c1c917c975e513556b6475c4b4fba2e1a67b3


//--------------------------------------------------------------------------//
/// Copyright (c) 2018 Milos Tosic. All Rights Reserved.                   ///
/// License: http://www.opensource.org/licenses/BSD-2-Clause               ///
//--------------------------------------------------------------------------//

#include <rbase_test_pch.h>
#include <rbase/inc/stringview.h>

using namespace rtm;

SUITE(rbase)
{
	TEST(string)
	{
		char buffer[128];
		const char* testString = "This is the test string";

		CHECK(23 == strLen(testString));

		strlCpy(buffer, 128, testString);

		CHECK(0 == strCmp(buffer, testString));

		strToUpper(buffer);
		CHECK(0 == strCmp(buffer, "THIS IS THE TEST STRING"));
		CHECK(0 == striCmp(buffer, testString));

		strToLower(buffer);
		CHECK(0 == strCmp(buffer, "this is the test string"));
		CHECK(0 == striCmp(buffer, testString));

		CHECK(0 == striCmp(strStr(buffer, "test"), "test string"));

		StringTemp<> fs(testString);
		String ds = fs;
		StringView vs(ds.data(), ds.length());

		CHECK(0 == strCmp(vs, testString));

		CHECK(true);
	}
}

Add basic string unit test

Add basic string unit test


#include <xpcc/architecture/platform.hpp>
#include <xpcc/debug/logger.hpp>

using namespace xpcc::atmega;

// Create a new UART object and configure it to a baudrate of 115200
Uart0 uart(115200);
xpcc::IODeviceWrapper< Uart0 > loggerDevice(uart);

// Set all four logger streams to use the UART
xpcc::log::Logger xpcc::log::debug(loggerDevice);
xpcc::log::Logger xpcc::log::info(loggerDevice);
xpcc::log::Logger xpcc::log::warning(loggerDevice);
xpcc::log::Logger xpcc::log::error(loggerDevice);

// Set the log level
#undef	XPCC_LOG_LEVEL
#define	XPCC_LOG_LEVEL xpcc::log::DEBUG

int
main()
{
	// Enable interrupts, this is needed for every buffered UART
	sei();

	// Use the logging streams to print some messages.
	// Change XPCC_LOG_LEVEL above to enable or disable these messages
	XPCC_LOG_DEBUG   << "debug"   << xpcc::endl;
	XPCC_LOG_INFO    << "info"    << xpcc::endl;
	XPCC_LOG_WARNING << "warning" << xpcc::endl;
	XPCC_LOG_ERROR   << "error"   << xpcc::endl;

	while (1)
	{
	}
}

#include <xpcc/architecture/platform.hpp>
#include <xpcc/debug/logger.hpp>

using namespace xpcc::atmega;
typedef xpcc::avr::SystemClock clock;

// Create a new UART object and configure it to a baudrate of 115200
Uart0 uart;
xpcc::IODeviceWrapper< Uart0 > loggerDevice(uart);

// Set all four logger streams to use the UART
xpcc::log::Logger xpcc::log::debug(loggerDevice);
xpcc::log::Logger xpcc::log::info(loggerDevice);
xpcc::log::Logger xpcc::log::warning(loggerDevice);
xpcc::log::Logger xpcc::log::error(loggerDevice);

// Set the log level
#undef	XPCC_LOG_LEVEL
#define	XPCC_LOG_LEVEL xpcc::log::DEBUG

int
main()
{
    GpioOutputD1::connect(Uart0::Tx);
    GpioInputD0::connect(Uart0::Rx);
    Uart0::initialize<clock, 115200>();

	// Enable interrupts, this is needed for every buffered UART
	sei();

	// Use the logging streams to print some messages.
	// Change XPCC_LOG_LEVEL above to enable or disable these messages
	XPCC_LOG_DEBUG   << "debug"   << xpcc::endl;
	XPCC_LOG_INFO    << "info"    << xpcc::endl;
	XPCC_LOG_WARNING << "warning" << xpcc::endl;
	XPCC_LOG_ERROR   << "error"   << xpcc::endl;

	while (1)
	{
	}
}

Fix Uart in Logger example

Fix Uart in Logger example


// Copyright (c) 2015 The Gulden developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#ifdef __APPLE__
#include <TargetConditionals.h>
    #import "BRMerkleBlock.h"
#endif
#include "diff_common.h"
#include "diff_delta.h"
#include "diff_old.h"
#ifdef BUILD_IOS
    #import "BRMerkleBlock.h"
#endif

unsigned int GetNextWorkRequired(const INDEX_TYPE indexLast, const BLOCK_TYPE block, unsigned int nPowTargetSpacing, unsigned int nPowLimit)
{
    static int nDeltaSwitchoverBlock = DIFF_SWITCHOVER(350000, 1, 250000);
    static int nOldDiffSwitchoverBlock = DIFF_SWITCHOVER(500, 500, 260000);

    if (INDEX_HEIGHT(indexLast)+1 >= nOldDiffSwitchoverBlock)
    {
        if (INDEX_HEIGHT(indexLast)+1 >= nDeltaSwitchoverBlock)
        {
            return GetNextWorkRequired_DELTA(indexLast, block, nPowTargetSpacing, nPowLimit, nDeltaSwitchoverBlock);
        }
        else
        {
            return 524287999;
        }
    }
    return diff_old(INDEX_HEIGHT(indexLast)+1);
}

Add file missed in previous commit.

Add file missed in previous commit.


#include <iostream>
#include <gtest/gtest.h>
#include "ell.hpp"
#include "exceptions/cancelled.hpp"

TEST(test_task, simple_yield)
{
  using namespace ell;
  EventLoop loop;

  int count    = 0;
  bool has_run = false;

  auto task2 = loop.call_soon([&]()
                              {
                                for (int i = 0; i < 5; ++i)
                                {
                                  ASSERT_TRUE(has_run); // make sure that has run first.
                                  count--;
                                  ASSERT_EQ(0, count);
                                  yield();
                                }
                              });
  auto task = loop.call_soon([&]()
                             {
                               for (int i = 0; i < 5; ++i)
                               {
                                 has_run = true;
                                 ASSERT_EQ(0, count);
                                 count++;
                                 yield();
                               }
                             });
  loop.run_until_complete(task);
  ASSERT_EQ(0, count);
}

TEST(test_task, chained)
{
  using namespace ell;

  EventLoop loop;
  int count = 0;
  auto task = loop.call_soon([&]()
                             {
                               ASSERT_EQ(0, count);
                               yield([&]()
                                     {
                                       ASSERT_EQ(0, count);
                                       count++;

                                       yield([&]()
                                             {
                                               ASSERT_EQ(1, count);
                                               count++;

                                               yield([&]()
                                                     {
                                                       ASSERT_EQ(2, count);
                                                       count++;
                                                       yield();
                                                     });
                                             });
                                     });
                             });
  loop.run_until_complete(task);
  ASSERT_EQ(3, count);
}

int main(int ac, char **av)
{
  ell::initialize_logger();
  ::testing::InitGoogleTest(&ac, av);
  return RUN_ALL_TESTS();
}

Add some tests for tasks.

Add some tests for tasks.


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

// UNSUPPORTED: c++98, c++03

// RUN: %build -fno-exceptions
// RUN: %run

// RUN: %build
// RUN: %run

// UNSUPPORTED: c++98, c++03

// <vector>

// Test that vector won't try to call the move constructor when resizing if
// the class has a deleted move constructor (but a working copy constructor).

#include <vector>

class CopyOnly {
public:
  CopyOnly() { }

  CopyOnly(CopyOnly&&) = delete;
  CopyOnly& operator=(CopyOnly&&) = delete;

  CopyOnly(const CopyOnly&) = default;
  CopyOnly& operator=(const CopyOnly&) = default;
};

int main() {
    std::vector<CopyOnly> x;
    x.emplace_back();

    CopyOnly c;
    x.push_back(c);

    return 0;
}

[libc++] Add a test for resizing of a vector with copy-only elements

See https://reviews.llvm.org/D62228#1658620

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


/**
 * \file
 * \brief board::lowLevelInitialization() implementation for NUCLEO-F429ZI
 *
 * \author Copyright (C) 2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include "distortos/board/lowLevelInitialization.hpp"

namespace distortos
{

namespace board
{

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

void lowLevelInitialization()
{

}

}	// namespace board

}	// namespace distortos

Add empty board::lowLevelInitialization() for NUCLEO-F429ZI


# include <iostream>
# include <algorithm>

using namespace std;

bool isAnagram(string str1, string str2) {
	if str1.size() != str2.size()
		return false;
	sort(str1.begin(), str1.end());
	sort(str2.begin(), str2.end());
	return str1 == str2;
}

int main() {
	string str1, str2;
	cout << "Enter first string" << endl;
	cin >> str1;
	cout << "Enter second string" << endl;
	cin >> str2;

	cout << "Strings are anagram: " << isAnagram(str1, str2) << endl;

	return 0;
}

Check if strings are anagram

Check if strings are anagram


extern "C"{
    #include "global_fakes.h"
}
#include <gtest/gtest.h>

DEFINE_FFF_GLOBALS;

class FFFTestSuite: public testing::Test
{
public:
    void SetUp()
    {
        RESET_FAKE(voidfunc1);
        RESET_FAKE(voidfunc2);
        RESET_FAKE(longfunc0);
        RESET_HISTORY();
    }
};

#include "test_cases.include"

Test suite for global fakes from a cpp context


#include <bits/stdc++.h>

#define MAX ...

vector<int> G[MAX];

/* this array may be initialized with false
    eg.: memset(visited, false, sizeof visited) */
bool visited[MAX];

void dfs(int at) {
    if(visited[at])
        return;
    visited[at] = true;
    for (int i= 0; i< (int)G[at].size(); i++)
        dfs(G[at][i]);
}

Add dfs implementation in c++

Add dfs implementation in c++


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

#include "test.hh"

namespace pegtl
{
   void unit_test()
   {
      verify_analyze< not_at< eof > >( __LINE__, __FILE__, false );
      verify_analyze< not_at< any > >( __LINE__, __FILE__, false );

      verify_rule< not_at< eof > >( __LINE__, __FILE__,  "", result_type::LOCAL_FAILURE, 0 );
      verify_rule< not_at< eof > >( __LINE__, __FILE__,  " ", result_type::SUCCESS, 1 );
      verify_rule< not_at< any > >( __LINE__, __FILE__,  "", result_type::SUCCESS, 0 );
      verify_rule< not_at< any > >( __LINE__, __FILE__,  "a", result_type::LOCAL_FAILURE, 1 );
      verify_rule< not_at< any > >( __LINE__, __FILE__,  "aa", result_type::LOCAL_FAILURE, 2 );
      verify_rule< not_at< any > >( __LINE__, __FILE__,  "aaaa", result_type::LOCAL_FAILURE, 4 );
   }

} // pegtl

#include "main.hh"

Fix wrong renames detected by git.

Fix wrong renames detected by git.


// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/settings/cros_settings.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chromeos/settings/cros_settings_names.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, ChromeOSInfoPrivateTest) {
  // Set the initial timezone to a different one that JS function
  // timezoneSetTest() will attempt to set.
  base::StringValue initial_timezone("America/Los_Angeles");
  chromeos::CrosSettings::Get()->Set(chromeos::kSystemTimezone,
                                     initial_timezone);

  ASSERT_TRUE(RunComponentExtensionTest("chromeos_info_private")) << message_;
}

// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/settings/cros_settings.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chromeos/settings/cros_settings_names.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_ChromeOSInfoPrivateTest) {
  // Set the initial timezone to a different one that JS function
  // timezoneSetTest() will attempt to set.
  base::StringValue initial_timezone("America/Los_Angeles");
  chromeos::CrosSettings::Get()->Set(chromeos::kSystemTimezone,
                                     initial_timezone);

  ASSERT_TRUE(RunComponentExtensionTest("chromeos_info_private")) << message_;
}

Disable ChromeOSInfoPrivateTest due to DST failure.

TBR=zelidrag@chromium.org
BUG=314623

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

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


#include<bits/stdc++.h>
using namespace std;

// Returns the longest repeating non-overlapping substring
string longestRepeatedSubstring(string str){
    int n = str.length();
    int LCSRe[n+1][n+1];
    // Setting all to 0
    memset(LCSRe, 0, sizeof(LCSRe));
    string res; // To store result
    int res_length  = 0; // To store length of result

    // building table in bottom-up manner
    int i, index = 0;
    for (i=1; i<=n; i++){
      for (int j=i+1; j<=n; j++){
        // (j-i) > LCSRe[i-1][j-1] to remove
        if (str[i-1] == str[j-1] &&
          LCSRe[i-1][j-1] < (j - i)){
          LCSRe[i][j] = LCSRe[i-1][j-1] + 1;
          if (LCSRe[i][j] > res_length){
            res_length = LCSRe[i][j];
            index = max(i, index);
          }
        }
        else
          LCSRe[i][j] = 0;
      }
    }
    if (res_length > 0){
  		cout <<  (index  - res_length +1)<<endl;
  	  for (i = index - res_length + 1; i <= index; i++)
          res.push_back(str[i-1]);
		}
    return res;
}

// Driver program to test the above function
int main(){
    string str = "hello,p23puoeouhello,oues";
    cout << longestRepeatedSubstring(str); //hello,
    return 0;
}

Add algorithm to find Longest Repeated substring withot overlapping.


#include<iostream>

using namespace std;

class Node{
        public:
                int data;
                Node *next;

                Node(){}

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

                Node *insertElement(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;
                }

		void displayFromEnd(Node *head){

			if(!head->next){
				cout<<head->data<<"\n";
				return;
			}

			displayFromEnd(head->next);
			cout<<head->data<<"\n";
		}
};

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.insertElement(head,p);
                }

	if(!head)
		cout<<"Sorry! No elements in the list. :(\n";
	else{
		cout<<"The elements accessed from the end are: \n";
		np.displayFromEnd(head);
	}
}

Print elements from the end of linked list


#include <test.hpp>

TEST_CASE("skip") {

    SECTION("check that skip skips the right amount of bytes") {

        std::vector<std::string> filenames = {
            "boolean/data-true",
            "boolean/data-false",
            "bytes/data-one",
            "bytes/data-string",
            "bytes/data-binary",
            "double/data-zero",
            "double/data-pos",
            "double/data-neg",
            "float/data-zero",
            "float/data-pos",
            "float/data-neg",
            "fixed32/data-zero",
            "fixed32/data-max-uint",
            "fixed32/data-min-uint",
            "fixed64/data-zero",
            "fixed64/data-max-uint",
            "fixed64/data-min-uint",
            "sfixed32/data-zero",
            "sfixed32/data-max-int",
            "sfixed32/data-min-int",
            "sfixed64/data-zero",
            "sfixed64/data-max-int",
            "sfixed64/data-min-int",
            "message/data-message",
            "string/data-one",
            "string/data-string",
            "int32/data-zero",
            "int32/data-pos",
            "int32/data-neg",
            "int32/data-min",
            "int32/data-max",
            "int64/data-zero",
            "int64/data-pos",
            "int64/data-neg",
            "int64/data-min",
            "int64/data-max",
            "sint32/data-zero",
            "sint32/data-pos",
            "sint32/data-neg",
            "sint32/data-min",
            "sint32/data-max",
            "sint64/data-zero",
            "sint64/data-pos",
            "sint64/data-neg",
            "sint64/data-min",
            "sint64/data-max",
            "uint32/data-zero",
            "uint32/data-pos",
            "uint32/data-max",
            "uint64/data-zero",
            "uint64/data-pos",
            "repeated/data-one",
        };

        for (const auto& filename : filenames) {
            std::string buffer = get_file_data(std::string("test/t/") + filename + ".pbf");

            mapbox::util::pbf item(buffer.data(), buffer.size());

            REQUIRE(item.next());
            item.skip();
            REQUIRE(!item);
        }

    }

}

Add tests of skip() function.

Add tests of skip() function.


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

using namespace Halide;

// FIXME: We should use a proper framework for this. See issue #898
void h_assert(bool condition, const char *msg) {
    if (!condition) {
        printf("FAIL: %s\n", msg);
        abort();
    }
}

int main() {
    Halide::Func f;
    Halide::Var x, y;

    // This should throw an error because downcasting will loose precision which
    // should only happen if the user explicitly asks for it
    f(x, y) = 0.1f;

    // Use JIT for computation
    Image<float16_t> simple = f.realize(10, 3);

    // Assert some basic properties of the image
    h_assert(simple.extent(0) == 10, "invalid width");
    h_assert(simple.extent(1) == 3, "invalid height");
    h_assert(simple.min(0) == 0, "unexpected non zero min in x");
    h_assert(simple.min(1) == 0, "unexpected non zero min in y");
    h_assert(simple.channels() == 1, "invalid channels");
    h_assert(simple.dimensions() == 2, "invalid number of dimensions");

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

Add test case to check that implicit downcasting when a Func returns
float (32 bits) but the buffer has type float16_t (16 bits) is an error.

Former-commit-id: ce812a50d7cf6bd13e7c4a2592f4f2a2484ce381


#include <iostream>
using std::cin;
using std::cout;

int *A;
int sum;

void f(int i) {
  A[i] = i * 3;
}

void g(int i) {
  sum += A[i];
}

int main() {
  unsigned n;
  cin >> n;

  A = new int[n];
  sum = 0;

  for (unsigned i = 0; i < n; ++i) {
    f(i);
    g(i);
  }

  cout << sum << '\n';
  return 0;
}

Add cross-call example (case 2)

Add cross-call example (case 2)


// RUN: %clang_cc1 %s -chain-include %s -ast-dump | FileCheck -strict-whitespace %s

// CHECK: TranslationUnitDecl 0x{{.+}} <<invalid sloc>> <invalid sloc>
// CHECK: `-<undeserialized declarations>

Add test for current AST dump behavior

[ASTDump] Add test for current AST dump behavior

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


#include <iostream>

using namespace std;

struct Base {
    void bar(int i) {
        cout << "Base::bar(int)" << endl;
    }
protected:
    int ival = 0;
};

struct Derived1 : virtual public Base {
    void bar(char c) {
        cout << "Derived1::bar(char)" << endl;
    }
    void foo(char c) {
        cout << "Derived1::foo(char)" << endl;
    }
protected:
    char cval = 'c';
};
struct Derived2 : virtual public Base {
    void foo(int i) {
        cout << "Derived2::foo(int)" << endl;
    }
protected:
    int ival = 1;
    char cval = 'd';
};
class VMI : public Derived1, public Derived2 {
public:
    void access_ival() {
        cout << Base::ival << endl;//without Base::, it will be Derived2::ival
    }

    void access_cval() {
        cout << Derived1::cval << endl;//both cval need ::
    }
};

int main() {
    VMI vmi;
    vmi.access_ival();
    vmi.access_cval();
    vmi.Derived1::foo('c');//both need ::
    vmi.bar(1);//call Derived1::bar()
    vmi.bar('c');//call Derived1::bar()
    vmi.Base::bar(1);

    return 0;
}

Add solution for chapter 18, test 28

Add solution for chapter 18, test 28


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

#include "ui/message_center/message_center_util.h"

#include "base/command_line.h"
#include "ui/message_center/message_center_switches.h"

namespace message_center {

bool IsRichNotificationEnabled() {
  return CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnableRichNotifications);
}

}  // namespace message_center

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

#include "ui/message_center/message_center_util.h"

#include "base/command_line.h"
#include "ui/message_center/message_center_switches.h"

namespace message_center {

bool IsRichNotificationEnabled() {
#if defined(OS_WIN) && defined(USE_AURA)
  return false;
#else
  return CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnableRichNotifications);
#endif
}

}  // namespace message_center

Fix for crash trying to deference ash::Shell::message_center()

Because we don't really have a operational ash::shell in
windows 7 or earlier.

So we need to default to the non-rich one

BUG=178429
TEST=see bug
Review URL: https://codereview.chromium.org/12328129

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


/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

struct GrGLInterface;

const GrGLInterface* GrGLDefaultInterface() {
    return NULL;
}

/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "GrGLInterface.h"

const GrGLInterface* GrGLDefaultInterface() {
    return NULL;
}

Include GrGLInterface.h instead of forward declaring, since we have to get NULL defined anyway.

git-svn-id: e8541e15acce502a64c929015570ad1648e548cd@2280 2bbb7eff-a529-9590-31e7-b0007b416f81


/*
* DTLS Hello Verify Request
* (C) 2012 Jack Lloyd
*
* Released under the terms of the Botan license
*/

#include <botan/internal/tls_messages.h>
#include <botan/lookup.h>
#include <memory>

namespace Botan {

namespace TLS {

Hello_Verify_Request::Hello_Verify_Request(const MemoryRegion<byte>& buf)
   {
   if(buf.size() < 3)
      throw Decoding_Error("Hello verify request too small");

   if(buf[0] != 254 || (buf[1] != 255 && buf[1] != 253))
      throw Decoding_Error("Unknown version from server in hello verify request");

   m_cookie.resize(buf.size() - 2);
   copy_mem(&m_cookie[0], &buf[2], buf.size() - 2);
   }

Hello_Verify_Request::Hello_Verify_Request(const MemoryVector<byte>& client_hello_bits,
                                           const std::string& client_identity,
                                           const SymmetricKey& secret_key)
   {
   std::auto_ptr<MessageAuthenticationCode> hmac(get_mac("HMAC(SHA-256)"));
   hmac->set_key(secret_key);

   hmac->update_be(client_hello_bits.size());
   hmac->update(client_hello_bits);
   hmac->update_be(client_identity.size());
   hmac->update(client_identity);

   m_cookie = hmac->final();
   }

MemoryVector<byte> Hello_Verify_Request::serialize() const
   {
   /* DTLS 1.2 server implementations SHOULD use DTLS version 1.0
      regardless of the version of TLS that is expected to be
      negotiated (RFC 6347, section 4.2.1)
   */

   Protocol_Version format_version(Protocol_Version::TLS_V11);

   MemoryVector<byte> bits;
   bits.push_back(format_version.major_version());
   bits.push_back(format_version.minor_version());
   bits += m_cookie;
   return bits;
   }

}

}

Add missing source for DTLS hello verify


extern "C" {
#include <wiringPi.h>
}

#include <signal.h>
#include <errno.h>

#include <iostream>
#include <thread>
#include <chrono>

void gpio4Callback(void) {
    std::cout << "Hello" << std::endl;
}

int main(){
    sigset_t set;
    int sig;
    int *sigptr = &sig;
    int ret_val;
    sigemptyset(&set);
    sigaddset(&set, SIGQUIT);
    sigaddset(&set, SIGINT);
    sigaddset(&set, SIGTERM);
    sigaddset(&set, SIGUSR1);
    sigprocmask( SIG_BLOCK, &set, NULL );
    std::cout << "Waiting for a signal or button\n";

    wiringPiSetup () ;

    wiringPiISR (4, INT_EDGE_FALLING, &gpio4Callback) ;

    ret_val = sigwait(&set,sigptr);
    if(ret_val == -1)
        perror("sigwait failed\n");
    else {
        std::cout << "sigwait returned with sig: " << *sigptr << std::endl;
    }

    return 0;
}

Add gpio interrupt plus signal wait

Add gpio interrupt plus signal wait


#include <iostream>
#include <limits>

using namespace std;

template <typename T1, typename T2>
auto sum(T1 a, T2 b) -> decltype(a + b) {
    return a + b;
}

int main() {
    char c1 = 127;
    char c2 = 127;
    long lng = numeric_limits<long>::max() - 200;
    cout << sum(c1, c2) << endl;
    cout << sum(c2, lng) << endl;
    return 0;
}

Add solution for chapter 16 test 41

Add solution for chapter 16 test 41


#include <iostream>
using namespace std;

int main(){

  string animals[][3] = {
    {"fox", "dog", "cat"},
    {"mouse", "squirrel", "parrot"}
  };

  for(int i = 0; i < sizeof(animals)/sizeof(animals[0]); i++){
    for(int j = 0; j < sizeof(animals[0])/sizeof(string); j++){
      cout << animals[i][j] << " " << flush;
    }
    cout << endl;
  }

  return 0;
}

Implement For Loop Using Sizeof Example

Implement For Loop Using Sizeof Example


class Solution {
public:
    long long minimalKSum(vector<int>& nums, int k) {
        auto cmp = [](int left, int right){
            return left > right;
        };
        std::priority_queue<int, std::vector<int>, decltype(cmp)> q(cmp);
        for (const auto& num : nums) {
            q.emplace(std::move(num));
        }
        // while (!q.empty()) {
        //     std::cout << q.top() << std::endl;
        //     q.pop();
        // }
        int64_t ret = 0;
        int start = 0;
        while (!q.empty()) {
            int cur = q.top();
            q.pop();
            if (cur == start) continue;
            int count = cur - start - 1;
            if (count == 0) {
                start = cur;
                continue;
            }
            if (count >= k) {
                ret += int64_t((start + 1 + start + k)) * int64_t(k) / 2;
                return ret;
            } else {
                ret += int64_t((start + cur)) * int64_t(count) / 2;
                k -= count;
                start = cur;
            }
        }
        if (k > 0) {
            ret += int64_t((start + 1 + start + k)) * int64_t(k) / 2;
        }
        return ret;
    }
};

Append K Integers With Minimal Sum

Append K Integers With Minimal Sum


// Copyright (c) 2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "wallet/test/wallet_test_fixture.h"

#include "rpc/server.h"
#include "wallet/db.h"
#include "wallet/wallet.h"

CWallet *pwalletMain;

WalletTestingSetup::WalletTestingSetup(const std::string& chainName):
    TestingSetup(chainName)
{
    bitdb.MakeMock();

    bool fFirstRun;
    std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, "wallet_test.dat"));
    pwalletMain = new CWallet(std::move(dbw));
    pwalletMain->LoadWallet(fFirstRun);
    RegisterValidationInterface(pwalletMain);

    RegisterWalletRPCCommands(tableRPC);
}

WalletTestingSetup::~WalletTestingSetup()
{
    UnregisterValidationInterface(pwalletMain);
    delete pwalletMain;
    pwalletMain = nullptr;

    bitdb.Flush(true);
    bitdb.Reset();
}

// Copyright (c) 2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "wallet/test/wallet_test_fixture.h"

#include "rpc/server.h"
#include "wallet/db.h"
#include "wallet/wallet.h"

std::unique_ptr<CWallet> pwalletMain;

WalletTestingSetup::WalletTestingSetup(const std::string& chainName):
    TestingSetup(chainName)
{
    bitdb.MakeMock();

    bool fFirstRun;
    std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, "wallet_test.dat"));
    pwalletMain = std::unique_ptr<CWallet>(new CWallet(std::move(dbw)));
    pwalletMain->LoadWallet(fFirstRun);
    RegisterValidationInterface(pwalletMain.get());

    RegisterWalletRPCCommands(tableRPC);
}

WalletTestingSetup::~WalletTestingSetup()
{
    UnregisterValidationInterface(pwalletMain.get());
    pwalletMain.reset();

    bitdb.Flush(true);
    bitdb.Reset();
}

Use unique_ptr for pwalletMain (CWallet)


#include <sstream>
#include <gtest/gtest.h>
#include "portsocket.h"

#define TEST_CLASS PortSocketTest

class TEST_CLASS : public testing::Test {
protected:
    class DummySocket : PortSocket {
    public:
        DummySocket(bool *sentinel) : sentinel(sentinel) { *sentinel = true; }
        int read(PortType port, SizeType len, void *buffer) { }
        int write(PortType port, SizeType len, const void *buffer) { }
        ~DummySocket() { *sentinel = false; }
    private:
        bool *sentinel;
    };
};

TEST_F(TEST_CLASS, TestConstructDestruct) {
    bool sentinel = false;
    {
        DummySocket sock(&sentinel);
        ASSERT_EQ(sentinel, true) << "Failed to construct instance";
    }
    ASSERT_EQ(sentinel, false) << "Failed to destruct instance";
}

Create dumb test for better coverage

Create dumb test for better coverage


// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm -o - %s -std=c++14 | FileCheck %s

template<typename> struct custom_copy_ctor {
  custom_copy_ctor() = default;
  custom_copy_ctor(custom_copy_ctor const &) {}
};

// CHECK: define {{.*}} @_ZN16custom_copy_ctorIvEC2ERKS0_(
void pr22354() {
  custom_copy_ctor<void> cc;
  [cc](auto){}(1);
}

PR22354: Add a test that we emit copy-ctors for captures in generic lambdas.

The bug was fixed by r235921.

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


#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <cerrno>
#include <cfloat>
#include <ciso646>
#include <climits>
#include <clocale>
#include <cmath>
#include <complex>
#include <csetjmp>
#include <csignal>
#include <cstdarg>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <cwchar>
#include <cwctype>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <strstream>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>

Add an input file that includes all standard C++ headers

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


#include <iostream>

using namespace std;

struct Node {
  int data;

  Node* left;
  Node* right;

  Node(int data, Node* left = nullptr, Node* right = nullptr)
    : data(data), left(left), right(right) {}
};

class BinaryTree {
  Node* root;

  BinaryTree(Node* node) {
    root = copyNode(node);
  }

  Node* copyNode(Node* node) {
    if (node == nullptr)
      return node;
    return new Node(node->data,
                    copyNode(node->left),
                    copyNode(node->right));
  }

  void eraseNode(Node* node) {
    if (node != nullptr) {
      eraseNode(node->left);
      eraseNode(node->right);
      delete node;
    }
  }

  void assignFrom(Node*& to, Node*& from) {
    Node* toDel = to;
    to = from;
    from = nullptr;
    eraseNode(toDel);
  }

public:
  BinaryTree() : root(nullptr) {}

  BinaryTree(int rootData,
             BinaryTree&& left = BinaryTree(),
             BinaryTree&& right = BinaryTree()) {
    root = new Node(rootData);
    assignFrom(root->left, left.root);
    assignFrom(root->right, right.root);
  }

  BinaryTree(const BinaryTree& other) {
    root = copyNode(other.root);
  }

  BinaryTree& operator=(const BinaryTree& other) {
    if (this != &other) {
      eraseNode(root);
      root = copyNode(other.root);
    }
  }

  ~BinaryTree() {
    eraseNode(root);
  }

  bool empty() const { return root == nullptr; }

  BinaryTree leftTree() const {
    return BinaryTree(root->left);
  }

  BinaryTree rightTree() const {
    return BinaryTree(root->right);
  }

  int getRoot() const {
    return root->data;
  }

  friend ostream& operator<<(ostream& os, const BinaryTree& bt) {
    if (bt.empty())
      return os << '.';

    return os << '(' << bt.getRoot() << ' ' << bt.leftTree() << ' '
      << bt.rightTree() << ')';
  }

};

int main() {
  BinaryTree bt(3);
  BinaryTree bt2(3, 4, 5);

  BinaryTree bt3(3, 4, BinaryTree(5, 6, 7));

  cout << bt3 << endl;

  return 0;
}

Add binary tree live implementation

Add binary tree live implementation


#include <iostream>
#include <queue>
using namespace std;

class Node {
public:
  int data;
  Node *left;
  Node *right;

  Node(int x) {
    data = x;
    left = NULL;
    right = NULL;
  }
};

vector<Node *> rightView(Node *root) {
  vector<Node *> rightView;
  if (root == NULL) return rightView;
  queue<Node *> q;
  q.push(root);
  while (!q.empty()) {
    int n = q.size();
    for (int i = 0; i < n; i++) {
      Node *elem = q.front();
      q.pop();
      if (i == n - 1) rightView.push_back(elem);
      if (elem->left != NULL) q.push(elem->left);
      if (elem->right != NULL) q.push(elem->right);
    }
  }
  return rightView;
}

vector<Node *> leftView(Node *root) {
  vector<Node *> leftView;
  if (root == NULL) return leftView;
  queue<Node *> q;
  q.push(root);
  while (!q.empty()) {
    int n = q.size();
    for (int i = 0; i < n; i++) {
      Node *elem = q.front();
      q.pop();
      if (i == 0) leftView.push_back(elem);
      if (elem->left != NULL) q.push(elem->left);
      if (elem->right != NULL) q.push(elem->right);
    }
  }
  return leftView;
}

int main() {
  Node *root = new Node(5);
  root->left = new Node(9);
  root->right = new Node(6);
  root->right->right = new Node(8);
  root->right->left = new Node(3);
  root->right->left->left = new Node(16);
  root->right->left->left->right = new Node(66);
  root->left->right = new Node(10);
  vector<Node *> Rview = rightView(root);
  cout << "Right view:\n";
  for (auto node : Rview) {
    cout << node->data << endl;
  }
  cout << "Left view:\n";
  vector<Node *> Lview = leftView(root);
  for (auto node : Lview) {
    cout << node->data << endl;
  }
  return 0;
}

Add c++ code for printing the side view of a binary tree