#include <chrono>
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>

#include <vpp/vpp.hh>
#include <vpp/utils/opencv_bridge.hh>
#include <vpp/algorithms/FAST_detector/FAST.hh>

#include "get_time.hh"

int main(int argc, char* argv[])
{
  using namespace vpp;

  if (argc != 3)
  {
    std::cerr << "Usage : " << argv[0] << " image threshold" << std::endl;
    return 1;
  }

  int K = 400;

  typedef image2d<vuchar3> I;
  I A = clone_with_border(from_opencv<vuchar3>(cv::imread(argv[1])), 3);
  I B(A.domain(), 1);

  image2d<unsigned char> Agl(A.domain(), 3);
  image2d<unsigned char> Bgl(A.domain());

  pixel_wise(Agl, A) << [] (unsigned char& gl, vuchar3& c)
  {
    gl = (c[0] + c[1] + c[2]) / 3;
  };

  auto time = get_time_in_seconds();
  for (unsigned i = 0; i < K; i++)
    fast_detector<9>(Agl, Bgl, atoi(argv[2]));
  double vpp_ms_per_iter = 1000 * (get_time_in_seconds() - time) / K;

  // Opencv: void FAST(InputArray _img, std::vector<KeyPoint>& keypoints, int threshold, bool nonmax_suppression)
  time = get_time_in_seconds();
  cv::Mat cv_Agl = to_opencv(Agl);
  cv::Mat cv_B = to_opencv(B);
  std::vector<cv::KeyPoint> keypoints;
  for (unsigned i = 0; i < K; i++)
  {
    keypoints.clear();
    FAST(cv_Agl, keypoints, 10, false);
  }
  double opencv_ms_per_iter = 1000 * (get_time_in_seconds() - time) / K;

  std::cout << "Time per iterations: " << std::endl
            << "OpenCV: " << opencv_ms_per_iter << "ms" << std::endl
            << "VPP: " << vpp_ms_per_iter << "ms" << std::endl;

  pixel_wise(Bgl) << [] (unsigned char& gl)
  {
    gl = gl * 255;
  };

  cv::imwrite("b.pgm", to_opencv(Bgl));

}

Add benchmark of the fast detector

Add benchmark of the fast detector


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        ListNode* dummy = new ListNode(), *pre = dummy;
        dummy->next = head;
        bool in = false;
        while (head && head->next) {
            if (in) {
                if (head->val != head->next->val) {
                    pre->next = head->next;
                    in = false;
                }
                head = head->next;
            } else {
                if (head->val == head->next->val) {
                    in = true;
                } else {
                    pre = pre->next;
                }
                head = head->next;
            }
        }
        if (in) pre->next = nullptr;
        return dummy->next;

    }
};

Remove Duplicates from Sorted List II

Remove Duplicates from Sorted List II


#include <iostream>
#include <deque>

using namespace std;

// This is a very well known problem that can easily be found
// in google as 'maximum sliding window' where basically we are
// moving over an array printing each max value for each sub-array
// (or window). You can take a look to the explanation and
// code from:
// http://articles.leetcode.com/sliding-window-maximum/

void printKMax(int arr[], int n, int k){
   deque <int> q;

    // First we need to take care of the first window.
    // We will ensure that the highest element of the window is always in
    // the front of the deque, for that reason on each iteration (i) we
    // remove all the elements in the back of the deque with lower that
    // the current element in the array. This is done in this first while
    // loop.
    for (int i = 0; i < k; i++) {
        while(!q.empty() && arr[i] >= arr[q.back()]) {
            q.pop_back();
        }
        //Each element in the array 'arr' is added at some time into the
        // queue elements with lower value that the current maximum one
        // are removed with the previous while loop.
        q.push_back(i);
    }

    // Section 2.
    // By this point we already checked the first window and all the remaining
    // sections will be taken care in the next for loop.
    for (int i = k; i < n; i++) {
        cout << arr[q.front()] << " ";
        while (!q.empty() && arr[i] >= arr[q.back()])
            q.pop_back();
        //let's remove the elements that are out of the window from the front.
        // As you can see we are attacking the deque in the front as well, but
        // now we only remove the elements that are not part of the subarray
        // and for that reason not valid.
        while(!q.empty() && q.front() <= i-k)
            q.pop_front();
        q.push_back(i);
    }
    cout << arr[q.front()] << " ";
    cout << endl;
}

int main(){
    int t;
    cin >> t;
    while(t>0) {
        int n,k;
        cin >> n >> k;
        int i;
        int arr[n];
        for(i=0;i<n;i++)
            cin >> arr[i];
        printKMax(arr, n, k);
        t--;
    }
    return 0;
}

Add first version of C++ stl deque.

Add first version of C++ stl deque.

Signed-off-by: Rene Sapiens <695da3b4459f3ce51494429e951e34f7ee371262@gmail.com>


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

// Check that call to constructor for struct A is generated correctly.
struct A { A(int x = 2); };
struct B : public A {};
B x;

// CHECK: call void @_ZN1AC1Ei

Add code generation test for r86500.

Add code generation test for r86500.

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


// RUN: rm -rf %t
// RUN: %clang_cc1 -x objective-c++ -fmodules -fmodule-cache-path %t -I %S/Inputs %s -verify

// expected-no-diagnostics
@import cxx_many_overloads;

void g() {
  f(N::X<0>());
}

// RUN: rm -rf %t
// RUN: %clang_cc1 -x objective-c++ -fmodules -fmodules-cache-path=%t -I %S/Inputs %s -verify

// expected-no-diagnostics
@import cxx_many_overloads;

void g() {
  f(N::X<0>());
}

Fix conflict between r174685 and r174645 (rename -fmodule-cache-path <foo> to -fmodules-cache-path=<foo>).

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


// RUN: clang-cc -emit-llvm %s -o %t -triple=x86_64-apple-darwin9 &&
struct A {
  A();
  ~A();
  void f();
};

void f() {
  // RUN: grep "call void @_ZN1AC1Ev" %t | count 2 &&
  // RUN: grep "call void @_ZN1AD1Ev" %t | count 2
  A();
  A().f();
}

Add a simple test for temporaries.

Add a simple test for temporaries.

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


// Test that on the second entry to a function the origins are still right.

// RUN: %clangxx_msan -m64 -O0 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out
// RUN: %clangxx_msan -m64 -O1 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out
// RUN: %clangxx_msan -m64 -O2 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out
// RUN: %clangxx_msan -m64 -O3 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out

// RUN: %clangxx_msan -fsanitize-memory-track-origins -m64 -O0 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out && FileCheck %s --check-prefix=CHECK-ORIGINS < %t.out
// RUN: %clangxx_msan -fsanitize-memory-track-origins -m64 -O1 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out && FileCheck %s --check-prefix=CHECK-ORIGINS < %t.out
// RUN: %clangxx_msan -fsanitize-memory-track-origins -m64 -O2 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out && FileCheck %s --check-prefix=CHECK-ORIGINS < %t.out
// RUN: %clangxx_msan -fsanitize-memory-track-origins -m64 -O3 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out && FileCheck %s --check-prefix=CHECK-ORIGINS < %t.out

#include <stdlib.h>

extern "C"
int f(int depth) {
  if (depth) return f(depth - 1);

  int x;
  int *volatile p = &x;
  return *p;
}

int main(int argc, char **argv) {
  return f(1);
  // CHECK: WARNING: MemorySanitizer: use-of-uninitialized-value
  // CHECK: {{#0 0x.* in main .*stack-origin2.cc:}}[[@LINE-2]]

  // CHECK-ORIGINS: Uninitialized value was created by an allocation of 'x' in the stack frame of function 'f'
  // CHECK-ORIGINS: {{#0 0x.* in f .*stack-origin2.cc:}}[[@LINE-14]]

  // CHECK: SUMMARY: MemorySanitizer: use-of-uninitialized-value {{.*stack-origin2.cc:.* main}}
}

[msan] Add one more test for the handling of stack origins.

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


#include "cxx_runtime.h"
#include "output.h"

Output output;

int bar(char *buffer, int size)
{
	char tmp[size * 2];
	int index = 0;

	output << "enter bar\n";

	for (int i = 0; i < size; i++)
	{
		if (buffer[i] == 'i')
		{
			tmp[index++] = '~';
			tmp[index++] = 'i';
		}
		else
			tmp[index++] = buffer[i];
	}

	memcpy(buffer, tmp, index);
	return index;
}

int main()
{
	char foo[256] = "this is a test";

	int newLen = bar(foo, strlen(foo));
	for (int i = 0; i < newLen; i++)
		output << foo[i];

	// CHECK: th~is ~is a test
}

Add test for dynamic stack allocation

Add test for dynamic stack allocation


#include <iostream>
#include <fstream>
#include <stack>

using std::ifstream;
using std::ofstream;
using std::ios;
using std::cout;
using std::stack;

bool is_digit(char c) {
  return c >= '0' && c <= '9';
}

void apply_operation(char operation, stack<double>& operands) {
  double second_operand = operands.top();
  operands.pop();
  double first_operand = operands.top();
  operands.pop();

  switch (operation) {
    case '+':
      operands.push(first_operand + second_operand);
      break;
    case '-':
      operands.push(first_operand - second_operand);
      break;
    case '*':
      operands.push(first_operand * second_operand);
      break;
    case '/':
      operands.push(first_operand / second_operand);
      break;
  }
}

void write_result(ofstream& results, stack<double>& operands) {
  results.write((const char*)&operands.top(), sizeof(double));
  operands.pop();
}

void calculate_expressions() {
  ifstream expressions("expressions.txt");
  ofstream results("results.bin", ios::trunc | ios::binary);

  stack<double> operands;

  while (!expressions.eof()) {
    char next_character = expressions.peek();

    if (is_digit(next_character)) {
      double operand;
      expressions >> operand;
      operands.push(operand);
    } else {
      char operation;
      expressions >> operation;
      apply_operation(operation, operands);
    }

    if (expressions.peek() == ';') {
      write_result(results, operands);
    }

    expressions.ignore(2, ' ');
  }

  write_result(results, operands);

  results.close();
  expressions.close();
}

void print_results() {
  ifstream results("results.bin", ios::binary);

  double result;
  while (results.read((char*)&result, sizeof(double))) {
    cout << result << ' ';
  }

  results.close();
}

int main() {
  calculate_expressions();
  print_results();
  cout << '\n';

  return 0;
}

Add solution to homework 1

Add solution to homework 1


// RUN: grep -Ev "// *[A-Z-]+:" %s > %t.cpp
// RUN: clang-format -style=none -i %t.cpp
// RUN: FileCheck -strict-whitespace -input-file=%t.cpp %s

// CHECK: int   i;
int   i;

Add basic test for -style=none.

clang-format: Add basic test for -style=none.

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


#if (defined(__GNUC__) && (__GNUC__ > (major) || __GNUC__ == (major) && __GNUC_MINOR__ >= (minor)))
#  define <+FILE_CAPITAL+>_AVAILABLE_GCC_WARNING_PRAGMA
#endif

#ifdef <+FILE_CAPITAL+>_AVAILABLE_GCC_WARNING_PRAGMA
#  pragma GCC diagnostic push
#  pragma GCC diagnostic ignored "-Weffc++"
#  if __cplusplus >= 201103L
#    pragma GCC diagnostic ignored "-Wsuggest-override"
#    pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant"
#  endif  // __cplusplus >= 201103L
#endif  // <+FILE_CAPITAL+>_AVAILABLE_GCC_WARNING_PRAGMA
#include <gtest/gtest.h>
#ifdef <+FILE_CAPITAL+>_AVAILABLE_GCC_WARNING_PRAGMA
#  pragma GCC diagnostic pop
#endif  // <+FILE_CAPITAL+>_AVAILABLE_GCC_WARNING_PRAGMA

#ifdef <+FILE_CAPITAL+>_AVAILABLE_GCC_WARNING_PRAGMA
#  if __cplusplus >= 201103L
#    pragma GCC diagnostic ignored "-Wsuggest-override"
#    pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant"
#  endif  // __cplusplus >= 201103L
#endif  // <+FILE_CAPITAL+>_AVAILABLE_GCC_WARNING_PRAGMA

TEST(<+FILE_PASCAL+>, Test01) {
  <+CURSOR+>
  EXPECT_EQ(1, 1);
}

