// Copyright 2014 Google Inc. 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 "syzygy/pe/transforms/coff_convert_legacy_code_references_transform.h"

#include "gtest/gtest.h"
#include "syzygy/block_graph/unittest_util.h"

namespace pe {
namespace transforms {

namespace {

using block_graph::BlockGraph;

}  // namespace

TEST(CoffConvertLegacyCodeReferencesTransformTest, Succeeds) {
  testing::DummyTransformPolicy policy;
  BlockGraph bg;
  BlockGraph::Block* b0 = bg.AddBlock(BlockGraph::DATA_BLOCK, 10, "b0");
  BlockGraph::Block* b1 = bg.AddBlock(BlockGraph::CODE_BLOCK, 10, "b1");
  BlockGraph::Block* b2 = bg.AddBlock(BlockGraph::CODE_BLOCK, 10, "b2");

  b1->SetReference(0, BlockGraph::Reference(BlockGraph::ABSOLUTE_REF,
                                            BlockGraph::Reference::kMaximumSize,
                                            b2,
                                            0,
                                            0));

  CoffConvertLegacyCodeReferencesTransform tx;
  EXPECT_TRUE(tx.TransformBlockGraph(&policy, &bg, b0));

  // The reference type should have changed.
  BlockGraph::Reference ref;
  ASSERT_TRUE(b1->GetReference(0, &ref));
  ASSERT_EQ(BlockGraph::RELOC_ABSOLUTE_REF, ref.type());
}

}  // namespace transforms
}  // namespace pe

Add missing unittest file from r1986.

Add missing unittest file from r1986.

BUG=
TBR=etienneb@chromium.org

Review URL: https://codereview.appspot.com/50100043

git-svn-id: db59699583a60be9a535cd09cdc9132301867226@1987 15e8cca8-e42c-11de-a347-f34a4f72eb7d


#include "EM_Classes.h"

Transitions::Transitions(const Model &model): N(model.N), Nm(model.Nm){
	F.setZero(Nm, Nm);
}

// updateF needs the smooth probabilities
void updateF(const MatrixXd & Xtt, const MatrixXd & Xt1t,
			 const MatrixXd & XiS, const int &T, const int & N){
	for(unsigned int j = 0; j <= parSelect.N - 1; ++j){
		for(unsigned int i = 0;  i <= parSelect.N - 1; ++i){
			xS = XiS.row(j).tail(T - 1);
			xtt_lag1 = Xitt.row(i).head(T - 1);
			xt1t = Xit1t.row(j).head(T).tail(T - 1);
			xS_lag1 = XiS.row(i).head(T - 1);
			F(j, i) = F(j, i)*((xS.cwiseProduct(xtt_lag1).cwiseQuotient(xt1t)).sum())/(xS_lag1.sum());
		}
	}
}

void updateRho(const MatrixXd & Xtt, const MatrixXd & Xt1t,
			   const MatrixXd & XiS){

}

Add update algorithm to transition probabilities


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

using namespace std;

typedef struct node {
    string val;
    bool visited = false;
    vector < node >  neighbors ;
} node;

typedef vector < node >  list_nodes;

inline void dfs(node start){
    stack<node> s;
    s.push(start);
    while(s.empty() == false){
        node top = s.top();
        s.pop();

        if (top.visited == false){
            top.visited  = true;
            cout << "Node " << top.val << " visited" << endl;
        }

        list_nodes n = top.neighbors;
        cout << "\tNum of neighbors " << n.size() << endl;
        for (node a: n){
            s.push(a);
        }

    }
}

int main(){

    node a,b,c,d ;
    a.val = "a";
    b.val = "b";
    c.val = "c";
    d.val = "d";

    list_nodes la(2), lc(1);
    lc[0] = d;
    la[0] = b;
    la[1] = c;

    c.neighbors = lc;
    a.neighbors = la;

    dfs(a);
    return 0;

}

Add Module for storing the graph's algorithms and create a first version of Depth first search


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* convertBST(TreeNode* root) {
        if (!root)
            return root;
        std::vector<int> nums;
        inOrder(root, &nums);

        TreeNode* dummy = root;
        std::stack<TreeNode*> s;
        int index = 0;
        int sum = getsum(nums);
        while (true) {
            while (root) {
                s.push(root);
                root = root->left;
            }
            if (s.empty())
                break;
            root = s.top();
            s.pop();
            sum -= nums[index];
            ++index;
            root->val += sum;
            root = root->right;
        }
        return dummy;
    }
private:
    int getsum(std::vector<int>& nums) {
        int sum = 0;
        for (const auto &num : nums) {
            sum += num;
        }
        return sum;
    }
    void inOrder(TreeNode *root, std::vector<int> *nums) {
        if (!root)
            return;
        std::stack<TreeNode*> s;
        while (true) {
            while (root) {
                s.push(root);
                root = root->left;
            }
            if (s.empty())
                break;
            root = s.top();
            s.pop();
            nums->push_back(root->val);
            root = root->right;
        }
        return;
    }
};

Convert BST to Greater Tree

Convert BST to Greater Tree


//===-- StatepointDefaultGC.cpp - The default statepoint GC strategy ------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains a GCStrategy which serves as an example for the usage
// of a statepoint based lowering strategy.  This GCStrategy is intended to
// suitable as a default implementation usable with any collector which can
// consume the standard stackmap format generated by statepoints, uses the
// default addrespace to distinguish between gc managed and non-gc managed
// pointers, and has reasonable relocation semantics.
//
//===----------------------------------------------------------------------===//

#include "llvm/CodeGen/GCStrategy.h"
#include "llvm/IR/Value.h"
#include "llvm/IR/DerivedTypes.h"

using namespace llvm;

namespace {
class StatepointGC : public GCStrategy {
public:
  StatepointGC() {
    UseStatepoints = true;
    // These options are all gc.root specific, we specify them so that the
    // gc.root lowering code doesn't run.
    InitRoots = false;
    NeededSafePoints = 0;
    UsesMetadata = false;
    CustomRoots = false;
    CustomSafePoints = false;
  }
  Optional<bool> isGCManagedPointer(const Value *V) const override {
    // Method is only valid on pointer typed values.
    PointerType *PT = cast<PointerType>(V->getType());
    // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
    // GC managed heap.  We know that a pointer into this heap needs to be
    // updated and that no other pointer does.
    return (1 == PT->getAddressSpace());
  }
};
}

static GCRegistry::Add<StatepointGC>
X("statepoint-example", "an example strategy for statepoint");

namespace llvm {
void linkStatepointExampleGC() {}
}

Add a missing file from 225365

Add a missing file from 225365

git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@225366 91177308-0d34-0410-b5e6-96231b3b80d8


// RUN: %clang_cc1 -fsyntax-only -std=c++11 %s -verify

void test_nonaggregate(int i) {
  auto lambda = [i]() -> void {}; // expected-error{{lambda expressions are not supported yet}} \
  // expected-note 3{{candidate constructor}}
  decltype(lambda) foo = { 1 }; // expected-error{{no matching constructor}}
}

Add a test for the non-aggregaticity of lambda types per C++11
[expr.prim.lambda].

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


// Chapter 21, Exercise 3: implement count() yourself and test it

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

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

template<class In, class T>
int my_count(In first, In last, const T& val)
{
    int ctr = 0;
    while (first !=last;) {
        if (*first == val) ++ctr;
        ++first;
    }
    return ctr;
}

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

int main()
try {
    vector<int> vi;
    for (int i = 0; i<50; ++i)
        vi.push_back(randint(50));
    cout << "vi:\n";
    for (vector<int>::iterator p = vi.begin(); p!=vi.end(); ++p)
        cout << *p << '\n';
    cout << "Enter value for which you want to know the count, -1 to exit: ";
    int val;
    while (cin>>val) {
        if (val==-1) break;
        int ctr = count(vi.begin(),vi.end(),val);
        cout << val << " is " << ctr << " time" << (ctr!=1 ? "s " : " ")
            << "in vi.\nNext value: ";
    }
}
catch (Range_error& re) {
    cerr << "bad index: " << re.index << "\n";
}
catch (exception& e) {
    cerr << "exception: " << e.what() << endl;
}
catch (...) {
    cerr << "exception\n";
}

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

Add Chapter 21, exercise 3

Add Chapter 21, exercise 3


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

// Test that the __libcpp_version file matches the value of _LIBCPP_VERSION

#include <__config>

#ifndef _LIBCPP_VERSION
#error _LIBCPP_VERSION must be defined
#endif

static const int libcpp_version =
#include <__libcpp_version>
;

static_assert(_LIBCPP_VERSION == libcpp_version,
              "_LIBCPP_VERSION doesn't match __libcpp_version");

int main() {

}

Add test that _LIBCPP_VERSION matches __libcpp_version

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


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

using namespace Halide;

int main(int argc, char **argv) {
    if (!get_jit_target_from_environment().has_gpu_feature()) {
        printf("Not running test because no gpu feature enabled in target.\n");
        return 0;
    }

    // A sequence of stages which may or may not run on the gpu.
    Func f, g, h;
    ImageParam in(Int(32), 1);
    Var x;

    f(x) = in(x) + in(x + 1);
    g(x) = f(x * 2);
    h(x) = g(x) - 7;

    Param<bool> gpu_f, gpu_g, gpu_h;

    f.compute_root().specialize(gpu_f).gpu_tile(x, 16);
    g.compute_root().specialize(gpu_g).gpu_tile(x, 16);
    h.compute_root().specialize(gpu_h).gpu_tile(x, 16);

    Image<int> out(128), reference(128), input(256);

    lambda(x, x * 17 + 43 + x * x).realize(input);
    in.set(input);

    gpu_f.set(false);
    gpu_g.set(false);
    gpu_h.set(false);
    h.realize(reference);

    for (int i = 1; i < 8; i++) {
        gpu_f.set((bool)(i & 1));
        gpu_g.set((bool)(i & 2));
        gpu_h.set((bool)(i & 4));

        h.realize(out);

        RDom r(out);
        uint32_t err = evaluate<uint32_t>(sum(abs(out(r) - reference(r))));
        if (err) {
            printf("Incorrect results for test %d\n", i);
            return -1;
        }
    }

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

Add test where specialization may place stages on the gpu

Former-commit-id: 7491333af6d74847eb5298fee58e48d4a4ca616f


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        stack<ListNode*> s;
        s.push(head);
        ListNode* ret=head;
        while(head->next){
            head=head->next;
            s.push(head);
        }
        int i=1;
        ListNode* prev=NULL;
        while(i<n){
            prev=s.top();
            s.pop();
            i++;
        }
        s.pop();
        if(s.size()){
            s.top()->next=prev;
            return ret;
        }else{
            return prev;
        }
    }
};

