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

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

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

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

#include "tensorflow/core/framework/common_shape_fns.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/shape_inference.h"

namespace tensorflow {

// --------------------------------------------------------------------------
REGISTER_OP("Roll")
    .Input("input: T")
    .Input("shift: Tshift")
    .Input("axis: Taxis")
    .Output("output: T")
    .Attr("T: type")
    .Attr("Tshift: {int32,int64}")
    .Attr("Taxis: {int32,int64}")
    .SetShapeFn(shape_inference::UnchangedShape);

}  // namespace tensorflow

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

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

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

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

#include "tensorflow/core/framework/common_shape_fns.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/shape_inference.h"

namespace tensorflow {

// --------------------------------------------------------------------------
REGISTER_OP("Roll")
    .Input("input: T")
    .Input("shift: Tshift")
    .Input("axis: Taxis")
    .Output("output: T")
    .Attr("T: type")
    .Attr("Tshift: {int32,int64}")
    .Attr("Taxis: {int32,int64}")
    .SetShapeFn([](shape_inference::InferenceContext* c) {
      shape_inference::ShapeHandle unused;
      // The `input` must be 1-D or higher
      TF_RETURN_IF_ERROR(c->WithRankAtLeast(c->input(0), 1, &unused));

      return shape_inference::UnchangedShape(c);
    });

}  // namespace tensorflow

Improve shape function check for `tf.roll`


#include"Game.h"

int main(int argc, char **args)
{
	Game *game = new Game();

    const char windowTitle[] = "Chapter 1: Setting up SDL";
	game->init(windowTitle, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, false);

	while (game->isRunning()) {
		game->handleEvents();
		game->update();
		game->render();
	}

	game->clean();

    return 0;
}

Update branch chapter3 and resolve conflicts.


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

#include "GrGLConfig.h"
#include "GrGLInterface.h"

void GrGLClearErr(const GrGLInterface* gl) {
    while (GR_GL_NO_ERROR != gl->fGetError()) {}
}

void GrGLCheckErr(const GrGLInterface* gl,
                  const char* location,
                  const char* call) {
    uint32_t err = GR_GL_GET_ERROR(gl);
    if (GR_GL_NO_ERROR != err) {
        GrPrintf("---- glGetError %x", GR_GL_GET_ERROR(gl));
        if (NULL != location) {
            GrPrintf(" at\n\t%s", location);
        }
        if (NULL != call) {
            GrPrintf("\n\t\t%s", call);
        }
        GrPrintf("\n");
    }
}

void GrGLResetRowLength(const GrGLInterface* gl) {
    if (gl->supportsDesktop()) {
        GR_GL_CALL(gl, PixelStorei(GR_GL_UNPACK_ROW_LENGTH, 0));
    }
}

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

#if GR_GL_LOG_CALLS
    bool gLogCallsGL = !!(GR_GL_LOG_CALLS_START);
#endif

#if GR_GL_CHECK_ERROR
    bool gCheckErrorGL = !!(GR_GL_CHECK_ERROR_START);
#endif

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

#include "GrGLConfig.h"
#include "GrGLInterface.h"

void GrGLClearErr(const GrGLInterface* gl) {
    while (GR_GL_NO_ERROR != gl->fGetError()) {}
}

void GrGLCheckErr(const GrGLInterface* gl,
                  const char* location,
                  const char* call) {
    uint32_t err = GR_GL_GET_ERROR(gl);
    if (GR_GL_NO_ERROR != err) {
        GrPrintf("---- glGetError %x", err);
        if (NULL != location) {
            GrPrintf(" at\n\t%s", location);
        }
        if (NULL != call) {
            GrPrintf("\n\t\t%s", call);
        }
        GrPrintf("\n");
    }
}

void GrGLResetRowLength(const GrGLInterface* gl) {
    if (gl->supportsDesktop()) {
        GR_GL_CALL(gl, PixelStorei(GR_GL_UNPACK_ROW_LENGTH, 0));
    }
}

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

#if GR_GL_LOG_CALLS
    bool gLogCallsGL = !!(GR_GL_LOG_CALLS_START);
#endif

#if GR_GL_CHECK_ERROR
    bool gCheckErrorGL = !!(GR_GL_CHECK_ERROR_START);
#endif

Fix gl error debug print.


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

#include <dpcdecl.h>
#include <dmgr.h>
#include <depp.h>

uint8_t
peek(int reg)
{
	HIF deviceHandle;
	int status;
	char deviceName[32] = "Cr2s2";
	uint8_t data;

	status = DmgrOpen(&deviceHandle, deviceName);
	if (!status) {
		printf("Problem opening device, code %d\n", DmgrGetLastError());
		return 0;
	}

	status = DeppEnable(deviceHandle);
	if (!status) {
		printf("Problem enabling port 0, code %d\n", DmgrGetLastError());
		return 0;
	}

	DeppGetReg(deviceHandle, reg, &data, fFalse);

	status = DeppDisable(deviceHandle);
	if (!status) {
		printf("Problem disabling DEPP, code %d\n", DmgrGetLastError());
		return 0;
	}
	DmgrClose(deviceHandle);

	return data;
}

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

	if (argc != 2) {
		printf("usage: %s register\n", argv[0]);
		exit(1);
	}

	reg = atoi(argv[1]);

	printf("%x\n", peek(reg));

	return 0;
}

Add ability to peek registers through USB, beautify code.


#include <sys/types.h> /* size_t, ssize_t */
#include <stdarg.h> /* va_list */
#include <stddef.h> /* NULL */
#include <stdint.h> /* int64_t */

#include "kcgi.h"

#include <iostream>

int
main(int argc, char *argv[])
{
	enum kcgi_err	  er;
	struct kreq	  r;
	const char *const pages[1] = { "index" };

	/* Set up our main HTTP context. */

	er = khttp_parse(&r, NULL, 0, pages, 1, 0);
	if (KCGI_OK != er)
		return 0;

	khttp_head(&r, kresps[KRESP_STATUS],
	  "%s", khttps[KHTTP_200]);
	khttp_head(&r, kresps[KRESP_CONTENT_TYPE],
	  "%s", kmimetypes[r.mime]);
	khttp_body(&r);
	khttp_puts(&r, "Hello, world!\n");

	std::cerr << "Said hello!";

	khttp_free(&r);
	return 0;
}

Add a sample C++ file.


// This file is part of playd.
// playd is licensed under the MIT licence: see LICENSE.txt.

/**
 * @file
 * Tests for command results.
 */

#include <sstream>

#include "catch.hpp"
#include "../cmd_result.hpp"
#include "dummy_response_sink.hpp"
// This file is part of playd.
// playd is licensed under the MIT licence: see LICENSE.txt.

/**
 * @file
 * Tests for error classes.
 */

#include "catch.hpp"

#include "../errors.hpp"

SCENARIO("Errors contain a retrievable message", "[error]") {
	GIVEN("An Error") {
		Error e = NetError("need an RS-232 Interface Lead");

		WHEN("Message() is called") {
			auto s = e.Message();

			THEN("the result is the message given in the Error's ctor") {
				REQUIRE(s == "need an RS-232 Interface Lead");
			}
		}
	}
}

Add tiny test for Error::Message().


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

using namespace Halide;

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

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

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

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

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

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

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


#include <iostream>

namespace
{

class Repl
{
  std::istream& in_;
  std::ostream& out_;
  std::string prompt_ = "mclisp> ";

  public:
    Repl(std::istream& in=std::cin, std::ostream& out=std::cout) : in_(in), out_(out) {};
    int loop();
};

int Repl::loop()
{
  std::string val;

  while (val != "quit")
  {
    out_ << prompt_;
    in_ >> val;
    out_ << val << std::endl;
  }
  return 0;
}

}; //end namespace

int main(int argc, const char **argv)
{
  Repl repl;
  return repl.loop();
}

Add a very dumb echo repl.


#include <stdio.h>
#include "../include/AliHLTTPCGeometry.h" //We use this to convert from row number to X

struct ClusterData {
	int fId;
	int fRow;
	float fX;
	float fY;
	float fZ;
	float fAmp;
};

int main(int argc, char** argv)
{
	for (int iEvent = 0;iEvent < 2;iEvent++) //Multiple events go to multiple files, named event.[NUM].dump
	{
		char filename[1024];
		sprintf(filename, "event.%d.dump", iEvent);
		FILE* fp = fopen(filename, "w+b");
		int clusterId = 0; //Here we count up the cluster ids we fill (must be unique).
		for (int iSector = 0;iSector < 36;iSector++) //HLT Sector numbering, sectors go from 0 to 35, all spanning all rows from 0 to 158.
		{
			int nNumberOfHits = 100; //For every sector we first have to fill the number of hits in this sector to the file
			fwrite(&nNumberOfHits, sizeof(nNumberOfHits), 1, fp);

			ClusterData* tempBuffer = new ClusterData[nNumberOfHits]; //As example, we fill 100 clusters per sector
			for (int i = 0;i < nNumberOfHits;i++)
			{
			    tempBuffer[i].fId = clusterId++;
			    tempBuffer[i].fRow = i; //We fill one hit per TPC row
			    tempBuffer[i].fX = AliHLTTPCGeometry::Row2X(i);
			    tempBuffer[i].fY = i *iSector * 0.03f;
			    tempBuffer[i].fZ = i * (1 + iEvent) * (iSector >= 18 ? -1 : 1);
			    tempBuffer[i].fAmp = 100; //Arbitrary amplitude
			}

			fwrite(tempBuffer, sizeof(tempBuffer[0]), nNumberOfHits, fp);
			delete tempBuffer;
		}
		fclose(fp);
	}
	return(0);
}

Add example file to create event dump manually


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

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

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

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

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

TEST(DamageTask, GetTaskID)
{
    const DamageTask damage(EntityType::ENEMIES, 2);
    EXPECT_EQ(damage.GetTaskID(), +TaskID::DAMAGE);
}

TEST(DamageTask, Run)
{
    GameAgent agent(CardClass::ROGUE, CardClass::DRUID, PlayerType::PLAYER1);
    Player& player1 = agent.GetPlayer1();

    std::vector<Card> cards;
    cards.reserve(5);

    const std::string name = "test";
    for (size_t i = 0; i < 5; ++i)
    {
        const auto id = static_cast<char>(i + 0x30);
        cards.emplace_back(GenerateMinionCard(name + id, 1, 1));
        PlayMinionCard(player1, cards[i]);
    }

    DamageTask damage(EntityType::FRIENDS, 1);
    MetaData result = damage.Run(player1);

    EXPECT_EQ(result, MetaData::DAMAGE_SUCCESS);
    EXPECT_EQ(player1.GetField().size(), 0u);
}

Add unit test for DamageTask


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

vector<int> BreadthFirstSearch(int vertex,vector<int> adjacent[],int start_vertex,int destination){
	queue<int> que;
    //bfsPath will store the path
	vector<int> bfsPath;
    //this array will take care of duplicate traversing
	bool visited[vertex];
    vector<int>::iterator it;
	que.push(start_vertex);
    bfsPath.push_back(start_vertex);
	visited[start_vertex]=true;
    int flag=0;
	while(!que.empty()){
		int tem = que.front();
		que.pop();
		for(it = adjacent[tem].begin();it<adjacent[tem].end();it++){
            if(!visited[*it]){
                bfsPath.push_back(*it);
                //if destination is found
                if(*it==destination){
                    flag=1;
                    break;
                }
                visited[*it] = true;
                que.push(*it);
            }
        }
        if(flag==1){
            break;
        }
	}
    //if we will not find the destination
    if(flag==0){
        bfsPath.clear();
    }
    return bfsPath;
}

