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

template<typename T> struct A { };

template<typename T, typename U = A<T*> >
  struct B : U { };

template<>
struct A<int*> {
  void foo();
};

template<>
struct A<float*> {
  void bar();
};

void test(B<int> *b1, B<float> *b2) {
  b1->foo();
  b2->bar();
}

Add a test case that goes with the last commit


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

#include "gtest/gtest.h"
#include "test_helper/samples_reader.h"
#include "fortune_points/diagram/site.h"
#include "fortune_points/diagram/voronoi.h"
#include "fortune_points/algorithm/fortune.h"
#include "fortune_points/geom/floating_point.h"

namespace{
  const int NUMBER_OF_TESTS = 26;
  const std::string TEST_INPUT_DIR =
    "fortune_points/__tests__/algorithm/sites_input_samples/input";
  const std::string TEST_OUTPUT_DIR =
    "fortune_points/__tests__/algorithm/diagram_output_samples/output";
  TEST(FortuneAlgorithmTest, DiagramTest){
    for(int i = 0; i < NUMBER_OF_TESTS; i++){
      std::string testCase = std::to_string(i);
      std::vector<Site> sites;
      read_algorithm_input(TEST_INPUT_DIR+testCase+".in",sites);
      std::vector<Edge> correctEdges, computedEdges;
      std::vector<Vertice> correctVertices, computedVertices;
      read_algorithm_output(TEST_OUTPUT_DIR+testCase+".out",
                            correctEdges, correctVertices);
      fortune(sites,computedEdges,computedVertices);
      std::string failMSG = "Fail on input " + testCase + ".";
      ASSERT_EQ(computedEdges.size(), correctEdges.size()) << failMSG;
      for(int j = 0; j < (int)correctEdges.size(); j++){
        //printf("ID: %d\n",computedEdges[j].id);
        //printf("Sites: %d %d\n",computedEdges[j].s0,computedEdges[j].s1);
        //printf("Bisector: %lf %lf %lf\n",computedEdges[j].l.a,computedEdges[j].l.b,computedEdges[j].l.c);
        ASSERT_NEAR(correctEdges[j].l.a,computedEdges[j].l.a,EPS) << failMSG;
        ASSERT_NEAR(correctEdges[j].l.b,computedEdges[j].l.b,EPS) << failMSG;
        ASSERT_NEAR(correctEdges[j].l.c,computedEdges[j].l.c,EPS) << failMSG;
      }
      ASSERT_EQ(computedVertices.size(), correctVertices.size()) << failMSG;
      for(int j = 0; j < (int)correctVertices.size(); j++){
        //printf("%lf,%lf\n",computedVertices[j].x,computedVertices[j].y);
        ASSERT_NEAR(correctVertices[j].x,computedVertices[j].x,EPS) << failMSG;
        ASSERT_NEAR(correctVertices[j].y,computedVertices[j].y,EPS) << failMSG;
      }
      printf("%s\n",("Succeed on input " + testCase + ".").c_str());
    }
  }
}

Test for the algorithm output


//===-- PPCPredicates.cpp - PPC Branch Predicate Information --------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the PowerPC branch predicates.
//
//===----------------------------------------------------------------------===//

#include "PPCPredicates.h"
#include "llvm/Support/ErrorHandling.h"
#include <cassert>
using namespace llvm;

PPC::Predicate PPC::InvertPredicate(PPC::Predicate Opcode) {
  switch (Opcode) {
  default: llvm_unreachable("Unknown PPC branch opcode!");
  case PPC::PRED_EQ: return PPC::PRED_NE;
  case PPC::PRED_NE: return PPC::PRED_EQ;
  case PPC::PRED_LT: return PPC::PRED_GE;
  case PPC::PRED_GE: return PPC::PRED_LT;
  case PPC::PRED_GT: return PPC::PRED_LE;
  case PPC::PRED_LE: return PPC::PRED_GT;
  case PPC::PRED_NU: return PPC::PRED_UN;
  case PPC::PRED_UN: return PPC::PRED_NU;
  }
}

//===-- PPCPredicates.cpp - PPC Branch Predicate Information --------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the PowerPC branch predicates.
//
//===----------------------------------------------------------------------===//

#include "PPCPredicates.h"
#include "llvm/Support/ErrorHandling.h"
#include <cassert>
using namespace llvm;

PPC::Predicate PPC::InvertPredicate(PPC::Predicate Opcode) {
  switch (Opcode) {
  case PPC::PRED_EQ: return PPC::PRED_NE;
  case PPC::PRED_NE: return PPC::PRED_EQ;
  case PPC::PRED_LT: return PPC::PRED_GE;
  case PPC::PRED_GE: return PPC::PRED_LT;
  case PPC::PRED_GT: return PPC::PRED_LE;
  case PPC::PRED_LE: return PPC::PRED_GT;
  case PPC::PRED_NU: return PPC::PRED_UN;
  case PPC::PRED_UN: return PPC::PRED_NU;
  }
  llvm_unreachable("Unknown PPC branch opcode!");
}

Remove default case from fully covered switch.


#include "catch.hpp"

#include "etl/fast_vector.hpp"
#include "etl/fast_matrix.hpp"

TEST_CASE( "deep_assign/vec<mat>", "deep_assign" ) {
    etl::fast_vector<etl::fast_matrix<double, 2, 3>, 2> a;

    a = 0.0;

    for(auto& v : a){
        for(auto& v2 : v){
            REQUIRE(v2 == 0.0);
        }
    }
}

TEST_CASE( "deep_assign/mat<vec>", "deep_assign" ) {
    etl::fast_matrix<etl::fast_vector<double, 2>, 2, 3> a;

    a = 0.0;

    for(auto& v : a){
        for(auto& v2 : v){
            REQUIRE(v2 == 0.0);
        }
    }
}

TEST_CASE( "deep_assign/mat<mat>", "deep_assign" ) {
    etl::fast_matrix<etl::fast_matrix<double, 2, 3>, 2, 3> a;

    a = 0.0;

    for(auto& v : a){
        for(auto& v2 : v){
            REQUIRE(v2 == 0.0);
        }
    }
}

Add test for special cases of assignment


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

// Note: we fail this test because we perform template instantiation
// at the end of the translation unit, so argument-dependent lookup
// finds functions that occur after the point of instantiation. Note
// that GCC fails this test; EDG passes the test in strict mode, but
// not in relaxed mode.
namespace N {
  struct A { };
  struct B : public A { };

  int& f0(A&);
}

template<typename T, typename Result>
struct X0 {
  void test_f0(T t) {
    Result r = f0(t);
  };
};

void test_f0() {
  X0<N::A, int&> xA;
  xA.test_f0(N::A());
  X0<N::B, int&> xB;
  xB.test_f0(N::B());
}

namespace N {
  char& f0(B&);
}

Add a test illustrating our current inability to properly cope with the point of instantation of a member function of a class template specialization


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

bool cmp(int a, int b)
{
	return a > b;
}

int main()
{
	int T;
	cin >> T;
	while (T--) {
		int n, k;
		cin >> n >> k;
		int *a = new int[n];
		int *b = new int[n];
		for (int i = 0; i < n; i++) {
			cin >> a[i];
		}
		for (int i = 0; i < n; i++) {
			cin >> b[i];
		}
		sort(a, a + n);
		sort(b, b + n, cmp);
		bool flag = true;
		for (int i = n - 1; i >= 0; i--) {
			if (a[i] + b[i] < k) {
				flag = false;
				break;
			}
		}
		if (flag)
			cout << "YES" << endl;
		else
			cout << "NO" << endl;
		delete [] a;
		delete [] b;
	}
	return 0;
}

Add the solution to "Two arrays".


#include "engine/guidance/assemble_overview.hpp"
#include "engine/guidance/assemble_geometry.hpp"
#include "engine/guidance/assemble_steps.hpp"
#include "engine/guidance/assemble_route.hpp"
#include "engine/guidance/assemble_leg.hpp"

#include <boost/test/unit_test.hpp>
#include <boost/test/test_case_template.hpp>

BOOST_AUTO_TEST_SUITE(guidance_assembly)

BOOST_AUTO_TEST_CASE(rfc4648_test_vectors)
{
    using namespace osrm::engine::guidance;
    using namespace osrm::engine;

    // TODO(daniel-j-h):
}

BOOST_AUTO_TEST_SUITE_END()

Add guidance assembly unit test stub


#include <iostream>
#include <cvd/connected_components.h>
#include <cvd/image.h>

using namespace std;
using namespace CVD;

int main()
{
	for(int i=0; i < (1<<9); i++)
	{
		cout << "------------------------\n" << i << endl;
		int j=i;
		vector<ImageRef> p;
		for(int y=0; y < 3; y++)
			for(int x=0; x < 3; x++)
			{
				if(j&1)
					p.push_back(ImageRef(x, y));
				j>>=1;
			}

		vector<vector<ImageRef> > v;
		connected_components(p, v);

		Image<char> im(ImageRef(3,3), '.');

		for(unsigned int j=0; j <v.size(); j++)
			for(unsigned int k=0; k <v[j].size(); k++)
				im[v[j][k]]=65+j;

		cout << "Created " << v.size() << " groups\n";
		cout.write(im.data(), 3);
		cout << endl;
		cout.write(im.data()+3, 3);
		cout << endl;
		cout.write(im.data()+6, 3);
		cout << endl;
		cout << endl;
		cin.get();
	}

}

Test program for finding bugs in connected_components.


#include <cstdlib>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
using namespace std;

// Treap has 2 main operations that are O(log(n)):
// - split(t, k) -> split t into 2 trees, one with all keys <= k, the other with the rest
// - merge(t1, t2) -> merge 2 trees where keys of t1 are smaller than any key in t2

struct Tree {
  Tree* left;
  Tree* right;
  int key;
  int value;
  int priority;

  Tree(int k, int v) {
    left = right = 0;
    key = k;
    value = v;
    priority = rand();
  }
};

pair<Tree*, Tree*> split(Tree* t, int k) {
  if (t == 0) return make_pair(nullptr, nullptr);
  if (t->key <= k) {
    auto p = split(t->right, k);
    t->right = p.first;
    return make_pair(t, p.second);
  }
  auto p = split(t->left, k);
  t->left = p.second;
  return make_pair(p.first, t);
}

Tree* merge(Tree* t1, Tree* t2) {
  if (t1 == 0) return t2;
  if (t2 == 0) return t1;
  if (t1->priority >= t2->priority) {
    t1->right = merge(t1->right, t2);
    return t1;
  }
  t2->left = merge(t1, t2->left);
  return t2;
}

// More complex operations can be implemented using only merge and split. See for example insert.
Tree* insert(Tree* t, int k, int v) {
  Tree* n = new Tree(k, v);
  auto p = split(t, k);
  return merge(p.first, merge(n, p.second));
}

void print(Tree* t, int level = 0) {
  if (t->right) print(t->right, level + 1);
  cout << string(4 * level, ' ') << "key: " << t->key << ", value: " << t->value << ", priority:"
       << t->priority << endl;
  if (t->left) print(t->left, level + 1);
}

void destroy(Tree* t) {
  if (t->left) destroy(t->left);
  if (t->right) destroy(t->right);
  delete t;
}

int main() {
  Tree* root = nullptr;
  for (int i = 0; i < 10; ++i) {
    int k = rand() % 10;
    root = insert(root, k, i);
  }
  print(root);
  destroy(root);
}

Add implementation of Treap in C++


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

// Code for finding all nodes at a distanc of K from a given node in a binary tree.

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

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

// Function for finding nodes in subtree of tree at distance of K from the given node.
void subtreeNodes(Node *root, int k, vector<Node *> &ans) {
  if (root == NULL || k < 0) return;
  if (k == 0) {
    ans.push_back(root);
    return;
  }
  subtreeNodes(root->left, k - 1, ans);
  subtreeNodes(root->right, k - 1, ans);
}