Remove Nth Node From End of List

Remove Nth Node From End of List


class Solution {
public:
    bool checkIfPangram(string sentence) {
        if (sentence.size() < 26)
            return false;
        std::vector<int> table(26, 0);
        for (const auto & c : sentence) {
            table[c-97] = 1;
        }
        return sum(table) == 26;
    }
private:
    int sum(std::vector<int> &table) {
        int sum = 0;
        for (const auto &i : table) {
            sum += std::move(i);
        }
        return sum;
    }
};

Check if the Sentence Is Pangram

Check if the Sentence Is Pangram


#include<iostream>
#include<cstdlib>

using namespace std;

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

		Node(){}

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

		Node *push(Node *head, int data){
			Node *np=new Node(data);
			Node *t=head;

			cout<<"Pushing "<<np->data<<"...\n";

			if(head==NULL)
				return np;

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

			t->next=np;

			return head;
		}

		Node *pop(Node *head){
			Node *t=head;
			Node *p;

			if(head==NULL){
				cout<<"Nothing to pop. Stack empty.\n";
				return NULL;
			}

			if(head->next==NULL){
				cout<<"Popping "<<head->data<<"...\n";
				free(head);
				return NULL;
			}

			while(t->next!=NULL){
				p=t;
				t=t->next;
			}

			p->next=NULL;

			cout<<"Popping "<<t->data<<"...\n";

			free(t);

			return head;
		}

		void displayStack(Node *head){

			if(head==NULL)
				cout<<"Nothing to display. Stack empty.\n";
			else{
				cout<<"\nThe list is as follows:\n";

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

int main()
{
	int d,e;
	Node *head=NULL;
	Node np;

	while(1){
		cout<<"Press 1/2/3 to push pop or display the elements of stack. Press anything else to exit.\n";

		cin>>e;
		switch(e){
			case 1:
				cout<<"Enter the data you want to push: ";
				cin>>d;
				head=np.push(head,d);
				break;
			case 2:
				head=np.pop(head);
				break;
			case 3:
				np.displayStack(head);
				break;
			default:
				goto stack;
		}
	}

	stack:

	return 0;
}

Implement stack using linked list

Implement stack using linked list


#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 test failing on hexagon.

Former-commit-id: a91a9ce74fbc2b2bf486e561e5601ad438b047a9


//
// Copyright 2013 Jeff Bush
//
// 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 "output.h"

//
// Struct as return value
//

struct MyStruct
{
	int a;
	int b;
};

Output output;

MyStruct doIt(int a, int b)
{
	MyStruct s1;
	s1.a = a;
	s1.b = b;
	return s1;
}

int main()
{
	MyStruct s1 = doIt(0x37523482, 0x10458422);

	output << "s1a" << s1.a << "\n";
	output << "s1b" << s1.b << "\n";

	return 0;
}

Add struct return test (currently causes compiler assertion)


// https://leetcode.com/problems/contains-duplicate/
// The naive version shown as version 1 could get time limit exceeded. Since the
// problem is a query for the existance. It's easy to come up with a solution using
// map.

// Version 1
class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        size_t n = nums.size();
        for (size_t i = 0; i < n; ++i) {
            for (size_t j = 0; j < i; ++j) {
                if (nums[i] == nums[j]) {
                    return true;
                }
            }
        }
        return false;
    }
};

// Version 2
class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        unordered_set<int> prevs;
        size_t n = nums.size();
        for (size_t i = 0; i < n; ++i) {
            if (prevs.find(nums[i]) != prevs.end()) {
                return true;
            }
            prevs.insert(nums[i]);
        }
        return false;
    }
};

Add a solution for problem 217: Contains Duplicate.


//The purpose of this program is to get the number of uniq source phrases in the document
//In order to use a smaller probing_hash_table

#include "helpers/line_splitter.hh"

#include "util/file_piece.hh"
#include "util/file.hh"
#include "util/usage.hh"

#include <stdio.h>
#include <fstream>
#include <iostream>

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

	if (argc != 2) {
		std::cout << "ERROR! The program requires 1 argument, but " << argc - 1 << " were provided." << std::endl;
		std::cout << "Usage: " << argv[0] << " path_to_phrase_table." << std::endl;
	}

	//Read the file
	util::FilePiece filein(argv[1]);

	unsigned long uniq_lines = 0;
	line_text prev_line;

	while (true){
		line_text new_line;
		try {
			//Process line read
			new_line = splitLine(filein.ReadLine());
		} catch (util::EndOfFileException e){
			std::cout << "End of file" << std::endl;
			break;
		}
		if (new_line.source_phrase == prev_line.source_phrase){
			continue;
		} else {
			uniq_lines++;
			prev_line = new_line;
		}
	}

	std::cout << "Number of unique lines is: " << uniq_lines << std::endl;
	return 1;
}

Determine the number of unique lines.

Determine the number of unique lines.


/* Copyright 2019 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/util/xla_config_proxy.h"

namespace tensorflow {

/*static*/
OptimizerOptions::GlobalJitLevel XlaConfigProxy::GetGlobalJitLevel(
    OptimizerOptions::GlobalJitLevel jit_level_in_session_opts) {
  OptimizerOptions::GlobalJitLevel global_jit_level = jit_level_in_session_opts;
  ConfigSetterRegistry<OptimizerOptions::GlobalJitLevel>::Global()->Update(
      jit_level_in_session_opts);
  return global_jit_level;
}

}  // namespace tensorflow

/* Copyright 2019 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/util/xla_config_proxy.h"

namespace tensorflow {

/*static*/
OptimizerOptions::GlobalJitLevel XlaConfigProxy::GetGlobalJitLevel(
    OptimizerOptions::GlobalJitLevel jit_level_in_session_opts) {
  OptimizerOptions::GlobalJitLevel global_jit_level = jit_level_in_session_opts;
  ConfigSetterRegistry<OptimizerOptions::GlobalJitLevel>::Global()->Update(
      global_jit_level);
  return global_jit_level;
}

}  // namespace tensorflow

Fix a typo in XlaConfigProxy.

Fix a typo in XlaConfigProxy.


// Chapter 24, Try This 2: run conversion test functions, modify f() to print
// the variables

#include<iostream>
#include<iomanip>

using std::cout;

void f(int i, double fpd)
{
    cout << std::setprecision(15);
    char c = i;
    cout << "c = i: " << int(c) << '\n';
    short s = i;
    cout << "s = i: " << s << '\n';
    i = i+1;
    cout << "i + 1: " << i << '\n';
    long lg = i*i;
    cout << "lg = i*i: " << lg << '\n';
    float fps = fpd;
    cout << "fps = fpd: " << fps << '\n';
    i = fpd;
    cout << "i = pfd: " << i << '\n';
    fps = i;
    cout << "fps = i: " << fps << '\n';
}

void g()
{
    char ch = 0;
    for (int i = 0; i<500; ++i)
        cout << int(ch++) << '\t';
}

int main()
{
    g();
    cout << "\n\n";
    f(127,5.7);
    cout << '\n';
    f(33000,3.4e39);
    cout << '\n';
    f(2147483647,21.00000009e8);
}

Add Chapter 24, Try This 2

Add Chapter 24, Try This 2


/*
 *	Author: matthew6868（mxu.public@outlook.com）
 *	Date: 2016-10-20
 *	Corporation:  Zoom Video Communication, Inc, 软视（杭州）有限公司
 */
void makeOddNumberFisrt(std::vector<int> &data) {
	//std::partition(v.begin(), v.end(), [v](int i) {return v[i] % 2 == 1; });
	if (data.size() > 1) {
		int left = 0, right = data.size() -1 ;
		// left 指向左边的奇数索引，right 指向右边的奇数索引。
		while (left < right) {
			// 如果头尾索引都是偶数，则左移右边的索引
			if (data[left] % 2 == 0 && data[right] % 2 == 0) {
				right--;
			}
			else if (data[left] % 2 != 0 && data[right] % 2 != 0) {
				// 如果头尾索引都是奇数数，则右移左边的索引
				left++;
			} else if (data[left] % 2 == 0 && data[right] % 2 != 0) {
				// 如果左侧是偶数，右侧是奇数，则交换位置，并同时移动左右索引
				int temp = data[left];
				data[left] = data[right];
				data[right] = temp;
				left++;
				right--;
			}
			else {
				left++;
				right++;
			}
		}
	}
}

Add interview question odd number fist from Zoom Inc.


#include <stdio.h>

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

void printInorder(NODE* root) {
  if (root) {
    printInorder(root->left);
    printf("%c ", root->data);
    printInorder(root->right);
  }
}

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

  return node;
}

int search(char* inOrder, int start, int end, int data) {
  for (int i = start; i <= end; i++) {
    if (inOrder[i] == data) {
      return i;
    }
  }
  return -1;
}

NODE* buildTree(char* inOrder, char* preOder, int start, int end) {
  static int preIndex = 0;

  printf("start : [%d] end : [%d] \n", start, end);

  if (start > end) return nullptr;

  NODE* temp = newNode(preOder[preIndex++]);

  if (start == end) return temp;

  int inIndex = search(inOrder, start, end, temp->data);

  printf("Got the index in inOrder array at : [%d] \n", inIndex);

  if (inIndex >= 0) {
    temp->left = buildTree(inOrder, preOder, start, inIndex - 1);

    temp->right = buildTree(inOrder, preOder, inIndex + 1, end);
  }
  return temp;
}

int main(int argc, char const* argv[]) {
  char in[] = {'D', 'B', 'E', 'A', 'F', 'C'};
  char pre[] = {'A', 'B', 'D', 'E', 'C', 'F'};
  int len = sizeof(in) / sizeof(in[0]);
  NODE* root = buildTree(in, pre, 0, len - 1);

  /* Let us test the built tree by printing Insorder traversal */
  printf("Inorder traversal of the constructed tree is \n");
  printInorder(root);
  return 0;
}

Build the binary tree from Inorder and PreOdertraversal.


#include <iostream>
#include "matrix/Vector"

using namespace sipl;

int main()
{
    VectorXi v(3);
    v[0] = 1;
    v[1] = 2;
    v[2] = 3;
    std::cout << v << std::endl;
}

Test driver for Vector class

Test driver for Vector class


#include <iostream>
#include <set>
#include <cassert>

template <typename T>
struct node {
    T data;
    node *left = nullptr, *right = nullptr;
    node(T data): data(data) {}
};

template <typename T>
class tree {
    node<T>* root = nullptr;

public:
    bool contains(const T& data) {
        auto curr = root;
        while (curr != nullptr) {
            if (curr->data == data)
                return true;
            curr = data < curr->data ? curr->left : curr->right;
        }
        return false;
    }