//this fn will print the path
void printTraversal(vector<int>bfsPath){
    vector<int>::iterator it;
    for(it = bfsPath.begin();it<bfsPath.end();it++){
        cout<<*it<<endl;
    }
}

int main() {
    //number of vertex
	int vertex = 4;
	vector<int> adjacent[vertex];
	adjacent[0].push_back(1);
	adjacent[0].push_back(3);
	adjacent[1].push_back(2);
	adjacent[2].push_back(3);
    //starting vertex
	int start_vertex = 0;
    //destination
    int destination = 3;
	vector<int> bfsPath = BreadthFirstSearch(vertex,adjacent,start_vertex,destination);
    if(!bfsPath.empty()){
    printTraversal(bfsPath);
    }else{
        cout<<"path not found";
    }
    return 0;
}

Add Breadth First Search in Cpp


// RUN: %clang_cc1 -fopenmp -x c++ -triple x86_64-apple-darwin10  -stack-protector 2 -emit-llvm -o - %s | FileCheck %s

// Check that function attributes are added to the OpenMP runtime functions.

template <class T>
struct S {
  T f;
  S(T a) : f(a) {}
  S() : f() {}
  operator T() { return T(); }
  ~S() {}
};

// CHECK: define internal void @.omp.copyprivate.copy_func(i8*, i8*) [[ATTR0:#[0-9]+]] {

void foo0();

int foo1() {
  char a;

#pragma omp parallel
  a = 2;
#pragma omp single copyprivate(a)
  foo0();

  return 0;
}

// CHECK: define internal void @.omp_task_privates_map.({{.*}}) [[ATTR3:#[0-9]+]] {
// CHECK: define internal i32 @.omp_task_entry.({{.*}}) [[ATTR0]] {
// CHECK: define internal i32 @.omp_task_destructor.({{.*}}) [[ATTR0]] {

int foo2() {
  S<double> s_arr[] = {1, 2};
  S<double> var(3);
#pragma omp task private(s_arr, var)
  s_arr[0] = var;
  return 0;
}

// CHECK: define internal void @.omp.reduction.reduction_func(i8*, i8*) [[ATTR0]] {

float foo3(int n, float *a, float *b) {
  int i;
  float result;

#pragma omp parallel for private(i) reduction(+:result)
  for (i=0; i < n; i++)
    result = result + (a[i] * b[i]);
  return result;
}

// CHECK: attributes [[ATTR0]] = {{{.*}} sspstrong {{.*}}}
// CHECK: attributes [[ATTR3]] = {{{.*}} sspstrong {{.*}}}

Add a test case for r251476.


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

#include <shogun/features/streaming/StreamingDenseFeatures.h>
#include <shogun/io/CSVFile.h>
#include <shogun/io/streaming/StreamingAsciiFile.h>
#include <unistd.h>
#include <gtest/gtest.h>

using namespace shogun;

TEST(StreamingDenseFeatures, example_reading)
{
	index_t n=20;
	index_t dim=2;
	std::string tmp_name = "/tmp/StreamingDenseFeatures_reading.XXXXXX";
	char* fname = mktemp(const_cast<char*>(tmp_name.c_str()));

	SGMatrix<float64_t> data(dim,n);
	for (index_t i=0; i<dim*n; ++i)
		data.matrix[i] = sg_rand->std_normal_distrib();

	CDenseFeatures<float64_t>* orig_feats=new CDenseFeatures<float64_t>(data);
	//CCSVFile* saved_features = new CCSVFile(fname, 'w');
	CAsciiFile* saved_features = new CAsciiFile(fname, 'w');
	orig_feats->save(saved_features);
	saved_features->close();
	SG_UNREF(saved_features);

	CStreamingAsciiFile* input = new CStreamingAsciiFile(fname);
	CStreamingDenseFeatures<float64_t>* feats = new CStreamingDenseFeatures<float64_t>(input, false, 5);

	index_t i = 0;
	feats->start_parser();
	while (feats->get_next_example())
	{
		SGVector<float64_t> example = feats->get_vector();
		SGVector<float64_t> expected = orig_feats->get_feature_vector(i);

		ASSERT_EQ(dim, example.vlen);

		for (index_t j = 0; j < dim; j++)
			EXPECT_NEAR(expected.vector[j], example.vector[j], 1E-6);

		feats->release_example();
		i++;
	}
	feats->end_parser();

	SG_UNREF(orig_feats);
	SG_UNREF(feats);
}

Add basic unit test for StreamingDenseFeatures reading


//   Copyright 2016 otris software AG
//
//   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 <ews/ews.hpp>
#include <ews/ews_test_support.hpp>
#include <exception>
#include <iostream>
#include <ostream>
#include <stdlib.h>
#include <string>

int main()
{
    int res = EXIT_SUCCESS;
    ews::set_up();

    try
    {
        const auto env = ews::test::environment();
        auto service = ews::service(env.server_uri, env.domain, env.username,
                                    env.password);

        ews::distinguished_folder_id inbox = ews::standard_folder::inbox;

        auto folder_ids = service.find_folder(inbox);
        if (!folder_ids.empty())
        {
            // Get first folder
            auto folder = service.get_folder(folder_ids.front());
            auto name = folder.get_display_name();

				// Add suffix to folders display
				// or remove suffix if already exists
            auto pos = name.find("_updated");
            if (pos == std::string::npos)
            {
                name += "_updated";
            }
            else
            {
                name = name.substr(0, pos);
            }

            // Create property and update
            auto prop = ews::property(
                ews::folder_property_path::display_name, name);
            auto new_id = service.update_folder(folder.get_folder_id(), prop);
        }
    }
    catch (std::exception& exc)
    {
        std::cout << exc.what() << std::endl;
        res = EXIT_FAILURE;
    }

    ews::tear_down();
    return res;
}

Add example for UpdateFolder operation


/*
 * Problem: Find Merge Point of Two Lists
 * Author: Anirudha Bose <ani07nov@gmail.com>

   Find merge point of two linked lists
   Node is defined as
     struct Node
     {
         int data;
         Node* next;
     }
 */

int lengthOfList(Node* head)
{
    int l=0;
    while(head != NULL)
    {
        head = head->next;
        l++;
    }
    return l+1;
}

int FindMergeNode(Node *headA, Node *headB)
{
    int A = lengthOfList(headA), B = lengthOfList(headB);

    int c = 0;
    if(A>B)
    {
        while(c != A-B)
        {
            headA = headA->next;
            c++;
        }
    }
    else
    {
        while(c != B-A)
        {
            headB = headB->next;
            c++;
        }
    }

    while(headA != NULL && headB != NULL)
    {
        if(headA == headB)
            return headA->data;
        headA = headA->next;
        headB = headB->next;
    }
    return -1;
}

Merge point of two lists


#include <cassert>
#include <gtest/gtest.h>
#include <system.h>
#include <basecpu.h>

#define TEST_CLASS BaseCPUTest

class BaseTestCPU : public BaseCPU {
public:
    BaseTestCPU(int maxTicks, const System &sys) : maxTicks(maxTicks), ticks(0), resets(0), BaseCPU(sys) { }
    void reset() { resets++; }
    void tick() {
        assert(isRunning());
        ticks++;
        if(ticks>= maxTicks) {
            stop();
        }
    }

    int ticks;
    int resets;
    int maxTicks;
};

const int TEST_TICK_COUNT = 3;

class TEST_CLASS : public testing::Test {
protected:
    TEST_CLASS() : cpu(TEST_TICK_COUNT, dummySystem) { }
    BaseTestCPU cpu;
    System dummySystem;
};

TEST_F(TEST_CLASS, TestRunLoop) {
    ASSERT_FALSE(cpu.isRunning()) << "Incorrect initial CPU running state";
    ASSERT_EQ(cpu.ticks, 0) << "Incorrect initial CPU tick count";
    ASSERT_EQ(cpu.resets, 0) << "Incorrect initial CPU reset count";
    cpu.startup();
    ASSERT_FALSE(cpu.isRunning()) << "Incorrect final CPU running state";
    ASSERT_EQ(cpu.ticks, TEST_TICK_COUNT) << "Incorrect final CPU tick count";
    ASSERT_EQ(cpu.resets, 1) << "Incorrect initial CPU reset count";
}

Create tests for base cpu


// 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 "content/renderer/pepper/usb_key_code_conversion.h"

#include "base/basictypes.h"
#include "third_party/WebKit/public/web/WebInputEvent.h"
#include "ui/events/keycodes/dom4/keycode_converter.h"

using blink::WebKeyboardEvent;

namespace content {

uint32_t UsbKeyCodeForKeyboardEvent(const WebKeyboardEvent& key_event) {
  // Extract the scancode and extended bit from the native key event's lParam.
  int scancode = (key_event.nativeKeyCode >> 16) & 0x000000FF;
  if ((key_event.nativeKeyCode & (1 << 24)) != 0)
    scancode |= 0xe000;

  ui::KeycodeConverter* key_converter = ui::KeycodeConverter::GetInstance();
  return key_converter->NativeKeycodeToUsbKeycode(scancode);
}

const char* CodeForKeyboardEvent(const WebKeyboardEvent& key_event) {
  ui::KeycodeConverter* key_converter = ui::KeycodeConverter::GetInstance();
  return key_converter->NativeKeycodeToCode(key_event.nativeKeyCode);
}

}  // namespace content

// 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 "content/renderer/pepper/usb_key_code_conversion.h"

#include "base/basictypes.h"
#include "third_party/WebKit/public/web/WebInputEvent.h"
#include "ui/events/keycodes/dom4/keycode_converter.h"

using blink::WebKeyboardEvent;

namespace content {

uint32_t UsbKeyCodeForKeyboardEvent(const WebKeyboardEvent& key_event) {
  // Extract the scancode and extended bit from the native key event's lParam.
  int scancode = (key_event.nativeKeyCode >> 16) & 0x000000FF;
  if ((key_event.nativeKeyCode & (1 << 24)) != 0)
    scancode |= 0xe000;

  ui::KeycodeConverter* key_converter = ui::KeycodeConverter::GetInstance();
  return key_converter->NativeKeycodeToUsbKeycode(scancode);
}

const char* CodeForKeyboardEvent(const WebKeyboardEvent& key_event) {
  // Extract the scancode and extended bit from the native key event's lParam.
  int scancode = (key_event.nativeKeyCode >> 16) & 0x000000FF;
  if ((key_event.nativeKeyCode & (1 << 24)) != 0)
    scancode |= 0xe000;

  ui::KeycodeConverter* key_converter = ui::KeycodeConverter::GetInstance();
  return key_converter->NativeKeycodeToCode(scancode);
}

}  // namespace content

Fix CodeForKeyboardEvent to properly calculate the scancode.


// 83. Remove Duplicates from Sorted List
/**
 * Given a sorted linked list, delete all duplicates such that each element appear only once.
 *
 * For example,
 * Given 1->1->2, return 1->2.
 * Given 1->1->2->3->3, return 1->2->3.
 *
 * Tags: Linked List
 *
 * Author: Kuang Qin
 */

#include <iostream>

using namespace std;

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

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        ListNode *curr = head;
        while (curr != NULL) {
            // search and delete duplicates
            while (curr->next != NULL && curr->next->val == curr->val) {
                curr->next = curr->next->next;
            }

            // move forward
            curr = curr->next;
        }

        return head;
    }
};

// recursive
class Solution_Recursive {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if (head == NULL || head->next == NULL) {
            return head;
        }

        head->next = deleteDuplicates(head->next);

        // duplicates
        if (head->val == head->next->val) {
            return head->next;
        }

        return head;
    }
};

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

    return 0;
}

Add Solution for 083 Remove Duplicates from Sorted List


//
// Created by Ivan Shynkarenka on 15.02.2016.
//