int findNodes(Node *root, int key, int k, vector<Node *> &ans) {
  if (root == NULL || k < 0) return -1;
  if (root->data == key) {
    subtreeNodes(root, k, ans);
    return k - 1;
  }
  int lDist = findNodes(root->left, key, k, ans);
  if (lDist >= 0) {
    if (lDist == 0) {
      ans.push_back(root);
      return -1;
    }
    subtreeNodes(root->right, lDist - 1, ans);
    return lDist - 1;
  }
  int rDist = findNodes(root->right, key, k, ans);
  if (rDist >= 0) {
    if (rDist == 0) {
      ans.push_back(root);
      return -1;
    }
    subtreeNodes(root->left, rDist - 1, ans);
    return rDist - 1;
  }
  return -1;
}

vector<Node *> findNodesAtK(Node *root, int key, int k) {
  vector<Node *> ans;
  findNodes(root, key, k, ans);
  return ans;
}

int main() {
  Node *root = new Node(5);
  root->left = new Node(9);
  root->right = new Node(6);
  root->right->right = new Node(8);
  root->right->left = new Node(3);
  root->right->left->left = new Node(16);
  root->right->left->left->right = new Node(66);
  root->left->right = new Node(10);
  vector<Node *> ans = findNodesAtK(root, 8, 3);
  for (auto e : ans) {
    cout << e->data << " ";
  }
  cout << endl;
  return 0;
}

Add Code for finding all nodes at a distanc of K from a given node in a binary tree.


#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
typedef vector < ll > vl;

vl arr(3);
/*
	returs gcd(a,b) and find the coeficcients of bezout
	such that d = ax + by
	arr[0] gcd
	arr[1] x
	arr[2] y
*/
void extended(ll a, ll b){
	ll y =0;
	ll x =1;
	ll xx =0;
	ll yy =1;
	while(b){
		ll	 q = a / b;
		ll t = b;
		b = a%b;
		a = t;

		t = xx;
		xx = x-q*xx;
		x = t;

		t = yy;
		yy = y -q*yy;
		y = t;
	}
	arr[0] = a;
	arr[1] = x;
	arr[2] = y;
}

int main(){
	ll a = 20, b = 50;
	extended(a,b);
	printf("gcd(%lld, %lld) = %lld = %lld * %lld + %lld * %lld\n", a, b, arr[0], a,arr[1], b, arr[2]);
	return 0;
}

Add extended euclidean theorem algorithm.


/*
 * (C) Copyright 2016 Mirantis 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.
 *
 * Author:
 *     Radoslaw Zarzynski <rzarzynski@mirantis.com>
 */

#include <iostream>

#include "static_ptr.hpp"

class Interface {
public:
  virtual ~Interface() {};
  virtual void print_name() const noexcept = 0;
};

class Base1 : public Interface {
  long member[2];
public:
  virtual void print_name() const noexcept override {
    std::cout << "Base1" << std::endl;
  }
};

class Base2 : public Interface {
  long member[4];
public:
  virtual ~Base2() {
    std::cout << "Base2 dted" << std::endl;
  }

  virtual void print_name() const noexcept override {
    std::cout << "Base2" << std::endl;
  }
};

class Factory {
  static constexpr size_t max_size = sizeof(Base1) > sizeof(Base2) ? sizeof(Base1) : sizeof(Base2);
public:
  static constexpr size_t get_max_size() {
    return max_size;
  }

  // cannot use get_max_size here due to a language quirk
  static static_ptr<Interface, max_size> make_instance(bool first_one) {
    if (first_one) {
      return Base1();
    } else {
      return Base2();
    }
  }
};

int main (void) {
  std::cout << "max size: " << Factory::get_max_size() << std::endl;

  static_ptr<Interface, Factory::get_max_size()> ptr = Base2();
  ptr->print_name();

  return 0;
}

Add example showing the basic usage scenario for static_ptr.


#include <gtest/gtest.h>

TEST(MathMeta, ensure_c11_features_present) {
  int s[] = {2, 4};
  auto f = [&s](auto i) { return i + s[0]; };
  EXPECT_EQ(4, f(2));
}

Revert "remove test temporarily to debug"


#include<iostream>

using namespace std;

class Node{
	public:

	int data;
	Node *prev, *next;

	Node(){}

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

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

		if(head==NULL)
			return np;

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

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

		return head;
	}

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

		if(pos==1){
			np->next=head;
			head->prev=np;
			head=np;
			return head;
		}

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

		if(t->next!=NULL){
			Node *tm=t->next;
			np->next=tm;
			tm->prev=np;
		}

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

		return head;
	}

	void displayList(Node *head){
		cout<<"\nElements of the list are:\n";

		while(head){
			cout<<head->data<<"\n";
			head=head->next;
		}
	}
};

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

	cout<<"Enter the number of elements: ";
	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 node in doubly linked list


/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
 * WARRANTY OF ANY KIND, either express or implied. See the License for the specific
 * language governing rights and limitations under the License.
 *
 * The Original Code is [Open Source Virtual Machine.]
 *
 * The Initial Developer of the Original Code is Adobe System Incorporated.  Portions created
 * by the Initial Developer are Copyright (C)[ 2004-2006 ] Adobe Systems Incorporated. All Rights
 * Reserved.
 *
 * Contributor(s): Adobe AS3 Team
 *
 * Alternatively, the contents of this file may be used under the terms of either the GNU
 * General Public License Version 2 or later (the "GPL"), or the GNU Lesser General Public
 * License Version 2.1 or later (the "LGPL"), in which case the provisions of the GPL or the
 * LGPL are applicable instead of those above. If you wish to allow use of your version of this
 * file only under the terms of either the GPL or the LGPL, and not to allow others to use your
 * version of this file under the terms of the MPL, indicate your decision by deleting provisions
 * above and replace them with the notice and other provisions required by the GPL or the
 * LGPL. If you do not delete the provisions above, a recipient may use your version of this file
 * under the terms of any one of the MPL, the GPL or the LGPL.
 *
 ***** END LICENSE BLOCK ***** */

#include "avmplus.h"
namespace avmplus
{
	namespace NativeID {
		#include "builtin.cpp"
	}
}

Change 262430 by wsharp@WSHARP-380 on 2006/12/04 07:26:06


#include <atomic>
#include <chrono>
#include <thread>
#include <utility>

#include <fmt/printf.h>
#include <gsl/gsl_assert>

template <typename Agent> concept IsAgent = requires(Agent agent) {
  {agent.doWork()};
};

template <typename Agent> requires IsAgent<Agent> class Runner {
public:
  Runner(Agent &&agent) : m_agent(std::forward<Agent>(agent)) {}

  constexpr void start() {
    m_running = true;
    m_thread = std::thread([&]() { run(); });
  }

  constexpr void run() {
    while (m_running) {
      m_agent.doWork();
    }
  }

  constexpr void stop() {
    m_running = false;
    m_thread.join();
  }

  ~Runner() { Expects(m_running == false); }

private:
  Agent m_agent;
  std::thread m_thread;
  std::atomic<bool> m_running{false};
};

template <typename Agent> Runner(Agent &&)->Runner<Agent>;

class HelloWorldAgent {
public:
  void doWork() noexcept { fmt::print("Hello, {}!\n", "Nanosecond"); }
};

int main() {
  using namespace std::chrono_literals;

  auto runner = Runner{HelloWorldAgent{}};
  runner.start();

  std::this_thread::sleep_for(2s);

  runner.stop();

  return 0;
}

Add runner agent with concepts example.


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
struct Item {
    int level;
    TreeNode* root;
};

public:
    TreeNode* addOneRow(TreeNode* root, int val, int depth) {
        if (depth == 1) {
            TreeNode *newroot = new TreeNode(val);
            if (root) {
                newroot->left = root;
            }
            return newroot;
        }
        if (!root) {
            return root;
        }
        std::queue<Item> q;
        q.push(Item{1, root});
        while (!q.empty()) {
            Item cur = q.front();
            q.pop();
            if ((cur.level+1) < depth) {
                if (cur.root->left) {
                    q.push(Item{cur.level+1, cur.root->left});
                }
                if (cur.root->right) {
                    q.push(Item{cur.level+1, cur.root->right});
                }
            } else if ((cur.level+1) == depth) {
                // found
                TreeNode *newleft = new TreeNode{val};
                TreeNode *newright = new TreeNode{val};
                newleft->left = cur.root->left;
                newright->right = cur.root->right;
                cur.root->left = newleft;
                cur.root->right = newright;
            } else {
                break;
            }
        }
        return root;
    }
};

Add One Row to Tree


#include <UnitTest++.h>

// Unit tests for vec classes

#include <OpenSG/OSGNode.h>
#include <OpenSG/OSGNameAttachment.h>
#include <OpenSG/OSGSceneFileHandler.h>

#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/operations.hpp>
namespace bf = boost::filesystem;

struct FileFixture
{
   FileFixture()
   {
      test_file = bf::path("test_file.osb");
      bf::remove(test_file);
   }

   ~FileFixture()
   {
      bf::remove(test_file);
   }

   bf::path test_file;
};

TEST_FIXTURE(FileFixture, CreateOSBFile)
{
   OSG::NodePtr n = OSG::Node::create();

   CHECK(!bf::exists(test_file));
   OSG::SceneFileHandler::the()->write(n, test_file.native_file_string().c_str());
   CHECK(bf::exists(test_file));

   OSG::NodePtr new_n =
      OSG::SceneFileHandler::the()->read(test_file.native_file_string().c_str());
   CHECK(new_n != OSG::NullFC);
}

TEST_FIXTURE(FileFixture, TestNameRetention)
{
   std::string start_name("node");
   OSG::NodePtr n = OSG::Node::create();
   OSG::setName(n, start_name);

   CHECK(!bf::exists(test_file));
   OSG::SceneFileHandler::the()->write(n, test_file.native_file_string().c_str());
   CHECK(bf::exists(test_file));

   OSG::NodePtr new_n =
      OSG::SceneFileHandler::the()->read(test_file.native_file_string().c_str());
   CHECK(new_n != OSG::NullFC);
   CHECK(OSG::getName(new_n) != NULL);
   std::string cur_name = std::string(OSG::getName(new_n));

   CHECK(cur_name == start_name);
}

Add test to demonstrate bug where names are not loaded by the osb loader.


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

#include "../Fuzz.h"

void fuzz_NullGLCanvas(Fuzz* f);

extern "C" {

    // Set default LSAN options.
    const char *__lsan_default_options() {
        // Don't print the list of LSAN suppressions on every execution.
        return "print_suppressions=0";
    }

    int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
        auto fuzz = Fuzz(SkData::MakeWithoutCopy(data, size));
        fuzz_NullGLCanvas(&fuzz);
        return 0;
    }
}  // extern "C"

Add libFuzzer style fuzzer for NullGLCanvas for use on OSS-Fuzz.


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int mod = 1e9 + 7;

int a[2010];
int dp[2010][2010];

int main(void) {
    int n, h;
    scanf("%d %d", &n, &h);
    for (int i = 1; i <= n; i++)
        scanf("%d", &a[i]);

    // fill up the base cases
    dp[1][0] = (a[1] == h || a[1]  + 1 == h) ? 1 : 0; // left alone OR opened and closed
    dp[1][1] = (a[1] + 1 == h) ? 1 : 0; // opened and did not close

    for (int i = 2; i <= n; i++) {
        // the value of open must satisfy one of the following equations
        // a[i] + open = h     => open = h - a[i];
        // a[i] + open + 1 = h => open = h - a[i] - 1;
        for (int open = max(h - a[i] - 1, 0); open <= min(h - a[i], i); open++) {
            if (a[i] + open == h) {
                // do nothing
                dp[i][open] = (dp[i][open] + dp[i - 1][open]) % mod;

                // close one
                if (open > 0)
                    dp[i][open] = (dp[i][open] + dp[i - 1][open - 1]) % mod;

            }
            else if (a[i] + open + 1 == h) {
                // open one here and close it as well
                dp[i][open] = (dp[i][open] + dp[i - 1][open]) % mod;

                // have open + 1 from earlier and close one of them
                dp[i][open] = (dp[i][open] + (dp[i - 1][open + 1] * (ll)(open + 1)) % mod) % mod;

                // have open from earlier, close one of them and open your own
                dp[i][open] = (dp[i][open] + (dp[i - 1][open] * (ll)open) % mod) % mod;
            }
        }
    }
    printf("%d\n", dp[n][0]);
    return 0;
}