#ifdef <+FILE_CAPITAL+>_AVAILABLE_GCC_WARNING_PRAGMA
#  pragma GCC diagnostic pop
#endif  // <+FILE_CAPITAL+>_AVAILABLE_GCC_WARNING_PRAGMA

Add a template for Google Test

Add a template for Google Test


#include "Halide.h"
#include "wrapper_tutorial_01.h"
#include "tiramisu/utils.h"
#include <cstdlib>
#include <iostream>

int main(int, char **)
{
    int N = 10;

    Halide::Buffer<int32_t> output(N);
    init_buffer(output, (int32_t)9);

    std::cout << "Array (after initialization)" << std::endl;
    print_buffer(output);

    function0(output.raw_buffer());

    std::cout << "Array after the Halide pipeline" << std::endl;
    print_buffer(output);

    Halide::Buffer<int32_t> expected(N);
    init_buffer(expected, (int32_t)7);

    compare_buffers("tutorial_01", output, expected);

    return 0;
}

Add wrapper for user tuto 01

Add wrapper for user tuto 01


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

#include "SkTypes.h"

#include "mozilla/mozalloc.h"
#include "mozilla/mozalloc_abort.h"
#include "mozilla/mozalloc_oom.h"

void sk_throw() {
    SkDEBUGFAIL("sk_throw");
    mozalloc_abort("Abort from sk_throw");
}

void sk_out_of_memory(void) {
    SkDEBUGFAIL("sk_out_of_memory");
    mozalloc_handle_oom(0);
}

void* sk_malloc_throw(size_t size) {
    return sk_malloc_flags(size, SK_MALLOC_THROW);
}

void* sk_realloc_throw(void* addr, size_t size) {
    return moz_xrealloc(addr, size);
}

void sk_free(void* p) {
    moz_free(p);
}

void* sk_malloc_flags(size_t size, unsigned flags) {
    return (flags & SK_MALLOC_THROW) ? moz_xmalloc(size) : moz_malloc(size);
}

Add a new SkMemory implementation that uses mozalloc instead of malloc

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


// Print all root to leaf paths of a binary tree

/*
Algorithm:
initialize: pathlen = 0, path[1000]
// 1000 is some max limit for paths, it can change

// printPathsRecur traverses nodes of tree in preorder
printPathsRecur(tree, path[], pathlen)
   1) If node is not NULL then
         a) push data to path array:
                path[pathlen] = node->data.
         b) increment pathlen
                pathlen++
   2) If node is a leaf node then print the path array.
   3) Else
        a) Call printPathsRecur for left subtree
                 printPathsRecur(node->left, path, pathLen)
        b) Call printPathsRecur for right subtree.
                printPathsRecur(node->right, path, pathLen)
*/

#include <iostream>
using namespace std;

struct Node{
	int data;
	struct Node *left;
	struct Node *right;
};

void printArray(int A[], int len){
int i;
	for(i=0; i<len; i++)
		cout<<A[i];
	cout<<"\n";
}

void printPathsRecur(struct Node *root, int path[], int pathLen){
	if(root == NULL)
		return;
	path[pathLen] = root->data;
	pathLen++;

	// if it's a leaf, print the path that led there
	if(root->left == NULL && root->right == NULL){
		printArray(path, pathLen);
	}
	else{
	// try both subtrees
		printPathsRecur(root->left, path, pathLen);
		printPathsRecur(root->right, path, pathLen);
	}
}

void printPaths(struct Node *root){
	int path[1000];
	printPathsRecur(root, path, 0);
}

struct Node *newNode(int x){
	struct Node *newptr = new Node;
	newptr->data = x;
	newptr->left = NULL;
	newptr->right = NULL;
	return newptr;
}

int main(){
	struct Node *root = newNode(1);
	root->left = newNode(2);
	root->right = newNode(3);
	root->left->left = newNode(4);
	root->left->right = newNode(5);

	printPaths(root);
return 0;
}

Print all paths from root to node separately.


// Chapter 26, exercise 12: generate random floating point numbers and sort them
// using std::sort(). Measure time used to sort 500,000 doubles and 5,000,000
// doubles.

#include<ctime>
#include<cstdlib>
#include<iostream>
#include<exception>
#include<vector>
#include<limits>
#include<algorithm>

using namespace std;

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

inline double drand(double min, double max)
{
    double d = double(rand()) / RAND_MAX;
    return min + d * (max-min);
}

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

int main()
try {
    srand(time(0));
    vector<int> sizes = {500000, 5000000, 10000000};

    for (int i = 0; i<sizes.size(); ++i) {
        cout << "Sorting " << sizes[i] << " doubles:\n";
        double t = 0;
        for (int j = 0; j<3; ++j) {
            vector<double> v(sizes[i]);
            for (int i = 0; i<v.size(); ++i)
                v[i] = drand(numeric_limits<double>::min()/2,
                             numeric_limits<double>::max()/2);
            clock_t t1 = clock();
            if (t1 == clock_t(-1))
                throw exception("sorry, no clock");
            sort(v.begin(),v.end());
            clock_t t2 = clock();
            if (t2 == clock_t(-1))
                throw exception("sorry, clock overflow");
            t += double(t2-t1)/CLOCKS_PER_SEC;
        }
        cout << "Time: " << t/3 << " seconds\n\n";
    }
}
catch (exception& e) {
    cerr << e.what() << endl;
}
catch (...) {
    cerr << "exception \n";
}

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

Add Chapter 26, exercise 12

Add Chapter 26, exercise 12


/*
 * https://leetcode.com/problems/fizz-buzz/
 * Write a program that outputs the string representation of numbers from 1 to n.
 * But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”.
 * For numbers which are multiples of both three and five output “FizzBuzz”.
 */
class Solution {
public:
    vector<string> fizzBuzz(int n) {
        vector<string> res;
        for(int i = 1; i <= n; i++) {
            if((i % 3 == 0) && (i % 5 == 0))
                res.push_back("FizzBuzz");
            else if (i % 3 == 0)
                res.push_back("Fizz");
            else if (i % 5 == 0)
                res.push_back("Buzz");
            else {
                stringstream ss;
                ss<<i;
                res.push_back(ss.str());
                ss.clear();
            }
        }
        return res;
    }
};

Add solution 412. Fizz Buzz

Add solution 412. Fizz Buzz


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

#include "base/path_service.h"
#include "chrome/test/remoting/qunit_browser_test_runner.h"

#if defined(OS_MACOSX)
#include "base/mac/foundation_util.h"
#endif // !defined(OS_MACOSX)

namespace remoting {

IN_PROC_BROWSER_TEST_F(QUnitBrowserTestRunner, Remoting_Webapp_Js_Unittest) {
  base::FilePath base_dir;
  ASSERT_TRUE(PathService::Get(base::DIR_EXE, &base_dir));

#if defined(OS_MACOSX)
  if (base::mac::AmIBundled()) {
    // If we are inside a mac bundle, navigate up to the output directory
    base_dir = base::mac::GetAppBundlePath(base_dir).DirName();
  }
#endif // !defined(OS_MACOSX)
  RunTest(
      base_dir.Append(FILE_PATH_LITERAL("remoting/unittests/unittests.html")));
}

}  // namespace remoting

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

#include "base/path_service.h"
#include "chrome/test/remoting/qunit_browser_test_runner.h"

#if defined(OS_MACOSX)
#include "base/mac/foundation_util.h"
#endif // !defined(OS_MACOSX)

namespace remoting {

// Flakily times out on Win7 Tests (dbg): https://crbug.com/504204.
#if defined(OS_WIN) && !defined(NDEBUG)
#define MAYBE_Remoting_Webapp_Js_Unittest DISABLE_Remoting_Webapp_Js_Unittest
#else
#define MAYBE_Remoting_Webapp_Js_Unittest Remoting_Webapp_Js_Unittest
#endif
IN_PROC_BROWSER_TEST_F(QUnitBrowserTestRunner,
                       MAYBE_Remoting_Webapp_Js_Unittest) {
  base::FilePath base_dir;
  ASSERT_TRUE(PathService::Get(base::DIR_EXE, &base_dir));

#if defined(OS_MACOSX)
  if (base::mac::AmIBundled()) {
    // If we are inside a mac bundle, navigate up to the output directory
    base_dir = base::mac::GetAppBundlePath(base_dir).DirName();
  }
#endif // !defined(OS_MACOSX)
  RunTest(
      base_dir.Append(FILE_PATH_LITERAL("remoting/unittests/unittests.html")));
}

}  // namespace remoting

Disable flakily timing out QUnitBrowserTestRunner.Remoting_Webapp_Js_Unittest

TBR=garykac
BUG=504204

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

Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#336081}


#include "kiss_fft.h"
#include <complex>
#include <iostream>
#include <vector>
using namespace std;

int main() {
  const int nfft = 256;
  kiss_fft_cfg fwd = kiss_fft_alloc(nfft, 0, NULL, NULL);
  kiss_fft_cfg inv = kiss_fft_alloc(nfft, 1, NULL, NULL);

  vector<std::complex<float>> x(nfft, 0.0);
  vector<std::complex<float>> fx(nfft, 0.0);

  x[0] = 1;
  x[1] = std::complex<float>(0, 3);

  kiss_fft(fwd, (kiss_fft_cpx *)&x[0], (kiss_fft_cpx *)&fx[0]);
  for (int k = 0; k < nfft; ++k) {
    fx[k] = fx[k] * conj(fx[k]);
    fx[k] *= 1. / nfft;
  }
  kiss_fft(inv, (kiss_fft_cpx *)&fx[0], (kiss_fft_cpx *)&x[0]);
  cout << "the circular correlation of [1, 3i, 0 0 ....] with itself = ";
  cout << x[0] << "," << x[1] << "," << x[2] << "," << x[3] << " ... " << endl;
  kiss_fft_free(fwd);
  kiss_fft_free(inv);
  return 0;
}

Add an example of Kiss FFT in C++.

Add an example of Kiss FFT in C++.


#include "Halide.h"

using namespace Halide;

bool errored = false;
void my_error(void *, const char *msg) {
    printf("Expected error: %s\n", msg);
    errored = true;
}

void my_print(void *, const char *msg) {
    // Empty to neuter debug message spew
}

int main(int argc, char **argv) {
    Target t = get_jit_target_from_environment();
    if (!t.has_feature(Target::CUDA)) {
        printf("Not running test because cuda not enabled\n");
        return 0;
    }

    // Turn on debugging so that the pipeline completes and error
    // checking is done before realize returns. Otherwise errors are
    // discovered too late to call a custom error handler.
    t.set_feature(Target::Debug);

    Func f;
    Var c, x;
    f(c, x) = x + c + 3;
    f.bound(c, 0, 3).unroll(c);

    Func g;
    g(c, x) = f(c, x) * 8;

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

    g.set_error_handler(&my_error);
    g.set_custom_print(&my_print);

    // Should succeed
    g.realize(3, 100, t);
    if (errored) {
        printf("There was not supposed to be an error\n");
        return -1;
    }

    // Should trap
    g.realize(4, 100, t);

    if (!errored) {
        printf("There was supposed to be an error\n");
        return -1;
    }

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

Add test for gpu assertions

Add test for gpu assertions

Former-commit-id: aaa460a1537dcca4530d71746113027a3a54c991


#include <stdio.h>

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

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

  return node;
}

void printBoundaryLeft(NODE* root) {
  if (root) {
    if (root->left) {
      printf("%d ", root->data);
      printBoundaryLeft(root->left);
    } else if (root->right) {
      printf("%d ", root->data);
      printBoundaryLeft(root->right);
    }
  }
}

void printLeaves(NODE* root) {
  if (root) {
    printLeaves(root->left);

    if (root->left == nullptr && root->right == nullptr) {
      printf("%d ", root->data);
    }

    printLeaves(root->right);
  }
}

void printBoundaryRight(NODE* root) {
  if (root) {
    if (root->right) {
      printBoundaryRight(root->right);
      printf("%d ", root->data);
    } else if (root->left) {
      printBoundaryRight(root->left);
      printf("%d ", root->data);
    }
  }
}

void printBoundary(NODE* root) {
  if (root) {
    printf("%d ", root->data);

    printBoundaryLeft(root->left);

    printLeaves(root->left);
    printLeaves(root->right);

    printBoundaryRight(root->right);
  }
}