    void insert(T data) {
        auto ptr = &root;
        while (auto curr = *ptr) {
            if (curr->data == data)
                return;
            ptr = data < curr->data ? &curr->left : &curr->right;
        }
        *ptr = new node<T>(data);
    }

    void remove(const T& data) {
        auto ptr = &root;
        while (auto curr = *ptr) {
            if (data == curr->data) {
                if (curr->left == nullptr) {
                    *ptr = curr->right;
                } else if (curr->right == nullptr) {
                    *ptr = curr->left;
                } else {
                    auto l = curr->left, r = l->right;
                    if (r == nullptr) {
                        l->right = curr->right;
                        *ptr = l;
                    } else {
                        while (r->right != nullptr)
                            l = r, r = r->right;
                        l->right = r->left;
                        r->left = curr->left;
                        r->right = curr->right;
                        *ptr = r;
                    }
                }
                delete curr;
                return;
            }
            ptr = data < curr->data ? &curr->left : &curr->right;
        }
    }
};

int main() {
    tree<int> ours;
    std::set<int> theirs;
    int op_counts[] = {0, 0, 0};
    for (int i = 0; i < 100000; ++i) {
        int data = rand() % 100;
        int op = rand() % 3;
        ++op_counts[op];
        if (op == 0) {
            assert(ours.contains(data) == theirs.count(data));
        } else if (op == 1) {
            ours.insert(data);
            theirs.insert(data);
        } else {
            assert(op == 2);
            ours.remove(data);
            theirs.erase(data);
        }
    }

    for (int n : op_counts)
        assert(n > 0);
    std::cout << "All tests passed" << std::endl;
    return 0;
}

Write and test binary search tree in cpp


// 173. Binary Search Tree Iterator
/**
 * Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
 *
 * Calling next() will return the next smallest number in the BST.
 *
 * Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
 *
 * Tags: Tree, Stack, Design
 *
 * Similar Problems: (M) Binary Tree Inorder Traversal, (M) Flatten 2D Vector, (M) Zigzag Iterator, (M) Peeking Iterator, (M) Inorder Successor in BST
 *
 * Author: Kuang Qin
 */

#include "stdafx.h"
#include <stack>
#include <iostream>

using namespace std;

/**
 * Definition for binary tree
 */
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

// Time: O(1), pop the top element on the stack
// Space: O(h), elements in the stack will never exceed the height of the tree
class BSTIterator {
    stack<TreeNode *> st;

    // push all left children onto the stack
    void pushAllNodes(TreeNode *root) {
        while (root != NULL)
        {
            st.push(root);
            root = root->left;
        }
    }
public:
    BSTIterator(TreeNode *root) {
        pushAllNodes(root);
    }

    /** @return whether we have a next smallest number */
    bool hasNext() {
        return !st.empty();
    }

    /** @return the next smallest number */
    int next() {
        // pop the smallest element
        TreeNode *node = st.top();
        st.pop();

        // push the right subtree of current node
        pushAllNodes(node->right);
        return node->val;
    }
};

/**
 * Your BSTIterator will be called like this:
 * BSTIterator i = BSTIterator(root);
 * while (i.hasNext()) cout << i.next();
 */

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

Add Solution for Problem 173

Add Solution for Problem 173


#include <bits/stdc++.h>

using namespace std;

ll modular_pow(ll  base, int exponent, ll  modulus){
	ll result = 1;
	while (exponent > 0){
		/* if y is odd, multiply base with result */
		if (exponent & 1)
			result = (result * base) % modulus;
		/* exponent = exponent/2 */
		exponent = exponent >> 1;
		/* base = base * base */
		base = (base * base) % modulus;
	}
	return result;
}

int main(){

}

Add algorithm for modular pow.

Add algorithm for modular pow.


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

#include <iostream>
using namespace std;

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

class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) {
		ListNode dummy(-1);
		dummy.next = head;

		ListNode *p=&dummy;
		if(p->next==NULL || p->next->next==NULL)
			return dummy.next;

		while(1)
		{
			p = p->next;

			if(p==NULL || p->next ==NULL)
				break;
			ListNode *temp = p->next;

			if(p->val==temp->val)
			{
				while(temp->next!=NULL)
				{
					if(p->val!=temp->next->val)
						break;
					ListNode *ttemp = temp;
					temp = temp->next;
					delete ttemp;
				}
				p->next = temp->next;
				delete temp;
			}
		}

		return dummy.next;
    }
};

int main()
{
	//ListNode a(1);
	//ListNode b(1),c(1),d(2),e(3);
	//a.next = &b;b.next = &c; c.next = &d; d.next = &e;

	ListNode a(1);
	ListNode b(1);
	a.next  = &b;
	Solution solute;

	solute.deleteDuplicates(&a);
}

Remove Duplicates from Sorted List

Remove Duplicates from Sorted List

https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list/


#include "catch.hpp"

#include <mapnik/debug.hpp>
#include <mapnik/xml_tree.hpp>
#include <mapnik/xml_loader.hpp>

TEST_CASE("xml parser") {

  SECTION("trims whitespace") {

    // simple and non-valid mapnik XML reduced from the empty_parameter2.xml
    // test case. this is to check that the xml parsing routine is trimming
    // whitespace from text nodes as part of the parsing operation.
    const std::string xml("<Map>"
                          "  <Layer>"
                          "    <Datasource>"
                          "      <Parameter name=\"empty\"><![CDATA[ ]]></Parameter>"
                          "    </Datasource>"
                          "  </Layer>"
                          "</Map>");

    mapnik::xml_tree tree("utf8");
    tree.set_filename("xml_datasource_parameter_trim.cpp");
    REQUIRE_NOTHROW(read_xml_string(xml, tree.root(), ""));

    REQUIRE(tree.root().has_child("Map"));
    mapnik::xml_node const &map = tree.root().get_child("Map");

    REQUIRE(map.has_child("Layer"));
    mapnik::xml_node const &layer = map.get_child("Layer");

    REQUIRE(layer.has_child("Datasource"));
    mapnik::xml_node const &datasource = layer.get_child("Datasource");

    REQUIRE(datasource.has_child("Parameter"));
    mapnik::xml_node const &parameter = datasource.get_child("Parameter");

    // parser should call mapnik::util::trim on the text content and
    // this should result in an empty text string in the parameter.
    REQUIRE(parameter.get_text() == "");
  }
}

Add test for XML parser whitespace trimming behaviour.

This tests the at the XML parser trims whitespace from XML text
nodes. This was already the behaviour of the libxml2 parser, but
not the rapidxml parser.

Note that this makes #2878 pass for the rapidxml parser as well
as the libxml2 parser. It seems that Travis uses the rapidxml
parser only.


/* Copyright 2015 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/kernels/cwise_ops_common.h"

namespace tensorflow {
REGISTER4(UnaryOp, CPU, "Asin", functor::asin, Eigen::half, bfloat16, float,
          double);

#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#if !defined(MLIR_GENERATED_GPU_KERNELS_ENABLED)
REGISTER3(UnaryOp, GPU, "Asin", functor::asin, Eigen::half, float, double);
#endif
REGISTER(UnaryOp, GPU, "Asin", functor::asin, bfloat16)
#endif

}  // namespace tensorflow

/* Copyright 2015 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/kernels/cwise_ops_common.h"

namespace tensorflow {
REGISTER6(UnaryOp, CPU, "Asin", functor::asin, Eigen::half, bfloat16, float,
          double, complex64, complex128);

#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#if !defined(MLIR_GENERATED_GPU_KERNELS_ENABLED)
REGISTER3(UnaryOp, GPU, "Asin", functor::asin, Eigen::half, float, double);
#endif
REGISTER(UnaryOp, GPU, "Asin", functor::asin, bfloat16)
#endif

}  // namespace tensorflow

Add complex support for tf.math.asin

Add complex support for tf.math.asin

This PR address the feature requested by 54317 in adding
complex support for tf.math.asin.

This PR fixes 54317.

Signed-off-by: Yong Tang <765086fe2e0c1f980161f127fec596800f327f62@outlook.com>


#include "gtest/gtest.h"

#include "worker.h"
#include "requests.pb.h"

class TestMessageWorker : public traffic::MessageWorker
{
protected:
	bool set_up() { return true; }

	bool process_summary() {
		summary = true;
		return true;
	}

	bool process_statistics() {
		statistic = true;
		return true;
	}

public:
	bool statistic;
	bool summary;

	using traffic::MessageWorker::process;

	TestMessageWorker()
	:
		traffic::MessageWorker(),
		statistic(false),
		summary(false)
	{ }
};

TEST(ServerMessageWorker, basic_message_worker) {
	TestMessageWorker w;

	request::Request request;
	request.set_version(1);

	request::Statistic *stat = request.mutable_statistic();

	request::TimeRange *range = stat->mutable_range();

	range->set_start(1);
	range->set_end(2);

	stat->set_address("10.10.10.10");

	std::string buffer;
	request.SerializeToString(&buffer);

	std::string out_buffer;
	w.process(out_buffer, (void *)buffer.c_str(), buffer.size());

	EXPECT_TRUE(w.statistic);
	EXPECT_FALSE(w.summary);
}

Add simple test for message prototype

Add simple test for message prototype

Signed-off-by: Jan Losinski <577c4104c61edf9f052c616c0c23e67bef4a9955@wh2.tu-dresden.de>


#include <iostream>
#include <queue>

using namespace std;

struct edge{
    int to, weight;
    edge(){}
    edge(int _to, int _weight){
        to = _to;
        weight = _weight;
    }
    bool operator < (edge e) const {
        return weight > e.weight;
    }
};

typedef priority_queue<edge> pq;

int main(){
    pq edges;

    edges.push(edge(1, 23));
    edges.push(edge(2, 3));
    edges.push(edge(3, 10));
    edges.push(edge(4, 11));
    edges.push(edge(5, 4));

    while(!edges.empty()){
        edge a = edges.top();
        edges.pop();
        cout << a.to << endl;
    }
}

Add useful structure for combininig with more powerful structure.


#include <iostream>
#include <fstream>

using std::ifstream;
using std::ios;
using std::cout;

int main() {
  ifstream text_file("lines.txt", ios::binary);

  char buffer[100];
  while (text_file.read(buffer, 100).gcount()) {
    for (int i = 0; i < text_file.gcount(); ++i) {
      cout << (int)buffer[i] << ' ';
    }
    cout << '\n';
  }

  text_file.close();

  return 0;
}

Add program which prints the bytes in a file as numbers in base-ten number system


class Solution {
public:
    bool closeStrings(string word1, string word2) {
        std::vector<int> v1(26, 0), v2(26, 0);
        std::unordered_set<char> s1, s2;
        for (const auto& c: word1) {
            v1[c-'a']++;
            s1.emplace(c);
        }
        for (const auto& c: word2) {
            v2[c-'a']++;
            s2.emplace(c);
        }
        std::sort(v1.begin(), v1.end());
        std::sort(v2.begin(), v2.end());
        return s1 == s2 && v1 == v2;
    }
};

Determine if Two Strings Are Close

Determine if Two Strings Are Close


// RUN: %clang_cc1 -triple i386-apple-darwin9 -analyze -analyzer-experimental-internal-checks -checker-cfref -analyzer-store=region -verify -fblocks -analyzer-opt-analyze-nested-blocks %s
// RUN: %clang_cc1 -triple x86_64-apple-darwin9 -analyze -analyzer-experimental-internal-checks -checker-cfref -analyzer-store=region -verify -fblocks   -analyzer-opt-analyze-nested-blocks %s
// XFAIL: *

// This test case currently crashes because of an assertion failure.
char &test1_aux();
char *test1() {
  return &test1_aux();
}

Add failing test case for C++ static analysis.

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


// https://leetcode.com/problems/serialize-and-deserialize-binary-tree/

// Use level order or preorder traversal to serialize since these two methods
// saves parents before childs. It would be convenient to deserialize.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Codec {
    void serialize(const TreeNode* root, string* rep) {
        if (root == nullptr) {
            rep->push_back('#');
            return;
        }
        rep->append(to_string(root->val));
        rep->push_back(' ');
        serialize(root->left, rep);
        serialize(root->right, rep);
    }

    TreeNode* deserialize(istringstream& inbuf) {
        char c;
        inbuf >> c;
        if (c == '#') return nullptr;
        else {
            inbuf.putback(c);
            int v;
            inbuf >> v;
            TreeNode* root = new TreeNode(v);
            root->left = deserialize(inbuf);
            root->right = deserialize(inbuf);
            return root;
        }
    }

public:

    // Encodes a tree to a single string.
    string serialize(const TreeNode* root) {
        string rep;
        serialize(root, &rep);
        return rep;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(const string& data) {
        istringstream inbuf(data);
        return deserialize(inbuf);
    }
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));

Add a solution for problem 297: Serialize and Deserialize Binary Tree.


/*
 * =====================================================================================
 *
 *       Filename:  max_product.cc
 *
 *    Description:  max product algorithms
 *
 *        Version:  1.0
 *        Created:  02/05/2015 05:56:41 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:   (Qi Liu), liuqi.edward@gmail.com
 *   Organization:  antq.com
 *
 * =====================================================================================
 */
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>