Increase Sequence - 466D - Codeforces


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

template<typename T>
T kadane_method(const std::vector<T>& v){
	T ret = 0;
	std::for_each(v.begin(), v.end(), [c_max = 0, max = 0, &ret](T m) mutable {
		c_max  = c_max + m;
		// the ccurrent max is a negative number,
		// we can't use that cuz it will not give us
		// the maximum sum
		if (c_max < 0) c_max = 0;
		// we have to check if there is a new max
		// if c_max is greater than it means there is a new max so we
		// have to use that instead.
		if (max < c_max) max = c_max;

		//std::cout << "m: " << m << " c_max: "
		//			<< c_max << " max: " << max << '\n';
		ret = max;
	});

	return ret;
}

int main() {
	std::cout << kadane_method<int>({-2, -3, 4, -1, -2, 1, 5, -3}) << '\n';
	std::cout << kadane_method<int>({-2, 1, -3, 4, -1, 2, 1, -5, 4}) << '\n';
	std::cout << kadane_method<int>({2, 3, 7, -5, -1, 4, -10}) << '\n';
}

Add max sub array implementaion in C++


/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/*
 psimpl-c
 Copyright (c) 2013 Jamie Bullock <jamie@jamiebullock.com>

 Based on psimpl
 Copyright (c) 2010-2011 Elmar de Koning <edekoning@gmail.com>
 */

#include "psimpl-c.h"
#include "psimpl/psimpl.h"

#include <stdio.h>

double *psimpl_simplify_douglas_peucker(
                                        psimpl_LineDimension dimensions,
                                        uint64_t points,
                                        double tolerance,
                                        double *original_points,
                                        double *simplified_points
                                        )
{
    double *original_end = original_points + (points * dimensions);

    switch (dimensions)
    {
        case psimpl_LineDimension_1D:
            return psimpl::simplify_douglas_peucker <1> (original_points, original_end, tolerance, simplified_points);

        case psimpl_LineDimension_2D:
            return psimpl::simplify_douglas_peucker <2> (original_points, original_end, tolerance, simplified_points);

        case psimpl_LineDimension_3D:
            return psimpl::simplify_douglas_peucker <3> (original_points, original_end, tolerance, simplified_points);

        default:
            fprintf(stderr, "Error: invalid dimensions: %d\n", dimensions);
            return  NULL;
            break;
    }
}

Add basic wrapper for Douglas-Peucker


//===- SimplifyCFG.cpp - CFG Simplification Routines -------------*- C++ -*--=//
//
// This file provides several routines that are useful for simplifying CFGs in
// various ways...
//
//===----------------------------------------------------------------------===//

#include "llvm/Analysis/SimplifyCFG.h"
#include "llvm/BasicBlock.h"
#include "llvm/Method.h"
#include "llvm/iTerminators.h"
#include "llvm/iOther.h"
#include "llvm/Type.h"

// UnifyAllExitNodes - Unify all exit nodes of the CFG by creating a new
// BasicBlock, and converting all returns to unconditional branches to this
// new basic block.  The singular exit node is returned.
//
// If there are no return stmts in the Method, a null pointer is returned.
//
BasicBlock *cfg::UnifyAllExitNodes(Method *M) {
  vector<BasicBlock*> ReturningBlocks;

  // Loop over all of the blocks in a method, tracking all of the blocks that
  // return.
  //
  for(Method::iterator I = M->begin(), E = M->end(); I != E; ++I)
    if ((*I)->getTerminator()->getInstType() == Instruction::Ret)
      ReturningBlocks.push_back(*I);

  if (ReturningBlocks.size() == 0)
    return 0;                          // No blocks return
  else if (ReturningBlocks.size() == 1)
    return ReturningBlocks.front();    // Already has a single return block

  // Otherwise, we need to insert a new basic block into the method, add a PHI
  // node (if the function returns a value), and convert all of the return
  // instructions into unconditional branches.
  //
  BasicBlock *NewRetBlock = new BasicBlock("", M);

  if (M->getReturnType() != Type::VoidTy) {
    // If the method doesn't return void... add a PHI node to the block...
    PHINode *PN = new PHINode(M->getReturnType());
    NewRetBlock->getInstList().push_back(PN);

    // Add an incoming element to the PHI node for every return instruction that
    // is merging into this new block...
    for (vector<BasicBlock*>::iterator I = ReturningBlocks.begin(),
                                       E = ReturningBlocks.end(); I != E; ++I)
      PN->addIncoming((*I)->getTerminator()->getOperand(0), *I);

    // Add a return instruction to return the result of the PHI node...
    NewRetBlock->getInstList().push_back(new ReturnInst(PN));
  } else {
    // If it returns void, just add a return void instruction to the block
    NewRetBlock->getInstList().push_back(new ReturnInst());
  }

  // Loop over all of the blocks, replacing the return instruction with an
  // unconditional branch.
  //
  for (vector<BasicBlock*>::iterator I = ReturningBlocks.begin(),
                                     E = ReturningBlocks.end(); I != E; ++I) {
    delete (*I)->getInstList().pop_back();  // Remove the return insn
    (*I)->getInstList().push_back(new BranchInst(NewRetBlock));
  }
  return NewRetBlock;
}

Add method to unify all exit nodes of a method


#include "generator/geo_objects/geo_objects_filter.hpp"

#include "generator/osm_element_helpers.hpp"

#include "indexer/ftypes_matcher.hpp"

using namespace feature;

namespace generator
{
namespace geo_objects
{
bool GeoObjectsFilter::IsAccepted(OsmElement const & element)
{
  return osm_element::IsBuilding(element) || osm_element::HasHouse(element) || osm_element::IsPoi(element);
}

bool GeoObjectsFilter::IsAccepted(FeatureBuilder const & feature)
{
  if (!feature.GetParams().IsValid())
    return false;

  return IsBuilding(feature) || HasHouse(feature) || IsPoi(feature);
}

// static
bool GeoObjectsFilter::IsBuilding(FeatureBuilder const & fb)
{
  auto const & checker = ftypes::IsBuildingChecker::Instance();
  return checker(fb.GetTypes());
}

// static
bool GeoObjectsFilter::HasHouse(FeatureBuilder const & fb)
{
  return !fb.GetParams().house.IsEmpty();
}

// static
bool GeoObjectsFilter::IsPoi(FeatureBuilder const & fb)
{
  auto const & poiChecker = ftypes::IsPoiChecker::Instance();
  return poiChecker(fb.GetTypes());
}
}  // namespace geo_objects
}  // namespace generator

#include "generator/geo_objects/geo_objects_filter.hpp"

#include "generator/osm_element_helpers.hpp"

#include "indexer/ftypes_matcher.hpp"

using namespace feature;

namespace generator
{
namespace geo_objects
{
bool GeoObjectsFilter::IsAccepted(OsmElement const & element)
{
  return osm_element::IsBuilding(element) || osm_element::HasHouse(element) || osm_element::IsPoi(element);
}

bool GeoObjectsFilter::IsAccepted(FeatureBuilder const & feature)
{
  if (!feature.GetParams().IsValid())
    return false;

  if (feature.IsLine())
    return false;

  return IsBuilding(feature) || HasHouse(feature) || IsPoi(feature);
}

// static
bool GeoObjectsFilter::IsBuilding(FeatureBuilder const & fb)
{
  auto const & checker = ftypes::IsBuildingChecker::Instance();
  return checker(fb.GetTypes());
}

// static
bool GeoObjectsFilter::HasHouse(FeatureBuilder const & fb)
{
  return !fb.GetParams().house.IsEmpty();
}

// static
bool GeoObjectsFilter::IsPoi(FeatureBuilder const & fb)
{
  auto const & poiChecker = ftypes::IsPoiChecker::Instance();
  return poiChecker(fb.GetTypes());
}
}  // namespace geo_objects
}  // namespace generator

Fix features filter: ignore lines


// Chapter 20, Exercise 04: Find and fix the errors in the Jack-and-Jill example
// from 20.3.1 by using STL techniques throughout.

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

double* get_from_jack(int* count)
{
    string ifname = "pics_and_txt/chapter20_ex02_in1.txt";
    ifstream ifs(ifname.c_str());
    if (!ifs) error("Can't open input file ",ifname);

    // Elegantly read input into vector first
    vector<double> v;
    double d;
    while (ifs>>d) v.push_back(d);

    *count = v.size();
    double* data = new double[*count];
    for (int i = 0; i<v.size(); ++i)
        data[i] = v[i];

    return data;
}

vector<double>* get_from_jill()
{
    string ifname = "pics_and_txt/chapter20_ex02_in2.txt";
    ifstream ifs(ifname.c_str());
    if (!ifs) error ("Can't open input file ",ifname);

    vector<double>* v = new vector<double>;
    double d;
    while (ifs>>d) (*v).push_back(d);

    return v;
}

// return an iterator to the element in [first:last) that has the highest value
template<class Iterator>
Iterator high(Iterator first, Iterator last)
{
    if (first==last) error("No highest value in empty sequence");
    Iterator high = first;
    for (Iterator p = first; p!=last; ++p)
        if (*high<*p) high = p;
    return high;
}

void fct()
{
    int jack_count = 0;
    double* jack_data = get_from_jack(&jack_count);
    vector<double>* jill_data = get_from_jill();

    double* jack_high = high(jack_data,jack_data+jack_count);
    vector<double>& v = *jill_data;
    double* jill_high = high(&v[0],&v[0]+v.size());
    cout << "Jill's high " << *jill_high << "; Jack's high " << *jack_high;

    delete[] jack_data;
    delete jill_data;
}

int main()
try {
    fct();
}
catch (Range_error& re) {
    cerr << "bad index: " << re.index << "\n";
}
catch (exception& e) {
    cerr << "exception: " << e.what() << endl;
}
catch (...) {
    cerr << "exception\n";
}

Add Chapter 20, exercise 4


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

#include "media/base/media.h"

#include "base/logging.h"

// This file is intended for platforms that don't need to load any media
// libraries (e.g., Android and iOS).
namespace media {

bool InitializeMediaLibrary(const base::FilePath& module_dir) {
  return true;
}

void InitializeMediaLibraryForTesting() {
}

bool IsMediaLibraryInitialized() {
  return true;
}

}  // namespace media

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

#include "media/base/media.h"

#include "base/logging.h"

#if defined(OS_ANDROID)
#include "base/android/jni_android.h"
#include "media/base/android/media_jni_registrar.h"
#endif

// This file is intended for platforms that don't need to load any media
// libraries (e.g., Android and iOS).
namespace media {

bool InitializeMediaLibrary(const base::FilePath& module_dir) {
  return true;
}

void InitializeMediaLibraryForTesting() {
#if defined(OS_ANDROID)
  // Register JNI bindings for android.
  JNIEnv* env = base::android::AttachCurrentThread();
  RegisterJni(env);
#endif
}

bool IsMediaLibraryInitialized() {
  return true;
}

}  // namespace media

Fix media and content unittests on Android debug bots