#include "cppbenchmark.h"

#include "debug/stack_trace.h"

const uint64_t iterations = 1000000;

BENCHMARK("Stack trace")
{
    uint64_t crc = 0;

    for (uint64_t i = 0; i < iterations; ++i)
        crc += CppCommon::StackTrace().frames().size();

    // Update benchmark metrics
    context.metrics().AddIterations(iterations - 1);
    context.metrics().SetCustom("CRC", crc);
}

BENCHMARK_MAIN()

Add capture stack trace benchmark


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

using namespace Halide;

int main(int argc, char **argv) {
    Param<float> val;

    Func f, g;
    Var x, y;

    f(x, y) = val + cast<uint8_t>(x);
    g(x, y) = f(x, y) + f(x - 1, y) + f(x + 1, y);

    g.split(y, y, _, 16);
    f.store_root();
    f.compute_at(g, y).memoize();

    val.set(23.0f);
    Image<uint8_t> out = g.realize(128, 128);

    for (int32_t i = 0; i < 128; i++) {
        for (int32_t j = 0; j < 128; j++) {
            assert(out(i, j) == (uint8_t)(3 * 23 + i + (i - 1) + (i + 1)));
        }
    }
}

Add error test for memoizing a Func with compute and storage at different levels.


/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You 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 Igor V. Stolyarov
 * @version $Revision$
 */

#include "LUTTables.h"
#include <string.h>

unsigned char mulLUT[256][256];  /* Multiply Luckup table */
unsigned char divLUT[256][256];  /* Divide Luckup table   */
bool mulLUT_inited = false;
bool divLUT_inited = false;

void init_mulLUT(){
    int i, j;
    if(mulLUT_inited) return;
    for(i = 0; i < 256; i++){
        for(j = 0; j < 256; j++){
            mulLUT[i][j] = (int)(((float)i * j) / 255 + 0.5);
        }
    }
    mulLUT_inited = true;
}

void init_divLUT(){
    int i, j;
    if(divLUT_inited) return;
    memset(divLUT[0], 0, 256);
    for(i = 1; i < 256; i++){
        for(j = 0; j <= i; j++){
            divLUT[i][j] = (int)(((float)j) / i * 255 + 0.5);
        }
        for(; j < 256; j++){
            divLUT[i][j] = 0;
        }
    }
    divLUT_inited = true;
}

Patch for HARMONY-3677 "[classlib][awt] Results of running checker tool"


/**
    Очень простой вводный пример на демонстрацию исключений
*/

#include <iostream>
#include <exception>
#include <string>

struct MyError
{
    std::string msg;
};

class Test
{
public:
    ~Test()
    {
        std::cout << "Вызван деструктор\n";
    }
};

double sin_by_sharnin(double x)
{
    const size_t fakt_3 = 6,
                 fakt_5 = 120;
    Test t1, t2;

    if (x == 1.0) {
        throw MyError{"Неправильный аргумент"};
    }

    if (x == 2.0) {
        /// ради теста, выбрасываем исключение типа double
        /// не стоит так делать в рабочих программах
        throw 5.78;
    }

    if (x == 3.0) {
        /// выбрасываем базовый тип исключений для всей стандартной библиотеки
        throw std::exception{};
    }

    t2 = t1; /// демонстрация работы деструкторов, даже при выбросе исключения
    return x - (x*x*x)/fakt_3 + (x*x*x*x*x)/fakt_5;
}

void find_sins(int code)
{
    std::cout << "sin(1.57) = "
        << sin_by_sharnin(1.57) << "\n";

    std::cout << "sin(0.87) = "
        << sin_by_sharnin(0.87) << "\n";

    if (code == 1) {
        std::cout << "sin(1.0) = "
            << sin_by_sharnin(1.0) << "\n";
    } else if (code == 2) {
        std::cout << "sin(2.0) = "
            << sin_by_sharnin(2.0) << "\n";
    } else {
        std::cout << "sin(3.0) = "
            << sin_by_sharnin(3.0) << "\n";
    }
}

int main()
{
    using namespace std;

    int code;
    cout << "Введите целое число: ";
    cin >> code;

    Test t1, t2;
    t2 = t1;

    try {
        find_sins(code);
    }
    catch (const MyError& err) {
        cout << "Исключение перехвачено c сообщением: ";
        cout << err.msg << "\n";
    }
    catch (const double&) {
        cout << "Исключение типа double перехвачено\n";
    }
    catch (const std::exception& exc) {
        cout << "Исключение типа exception перехвачено\n";
        cout << exc.what() << "\n";
    }
}

Add simplest exception example from lesson


/*
 * Copyright 2015 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "Benchmark.h"
#include "SkCanvas.h"
#include "SkMatrix.h"
#include "SkPaint.h"
#include "SkString.h"

/**
 * This bench measures the rendering time of SkCanvas::drawBitmap with different anti-aliasing /
 * matrix combinations.
 */

class DrawBitmapAABench : public Benchmark {
public:
    DrawBitmapAABench(bool doAA, const SkMatrix& matrix, const char name[])
        : fMatrix(matrix)
        , fName("draw_bitmap_") {

        fPaint.setAntiAlias(doAA);
        fName.appendf("%s_%s", doAA ? "aa" : "noaa", name);
    }

protected:
    const char* onGetName() override {
        return fName.c_str();
    }

    void onPreDraw() override {
        fBitmap.allocN32Pixels(200, 200);
        fBitmap.eraseARGB(255, 0, 255, 0);
    }

    void onDraw(const int loops, SkCanvas* canvas) override {
        canvas->concat(fMatrix);
        for (int i = 0; i < loops; i++) {
            canvas->drawBitmap(fBitmap, 0, 0, &fPaint);
        }
    }

private:
    SkPaint  fPaint;
    SkMatrix fMatrix;
    SkString fName;
    SkBitmap fBitmap;

    typedef Benchmark INHERITED;
};

DEF_BENCH( return new DrawBitmapAABench(false, SkMatrix::MakeScale(1), "ident"); )

DEF_BENCH( return new DrawBitmapAABench(false, SkMatrix::MakeScale(1.17f), "scale"); )

DEF_BENCH( return new DrawBitmapAABench(false, SkMatrix::MakeTrans(17.5f, 17.5f), "translate"); )

DEF_BENCH(
    SkMatrix m;
    m.reset();
    m.preRotate(15);
    return new DrawBitmapAABench(false, m, "rotate");
)

DEF_BENCH( return new DrawBitmapAABench(true, SkMatrix::MakeScale(1), "ident"); )

DEF_BENCH( return new DrawBitmapAABench(true, SkMatrix::MakeScale(1.17f), "scale"); )

DEF_BENCH( return new DrawBitmapAABench(true, SkMatrix::MakeTrans(17.5f, 17.5f), "translate"); )

DEF_BENCH(
    SkMatrix m;
    m.reset();
    m.preRotate(15);
    return new DrawBitmapAABench(true, m, "rotate");
)

Add a bench for measuring drawBitmap anti-aliasing overhead


//===-- ubsan_init_standalone_preinit.cc
//------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Initialization of standalone UBSan runtime.
//
//===----------------------------------------------------------------------===//

#include "ubsan_platform.h"
#if !CAN_SANITIZE_UB
#error "UBSan is not supported on this platform!"
#endif

#include "sanitizer_common/sanitizer_internal_defs.h"
#include "ubsan_init.h"

#if SANITIZER_CAN_USE_PREINIT_ARRAY
__attribute__((section(".preinit_array"), used)) void (*__local_ubsan_preinit)(
    void) = __ubsan::InitAsStandalone;
#endif // SANITIZER_CAN_USE_PREINIT_ARRAY

Add file missing from r313583


#include <iostream>
#include <cstring>

using namespace std;

struct WordTranslation {
    char word[100], translation[100];
    WordTranslation(const char _word[] = "", const char _translation[] = "") {
        strcpy(word, _word);
        strcpy(translation, _translation);
    }
};

class Dictionary {
    int size;
    WordTranslation words[1000];

    void removeWordAt(int index) {
        size--;
        for (int i = index; i < size; i++) {
            words[i] = words[i+1];
        }
    }

public:

    Dictionary() {
        size = 0;
    }

    void addWord(WordTranslation wordTranslation) {
        words[size++] = wordTranslation;
    }

    void removeWord(const char word[]) {
        for (int i = 0; i < size; i++) {
            if (strcmp(word, words[i].word) == 0) {
                removeWordAt(i);
                break;
            }
        }
    }

    WordTranslation findWord(const char word[]) {
        for (int i = 0; i < size; i++) {
            if (strcmp(word, words[i].word) == 0) {
                return words[i];
            }
        }

        return WordTranslation(word, word);
    }

    void translate(const char text[]) {
        const char *lastWhiteSpace = text, *currentWhiteSpace = strstr(text, " ");

        while (currentWhiteSpace != NULL) {
            char word[100] = {'\0'};

            strncpy(word, lastWhiteSpace, currentWhiteSpace - lastWhiteSpace);
            cout << findWord(word).translation << " ";

            lastWhiteSpace = currentWhiteSpace + 1;
            currentWhiteSpace = strstr(lastWhiteSpace, " ");
        }
        char word[100] = {'\0'};
        strcpy(word, lastWhiteSpace);
        cout << findWord(word).translation;

        cout << endl;
    }
};

int main() {
    Dictionary dictionary;
    dictionary.addWord(WordTranslation("tazi", "this"));
    dictionary.addWord(WordTranslation("zadacha", "task"));
    dictionary.addWord(WordTranslation("e", "is"));
    dictionary.addWord(WordTranslation("trudna", "hard"));

    dictionary.translate("tazi zadacha e trudna");

    dictionary.removeWord("zadacha");

    dictionary.translate("tazi zadacha e trudna");

    return 0;
}

Add solution to the dictionary task


// The rule of zero

#include <memory>

class shallow
{
	private:
		std::shared_ptr<int> p = std::make_shared<int>(5);
};

class deep
{
	public:
		deep() = default;

		deep(deep const& other)
			: p{std::make_unique<int>(*other.p)}
		{ }

	private:
		std::unique_ptr<int> p = std::make_unique<int>(5);
};

// Use existing RAII types to encapsulate and safely manage
// dynamically allocated resources.
//
// The class `shallow` ([5-9]) manages a dynamically allocated `int`
// object. Rather than manage this object manually, we use a
// [`std::shared_ptr`](cpp/memory/shared_ptr) on [15] to take
// ownership of the object. The lifetime of this object is now
// tied to the lifetime of the `foo` object that contains it
// without having to implement any constructors or destructors. If
// a `shallow` object is copied, the copy will share ownership of
// this resource.
//
// If we want to perform a deep copy, we can instead use a
// [`std::unique_ptr`](cpp/memory/unique_ptr) and implement a
// copy constructor to copy the resource, as shown with the `deep`
// class on [11-22].

int main()
{
	shallow s1;
	shallow s2 = s1;

	deep d1;
	deep d2 = d1;
}

Add rule of zero sample


//===-- UnreachableBlockElim.cpp - Remove unreachable blocks for codegen --===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass is an extremely simple version of the SimplifyCFG pass.  Its sole
// job is to delete LLVM basic blocks that are not reachable from the entry
// node.  To do this, it performs a simple depth first traversal of the CFG,
// then deletes any unvisited nodes.
//
// Note that this pass is really a hack.  In particular, the instruction
// selectors for various targets should just not generate code for unreachable
// blocks.  Until LLVM has a more systematic way of defining instruction
// selectors, however, we cannot really expect them to handle additional
// complexity.
//
//===----------------------------------------------------------------------===//

#include "llvm/CodeGen/Passes.h"
#include "llvm/Function.h"
#include "llvm/Pass.h"
#include "llvm/Support/CFG.h"
#include "Support/DepthFirstIterator.h"
using namespace llvm;