int main(int argc, char const* argv[]) {
  NODE* root = newNode(20);
  root->left = newNode(8);
  root->left->left = newNode(4);
  root->left->right = newNode(12);
  root->left->right->left = newNode(10);
  root->left->right->right = newNode(14);
  root->right = newNode(22);
  root->right->right = newNode(25);

  printBoundary(root);
  return 0;
}

Implement Boundary traversal of tree.

Implement Boundary traversal of tree.


// Verified: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_2_A
struct RMQ {
  int size;
  ll default_value;
  vector<ll> tree;

  RMQ (int n, ll def) {
    default_value = def;
    size = 1;
    while(size < n)size *= 2;
    tree = vector<ll>(size * 2 - 1, default_value);
  }

  void update(int x, ll y){
    int i = size + x - 1;
    tree[i] = y;
    while(i > 0){
      i = (i - 1) / 2;
      tree[i] = min(tree[2 * i + 1], tree[2 * i + 2]);
    }
  }

  // min [x, y)
  int find_min(int x, int y){
    return find_min(x, y, 0, 0, size);
  }

  int find_min(int x, int y, int k, int l, int r){
    if(r <= x || y<=l)
      return default_value;
    if(x <= l && r<=y)
      return tree[k];
    return min(find_min(x, y ,k * 2 + 1, l, (l + r) / 2), find_min(x, y, k * 2 + 2, (l + r) / 2, r));
  }
};

Add library (Range Minimum Query)

Add library (Range Minimum Query)


#include <string>

#include "configuration.hh"

int from_visual(const std::string& cont, int x) {
    if(cont.size() == 0) return 0;
    int count = 0,
        til = 0;
    int numTab = 0;
    for(unsigned int i = 0; i < cont.length(); i++) {
        unsigned int len;
        if(cont[i] == '\t') {
            len = TAB_SIZE - 1 - til;
            til = 0;
            numTab++;
        } else {
            len = 1;
            til++;
            til %= TAB_SIZE;
        }
        count += len;
        if(count > x - numTab) return i;
    }
    return -1;
}

int to_visual(const std::string& cont, int x) {
    int til = 0,
        xx = -1;
    for(std::string::const_iterator i = cont.begin();
                i <= cont.begin() + x; i++) {
        if(*i == '\t') {
            xx += TAB_SIZE - til;
            til = 0;
        } else {
            til++;
            til %= TAB_SIZE;
            xx++;
        }
    }
    return xx;
}

#include <string>

#include "configuration.hh"

int from_visual(const std::string& cont, int x) {
    if(cont.size() == 0) return 0;
    int count = 0,
        til = 0;
    int numTab = 0;
    for(unsigned int i = 0; i < cont.length(); i++) {
        unsigned int len;
        if(cont[i] == '\t') {
            len = TAB_SIZE - 1 - til;
            til = 0;
            numTab++;
        } else {
            len = 1;
            til++;
            til %= TAB_SIZE;
        }
        count += len;
        if(count > x - numTab) return i;
    }
    return -1;
}

int to_visual(const std::string& cont, int x) {
    int til = 0,
        xx = -1;
    for(std::string::const_iterator i = cont.begin();
                i <= cont.begin() + x; ++i) {
        if(*i == '\t') {
            xx += TAB_SIZE - til;
            til = 0;
        } else {
            til++;
            til %= TAB_SIZE;
            xx++;
        }
    }
    return xx;
}

Use prefix ``++`` for objects

Use prefix ``++`` for objects


#include <stdio.h>
#include <stdlib.h> /* rand(), srand() */
#include <time.h> /* time() */
#include <math.h> /* abs() */

int main(void)
{
    srand(time(NULL));

    int N, T;
    printf("Enter N= "); scanf("%d", &N);
    printf("Enter T= "); scanf("%d", &T);

    int step = 0;
    for(int count = 0; count < T; ++count)
    {
        int s, x = 0, y = 0;
        for(s = 0; abs(x) < N || abs(y) < N; ++s)
        {
            switch(rand() % 4)
            {
            case 0: ++x; break;
            case 1: ++y; break;
            case 2: --x; break;
            case 3: --y; break;
            }
        }
        step += s;
    }
    step /= T;

    printf("Result: %d\n", step);

    return 0;
}

Add solution of prob 4

Add solution of prob 4


#include <stdio.h>

void PrintNextGreatest(int arr[], int size) {
  int temp[size];
  int max = -1;

  temp[size - 1] = max;
  for (int count = size - 2; count >= 0; count--) {
    if (arr[count] > max) {
      max = arr[count];
    }
    temp[count] = max;
  }
  printf("Original array \n");
  for (int i = 0; i < size; i++) {
    printf("%d ", arr[i]);
  }

  printf("Right Next Greater array \n");
  for (int i = 0; i < size; i++) {
    printf("%d ", temp[i]);
  }
}

int main(int argc, char const *argv[]) {
  int arr[] = {16, 17, 4, 3, 5, 2};
  int size = sizeof(arr) / sizeof(arr[0]);

  PrintNextGreatest(arr, size);
  return 0;
}

Print max right element in array.

Print max right element in array.


class RandomizedCollection {
public:
    map<int,vector<int>> index;
    vector<int> nums;
    /** Initialize your data structure here. */
    RandomizedCollection() {

    }

    /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
    bool insert(int val) {
        nums.push_back(val);
        if (index[val].size()>0){
            index[val].push_back(nums.size()-1);
            return false;
        }else{
            index[val].push_back(nums.size()-1);
            return true;
        }
    }

    /** Removes a value from the collection. Returns true if the collection contained the specified element. */
    bool remove(int val) {
        if(index[val].size()==0) return false;
        int x=index[val].back();
        if(x==nums.size()-1){
            index[val].pop_back();
            nums.pop_back();
            return true;
        }
        int y=nums[nums.size()-1];
        index[val].pop_back();
        swap(nums[x],nums[nums.size()-1]);
        nums.pop_back();
        index[y].pop_back();
        index[y].push_back(x);
        sort(index[y].begin(),index[y].end());
        return true;
    }

    /** Get a random element from the collection. */
    int getRandom() {
        int n=nums.size();
        int x=rand()%n;
        return nums[x];
    }
};

/**
 * Your RandomizedCollection object will be instantiated and called as such:
 * RandomizedCollection obj = new RandomizedCollection();
 * bool param_1 = obj.insert(val);
 * bool param_2 = obj.remove(val);
 * int param_3 = obj.getRandom();
 */

Insert Delete GetRandom O(1) - Duplicates allowed


// Chapter 21, Exercise 5: redesign and reimplement find() and count() to take
// iterators to first and last elements (no end()), compare results to the
// standard versions - can't return iterator to end() if not found

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

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

// return iterator to first occurrence of val in [first,last]; if element is not
// found, return iterator to first - user has to check if first contains the
// value or not
template<class In, class T>
In my_find(In first, In last, const T& val)
{
    In p = first;
    while (p != last) {
        if (*p == val) return p;
        ++p;
    }

    // check last element
    if (*p == val) return p;

    return first;   // did not find val, user has to check if *first == val
}

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

// return number of occurrences of val in [first,last]
template<class In, class T>
int my_count(In first, In last, const T& val)
{
    int count = 0;
    while (first != last) {
        if (*first==val) ++count;
        ++first;
    }
    if (*first==val) ++count;
    return count;
}

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

int main()
try {
    vector<int> vi;
    for (int i = 0; i<10; ++i)
        vi.push_back(randint(10));

    typedef vector<int>::iterator vi_it;

    cout << "vi:\n";
    for (vi_it it = vi.begin(); it<vi.end(); ++it)
        cout << *it << '\n';

    cout << "Enter int to search for and count (-1 to quit): ";
    int n;
    while (cin>>n) {
        if (n==-1) break;
        vi_it it = my_find(vi.begin(),vi.end()-1,n);
        int count = my_count(vi.begin(),vi.end()-1,n);
        if (it==vi.begin() && *it!=n) cout << n << " is not in vi. Next int: ";
        else cout << n << " is at index " << it-vi.begin()
            << " (occurs " << count << " time" << (count==1 ? "" : "s")
            << "). Next int: ";
    }
}
catch (Range_error& re) {
    cerr << "bad index: " << re.index << "\n";
}
catch (exception& e) {
    cerr << "exception: " << e.what() << endl;
}
catch (...) {
    cerr << "exception\n";
}

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

Add Chapter 21, exercise 5

Add Chapter 21, exercise 5


// RUN: %clang_cc1 %s -verify -fsyntax-only -Wc++2a-compat -std=c++17

#define concept constexpr bool
template<typename T>
concept x = 0;
#undef concept

int concept = 0; // expected-warning {{'concept' is a keyword in C++2a}}
int requires = 0; // expected-warning {{'requires' is a keyword in C++2a}}

Add missing test for warning added in r310803.

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