template<typename Type>
inline Type Max(Type t1, Type t2, Type t3)
{
	t1 = t1 > t2 ? t1 : t2;
	return t1 > t3 ? t1 : t3;
}

template<typename Type>
inline Type Min(Type t1, Type t2, Type t3)
{
	t1 = t1 < t2 ? t1 : t2;
	return t1 < t3 ? t1 : t3;
}

/*
 * Find the maximum continuous product sub-array
 */
template<typename Type>
Type MaxContinuousProduct(Type* array, int32_t size)
{
	int i;
	Type max;
	Type* max_array = (Type*)malloc(size*sizeof(Type));
	Type* min_array = (Type*)malloc(size*sizeof(Type));

	max = array[0];
	max_array[0] = array[0];
	min_array[0] = array[0];
	for(i = 1; i < size; ++i)
	{
		max_array[i] = Max(array[i], array[i] * max_array[i-1], array[i]*min_array[i-1]);
		min_array[i] = Min(array[i], array[i] * max_array[i-1], array[i]*min_array[i-1]);
		if(max_array[i] > max)
			max = max_array[i];
	}
	free(max_array);
	free(min_array);
	return max;
}

int main()
{
	int array[9] = {-3, 5, 5, 10, -3, 9, 8, 2, -1};
	int ans = MaxContinuousProduct(array, 9);
	fprintf(stdout, "Max: %d\n", ans);
	return 0;
}

Add maximum continuous product of sub array


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

static void test_filepath_creation(skiatest::Reporter* reporter) {
    SkString result;
    SkString filename("test");
    const char* dir = "test/path";
    sk_tools::make_filepath(&result, dir, filename);
    REPORTER_ASSERT(reporter, result.equals("test/path/test"));
}

static void test_get_basename(skiatest::Reporter* reporter) {
    SkString result;
    SkString path("/path/basename");
    sk_tools::get_basename(&result, path);
    REPORTER_ASSERT(reporter, result.equals("basename"));

    result.reset();
    path.set("/path/dir/");
    sk_tools::get_basename(&result, path);
    REPORTER_ASSERT(reporter, result.equals("dir"));

    result.reset();
    path.set("path");
    sk_tools::get_basename(&result, path);
    REPORTER_ASSERT(reporter, result.equals("path"));

#if defined(SK_BUILD_FOR_WIN)
    result.reset();
    path.set("path\\winbasename");
    sk_tools::get_basename(&result, path);
    REPORTER_ASSERT(reporter, result.equals("winbasename"));

    result.reset();
    path.set("path\\windir\\");
    sk_tools::get_basename(&result, path);
    REPORTER_ASSERT(reporter, result.equals("windir"));
#endif
}

static void TestPictureUtils(skiatest::Reporter* reporter) {
    test_filepath_creation(reporter);
    test_get_basename(reporter);
}

#include "TestClassDef.h"
DEFINE_TESTCLASS("PictureUtils", PictureUtilsTestClass, TestPictureUtils)

Allow specific files and multiple inputs for picture testing tools.

Changed the render_pictures, bench_pictures and test_pictures.py so that multiple inputs can be given. Furthermore, specific files can also be specified.

Unit tests have also been added for picture_utils.cpp.

Committed http://code.google.com/p/skia/source/detail?r=4486

Review URL: https://codereview.appspot.com/6345054

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


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

using namespace Halide;

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

    f(x, y) = x + y;
    f.bound(y, 0, 1);
    f.parallel(y);

    f.realize(10, 1);

    return 0;
}

Add a test for the warning about parallel for loops of size one

Former-commit-id: c38732b7ff4d5b3bdfbbbd5cbc9175ab09d079fc


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

using namespace mfem;

namespace pa_kernels
{

template <typename INTEGRATOR>
double test_vector_pa_integrator(int dim)
{
   Mesh *mesh;
   if (dim == 2)
   {
      mesh = new Mesh(2, 2, Element::QUADRILATERAL, 0, 1.0, 1.0);
   }
   if (dim == 3)
   {
      mesh = new Mesh(2, 2, 2, Element::HEXAHEDRON, 0, 1.0, 1.0, 1.0);
   }

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

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

   BilinearForm blf_fa(&fes);
   blf_fa.AddDomainIntegrator(new INTEGRATOR);
   blf_fa.Assemble();
   blf_fa.Finalize();
   blf_fa.Mult(x, y_fa);

   BilinearForm blf_pa(&fes);
   blf_pa.SetAssemblyLevel(AssemblyLevel::PARTIAL);
   blf_pa.AddDomainIntegrator(new INTEGRATOR);
   blf_pa.Assemble();
   blf_pa.Mult(x, y_pa);

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

   delete mesh;
   return difference;
}

TEST_CASE("Nonlinear Convection", "[PartialAssembly], [NonlinearPA]")
{
   SECTION("2D")
   {
      REQUIRE(test_vector_pa_integrator<VectorMassIntegrator>(2) == Approx(0.0));
      REQUIRE(test_vector_pa_integrator<VectorDiffusionIntegrator>(2) == Approx(0.0));
   }

   SECTION("3D")
   {
      REQUIRE(test_vector_pa_integrator<VectorMassIntegrator>(3) == Approx(0.0));
      REQUIRE(test_vector_pa_integrator<VectorDiffusionIntegrator>(3) == Approx(0.0));
   }
}

}

Add consistency test for PA vector mass and diffusion


#include <iostream>
#include <math.h>

using namespace std;
typedef long long ll;

bool is_prime(ll n){
    if (n < 2) return false;
    if (n < 4) return true;
    if (n % 2 == 0 || n % 3 == 0) return false;
    if (n < 25) return true;
    for(int i = 5; i*i <= n; i += 6){
        if(n % i == 0 || n % (i + 2) == 0)
            return false;
    }
    return true;
}

int main(){
    cout << is_prime(23234) << endl;
    cout << is_prime(2) << endl;
    cout << is_prime(7454) << endl;
    cout << is_prime(976) << endl;
    cout << is_prime(1973) << endl;
    return 0;

}

Add algorithm primaly test .

Add algorithm  primaly test .


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

// <array>

// iterator, const_iterator

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

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

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

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

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

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

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

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

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


#include <peelo/text/rune.hpp>
#include <cassert>

int main()
{
  peelo::rune auml(0x00e4);

  assert(auml.equals(0x00e4));
  assert(auml.equals_icase(0x00c4));
  assert(auml.compare('a') > 0);
  assert(auml.compare(0x00e4) == 0);
  assert(auml.compare(0x00f6) < 0);
  assert(auml.compare_icase('A') > 0);
  assert(auml.compare_icase(0x00c4) == 0);
  assert(auml.compare_icase(0x00f6) < 0);

  assert(peelo::rune::to_upper(0x00e4) == 0x00c4);
  assert(peelo::rune::to_lower(0x00c4) == 0x00e4);

  auml = peelo::rune::min;
  --auml;
  assert(auml == peelo::rune::max);

  auml = peelo::rune::max;
  ++auml;
  assert(auml == peelo::rune::min);

  return 0;
}

Add test case for rune class.

Add test case for rune class.


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

struct meta {
  template<typename U>
  struct apply {
    typedef U* type;
  };
};

template<typename T, typename U>
void f(typename T::template apply<U>::type);

void test_f(int *ip) {
  f<meta, int>(ip);
}

Add a test case for r95555.

Add a test case for r95555.

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


class Solution {
public:
    bool arrayStringsAreEqual(vector<string>& word1, vector<string>& word2) {
        std::string s1 = "", s2 = "";
        for (const auto& word : word1) {
            s1 += word;
        }
        for (const auto& word : word2) {
            s2 += word;
        }
        return s1 == s2;
    }
};

Check If Two String Arrays are Equivalent


#include <iostream>

/**
 * Need to use 'auto' return type to return a lambda since we can't type it's
 * type. This is only possible in C++14 or later.
 */

auto func(void)
{
  auto lmb = [](int x){ return x+1; };
  return lmb;
}

int main(void)
{
  auto lmb = func();

  std::cout << "Lambda: " << lmb(1) << std::endl;

  return 0;
}

Add c++ lambda return type test

Add c++ lambda return type test


// RUN: %llvmgxx -S %s -o - | FileCheck %s

#include <utility>

typedef std::pair<int,int> P;
// CHECK: @_ZZ1fvE1X {{.*}} undef