/* mbed Microcontroller Library
 * Copyright (c) 2017 ARM Limited
 *
 * 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 "mbed.h"
#include "greentea-client/test_env.h"
#include "unity.h"
#include "utest.h"
#include "rtos.h"

#if defined(MBED_RTOS_SINGLE_THREAD)
  #error [NOT_SUPPORTED] test not supported
#endif

using namespace utest::v1;

#define TEST_STACK_SIZE 512
#define TEST_DELAY 10

static int change_counter = 0;
static Mutex mutex;
static ConditionVariable cond(mutex);

void increment_on_signal()
{
    mutex.lock();

    cond.wait();
    change_counter++;

    mutex.unlock();
}

void test_notify_one()
{
    Thread t1(osPriorityNormal, TEST_STACK_SIZE);
    Thread t2(osPriorityNormal, TEST_STACK_SIZE);

    change_counter = 0;
    t1.start(increment_on_signal);
    t2.start(increment_on_signal);

    wait_ms(TEST_DELAY);
    TEST_ASSERT_EQUAL(0, change_counter);

    mutex.lock();
    cond.notify_one();
    mutex.unlock();

    wait_ms(TEST_DELAY);
    TEST_ASSERT_EQUAL(1, change_counter);

    mutex.lock();
    cond.notify_one();
    mutex.unlock();

    t1.join();
    t2.join();
}

void test_notify_all()
{
    Thread t1(osPriorityNormal, TEST_STACK_SIZE);
    Thread t2(osPriorityNormal, TEST_STACK_SIZE);

    change_counter = 0;
    t1.start(increment_on_signal);
    t2.start(increment_on_signal);

    wait_ms(TEST_DELAY);
    TEST_ASSERT_EQUAL(0, change_counter);

    mutex.lock();
    cond.notify_all();
    mutex.unlock();

    wait_ms(TEST_DELAY);
    TEST_ASSERT_EQUAL(2, change_counter);

    t1.join();
    t2.join();
}

utest::v1::status_t test_setup(const size_t number_of_cases)
{
    GREENTEA_SETUP(10, "default_auto");
    return verbose_test_setup_handler(number_of_cases);
}

Case cases[] = {
    Case("Test notify one", test_notify_one),
    Case("Test notify all", test_notify_all),
};

Specification specification(test_setup, cases);

int main()
{
    return !Harness::run(specification);
}

Add test cases for ConditionVariable


// Test case for PR1420
// RUN: %llvmgxx %s -O0 -o %t.exe
// RUN: %t.exe > %t.out
// RUN: grep {sizeof(bitFieldStruct) == 8} %t.out
// RUN: grep {Offset bitFieldStruct.i = 0} %t.out
// RUN: grep {Offset bitFieldStruct.c2 = 7} %t.out
// XFAIL: *

#include <stdio.h>

class bitFieldStruct {
  public:
    int i;
    unsigned char c:7;
    int s:17;
    char c2;
};

int main()
{
  printf("sizeof(bitFieldStruct) == %d\n", sizeof(bitFieldStruct));

  if (sizeof(bitFieldStruct) != 2 * sizeof(int))
    printf("bitFieldStruct should be %d but is %d \n",
            2 * sizeof(int), sizeof(bitFieldStruct));

  bitFieldStruct x;

  char* xip = (char*) &x.i;
  char* xc2p = (char*) &x.c2;
  printf("Offset bitFieldStruct.i = %d\n", xip - xip);
  printf("Offset bitFieldStruct.c2 = %d\n", xc2p - xip);

  return 0;
}

Add a test case for PR1420


#include <cassert>
#include <cstdint>
#include <iostream>
#include <malloc.h>
#include <new>

class alignas(32) Vec3d {
    double x, y, z;
};

int main() {
    std::cout << "sizeof(Vec3d) is " << sizeof(Vec3d) << '\n';
    std::cout << "alignof(Vec3d) is " << alignof(Vec3d) << '\n';

    auto Vec = Vec3d{};
    auto pVec = new Vec3d[10];

    if (reinterpret_cast<uintptr_t>(&Vec) % alignof(Vec3d) == 0) {
        std::cout << "Vec is aligned to alignof(Vec3d)!\n";
    } else {
        std::cout << "Vec is not aligned to alignof(Vec3d)!\n";
    }

    if (reinterpret_cast<uintptr_t>(pVec) % alignof(Vec3d) == 0) {
        std::cout << "pVec is aligned to alignof(Vec3d)!\n";
    } else {
        std::cout << "pVec is not aligned to alignof(Vec3d)!\n";
    }

    delete[] pVec;
}

Add struct alignement test example.


// RUN: %clang_analyze_cc1 -analyzer-checker=core,unix -verify %s

// expected-no-diagnostics

// Test functions that are called "memcpy" but aren't the memcpy
// we're looking for. Unfortunately, this test cannot be put into
// a namespace. The out-of-class weird memcpy needs to be recognized
// as a normal C function for the test to make sense.
typedef __typeof(sizeof(int)) size_t;
void *memcpy(void *, const void *, size_t);

struct S {
  static S s1, s2;

  // A weird overload within the class that accepts a structure reference
  // instead of a pointer.
  void memcpy(void *, const S &, size_t);
  void test_in_class_weird_memcpy() {
    memcpy(this, s2, 1); // no-crash
  }
};

// A similarly weird overload outside of the class.
void *memcpy(void *, const S &, size_t);

void test_out_of_class_weird_memcpy() {
  memcpy(&S::s1, S::s2, 1); // no-crash
}

Add the forgotten test file.


// RUN: %clangxx -g -O0 %s -emit-llvm -S -o - | FileCheck %s
// PR14471

class C
{
  static int a;
  const static int const_a = 16;
protected:
  static int b;
  const static int const_b = 17;
public:
  static int c;
  const static int const_c = 18;
  int d;
};

int C::a = 4;
int C::b = 2;
int C::c = 1;

int main()
{
        C instance_C;
        instance_C.d = 8;
        return C::c;
}

// The definition of C::a drives the emission of class C, which is
// why the definition of "a" comes before the declarations while
// "b" and "c" come after.

// CHECK: metadata !"a", {{.*}} @_ZN1C1aE, metadata ![[DECL_A:[0-9]+]]} ; [ DW_TAG_variable ] [a] {{.*}} [def]
// CHECK: ![[DECL_A]] = metadata {{.*}} [ DW_TAG_member ] [a] [line {{.*}}, size 0, align 0, offset 0] [private] [static]
// CHECK: metadata !"const_a", {{.*}} [ DW_TAG_member ] [const_a] [line {{.*}}, size 0, align 0, offset 0] [private] [static]
// CHECK: ![[DECL_B:[0-9]+]] {{.*}} metadata !"b", {{.*}} [ DW_TAG_member ] [b] [line {{.*}}, size 0, align 0, offset 0] [protected] [static]
// CHECK: metadata !"const_b", {{.*}} [ DW_TAG_member ] [const_b] [line {{.*}}, size 0, align 0, offset 0] [protected] [static]
// CHECK: ![[DECL_C:[0-9]+]] {{.*}} metadata !"c", {{.*}} [ DW_TAG_member ] [c] [line {{.*}}, size 0, align 0, offset 0] [static]
// CHECK: metadata !"const_c", {{.*}} [ DW_TAG_member ] [const_c] [line {{.*}}, size 0, align 0, offset 0] [static]
// CHECK: metadata !"b", {{.*}} @_ZN1C1bE, metadata ![[DECL_B]]} ; [ DW_TAG_variable ] [b] {{.*}} [def]
// CHECK: metadata !"c", {{.*}} @_ZN1C1cE, metadata ![[DECL_C]]} ; [ DW_TAG_variable ] [c] {{.*}} [def]

Add testcase missed yesterday. Patch from Paul Robinson.


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

// <array>

// iterator, const_iterator

#include <array>
#include <iterator>
#include <cassert>

int main()
{
    {
    typedef std::array<int, 5> C;
    C c;
    C::iterator i;
    i = c.begin();
    C::const_iterator j;
    j = c.cbegin();
    assert(i == j);
    }
    {
    typedef std::array<int, 0> C;
    C c;
    C::iterator i;
    i = c.begin();
    C::const_iterator j;
    j = c.cbegin();
    assert(i == j);
    }

#if _LIBCPP_STD_VER > 11
    { // N3664 testing
        {
        typedef std::array<int, 5> C;
        C::iterator ii1{}, ii2{};
        C::iterator ii4 = ii1;
        C::const_iterator cii{};
        assert ( ii1 == ii2 );
        assert ( ii1 == ii4 );
        assert ( ii1 == cii );

        assert ( !(ii1 != ii2 ));
        assert ( !(ii1 != cii ));

//         C c;
//         assert ( ii1 != c.cbegin());
//         assert ( cii != c.begin());
//         assert ( cii != c.cend());
//         assert ( ii1 != c.end());
        }
        {
        typedef std::array<int, 0> C;
        C::iterator ii1{}, ii2{};
        C::iterator ii4 = ii1;
        C::const_iterator cii{};
        assert ( ii1 == ii2 );
        assert ( ii1 == ii4 );
        assert ( ii1 == cii );

        assert ( !(ii1 != ii2 ));
        assert ( !(ii1 != cii ));

//         C c;
//         assert ( ii1 != c.cbegin());
//         assert ( cii != c.begin());
//         assert ( cii != c.cend());
//         assert ( ii1 != c.end());
        }
    }
#endif
}

Implement tests for NULL iterators for <array> re: N3644


// 9.exercise.04.cpp
//
//  Look at the headache-inducing last example of §8.4. Indent it properly and
//  explain the meaning of the construct. Note that the example doesn't do
//  anything meaningful; it is pure obfuscation.
//
//  COMMENTS

int maint()
try
{
    return 0;
}
catch(exception& e)
{
    cerr << e.what() << '\n';
    return 1;
}
catch(...)
{
    cerr << "Unknown exception!\n";
    return 2;
}

Prepare exercise 4 from chapter 9.


#include <iostream>
#include <cstring>

using namespace std;

class Card {
    char title[100];
    char author[100];
    unsigned int count;

public:

    Card(const char _title[], const char _author[], unsigned int _count) {
        strcpy(title, _title);
        strcpy(author, _author);
        count = _count;
    }

    void print() {
        cout << "Title: " << title << endl;
        cout << "Author: " << author << endl;
        cout << "Count of available copies: " << count << endl;
    }
};

int main() {
    Card winFriendsInfluencePeople = Card("How to win friends and influence people", "Dale Carnegie", 3);
    winFriendsInfluencePeople.print();

    return 0;
}

Add solution to task 1


#include <iostream>
#include <cmath>

using namespace std;

class Point3D {
  double x;
  double y;
  double z;

public:

  double getX() {
    return x;
  }

  double getY() {
    return y;
  }

  double getZ() {
    return z;
  }

  void setX(double newX) {
    x = newX;
  }

  void setY(double newY) {
    y = newY;
  }

  void setZ(double newZ) {
    z = newZ;
  }

  void translate(Point3D translationVector) {
    setX(getX() + translationVector.getX());
    setY(getY() + translationVector.getY());
    setZ(getZ() + translationVector.getZ());
  }

  double distanceTo(Point3D other) {
    return sqrt(pow(getX() - other.getX(), 2) +
                pow(getY() - other.getY(), 2) +
                pow(getZ() - other.getZ(), 2));
  }

  void print() {
    cout << '(' << getX() << ", " << getY() << ", " << getZ() << ')' << '\n';
  }
};

void testTranslate() {
  Point3D point;
  point.setX(3);
  point.setY(5);
  point.setZ(2);

  Point3D translationVector;
  translationVector.setX(4);
  translationVector.setY(7);
  translationVector.setZ(1);

  point.translate(translationVector);
  point.print();
}

void testDistanceBetween() {
  Point3D firstPoint;
  firstPoint.setX(3);
  firstPoint.setY(5);
  firstPoint.setZ(2);

  Point3D secondPoint;
  secondPoint.setX(4);
  secondPoint.setY(1);
  secondPoint.setZ(7);

  cout << firstPoint.distanceTo(secondPoint) << '\n';
}

int main() {
  testTranslate();
  testDistanceBetween();

  return 0;
}

Add solution to the first problem - '3D point'


// RUN: %clangxx_xray -g -std=c++11 %s -o %t
// RUN: rm xray-log.fdr-reinit* || true
// RUN: XRAY_OPTIONS="verbosity=1" %run %t
// RUN: rm xray-log.fdr-reinit* || true
#include "xray/xray_log_interface.h"
#include <cassert>
#include <cstddef>
#include <thread>

volatile uint64_t var = 0;

std::atomic_flag keep_going = ATOMIC_FLAG_INIT;

[[clang::xray_always_instrument]] void __attribute__((noinline)) func() {
  ++var;
}

int main(int argc, char *argv[]) {
  // Start a thread that will just keep calling the function, to spam calls to
  // the function call handler.
  keep_going.test_and_set(std::memory_order_acquire);
  std::thread t([] {
    while (keep_going.test_and_set(std::memory_order_acquire))
      func();
  });

  static constexpr char kConfig[] =
      "buffer_size=1024:buffer_max=10:no_file_flush=true";

  // Then we initialize the FDR mode implementation.
  assert(__xray_log_select_mode("xray-fdr") ==
         XRayLogRegisterStatus::XRAY_REGISTRATION_OK);
  auto init_status = __xray_log_init_mode("xray-fdr", kConfig);
  assert(init_status == XRayLogInitStatus::XRAY_LOG_INITIALIZED);

  // Now we patch the instrumentation points.
  __xray_patch();

  // Spin for a bit, calling func() enough times.
  for (auto i = 0; i < 1 << 20; ++i)
    func();

  // Then immediately finalize the implementation.
  auto finalize_status = __xray_log_finalize();
  assert(finalize_status == XRayLogInitStatus::XRAY_LOG_FINALIZED);

  // Once we're here, we should then flush.
  auto flush_status = __xray_log_flushLog();
  assert(flush_status == XRayLogFlushStatus::XRAY_LOG_FLUSHED);

  // Without doing anything else, we should re-initialize.
  init_status = __xray_log_init_mode("xray-fdr", kConfig);
  assert(init_status == XRayLogInitStatus::XRAY_LOG_INITIALIZED);

  // Then we spin for a bit again calling func() enough times.
  for (auto i = 0; i < 1 << 20; ++i)
    func();

  // Then immediately finalize the implementation.
  finalize_status = __xray_log_finalize();
  assert(finalize_status == XRayLogInitStatus::XRAY_LOG_FINALIZED);

  // Once we're here, we should then flush.
  flush_status = __xray_log_flushLog();
  assert(flush_status == XRayLogFlushStatus::XRAY_LOG_FLUSHED);

  // Finally, we should signal the sibling thread to stop.
  keep_going.clear(std::memory_order_release);

  // Then join.
  t.join();
}

Add a test for re-initialising FDR mode (NFC)


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

#include "atom/browser/atom_browser_main_parts.h"

#include "base/command_line.h"
#include "base/strings/string_number_conversions.h"
#include "library_loaders/libgio.h"
#include "ui/gfx/switches.h"

namespace atom {

namespace {

const char* kInterfaceSchema = "org.gnome.desktop.interface";
const char* kScaleFactor = "scale-factor";

}  // namespace

void AtomBrowserMainParts::SetDPIFromGSettings() {
  LibGioLoader libgio_loader;

  // Try also without .0 at the end; on some systems this may be required.
  if (!libgio_loader.Load("libgio-2.0.so.0") &&
      !libgio_loader.Load("libgio-2.0.so")) {
    VLOG(1) << "Cannot load gio library. Will fall back to gconf.";
    return;
  }

  GSettings* client = libgio_loader.g_settings_new(kInterfaceSchema);
  if (!client) {
    VLOG(1) << "Cannot create gsettings client.";
    return;
  }

  gchar** keys = libgio_loader.g_settings_list_keys(client);
  if (!keys) {
    g_object_unref(client);
    return;
  }

  // Check if the "scale-factor" settings exsits.
  gchar** iter = keys;
  while (*iter) {
    if (strcmp(*iter, kScaleFactor) == 0)
      break;
    iter++;
  }

  if (*iter) {
    guint scale_factor = libgio_loader.g_settings_get_uint(
        client, kScaleFactor);
    if (scale_factor >= 1) {
      base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
          switches::kForceDeviceScaleFactor, base::UintToString(scale_factor));
    }
  }

  g_strfreev(keys);
  g_object_unref(client);
}

}  // namespace atom

Set scale factor to the value in gsettings


#include "go_quic_spdy_server_stream_go_wrapper.h"
#include "net/quic/quic_session.h"
#include "net/quic/quic_data_stream.h"

#include "go_functions.h"

GoQuicSpdyServerStreamGoWrapper::GoQuicSpdyServerStreamGoWrapper(net::QuicStreamId id, net::QuicSession* session, void* go_quic_spdy_server_stream)
  : net::QuicDataStream(id, session),
    go_quic_spdy_server_stream_(go_quic_spdy_server_stream) {
}

GoQuicSpdyServerStreamGoWrapper::~GoQuicSpdyServerStreamGoWrapper() {
}
// TODO(hodduc) more more implementation
//
uint32 GoQuicSpdyServerStreamGoWrapper::ProcessData(const char* data, uint32 data_len) {
  if (data_len > INT_MAX) {
    LOG(DFATAL) << "Data length too long: " << data_len;
    return 0;
  }

  uint32_t ret_data_len = DataStreamProcessorProcessData_C(go_quic_spdy_server_stream_, data, data_len);

  return data_len;
}

#include "go_quic_spdy_server_stream_go_wrapper.h"
#include "net/quic/quic_session.h"
#include "net/quic/quic_data_stream.h"

#include "go_functions.h"

GoQuicSpdyServerStreamGoWrapper::GoQuicSpdyServerStreamGoWrapper(net::QuicStreamId id, net::QuicSession* session, void* go_quic_spdy_server_stream)
  : net::QuicDataStream(id, session),
    go_quic_spdy_server_stream_(go_quic_spdy_server_stream) {
}

GoQuicSpdyServerStreamGoWrapper::~GoQuicSpdyServerStreamGoWrapper() {
}
// TODO(hodduc) more more implementation
//
uint32 GoQuicSpdyServerStreamGoWrapper::ProcessData(const char* data, uint32 data_len) {
  if (data_len > INT_MAX) {
    LOG(DFATAL) << "Data length too long: " << data_len;
    return 0;
  }

  uint32_t ret_data_len = DataStreamProcessorProcessData_C(go_quic_spdy_server_stream_, data, data_len);

  return ret_data_len;
}

Fix GoQuicSpdyServerStreamGoWrapper not returning correct len


#include <cstdio>
#include <cstring>

using namespace std;

int binary_to_decimal(char * number)
{
  int result = 0;
  int power = 0;
  for (int i = strlen(number) - 1; i >= 0; i--)
  {
    int x = number[i] - '0';
    result +=  x * (1 << power);
    power++;
  }

  return result;
}

int octal_to_decimal(char * number)
{
  int result = 0;
  int number_length = strlen(number);
  for (int i = 0; i < number_length; i++)
  {
    result += number[i] - '0';
    if (i < number_length - 1)
    {
      result *= 8;
    }
  }

  return result;
}

int hexadecimal_to_decimal(char *number)
{
  int number_length = strlen(number);
  char result[100] = "";
  for (int i = 0; i < number_length; i++)
  {
    if (number[i] == '0') strcat(result, "0000");
    else if (number[i] == '1') strcat(result, "0001");
    else if (number[i] == '2') strcat(result, "0010");
    else if (number[i] == '3') strcat(result, "0011");
    else if (number[i] == '4') strcat(result, "0100");
    else if (number[i] == '5') strcat(result, "0101");
    else if (number[i] == '6') strcat(result, "0110");
    else if (number[i] == '7') strcat(result, "0111");
    else if (number[i] == '8') strcat(result, "1000");
    else if (number[i] == '9') strcat(result, "1001");
    else if (number[i] == 'A') strcat(result, "1010");
    else if (number[i] == 'B') strcat(result, "1011");
    else if (number[i] == 'C') strcat(result, "1100");
    else if (number[i] == 'D') strcat(result, "1101");
    else if (number[i] == 'E') strcat(result, "1110");
    else if (number[i] == 'F') strcat(result, "1111");
  }

  return binary_to_decimal(result);
}

int main()
{
  int numeral_system;
  char number[100];

  while (scanf("%d%s", &numeral_system, number))
  {
    if (numeral_system == 2) printf("%d\n", binary_to_decimal(number));
    else if (numeral_system == 8) printf("%d\n", octal_to_decimal(number));
    else if (numeral_system == 16) printf("%d\n", hexadecimal_to_decimal(number));
  }

  return 0;
}

Add a solution for task 1a


/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2015 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#include "catch.hpp"

#include <mapnik/datasource.hpp>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/raster.hpp>
#include <mapnik/util/fs.hpp>

namespace {

mapnik::datasource_ptr get_gdal_ds(std::string const& file_name,
                                   boost::optional<mapnik::value_integer> band)
{
    std::string gdal_plugin("./plugins/input/gdal.input");
    if (!mapnik::util::exists(gdal_plugin))
    {
        return mapnik::datasource_ptr();
    }

    mapnik::parameters params;
    params["type"] = std::string("gdal");
    params["file"] = file_name;
    if (band)
    {
        params["band"] = *band;
    }

    auto ds = mapnik::datasource_cache::instance().create(params);
    REQUIRE(ds != nullptr);

    return ds;
}

} // anonymous namespace

TEST_CASE("gdal") {

    SECTION("upsampling")
    {
        std::string dataset = "test/data/tiff/ndvi_256x256_gray32f_tiled.tif";
        mapnik::datasource_ptr ds = get_gdal_ds(dataset, 1);

        if (!ds)
        {
            // GDAL plugin not built.
            return;
        }

        mapnik::box2d<double> envelope = ds->envelope();
        CHECK(envelope.width() == 256);
        CHECK(envelope.height() == 256);

        // Indicate four times bigger resolution.
        mapnik::query::resolution_type resolution(2.0, 2.0);
        mapnik::query query(envelope, resolution, 1.0);

        auto features = ds->features(query);
        auto feature = features->next();

        mapnik::raster_ptr raster = feature->get_raster();

        REQUIRE(raster != nullptr);
        CHECK(raster->data_.width() == 256);
        CHECK(raster->data_.height() == 256);
    }

} // END TEST CASE

Add test that GDAL plugin does not upsample.


#include <iostream>

using namespace std;

class Class {
public:
    Class() {
        cout << "Class()" << endl;
    }
};

class Base : public Class {
public:
    Base() {
        cout << "Base()" << endl;
    }
};

class D1 : virtual public Base {
public:
    D1() {
        cout << "D1()" << endl;
    }
};

class D2 : virtual public Base {
public:
    D2() {
        cout << "D2()" << endl;
    }
};

class MI : public D1, public D2 {
public:
    MI() {
        cout << "MI()" << endl;
    }
};

class Final : public MI, public Class {
public:
    Final() {
        cout << "Final()" << endl;
    }
};

int main() {
    //(a)(b)
    Final f;

    //(c)
    Base *pb = nullptr;
    Class *pc = nullptr;
    MI *pmi = nullptr;
    D2 *pd2 = nullptr;
//    pb = new Class;//invalid conversion
//    pc = new Final;//'Class' is an ambiguous base of 'Final'
//    pmi = pb;//invalid conversion
//    pd2 = pmi;//ok
    return 0;
}

Add solution for chapter 18, test 29


#include <iostream>
#include <cassert>

class [[clang::consumable(unconsumed)]] Object {
public:
    Object() {}
    Object(Object&& other) { other.invalidate(); }
    [[clang::callable_when(unconsumed)]]
    void do_something() { assert(m_valid); }

private:
    [[clang::set_typestate(consumed)]]
    void invalidate() { m_valid = false; }
    bool m_valid { true };
};

int main(int, char**) {
    Object object;
    auto other = std::move(object);
    object.do_something();
    return 0;
}

Add example of clang attributes for prevention of use after move.


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

struct thing {
    unsigned int a : 15;
    unsigned int b : 15;
};

thing x;

void f1(int n) {
    for (int i = 0; i < n; i++) {
        x.a++;
    }
}
void f2(int n) {
    for (int i = 0; i < n; i++) {
        x.b++;
    }
}

int main() {
    std::cout << sizeof(thing) << "\n";
    std::thread t1(f1, 1000000);
    std::thread t2(f2, 1000000);
    t1.join();
    t2.join();

    std::cout << x.a << " " << x.b << "\n";

    return 0;
}

Add an experiment that tests some bitfield stuff


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

// trigger a problem in DerivativeApproximation with memory handling

#include <base/logstream.h>
#include <lac/vector.h>
#include <grid/tria.h>
#include <grid/grid_generator.h>
#include <grid/tria_accessor.h>
#include <dofs/hp_dof_handler.h>
#include <fe/fe_dgq.h>
#include <numerics/derivative_approximation.h>

#include <fstream>

template <int dim>
void test ()
{
  Triangulation<dim> tria;
  GridGenerator::hyper_cube(tria);
  tria.refine_global (1);

  hp::FECollection<dim> fe_collection;
  fe_collection.push_back (FE_DGQ<dim> (1));

  hp::DoFHandler<dim> dof_handler(tria);
  dof_handler.distribute_dofs (fe_collection);

  Vector<double> v(dof_handler.n_dofs());
  Vector<float> e(tria.n_active_cells());
  DerivativeApproximation::approximate_gradient (dof_handler, v, e);
}

int main ()
{
  std::ofstream logfile("crash_04/output");
  logfile.precision(2);

  deallog.attach(logfile);
  deallog.depth_console(0);
  deallog.threshold_double(1.e-10);

  test<1> ();
  test<2> ();
  test<3> ();

  deallog << "OK" << std::endl;
}

Add new test that shows failure in DerivativeApproximation


// Simple example file for the the fparser optimization bug
// (c) 2014 by Daniel Schwen
// ========================================================

// $CXX -o optimizer_bug optimizer_bug.cc -I ../../../installed/include/libmesh/ ../../../build/contrib/fparser/.libs/libfparser_la-fp*

#include "../fparser.hh"

#include <iostream>
#include <fstream>
#include <string>

int main()
{
  std::ofstream myfile;
  double p[3] = {0.0, 2.0, 0.1};
  const double step = 0.01;
  FunctionParser fparser;

  // The White Whale
  std::string func = "c*2*(1-c)^2 - c^2*(1-c)*2";

  // Parse the input expression into bytecode
  fparser.Parse(func, "c");
#ifdef FUNCTIONPARSER_SUPPORT_DEBUGGING
  std::cout << "Input Expression:\n" << func << std::endl;
  fparser.PrintByteCode(std::cout);
  std::cout << std::endl;
#endif

  // eval into file
  myfile.open ("pre.dat");
  for (p[0]=0.0; p[0]<=1.0; p[0]+=0.01) myfile << p[0] << ' ' << fparser.Eval(p) << std::endl;
  myfile.close();

  FunctionParser fparser2(fparser);

  // output optimized version
  fparser.Optimize();
#ifdef FUNCTIONPARSER_SUPPORT_DEBUGGING
  std::cout << "Optimized Input Expression:\n" << func << std::endl;
  fparser.PrintByteCode(std::cout);
  std::cout << std::endl;
#endif

  // eval into file
  myfile.open ("post.dat");
  for (p[0]=0.0; p[0]<=1.0; p[0]+=0.01) myfile << p[0] << ' ' << fparser.Eval(p) << std::endl;
  myfile.close();

  // compute difference
  double diff = 0.0;
  for (p[0]=0.0; p[0]<=1.0; p[0]+=step) diff+=step*(fparser.Eval(p)-fparser2.Eval(p));

  std::cout << "Integral of f_optimized()-f_original() on [0,1] = " << diff << "  (should be ~0.0)" << std::endl;
  return 0;
}

Add minimal testcase for optimizer bug in FParser.


#include <iostream>
#include <string>
#include "test16_62_Sales_data.h"

using namespace std;

int main() {
    Sales_data item("book1", 4, 30.0), *p = &item;
    auto pdata = &Sales_data::isbn;
    cout << (item.*pdata)() << endl;
    cout << (p ->* pdata)() << endl;
    return 0;
}

Add solution for chapter 19, test 13


/** \file    xml_parser_test.cc
 *  \brief   Tests the FileUtil::GetFileName() function.
 *  \author  Dr. Johannes Ruscheinski
 */