/**
 * 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* trimBST(TreeNode* root, int L, int R) {
        if(!root) return NULL;
        if(root->val<L) return trimBST(root->right,L,R);
        if(root->val>R) return trimBST(root->left,L,R);
        root->left=trimBST(root->left,L,R);
        root->right=trimBST(root->right,L,R);
        return root;
    }
};

Trim a Binary Search Tree

Trim a Binary Search Tree


// Make sure the intrinsic headers compile cleanly with no warnings or errors.

// RUN: %clang_cc1 -triple x86_64-unknown-unknown -Wsystem-headers \
// RUN:   -fsyntax-only -x c++ -Wno-ignored-attributes -verify %s
// RUN: %clang_cc1 -triple x86_64-unknown-unknown -Wsystem-headers \
// RUN:   -fsyntax-only -x c++ -Wno-ignored-attributes -target-feature +f16c \
// RUN:   -verify %s

// expected-no-diagnostics

// Dont' include mm_malloc.h. It's system specific.
#define __MM_MALLOC_H

#include <x86intrin.h>

Add a test to verify the x86 intrinsic headers compile cleanly with no warnings or errors.

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


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

typedef struct node
{
	int time;
	int due;
}task_node;

bool cmp(task_node a, task_node b)
{
	return a.due < b.due;
}

bool is_possible(task_node *a, int n)
{
	sort(a, a + n, cmp);
	int sum = 0;
	for (int i = 0; i < n; i++) {
		if (a[i].time > a[i].due - sum) {
			return false;
		}
		sum += a[i].time;
	}
	return true;
}

int main()
{
	int N;
	cin >> N;
	while (N--) {
		int X;
		cin >> X;
		task_node *a = new task_node[X];
		for (int i = 0; i < X; i++) {
			cin >> a[i].time >> a[i].due;
		}
		if (is_possible(a, X))
			cout << "possible" << endl;
		else
			cout << "impossible" << endl;
		delete [] a;
	}
	return 0;
}

Add the solution to "Student Scheduling".


#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <deque>

#define MEM_SIZE (1<<20)
#define CACHE_SIZE (1<<8)
#define DATA_SIZE (1<<8)

using namespace std;

int main() {
	// Variables used
	int dir, cmd, op;
	unsigned char dat, wait;

	// Plant the seed
	srand(time(0));

	// Infinit Loop
	while(true){
		// Each command is 32 bits,
		// 19...0 bits for dir,
		// 27...20 bits for data
		// 28 bit indicates operation type 1:read 0:write
		cmd = rand();
		dir = cmd & 0xFFFFF;
		dat = (cmd & 0xF00000)>>20;
		op = (cmd>>28)&1;
		printf("op=%c on dir(0x%x) data:%d\n","wr"[op],dir,dat);
		wait = getchar();
	}
	return 0;
}

 Add body skeleton for cache simulation program

Signed-off-by: Ulises Mendez Martinez <64c66da2351c01d4afecd1591810410a1c01865c@gmail.com>


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

template<typename T> struct Node {
	int lhs;
	void splay( )
	{
		Node<T> n[1];
		(void)n->lhs;
	}
};

void f() {
	Node<int> n;
	return n.splay();
}

Test case for my last fix.

Test case for my last fix.

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


#include"ros/ros.h"
#include"arm_msgs/ArmAnglesDegree.h"
#include"servo_msgs/IdBased.h"

#include<vector>

void armMsgCb(const arm_msgs::ArmAnglesDegree::ConstPtr& msg);

ros::Publisher pub;

int main(int argc, char* argv[]) {
  ros::init(argc, argv, "arm_id_based_node");
  ros::NodeHandle pnh("~");
  std::vector<int> id_vec;
  pnh.getParam("id", id_vec);
  if (id_vec.empty()) {
    ROS_ERROR("I need id parameter: id is int vector");
    return 1;
  }
  ros::NodeHandle nh;
  ros::Subscriber sub = nh.subscribe("arm_roll", 5, armMsgCb);
  pub = nh.advertise<servo_msgs::IdBased>("cmd_krs", 10);
  ros::spin();

  return 0;
}

void armMsgCb(const arm_msgs::ArmAnglesDegree::ConstPtr& msg) {

}

Add arm_id_baesd_node without callback function


//===----------------------------------------------------------------------===//
//
// 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: libcpp-has-no-threads

// This test ensures that std::memory_order has the same size under all
// standard versions to make sure we're not breaking the ABI. This is
// relevant because std::memory_order is a scoped enumeration in C++20,
// but an unscoped enumeration pre-C++20.
//
// See PR40977 for details.

#include <atomic>
#include <type_traits>

enum cpp17_memory_order {
  cpp17_memory_order_relaxed, cpp17_memory_order_consume, cpp17_memory_order_acquire,
  cpp17_memory_order_release, cpp17_memory_order_acq_rel, cpp17_memory_order_seq_cst
};

static_assert((std::is_same<std::underlying_type<cpp17_memory_order>::type,
                            std::underlying_type<std::memory_order>::type>::value),
  "std::memory_order should have the same underlying type as a corresponding "
  "unscoped enumeration would. Otherwise, our ABI changes from C++17 to C++20.");

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

Add a test for PR40977

[libc++] Add a test for PR40977

Even though the header makes the exact same check since https://llvm.org/D59063,
the headers could conceivably change in the future and introduce a bug.

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


#include <iostream>
#include <sstream>
#include <string>
#include <cstdlib>
using namespace std;

int reverse(int x)
{
	int r = 0;
	while (x > 0) {
		r = r * 10 + x % 10;
		x /= 10;
	}
	return r;
}

bool is_palindrome(int x)
{
	if (reverse(x) == x) {
		return true;
	}
	return false;
}

int main()
{
	int T;
	cin >> T;
	while (T--) {
		int x;
		cin >> x;
		while (!is_palindrome(--x));
		cout << x << endl;
	}
	return 0;
}

Add the solution to "Preceding Palindrome".


// RUN: %clang_cc1 -verify %s -pedantic-errors
// RUN: %clang_cc1 -verify %s -pedantic-errors -DINLINE
// RUN: %clang_cc1 -verify %s -pedantic-errors -DSTATIC
// RUN: %clang_cc1 -verify %s -pedantic-errors -std=c++11 -DCONSTEXPR
// RUN: %clang_cc1 -verify %s -std=c++11 -DDELETED

#if INLINE
inline // expected-error {{'main' is not allowed to be declared inline}}
#elif STATIC
static // expected-error {{'main' is not allowed to be declared static}}
#elif CONSTEXPR
constexpr // expected-error {{'main' is not allowed to be declared constexpr}}
#endif
int main(int argc, char **argv)
#if DELETED
  = delete; // expected-error {{'main' is not allowed to be deleted}}
#else
{
  int (*pmain)(int, char**) = &main; // expected-error {{ISO C++ does not allow 'main' to be used by a program}}

  if (argc)
    main(0, 0); // expected-error {{ISO C++ does not allow 'main' to be used by a program}}
}
#endif

Add a test file missed from r199782.

Add a test file missed from r199782.

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


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

using namespace std;
using std::placeholders::_1;

int main() {
    vector<string> svec = {"", "a", "", "b", "c"};
    //use mem_fn
    cout << count_if(svec.cbegin(), svec.cend(), mem_fn(&string::empty)) << " strings are empty" << endl;
    //use function
    function<bool (const string&)> fcn = &string::empty;
    cout << count_if(svec.cbegin(), svec.cend(), fcn) << " strings are empty" << endl;
    //use bind
    cout << count_if(svec.cbegin(), svec.cend(), bind(&string::empty, _1)) << " strings are empty" << endl;
    return 0;
}

Add solution for chapter 19, test 18

Add solution for chapter 19, test 18


#include <OpenSG/OSGBaseInitFunctions.h>
#include <OpenSG/OSGNode.h>
#include <OpenSG/OSGNodeCore.h>
#include <OpenSG/OSGRefPtr.h>

int main (int argc, char **argv)
{
    OSG::osgInit(argc, argv);

    // Test getting pointers
    OSG::NodePtr node_ptr = OSG::Node::create();
    OSG::Node* node_cptr = get_pointer(node_ptr);

    OSG::NodeRefPtr node_rptr(OSG::Node::create());
    node_cptr = get_pointer(node_rptr);

}

Add a test application for the get_pointer methods.  This should really be in a unittest framework...

git-svn-id: 6c7e10cdde2c115f53707ba8ec4efe535f92d362@89 4683daeb-ad0f-0410-a623-93161e962ae5


// Test that we can jump from a type unit in one dwo file into a type unit in a
// different dwo file.

// REQUIRES: lld

// RUN: %clang %s -target x86_64-pc-linux -fno-standalone-debug -g \
// RUN:   -fdebug-types-section -gsplit-dwarf -c -o %t1.o -DONE
// RUN: %clang %s -target x86_64-pc-linux -fno-standalone-debug -g \
// RUN:   -fdebug-types-section -gsplit-dwarf -c -o %t2.o -DTWO
// RUN: llvm-dwarfdump %t1.dwo -debug-types | FileCheck --check-prefix=ONEUNIT %s
// RUN: llvm-dwarfdump %t2.dwo -debug-types | FileCheck --check-prefix=ONEUNIT %s
// RUN: ld.lld %t1.o %t2.o -o %t
// RUN: %lldb %t -o "target var a b **b.a" -b | FileCheck %s

// ONEUNIT-COUNT-1: DW_TAG_type_unit

// CHECK:      (const A) a = (a = 42)
// CHECK:      (const B) b = {
// CHECK-NEXT:   a = 0x{{.*}}
// CHECK-NEXT: }
// CHECK:      (const A) **b.a = (a = 42)

struct A;

extern const A *a_ptr;
#ifdef ONE
struct A {
  int a = 42;
};
constexpr A a{};
const A *a_ptr = &a;
#else
struct B {
  const A **a;
};
extern constexpr B b{&a_ptr};
#endif

Add one more type unit test

[DWARF] Add one more type unit test

This test passes already, but it seems interesting to test that we can
jump between type units in different dwo files nonetheless.

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


// 415. Add Strings
/**
 * Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
 *
 * Note:
 *
 * 1. The length of both num1 and num2 is < 5100.
 * 2. Both num1 and num2 contains only digits 0-9.
 * 3. Both num1 and num2 does not contain any leading zero.
 * 4. You must not use any built-in BigInteger library or convert the inputs to integer directly.
 *
 * Tags: Math
 *
 * Similar Problems: (M) Add Two Numbers, (M) Multiply Strings
 *
 * Author: Kuang Qin
 */

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

using namespace std;

class Solution {
public:
    string addStrings(string num1, string num2) {
        string res("");
        int carry = 0, i = num1.size() - 1, j = num2.size() - 1;
        while (i >= 0 || j >= 0 || carry == 1) {
            if (i >= 0)
                carry += num1[i--] - '0';

            if (j >= 0)
                carry += num2[j--] - '0';

            res += carry % 10 + '0';
            carry /= 10;
        }

        reverse(res.begin(), res.end());
        return res;
    }
};

int main() {
    string num1 = "13", num2 = "9";
    Solution sol;
    string res = sol.addStrings(num1, num2);
    cout << res << endl;
    cin.get();

    return 0;
}

Add Solution for 415 Add Strings

Add Solution for 415 Add Strings


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

const int maxn = 100;

int main()
{
	int n;
	cin >> n;
	int *c = new int[maxn];
	memset(c, 0, sizeof(c));
	while (n--) {
		int x;
		cin >> x;
		c[x]++;
	}
	for (int i = 0; i < maxn; i++) {
		cout << c[i] << " ";
	}
	delete [] c;
	return 0;
}

Add the solution to "Counting Sort 1".

Add the solution to "Counting Sort 1".


#include "test/test_main.h"

int main(int argc, char** argv) {
  ::testing::InitGoogleTest(&argc, argv);
  // what ever initialization you need here
  // invode the test
  return RUN_ALL_TESTS();
}

Add the aggregate test file.

Add the aggregate test file.


// 5. Longest Palindromic Substring
/**
 * Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
 *
 * Example:
 *
 * Input: "babad"
 * Output: "bab"
 * Note: "aba" is also a valid answer.
 *
 * Example:
 *
 * Input: "cbbd"
 * Output: "bb"
 *
 * Tags: String
 *
 * Similar Problems: (H) Shortest Palindrome (E) Palindrome Permutation (H) Palindrome Pairs
 *
 * Author: Kuang Qin
 */

#include <iostream>
#include <string>

using namespace std;

class Solution {
public:
    string longestPalindrome(string s) {
        int n = s.size();
        if (n < 2) {
            return s;
        }

        int start = 0, maxLen = 0, i = 0;
        // stop if max length is the possible largest
        while (i < n - 1 && maxLen < 2 * (n - i)) {
            int left = i, right = i;

            // check duplicates, which are natural palindromic string
            while (right < n - 1 && s[right + 1] == s[right]) {
                right++;
            }

            i = right + 1;  // skip all the duplicates for next check

            // start from middle, check both sides
            while (left > 0 && right < n - 1 && s[left - 1] == s[right + 1]) {
                left--;
                right++;
            }

            // update max length
            int curLen = right - left + 1;
            if (curLen > maxLen) {
                maxLen = curLen;
                start = left;
            }
        }

        return s.substr(start, maxLen);
    }
};

int main() {
    string s = "babbad";
    Solution sol;
    string res = sol.longestPalindrome(s);
    cout << res << endl;
    cin.get();

    return 0;
}

Add Solution for 5. Longest Palindromic Substring


// RUN: %clangxx_asan -O0 -fsanitize-address-use-after-scope %s -o %t && %run %t

// Function jumps over variable initialization making lifetime analysis
// ambiguous. Asan should ignore such variable and program must not fail.

#include <stdlib.h>

int *ptr;

void f1(int cond) {
  if (cond)
    goto label;
  int tmp;

 label:
  ptr = &tmp;
  *ptr = 5;
}

void f2(int cond) {
  switch (cond) {
  case 1: {
    ++cond;
    int tmp;
    ptr = &tmp;
    exit(0);
  case 2:
    ptr = &tmp;
    *ptr = 5;
    exit(0);
  }
  }
}

void f3(int cond) {
  {
    int tmp;
    goto l2;
  l1:
    ptr = &tmp;
    *ptr = 5;

    exit(0);
  }
 l2:
  goto l1;
}

void use(int *x) {
  static int c = 10;
  if (--c == 0)
    exit(0);
  (*x)++;
}

void f4() {
  {
    int x;
 l2:
    use(&x);
    goto l1;
  }
 l1:
  goto l2;
}

int main() {
  f1(1);
  f2(1);
  f3(1);
  f4();
  return 0;
}

[asan] Test jumps which bypass variables declaration

Summary:
Clang should not generate lifetime intrinsics for such variables. D24693

PR28267

Reviewers: eugenis

Subscribers: llvm-commits, kubabrecka

Differential Revision: https://reviews.llvm.org/D24696

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


// Chapter 21, Try This 4: get Dow Jones map example to work

#include "../lib_files/std_lib_facilities.h"
#include<map>
#include<numeric>

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

double weighted_value(const pair<string,double>& a,
    const pair<string,double>& b)
{
    return a.second * b.second;
}

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