namespace {
  class UnreachableBlockElim : public FunctionPass {
    virtual bool runOnFunction(Function &F);
  };
  RegisterOpt<UnreachableBlockElim>
  X("unreachableblockelim", "Remove unreachable blocks from the CFG");
}

FunctionPass *llvm::createUnreachableBlockEliminationPass() {
  return new UnreachableBlockElim();
}

bool UnreachableBlockElim::runOnFunction(Function &F) {
  std::set<BasicBlock*> Reachable;

  // Mark all reachable blocks.
  for (df_ext_iterator<Function*> I = df_ext_begin(&F, Reachable),
         E = df_ext_end(&F, Reachable); I != E; ++I)
    /* Mark all reachable blocks */;

  // Loop over all dead blocks, remembering them and deleting all instructions
  // in them.
  std::vector<BasicBlock*> DeadBlocks;
  for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
    if (!Reachable.count(I)) {
      DeadBlocks.push_back(I);
      for (succ_iterator SI = succ_begin(&*I), E = succ_end(&*I); SI != E; ++SI)
        (*SI)->removePredecessor(I);
      I->dropAllReferences();
    }

  if (DeadBlocks.empty()) return false;

  // Actually remove the blocks now.
  for (unsigned i = 0, e = DeadBlocks.size(); i != e; ++i)
    F.getBasicBlockList().erase(DeadBlocks[i]);

  return true;
}

Add a trivially simple pass to delete unreachable blocks from the CFG. This pass is required to paper over problems in the code generator (primarily live variables and its clients) which doesn't really have any well defined semantics for unreachable code.


/*-----------------------------------------------------------------------------------------------
The MIT License (MIT)

Copyright (c) 2015-2018 OSRE ( Open Source Render Engine ) by Kim Kulling

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

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

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-----------------------------------------------------------------------------------------------*/
#include <gtest/gtest.h>
#include <osre/Assets/AssimpWrapper.h>

namespace OSRE {
namespace UnitTest {

using namespace ::OSRE::Assets;

class AssimpWrapperTest : public ::testing::Test {
    // empty
};

TEST_F( AssimpWrapperTest, createTest ) {
    bool ok( true );
    try {
        AssimpWrapper assimpWrapper;
    } catch (...) {
        ok = false;
    }
    EXPECT_TRUE( ok );
}

}
}

Add missing file to fix the build.


// Chapter 20, Exercise 05: Define an input and an output operator (>> and <<)
// for vector.

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

template<class T>
ostream& operator<<(ostream& os, const vector<T>& v)
{
    os << "{ ";
    for (int i = 0; i<v.size(); ++i) {
        os << v[i];
        if (i+1<v.size()) os << ',';
        os << ' ';
    }
    os << '}';
    return os;
}

template<class T>
istream& operator>>(istream& is, vector<T>& v)
{
    char ch;
    is >> ch;
    if (ch!='{') error("vector must start with '{'");
    T element;
    while (true) {
        is >> ch;
        if (is && ch=='}') return is;
        else is.unget();
        is >> element;
        if (is) v.push_back(element);
        else error("invalid element");
    }
    return is;
}

int main()
try {
    vector<double> vd;
    vector<int> vi;
    vector<string> vs;
    cout << "Enter vector of doubles: ";
    cin >> vd;
    cout << "Enter vector of integers: ";
    cin >> vi;
    cout << "Enter vector of strings: ";
    cin >> vs;

    cout << vd << "\n" << vi << "\n" << vs << "\n";
}
catch (Range_error& re) {
    cerr << "bad index: " << re.index << "\n";
}
catch (exception& e) {
    cerr << "exception: " << e.what() << endl;
}
catch (...) {
    cerr << "exception\n";
}

Add Chapter 20, exercise 5


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

#include "net/third_party/quiche/src/quic/core/crypto/common_cert_set.h"

#include <cstddef>

#include "net/third_party/quiche/src/quic/core/quic_utils.h"
#include "net/third_party/quiche/src/common/platform/api/quiche_arraysize.h"
#include "net/third_party/quiche/src/common/platform/api/quiche_string_piece.h"

namespace quic {

namespace {

class CommonCertSetsEmpty : public CommonCertSets {
 public:
  // CommonCertSets interface.
  quiche::QuicheStringPiece GetCommonHashes() const override {
    return quiche::QuicheStringPiece();
  }

  quiche::QuicheStringPiece GetCert(uint64_t /* hash */,
                                    uint32_t /* index */) const override {
    return quiche::QuicheStringPiece();
  }

  bool MatchCert(quiche::QuicheStringPiece /* cert */,
                 quiche::QuicheStringPiece /* common_set_hashes */,
                 uint64_t* /* out_hash */,
                 uint32_t* /* out_index */) const override {
    return false;
  }

  CommonCertSetsEmpty() {}
  CommonCertSetsEmpty(const CommonCertSetsEmpty&) = delete;
  CommonCertSetsEmpty& operator=(const CommonCertSetsEmpty&) = delete;
  ~CommonCertSetsEmpty() override {}
};

}  // anonymous namespace

CommonCertSets::~CommonCertSets() {}

// static
const CommonCertSets* CommonCertSets::GetInstanceQUIC() {
  static CommonCertSetsEmpty* certs = new CommonCertSetsEmpty();
  return certs;
}

}  // namespace quic

Add flag to remove common certs


// Test that LargeAllocator unpoisons memory before releasing it to the OS.
// RUN: %clangxx_asan %s -o %t
// RUN: ASAN_OPTIONS=quarantine_size=1 %t

#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>

int main() {
  void *p = malloc(1024 * 1024);
  free(p);

  char *q = (char *)mmap(p, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
  assert(q);
  assert(q <= p);
  assert(q + 4096 > p);

  memset(q, 42, 4096);

  munmap(q, 4096);
  return 0;
}


//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <functional>

// reference_wrapper

// Test that reference wrapper meets the requirements of TriviallyCopyable,
// CopyConstructible and CopyAssignable.

#include <functional>
#include <type_traits>

int main()
{
    typedef std::reference_wrapper<int> T;
    static_assert(std::is_copy_constructible<T>::value, "");
    static_assert(std::is_copy_assignable<T>::value, "");
    // Extension up for standardization: See N4151.
    static_assert(std::is_trivially_copyable<T>::value, "");
}

Add test for type properties of std::reference_wrapper


#include<iostream>
#include<cstdlib>

using namespace std;

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

		Node(){}

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

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

                        if(head==NULL)
                                return np;

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

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

                        return head;
                }

		Node *deleteNode(Node *head, int pos){
			Node *t=head;

			if(pos==1){
				while(t->next!=head)
					t=t->next;
				t->next=head->next;
				Node *tm=head;
				head=head->next;
				free(tm);

				return head;
			}

			int c=1;

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

			Node *tm=t->next;
			t->next=t->next->next;
			free(tm);

			return head;
		}

		void displayList(Node *head){
                        Node *t=head;
                        cout<<"\nElements of the list are:\n";
                        while(t->next!=head){
                                cout<<t->data<<"\n";
                                t=t->next;
                        }
                        cout<<t->data<<"\n";
                }
};

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

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

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

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

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

        np.displayList(head);
}

Add code to delete node in circular linked list


/*
	This programtests class reverse_str
*/

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

void test_single(char* s){

	// avoid printing nullpointer
	if(s!=nullptr)
		std::cout<<"\nString: "<<s;
	else
		std::cout<<"\nnull";

	std::cout<<"\nLength: "<<Reverse_str::get_length(s);

	Reverse_str::reverse(s);

	// avoid printing nullpointer
	if(s!=nullptr)
		std::cout<<"\nReversed: "<<s;
	else
		std::cout<<"\nnull";

	std::cout<<"\n";
}

void test_all(){

	// null pointer
	char* s1 = nullptr;
	test_single(s1);

	// length 0
	char s2[] = "";
	test_single(s2);

	// length 1
	char s3[] = "r";
	test_single(s3);

	// length 2
	char s4[] = "rk";
	test_single(s4);

	//length 3
	char s5[] = "xyz";
	test_single(s5);

	// length 10
	char s6[] = "what's up!";
	test_single(s6);

	// length 17
	char s7[] = "let's do some c++";
	test_single(s7);

	std::cout<<"\n\n";
}

int main(){

	// test all
	test_all();

	return 0;
}

Add test case for method to reverse null terminated string


// Chapter 20, Exercise 07: find the lexicographical last string in an unsorted
// vector<string>. Beware that "lexicographical" is not the same as "alphabeti-
// cal", as "Zzzz"<"aaa" (uppercase letters are lexicographically before lower-
// case letters).

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

// returns an iterator to the biggest element of the argument
template<class Iterator>
Iterator biggest_element(Iterator first, Iterator last)
{
    Iterator high = first;
    while (first != last) {
        if (*first>*high) high = first;
        ++first;
    }
    return high;
}

int main()
try {
    vector<string> vs;
    string s;
    cout << "Enter a few words, Ctrl-Z to end: ";
    while (cin>>s)
        vs.push_back(s);

    vector<string>::iterator last = biggest_element(vs.begin(),vs.end());
    if (last!=vs.end())
        cout << "The lexicographically last string in the vector is \""
            << *last << "\".\n";
    else
        cout << "Something went wrong.\n";
}
catch (Range_error& re) {
    cerr << "bad index: " << re.index << "\n";
}
catch (exception& e) {
    cerr << "exception: " << e.what() << endl;
}
catch (...) {
    cerr << "exception\n";
}

Add Chapter 20, exercise 7


/*
 * Website:
 *      https://github.com/wo3kie/dojo
 *
 *  Author:
 *      Lukasz Czerwinski
 *
 * Compilation:
 *      g++ --std=c++11 base64.encode.cpp -o base64.encode
 *
 *  Usage:
 *      $ ./base64.encode "Hello World"
 *      SGVsbG8gV29ybGQ
 */

#include <iostream>
#include <string>

#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/transform_width.hpp>

std::string base64encode( std::string const & text )
{
    using namespace boost::archive::iterators;

    typedef base64_from_binary< transform_width< const char *, 6, 8 > >  base64_text;

    std::string encoded;

    std::copy(
        base64_text( & * text.begin() ),
        base64_text( & * text.end() ),
        std::back_inserter( encoded )
    );

    return encoded;
}

int main( int argc, char * argv[] )
{
    if( argc != 2 )
    {
        std::cerr << "Usage: " << argv[0] << " text" << std::endl;
        return 1;
    }

    std::cout << base64encode( argv[1] ) << std::endl;

    return 0;
}

Implement a program to do base64 encoding


// RUN: rm -rf %t
// RUN: mkdir %t
// RUN: echo '[{"directory":".","command":"clang++ -c %t/test.cpp","file":"%t/test.cpp"}]' > %t/compile_commands.json
// RUN: cp "%s" "%t/test.cpp"
// RUN: remove-cstr-calls "%t" "%t/test.cpp"
// RUN: cat "%t/test.cpp" | FileCheck %s
// FIXME: implement a mode for refactoring tools that takes input from stdin
// and writes output to stdout for easier testing of tools.

namespace std {
template<typename T> class allocator {};
template<typename T> class char_traits {};
template<typename C, typename T, typename A> struct basic_string {
  basic_string();
  basic_string(const C *p, const A& a = A());
  const C *c_str() const;
};
typedef basic_string<char, std::char_traits<char>, std::allocator<char> > string;
}
namespace llvm { struct StringRef { StringRef(const char *p); }; }