/*
    Copyright (C) 2015, Library of the University of Tübingen

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <iostream>
#include <stdexcept>
#include "FileUtil.h"
#include "util.h"

__attribute__((noreturn)) void Usage() {
    std::cerr << "usage: " << ::progname << " path\n";
    std::exit(EXIT_FAILURE);
}

int main(int argc, char *argv[]) {
    ::progname = argv[0];
    if (argc != 2)
	Usage();

    try {
	FILE *file(std::fopen(argv[1], "r"));
	std::cout << "File pointer points to \"" << FileUtil::GetFileName(file) << "\".\n";
    } catch(const std::exception &x) {
	Error("caught exception: " + std::string(x.what()));
    }
}

Test for the new FileUtil::GetFileName() functions.


#include "tbb/parallel_sort.h"
#include <math.h>

using namespace tbb;

const int N = 100000;
float a[N], b[N], c[N], d[N];

void SortExample() {
  for( int i = 0; i < N; i++ ) {
     a[i] = sin((double)i);
     b[i] = cos((double)i);
     c[i] = 1/sin((double)i);
     d[i] = 1/cos((double)i);
  }
  parallel_sort(a, a + N);
  parallel_sort(b, b + N, std::greater<float>());
  parallel_sort(c);
  parallel_sort(d, std::greater<float>());
}

int main( void )
{
  SortExample();
  return 0;
}

Add in Intel TBB tests


#include "gtest/gtest.h"
#include "gmock/gmock.h"

#include "Vec2i.h"

TEST(TestVec2i, DisplacingDirectionWithOffsetWillWrap ) {

    ASSERT_EQ( Knights::EDirection::kWest,  Knights::wrapDirection(  Knights::EDirection::kNorth, -1 ) );
    ASSERT_EQ( Knights::EDirection::kNorth, Knights::wrapDirection(  Knights::EDirection::kEast, -1 ) );
    ASSERT_EQ( Knights::EDirection::kEast,  Knights::wrapDirection(  Knights::EDirection::kSouth, -1 ) );
    ASSERT_EQ( Knights::EDirection::kSouth,  Knights::wrapDirection(  Knights::EDirection::kWest, -1 ) );

    ASSERT_EQ( Knights::EDirection::kNorth,  Knights::wrapDirection(  Knights::EDirection::kNorth, -4 ) );
    ASSERT_EQ( Knights::EDirection::kEast, Knights::wrapDirection(  Knights::EDirection::kEast, -4 ) );
    ASSERT_EQ( Knights::EDirection::kSouth,  Knights::wrapDirection(  Knights::EDirection::kSouth, -4 ) );
    ASSERT_EQ( Knights::EDirection::kWest,  Knights::wrapDirection(  Knights::EDirection::kWest, -4 ) );

    ASSERT_EQ( Knights::EDirection::kEast,  Knights::wrapDirection(  Knights::EDirection::kNorth, +1 ) );
    ASSERT_EQ( Knights::EDirection::kSouth, Knights::wrapDirection(  Knights::EDirection::kEast, +1 ) );
    ASSERT_EQ( Knights::EDirection::kWest,  Knights::wrapDirection(  Knights::EDirection::kSouth, +1 ) );
    ASSERT_EQ( Knights::EDirection::kNorth,  Knights::wrapDirection(  Knights::EDirection::kWest, +1 ) );

    ASSERT_EQ( Knights::EDirection::kNorth,  Knights::wrapDirection(  Knights::EDirection::kNorth, +4 ) );
    ASSERT_EQ( Knights::EDirection::kEast, Knights::wrapDirection(  Knights::EDirection::kEast, +4 ) );
    ASSERT_EQ( Knights::EDirection::kSouth,  Knights::wrapDirection(  Knights::EDirection::kSouth, +4 ) );
    ASSERT_EQ( Knights::EDirection::kWest,  Knights::wrapDirection(  Knights::EDirection::kWest, +4 ) );
}

Add basic test for Vec2


/**
 *
 * Authors:
 *   Tim Dwyer <tgdwyer@gmail.com>
 *
 * Copyright (C) 2005 Authors
 *
 * This version is released under the CPL (Common Public License) with
 * the Graphviz distribution.
 * A version is also available under the LGPL as part of the Adaptagrams
 * project: http://sourceforge.net/projects/adaptagrams.
 * If you make improvements or bug fixes to this code it would be much
 * appreciated if you could also contribute those changes back to the
 * Adaptagrams repository.
 */