int main()
try {
    map<string,double> dow_price;
    // Dow Jones Industrial index (symbol price);
    // for up-to-date quotes see www.djindexes.com
    dow_price["MMM"] = 160.60;
    dow_price["AXP"] = 90.44;
    dow_price["T"] = 32.67;
    dow_price["BA"] = 125.06;
    dow_price["CAT"] = 89.75;
    dow_price["CVX"] = 106.02;

    map<string,double> dow_weight;  // Dow (symbol, weight)
    dow_weight.insert(make_pair("MMM",5.94));
    dow_weight.insert(make_pair("AXP",3.35));
    dow_weight.insert(make_pair("T",1.21));
    dow_weight.insert(make_pair("BA",4.63));
    dow_weight.insert(make_pair("CAT",3.32));
    dow_weight.insert(make_pair("CVX",3.92));

    map<string,string> dow_name;    // Dow (symbol, name)
    dow_name["MMM"] = "3M Co.";
    dow_name["AXP"] = "American Express";
    dow_name["T"] = "AT&T";
    dow_name["BA"] = "Boeing";
    dow_name["CAT"] = "Caterpillar";
    dow_name["CVX"] = "Chevron";

    typedef map<string,double>::const_iterator Dow_iterator;

    // write price for each company in the Dow index:
    for (Dow_iterator p = dow_price.begin(); p!=dow_price.end(); ++p) {
        const string& symbol = p->first;    // the "ticker" symbol
        cout << symbol << '\t' << p->second << '\t' << dow_name[symbol] << '\n';
    }

    double dji_index =
        inner_product(dow_price.begin(),dow_price.end(),    // all companies
            dow_weight.begin(),     // their weights
            0.0,                    // initial value
            plus<double>(),         // add (as usual)
            weighted_value);        // and multiply

    cout << "DJI index is " << dji_index << "\n";
}
catch (Range_error& re) {
    cerr << "bad index: " << re.index << "\n";
}
catch (exception& e) {
    cerr << "exception: " << e.what() << endl;
}
catch (...) {
    cerr << "exception\n";
}

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

Add Chapter 21, Try This 4

Add Chapter 21, Try This 4


/*
 test_pgmspace.cpp - pgmspace tests
 Copyright © 2016 Ivan Grokhotkov

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 */

#include <catch.hpp>
#include <string.h>
#include <pgmspace.h>

TEST_CASE("strstr_P works as strstr", "[core][pgmspace]")
{
    auto t = [](const char* h, const char* n) {
        char* strstr_P_result = strstr_P(h, n);
        char* strstr_result = strstr(h, n);
        REQUIRE(strstr_P_result == strstr_result);
    };

    // Test case data is from avr-libc, original copyright (c) 2007  Dmitry Xmelkov
    // See avr-libc/tests/simulate/pmstring/strstr_P.c
    t ("", "");
    t("12345", "");
    t("ababac", "abac");
    t("", "a");
    t("b", "a");
    t("a", "a");
    t("abcbef", "a");
    t(".a", "a");
    t(".a.", "a");
    t("ABCDEFGH", "H");
    t("", "12");
    t("13", "12");
    t("32", "12");
    t("12", "12");
    t("123", "12");
    t("012", "12");
    t("01200", "12");
    t("a_ab_abc_abcd_abcde", "abcdef");
    t("a_ab_abc_abcd_abcde_abcdef", "abcdef");
    t("aababcabcdabcde", "abcdef");
    t("aababcabcdabcdeabcdef", "abcdef");
    t("abaabaaabaaaab", "aaaaab");
    t("abaabaaabaaaabaaaaab", "aaaaab");
    t("_foo_foo", "foo");
    t("A", "a");
}

Add missing pgmspace test file

Add missing pgmspace test file


#include <libdariadb/storage/memstorage/memstorage.h>
#include <libdariadb/storage/settings.h>
#include <libdariadb/utils/async/thread_manager.h>
#include <libdariadb/utils/logger.h>

#include <benchmark/benchmark_api.h>

class BenchmarkLogger : public dariadb::utils::ILogger {
public:
  BenchmarkLogger() {}
  ~BenchmarkLogger() {}
  void message(dariadb::utils::LOG_MESSAGE_KIND, const std::string &) {}
};

class Memstorage : public benchmark::Fixture {
  virtual void SetUp(const ::benchmark::State &) {
    auto _raw_ptr = new BenchmarkLogger();
    auto _logger = dariadb::utils::ILogger_ptr{_raw_ptr};

    dariadb::utils::LogManager::start(_logger);
    settings = dariadb::storage::Settings::create();
    settings->chunk_size.setValue(10);
    auto _engine_env = dariadb::storage::EngineEnvironment::create();
    _engine_env->addResource(dariadb::storage::EngineEnvironment::Resource::SETTINGS,
                             settings.get());
    dariadb::utils::async::ThreadManager::start(settings->thread_pools_params());

    ms = dariadb::storage::MemStorage::create(_engine_env, size_t(0));
  }

  virtual void TearDown(const ::benchmark::State &) {
    ms = nullptr;
    dariadb::utils::async::ThreadManager::stop();
  }

public:
  dariadb::storage::Settings_ptr settings;
  dariadb::storage::MemStorage_ptr ms;
};

BENCHMARK_DEFINE_F(Memstorage, AddNewTrack)(benchmark::State &state) {
  auto meas = dariadb::Meas();
  while (state.KeepRunning()) {
    benchmark::DoNotOptimize(ms->append(meas));
    meas.id++;
  }
}
BENCHMARK_REGISTER_F(Memstorage, AddNewTrack)
    ->Arg(1000)
    ->Arg(10000)
    ->Arg(20000)
    ->Arg(50000);

Add new track to memory

microbenchmark: Add new track to memory


#include <iostream>
#include <cstring>

#include "cmdline.h"

CMDLINE::CMDLINE(int argC, char **argV)
{
  argc = argC;
  for (int i = 0; i < argc; i++)
    argv[i] = argV[i];
}

int CMDLINE::help()
{
  std::cout << "Help! (coming soon)" << std::endl;
  return 0;
}

int CMDLINE::version()
{
  std::cout << "Version: no version numbering yet." << std::endl;
  return 0;
}

int CMDLINE::parseCommandLine(cmdoptions_t *CMDoptions)
{
  // Set default values for cmd options
  CMDoptions->populationSize = 50;
  CMDoptions->geneSize = 64;

  for (int i = 0; i < argc; i++)
  {
    char *option = argv[i];
    if ((strcmp(option, "--help") == 0)
        || (strcmp(option, "-h") == 0)
        || (strcmp(option, "-?") == 0))
    {
        help();
    }
    else if ((strcmp(option, "--version") == 0)
          || (strcmp(option, "-h") == 0))
    {
      version();
    }
    else if ((strcmp(option, "--population") == 0)
          || (strcmp(option, "-p") == 0))
    {
      // give a population size (the number of individuals)
      sscanf(argv[++i], "%d", &CMDoptions->populationSize);
    }
    else if ((strcmp(option, "--genes") == 0)
          || (strcmp(option, "-g") == 0))
    {
      // Give a gene size of the individual
      sscanf(argv[++i], "%d", &CMDoptions->geneSize);
    }
  }

  return 0;
}

Add the class 'CMDLINE'. So the user is able to change default setting.


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

struct Node
{
	string s;
	Node *left;
	Node *right;
};

Node *new_node(string s)
{
	Node *temp = new Node();
	temp->s = s;
	temp->left = NULL;
	temp->right = NULL;
	return temp;
}

bool add_edge(Node *root, Node *father, Node *child)
{
	if (root == NULL) {
		return false;
	}
	if (root->s == father->s) {
		if (root->left == NULL) {
			root->left = child;
			return true;
		}
		else {
			root->right = child;
			return true;
		}
	}
	if (!add_edge(root->left, father, child)) {
		return add_edge(root->right, father, child);
	}
	return true;
}

void pre_order(Node *root)
{
	if (root == NULL) {
		return;
	}
	cout << root->s << endl;
	pre_order(root->left);
	pre_order(root->right);
}

int main()
{
	int T;
	cin >> T;
	while (T--) {
		int k;
		cin >> k;
		string s1, s2;
		cin >> s1 >> s2;
		Node *tree = new_node(s1);
		Node *left = new_node(s2);
		tree->left = left;
		while (--k) {
			cin >> s1 >> s2;
			add_edge(tree, new_node(s1), new_node(s2));
		}
		pre_order(tree);
	}
	return 0;
}

Add the solution to "Preorder Perusal".

Add the solution to "Preorder Perusal".


#include <stdio.h>

int main(void)
{
    const double r = 100;
    int count = 1; /* Include (0, 0) which makes denominator to zero */

    for(double x = 1; x <= r; ++x)
        for(double y = 1 / (3 * x); x * x + y * y <= r * r && y <= 2 / (3 * x); ++y, ++count);

    printf("Result: %d\n", count);

    return 0;
}

Add solution of prob 1

Add solution of prob 1


// 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/test/webdriver/commands/response.h"

#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/values.h"

namespace webdriver {

namespace {

// Error message taken from:
// http://code.google.com/p/selenium/wiki/JsonWireProtocol#Response_Status_Codes
const char* const kStatusKey = "status";
const char* const kValueKey = "value";
const char* const kMessageKey = "message";
const char* const kScreenKey = "screen";
const char* const kClassKey = "class";
const char* const kStackTraceFileNameKey = "stackTrace.fileName";
const char* const kStackTraceLineNumberKey = "stackTrace.lineNumber";

}  // namespace

Response::Response() {
  SetStatus(kSuccess);
  SetValue(Value::CreateNullValue());
}

Response::~Response() {}

ErrorCode Response::GetStatus() const {
  int status;
  if (!data_.GetInteger(kStatusKey, &status))
    NOTREACHED();
  return static_cast<ErrorCode>(status);
}

void Response::SetStatus(ErrorCode status) {
  data_.SetInteger(kStatusKey, status);
}

const Value* Response::GetValue() const {
  Value* out = NULL;
  LOG_IF(WARNING, !data_.Get(kValueKey, &out))
      << "Accessing unset response value.";  // Should never happen.
  return out;
}

void Response::SetValue(Value* value) {
  data_.Set(kValueKey, value);
}

void Response::SetError(ErrorCode error_code, const std::string& message,
                        const std::string& file, int line) {
  DictionaryValue* error = new DictionaryValue;
  error->SetString(kMessageKey, message);
  error->SetString(kStackTraceFileNameKey, file);
  error->SetInteger(kStackTraceLineNumberKey, line);

  SetStatus(error_code);
  SetValue(error);
}

void Response::SetField(const std::string& key, Value* value) {
  data_.Set(key, value);
}

std::string Response::ToJSON() const {
  std::string json;
  base::JSONWriter::Write(&data_, false, &json);
  return json;
}

}  // namespace webdriver

Fix build. Forgot to explictly add file while patching.
BUG=none
TEST=none
TBR=rsleevi

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

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


// RUN: %clang_cc1 -std=c++1z -verify %s

void f(int n) {
  switch (n) {
  case 0:
    n += 1;
    [[fallthrough]]; // ok
  case 1:
    if (n) {
      [[fallthrough]]; // ok
    } else {
      return;
    }
  case 2:
    for (int n = 0; n != 10; ++n)
      [[fallthrough]]; // expected-error {{does not directly precede switch label}}
  case 3:
    while (true)
      [[fallthrough]]; // expected-error {{does not directly precede switch label}}
  case 4:
    while (false)
      [[fallthrough]]; // expected-error {{does not directly precede switch label}}
  case 5:
    do [[fallthrough]]; while (true); // expected-error {{does not directly precede switch label}}
  case 6:
    do [[fallthrough]]; while (false); // expected-error {{does not directly precede switch label}}
  case 7:
    switch (n) {
    case 0:
      // FIXME: This should be an error, even though the next thing we do is to
      // fall through in an outer switch statement.
      [[fallthrough]];
    }
  case 8:
    [[fallthrough]]; // expected-error {{does not directly precede switch label}}
    goto label;
  label:
  case 9:
    n += 1;
  case 10: // no warning, -Wimplicit-fallthrough is not enabled in this test, and does not need to
           // be enabled for these diagnostics to be produced.
    break;
  }
}

[[fallthrough]] typedef int n; // expected-error {{'fallthrough' attribute cannot be applied to a declaration}}
typedef int [[fallthrough]] n; // expected-error {{'fallthrough' attribute cannot be applied to types}}
typedef int n [[fallthrough]]; // expected-error {{'fallthrough' attribute cannot be applied to a declaration}}

enum [[fallthrough]] E {}; // expected-error {{'fallthrough' attribute cannot be applied to a declaration}}
class [[fallthrough]] C {}; // expected-error {{'fallthrough' attribute cannot be applied to a declaration}}