P f() {
  static const P X = P(1,2);
  return X;
}

Check that P is not zero initialized.

Check that P is not zero initialized.

git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@98627 91177308-0d34-0410-b5e6-96231b3b80d8


#include<iostream>
#include<cstdlib>

using namespace std;

class Node{
	public:

	int data;
	Node *prev, *next;

	Node(){}

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

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

		if(head==NULL)
			return np;

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

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

		return head;
	}

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

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

		while(c<pos-1){
			t=t->next;
			c++;
		}
		if(t->next->next!=NULL)
			t->next->next->prev=t;
		Node *tm=t->next;
		t->next=t->next->next;
		free(tm);

		return head;
	}

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

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

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

        cout<<"Enter the 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 doubly linked list


#pragma once

#include <Windows.h>
#include <WinINet.h>
#include <IOStream>
#include <String>

#pragma comment(lib, "WinINet.lib")

std::string replaceAll(std::string subject, const std::string& search,
    const std::string& replace) {
    size_t pos = 0;
    while ((pos = subject.find(search, pos)) != std::string::npos) {
        subject.replace(pos, search.length(), replace);
        pos += replace.length();
    };
    return subject;
};

std::string DownloadURL(std::string URL) {
    HINTERNET interwebs = InternetOpenA("Mozilla/5.0", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, NULL);
    HINTERNET urlFile;
    std::string rtn;
    if (interwebs) {
        urlFile = InternetOpenUrlA(interwebs, URL.c_str(), NULL, NULL, NULL, NULL);
        if (urlFile) {
            char buffer[2000];
            DWORD bytesRead;
            do {
                InternetReadFile(urlFile, buffer, 2000, &bytesRead);
                rtn.append(buffer, bytesRead);
                memset(buffer, 0, 2000);
            } while (bytesRead);
            InternetCloseHandle(interwebs);
            InternetCloseHandle(urlFile);
            std::string p = replaceAll(rtn, "|n", "\r\n");
            return p;
        };
    };
    InternetCloseHandle(interwebs);
    std::string p = replaceAll(rtn, "|n", "\r\n");
    return p;
};

std::string keychecker() {
    std::string key;
    std::cout << "Enter Key: ";
    std::cin >> key;
    return key;
};

void auth() {
    std::string hostfile = ""; //Hwid check site [Pastebin etc.]
    std::string hot = keychecker();
    std::string result = DownloadURL(hostfile += hot);
    if (result == "1") {
        std::cout << "Whitelisted Key: " + hot, +"\n"; //Success message.
    }
    else {
        std::cout << "Key Not Found\n" << hot.c_str();
        Sleep(10000);
        exit(10);
    };
};

Rename to be more descriptive correction


/*
 * gtest_main.cpp
 *
 *  Created on: May 12, 2015
 *      Author: Vance Zuo
 */

#include "gmock/gmock.h"
#include <stdio.h>

int main(int argc, char **argv) {
  printf("Running main() from gtest_main.cpp\n");
  testing::InitGoogleMock(&argc, argv);
  return RUN_ALL_TESTS();
}

Add google testing framework main

Add google testing framework main

To run, requires gmock/gmock.h, gmock/gmock-gtest-all.cc, and
gtest/gtest.h (obtainable from https://code.google.com/p/googlemock/).


#include  <iostream>
using namespace std;

// function to sort a using shellSort
int shellSort(int a[],int n)
{
	for(int shell=n/2;shell>0; shell/=2)
	{
		for(int i=shell;i<n;i++)
		{
			int tmp=a[i];
			int j;
			for (j=i;(j>=shell) && (a[j-shell]>tmp); j-=shell)
				a[j]=a[j-shell];
			a[j]=tmp;
		}
	}
	return 0;
}
int main()
{
	int n,arr[10000];
	cin >> n;
	for (int i=0;i<n;i++)
		cin >> arr[i];
	shellSort(arr,n);
	cout << "Array after sorting: \n";
	for (int i=0;i<n;i++)
		cout << arr[i] << " ";
	cout << endl;

	return 0;
}

Add shell sort in cpp

Add shell sort in cpp


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

#include <bits/stdc++.h>

typedef std::pair<double, double> DoublePair;
typedef std::vector<DoublePair> DoublePairs;

// circle
int x, y, r;
// line
int A, B, C;

bool pointOfLine(DoublePair point) {
    double factor = A * point.first + B * point.second + C;
    return std::fabs(factor) < 1e-10;
}

DoublePair moveInDirection(DoublePair start, DoublePair vect, double dist) {
    double factor = dist / std::sqrt(A * A + B * B);
    DoublePair res(
        start.first + vect.first * factor,
        start.second + vect.second * factor
    );
    return res;
}

DoublePair getNearest(double dist) {
    DoublePair center(x, y), normal1(A, B), normal2(-A, -B);
    DoublePair nearest1 = moveInDirection(center, normal1, dist);
    DoublePair nearest2 = moveInDirection(center, normal2, dist);
    if (pointOfLine(nearest1)) {
        return nearest1;
    } else {
        return nearest2;
    }
}

int main() {
    std::cin >> x >> y >> r >> A >> B >> C;
    // distance from the center of the circle to the line
    double dist = std::abs(A * x + B * y + C) / std::sqrt(A * A + B * B);
    DoublePair nearest = getNearest(dist);
    DoublePairs ans;
    if (r > dist) {
        double path = std::sqrt(r * r - dist * dist);
        DoublePair direction1(B, -A);
        DoublePair direction2(-B, A);
        ans.push_back(moveInDirection(nearest, direction1, path));
        ans.push_back(moveInDirection(nearest, direction2, path));
    } else if (std::fabs(r - dist) < 1e-10) {
        // r == dist
        ans.push_back(nearest);
    }
    std::cout << ans.size() << std::endl;
    for (int i = 0; i < ans.size(); i++) {
        std::cout << std::setprecision(8) << std::fixed;
        std::cout << ans[i].first << " " << ans[i].second << std::endl;
    }
    return 0;
}

Add intersection of line and circle

Add intersection of line and circle


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* transfer(ListNode* head, ListNode* tail){
        if(head == tail) return NULL;
        ListNode *fast = head, *slow = head;
        while(fast != tail){
            fast = fast->next;
            if(fast != tail){
                fast = fast->next;
                slow = slow->next;
            }
        }
        TreeNode* root = new TreeNode(slow->val);
        root->left = transfer(head, slow);
        root->right = transfer(slow->next, tail);
        return root;
    }
    TreeNode* sortedListToBST(ListNode* head) {
        return transfer(head, NULL);
    }
};

Convert Sorted List to Binary Search Tree


#include <agency/agency.hpp>
#include <iostream>
#include <mutex>

int main()
{
  using namespace agency;

  std::cout << "Starting predecessor and continuation tasks asynchronously..." << std::endl;

  std::mutex mut;

  // asynchronously create 5 agents to greet us in a predecessor task
  std::future<void> predecessor = bulk_async(par(5), [&](parallel_agent& self)
  {
    mut.lock();
    std::cout << "Hello, world from agent " << self.index() << " in the predecessor task" << std::endl;
    mut.unlock();
  });

  // create a continuation to the predecessor
  std::future<void> continuation = bulk_then(par(5), [&](parallel_agent& self)
  {
    mut.lock();
    std::cout << "Hello, world from agent " << self.index() << " in the continuation" << std::endl;
    mut.unlock();
  },
  predecessor);

  std::cout << "Sleeping before waiting on the continuation..." << std::endl;
  std::this_thread::sleep_for(std::chrono::seconds(1));
  std::cout << "Woke up, waiting for the continuation to complete..." << std::endl;

  // wait for the continuation to complete before continuing
  continuation.wait();

  std::cout << "OK" << std::endl;
  return 0;
}

Add an example program for bulk_then

Add an example program for bulk_then


// Test the DAS class.
// Read attributes from one or more files, printing the resulting table to
// stdout. If a file is named `-' read from stdin for that file. The option
// `-d' causes new/delete run-time debugging to be turned on.
//
// jhrg 7/25/94

// $Log: das-test.cc,v $
// Revision 1.1  1994/08/02 18:08:38  jimg
// Test driver for DAS (and AttrTable) classes.
//

#include <iostream.h>
#include <String.h>
#include <Pix.h>
#include <GetOpt.h>

#include "DAS.h"
#include "Space.h"

int
main(int argc, char *argv[])
{
    GetOpt getopt (argc, argv, "d");
    int option_char;

    // process options first so that debugging in on for object instantitaion.
    while ((option_char = getopt ()) != EOF)
	switch (option_char)
	  {
	    case 'd':
	      space_debug = 1;
	      executable_name = "das-test";
	      break;
	    case '?':
	      fprintf (stderr, "usage: %s [d] filename ...\n", argv[0]);
	  }

    DAS das;

    for (int i = getopt.optind; i < argc; ++i) {
	if (strcmp(argv[i], "-") == 0) {
	    cout << "Enter attributes:\n";
	    das.parse();
	    cout << das;
	}
	else {
	    cout << "Reading from: " << argv[i] << endl;
	    das.parse(argv[i]);
	    cout << das;
	}
    }
}


// http://www.geeksforgeeks.org/bipartite-graph/
#include<iostream>
#include<queue>
#define V 4
using namespace std;

bool isBipartite(int Graph[][V], int src) {
    int color[V];
    for (int i = 0; i < V; i++)
        color[i] = -1;
    color[src] = 1;
    queue<int> q;
    q.push(src);
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        for (int v = 0; v < V; v++) {
            if (Graph[u][v] && color[v] == -1) {
                color[v] = 1 - color[u];
                q.push(v);
            } else if (Graph[u][v] && color[u] == color[v]) return false;
        }
    }
    return true;
}

int main() {
    int Graph[][V] = {{0, 1, 0, 1},
                      {1, 0, 1, 0},
                      {0, 1, 0, 1},
                      {1, 0, 1, 0}};
    isBipartite(Graph, 0) ? cout<<"Yes" : cout<<"No";

    return 0;
}

Implement is bipartite for a given graph

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


/*
Copyright 2015 Rogier van Dalen.

This file is part of Rogier van Dalen's Mathematical tools library for C++.

This library 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 2 of the License, or
(at your option) any later version.

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

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

/** \file
Integration check to see whether using dense symbols in a sequence works.
*/

#define BOOST_TEST_MODULE test_sequence_alphabet
#include "utility/test/boost_unit_test.hpp"

#include "math/sequence.hpp"
#include "math/alphabet.hpp"

#include <string>

BOOST_AUTO_TEST_SUITE (test_suite_sequence_alphabet)

typedef math::alphabet <std::string> alphabet_type;