void f1(const std::string &s) {
  f1(s.c_str());
  // CHECK: void f1
  // CHECK-NEXT: f1(s)
}
void f2(const llvm::StringRef r) {
  std::string s;
  f2(s.c_str());
  // CHECK: std::string s;
  // CHECK-NEXT: f2(s)
}
void f3(const llvm::StringRef &r) {
  std::string s;
  f3(s.c_str());
  // CHECK: std::string s;
  // CHECK: f3(s)
}

Copy the existing regression test for remove-cstr-calls from the tooling branch to preserve its history. It's not yet functional.


// Chapter 20, Exercise 13: modify exercise 12 to use 0 to represent the one
// past the last element (end()) instead of allocating a real Link

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

template<class Elem> struct Link {
    Link(const Elem& v = Elem(), Link* p = 0, Link* s = 0)
        :prev(p), succ(s), val(v) { }
    Link* prev;
    Link* succ;
    Elem val;
};

template<class Elem> class my_list {
public:
    my_list() :first(0) { }

    class iterator;

    iterator begin() { return iterator(first); }
    iterator end() { return iterator(0); }

    iterator insert(iterator p, const Elem& v); // insert v into list before p
    iterator erase(iterator p);          // remove p from the list

    void push_back(const Elem& v);
    void push_front(const Elem& v);
    void pop_front();
    void pop_back();

    Elem& front() { return *first; }
    Elem& back();

    Link<Elem>* first;
};

template<class Elem> class my_list<Elem>::iterator {
    Link<Elem>* curr;
public:
    iterator(Link<Elem>* p) :curr(p) { }

//    Link<Elem>* get_link() { return curr; }

    iterator& operator++() { curr = curr->succ; return *this; } // forward
    iterator& operator--() { curr = curr->prev; return *this; } // backward
    Elem& operator*() { return curr->val; }    // get value (dereference)

    bool operator==(const iterator& b) const { return curr==b.curr; }
    bool operator!=(const iterator& b) const { return curr!=b.curr; }
};

template<class Elem>
void my_list<Elem>::push_front(const Elem& v)
{
    first = new Link<Elem>(v,0,first);
}

template<class Iterator>
Iterator high(Iterator first, Iterator last)
{
    Iterator high = first;
    for (Iterator p = first; p!=last; ++p)
        if (*high<*p) high = p;
    return high;
}

int main()
try {
    my_list<int> lst;
    int x;
    while (cin >> x) lst.push_front(x);
    my_list<int>::iterator p = high(lst.begin(),lst.end());
    cout << "The highest value was " << *p << "\n";
}
catch (Range_error& re) {
    cerr << "bad index: " << re.index << "\n";
}
catch (exception& e) {
    cerr << "exception: " << e.what() << endl;
}
catch (...) {
    cerr << "exception\n";
}

Add Chapter 20, exercise 13


#include <iostream>
#include <vector>
#include <stdexcept>

using namespace std;
/*Ex8.2:
Write a function print() that prints a vector of ints to cout. Give it
two arguments: a string for “labeling” the output and a vector.
*/

void print(string label, vector<int> v){
    cout << label << ": " << endl;
    for (int i = 0; i < v.size(); ++i)
        cout << v[i] << " " ;
}

/*Ex8.3:
Create a vector of Fibonacci numbers and print them using the function
from exercise 2. To create the vector, write a function, fibonacci(x,y,v,n),
where integers x and y are ints, v is an empty vector<int>, and n is the number
of elements to put into v; v[0] will be x and v[1] will be y. A Fibonacci number
is one that is part of a sequence where each element is the sum of the two
previous ones. For example, starting with 1 and 2, we get 1, 2, 3, 5, 8, 13, 21,
. . . . Your fibonacci() function should make such a sequence starting with its
x and y arguments.
*/

void fibonacci(int x, int y, vector<int>& v, int n){
    if(n <= 0) {
        cout << "n can't <= 0" << endl;
        return;
    }

    if(n == 1)
        v = {x};
    else if(n == 2)
       v = {x,y};
    else{
        v.clear();
        v.push_back(x);
        v.push_back(y);
        for(int i = 2; i < n; ++i)
            v.push_back(v[i-1] + v[i-2]);
    }
    return;
}

int main(int argc, char const *argv[])
{
    char exit = 'n';
    int n;
    int firstElem;
    int secondElem;
    vector<int> vFibonacci;
    try{
        while(exit != 'y' || exit != 'Y'){
            cout << "Element of Fibonacci: n = ";
            cin >> n;

            cout << "\nfirstElem: ";
            cin >> firstElem;

            cout << "\nsecondElem: ";
            cin >> secondElem;

            fibonacci(firstElem,secondElem,vFibonacci,n);

            print("Result: ",vFibonacci);

            cout << "\nDo you what to exit? (y/n): ";
            cin >> exit;
        }
        return 0;
    }catch(runtime_error &e){
        cout << e.what() << endl;
    }catch(...){
        cout << "Exiting..." << endl;
    }

}

Add chap8, ex2 + ex3


/* **********************************************************
 * Copyright (c) 2011 Google, Inc.  All rights reserved.
 * **********************************************************/

/* Dr. Memory: the memory debugger
 *
 * 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;
 * version 2.1 of the License, and no 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
 * Library 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 Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "gtest/gtest.h"

TEST(StringTests, Memmove) {
    const char input[128] = "0123456789abcdefg";  // strlen(input) = 17.
    char tmp[128];

    // Trivial: aligned copy, no overlapping.
    EXPECT_EQ(tmp, memmove(tmp, input, strlen(input) + 1));
    ASSERT_STREQ(input, tmp);

    strcpy(tmp, input);
    // Overlapping copy forwards, should skip 1 byte before going to fastpath.
    EXPECT_EQ(tmp+7, memmove(tmp+7, tmp+3, strlen(tmp) + 1 - 3));
    EXPECT_STREQ("01234563456789abcdefg", tmp);

    strcpy(tmp, input);
    // Overlapping copy forwards, different alignment.
    EXPECT_EQ(tmp+6, memmove(tmp+6, tmp+3, strlen(tmp) + 1 - 3));
    EXPECT_STREQ("0123453456789abcdefg", tmp);

    strcpy(tmp, input);
    // Overlapping copy backwards, should skip 3 bytes before going to fastpath.
    EXPECT_EQ(tmp+3, memmove(tmp+3, tmp+7, strlen(tmp) + 1 - 7));
    EXPECT_STREQ("012789abcdefg", tmp);

    strcpy(tmp, input);
    // Overlapping copy backwards, different alignment.
    EXPECT_EQ(tmp+3, memmove(tmp+3, tmp+6, strlen(tmp) + 1 - 6));
    EXPECT_STREQ("0126789abcdefg", tmp);
}

Add memmove tests to app_suite


/*
	This program tests merge sort
*/

#include<iostream>
#include<vector>
#include "mergesort.h"	// My implementation of merge sort

// Displays vector

void printVector(std::vector<int> A){
	for(auto x: A){
		std::cout<<x<<" ";

	}
	std::cout<<std::endl;
}

// Tests merge sort on vector A

void testMergeSort(std::vector<int> A){

	std::cout<<"Before: ";
	printVector(A);
	Mergesort::mergesort(A);
	std::cout<<"After: ";
	printVector(A);
}

// tests merge sort on several different inputs

void testMergeSort(){

	std::vector<int> v1 = {10,9,8,7,6,5,4,3,2,1};
	testMergeSort(v1);

	std::vector<int> v2 = {5,4,3,2,1};
	testMergeSort(v2);

	std::vector<int> v3 = {1,2,3,4,5,6,7,8,9,10};
	testMergeSort(v3);

	std::vector<int> v4 = {6,5,4,7,8,9,9,5,4,9,2,0,3,1,5,9,8,7,4,5,6,3};
	testMergeSort(v4);

	// test on empty vector
	std::vector<int> v5;
	testMergeSort(v5);

	std::vector<int> v6 = {2,4,-6,1,-9,3,0};
	testMergeSort(v6);

	std::vector<int> v7 = {1,2,3,4,5,6,7,8,9,0};
	testMergeSort(v7);
}

int main(){

	// test merge sort
	testMergeSort();

	return 0;
}

Add test program for mergesort


class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if(nums.size()<3) return nums.size();
        int f=0,r=1;
        while(r<nums.size()){
            if(nums[f]==nums[r]){
                if(r-f>1) nums.erase(nums.begin()+r,nums.begin()+r+1);
                else r++;
            }else{
                f=r;
                r++;
            }
        }
        return nums.size();
    }
};

Remove Duplicates from Sorted Array II


#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    // Declare a variable named 'input_string' to hold our input.
    string input_string;

    // Read a full line of input from stdin (cin) and save it to our variable, input_string.
    getline(cin, input_string);

    // Print a string literal saying "Hello, World." to stdout using cout.
    cout << "Hello, World." << endl;
    cout << input_string << endl;

    // TODO: Write a line of code here that prints the contents of input_string to stdout.

    return 0;
}

Add c++ solution to the hello World problem


#include <boost/test/unit_test.hpp>
#include <ygo/deck/c/Format.h>
#include <ygo/deck/c/DB.h>

struct Format_Fixture
{
    Format_Fixture()
    {
        DB_NAME(set_path)("test/card.db");
    }
};

BOOST_FIXTURE_TEST_SUITE(Format, Format_Fixture)

BOOST_AUTO_TEST_CASE(Create)
{
    int count;
    auto formatDates = FORMAT_NAME(formatDates)(&count);
    for (auto i = 0; i < count; i++) {
        auto formatA = FORMAT_NAME(new)(ygo_data_Format_ADVANCED,
                formatDates[i]);
        auto formatDateA = FORMAT_NAME(formatDate)(formatA);
        auto formatFA = FORMAT_NAME(format)(formatA);
        BOOST_CHECK_EQUAL(std::string(formatDateA), formatDates[i]);
        BOOST_CHECK(formatFA == ygo_data_Format_ADVANCED);
        FORMAT_NAME(delete_formatDate)(formatDateA);

        auto formatT = FORMAT_NAME(new)(ygo_data_Format_TRADITIONAL,
                formatDates[i]);
        auto formatDateT = FORMAT_NAME(formatDate)(formatT);
        auto formatTA = FORMAT_NAME(format)(formatT);
        BOOST_CHECK_EQUAL(std::string(formatDateT), formatDates[i]);
        BOOST_CHECK(formatTA == ygo_data_Format_TRADITIONAL);
        FORMAT_NAME(delete_formatDate)(formatDateT);
    }
    FORMAT_NAME(delete_formatDates)(formatDates, count);
}

BOOST_AUTO_TEST_CASE(Invalid)
{
    auto format = FORMAT_NAME(new)(ygo_data_Format_ADVANCED, "InvalidFormat");
    BOOST_CHECK(format == nullptr);
}

BOOST_AUTO_TEST_CASE(Limits)
{
    auto formatA = FORMAT_NAME(new)(ygo_data_Format_ADVANCED, "April 2004");
    auto formatT = FORMAT_NAME(new)(ygo_data_Format_TRADITIONAL, "April 2004");

    BOOST_CHECK_EQUAL(0, FORMAT_NAME(cardCount)(formatA, "Change of Heart"));
    BOOST_CHECK_EQUAL(1, FORMAT_NAME(cardCount)(formatT, "Change of Heart"));

    BOOST_CHECK_EQUAL(1, FORMAT_NAME(cardCount)(formatA, "Mage Power"));
    BOOST_CHECK_EQUAL(1, FORMAT_NAME(cardCount)(formatT, "Mage Power"));

    BOOST_CHECK_EQUAL(2, FORMAT_NAME(cardCount)(formatA, "Creature Swap"));
    BOOST_CHECK_EQUAL(2, FORMAT_NAME(cardCount)(formatT, "Creature Swap"));

    BOOST_CHECK_EQUAL(3, FORMAT_NAME(cardCount)(formatA, "Kuriboh"));
    BOOST_CHECK_EQUAL(3, FORMAT_NAME(cardCount)(formatT, "Kuriboh"));

    FORMAT_NAME(delete)(formatA);
    FORMAT_NAME(delete)(formatT);

}