#include "variable.h"
std::ostream& operator <<(std::ostream &os, const Variable &v) {
	os << "(" << v.id << "=" << v.position() << ")";
	return os;
}

Add the vpsc library for IPSEPCOLA features


// RUN: %llvmgxx -O0 -emit-llvm -S -g -o - %s | grep 'uint 1,' &&
// RUN: %llvmgxx -O0 -emit-llvm -S -g -o - %s | grep 'uint 2,'

class A {
public:
  int x;
protected:
  int y;
private:
  int z;
};

A a;

Make sure C++ protection shows up in debug info


//
// Programmer:    Craig Stuart Sapp <craig@ccrma.stanford.edu>
// Creation Date: Mon 18 Apr 2022 06:34:46 PM UTC
// Last Modified: Mon 18 Apr 2022 06:34:49 PM UTC
// Filename:      imagedemo.cpp
// URL:           https://github.com/craigsapp/humlib/blob/master/cli/imagedemo.cpp
// Syntax:        C++11
// vim:           ts=3 noexpandtab nowrap
//
// Description:   Demonstration of how to use PixelColor class
//                to create simple images.
//

#include "humlib.h"
#include <iostream>

using namespace hum;
using namespace std;

void   processFile         (HumdrumFile& infile, Options& options);
double calculateNpviRhythm (HumdrumFile& infile, Options& option);
double calculateCvPitch    (HumdrumFile& infile, Options& options);
string getReference        (HumdrumFile& infile, const string& targetKey);

///////////////////////////////////////////////////////////////////////////

int main(int argc, char** argv) {
	Options options;
	options.define("x|columns=i:4", "Number of columns in image");
	options.define("y|rows=i:4", "Number of rows in image");
	options.process(argc, argv);

	int rows = options.getInteger("rows");
	int cols = options.getInteger("columns");

	vector<vector<PixelColor>> image;
	for (int y=0; y<(int)image.size(); y++) {
			for (int x=0; x<(int)image[y].size(); x++) {
				image[y][x].setRedF((double)y/rows);
				image[y][x].setBlueF((double)x/cols);
			}
	}

	// Output image header:
	cout << "P3" << endl;
	cout << cols << " " << rows << endl;
	cout << 255 << endl;

	// Output image pixels:
	for (int y=0; y<(int)image.size(); y++) {
			for (int x=0; x<(int)image[y].size(); x++) {
				cout << image[y][x] << " ";
			}
			cout << endl;
	}

	return 0;
}

Add image generation demo file.


class Solution {
public:
    vector<string> divideString(string s, int k, char fill) {
        std::vector<std::string> ret;
        std::string cur;
        for (int i = 0; i < s.size(); i += k) {
            ret.emplace_back(s.substr(i, k));
        }
        while (ret[ret.size()-1].size() < k) {
            ret[ret.size()-1] += fill;
        }
        return ret;
    }
};

Divide a String Into Groups of Size k