BOOST_AUTO_TEST_CASE (test_sequence_alphabet) {
    alphabet_type alphabet;

    auto symbol1 = alphabet.add_symbol ("hello");
    auto symbol2 = alphabet.add_symbol ("bye");

    typedef decltype (symbol1) internal_symbol_type;

    math::empty_sequence <internal_symbol_type> empty_sequence;
    math::optional_sequence <internal_symbol_type> sequence1 (symbol1);
    math::single_sequence <internal_symbol_type> sequence2 (symbol2);

    // The first symbol will be chosen because dense symbols are not in
    // lexicographical order.
    BOOST_CHECK (math::choose (sequence1, sequence2) == sequence1);
    BOOST_CHECK (math::plus (sequence1, sequence2) == empty_sequence);

    auto sequence12 = sequence1 * sequence2;
    BOOST_CHECK_EQUAL (range::size (sequence12.symbols()), 2);
    BOOST_CHECK (range::first (sequence12.symbols()) == symbol1);
    BOOST_CHECK (range::second (sequence12.symbols()) == symbol2);
}

BOOST_AUTO_TEST_SUITE_END()

Test integration of sequence and alphabet

Ignore-this: d19eba6f3b80112fef83eb68eb3eae6d

darcs-hash:20150123164458-fa073-9c85fae8c0d94177f4a4858c283d28f0021045c5


// Write a program to find the increasing array with the largest sum of array.

#include <stdio.h>

const int MIN = -2147483647;

void importArray(int array[], int &length);
void exportArray(int array[], int length);
void exportArray(int array[], int length, int from, int to);
void handleRequirement(int array[], int length, int &from, int &to);

int main() {
	int array[100], length, from, to;

	importArray(array, length);
	exportArray(array, length);
	handleRequirement(array, length, from, to);
	exportArray(array, length, from, to);

	return 0;
}

void handleRequirement(int array[], int length, int &from, int &to) {
	int result, max, index, pointer;

	result = MIN;

	for (index = 0; index < length - 1; index++) {

		max = array[index];

		for (pointer = index + 1; pointer < length; pointer++) {
			if (array[pointer] >= array[pointer - 1]) {
				to = pointer;
				max += array[pointer];
			} else {
				break;
			}
		}

		if (result <= max) {
			from = index;
			to = pointer - 1;
			result = max;
		}
	}
}

void importArray(int array[], int &length) {
	int index;

	do
	{
		printf("N: ");
		scanf("%d", &length);
	} while (length < 0);

	printf("Import array: ");

	for (index = 0; index < length; index++) {
		scanf("%d", &array[index]);
	}
}

void exportArray(int array[], int length) {
	int index;

	printf("Export array: ");

	for (index = 0; index < length; index++) {
		printf("%d ", array[index]);
	}
	printf("\n");
}

void exportArray(int array[], int length, int from, int to) {
	int index;

	printf("Export array: ");

	for (index = from; index <= to; index++) {
		printf("%d ", array[index]);
	}
	printf("\n");
}

Add problem: Write a program to find the increasing array with the largest sum of array.


#include <csetjmp>
#include <unistd.h>

#if defined(__APPLE__)
#include <OpenGL/gl.h>
#else
#include <GL/gl.h>
#endif

#include "Halide.h"
#include "HalideRuntimeOpenGL.h"

std::string error_message;

/*
** Don't rely on func.set_error_handler() mechanism, it doesn't seem to catch
** the user OpenGL state errors. That might be a separate bug.
*/
jmp_buf env;
void on_sigabrt (int signum)
{
  longjmp (env, 1);
}
void catching_stderr_abort(std::function<void ()> func)
{
    auto ferr = tmpfile();
    auto prev_stderr = dup(2);
    dup2(fileno(ferr), 2);
    if (setjmp (env) == 0) {
        auto prev_handler = signal(SIGABRT, &on_sigabrt);
        (func)();
        signal(SIGABRT, prev_handler);
    }
    fseek(ferr, 0, SEEK_END);
    error_message.resize(ftell(ferr));
    rewind(ferr);
    fread(&error_message[0], 1, error_message.size(), ferr);
    dup2(prev_stderr, 2);
    close(prev_stderr);
}

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

    Image<uint8_t> output(255, 10, 3);

    Var x, y, c;
    Func g;
    g(x, y, c) = Halide::cast<uint8_t>(255);
    g.bound(c, 0, 3);
    g.glsl(x, y, c);

    // Let Halide initialize OpenGL
    g.realize(output);

    // Bad OpenGL call leaves OpenGL in a bad state
    glEnableVertexAttribArray(-1);

    // Halide should report that the OpenGL context is in a bad state due to user code`
    catching_stderr_abort( [&] () { g.realize(output); } );

    if (error_message.empty()) {
        fprintf(stderr, "Failed to report error in user OpenGL state\n");
        return 1;
    }
    else if (error_message.find("user OpenGL state") == std::string::npos) {
        error_message.erase(error_message.size() - 1); // remove trailing newline
        fprintf(stderr, "Reported error '%s' rather than identifying error at 'user OpenGL state'\n", error_message.c_str());
        return 1;
    }

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

Add (failing) test that halide reports user error when called with OpenGL in bad state


#include <iostream>
#include <new>
#include <cstdlib>

using namespace std;

void* operator new (size_t size) {
    cout << "operator new(" << size << ")" << endl;
    if(void *mem = malloc(size)) {
        return mem;
    } else {
        throw bad_alloc();
    }
}

void operator delete(void *mem) noexcept {
    cout << "operator delete(" << mem << ")" << endl;
    free(mem);
}

class Test {
private:
    int i;
    long l;
};

int main() {
    int *pi = new int(1);
    delete pi;
    long *pl = new long(10);
    delete pl;
    Test *pt = new Test();
    delete pt;
    return 0;
}

Add solution for chapter 19, test 1

Add solution for chapter 19, test 1


#include <iostream>
#include <vector>
#include <list>

template <template<class,class> class Container, class Object>
class UDTContainer{
	private:
		Container<Object,std::allocator<Object> > m_cointainer;
	public:

};

int main(){

	UDTContainer<std::vector,std::string> obj_udtc;
}

Update gitignore and added a test class that accepts STL class as a template template argument


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

int count_one_came_out_when_throwing_dice(const int count)
{
    int rc = 0;

    for(int i = 0; i < count; ++i)
        if(rand() % 6 + 1 == 1) ++rc;

    return rc;
}

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

    const int max = 10000;

    int six = 0, twelve = 0;
    for(int i = 0; i < max; ++i)
    {
        six += (count_one_came_out_when_throwing_dice(6) >= 1);
        twelve += (count_one_came_out_when_throwing_dice(12) >= 2);
    }

    printf("Result: %s\n", (six == twelve) ? "SAME" : (six < twelve) ? "SIX" : "TWELVE");

    return 0;
}

Add solution of prob 5

Add solution of prob 5


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

// CHECK: store i32 49, i32* %size
// CHECK: store i32 52, i32* %size
template<typename T>
class TemplateClass {
public:
  void templateClassFunction() {
    int size = sizeof(__PRETTY_FUNCTION__);
  }
};

// CHECK: store i32 27, i32* %size
// CHECK: store i32 30, i32* %size
template<typename T>
void functionTemplate(T t) {
  int size = sizeof(__PRETTY_FUNCTION__);
}

int main() {
  TemplateClass<int> t1;
  t1.templateClassFunction();
  TemplateClass<double> t2;
  t2.templateClassFunction();

  functionTemplate<int>(0);
  functionTemplate(0.0);

  return 0;
}

Add test for dependent PredefinedExprs.

Add test for dependent PredefinedExprs.

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


/*
 * Copyright 2010, NagaChaitanya Vellanki
 *
 * Author NagaChaitanya Vellanki
 *
 * Swapping two variables without auxillary
 */

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

using namespace std;

int main()
{
  int32_t a = 10;
  int32_t b = 20;
  cout << "a is " << a << ",b is " << b << endl;
  a = a + b;
  b = a - b;
  a = a - b;
  cout << "After Swapping " << endl;
  cout << "a is " << a << ",b is " << b << endl;
  return 0;
}

Add Swapping without a auxillary variable


#include "EM_Classes.h"

Model::Model(const int &N_, const int &lagsS_, const int &lagsY_,
			 const bool &sigma_, const bool &beta_,
			 const bool &meanCorrected):
	N(N_), lagsS(lagsS_), lagsY(lagsY_), sigma(sigma_), beta(beta_),
	meanCorrected(meanCorrected){}

Model::Model(const int &N_ = 2, const int &lagsS_= 0,
			 const int &lagsY_= 0, const bool &sigma_ = TRUE,
			 const bool &beta_ = TRUE, const bool &meanCorrected):
	N(N_), lagsS(lagsS_), lagsY(lagsY_), sigma(sigma_), beta(beta_),
	meanCorrected(meanCorrected){}

Data::Data(const MatrixXd & y,const MatrixXd & x):
	Y(y){
	MatrixXd c;
	if (y.rows() > y.cols())
		Y.transposeInPlace();
	if (x.rows() > x.cols())
		x.transposeInPlace();
	T = y.rows();
	M = y.cols(); // if M = 1, Univariate model
	// T can't be different from x.rows()
	Mx = x.cols();
	X << c.setOnes(T, 0) << x;
}

Data::Data(const MatrixXd & y):
	Y(y){
	if(y.cols > y.rows)
		y.transposeInPlace()
	T = y.rows();
	M = y.cols();
	x.setOnes(T, 0);
	mX = x.cols();
}

Create constructors for classes Data and Model


/**
 * Delete Node in a Linked List
 *
 * cpselvis(cpselvis@gmail.com)
 * Oct 8th, 2016
 */

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

class Solution {
public:
  void deleteNode(ListNode* node) {
    if (node != NULL)
      {
	node -> val = node -> next -> val;
	node -> next = node -> next -> next;
      }
  }
};

Delete Node in a Linked List.

Delete Node in a Linked List.


#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 toSumTree(NODE* root) {
  if (root == nullptr) return 0;

  int old_value = root->data;
  printf("old_value : [%d] \n", old_value);

  root->data = toSumTree(root->left) + toSumTree(root->right);

  printf("root->data : [%d] \n", root->data);
  return root->data + old_value;
}

void printInorder(NODE* node) {
  if (node) {
    printInorder(node->left);
    printf("%d ", node->data);
    printInorder(node->right);
  }
}

#if 0
                  10
               /      \
              -2        6
           /   \      /  \
         8     -4    7    5
#endif
int main(int argc, char const* argv[]) {
  NODE* root = newNode(10);
  root->left = newNode(-2);
  root->right = newNode(6);
  root->left->left = newNode(8);
  root->left->right = newNode(-4);
  root->right->left = newNode(7);
  root->right->right = newNode(5);

  toSumTree(root);

  // Print inorder traversal of the converted tree to test result of toSumTree()
  printf("Inorder Traversal of the resultant tree is: \n");
  printInorder(root);
  return 0;
}