BOOST_AUTO_TEST_SUITE_END()

Add unit tests for format c bindings


name: SCIP Disabled

on: [push, pull_request]

jobs:
  # Building using the github runner environement directly.
  cmake:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
    - name: Check cmake
      run: cmake --version
    - name: Configure
      run: cmake -S. -Bbuild -DCMAKE_BUILD_TYPE=Release -DBUILD_DEPS=ON -DUSE_SCIP=OFF
    - name: Build
      run: cmake --build build --config Release --target all -v
    - name: Test
      run: CTEST_OUTPUT_ON_FAILURE=1 cmake --build build --config Release --target test -v
    - name: Install
      run: cmake --build build --config Release --target install -v -- DESTDIR=install

Add job with SCIP support disabled


#include <stdio.h>

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

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

int sum(NODE* root) {
  if (root == nullptr) return 0;

  return (sum(root->left) + root->data + sum(root->right));
}

bool isSumTree(NODE* root) {
  if (root == nullptr || (root->left == nullptr && root->right == nullptr))
    return true;
  int left_sum = sum(root->left);
  int right_sum = sum(root->right);

  if ((root->data == left_sum + right_sum) &&
      (isSumTree(root->left) && isSumTree(root->right)))
    return true;

  return false;
}

int main(int argc, char const* argv[]) {
  NODE* root = newNode(26);
  root->left = newNode(10);
  root->right = newNode(3);
  root->left->left = newNode(4);
  root->left->right = newNode(6);
  root->right->right = newNode(3);
  if (isSumTree(root))
    printf("The given tree is a SumTree ");
  else
    printf("The given tree is not a SumTree ");
  return 0;
}

Check whether given tree is sum tree.


// Chapter 23, exercise 14: like the sample program from 23.8.7, but read input
// from file into memory and experiment with patterns including '\n'

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

using namespace std;

int main()
{
    string ifname = "pics_and_txt/chapter23_ex12_in.txt";
    ifstream ifs(ifname);
    if (!ifs) throw runtime_error("Can't open " + ifname);
    string line;
    string text;
    while (getline(ifs,line))
        text += line + "\n";

    regex pattern;

    string pat;
    string prompt = "Enter pattern (qqq to exit): ";
    cout << prompt;
    while (getline(cin,pat)) {   // read pattern
        if (pat=="qqq") break;
        try {
            pattern = pat;  // this checks pat
        }
        catch (regex_error) {
            cout << pat << " is not a valid regular expression\n";
            exit(1);
        }

        smatch matches;
        if (regex_search(text,matches,pattern))
            cout << "Match found: " << matches[0] << '\n';
        else
            cout << "No match found\n";
        cout << prompt;
    }
}

Add Chapter 23, exercise 14


#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef vector < ll > vl;
int main(){
    vl data = {234234LL, 2322LL,1LL, -1LL, 3454LL};

    sort(data.begin(), data.end());

    for (int i=0; i< data.size(); i++)
        printf("%lld ", data[i]);
    return 0;
}

Add faster algorithm for working with sorting.


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

#include "../JPetAnalysisTools/JPetAnalysisTools.h"

BOOST_AUTO_TEST_SUITE(FirstSuite)

BOOST_AUTO_TEST_CASE(constructor_getHitsOrderedByTime)
{
  std::vector<JPetHit> hits(4);
  hits[0].setTime(2);
  hits[1].setTime(1);
  hits[2].setTime(4);
  hits[3].setTime(3);
  auto results = JPetAnalysisTools::getHitsOrderedByTime(hits);
  BOOST_REQUIRE_EQUAL(results[0].getTime(), 1);
  BOOST_REQUIRE_EQUAL(results[1].getTime(), 2);
  BOOST_REQUIRE_EQUAL(results[2].getTime(), 3);
  BOOST_REQUIRE_EQUAL(results[3].getTime(), 4);
}

BOOST_AUTO_TEST_SUITE_END()

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

#include "../JPetAnalysisTools/JPetAnalysisTools.h"

BOOST_AUTO_TEST_SUITE(FirstSuite)

BOOST_AUTO_TEST_CASE(constructor_getHitsOrderedByTime)
{
  std::vector<JPetHit> hits(4);
  hits[0].setTime(2);
  hits[1].setTime(1);
  hits[2].setTime(4);
  hits[3].setTime(3);
  auto results = JPetAnalysisTools::getHitsOrderedByTime(hits);
  double epsilon = 0.0001;
  BOOST_REQUIRE_CLOSE(results[0].getTime(), 1, epsilon );
  BOOST_REQUIRE_CLOSE(results[1].getTime(), 2, epsilon );
  BOOST_REQUIRE_CLOSE(results[2].getTime(), 3, epsilon );
  BOOST_REQUIRE_CLOSE(results[3].getTime(), 4, epsilon );
}

BOOST_AUTO_TEST_SUITE_END()

Change tests in JPetAnalysisTools to use double instead of int


// 10.exercise.06.cpp
//
//  Define a Roman_int class for holding Roman numerals (as ints) with a << and
//  >>. Provide Roman_int with an as_int() member that returns the int value,
//  so that if r is a Roman_int, we can write cout << "Roman" << r << "equals"
//  << r.as_int() << '\n';.

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

Prepare exercise 6 from chapter 10.


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

/* http://codeforces.com/contest/527/submission/11525645 */

#include <iostream>

int main() {
    long long int a, b;
    std::cin >> a >> b;
    long long int ans = 0;
    while (b > 0) {
        ans += a / b;
        a = a % b;
        long long int temp = a;
        a = b;
        b = temp;
    }
    std::cout << ans << std::endl;
    return 0;
}

Add the first codeforces problem


/**
 * Rod Cutting
 * Given a length of rod, sample lengths and its
 * corresponding profits find the maximum profit
 * that can be made given the length.
 * @Author: wajahat siddiqui
 */
#include <iostream>
using namespace std;

inline unsigned int max(unsigned int a, unsigned int b) {
	return (a > b) ? a : b;
}
void printArray(unsigned int **A, int M, int N) {
	for (unsigned int i = 0; i <= M; i++) {
		for (unsigned int j = 0; j <= N; j++){
			cout<<A[i][j]<<" ";
		}
		cout<<endl;
	}
	cout<<endl;
}

/**
 * @param N is the length of the rod for which max profit to be found
 * @param M is the number of rods
 */
unsigned int findMaxProfit(int profit[], int M, int N) {
	unsigned int solution;
	unsigned int **T = new unsigned int *[M+1];
	for (int i = 0; i <= M; i++)
		T[i] = new unsigned int [N+1];
	for (int i = 0; i <= M; i++)
		T[i][0] = 0;
	for (int i = 1; i <= M; i++) {
		for (int j = 1; j <= N; j++) {
			if (j >= i) {
				T[i][j] = max((T[i][j-i] + profit[i-1]), T[i-1][j]);
			} else {
				T[i][j] = T[i-1][j];
			}
		}
	}

	printArray(T, M, N);
	solution = T[M][N];

	for (int i = 0; i <= M; i++)
		delete [] T[i];
	delete [] T;
	return solution;
}

int main() {
	int N = 5; // Rod Length
	int profit[] = {2, 5, 7, 8};
	int M = sizeof(profit)/sizeof(profit[0]); // No. of rods
	cout<<"Maximum profit that can be made from Rod Length: "<<N<<" is: "
	    <<findMaxProfit(profit, M, N);
	return 0;
}

Implement rod cutting to maximize profit using DP


/*
* @author Abhishek Datta
* @github_id abdatta
* @since 15th October, 2017
*
* The following algroithm takes complex coeeficients
* and calculates its inverse discrete fourier transform
*/

#include <complex>
#include <iostream>
#include <iomanip>
#include <valarray>

const double PI = std::acos(-1);

typedef std::complex<double> Complex;
typedef std::valarray<Complex> CArray;

// recursive fft (in-place)
void fft(CArray& x)
{
    const size_t N = x.size();
    if (N <= 1) return;

    // divide
    CArray even = x[std::slice(0, N/2, 2)];
    CArray  odd = x[std::slice(1, N/2, 2)];

    // conquer
    fft(even);
    fft(odd);

    // combine
    for (size_t k = 0; k < N/2; ++k)
    {
        Complex t = std::polar(1.0, 2 * PI * k / N) * odd[k];
        x[k    ] = even[k] + t;
        x[k+N/2] = even[k] - t;
    }
}

// inverse fft (in-place)
void ifft(CArray& x)
{
    // conjugate the complex numbers
    x = x.apply(std::conj);

    // forward fft
    fft( x );

    // conjugate the complex numbers again
    x = x.apply(std::conj);

    // scale the numbers
    x /= x.size();
}

int main()
{
	int t; // no. of test cases to try on
	std::cin>>t;
	while(t--)
	{
		int n; // n is for order of the polynomial
		std::cin>>n;
	    Complex test[n];
	    for (int i = 0; i < n; ++i)
	    {
	    	double real, imag;
	    	std::cin>>real>>imag; // reading each coefficient as a complex number
	    	test[i].real(real); // setting real part to real
	    	test[i].imag(imag); // and imaginary part to imaginary
	    }

	    CArray data(test, n);

	    ifft(data);

	    for (int i = 0; i < n; ++i)
	    {
	        std::cout << std::fixed << std::setprecision(6) << data[i].real() << " " << data[i].imag() << std::endl;
	    }
	}
}

Add algorithm for Inverse FFT


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

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

#if defined(TOOLKIT_VIEWS)
// Need to port ExtensionInfoBarDelegate::CreateInfoBar() to other platforms.
// See http://crbug.com/39916 for details.
#define MAYBE_Infobars Infobars
#else
#define MAYBE_Infobars DISABLED_Infobars
#endif

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) {
  // TODO(finnur): Remove once infobars are no longer experimental (bug 39511).
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("infobars")) << message_;
}

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

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

#if defined(TOOLKIT_VIEWS)
#if defined (OS_WIN)
#define MAYBE_Infobars Infobars
#else
// Flaky on ChromeOS, see http://crbug.com/40141.
#define MAYBE_Infobars FLAKY_Infobars
#endif

#else
// Need to port ExtensionInfoBarDelegate::CreateInfoBar() to other platforms.
// See http://crbug.com/39916 for details.
#define MAYBE_Infobars DISABLED_Infobars
#endif

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) {
  // TODO(finnur): Remove once infobars are no longer experimental (bug 39511).
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("infobars")) << message_;
}

Mark a test as flaky on ChromeOS.


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

#include "base/i18n/timezone.h"
#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace base {
namespace {

#if defined(OS_ANDROID)
// icu's timezone utility doesn't work on Android.
#define MAYBE_CountryCodeForCurrentTimezone DISABLED_CountryCodeForCurrentTimezone
#else
#define MAYBE_CountryCodeForCurrentTimezone CountryCodeForCurrentTimezone
#endif

TEST(TimezoneTest, MAYBE_CountryCodeForCurrentTimezone) {
  std::string country_code = CountryCodeForCurrentTimezone();
  EXPECT_EQ(2U, country_code.size());
}

}  // namespace
}  // namespace base

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

#include "base/i18n/timezone.h"

#include "testing/gtest/include/gtest/gtest.h"