/**
 * 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:
    inline bool isLeaf(TreeNode* n) {
        return n->left == NULL && n->right == NULL;
    }
    bool isValidBSTInternal(TreeNode* root, int& minVal, int& maxVal)
    {
        int currMin, currMax;

        if (root == NULL) {
            return true;
        }
        if (isLeaf(root)) {
            minVal = maxVal = root->val;
            return true;
        }

        if (root->left) {
            if (!isValidBSTInternal(root->left, minVal, maxVal)) {
                return false;
            }

            if (root->val <= maxVal) {
                return false;
            }

            currMin = min(root->val, minVal);
            currMax = max(root->val, maxVal);
        } else {
            currMin = currMax = root->val;
        }

        if (root->right) {
            if (!isValidBSTInternal(root->right, minVal, maxVal)) {
                return false;
            }
            if (root->val >= minVal) {
                return false;
            }
            minVal = min(minVal, currMin);
            maxVal = max(maxVal, currMax);
        } else {
            minVal = currMin;
            maxVal = currMax;
        }

        return true;
    }

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

Validate if a binary tree is BST


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

#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"

class DownloadsApiTest : public ExtensionApiTest {
 public:
  void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
  }

  void SetUpTempDownloadsDir() {
    ASSERT_TRUE(tmpdir.CreateUniqueTempDir());
    browser()->profile()->GetPrefs()->SetFilePath(
        prefs::kDownloadDefaultDirectory, tmpdir.path());
  }

 private:
  ScopedTempDir tmpdir;
};

IN_PROC_BROWSER_TEST_F(DownloadsApiTest, DownloadsApiTest) {
  SetUpTempDownloadsDir();
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionTest("downloads")) << message_;
}

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

#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"

class DownloadsApiTest : public ExtensionApiTest {
 public:
  void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
  }

  void SetUpTempDownloadsDir() {
    ASSERT_TRUE(tmpdir.CreateUniqueTempDir());
    browser()->profile()->GetPrefs()->SetFilePath(
        prefs::kDownloadDefaultDirectory, tmpdir.path());
  }

 private:
  ScopedTempDir tmpdir;
};

// This test is disabled. See bug http://crbug.com/130950
IN_PROC_BROWSER_TEST_F(DownloadsApiTest, DISABLED_DownloadsApiTest) {
  SetUpTempDownloadsDir();
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionTest("downloads")) << message_;
}

Disable DownloadsApiTest.DownloadsApiTest because it is too flaky and times out too often.


// RUN: %llvmgxx %s -S -o - | grep '%XX = global int 4'

struct S {
  int  A[2];
};

int XX = (int)&(((struct S*)0)->A[1]);

Add a testcase to check that initializer that CAN be evaluated statically ARE.


#include<iostream>

using namespace std;

class Node{
	public:

	int data;
	Node *next,*head;

	Node(){}

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

	Node *addElement(Node *head, int d){

		Node *nde=new Node(d);
		Node *tmp=head;

		if(head==NULL)
			return nde;
		else{
			while(tmp->next)
				tmp=tmp->next;
		}

		tmp->next=nde;

		return head;
	}

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

		if(head==NULL)
			cout<<"No elements in the list! :(";
		else{
			cout<<"Elements in the list are:\n";
			while(nde){
				cout<<nde->data<<"\n";
				nde=nde->next;
			}
		}
	}
};

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

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

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

	np.displayList(head);
}

Add code to print linked list


#include <iostream>
#include <fstream>

int main()
{
    std::ifstream file("data.txt");
    std::string line;
    // See: https://stackoverflow.com/q/7219062/496459
    // std::getline has no buffer-size limitation, per the standard.
    while(std::getline(file, line))
    {
        std::cout << line << '\n';
    }

    return 0;
}

Add idiom to read lines from a file.


#include <iostream>
#include <cblas.h>
int main ( int argc, char* argv[] ) {
    const long n = ((long)1 << 31) - 1;
    std::cout << n <<std::endl;
    float*  A = new float[n];
    float*  B = new float[n];
    float*  C = new float[1];
    for(long i =0; i <n; i++){
        A[i] = 1;
        B[i] = 1;

    }
    cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 1, 1, n,  1.0, A, n, B, 1, 0.0, C, 1);
    std::cout << *C <<std::endl;
    delete[] A;
    delete[] B;
    delete[] C;
    return 0;
}

Add trivial gemm test for multithread consistency


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

void swap(int &a, int &b)
{
	int temp = a;
	a = b;
	b = temp;
}

void reverse(int *a, int start, int end)
{
	for (int i = 0; i < (end - start + 1) / 2; i++) {
		swap(a[start + i], a[end - i]);
	}
}

void partition(int *a, int n)
{
	int *temp = new int[n];
	int i = 0, j = n - 1;
	for (int k = 1; k < n; k++) {
		if (a[k] < a[0]) {
			temp[i++] = a[k];
		}
		else {
			temp[j--] = a[k];
		}
	}
	temp[i] = a[0];
	memcpy(a, temp, n * sizeof(int));
	reverse(a, i + 1, n - 1);
}

void print(int *a, int n)
{
	for (int i = 0; i < n; i++) {
		cout << a[i] << " ";
	}
}

int main()
{
	int n;
	cin >> n;
	int *a = new int[n];
	for (int i = 0; i < n; i++) {
		cin >> a[i];
	}
	partition(a, n);
	print(a, n);
	return 0;
}

Add the solution to "QuickSort1 - Partition".


class Solution {
public:
    bool isValidSerialization(string preorder) {
        vector<string> h;
        string t;
        for(int i=0;i<preorder.size();){
            if(preorder[i]==','){
                h.push_back(t);
                t.erase(t.begin(),t.end());
                preorder.erase(preorder.begin()+i,preorder.begin()+i+1);
            }else{
                t+=preorder[i];
                i++;
            }
        }
        h.push_back(t);
        int o=look(h,0);
        if(o==h.size()) return true;
        return false;
    }
    int look(vector<string>& h, int x){
        //cout<<x<<" "<<h[x]<<endl;
        if(x>=h.size()) return x+1;
        if(h[x][0]-'#'==0) return x+1;
        int k=look(h,x+1);
        //if(k>=h.size()) return k+1;
        return look(h,k);
    }
};

Verify Preorder Serialization of a Binary Tree


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

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

Revert "Revert "this is my test""


// Copyright 2015 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 "sandbox/linux/services/resource_limits.h"

#include <errno.h>
#include <sys/resource.h>
#include <sys/time.h>
#include <unistd.h>

#include "base/logging.h"
#include "sandbox/linux/tests/test_utils.h"
#include "sandbox/linux/tests/unit_tests.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace sandbox {

namespace {

// Not being able to fork breaks LeakSanitizer, so disable on
// all ASAN builds.
SANDBOX_TEST(ResourceLimits, DISABLE_ON_ASAN(NoFork)) {
  // Make sure that fork will fail with EAGAIN.
  SANDBOX_ASSERT(ResourceLimits::Lower(RLIMIT_NPROC, 0));
  errno = 0;
  pid_t pid = fork();
  // Reap any child if fork succeeded.
  TestUtils::HandlePostForkReturn(pid);
  SANDBOX_ASSERT_EQ(-1, pid);
  CHECK_EQ(EAGAIN, errno);
}

}  // namespace

}  // namespace sandbox

// Copyright 2015 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 "sandbox/linux/services/resource_limits.h"

#include <errno.h>
#include <sys/resource.h>
#include <sys/time.h>
#include <unistd.h>

#include "base/logging.h"
#include "sandbox/linux/tests/test_utils.h"
#include "sandbox/linux/tests/unit_tests.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace sandbox {

namespace {

// Fails on Android: crbug.com/459158
#if !defined(OS_ANDROID)
#define MAYBE_NoFork DISABLE_ON_ASAN(NoFork)
#else
#define MAYBE_NoFork DISABLED_NoFork
#endif  // OS_ANDROID

// Not being able to fork breaks LeakSanitizer, so disable on
// all ASAN builds.
SANDBOX_TEST(ResourceLimits, MAYBE_NoFork) {
  // Make sure that fork will fail with EAGAIN.
  SANDBOX_ASSERT(ResourceLimits::Lower(RLIMIT_NPROC, 0));
  errno = 0;
  pid_t pid = fork();
  // Reap any child if fork succeeded.
  TestUtils::HandlePostForkReturn(pid);
  SANDBOX_ASSERT_EQ(-1, pid);
  CHECK_EQ(EAGAIN, errno);
}

}  // namespace

}  // namespace sandbox

Disable ResourceLimits.NoFork in sandbox_linux_unittests on Android.


Add Chapter 20, exercise 15


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

#include "test16_62_Sales_data.h"

using namespace std;

bool compareIsbn(const Sales_data &lhs, const Sales_data &rhs) {
    return lhs.isbn() < rhs.isbn();
}

typedef tuple<vector<Sales_data>::size_type, vector<Sales_data>::const_iterator,
    vector<Sales_data>::const_iterator> matches;

vector<matches> find_book(const vector<vector<Sales_data>> &files, const string &book) {
    vector<matches> ret;
    for(auto itr = files.cbegin(); itr != files.cend(); ++ itr) {
        auto found = equal_range(itr -> cbegin(), itr -> cend(), book, compareIsbn);
        if(found.first != found.second) {
            ret.push_back(make_tuple(itr - files.cbegin(), found.first, found.second));
        }
    }
    return ret;
}

void reportResults(istream &in, ostream &os, const vector<vector<Sales_data>> &files) {
    string s;
    while(in >> s) {
        auto found = find_book(files, s);
        if(found.empty()) {
            os << s << " is not found in any stores" << endl;
        }
        for(const auto &store : found) {
            os << "store: " << get<0>(store) << " sales: "
            << accumulate(get<1>(store), get<2>(store), Sales_data(s)) << endl;
        }
    }
}

int main() {
    vector<Sales_data> store1 = {{"book1", 2, 30.0}, {"book2", 1, 15.0}, {"book2", 2, 15.0}, {"book4", 5, 20.0}};
    vector<Sales_data> store2 = {{"book1", 1, 30.0}, {"book3", 6, 12.0}, {"book4", 1, 20.0}};
    vector<vector<Sales_data>> files = {store1, store2};
    reportResults(cin, cout, files);

    return 0;
}

Add solution for chapter 17 test 4


#include <iostream>

using namespace std;

const int MAX = 100;

struct Person {
  string firstName;
  string lastName;

  void input() {
    cout << "Enter person's first and last names separated by a space: ";
    cin >> firstName >> lastName;
  }

  void print() {
    cout << firstName << ' ' << lastName << '\n';
  }
};

struct Client {
  Person person;
  double account;

  void input() {
    person.input();

    cout << "Enter account: ";
    cin >> account;
  }

  void print() {
    person.print();
    cout << "Account: " << account << '\n';
  };
};

void inputClients(int n) {
  Client clients[MAX];

  for (int i = 0; i < n; ++i) {
    clients[i].input();
  }
}

void printClients(Client clients[], int n) {
  for (int i = 0; i < n; ++i) {
    clients[i].print();
  }
}

double sumAccounts(Client clients[], int n) {
  double sum = 0;

  for (int i = 0; i < n; ++i) {
    sum += clients[i].account;
  }

  return sum;
}

int main() {
  return 0;
}

Add solution to first problem


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

#include "atom/browser/javascript_environment.h"

#include "base/command_line.h"
#include "gin/array_buffer.h"
#include "gin/v8_initializer.h"

namespace atom {

JavascriptEnvironment::JavascriptEnvironment()
    : initialized_(Initialize()),
      isolate_(isolate_holder_.isolate()),
      isolate_scope_(isolate_),
      locker_(isolate_),
      handle_scope_(isolate_),
      context_(isolate_, v8::Context::New(isolate_)),
      context_scope_(v8::Local<v8::Context>::New(isolate_, context_)) {
}

bool JavascriptEnvironment::Initialize() {
  auto cmd = base::CommandLine::ForCurrentProcess();
  if (cmd->HasSwitch("debug-brk")) {
    // Need to be called before v8::Initialize().
    const char expose_debug_as[] = "--expose_debug_as=v8debug";
    v8::V8::SetFlagsFromString(expose_debug_as, sizeof(expose_debug_as) - 1);
  }
  gin::IsolateHolder::Initialize(gin::IsolateHolder::kNonStrictMode,
                                 gin::ArrayBufferAllocator::SharedInstance());
  return true;
}

}  // namespace atom

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

#include <string>

#include "atom/browser/javascript_environment.h"

#include "base/command_line.h"
#include "gin/array_buffer.h"
#include "gin/v8_initializer.h"

namespace atom {

JavascriptEnvironment::JavascriptEnvironment()
    : initialized_(Initialize()),
      isolate_(isolate_holder_.isolate()),
      isolate_scope_(isolate_),
      locker_(isolate_),
      handle_scope_(isolate_),
      context_(isolate_, v8::Context::New(isolate_)),
      context_scope_(v8::Local<v8::Context>::New(isolate_, context_)) {
}

bool JavascriptEnvironment::Initialize() {
  auto cmd = base::CommandLine::ForCurrentProcess();
  if (cmd->HasSwitch("debug-brk")) {
    // Need to be called before v8::Initialize().
    const char expose_debug_as[] = "--expose_debug_as=v8debug";
    v8::V8::SetFlagsFromString(expose_debug_as, sizeof(expose_debug_as) - 1);
  }

  const std::string js_flags_switch = "js-flags";

  if (cmd->HasSwitch(js_flags_switch)) {
    const char *js_flags_value =
      (cmd->GetSwitchValueASCII(js_flags_switch)).c_str();
    v8::V8::SetFlagsFromString(js_flags_value, strlen(js_flags_value));
  }

  gin::IsolateHolder::Initialize(gin::IsolateHolder::kNonStrictMode,
                                 gin::ArrayBufferAllocator::SharedInstance());

  return true;
}

}  // namespace atom

Add --js-flags support for main thread.


#include <iostream>
#include <vector>

#include <UnitTest++.h>
#include "model/focus-cycle.h"
#include "logging/logging.h"
#include "logging/stream.h"

const int last_window = 9;
StreamLog log(std::cerr);

struct FocusCycleFixture
{
    FocusCycle cycle;
    std::vector<Window> windows;

    FocusCycleFixture() :
        cycle(log)
    {
        for (int win = 0; win < last_window + 1; win++)
        {
            windows.push_back(win);
        }

        cycle.update_window_list(windows);
    }
};

SUITE(FocusModelSuite)
{
    /**
     * Ensures that FocusCycle.get_next returns the correct value in cases when
     * it doesn't wrap around.
     */
    TEST_FIXTURE(FocusCycleFixture, test_gets_windows)
    {
        // It starts at the first window, but get_next() doesn't return it, so
        // we have to start at the second window.
        for (int win = 1; win < last_window + 1; win++)
        {
            CHECK_EQUAL(cycle.get_next(), win);
        }
    }

    /**
     * This ensures that the FocusCycle wraps around when it gets past the
     * last window.
     */
    TEST_FIXTURE(FocusCycleFixture, test_wraparound)
    {
        for (int win = 1; win < last_window + 1; win++)
        {
            cycle.get_next();
        }

        CHECK_EQUAL(cycle.get_next(), 0);
    }

    /**
     * This ensures that setting the focus to a valid window causes the window
     * after it to be returned by get_next.
     */
    TEST_FIXTURE(FocusCycleFixture, test_set_focus)
    {
        // As before, setting the focus means that the window *after* the current
        // focus will be returned by get_next
        cycle.set_focus(5);
        for (int win = 6; win < last_window; win++)
        {
            CHECK_EQUAL(cycle.get_next(), win);
        }
    }

    /**
     * This ensures that setting the focus to an invalid window does nothing.
     */
    TEST_FIXTURE(FocusCycleFixture, test_set_invalid)
    {
        // As before, setting the focus means that the window *after* the current
        // focus will be returned by get_next
        cycle.set_focus(100);
        CHECK_EQUAL(cycle.get_next(), 1);
    }
}