Convert the given tree for sum property.


// 155. Min Stack
/**
 * Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
 *
 * push(x) -- Push element x onto stack.
 * pop() -- Removes the element on top of the stack.
 * top() -- Get the top element.
 * getMin() -- Retrieve the minimum element in the stack.
 *
 * Example:
 *
 * MinStack minStack = new MinStack();
 * minStack.push(-2);
 * minStack.push(0);
 * minStack.push(-3);
 * minStack.getMin();   --> Returns -3.
 * minStack.pop();
 * minStack.top();      --> Returns 0.
 * minStack.getMin();   --> Returns -2.
 *
 * Tags: Stack Design
 *
 * Similar Problems: (H) Sliding Window Maximum
 *
 * Author: Kuang Qin
 */

using namespace std;

#include <stack>
#include <iostream>

class MinStack {
private:
    stack<int> s1;    // s1 as the original stack
    stack<int> s2;    // s2 always keeps the current minimun element on the top

public:
    /** initialize your data structure here. */
    MinStack() {

    }

    void push(int x) {
        s1.push(x);
        if (s2.empty() || x <= getMin())
            s2.push(x);     // keep the top element of s2 the minimum
    }

    void pop() {
        if (s1.top() == getMin())
            s2.pop();
        s1.pop();
    }

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

    int getMin() {
        return s2.top();
    }
};

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(x);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */

int main()
{
    MinStack obj;
    obj.push(0);
    obj.push(1);
    obj.push(0);
    int param_1 = obj.getMin();
    obj.pop();
    int param_2 = obj.top();
    int param_3 = obj.getMin();

    cout << param_1 << " " << param_2 << " " << param_3 << endl;
    system("pause");

    return 0;
}

Add Solution for 155 Min Stack

Add Solution for 155 Min Stack


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

typedef struct node
{
	int num;
	string str;
}c_node;

int main()
{
	int n;
	cin >> n;
	c_node *a = new c_node[n];
	for (int i = 0; i < n; i++) {
		cin >> a[i].num >> a[i].str;
	}
	map< int, list<string> > int_list_map;
	for (int i = 0; i < n; i++) {
		if (i < n / 2) {
			a[i].str = "-";
		}
		map< int, list<string> >::iterator iter = int_list_map.find(a[i].num);
		if (iter == int_list_map.end()) {
			list<string> str_list;
			str_list.push_back(a[i].str);
			int_list_map.insert(pair< int, list<string> > (a[i].num, str_list));
		}
		else {
			iter->second.push_back(a[i].str);
		}
	}
	for (map< int, list<string> >::iterator i = int_list_map.begin(); i != int_list_map.end(); i++) {
		while (!i->second.empty()) {
			cout << i->second.front() << " ";
			i->second.pop_front();
		}
	}
	delete [] a;
	return 0;
}

Add the solution to "The Full Counting Sort".


// RUN: %clang_cc1 -fsyntax-only -std=c++11 2>&1 %s | FileCheck -strict-whitespace %s

struct A {
  unsigned int a;
};

// PR10696
void testOverlappingInsertions(int b) {
  A var = { b };
  // CHECK:  A var = { b };
  // CHECK:            ^
  // CHECK:            static_cast<unsigned int>( )
}

Add a test for r158229 (overlapping fixits). This was PR10696!

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


// 035. Search Insert Position
/**
 * Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
 *
 * You may assume no duplicates in the array.
 *
 * Here are few examples.
 * [1,3,5,6], 5 -> 2
 * [1,3,5,6], 2 -> 1
 * [1,3,5,6], 7 -> 4
 * [1,3,5,6], 0 -> 0
 *
 * Tags: Array, Binary Search
 *
 * Similar Problems: (E) First Bad Version
 *
 * Author: Kuang Qin
 */

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

using namespace std;

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int n = nums.size();
        if (n == 0)
        {
            return 0;
        }

        int left = 0, right = n - 1;
        while (left <= right)
        {
            int mid = (left + right) / 2;
            if (target == nums[mid])
            {
                return mid;
            }
            else if (target > nums[mid])
            {
                left = mid + 1;
            }
            else // target < nums[mid]
            {
                right = mid - 1;
            }
        }

        return left;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    vector<int> nums;
    nums.push_back(1);
    nums.push_back(3);
    nums.push_back(5);
    nums.push_back(6);
    int target = 0;

    Solution mySolution;
    int res = mySolution.searchInsert(nums, target);
    cout << res << endl;
    system("pause");
    return 0;
}

Add Solution for Problem 035

Add Solution for Problem 035


//
// Test Suite for geos::operation::OverlayOp class for UNION

#include <tut.hpp>
// geos
#include <geos/operation/overlay/OverlayOp.h>
#include <geos/geom/Geometry.h>
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/PrecisionModel.h>
#include <geos/io/WKBReader.h>
#include <geos/io/WKTReader.h>
// std
#include <string>
#include <memory>

using namespace geos::geom;
using namespace geos::operation;

namespace tut
{
    //
    // Test Group
    //

    struct test_overlayopunion_data
    {
        typedef geos::geom::Geometry::AutoPtr GeometryPtr;
        typedef geos::geom::GeometryFactory GeometryFactory;
        typedef geos::geom::GeometryFactory::unique_ptr GeometryFactoryPtr;
    };

    typedef test_group<test_overlayopunion_data> group;
    typedef group::object object;

    group test_issimpleop_group("geos::operation::OverlayOp::UNION");

    //
    // Test Cases
    //

    // 1 - Union four segments of a square
    template<>
    template<>
    void object::test<1>()
    {
        // Arrange
        geos::geom::PrecisionModel pm(1e+13);
        GeometryFactoryPtr factory = geos::geom::GeometryFactory::create(&pm);
        geos::io::WKTReader reader(*factory);
        GeometryPtr line1(reader.read("LINESTRING(0 0, 0 5)"));
        GeometryPtr line2(reader.read("LINESTRING(0 5, 5 5)"));
        GeometryPtr line3(reader.read("LINESTRING(5 5, 5 0)"));
        GeometryPtr line4(reader.read("LINESTRING(5 0, 0 0)"));

        // Act: union segments incrementally
        GeometryPtr lines12(line1->Union(line2.get()));
        GeometryPtr lines123(lines12->Union(line3.get()));
        GeometryPtr lines1234(lines123->Union(line4.get()));

        // Assert
        ensure_equals(lines1234->getGeometryTypeId(), geos::geom::GEOS_MULTILINESTRING);
    }

} // namespace tut

Add basic test for geos::operation::OverlayOp with UNION.

Test union of four segments (linestrings) of a suqare.

git-svn-id: 6c2b1bd10c324c49ea9d9e6e31006a80e70507cb@4153 5242fede-7e19-0410-aef8-94bd7d2200fb


#include <stdio.h>
#include <map>
#include <vector>

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

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

  return node;
}

void PrintTopViewUtil(NODE* node, int level, std::map<int, int>& map) {
  if (node) {
    PrintTopViewUtil(node->left, level - 1, map);
    PrintTopViewUtil(node->right, level + 1, map);
    map[level] = node->data;
  }
}

void PrintTopView(NODE* node) {
  std::map<int, int> map;

  PrintTopViewUtil(node, 0, map);

  std::map<int, int>::iterator it;

  for (it = map.begin(); it != map.end(); it++) {
    printf("%d ", it->second);
  }
}

int main(int argc, char** argv) {
  NODE* root = NewNode(1);
  root->left = NewNode(2);
  root->right = NewNode(3);
  root->left->right = NewNode(4);
  root->left->right->right = NewNode(5);
  root->left->right->right->right = NewNode(6);

  PrintTopView(root);

  return 0;
}

Print top view of the binary tree.

Print top view of the binary tree.


// Description: Print slur linking info

#include "humlib.h"

using namespace hum;

int main(int argc, char** argv) {
   if (argc != 2) {
      return 1;
   }
   HumdrumFile infile;
   if (!infile.read(argv[1])) {
      return 1;
   }
cerr << "ANALYZING SLURS" << endl;
   infile.analyzeKernSlurs();
cerr << "DONE ANALYZING SLURS" << endl;
   return 0;
}

Add test program for slur parsing.

Add test program for slur parsing.


#include <iostream>
#include <string>

using namespace std;

int main()
{
  string time12;

  cin >> time12;

  char p = time12[time12.size() - 2];
  if (p == 'P')
  {
    int t = (int)time12[0] - '0';
    t = t * 10;
    t += (int)time12[1] - '0';
    if (t < 12)
    {
      t += 12;
    }
    cout << t;
    for (int i = 2; i < time12.size() - 2; i++)
    {
      cout << time12[i];
    }
    cout << endl;
  }
  else
  {
    int t = (int)time12[0] - '0';
    t = t * 10;
    t += (int)time12[1] - '0';
    if (t == 12)
    {
      t = 0;
    }

    if (t < 10) cout << 0;
    cout << t;
    for (int i = 2; i < time12.size() - 2; i++)
    {
      cout << time12[i];
    }
    cout << endl;
  }

  return 0;
}

Add a solution for time converter task

Add a solution for time converter task


#include <iostream>

int main() {
  std::cout << "Hello, World!" << std::endl;
  return 0;
}

#include <iostream>
#include <stdlib.h>

#include "exampleConfig.h"
#include "example.h"

/*
 * Simple main program that demontrates how access
 * CMake definitions (here the version number) from source code.
 */
int main() {
  std::cout << "C++ Boiler Plate v"
            << PROJECT_VERSION_MAJOR
            << "."
            << PROJECT_VERSION_MINOR
            << std::endl;
  std::system("cat ../LICENCE");

  // Bring in the dummy class from the example source,
  // just to show that it is accessible from main.cpp.
  Dummy d = Dummy();
  return d.doSomething() ? 0 : -1;
}

Update example to demonstrate version numbers.


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "../excercise04/make_random_data/make_random_data.hpp"
#include "../excercise04/sort/heap.hpp"
#include "../excercise04/sort/swap.hpp"
#include "priority_queue/priority_queue.hpp"

#define MIN_SIZE    100
#define MAX_SIZE    100000
#define SIZE_STEP   10

#define M   100