namespace base {
namespace {

#if defined(OS_ANDROID)
// icu's timezone utility doesn't work on Android.
#define MAYBE_CountryCodeForCurrentTimezone DISABLED_CountryCodeForCurrentTimezone
#else
#define MAYBE_CountryCodeForCurrentTimezone CountryCodeForCurrentTimezone
#endif

TEST(TimezoneTest, MAYBE_CountryCodeForCurrentTimezone) {
  std::string country_code = CountryCodeForCurrentTimezone();
  EXPECT_EQ(2U, country_code.size());
}

}  // namespace
}  // namespace base

Revert 235842 "fix android build by adding build_config.h"


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

#include <shogun/base/init.h>
#include <shogun/labels/BinaryLabels.h>
#include <shogun/evaluation/ROCEvaluation.h>
#include <gtest/gtest.h>

using namespace shogun;

TEST(ROCEvaluation,one)
{
	int num_labels = 10;
	CBinaryLabels* gt = new CBinaryLabels(num_labels);
	CROCEvaluation* roc = new CROCEvaluation();

	for (int i = 0; i < num_labels; i++) {
		int l = (CMath::random(-1.0, 1.0) < 0 ? -1 : 1);
		gt->set_label(i, l);
	}

	roc->evaluate(gt, gt);

	EXPECT_EQ(roc->get_auROC(), 1);
}

Add unit test for ROCEvaluation as currently this little example fails


/*
 * 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_PolyUtils(Fuzz* f);

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

Add oss-fuzz entrypoint for Polyutils fuzz


// Chapter 20, Exercise 12: complete the definition of list from 20.4.1-2 and
// get the high() example to run. Allocate a Link to represent one past the end.

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

template<class Elem> struct Link {
    Link(const Elem& v = Elem(), Link* p = 0, Link* s = 0)
        :prev(p), succ(s), val(v) { }
    Link* prev;
    Link* succ;
    Elem val;
};

template<class Elem> class my_list {
public:
    my_list() :first(new Link<Elem>()), last(first) { }

    class iterator;

    iterator begin() { return iterator(first); }
    iterator end() { return iterator(last); }

    iterator insert(iterator p, const Elem& v); // insert v into list before p
    iterator erase(iterator p);          // remove p from the list

    void push_back(const Elem& v);
    void push_front(const Elem& v);
    void pop_front();
    void pop_back();

    Elem& front() { return *first; }
    Elem& back();

    Link<Elem>* first;
    Link<Elem>* last;   // one beyond the last link
};

template<class Elem> class my_list<Elem>::iterator {
    Link<Elem>* curr;
public:
    iterator(Link<Elem>* p) :curr(p) { }

//    Link<Elem>* get_link() { return curr; }

    iterator& operator++() { curr = curr->succ; return *this; } // forward
    iterator& operator--() { curr = curr->prev; return *this; } // backward
    Elem& operator*() { return curr->val; }    // get value (dereference)

    bool operator==(const iterator& b) const { return curr==b.curr; }
    bool operator!=(const iterator& b) const { return curr!=b.curr; }
};

template<class Elem>
void my_list<Elem>::push_front(const Elem& v)
{
    first = new Link<Elem>(v,0,first);
}

template<class Iterator>
Iterator high(Iterator first, Iterator last)
{
    Iterator high = first;
    for (Iterator p = first; p!=last; ++p)
        if (*high<*p) high = p;
    return high;
}

int main()
try {
    my_list<int> lst;
    int x;
    while (cin >> x) lst.push_front(x);
    my_list<int>::iterator p = high(lst.begin(),lst.end());
    cout << "The highest value was " << *p << "\n";
}
catch (Range_error& re) {
    cerr << "bad index: " << re.index << "\n";
}
catch (exception& e) {
    cerr << "exception: " << e.what() << endl;
}
catch (...) {
    cerr << "exception\n";
}

Add Chapter 20, exercise 12


// RUN: not %clang_cc1 -fmodules -fmodule-map-file=does-not-exist.modulemap -verify %s 2>&1 | FileCheck %s

// CHECK: module map file 'does-not-exist.modulemap' not found

Add test file missed from r223561.


#include <iostream>
#include <cmath>

using namespace std;

class Point2D {
  double x;
  double y;

public:

  double getX() {
    return x;
  }

  double getY() {
    return y;
  }

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

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

  void translate(double dx, double dy) {
    setX(getX() + dx);
    setY(getY() + dy);
  }

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

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

void testTranslate() {
  Point2D point;
  point.setX(3);
  point.setY(5);

  point.translate(2, 3);
  point.print();
}

void testDistanceBetween() {
  Point2D firstPoint;
  firstPoint.setX(3);
  firstPoint.setY(5);

  Point2D secondPoint;
  secondPoint.setX(4);
  secondPoint.setY(1);

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

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

  return 0;
}

Add solution to third part of first problem. Replace the structure with class with getters and setters


167. Two Sum II - Input array is sorted
/**
 * Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
 *
 * The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
 *
 * You may assume that each input would have exactly one solution.
 *
 * Input: numbers={2, 7, 11, 15}, target=9
 * Output: index1=1, index2=2
 *
 * Tags: Array, Two Pointers, Binary Search
 *
 * Similar Problems: (E) Two Sum
 *
 * Author: Kuang Qin
 */

#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        vector<int> res;
        int n = numbers.size();
        if (n < 2)
            return res;

        // use two pointers
        int left = 0, right = n - 1;

        while (left < right)
        {
            int sum = numbers[left] + numbers[right];

            if (sum == target)
            {
                res.push_back(left + 1);
                res.push_back(right + 1);
                break;
            }
            else if (sum < target)
                left++;
            else    // sum > target
                right--;
        }

        return res;
    }
};

int main()
{
    vector<int> numbers = {2, 3, 4};
    int target = 6;
    Solution sol;
    vector<int> res = sol.twoSum(numbers, target);
    cout << "index1 = " << res[0] << ", index2 = " << res[1] << endl;
    cin.get();

    return 0;
}

Add Solution for 167. Two Sum II - Input array is sorted


/**
 * To implement minimum stack that returns minimum element in O(1) time
 */
 #include <iostream>
 #include <stack>
 using namespace std;

 class MinStack {
 private:
 	stack<int> min;
 	stack<int> s;
 public:
 	void push(int data) {
 		if (min.empty()) {
 			min.push(data);
 		} else if (data < min.top()) {
 			min.push(data);
 		} else if (data > min.top()) {
 			min.push(min.top());
 		}

 		s.push(data);
 	}

 	void pop() {
 		min.pop();
 		s.pop();
 	}

 	int top() {
 		return s.top();
 	}

 	/**
 	 * T(n) = O(1)
 	 **/
 	int getMin() {
 		return min.top();
 	}
 };

 int main() {
 	MinStack minStack;
 	int keys[] = {3, 1, 2, -1, 0, 4, -6};
 	int size = sizeof(keys)/sizeof(keys[0]);

 	for (int i = 0; i < size; i++) {
 		cout<<"Pushing key: "<<keys[i]<<endl;
 		minStack.push(keys[i]);
 		cout<<"Current Minimum: "<<minStack.getMin()<<endl;
 	}

 	cout<<"Popping 5 values\n";
 	for (int i = 0; i < 5; i++) {
 		cout<<"Popping: "<<minStack.top()<<endl;
 		minStack.pop();
 		cout<<"Current Minimum: "<<minStack.getMin()<<endl;
 	}

 	return 0;
 }

Implement minimum stack that will return the minimum element from the entire stack in O(1) time


#include <iostream>
#include <queue>

using std::cout;
using std::queue;

int dequeue_min(queue<int>& q) {
  unsigned long queue_size = q.size();

  int min = q.front();
  q.pop();

  for (int i = 1; i < queue_size; ++i) {
    int front = q.front();
    q.pop();

    if (front < min) {
      q.push(min);
      min = front;
    } else {
      q.push(front);
    }
  }

  return min;
}

void print_queue(queue<int> q) {
  while (!q.empty()) {
    cout << q.front() << ' ';
    q.pop();
  }
}

int main() {
  queue<int> q;
  q.push(4);
  q.push(2);
  q.push(6);
  q.push(-1);
  q.push(3);

  cout << dequeue_min(q) << '\n';
  print_queue(q);
  cout << '\n';

  return 0;
}

Add dequeue min task solution


/*
 * Copyright 2010, NagaChaitanya Vellanki
 *
 * Author NagaChaitanya Vellanki
 *
 * Print length of the period of decimal representation of 1/n for n > 1
 */

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

using namespace std;

int main() {
  int32_t n = 0;

  cout << "Enter n(n > 1)" << endl;
  cin >> n;

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

  int32_t rem = 1;
  int32_t i = 0;

  // period of a fraction cannot be less than the period of sequence of
  // remainders
  while(i < n) {
    rem = (10 * rem) % n;
    i++;
  }

  // c is the (n + 1)th term in the sequence remainders
  int32_t c = rem;

  rem = (10 * rem) % n; // (n + 2)th term in the sequence of remainders
  i =  1;

  while(rem != c) {
    rem = (rem * 10) % n;
    i++;
  }

  cout << "The period length of " << 1 << "/" << n << " is " << i << endl;
  return 0;
}

Add period length of 1/n


#include <iostream>
#include <vector>
#include <string>

using namespace std;

struct Base1 {
    void print(int i) const {
        cout << "Base1::print(int)" << endl;
    }

protected:
    int ival;
    double dval;
    char cval;
private:
    int *id;
};

struct Base2 {
    void print(double d) const {
        cout << "Base2::print(double)" << endl;
    }
protected:
    double fval;
private:
    double dval;
};

struct Derived : public Base1 {
    void print(string s) const {
        cout << "Derived::print(string)" << endl;
    }
protected:
    string sval;
    double dval;
};

struct MI : public Derived, public Base2 {
    void print(vector<double> dvec) {
        cout << "MI::print(vector<double>)" << endl;
    }

    //for test 18.26
    void print(int i) const {
        cout << "MI::print(int)" << endl;
        Base1::print(i);
    }
    void foo(double);

protected:
    int *ival;
    vector<double> dvec;
};

int ival;
double dval;

//for test 18.27
void MI::foo(double cval) {
    int dval;
    dval = Base1::dval + Derived::dval;
    Base2::fval = dvec[dvec.size() - 1];
    sval[0] = Base1::cval;
}

int main() {
    MI mi;
    mi.print(42);

    return 0;
}

Add solution for chapter 18, test 26, 27


// Write class type objects to a stream

#include <iostream>

class foo
{
	public:
		foo(int x)
			: x(x)
		{ }

		friend std::ostream& operator<<(std::ostream& stream,
		                                foo const& f);

	private:
		int x;
};

std::ostream& operator<<(std::ostream& stream,
                         foo const& f)
{
	return stream << "A foo with x = " << f.x;
}

int main()
{
	foo f(10);
	std::cout << f << std::endl;
}

// Write your class type objects to an output stream by implementing
// `operator<<`.
//
// We implement `operator<<` on [19-23], which takes a reference to an
// [`std::ostream`](cpp/io/basic_ostream) (the base class for all
// output streams) and the `foo` object we wish to write to the stream.
// On [22], we simply write a string representing the `foo` object to
// the steam and return a reference to the stream itself, allowing
// this call to be chained.
//
// Note that we declare this `operator<<` as a `friend` of `foo` on
// [12-13]. This gives it access to `foo`'s private member, `x`.
//
// On [27-28], we stream a `foo` object to [`std::cout`](cpp/io/cout).

Add "write class type objects" sample


#include <iostream>
// yaml-cpp includes
#include "yaml-cpp/yaml.h"

int main()
{
   YAML::Emitter out;
   out << "Hello, World!";

   std::cout << "Here's the output YAML:\n" << out.c_str();

   return 0;
}

#include <iostream>
#include <yaml-cpp/yaml.h>