[[fallthrough]] // expected-error {{'fallthrough' attribute cannot be applied to a declaration}}
void g() {
  [[fallthrough]] int n; // expected-error {{'fallthrough' attribute cannot be applied to a declaration}}
  [[fallthrough]] ++n; // expected-error-re {{{{^}}fallthrough attribute is only allowed on empty statements}}

  switch (n) {
    // FIXME: This should be an error.
    [[fallthrough]];
    return;

  case 0:
    [[fallthrough, fallthrough]]; // expected-error {{multiple times}}
  case 1:
    [[fallthrough(0)]]; // expected-error {{argument list}}
  case 2:
    break;
  }
}

Add accidentally forgotten testcase from r262881.

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


// 108. Convert Sorted Array to Binary Search Tree
/**
 * Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
 *
 * Tags: Tree, Depth-first Search
 *
 * Similar Problems: (M) Convert Sorted List to Binary Search Tree
 *
 * Author: Kuang Qin
 */

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

using namespace std;

/**
 * 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 {
    TreeNode* dfs(vector<int>& nums, int start, int end) {
        if (start > end)
        {
            return NULL;
        }

        int mid = (start + end) / 2;
        TreeNode *root = new TreeNode(nums[mid]);

        root->left = dfs(nums, start, mid - 1);
        root->right = dfs(nums, mid + 1, end);

        return root;
    }
public:
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        int n = nums.size();
        if (n == 0)
        {
            return NULL;
        }

        return dfs(nums, 0, n - 1);
    }
};

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

Add Solution for Problem 108

Add Solution for Problem 108


// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// 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 <gtest/gtest.h>
#include "SurgSim/Framework/Timer.h"
//#include "MockObjects.h"  //NOLINT

using SurgSim::Framework::Timer;

TEST(TimerTest, Constructor)
{
	EXPECT_NO_THROW({std::shared_ptr<Timer> timer(new Timer());});

}

TEST(TimerTest, Starting)
{
	std::shared_ptr<Timer> timer(new Timer());
	EXPECT_EQ(timer->getCurrentNumberOfFrames(), 0);
	EXPECT_EQ(timer->getNumberOfClockFails(), 0);
}

TEST(TimerTest, SettingFrames)
{
	std::shared_ptr<Timer> timer(new Timer());
	timer->endFrame();
	EXPECT_EQ(timer->getCurrentNumberOfFrames(), 1);
	EXPECT_EQ(timer->getAverageFrameRate(), timer->getLastFrameRate());
	EXPECT_EQ(timer->getAverageFramePeriod(), timer->getLastFramePeriod());

	timer->start();
	timer->setNumberOfFrames(3);
	for (auto i = 0; i < 5; ++i)
	{
		timer->endFrame();
	}
	EXPECT_EQ(timer->getCurrentNumberOfFrames(), 3);
}

TEST(TimerTest, Comparison)
{
	std::shared_ptr<Timer> timer1(new Timer());
	std::shared_ptr<Timer> timer2(new Timer());

	for (auto i = 0; i < 100; ++i)
	{
		timer2->beginFrame();
		timer2->endFrame();
		timer1->endFrame();
	}
	EXPECT_TRUE(timer1->getAverageFramePeriod() >= timer2->getAverageFramePeriod());
}

Add UnitTests for Timer class.

Add UnitTests for Timer class.


class Solution {
public:
    string toHex(int num) {
        if(num==0) return "0";
        string ans;
        char hexa[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
        int cnt=0;
        while(num!=0 && cnt<8){
            ans=hexa[(num&15)]+ans;
            num=num>>4;
            cnt++;
        }
        return ans;
    }
};

Convert a Number to Hexadecimal

Convert a Number to Hexadecimal


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

#include "testing/gtest/include/gtest/gtest.h"
#include "tools/gn/value.h"

TEST(Value, ToString) {
  Value strval(NULL, "hi\" $me\\you\\$\\\"");
  EXPECT_EQ("hi\" $me\\you\\$\\\"", strval.ToString(false));
  EXPECT_EQ("\"hi\\\" \\$me\\you\\\\\\$\\\\\\\"\"", strval.ToString(true));

  // Test lists, bools, and ints.
  Value listval(NULL, Value::LIST);
  listval.list_value().push_back(Value(NULL, "hi\"me"));
  listval.list_value().push_back(Value(NULL, true));
  listval.list_value().push_back(Value(NULL, false));
  listval.list_value().push_back(Value(NULL, static_cast<int64>(42)));
  // Printing lists always causes embedded strings to be quoted (ignoring the
  // quote flag), or else they wouldn't make much sense.
  EXPECT_EQ("[\"hi\\\"me\", true, false, 42]", listval.ToString(false));
  EXPECT_EQ("[\"hi\\\"me\", true, false, 42]", listval.ToString(true));

  // Some weird types, we may want to enhance or change printing of these, but
  // here we test the current behavior.
  EXPECT_EQ("<void>", Value().ToString(false));
  EXPECT_EQ("<scope>", Value(NULL, Value::SCOPE).ToString(false));
}

Add missing GN test file.

Add missing GN test file.

This was missing from the last upload of https://codereview.chromium.org/265693003 but was present in the initial review.

TBR=scottmg
BUG=

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

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


#include <windows.h>
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>

int main(int argc, char *argv[]) {
    system("cls");

    // Write character.
    wchar_t ch = 0x754C; // U+754C (CJK UNIFIED IDEOGRAPH-754C)
    DWORD actual = 0;
    BOOL ret = WriteConsoleW(
        GetStdHandle(STD_OUTPUT_HANDLE),
        &ch, 1, &actual, NULL);
    assert(ret && actual == 1);

    // Read it back.
    CHAR_INFO data;
    COORD bufSize = {1, 1};
    COORD bufCoord = {0, 0};
    SMALL_RECT topLeft = {0, 0, 0, 0};
    ret = ReadConsoleOutputW(
            GetStdHandle(STD_OUTPUT_HANDLE), &data, bufSize, bufCoord, &topLeft);
    assert(ret);

    printf("CHAR: 0x%04x\n", data.Char.UnicodeChar);
    return 0;
}

Add a test program that writes and reads a non-ASCII character.


/*
 * Copyright (C) 2015-2016 Pavel Dolgov
 *
 * See the LICENSE file for terms of use.
 */

#include <bits/stdc++.h>

typedef std::pair<int, int> IntPair;
typedef std::deque<IntPair> IntPairs;

IntPairs vertices;

// make vector from two points
IntPair makeVector(IntPair p0, IntPair p1) {
    IntPair vect(p1.first - p0.first, p1.second - p0.second);
    return vect;
}

// [a, b]; where a, b - vectors
int vectorMul(IntPair a, IntPair b) {
    return a.first * b.second - b.first * a.second;
}

int lastVectorsMul(int index0, int index1, int index2) {
    IntPair v1 = makeVector(vertices[index0], vertices[index1]);
    IntPair v2 = makeVector(vertices[index1], vertices[index2]);
    return vectorMul(v1, v2);
}

int main() {
    int N;
    std::cin >> N;
    for (int i = 0; i < N; i++) {
        int x, y;
        std::cin >> x >> y;
        vertices.push_back(IntPair(x, y));
    }
    bool is_convex = true;
    bool is_positive = (lastVectorsMul(0, 1, 2) >= 0);
    for (int i = 1; i < N; i++) {
        bool curr = (lastVectorsMul(i, (i + 1) % N, (i + 2) % N) >= 0);
        if (is_positive != curr) {
            is_convex = false;
            break;
        }
        is_positive = curr;
    }
    std::cout << (is_convex ? "YES" : "NO") << std::endl;
    return 0;
}

Add convexity test for polygon

Add convexity test for polygon


/// \file multipath_alignment_graph.cpp
///
/// unit tests for the multipath mapper's MultipathAlignmentGraph

#include <iostream>
#include "json2pb.h"
#include "vg.pb.h"
#include "../multipath_mapper.hpp"
#include "../build_index.hpp"
#include "catch.hpp"

namespace vg {
namespace unittest {

TEST_CASE( "MultipathAlignmentGraph::align tries multiple traversals of snarls in tails", "[multipath][mapping][multipathalignmentgraph]" ) {

    string graph_json = R"({
        "node": [
            {"id": 1, "sequence": "GATT"},
            {"id": 2, "sequence": "A"},
            {"id": 3, "sequence": "G"},
            {"id": 4, "sequence": "CA"}
        ],
        "edge": [
            {"from": 1, "to": 2},
            {"from": 1, "to": 3},
            {"from": 2, "to": 4},
            {"from", 3, "to": 4}
        ]
    })";

    // Load the JSON
    Graph proto_graph;
    json2pb(proto_graph, graph_json.c_str(), graph_json.size());

    // Make it into a VG
    VG vg;
    vg.extend(proto_graph);

    // We need a fake read
    string read("GATTACA");

    // Pack it into an Alignment
    Alignment query;
    query.set_sequence(read);

    // Make up a fake MEM
    // GCSA range_type is just a pair of [start, end], so we can fake them.

    // This will actually own the MEMs
    vector<MaximalExactMatch> mems;

    // This will hold our MEMs and their start positions in the imaginary graph.
    // Note that this is also a memcluster_t
    vector<pair<const MaximalExactMatch*, pos_t>> mem_hits;

    // Make a MEM hit
    mems.emplace_back(read.begin() + 1, read.begin() + 2, make_pair(5, 5), 1);
    // Drop it on node 1 where it should sit
    mem_hits.emplace_back(&mems.back(), make_pos_t(1, false, 1));

    // Make an Aligner to use for the actual aligning and the scores
    Aligner aligner;

    // Make an identity projection translation
    auto identity = MultipathAlignmentGraph::create_identity_projection_trans(vg);

    // Make the MultipathAlignmentGraph to test
    MultipathAlignmentGraph mpg(vg, mem_hits, identity);

    // Make the output MultipathAlignment
    MultipathAlignment out;

    // Make it align
    mpg.align(query, vg, &aligner, true, 4, false, 5, out);

    cerr << pb2json(out) << endl;

    // Make sure it worked at all
    REQUIRE(out.sequence() == read);
    REQUIRE(out.subpath_size() > 0);
}

}

}

Add a test for the MultipathAlignmentGraph that just explodes


// Return multiple values
// C++11

#include <tuple>

std::tuple<int, bool, float> foo()
{
	return std::make_tuple(128, true, 1.5f);
}

int main()
{
	int obj1;
	bool obj2;
	float obj3;

	std::tie(obj1, obj2, obj3) = foo();
}

// Return multiple values of different types from a function.
//
// The `foo` function on [6-9] returns a
// [`std::tuple`](cpp/utility/tuple) representing multiple values
// of different types. We make use of the
// [`std::make_tuple`](cpp/utility/tuple/make_tuple) utility function
// to create the `std::tuple` object.
//
// On [17], we call this function and use [`std::tie`](cpp/utility/tuple/tie)
// to assign the return values to each of the given objects.
// If we cannot create the objects prior to this call, we can
// alternatively store the resulting `std::tuple` object and use
// [`std::get`](cpp/utility/tuple/get) to get the values from it.
//
// If the values are closely and logically related, consider composing
// them into a `struct` or `class`.

// Return multiple values
// C++11

#include <tuple>

std::tuple<int, bool, float> foo()
{
	return std::make_tuple(128, true, 1.5f);
}

int main()
{
	std::tuple<int, bool, float> result = foo();
	int value = std::get<0>(result);

	int obj1;
	bool obj2;
	float obj3;
	std::tie(obj1, obj2, obj3) = foo();
}

// Return multiple values of different types from a function.
//
// The `foo` function on [6-9] returns a
// [`std::tuple`](cpp/utility/tuple) representing multiple values
// of different types. We make use of the
// [`std::make_tuple`](cpp/utility/tuple/make_tuple) utility function
// to create the `std::tuple` object.
//
// On [13], we call this function and store the result. We then get
// the first of the returned values with [`std::get`](cpp/utility/tuple/get)
// on [14].
//
// Alternatively, on [19] we use [`std::tie`](cpp/utility/tuple/tie)
// to assign the return values to each of the given objects.
// This may not be possible if the objects cannot be constructed
// beforehand and it removes the possibility of copy elision.
//
// If the values are closely and logically related, consider composing
// them into a `struct` or `class` type.