int main()
{
    return UnitTest::RunAllTests();
}

Add a test for FocusCycle.


#include "TaskBase.h"
#include <gtest/gtest.h>
#include <unistd.h>

using namespace tpool;

namespace {
  struct FakeTask : public TaskBase {
    virtual void DoRun()
    {
      sleep(2);
    }
  };
}

TEST(TaskBase, test_GetState)
{
  FakeTask task;

  EXPECT_EQ(TaskBase::INIT, task.GetState());

}

Add unit test for TaskBase.


#include <QApplication>
#include <QMainWindow>
#include <QToolBar>
#include <QDir>
#include <QDebug>
#include "../placesview.h"
#include "libfmqt.h"

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

    Fm::LibFmQt contex;
    QMainWindow win;

    Fm::PlacesView view;
    win.setCentralWidget(&view);

    win.show();
    return app.exec();
}

Add a missing test case for places view.


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

#include <limits.h>

const bool swchar = (wchar_t)-1 > (wchar_t)0;

#ifdef __WCHAR_UNSIGNED__
int signed_test[!swchar];
#else
int signed_test[swchar];
#endif

int max_test[WCHAR_MAX == (swchar ? -(WCHAR_MIN+1) : (wchar_t)-1)];
int min_test[WCHAR_MIN == (swchar ? 0 : -WCHAR_MAX-1)];

Add a missing test for the limits on wchar


#include <iostream>

using namespace std;

bool check_pow_2(int num) {
    if ((num & (num-1)) == 0)
    	return true;
    return false;
}

int main() {
    int num = 2;

    check_pow_2(num) ? cout << "Num is a Power of 2" : cout << "Num is not a power of 2";
    cout << endl;

    num = 5;
    check_pow_2(num) ? cout << "Num is a Power of 2" : cout << "Num is not a power of 2";
    cout << endl;

    return 0;
}

Check power of 2 cpp


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

#include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"

#include "base/rand_util.h"
#include "build/build_config.h"

#if defined(OS_WIN)
#include <windows.h>
#endif

#include "chrome/common/chrome_constants.h"

namespace browser_sync {

static const double kErrorUploadRatio = 0.0;
void ChromeReportUnrecoverableError() {
  // TODO(lipalani): Add this for other platforms as well.
#if defined(OS_WIN)
  // We only want to upload |kErrorUploadRatio| ratio of errors.
  if (kErrorUploadRatio <= 0.0)
    return; // We are not allowed to upload errors.
  double random_number = base::RandDouble();
  if (random_number > kErrorUploadRatio)
    return;

  // Get the breakpad pointer from chrome.exe
  typedef void (__cdecl *DumpProcessFunction)();
  DumpProcessFunction DumpProcess = reinterpret_cast<DumpProcessFunction>(
      ::GetProcAddress(::GetModuleHandle(
                       chrome::kBrowserProcessExecutableName),
                       "DumpProcessWithoutCrash"));
  if (DumpProcess)
    DumpProcess();
#endif  // OS_WIN

}

}  // namespace browser_sync

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

#include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"

#include "base/rand_util.h"
#include "build/build_config.h"

#if defined(OS_WIN)
#include <windows.h>
#endif

#include "chrome/common/chrome_constants.h"

namespace browser_sync {

static const double kErrorUploadRatio = 0.15;
void ChromeReportUnrecoverableError() {
  // TODO(lipalani): Add this for other platforms as well.
#if defined(OS_WIN)
  // We only want to upload |kErrorUploadRatio| ratio of errors.
  if (kErrorUploadRatio <= 0.0)
    return; // We are not allowed to upload errors.
  double random_number = base::RandDouble();
  if (random_number > kErrorUploadRatio)
    return;

  // Get the breakpad pointer from chrome.exe
  typedef void (__cdecl *DumpProcessFunction)();
  DumpProcessFunction DumpProcess = reinterpret_cast<DumpProcessFunction>(
      ::GetProcAddress(::GetModuleHandle(
                       chrome::kBrowserProcessExecutableName),
                       "DumpProcessWithoutCrash"));
  if (DumpProcess)
    DumpProcess();
#endif  // OS_WIN

}

}  // namespace browser_sync

Revert 144124 - [Sync] Set error upload rate to 0.


// RUN: %clang_cc1 -mconstructor-aliases -fms-extensions %s -emit-llvm -o - -triple x86_64-windows-msvc | FileCheck %s

struct __declspec(dllexport) A { virtual ~A(); };
struct __declspec(dllexport) B { virtual ~B(); };
struct __declspec(dllexport) C : A, B { virtual ~C(); };
C::~C() {}

// This thunk should *not* be dllexport.
// CHECK: define linkonce_odr i8* @"\01??_EC@@W7EAAPEAXI@Z"
// CHECK: define dllexport void @"\01??1C@@UEAA@XZ"

Test that deleting destructor thunks are not exported


//===-- asan_dll_thunk.cc -------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of AddressSanitizer, an address sanity checker.
//
// This file defines a family of thunks that should be statically linked into
// the DLLs that have ASan instrumentation in order to delegate the calls to the
// shared runtime that lives in the main binary.
// See https://code.google.com/p/address-sanitizer/issues/detail?id=209 for the
// details.
//===----------------------------------------------------------------------===//

// Only compile this code when buidling asan_dll_thunk.lib
// Using #ifdef rather than relying on Makefiles etc.
// simplifies the build procedure.
#ifdef ASAN_DLL_THUNK
#include <windows.h>

// ------------------------- Helper macros ------------------ {{{1

static FARPROC getRealProcAddressOrDie(const char *name) {
  FARPROC ret = GetProcAddress(GetModuleHandle(NULL), name);
  if (!ret)
    abort();
  return ret;
}

#define WRAP_VV(name)                                                          \
  extern "C" void name() {                                                     \
    typedef void (*fntype)();                                                  \
    fntype fn = (fntype)getRealProcAddressOrDie(#name);                        \
    fn();                                                                      \
  }

#define WRAP_VW(name)                                                          \
  extern "C" void name(void *arg) {                                            \
    typedef void (*fntype)(void *arg);                                         \
    fntype fn = (fntype)getRealProcAddressOrDie(#name);                        \
    fn(arg);                                                                   \
  }

#define WRAP_VWW(name)                                                         \
  extern "C" void name(void *arg1, void *arg2) {                               \
    typedef void (*fntype)(void *, void *);                                    \
    fntype fn = (fntype)getRealProcAddressOrDie(#name);                        \
    fn(arg1, arg2);                                                            \
  }
// }}}

WRAP_VV(__asan_init_v3)

WRAP_VW(__asan_report_store1)
WRAP_VW(__asan_report_store2)
WRAP_VW(__asan_report_store4)
WRAP_VW(__asan_report_store8)
WRAP_VW(__asan_report_store16)
WRAP_VWW(__asan_report_store_n)

WRAP_VW(__asan_report_load1)
WRAP_VW(__asan_report_load2)
WRAP_VW(__asan_report_load4)
WRAP_VW(__asan_report_load8)
WRAP_VW(__asan_report_load16)
WRAP_VWW(__asan_report_load_n)

WRAP_VWW(__asan_register_globals)
WRAP_VWW(__asan_unregister_globals)

// TODO(timurrrr): Add more interface functions on the as-needed basis.

// TODO(timurrrr): Add malloc & friends (see asan_malloc_win.cc).

#endif // ASAN_DLL_THUNK

Add the first version of the RTL thunk that should be linked with instrumented DLLs


#include <iostream>
#include <string>

#include "test16_2_compare.h"

using namespace std;

template <typename It>
auto fcn3(It beg, It end) -> decltype(*beg + 0) {
    return *beg;
}

int main() {
    cout << compare<char*>("hi", "world") << endl;
    cout << compare<string>("dad", "bye") << endl;
    return 0;
}

Add solution for chapter 16 test 39.