int main()
{
   YAML::Emitter out;
   out << "Hello, World!";

   std::cout << "Here's the output YAML:\n" << out.c_str();

   return 0;
}

Remove comment. Just a trigger for a new build.


#include <cmath>
#include <memory>
#include <vector>
#include <parfil/robot.h>
#include <parfil/filter.h>

void TestCase1(std::vector<parfil::Motion>& motions, std::vector<parfil::Measurement>& measurements) {
  // fill in motions
  int num_motions = 8;
  motions.resize(num_motions);
  for (int i=0; i<num_motions; ++i) {
    motions[i].steering_angle = 2.0*M_PI/10.0;
    motions[i].forward_distance = 20.0;
  }

  // fill in measurements
  double[] measurements_arr = {
      4.746936, 3.859782, 3.045217, 2.045506,
      3.510067, 2.916300, 2.146394, 1.598332,
      2.972469, 2.407489, 1.588474, 1.611094,
      1.906178, 1.193329, 0.619356, 0.807930,
      1.352825, 0.662233, 0.144927, 0.799090,
      0.856150, 0.214590, 5.651497, 1.062401,
      0.194460, 5.660382, 4.761072, 2.471682,
      5.717342, 4.736780, 3.909599, 2.342536
  };
  int num_measurements = 8;
  int measurement_dimension = 4;
  measurements.resize(8);
  for (int i=0; i<num_measurements; ++i) {
    measurements[i].resize(measurement_dimension);
    double* from = measurements_arr + measurement_dimension*i;
    double* to = from + measurement_dimension;
    measurements[i].assign(from,to);
  }
}

int main(int, char**) {
  int num_particles = 500;
  std::unique_ptr<parfil::Filter> filter(new parfil::Filter(num_particles));

  std::vector<parfil::Motion> motions;
  std::vector<parfil::Measurement> measurements;
  TestCase1(motions,measurements);

  filter->run(motions,measurements);

  double x,y,heading;
  filter->GetPose(x,y,heading);
  std::cout << "x: " << x << " y: " << y << " heading: " << heading << std::endl;

  return 0;
}

Add toy example showing use of the interface


#include "cvd/internal/load_and_save.h"
#include "cvd/internal/io/bmp.h"
#include <vector>
using namespace std;
using namespace CVD;

namespace CVD{
namespace BMP{

void writeBMPHeader(unsigned int width, unsigned int height, unsigned int channels, std::ostream& out);

class WritePimpl
{
	public:
		WritePimpl(ostream& o_, ImageRef sz, const string& t)
		:o(o_),size(sz)
		{
			int ch;

			if(t == "unsigned char")
				ch=1;
			else if(t == "CVD::Rgb<unsigned char>")
			{
				ch=3;
				int l=size.x*3;
				if(l%4 != 0)
					l = (l/4+1)*4;
				buf.resize(l);
			}
			else
				throw Exceptions::Image_IO::UnsupportedImageSubType("BMP", t);

			writeBMPHeader(size.x, size.y, ch, o);

			pad = ((ch*size.x) % 4) ? (4 - ((ch*size.x) % 4)) : 0;
		}

		void write_raw_pixel_line(const byte* r)
		{
			char zeros[]={0,0,0,0};
			o.write((const char*)r, size.x);
			o.write(zeros,pad);
		}

		void write_raw_pixel_line(const Rgb<byte>* r)
		{
			//Transform to BGR
			for(int i=0; i < size.x; i++)
			{
				buf[i*3+0] = r[i].blue;
				buf[i*3+1] = r[i].green;
				buf[i*3+2] = r[i].red;
			}
			o.write(&buf[0], buf.size());
		}

	private:
		ostream& o;
		ImageRef size;
		int pad;
		vector<char> buf;

};

Writer::Writer(std::ostream&o, ImageRef size, const std::string& type, const std::map<std::string, Parameter<> >&)
:t(new WritePimpl(o, size, type))
{}

Writer::~Writer()
{}

void Writer::write_raw_pixel_line(const byte* l)
{
	t->write_raw_pixel_line(l);
}
void Writer::write_raw_pixel_line(const Rgb<byte>* l)
{
	t->write_raw_pixel_line(l);
}

}
}

Add missing file from the previous commit.


// RUN: %clang_cc1 -x c++ -fmodules -fmodules-local-submodule-visibility -fmodules-cache-path=%t %s -verify
// RUN: %clang_cc1 -x c++ -fmodules -fmodules-cache-path=%t %s -verify

// expected-no-diagnostics

#pragma clang module build A
  module A { }
#pragma clang module contents
#pragma clang module begin A
struct A {
   virtual void Foo(double x) const;
};
#pragma clang module end
#pragma clang module endbuild

#pragma clang module build B
  module B { }
#pragma clang module contents
#pragma clang module begin B
#pragma clang module import A
struct B : A {
   using A::Foo;
   virtual void Foo(double x) const;
};
#pragma clang module end
#pragma clang module endbuild

#pragma clang module import B

int main() {
  B b;
  b.Foo(1.0);
}

Add test for using declaration in classes.


#include "mbed.h"
#include "test_env.h"
#include "rtos.h"

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

#define NUM_THREADS         5
#define THREAD_STACK_SIZE   256

DigitalOut led1(LED1);
volatile bool should_exit = false;
volatile bool allocation_failure = false;

void task_using_malloc(void)
{
    void* data;
    while (1) {
        // Repeatedly allocate and free memory
        data = malloc(100);
        if (data != NULL) {
            memset(data, 0, 100);
        } else {
            allocation_failure = true;
        }
        free(data);

        if (should_exit) {
            return;
        }
    }
}

int main()
{
    Thread *thread_list[NUM_THREADS];
    int test_time = 15;
    GREENTEA_SETUP(20, "default_auto");

    // Allocate threads for the test
    for (int i = 0; i < NUM_THREADS; i++) {
        thread_list[i] = new Thread(osPriorityNormal, THREAD_STACK_SIZE);
        if (NULL == thread_list[i]) {
            allocation_failure = true;
        }
        thread_list[i]->start(task_using_malloc);
    }

    // Give the test time to run
    while (test_time) {
        led1 = !led1;
        Thread::wait(1000);
        test_time--;
    }

    // Join and delete all threads
    should_exit = 1;
    for (int i = 0; i < NUM_THREADS; i++) {
        if (NULL == thread_list[i]) {
            continue;
        }
        thread_list[i]->join();
        delete thread_list[i];
    }

    GREENTEA_TESTSUITE_RESULT(!allocation_failure);
}

Add a test for thread-safe malloc


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

using namespace Halide;

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

    //int W = 64*3, H = 64*3;
    const int W = 128, H = 48;

    Image<uint16_t> in(W, H, 2);
    for (int c = 0; c < 2; c++) {
        for (int y = 0; y < H; y++) {
            for (int x = 0; x < W; x++) {
                in(x, y, c) = rand() & 0xff;
            }
        }
    }

    Var x("x"), y("y");

    Func interleaved("interleaved");
    interleaved(x, y) = select(x%2 == 0, in(x, y, 0), in(x, y, 1));

    Target target = get_jit_target_from_environment();
    if (target.has_gpu_feature()) {
        interleaved.gpu_tile(x, y, 16, 16);
    } else if (target.features_any_of({Target::HVX_64, Target::HVX_128})) {
        interleaved.hexagon().vectorize(x, 32);
    } else {
        Var xo("xo"), yo("yo");
        interleaved.tile(x, y, xo, yo, x, y, 8, 8).vectorize(x);
    }

    Image<uint16_t> out = interleaved.realize(W, H, target);
    for (int y = 0; y < H; y++) {
        for (int x = 0; x < W; x++) {
            uint16_t correct = x%2 == 0 ? in(x, y, 0) : in(x, y, 1);
            if (out(x, y) != correct) {
                printf("out(%d, %d) = %d instead of %d\n", x, y, out(x, y), correct);
                return -1;
            }
        }
    }

    printf("Success!\n");

    return 0;

}

Add test failing on hexagon.


Add string generator for war


#include <array>

// C++17 only
// requires template argument deduction for class templates
namespace std
{
    template <typename... T>
    array(T... t) -> array<std::common_type_t<T...>, sizeof...(t)>;
}

int main()
{
    int a[] = {1,2,3};
    int b[] {4,5,6};

    // See: https://stackoverflow.com/q/7107606
    // not allowed as {1, 2, 3, 4} is purely a syntactic construct- it is not an expression and does not have a type,
    // therefore, auto cannot deduce its type from it.
    //auto c[] = {1,2,3};
    //auto d[] {4,5,6};

    // Alternative via std::array (see above), but not quite the same...
    // https://stackoverflow.com/q/6114067
    std::array e{1, 2, 3, 4};
}

Add explanation about auto and arrays.


#include <stddef.h>
// 199 Binary Tree Right Side View
/**
* Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
*
* For example:
* Given the following binary tree,
*    1            <---
*  /   \
* 2     3         <---
*  \     \
*   5     4       <---
* You should return [1, 3, 4].
*
* Tag:     Tree, Depth First Search, Breadth First Search
*
* Author:  Yanbin Lu
*/

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

using namespace std;

 struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 };

class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        vector<int> res;
        if(!root) return res;

		// using level order traverse
		// use a queue to store all nodes in the current level
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()){
            int n = q.size();
            for(int i = 0; i < n;i++){
                TreeNode* node = q.front();
                q.pop();
                if(node->left) q.push(node->left);
                if(node->right) q.push(node->right);

				// push the last node (right most node) to res
                if(i == n-1) res.push_back(node->val);
            }
        }
        return res;
    }
};

int main()
{
	// creat a binary tree
	TreeNode* root = new TreeNode(0);
	root->left = new TreeNode(3);
	root->right = new TreeNode(2);
	root->left->right = new TreeNode(5);

	Solution* sol = new Solution();
	vector<int> res = sol->rightSideView(root);

	for(int i = 0; i < res.size(); i++)
		cout<<res[i]<<std::endl;

	char c;
	std::cin>>c;

	return 0;
}

Add 199 Binary Tree Right Side View


// RUN: %clang_cc1 %s -triple=x86_64-apple-darwin10 -emit-llvm-only -fdump-vtable-layouts 2>&1 | FileCheck %s

/// Examples from the Itanium C++ ABI specification.
/// http://www.codesourcery.com/public/cxx-abi/

namespace Test1 {

// This is from http://www.codesourcery.com/public/cxx-abi/cxx-vtable-ex.html

// CHECK:      Vtable for 'Test1::A' (5 entries).
// CHECK-NEXT:    0 | offset_to_top (0)
// CHECK-NEXT:    1 | Test1::A RTTI
// CHECK-NEXT:        -- (Test1::A, 0) vtable address --
// CHECK-NEXT:    2 | void Test1::A::f()
// CHECK-NEXT:    3 | void Test1::A::g()
// CHECK-NEXT:    4 | void Test1::A::h()
struct A {
  virtual void f ();
  virtual void g ();
  virtual void h ();
  int ia;
};
void A::f() {}

}

Add tests from the Itanium C++ ABI spec.


#include "Halide.h"

using namespace Halide;

int main() {

    // This test must be run with an OpenGL target
    const Target &target = get_jit_target_from_environment();
    if (!target.has_feature(Target::OpenGL)) {
        fprintf(stderr, "ERROR: This test must be run with an OpenGL target, e.g. by setting HL_JIT_TARGET=host-opengl.\n");
        return 1;
    }

    Func f;
    Var x, y, c;
    RDom r(0, 10);
    f(x, y, c) = sum(r);
    f.bound(c, 0, 3).glsl(x, y, c);

    f.realize(100, 100, 3);

    printf("Success!\n");

    return 0;
}

Add failing opengl test using an inline reduction