Add std::get example to return multiple values sample


// Makes sure it doesn't crash.

// XFAIL: linux

// RUN: rm -rf %t
// RUN: not %clang_cc1 %s -index-store-path %t/idx -std=c++14
// RUN: c-index-test core -print-record %t/idx | FileCheck %s

namespace rdar32474406 {
void foo();
typedef void (*Func_t)();
// CHECK: [[@LINE+4]]:1 | type-alias/C | c:record-hash-crash-invalid-name.cpp@N@rdar32474406@T@Func_t | Ref,RelCont | rel: 1
// CHECK-NEXT: RelCont | c:@N@rdar32474406
// CHECK: [[@LINE+2]]:14 | function/C | c:@N@rdar32474406@F@foo# | Ref,RelCont | rel: 1
// CHECK-NEXT: RelCont | c:@N@rdar32474406
Func_t[] = { foo }; // invalid decomposition
}

[index] Add a test for a crash with unnamed NamedDecls

Previously this would crash during record hashing.

rdar://problem/32474406


#include "boost/unordered_map.hpp"
#include <iostream>
#include <vector>

#include "utils/Timer.hpp"

using Bucket = std::vector<int>;

void print(Bucket &buckets) {
    std::for_each(buckets.begin(), buckets.end(), [](auto item) { std::cout << item << " "; });
    std::cout << "\n";
}

class CountAllPermutations {
  public:
    size_t count(Bucket &buckets, size_t numsols) {
        size_t numberOfSolutions = numsols;
        bool isEmpty = std::all_of(buckets.cbegin(), buckets.cend(), [](auto value) { return value == 0; });

        if (isEmpty) {
            numberOfSolutions++;
            return numberOfSolutions;
        };

        for (size_t idx = 0; idx < buckets.size(); ++idx) {
            const int value = buckets[idx];
            if (value > 0) {
                Bucket newBuckets(buckets);
                newBuckets[idx] = value - 1;
                numberOfSolutions = count(newBuckets, numberOfSolutions);
            }
        }

        return numberOfSolutions;
    }
};

int main() {
    {
        utils::ElapsedTime<utils::MILLISECOND> t("Run time: ");
        Bucket buckets{2, 1};
        CountAllPermutations alg;
        std::cout << "Number of valid solutions: " << alg.count(buckets, 0) << "\n";
    }

    {
        Bucket buckets{2, 1, 2, 2};
        CountAllPermutations alg;
        std::cout << "Number of valid solutions: " << alg.count(buckets, 0) << "\n;
    }

    return 0;
}

Add solutons that count all permutations.


#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <vector>
#include <trng/lcg64_shift.hpp>

unsigned long long pow(unsigned long long x, unsigned long long n) {
	unsigned long long result=1;
	while (n > 0) {
		if ((n&1) > 0) {
			result=result*x;
		}
		x = x*x;
		n >>= 1;
	}
	return result;
}

unsigned int log2_floor(unsigned long long x) {
    unsigned int y(0);
    while (x>0) {
      x>>=1;
      ++y;
    };
    --y;
    return y;
  }

int main(void) {

	trng::lcg64_shift random_default;
	trng::lcg64_shift random_seed_111(111);
	trng::lcg64_shift random_split_3_0;
	random_split_3_0.split(3, 0);

	trng::lcg64_shift random_split_3_1;
	random_split_3_1.split(3, 1);

	trng::lcg64_shift random_split_3_2;
	random_split_3_2.split(3, 2);

	trng::lcg64_shift random_jump_6361;
	trng::lcg64_shift random_jump2_5667;

	std::cout << "# default, seed 111, split 3-0, split 3-1, split 3-2, jump-6361, jump2-5657" << std::endl;
	for (int i = 0; i < 1009; ++i) {
		std::cout << static_cast<long long>(random_default()) << ',';
		std::cout << static_cast<long long>(random_seed_111()) << ',';
		std::cout << static_cast<long long>(random_split_3_0()) << ',';
		std::cout << static_cast<long long>(random_split_3_1()) << ',';
		std::cout << static_cast<long long>(random_split_3_2()) << ',';

		random_jump_6361.jump(i);
		std::cout << static_cast<long long>(random_jump_6361()) << ',';

		random_jump2_5667.jump2(i%64);
		std::cout << static_cast<long long>(random_jump2_5667()) << '\n';
	}

	return 0;
}

Add cpp program which created the LCG64ShiftRandom test data.


// RUN: grep -Ev "// *[A-Z-]+:" %s > %t-input.cpp
// RUN: clang-tidy %t-input.cpp -checks='-*,google-explicit-constructor,clang-diagnostic-missing-prototypes' -export-fixes=%t.yaml -- -Wmissing-prototypes > %t.msg 2>&1
// RUN: FileCheck -input-file=%t.msg -check-prefix=CHECK-MESSAGES %s -implicit-check-not='{{warning|error|note}}:'
// RUN: FileCheck -input-file=%t.yaml -check-prefix=CHECK-YAML %s
#define X(n) void n ## n() {}
X(f)

// CHECK-MESSAGES: -input.cpp:2:1: warning: no previous prototype for function 'ff' [clang-diagnostic-missing-prototypes]
// CHECK-MESSAGES: -input.cpp:1:19: note: expanded from macro 'X'
// CHECK-MESSAGES: {{^}}note: expanded from here{{$}}

// CHECK-YAML: ---
// CHECK-YAML-NEXT: MainSourceFile:  '{{.*}}-input.cpp'
// CHECK-YAML-NEXT: Diagnostics:
// CHECK-YAML-NEXT:   - DiagnosticName:  clang-diagnostic-missing-prototypes
// CHECK-YAML-NEXT:     Message:         'no previous prototype for function ''ff'''
// CHECK-YAML-NEXT:     FileOffset:      30
// CHECK-YAML-NEXT:     FilePath:        '{{.*}}-input.cpp'
// CHECK-YAML-NEXT:     Notes:
// CHECK-YAML-NEXT:       - Message:         'expanded from macro ''X'''
// CHECK-YAML-NEXT:         FilePath:        '{{.*}}-input.cpp'
// CHECK-YAML-NEXT:         FileOffset:      18
// CHECK-YAML-NEXT:       - Message:         expanded from here
// CHECK-YAML-NEXT:         FilePath:        ''
// CHECK-YAML-NEXT:         FileOffset:      0
// CHECK-YAML-NEXT:     Replacements:    []
// CHECK-YAML-NEXT: ...

[clang-tidy] Add a test for proper handling of locations in scratch space.

This test examines the behavior change of clang::tooling::Diagnostic in r347372.

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