int main(void)
{
    srand(time(NULL));
    int *original = make_random_data(MAX_SIZE);

    for(int size_of_data = MIN_SIZE; size_of_data <= MAX_SIZE; size_of_data *= SIZE_STEP)
    {
        printf("SIZE OF DATA: %d\n", size_of_data);

        {
            const int capacity = size_of_data * 3;

            int data[capacity];
            memcpy(data, original, sizeof(int) * size_of_data);

            convert_to_binary_max_heap(data, size_of_data);

            clock_t before = clock();

            int count = size_of_data;
            for(int i = 0; i < M; ++i)
            {
                if(rand() % 2 == 0)
                    push_priority_queue(data, capacity, count, original[count]);
                else
                    pop_priority_queue(data, count);
            }

            clock_t after = clock();

            printf("Using heap:\t\t%lf\n", (double)(after - before)/CLOCKS_PER_SEC);
        }
        {
            int data[size_of_data];
            memcpy(data, original, sizeof(int) * size_of_data);

            clock_t before = clock();

            int count = size_of_data;
            for(int i = 0; i < M; ++i)
            {
                int max = data[0];
                if(rand() % 2 == 0) /* Push */
                {
                    data[count] = original[count++];
                }
                else /* Pop */
                {
                    for(int i = 0; i < count; ++i)
                        if(data[i] > max)
                        {
                            max = data[i];
                            swap(data[i], data[count--]);
                        }
                }
            }

            clock_t after = clock();

            printf("Not using heap:\t\t%lf\n", (double)(after - before)/CLOCKS_PER_SEC);
        }

        putchar('\n');
    }

    free_random_data(original);

    return 0;
}

Add a solution of prob 2

Add a solution of prob 2


/*
 * Lattice paths
 *
 * Starting in the top left corner of a 2×2 grid, and only being able to move
 * to the right and down, there are exactly 6 routes to the bottom right corner.
 *
 * How many such routes are there through a 20×20 grid?
 */

#include <iostream>

using Long = unsigned long long int;

// Forward declaration
constexpr Long binomial(unsigned n, unsigned k);

constexpr unsigned cols = 20;
constexpr unsigned rows = 20;

int main(int, char **) {
    // The number of paths through an n×m lattice is binomial(n+m, n).
    auto paths = binomial(rows + cols, rows);

    std::cout << "Project Euler - Problem 15: Lattice paths\n\n";
    std::cout << "The number of paths through a " << rows << u8"×" << cols
              << " lattice is\n"
              << paths << '\n';
}

/**
 * Compute the binomial coefficient n over k.
 *
 * @param n Parameter n.
 * @param k Parameter k.
 * @return The binomial coefficient, or 0 if k > n.
 */
constexpr Long binomial(unsigned n, unsigned k) {
    if(k > n) {
        return 0;
    }
    if(k > (n + 1) / 2) {
        return binomial(n, n - k);
    }
    Long result = 1;
    for(unsigned j = 1; j <= k; j++) {
        result = result * (n + 1 - j) / j;
    }
    return result;
}

Add solution to problem 15 in C++.

Add solution to problem 15 in C++.


#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
	int n, money;
	cin >> n >> money;
	int *toys = new int[n];
	for (int i = 0; i < n ; i++) {
		cin >> toys[i];
	}
	sort(toys, toys + n);
	int sum = 0;
	int count = 0;
	for (int i = 0; i < n; i++) {
		if (sum + toys[i] > money) {
			break;
		}
		else {
			sum += toys[i];
			count++;
		}
	}
	cout << count;
	delete [] toys;
	return 0;
}

Add the solution to "Mark and Toys".

Add the solution to "Mark and Toys".


// Copyright [2016] <Malinovsky Rodion>

#include "core/engine.h"
#include "gtest/gtest.h"

// Implement Engine test
// 1. Create a fixture, take base code from EngineLauncher
// 2. create cond var, which will emulate  SIGINT
// 3. run engine -> create server socket
// 4. create tcp client and write data to server socket
// 5. verify output of the echo server.

#error missing-implementation

Add stub for engine test with test plan

Add stub for engine test with test plan


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

    // Function mixes type, the float16_t should be implicitly upcast
    // to a float
    f(x, y) = 0.25f + float16_t(0.75);

    // Use JIT for computation
    Image<float> 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");

    // Read result back
    for (int x = simple.min(0); x < simple.extent(0); ++x) {
        for (int y = simple.min(1); y < simple.extent(1); ++y) {
            h_assert(simple(x, y) == 1.0f, "Invalid value read back");
        }
    }
    printf("Success!\n");
    return 0;
}

Add test to check implicit upcasting of float16_t works.


#include <UnitTest++.h>

// Unit tests for vec classes

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

TEST(CreateNode)
{
   OSG::NodePtr n = OSG::Node::create();
   CHECK(n != OSG::NullFC);
}

// --- Cloning --- //
TEST(TreeCloningName)
{
   OSG::NodePtr root = OSG::Node::create();
   OSG::NodePtr child_node = OSG::Node::create();
   root->addChild(child_node);
   OSG::setName(root, "root");
   OSG::setName(child_node, "child_node");

   OSG::NodePtr new_root = OSG::cloneTree(root);

   CHECK(new_root->getNChildren() == 1);
   CHECK(new_root != root);
   CHECK(new_root->getChild(0) != child_node);

   std::string new_name = OSG::getName(new_root);
   CHECK(new_name == "root");
}

Add node test.  Fails for now.  Need to figure out a way to handle osgInit.

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


#include "classad/classad_distribution.h"

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

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

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

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

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

	return 0;
}

Add fuzzing driver to classads HTCONDOR-814


// 145 Binary Tree PostOrder Tranversal
/**
* Given a binary tree, return the postorder traversal of its nodes' values.
*
* For example:
* Given binary tree {1,#,2,3},
*    1
*     \
*      2
*     /
*    3
* return [3,2,1].
*
* Note: Recursive solution is trivial, could you do it iteratively?
*
* Tag:    Tree, Stack
*
* Author: Yanbin Lu
*/

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

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> postorderTraversal(TreeNode* root) {
        vector<int> res;
        if(!root) return res;

        stack<TreeNode*> s;
        s.push(root);
        TreeNode* pre = NULL;
        TreeNode* cur;
        while (!s.empty()) {
            cur = s.top();

            // !pre coresponds to the root case, otherwise going down
            if(!pre || pre->left == cur || pre->right == cur){
                if(cur->left)               // to left child if exist
                    s.push(cur->left);      // t right child if left child doesnt exist
                else if(cur->right)
                    s.push(cur->right);
                else{                       // this is the leaf
                    s.pop();
                    res.push_back(cur->val);
                }
            }

            // going up from the left child
            else if(cur->left == pre){
                if(cur->right)
                    s.push(cur->right);      // to the right child if exist
                else{
                    s.pop();
                    res.push_back(cur->val);
                }
            }

            // going up from the right side, done from this point dowm
            else if(cur->right == pre){
                s.pop();
                res.push_back(cur->val);
            }

            pre = cur;
        }

        return res;
    }
};

int main()
{

    TreeNode* root = new TreeNode(2);
    root->left = new TreeNode(3);
    root->right = new TreeNode(4);
    root->left->right = new TreeNode(5);
    Solution* sol = new Solution();
    vector<int> res = sol->postorderTraversal(root);
    for(int i = 0; i < res.size(); i++)
        cout << res[i] << endl;

    char c;
    std::cin>>c;

    return 0;
}

Add 145 Binary Tree Postorder Traversal

Add 145 Binary Tree Postorder Traversal


Check if sum exists in two arrays

Check if sum exists in two arrays


#include "path.hpp"

void Path::init()
{
    // FIXME: unimplemented
}

#include <stdlib.h>

IFile *Path::openIFile(std::string const &path)
{
    // FIXME: unimplemented
    abort();
    return NULL;
}

Add placeholder Windows path code

Add placeholder Windows path code


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

void f() {
  void *p = malloc(sizeof(int) * 10); // expected-error{{no matching function for call to 'malloc'}}
}

int malloc(double);

Add test case to insure that implicit builtin declarations for C library functions aren't created in C++

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


#include <cmath>
#include <fmt/format.h>

struct ieee754 {
	int sign;
	int biased_exponent;
	uint64_t fraction;

	uint64_t significand() const { return 0x10'0000'0000'0000 | fraction; }
	int exponent() const { return biased_exponent - 1023; }

	explicit ieee754(double value) {
		auto bits = fmt::internal::bit_cast<uint64_t>(value);
		sign = bits >> 63;
		biased_exponent = static_cast<int>(bits >> 52) & 0x7ff;
		fraction = bits & 0xf'ffff'ffff'ffff;
	}
};

template <>
struct fmt::formatter<ieee754> {
	auto parse(format_parse_context& ctx) { return ctx.begin(); }

	auto format(ieee754 n, format_context& ctx) {
		return format_to(ctx.out(), "{} {:011b} {:052b} [e = {}]", n.sign, n.biased_exponent, n.fraction, n.exponent());
	}
};

int main(int argc, char* argv[]) {
	fmt::print("{}\n", ieee754(M_PI));
	return 0;
}

ADD floating point format library example.

Compile with: g++ float_fmt.cpp -o float_fmt -lfmt


// Copyright (c) 2017 Pierre Fourgeaud
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include <bandit/bandit.h>
#include "core/math/utils.h"

using namespace bandit;
using namespace snowhouse;
using namespace CodeHero;

go_bandit([]() {
    describe("::Clamp", []() {
        it("should not do anything if in the range", [] {
            AssertThat(Clamp(5.0f, 0.0f, 10.0f), Equals(5.0f));
            AssertThat(Clamp(5, 0, 10), Equals(5));
        });

        it("should Clamp the value back in the range is value is smaller than min", [] {
            AssertThat(Clamp(-5.0f, 0.0f, 10.0f), Equals(0.0f));
            AssertThat(Clamp(-5, 0, 10), Equals(0));
        });

        it("should Clamp the value back in the range is value is bigger than max", [] {
            AssertThat(Clamp(15.0f, 0.0f, 10.0f), Equals(10.0f));
            AssertThat(Clamp(15, 0, 10), Equals(10));
        });
    });
});

Add test for Clamp function in math/utils


/* Copyright 2021 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 {

// Filesystem Ops ----------------------------------------------------------

REGISTER_OP("FileSystemSetConfiguration")
    .Input("scheme: string")
    .Input("key: string")
    .Input("value: string")
    .SetIsStateful()
    .SetShapeFn(shape_inference::ScalarShape);

}  // namespace tensorflow

/* Copyright 2021 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 {

// Filesystem Ops ----------------------------------------------------------

REGISTER_OP("FileSystemSetConfiguration")
    .Input("scheme: string")
    .Input("key: string")
    .Input("value: string")
    .SetIsStateful()
    .SetShapeFn(shape_inference::NoOutputs);

}  // namespace tensorflow

Set NoOutputs as the shape inference function for the FileSystemSetConfiguration op.

PiperOrigin-RevId: 416909316
Change-Id: I1dea750ba447776ab4b927273b3559baa98dbca1