/**
 * Definition for singly-linked list.
 * 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;
        for(int i=0;fast && i < n;i++){
            fast = fast->next;
        }
        if(fast){
            while(fast && fast->next){
                slow = slow->next;
                fast = fast->next;
            }
            if(slow && slow->next){
                slow->next = slow->next->next;
            }
        }else if(head){
            head = head->next;
        }
        return head;
    }
};

Remove Nth Node From End of List

Remove Nth Node From End of List


// This is the starting point
//
#include <iostream>

int main() {
    std::string testString("This is a sample string");
    std::cout << testString << std::endl;

    return 0;
}

Add stub for the starting point

Add stub for the starting point


#include "mfem.hpp"
#include "catch.hpp"
#include <fstream>
#include <iostream>

using namespace mfem;

namespace pa_kernels
{

double test_nl_convection_nd(int dim)
{
   Mesh *mesh;
   if (dim == 2)
   {
      mesh = new Mesh(2, 2, Element::QUADRILATERAL, 0, 1.0, 1.0);
   }
   if (dim == 3)
   {
      mesh = new Mesh(2, 2, 2, Element::HEXAHEDRON, 0, 1.0, 1.0, 1.0);
   }

   int order = 2;
   H1_FECollection fec(order, dim);
   FiniteElementSpace fes(mesh, &fec, dim);

   GridFunction x(&fes), y_fa(&fes), y_pa(&fes);
   x.Randomize(3);

   NonlinearForm nlf_fa(&fes);
   nlf_fa.AddDomainIntegrator(new VectorConvectionNLFIntegrator);
   nlf_fa.Mult(x, y_fa);

   NonlinearForm nlf_pa(&fes);
   nlf_pa.SetAssemblyLevel(AssemblyLevel::PARTIAL);
   nlf_pa.AddDomainIntegrator(new VectorConvectionNLFIntegrator);
   nlf_pa.Setup();
   nlf_pa.Mult(x, y_pa);

   y_fa -= y_pa;
   double difference = y_fa.Norml2();

   delete mesh;

   return difference;
}

TEST_CASE("Nonlinear Convection", "[PartialAssembly], [NonlinearPA]")
{
   SECTION("2D")
   {
      REQUIRE(test_nl_convection_nd(2) == Approx(0.0));
   }

   SECTION("3D")
   {
      REQUIRE(test_nl_convection_nd(3) == Approx(0.0));
   }
}

}

Add test case verifying PA convection

Add test case verifying PA convection

Verify that the partial assembly and fully assembly for nonlinear convection give the same results in 2D and 3D


////////////////////////////////////////////////////////////////////////////////
/// @brief fundamental types for the optimisation and execution of AQL
///
/// @file arangod/Aql/Types.cpp
///
/// DISCLAIMER
///
/// Copyright 2010-2014 triagens GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Max Neunhoeffer
/// @author Copyright 2014, triagens GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "Aql/Types.h"

using namespace triagens::aql;
using Json = triagens::basics::Json;

AqlValue::~AqlValue () {
  switch (_type) {
    case JSON: {
      delete _json;
      return;
    }
    case DOCVEC: {
      for (auto it = _vector->begin(); it != _vector->end(); ++it) {
        delete *it;
      }
      delete _vector;
      return;
    }
    case RANGE: {
      return;
    }
    default:
      return;
  }
}

AqlValue* AqlValue::clone () const {
  switch (_type) {
    case JSON: {
      return new AqlValue(new Json(_json->copy()));
    }
    case DOCVEC: {
      auto c = new vector<AqlItemBlock*>;
      c->reserve(_vector->size());
      for (auto it = _vector->begin(); it != _vector->end(); ++it) {
        c->push_back((*it)->slice(0, (*it)->size()));
      }
      return new AqlValue(c);
    }
    case RANGE: {
      return new AqlValue(_range._low, _range._high);
    }
    default:
      return nullptr;
  }

}

////////////////////////////////////////////////////////////////////////////////
/// @brief splice multiple blocks, note that the new block now owns all
/// AqlValue pointers in the old blocks, therefore, the latter are all
/// set to nullptr, just to be sure.
////////////////////////////////////////////////////////////////////////////////

AqlItemBlock* AqlItemBlock::splice(std::vector<AqlItemBlock*>& blocks)
{
  return nullptr;
}

Add the forgotten file. splice is only a stub.


#include <iostream>
#include <interpreter.h>
#include <gui.h>
#include <easylogging++.h>
#include <SFML/Graphics.hpp>

INITIALIZE_EASYLOGGINGPP

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

    std::cout << "Who am I ? where am I ?    Lei" << std::endl;

    int i = foo();
    std::cout << str() + 1 << std::endl << i << std::endl;
    LOG(INFO) << "I'm drawing here...";

    sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
    sf::CircleShape shape(100.f);
    shape.setFillColor(sf::Color::Green);

    while (window.isOpen()) {
        sf::Event event;
        while (window.pollEvent(event)) {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear();
        window.draw(shape);
        window.display();
    }

    return 0;
}

#include <iostream>
#include <interpreter.h>
#include <gui.h>
#include <easylogging++.h>
#include <SFML/Graphics.hpp>

INITIALIZE_EASYLOGGINGPP

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

    int i = foo();
    std::cout << str() + 1 << std::endl << i << std::endl;
    LOG(INFO) << "Drawing...";

    sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
    sf::CircleShape shape(100.f);
    shape.setFillColor(sf::Color::Green);

    while (window.isOpen()) {
        sf::Event event;
        while (window.pollEvent(event)) {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear();
        window.draw(shape);
        window.display();
    }

    return 0;
}

Revert "this is my test"

Revert "this is my test"

This reverts commit acb4d53a4a705d7ec91c0acfedc73f8cedef621e.


#include<iostream>

using namespace std;

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

		Node(){}

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

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

			if(head==NULL)
				return np;

			while(t->next!=head)
				t=t->next;

			t->next=np;
			np->next=head;

			return head;
		}

		Node *insertNodePos(Node *head, int d, int pos){
			Node *np=new Node(d);
			Node *t=head;

			if(pos==1){
				while(t->next!=head)
					t=t->next;
				t->next=np;
				np->next=head;
				head=np;
				return head;
			}

			int c=1;
			while(c<pos-1){
				t=t->next;
				c++;
			}

			np->next=t->next;
			t->next=np;

			return head;
		}

		void displayList(Node *head){
			Node *t=head;
			cout<<"\nElements of the list are:\n";
			while(t->next!=head){
				cout<<t->data<<"\n";
				t=t->next;
			}
			cout<<t->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.insertNode(head,p);
                }

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

        if(pos>n+1)
                cout<<"\nSorry! The position you entered is out of bounds.\n";
        else{
                cout<<"\nInput the data of the node: ";
                cin>>d;
                head=np.insertNodePos(head,d,pos);
        }

	np.displayList(head);
}

Add code to insert a node in circular linked list


#include <cstdio>

volatile int x[40000000];

int main() {
//#ifdef EVAL
//    freopen("input.txt", "r", stdin);
//    freopen("output.txt", "w", stdout);
//#endif
    int N, max;
    scanf("%d", &N);

    for (long long i=0; i < 40000000; i++) {
        x[i] = 1;
    }

    for (long long i=0; i < 10000000; i++) {
        scanf("");
    }

    for (int i=0; i<N; i++) {
        int x;
        scanf("%d", &x);
        if (i == 0 || x > max)
            max = x;
    }
    printf("%d\n", max);
}

Add slow solution to `easy1` example problem


#include "catch.hpp"

// mapnik vector tile
#include "vector_tile_geometry_feature.hpp"
#include "vector_tile_layer.hpp"

// mapnik
#include <mapnik/geometry.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/feature_factory.hpp>
#include <mapnik/util/variant.hpp>

// protozero
#include <protozero/pbf_writer.hpp>

// libprotobuf
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wsign-conversion"
#include "vector_tile.pb.h"
#pragma GCC diagnostic pop

// std
#include <limits>

//
// Unit tests for encoding of geometries to features
//

TEST_CASE("encode feature pbf of degenerate linestring")
{
    mapnik::geometry::line_string<std::int64_t> line;
    line.add_coord(10,10);

    std::string layer_buffer = "";
    mapnik::vector_tile_impl::layer_builder_pbf layer("foo", 4096, layer_buffer);
    mapnik::feature_ptr f(mapnik::feature_factory::create(std::make_shared<mapnik::context_type>(),1));
    mapnik::vector_tile_impl::geometry_to_feature_pbf_visitor visitor(*f, layer);
    visitor(line);
    REQUIRE(layer_buffer == "");
}

Add test for invalid geometry encoding

Add test for invalid geometry encoding

There's currently a segmenation fault when an invalid geometry is
encoded to a layer builder due to the use of protozero rollback function


Add file with comments to be used in the file


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

// <memory>

// default_delete[]

// template <class U>
//   default_delete(const default_delete<U[]>&);
//
// This constructor shall not participate in overload resolution unless
//   U(*)[] is convertible to T(*)[].

#include <memory>
#include <cassert>

int main()
{
    std::default_delete<int[]> d1;
    std::default_delete<const int[]> d2;
}

Add test to ensure that the converting constructor in N4089 is present and working

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


// Conditionally instantiate class templates

#include <type_traits>
#include <limits>

template <typename T, typename Enable = void>
class foo;

template <typename T>
class foo<T, typename std::enable_if<std::is_integral<T>::value>::type>
{ };

template <typename T>
class foo<T, typename std::enable_if<std::is_floating_point<T>::value>::type>
{ };

int main()
{
	foo<int> f1;
	foo<float> f2;
}

// Use SFINAE to conditionally instantiate class templates.
//
// We provide two partial specializations of the `foo` class template:
// the first, on [9-11], is instantiated only for integral
// type, such as on [19]; the second, on [13-15], is instantiated
// only for floating point types, such as on [20].
//
// The [Substitution Failure Is Not An
// Error](http://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error)
// (SFINAE) rule states that
// failing to instantiate a template with some particular
// template arguments does not result in an error and that instantiation
// is simply discarded. On [10] and [14], we use
// [`std::enable_if`](cpp/types/enable_if) to force instantiation to
// succeed only when its first template argument evaluates to `true`
// (in the first case, when `T` is integral, and in the second case,
// when `T` is floating point). If neither case succeeds, the compiler
// will attempt to instantiate the undefined unspecialized template on
// [6-7] and give an error.
//
// If you want to simply prevent a template from being instantiated
// for certain template arguments, consider using `static_assert`
// instead.

Add "class templates SFINAE" sample

Add "class templates SFINAE" sample


#include <iostream>

using namespace std;

int removeDuplicates(int A[], int n) {
    if (n == 0) {
        return 0;
    }

    int prev = 0;
    int length = 1;
    for (int i = 1; i < n; ++i) {
        if (A[i] == A[prev]) {
            continue;
        } else {
            ++length;
            ++prev;
            A[prev] = A[i];
        }
    }

    return length;
}

int main() {
    int A[] = {1,1,2};
    cout << removeDuplicates(A, 3) << endl;
    return 0;
}

Remove duplicates from a sorted array

Remove duplicates from a sorted array


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

#include <cstddef>
#include <test_macros.h>

// UNSUPPORTED: c++98, c++03, c++11, c++14
// The following compilers don't like "std::byte b1{1}"
// XFAIL: clang-3.5, clang-3.6, clang-3.7, clang-3.8
// XFAIL: apple-clang-6, apple-clang-7, apple-clang-8.0

int main () {
  constexpr std::byte b{42};
  static_assert(std::to_integer<int>(b) == 42, "");
}

[test] Add specific test for P0138R2, direct-list-init of fixed enums from integers, part 3/3.

Test the C++17 Core Language feature independently from other std::byte tests.

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


#include <iostream>
#include <scheduler/coroutine.hh>

Coro* mc;
Coro* c1, *c2;

void start2(void*)
{
  int x=1;
  int y = 12;
  std::cerr <<"c2 start " << std::endl;
  std::cerr <<"c2->c1 " << std::endl;
  x++;
  coroutine_switch_to(c2, c1);
  assert(x==2);
  x++;
  std::cerr <<"c2->main " << std::endl;
  assert(x==3);
  coroutine_switch_to(c2, mc);
  std::cerr <<"END!!" << std::endl;
}
void start(void*)
{
  int x=0;
  std::cerr <<"c1 start" << std::endl;
  c2 = coroutine_new();
  std::cerr <<"c1->start c2" << std::endl;
  x++;
  coroutine_start(c1, c2, &start2, (void*)0);
  assert(x==1);x++;
  std::cerr <<"c1->main" << std::endl;
  coroutine_switch_to(c1, mc);
  assert(x==2);x++;
  std::cerr <<"c1->main" << std::endl;
  coroutine_switch_to(c1, mc);
  assert(x==3);x++;
  std::cerr <<"END!!" << std::endl;
}
int main(int argc, const char* argv[])
{
  mc = coroutine_new();
  coroutine_initialize_main(mc);
  c1 = coroutine_new();
  std::cerr <<"Starting c1 " << std::endl;
  coroutine_start(mc, c1, &start, (void*)0);
  std::cerr <<"Main->c1" << std::endl;
  coroutine_switch_to(mc, c1);
  std::cerr <<"Main->c2" << std::endl;
  coroutine_switch_to(mc, c2);
  std::cerr <<"Main done" << std::endl;
}

Add Matthieu's coroutines test program to the repository.

	* src/scheduler/testcoro.cc: New.


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

// A basic testrunner that supports JavaScript unittests.
// This lives in src/chrome/test/base so that it can include chrome_paths.h
// (required for JS unittests) without updating the DEPS file for each
// subproject.

#include "base/test/test_suite.h"
#include "chrome/common/chrome_paths.h"
#include "media/base/media.h"
#include "net/socket/ssl_server_socket.h"

int main(int argc, char** argv) {
  base::TestSuite test_suite(argc, argv);

#if defined(OS_MACOSX) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
  // This is required for the JavaScript unittests.
  chrome::RegisterPathProvider();
#endif // defined(OS_MACOSX) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))

  // Enable support for SSL server sockets, which must be done while
  // single-threaded.
  net::EnableSSLServerSockets();

  // Ensures runtime specific CPU features are initialized.
  media::InitializeCPUSpecificMediaFeatures();

  return test_suite.Run();
}

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

// A basic testrunner that supports JavaScript unittests.
// This lives in src/chrome/test/base so that it can include chrome_paths.h
// (required for JS unittests) without updating the DEPS file for each
// subproject.

#include "base/test/test_suite.h"
#include "base/test/unit_test_launcher.h"
#include "chrome/common/chrome_paths.h"
#include "media/base/media.h"
#include "net/socket/ssl_server_socket.h"

int main(int argc, char** argv) {
  base::TestSuite test_suite(argc, argv);

#if defined(OS_MACOSX) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
  // This is required for the JavaScript unittests.
  chrome::RegisterPathProvider();
#endif // defined(OS_MACOSX) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))

  // Enable support for SSL server sockets, which must be done while
  // single-threaded.
  net::EnableSSLServerSockets();

  // Ensures runtime specific CPU features are initialized.
  media::InitializeCPUSpecificMediaFeatures();

  return base::LaunchUnitTests(
      argc, argv, base::Bind(&base::TestSuite::Run,
                             base::Unretained(&test_suite)));
}

GTTF: Add --brave-new-test-launcher support to remoting_unittests.

BUG=236893

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

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


#include <gmi_mesh.h>
#include <gmi_null.h>
#include <apfMDS.h>
#include <apfMesh2.h>
#include <apfConvert.h>
#include <apf.h>
#include <PCU.h>

int main(int argc, char** argv)
{
  assert(argc==3);
  MPI_Init(&argc,&argv);
  PCU_Comm_Init();
  PCU_Protect();
  gmi_register_mesh();
  gmi_register_null();
  int* conn;
  int nelem;
  int etype;
  apf::Mesh2* m = apf::loadMdsMesh(argv[1],argv[2]);
  int dim = m->getDimension();
  destruct(m, conn, nelem, etype);
  m->destroyNative();
  apf::destroyMesh(m);
  gmi_model* model = gmi_load(".null");
  m = apf::makeEmptyMdsMesh(model, dim, false);
  apf::GlobalToVert outMap;
  apf::construct(m, conn, nelem, etype, outMap);
  outMap.clear();
  delete [] conn;
  apf::alignMdsRemotes(m);
  apf::deriveMdsModel(m);
  m->verify();
  m->destroyNative();
  apf::destroyMesh(m);
  PCU_Comm_Free();
  MPI_Finalize();
}

#include <gmi_mesh.h>
#include <gmi_null.h>
#include <apfMDS.h>
#include <apfMesh2.h>
#include <apfConvert.h>
#include <apf.h>
#include <PCU.h>

int main(int argc, char** argv)
{
  assert(argc==3);
  MPI_Init(&argc,&argv);
  PCU_Comm_Init();
  PCU_Protect();
  gmi_register_mesh();
  gmi_register_null();
  int* conn;
  double* coords;
  int nelem;
  int etype;
  int nverts;

  apf::Mesh2* m = apf::loadMdsMesh(argv[1],argv[2]);
  int dim = m->getDimension();
  extractCoords(m, coords, nverts);
  destruct(m, conn, nelem, etype);
  m->destroyNative();
  apf::destroyMesh(m);

  gmi_model* model = gmi_load(".null");
  m = apf::makeEmptyMdsMesh(model, dim, false);
  apf::GlobalToVert outMap;
  apf::construct(m, conn, nelem, etype, outMap);
  delete [] conn;
  apf::alignMdsRemotes(m);
  apf::deriveMdsModel(m);
  apf::setCoords(m, coords, nverts, outMap);
  delete [] coords;
  outMap.clear();
  m->verify();

  //apf::writeVtkFiles("after", m);

  m->destroyNative();
  apf::destroyMesh(m);
  PCU_Comm_Free();
  MPI_Finalize();
}

Add test for setting coordinates

Add test for setting coordinates