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

#include <exception>
#include <stdlib.h>
#include <assert.h>

struct A {};

// Despite being marked as noexcept, this function must have an EHT entry that
// is not 'cantunwind', so that the unwinder can correctly deal with the throw.
void f1() noexcept
{
    try {
        A a;
        throw a;
        assert(false);
    } catch (...) {
        assert(true);
        return;
    }
    assert(false);
}

int main()
{
    f1();
}

Add EH test case checking that handlers in noexcept functions can still unwind

git-svn-id: 6a9f6578bdee8d959f0ed58970538b4ab6004734@209944 91177308-0d34-0410-b5e6-96231b3b80d8


// RUN: %clang_cc1 -emit-llvm %s -o - -triple=x86_64-pc-linux-gnu | FileCheck %s

extern int aa __attribute__((section(".sdata")));
// CHECK-DAG: @aa = external global i32, section ".sdata", align 4

extern int bb __attribute__((section(".sdata"))) = 1;
// CHECK-DAG: @bb = global i32 1, section ".sdata", align 4

int foo() {
  return aa + bb;
}

Add test forgotten in r314262.

Add test forgotten in r314262.

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


#include <iostream>
using namespace std;

long long solve(int n)
{
    long long *res = new long long[n + 1];
    switch (n) {
    case 1: return 1;
    case 2: return 2;
    case 3: return 3;
    case 4: return 6;
    }
    res[1] = 1;
    res[2] = 2;
    res[3] = 3;
    res[4] = 6;
    for (int i = 5; i <= n; i++) {
        res[i] = res[i - 1] + res[i - 2] + res[i - 4];
    }
    long long x = res[n];
    delete [] res;
    return x;
}

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

Add the solution to "Cached Calculations".


/*

    Copyright Eli Dupree and Isaac Dupree, 2011, 2012

    This file is part of Lasercake.

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

    Lasercake 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 Lasercake.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "../utils.hpp"
#include <limits>
#include <array>

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

namespace /* anonymous */ {

void i64sqrt_test(uint64_t radicand) {
  uint64_t sqrt_result = i64sqrt(radicand); //implicit cast the result to 64 bits so we can square it
  BOOST_CHECK(sqrt_result * sqrt_result <= radicand);
  if(sqrt_result != std::numeric_limits<uint32_t>::max()) {
    BOOST_CHECK((sqrt_result+1) * (sqrt_result+1) > radicand);
  }
}

BOOST_AUTO_TEST_CASE( my_sqrt ) {
  std::array<uint64_t, 19> numbers_to_test = {{ 0, 1, 2, 3, 4, 5, 17, 232, 500,
    78978978, 8948954789789349789ull, 0xfffffffful, 0x100000000ull,
    0x100000001ull, 0xffffffffffffffffull, 0xfffffffffffffffeull,
    0xeeeeeeeeeeeeeeeeull, 0xfffffffe00000001ull, 0xfffffffe00000000ull
  }};
  BOOST_PARAM_TEST_CASE(i64sqrt_test, numbers_to_test.begin(), numbers_to_test.end());
}

}  /* end anonymous namespace */

Add a test for i64sqrt

Add a test for i64sqrt


#include <gtest/gtest.h>

#include "photoeffects.hpp"

using namespace cv;

TEST(photoeffects, GlowTest) {
    Mat image(10, 10, CV_8UC1);

    EXPECT_EQ(10, glow(image));
}

Add tests for glow implementation

Add tests for glow implementation


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

#include "chrome/browser/net/async_dns_field_trial.h"

#include "base/metrics/field_trial.h"
#include "build/build_config.h"
#include "chrome/common/chrome_version_info.h"

namespace chrome_browser_net {

bool ConfigureAsyncDnsFieldTrial() {
#if defined(OS_ANDROID) || defined(OS_IOS) || defined(OS_CHROMEOS)
  // There is no DnsConfigService on those platforms so disable the field trial.
  return false;
#endif
  const base::FieldTrial::Probability kAsyncDnsDivisor = 100;
  base::FieldTrial::Probability enabled_probability = 0;

  // TODO(szym): expand to DEV channel after fixing http://crbug.com/121085
  if (chrome::VersionInfo::GetChannel() <= chrome::VersionInfo::CHANNEL_CANARY)
    enabled_probability = 50;

  scoped_refptr<base::FieldTrial> trial(
      base::FieldTrialList::FactoryGetFieldTrial(
          "AsyncDns", kAsyncDnsDivisor, "disabled", 2012, 9, 30, NULL));

  int enabled_group = trial->AppendGroup("enabled", enabled_probability);
  return trial->group() == enabled_group;
}

}  // namespace chrome_browser_net

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

#include "chrome/browser/net/async_dns_field_trial.h"

#include "base/metrics/field_trial.h"
#include "build/build_config.h"
#include "chrome/common/chrome_version_info.h"

namespace chrome_browser_net {

bool ConfigureAsyncDnsFieldTrial() {
#if defined(OS_ANDROID) || defined(OS_IOS) || defined(OS_CHROMEOS)
  // There is no DnsConfigService on those platforms so disable the field trial.
  return false;
#endif
  const base::FieldTrial::Probability kAsyncDnsDivisor = 100;
  base::FieldTrial::Probability enabled_probability = 0;

  // TODO(szym): expand to DEV channel after fixing http://crbug.com/121085
  if (chrome::VersionInfo::GetChannel() <= chrome::VersionInfo::CHANNEL_CANARY)
    enabled_probability = 0;

  scoped_refptr<base::FieldTrial> trial(
      base::FieldTrialList::FactoryGetFieldTrial(
          "AsyncDns", kAsyncDnsDivisor, "disabled", 2012, 9, 30, NULL));

  int enabled_group = trial->AppendGroup("enabled", enabled_probability);
  return trial->group() == enabled_group;
}

}  // namespace chrome_browser_net

Disable Async DNS field trial

[net] Disable Async DNS field trial

Disabling due to http://crbug.com/121085

NOTRY=true
BUG=143454

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

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


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

class Trivial { int n; void f(); };
class NonTrivial1 { NonTrivial1(const NonTrivial1 &); };
class NonTrivial2 { NonTrivial2(NonTrivial2 &&); };
class NonTrivial3 { NonTrivial3 operator=(const NonTrivial3 &); };
class NonTrivial4 { NonTrivial4 operator=(NonTrivial4 &&); };
class NonTrivial5 { ~NonTrivial5(); };

static_assert(__is_trivial(Trivial), "Trivial is not trivial");
static_assert(!__is_trivial(NonTrivial1), "NonTrivial1 is trivial");
static_assert(!__is_trivial(NonTrivial2), "NonTrivial2 is trivial");
static_assert(!__is_trivial(NonTrivial3), "NonTrivial3 is trivial");
static_assert(!__is_trivial(NonTrivial4), "NonTrivial4 is trivial");
static_assert(!__is_trivial(NonTrivial5), "NonTrivial5 is trivial");

Test for C++11 [class]p6 (trivial classes).

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


#include "LanguageEasy.h"

//Windows
WindowMessage::WindowMessage()
{
	MessageName = "";
	Message = "";
}

WindowMessage::WindowMessage(string NewMessageName, string NewMessage)
{
	MessageName = NewMessageName;
	Message = NewMessage;
}

void WindowMessage::OutputWindow()
{
	char MessageBuffer[9999];
	char MessageNameBuffer[9999];
	sprintf_s(MessageBuffer, Message.c_str());
	sprintf_s(MessageNameBuffer, MessageName.c_str());
	MessageBoxA(NULL, MessageBuffer, MessageNameBuffer, MB_OK);
}

Add Window Message Class (Continued)

Add Window Message Class (Continued)

This will be used in Windows to output a message box using a object.


#include "logic.h"

#define ARBITRARY_SIZE 20

block* blockAlloc( void );
void blockFree( block * );

//Object pool:

static int mem_size {0};
static int mem_used {0};
static block* mem_array[BOARD_HEIGHT * BOARD_WIDTH / PIECES_PER_BLOCK];

block* blockAlloc( void )
{
  //check if enough space exists
  if( mem_used <= mem_size )
    {
      //get more space
    }
  return mem_array[ mem_used++ ];
}

void blockFree( block *b )
{
}

Add basic skeleton for object pool

Add basic skeleton for object pool


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

struct Queue {
    stack<int> s1, s2;
};

void enqueue(Queue *Q, int data) {
    Q->s1.push(data);
}

int dequeue(Queue *Q) {
    int top;
    if (!Q->s2.empty()) {
        top = Q->s2.top();
        Q->s2.pop();
    } else {
        while (!Q->s1.empty()) {
            Q->s2.push(Q->s1.top());
            Q->s1.pop();
        }
        top = Q->s2.top();
        Q->s2.pop();
    }
    return top;
}

int main() {
    Queue *Q = new Queue();
    cout<<"enqueue 1,2,3,4\n";
    enqueue(Q, 1);
    enqueue(Q, 2);
    enqueue(Q, 3);
    enqueue(Q, 4);
    cout<<"Dequeuing front 3\n";
    int i = 0;
    while (i < 3) {
        cout<<dequeue(Q)<<" ";
        i++;
    }
    cout<<endl<<"enqueue 5,6,7,8\n";
    enqueue(Q, 5);
    enqueue(Q, 6);
    enqueue(Q, 7);
    enqueue(Q, 8);
    cout<<"Dequeuing again front 3\n";
    i = 0;
    while (i < 3) {
        cout<<dequeue(Q)<<" ";
        i++;
    }
    cout<<endl<<"enqueue 9,10\n";
    enqueue(Q, 9);
    enqueue(Q, 10);
    cout<<"Dequeuing again front 3\n";
    i = 0;
    while (i < 3) {
        cout<<dequeue(Q)<<" ";
        i++;
    }
    cout<<endl;
    delete Q;
    return 0;
}

Implement queue using only stack

Implement queue using only stack

Implement enqueue and dequeue operations using 2 stacks
Time complexity O(1)

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


// RUN: %clang_cc1 -DSTDCPP11 -std=c++11 -verify -fsyntax-only %s
// RUN: %clang_cc1 -DSTDGNU11 -std=gnu++11 -verify -fsyntax-only %s
// RUN: %clang_cc1 -DSTDGNU11TRI -trigraphs -std=gnu++11 -verify -fsyntax-only %s
// RUN: %clang_cc1 -DSTDCPP17 -std=c++1z -verify -fsyntax-only %s
// RUN: %clang_cc1 -DSTDCPP17TRI -trigraphs -std=c++1z -verify -fsyntax-only %s

void foo() {
#if defined(NOFLAGS) || defined(STDCPP11) || defined(STDGNU11TRI) || defined(STDCPP17TRI)
  const char c[] = "??/n"; // expected-warning{{trigraph converted to '\' character}}
#elif defined(STDGNU11) || defined(STDCPP17)
  const char c[] = "??/n"; // expected-warning{{trigraph ignored}}
#else
#error Not handled.
#endif
}

Add test coverage for cc1's trigraph option handling.

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


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

#include "ui/compositor/test/test_suite.h"

#include "base/command_line.h"
#include "base/message_loop/message_loop.h"
#include "ui/compositor/compositor.h"
#include "ui/compositor/compositor_switches.h"
#include "ui/gfx/gfx_paths.h"
#include "ui/gl/gl_surface.h"

#if defined(OS_WIN)
#include "ui/gfx/win/dpi.h"
#endif

namespace ui {
namespace test {

CompositorTestSuite::CompositorTestSuite(int argc, char** argv)
    : TestSuite(argc, argv) {}

CompositorTestSuite::~CompositorTestSuite() {}

void CompositorTestSuite::Initialize() {
  base::TestSuite::Initialize();
  gfx::GLSurface::InitializeOneOffForTests();

  gfx::RegisterPathProvider();

#if defined(OS_WIN)
  gfx::InitDeviceScaleFactor(1.0f);
#endif

  message_loop_.reset(new base::MessageLoopForUI);
}

void CompositorTestSuite::Shutdown() {
  message_loop_.reset();

  base::TestSuite::Shutdown();
}

}  // namespace test
}  // namespace ui

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

#include "ui/compositor/test/test_suite.h"

#include "base/command_line.h"
#include "base/message_loop/message_loop.h"
#include "ui/compositor/compositor.h"
#include "ui/compositor/compositor_switches.h"
#include "ui/gfx/gfx_paths.h"
#include "ui/gl/gl_surface.h"

#if defined(OS_WIN)
#include "ui/gfx/win/dpi.h"
#endif

namespace ui {
namespace test {

CompositorTestSuite::CompositorTestSuite(int argc, char** argv)
    : TestSuite(argc, argv) {}

CompositorTestSuite::~CompositorTestSuite() {}

void CompositorTestSuite::Initialize() {
  base::TestSuite::Initialize();
  gfx::GLSurface::InitializeOneOffForTests(true);

  gfx::RegisterPathProvider();

#if defined(OS_WIN)
  gfx::InitDeviceScaleFactor(1.0f);
#endif

  message_loop_.reset(new base::MessageLoopForUI);
}

void CompositorTestSuite::Shutdown() {
  message_loop_.reset();

  base::TestSuite::Shutdown();
}

}  // namespace test
}  // namespace ui

ui: Make compositor unittests opt into real GL NullDraw contexts.

This breaks the dependency on the TestCompositor for the
compositor_unittests. Once it's no longer in use by any test suite, we
can remove it.

R=vollick@chromium.org
BUG=270918
NOTRY=true

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

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


#include <cstdio> // Libreria estandar de IO C++

int main( int argc, char *argv[] ) {
    /*
        Usamos el operador de resolucion :: para acceder a los elementos
        dentro de la libreria estandar std
    */

    std::cout << "Hola mundo!" << std::endl;
}

Add CPP hello world example

Add CPP hello world example


// 043. Multiply Strings
/**
 * Given two numbers represented as strings, return multiplication of the numbers as a string.
 *
 * Note: The numbers can be arbitrarily large and are non-negative
 *
 * Tags: Math, String
 *
 * Similar Problems: (M) Add Two Numbers, (E) Plus One, (E) Add Binary
 *
 * Author: Kuang Qin
 */

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

using namespace std;

class Solution {
public:
    string multiply(string num1, string num2) {
        if ((num1 == "0") || (num2 == "0"))
        {
            return "0";
        }

        // use an integer array to store multiplication products
        int len1 = num1.size(), len2 = num2.size(), len = len1 + len2;
        int *product = new int[len]();
        for (int i = len1 - 1; i >= 0; i--)
        {
            for (int j = len2 - 1; j >= 0; j--)
            {
                product[i + j + 1] += (num1[i] - '0') * (num2[j] - '0');
            }
        }

        // gather carry info to make each digit valid
        for (int i = len - 1; i > 0; i--)
        {
            product[i - 1] += product[i] / 10;    // add carry to previous digit
            product[i] = product[i] % 10;         // set current digit
        }

        // convert int into string
        string res("");
        if (product[0] != 0)    // first position could be zero
        {
            res += product[0] + '0';
        }

        for (int i = 1; i < len; i++)
        {
            res += product[i] + '0';
        }

        return res;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    string num1("8354"), num2("7890");
    Solution mySolution;
    string res = mySolution.multiply(num1, num2);
    cout << num1 << " x " << num2 << " = " << res << endl;
    system("pause");
    return 0;
}

Add Solution for Problem 043

Add Solution for Problem 043


#include "stdafx.h"
#include "ShowModeConverter.h"

WORD ShowModeConverter::ToShowWindowFlag(const ShowMode& showMode)
{
	if (showMode == SHOW_MODE_HIDE)
	{
		return SW_HIDE;
	}

	if (showMode == SHOW_MODE_NORMAL)
	{
		return SW_NORMAL;
	}

	if (showMode == SHOW_MODE_SHOW)
	{
		return SW_SHOW;
	}

	return 0;
}

Add arg for show mode

Add arg for show mode


#include "LinuxEventHandler.h"
#include "OSEventHandlerExport.h"

std::shared_ptr<ni::EventHandler> GetOSEventHandler(ni::DeviceType devices) {
	return std::make_shared<ni::LinuxEventHandler>(devices);
}

Add Linux event handler export function.


//
//  Remove_Duplicates_from_Sorted_Array_2.cpp
//  leetcode
//
//  Created by 邵建勇 on 15/5/11.
//  Copyright (c) 2015年 John Shaw. All rights reserved.
//

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

using namespace std;

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if (nums.size() == 0) {
            return 0;
        }
        if (nums.size() <= 2) {
            return (int)nums.size();
        }
        int index = 2;
        for (int i = 2; i < nums.size(); i++) {
            if (nums[index - 2] != nums[i]) {
                nums[index++] = nums[i];
            }
        }
        return index;
    }
};

Remove Duplicates from Sorted Array II

Remove Duplicates from Sorted Array II


#include <common/buffer.h>

#include <event/action.h>
#include <event/callback.h>
#include <event/event.h>
#include <event/event_system.h>

Action *
Callback::schedule(void)
{
	return (EventSystem::instance()->schedule(this));
}

Add file missed in r574.

Add file missed in r574.

git-svn-id: 9e2532540f1574e817ce42f20b9d0fb64899e451@575 4068ffdb-0463-0410-8185-8cc71e3bd399


#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <cstdio>
#include <map>

using namespace std;
/*
  struct ListNode {
      int val;
      ListNode *next;
      ListNode(int x) : val(x), next(NULL) {}
  };
*/

class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head)
    {
        map<int, int> lookup;
        ListNode* mover = head;
        if (head == NULL)
            return head;
        lookup[head->val] = 1;
        int c = 2;
        while (mover != NULL)
        {
            if ((mover->next != NULL) && (lookup.find(mover->next->val) == lookup.end()))
            {
                lookup[mover->next->val] = c;
                c++;
                mover = mover->next;
            }
            else if (mover->next == NULL)
                return head;
            else
                mover->next = mover->next->next;
        }
        return head;
    }
};

Remove Duplicates from sorted list (Made general case for unsorted list).


#include "unittest/gtest.hpp"

#include "arch/streamed_tcp.hpp"

namespace unittest {

namespace {

/* `run_in_thread_pool()` starts a RethinkDB IO layer thread pool and calls the
given function within a coroutine inside of it. */

struct starter_t : public thread_message_t {
    thread_pool_t *tp;
    boost::function<void()> fun;
    starter_t(thread_pool_t *tp, boost::function<void()> fun) : tp(tp), fun(fun) { }
    void run() {
        fun();
        tp->shutdown();
    }
    void on_thread_switch() {
        coro_t::spawn_now(boost::bind(&starter_t::run, this));
    }
};
void run_in_thread_pool(boost::function<void()> fun) {
    thread_pool_t thread_pool(1);
    starter_t starter(&thread_pool, fun);
    thread_pool.run(&starter);
}

void handle_echo_conn(boost::scoped_ptr<streamed_tcp_conn_t> &conn) {
    while (conn->get_istream().good()) {
        // Read a line and send it back
        std::string str;
        conn->get_istream() >> str;
        if (!conn->get_istream().fail()) {
            conn->get_ostream() << str << std::endl; // endl causes flush()
        }
    }
}

}   /* anonymous namespace */

void run_tcp_stream_test() {
    int port = 10000 + rand() % 20000;
    streamed_tcp_listener_t listener(port, boost::bind(&handle_echo_conn, _1));

    streamed_tcp_conn_t conn("localhost", port);
    std::string test_str = "0";
    for (int i = 0; i < 8192 / 32; ++i, test_str += std::string(32, static_cast<char>('a' + (i % 26)))) {
        conn.get_ostream() << test_str.substr(0, i);
        conn.get_ostream() << test_str.substr(i) << std::endl; // endl causes flush()
        //fprintf(stderr, "sent stuff of size %lu\n", test_str.length());
        std::string str;
        conn.get_istream() >> str;
        //fprintf(stderr, "got stuff\n");
        EXPECT_TRUE(!conn.get_istream().fail());
        EXPECT_EQ(str, test_str);
    }
    conn.get_ostream().flush();
}
TEST(TCPStreamTest, StartStop) {
    run_in_thread_pool(&run_tcp_stream_test);
}

}

Add a streamed tcp conn unit test

Add a streamed tcp conn unit test


// Test that -Wsystem-headers works with default and custom mappings like -Werror.
// Keep run lines at the bottom for line number stability.

#ifdef IS_SYSHEADER
#pragma clang system_header

int f() { return (int)0; } // Use the old-style-cast warning as an arbitrary "ordinary" diagnostic for the purpose of testing.

#warning "custom message"

#if defined(A) || defined(B)
// expected-warning@9 {{"custom message"}}
#elif defined(C)
// expected-warning@7 {{use of old-style cast}}
// expected-warning@9 {{"custom message"}}
#elif defined(D)
// expected-error@7 {{use of old-style cast}}
// expected-error@9 {{"custom message"}}
#elif defined(E)
// expected-error@7 {{use of old-style cast}}
// expected-warning@9 {{"custom message"}}
#endif

#else
#define IS_SYSHEADER
#include __FILE__
#endif

// RUN: %clang_cc1 -verify -fsyntax-only -DA %s
// RUN: %clang_cc1 -verify -fsyntax-only -DB -Wold-style-cast %s
// RUN: %clang_cc1 -verify -fsyntax-only -DC -Wold-style-cast -Wsystem-headers %s
// RUN: %clang_cc1 -verify -fsyntax-only -DD -Wold-style-cast -Wsystem-headers -Werror %s
// RUN: %clang_cc1 -verify -fsyntax-only -DE -Wold-style-cast -Wsystem-headers -Werror=old-style-cast %s

Add a proper test for -Wsystem-headers

Add a proper test for -Wsystem-headers

This will be extended as we fix issues in the current implementation.

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


// Chapter 24, exercise 10: test rand(); write a program that takes two integers
// n and d and calls randint(n) d times; output the number of draws for each
// [0:n) and see if there are any obvious biases

#include<iostream>
#include<iomanip>
#include<cstdlib>
#include<ctime>
#include<map>

using namespace std;

inline int randint(int max) { return rand()%max; }

inline int randint(int min, int max) { return randint(max-min)+min; }

int main()
try
{
    while (true) {
        cout << "Enter biggest number: ";
        int n;
        cin >> n;
        cout << "Enter number of draws (0 to exit): ";
        int d;
        cin >> d;
        if (d==0) break;
        srand(time(0));

        int r = 0;
        map<int,int> histo;
        for (int i = 0; i<d; ++i)
            ++histo[randint(n)];

        for (int i= 0; i<n; ++i) {
            cout << setw(2) << i << ": ";
            for (int j = 0; j<histo[i]; ++j)
                cout << '*';
            cout << '\n';
        }
    }
}
catch (exception& e) {
    cerr << "Exception: " << e.what() << '\n';
}
catch (...) {
    cerr << "Exception\n";
}

Add Chapter 24, exercise 10

Add Chapter 24, exercise 10


#include <bits/stdc++.h>

using namespace std;

int main()
{
    int sum = 0;
    int max_sum = array[0];
    for (int i = 0; i < length; ++i)
    {
        sum += array[i];
        sum = max(0, sum);
        max_sum = max(sum, max_sum);
    }
    return max_sum;
}

Add Maximum consecutive sum in c++

Add Maximum consecutive sum in c++


// Copyright Louis Dionne 2015
// Distributed under the Boost Software License, Version 1.0.

#include <boost/hana.hpp>
#include <boost/hana/struct_macros.hpp>

#include <iostream>
#include <string>
#include <type_traits>
#include <utility>
using namespace boost::hana;
using namespace std::literals;

std::string quote(std::string s) { return "\"" + s + "\""; }

template <typename Xs>
std::string join(Xs&& xs, std::string sep) {
  return fold.left(intersperse(std::forward<Xs>(xs), sep), "", _ + _);
}

template <typename T>
auto to_json(T&& x) -> decltype(std::to_string(std::forward<T>(x))) {
  return std::to_string(std::forward<T>(x));
}

std::string to_json(char c) { return quote({c}); }
std::string to_json(std::string s) { return quote(s); }

template <typename T>
std::enable_if_t<models<Struct, T>(), std::string> to_json(T&& x) {
  auto as_tuple = to<Tuple>(std::forward<T>(x));

  auto json = transform(std::move(as_tuple),
    fuse([](auto name, auto&& member) {
      return quote(to<char const*>(name)) + " : " +
                to_json(std::forward<decltype(member)&&>(member));
    }));

  return "{" + join(std::move(json), ", ") + "}";
}

template <typename Xs>
std::enable_if_t<models<Sequence, Xs>(), std::string> to_json(Xs&& xs) {
  auto json = transform(std::forward<Xs>(xs), [](auto&& x) {
    return to_json(std::forward<decltype(x)&&>(x));
  });

  return "[" + join(std::move(json), ", ") + "]";
}

struct Person {
  BOOST_HANA_DEFINE_STRUCT(Person,
    (std::string, name),
    (int, age)
  );
};

int main() {
  Person joe{"Joe", 30};
  std::cout << to_json(make_tuple(1, 'c', joe));
}

Add an example of JSON generation

Add an example of JSON generation


// Verifies that speculative loads from unions do not happen under asan.
// RUN: %clangxx_asan -O0 %s -o %t && ASAN_OPTIONS=detect_leaks=0 %run %t 2>&1
// RUN: %clangxx_asan -O1 %s -o %t && ASAN_OPTIONS=detect_leaks=0 %run %t 2>&1
// RUN: %clangxx_asan -O2 %s -o %t && ASAN_OPTIONS=detect_leaks=0 %run %t 2>&1
// RUN: %clangxx_asan -O3 %s -o %t && ASAN_OPTIONS=detect_leaks=0 %run %t 2>&1

typedef union {
  short q;
  struct {
    short x;
    short y;
    int for_alignment;
  } w;
} U;
int main() {
  char *buf = new char[2];
  buf[0] = buf[1] = 0x0;
  U *u = (U *)buf;
  return  u->q == 0 ? 0 : u->w.y;
}

Disable gvn non-local speculative loads under asan.

Summary: Fix for https://llvm.org/bugs/show_bug.cgi?id=25550

Differential Revision: http://reviews.llvm.org/D14764

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


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

#include "config.h"
#include "core/dom/RemoteSecurityContext.h"

#include "core/frame/csp/ContentSecurityPolicy.h"
#include "platform/weborigin/SecurityOrigin.h"

namespace blink {

RemoteSecurityContext::RemoteSecurityContext()
    : SecurityContext()
{
    // RemoteSecurityContext's origin is expected to stay uninitialized until
    // we set it using replicated origin data from the browser process.
    ASSERT(!haveInitializedSecurityOrigin());

    // CSP will not be replicated for RemoteSecurityContexts, as it is moving
    // to the browser process.  For now, initialize CSP to a default
    // locked-down policy.
    setContentSecurityPolicy(ContentSecurityPolicy::create());

    // FIXME: Document::initSecurityContext has a few other things we may
    // eventually want here, such as enforcing a setting to
    // grantUniversalAccess().
}

PassRefPtr<RemoteSecurityContext> RemoteSecurityContext::create()
{
    return adoptRef(new RemoteSecurityContext());
}

void RemoteSecurityContext::setReplicatedOrigin(PassRefPtr<SecurityOrigin> origin)
{
    // FIXME: Currently, replicated security origins are passed only at
    // RemoteFrame creation time.  Eventually, this class will also need to
    // handle origin updates to handle cases like setting document.domain, but
    // for now, check that this is the first and only time we are setting the
    // origin.
    ASSERT(!haveInitializedSecurityOrigin());
    setSecurityOrigin(origin);
}

} // namespace blink

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

#include "config.h"
#include "core/dom/RemoteSecurityContext.h"

#include "core/frame/csp/ContentSecurityPolicy.h"
#include "platform/weborigin/SecurityOrigin.h"

namespace blink {

RemoteSecurityContext::RemoteSecurityContext()
    : SecurityContext()
{
    // RemoteSecurityContext's origin is expected to stay uninitialized until
    // we set it using replicated origin data from the browser process.
    ASSERT(!haveInitializedSecurityOrigin());

    // CSP will not be replicated for RemoteSecurityContexts, as it is moving
    // to the browser process.  For now, initialize CSP to a default
    // locked-down policy.
    setContentSecurityPolicy(ContentSecurityPolicy::create());

    // FIXME: Document::initSecurityContext has a few other things we may
    // eventually want here, such as enforcing a setting to
    // grantUniversalAccess().
}

PassRefPtr<RemoteSecurityContext> RemoteSecurityContext::create()
{
    return adoptRef(new RemoteSecurityContext());
}

void RemoteSecurityContext::setReplicatedOrigin(PassRefPtr<SecurityOrigin> origin)
{
    setSecurityOrigin(origin);
}

} // namespace blink

Allow replicated origins to be updated.

Allow replicated origins to be updated.

Previously, replicated origins were set only when RemoteFrames were
created.  However, https://codereview.chromium.org/1098763003 is
going to send origin updates to frame proxies when the frame
navigates to another origin, so this check is no longer needed.

BUG=426512

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

git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@194229 bbb929c8-8fbe-4397-9dbb-9b2b20218538


//===-- SelectionDAGPrinter.cpp - Implement SelectionDAG::viewGraph() -----===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This implements the SelectionDAG::viewGraph method.
//
//===----------------------------------------------------------------------===//

#include "llvm/CodeGen/SelectionDAG.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/Function.h"
#include "llvm/Support/GraphWriter.h"
#include <fstream>
using namespace llvm;

/// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
/// rendered using 'dot'.
///
void SelectionDAG::viewGraph() {
  std::string Filename = "/tmp/dag." +
    getMachineFunction().getFunction()->getName() + ".dot";
  std::cerr << "Writing '" << Filename << "'... ";
  std::ofstream F(Filename.c_str());

  if (!F) {
    std::cerr << "  error opening file for writing!\n";
    return;
  }

  WriteGraph(F, this);
  F.close();
  std::cerr << "\n";

  std::cerr << "Running 'dot' program... " << std::flush;
  if (system(("dot -Tps -Nfontname=Courier -Gsize=7.5,10 " + Filename
              + " > /tmp/dag.tempgraph.ps").c_str())) {
    std::cerr << "Error running dot: 'dot' not in path?\n";
  } else {
    std::cerr << "\n";
    system("gv /tmp/dag.tempgraph.ps");
  }
  system(("rm " + Filename + " /tmp/dag.tempgraph.ps").c_str());
}

Implement initial selectiondag printing support.  This gets us a nice
graph with no labels! :)

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


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

// RUN: not %run %t 'A' 2>&1 | FileCheck %s
// RUN: not %run %t 'B' 2>&1 | FileCheck %s

// Missing lifetime markers in test_a
// https://bugs.llvm.org/show_bug.cgi?id=34353
// XFAIL: *

struct B {
  B() : p('B') {}
  char p;
};

struct C {
  const char *p;
  explicit C(const char *c) : p(c) {}
  C(const B &b) : p(&b.p) {} // NOLINT
};

struct A {
  char p;
  explicit A() : p('C') {}
  const operator C() const { return C(&p); }
};

volatile char r;
void test_a() {
  C s = A();
  r = *s.p;
}

void test_b() {
  C s = B();
  r = *s.p;
}

int main(int argc, char **argv) {
  switch (argv[1][0]) {
  case 'A':
    test_a();
    return 0;
  case 'B':
    test_b();
    return 0;
  }
  return 1;
}

// CHECK: ERROR: AddressSanitizer: stack-use-after-scope

[asan] Add use-after-scope test which fails because of bug in clang

Reviewers: kcc, eugenis

Subscribers: llvm-commits, kubamracek

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

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


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

#include "chrome/browser/apps/app_browsertest_util.h"
#include "extensions/test/extension_test_message_listener.h"

// This class of BrowserTests is a helper to create tests related to crashes in
// Chrome Apps. To be tested, the app will have to be placed as any other test
// app (see PlatformAppBrowserTest) and will need to send a "Done" message back.
// When the "Done" message is received, the test succeed. If it is not, it is
// assumed that Chrome has crashed and the test will anyway fail.
//
// The entry in this file should be something like:
// IN_PROC_BROWSER_TEST_F(AppCrashTest, <TEST_NAME>) {
//   ASSERT_TRUE(RunAppCrashTest("<DIRECTORY_TEST_NAME>"));
// }

class AppCrashTest : public extensions::PlatformAppBrowserTest {
public:
 void RunAppCrashTest(const char* name) {
   LoadAndLaunchPlatformApp(name, "Done");
  }
};

IN_PROC_BROWSER_TEST_F(AppCrashTest, HiddenWindows) {
  RunAppCrashTest("crashtest_hidden_windows");
}

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

#include "chrome/browser/apps/app_browsertest_util.h"
#include "extensions/test/extension_test_message_listener.h"

// This class of BrowserTests is a helper to create tests related to crashes in
// Chrome Apps. To be tested, the app will have to be placed as any other test
// app (see PlatformAppBrowserTest) and will need to send a "Done" message back.
// When the "Done" message is received, the test succeed. If it is not, it is
// assumed that Chrome has crashed and the test will anyway fail.
//
// The entry in this file should be something like:
// IN_PROC_BROWSER_TEST_F(AppCrashTest, <TEST_NAME>) {
//   ASSERT_TRUE(RunAppCrashTest("<DIRECTORY_TEST_NAME>"));
// }

class AppCrashTest : public extensions::PlatformAppBrowserTest {
public:
 void RunAppCrashTest(const char* name) {
   LoadAndLaunchPlatformApp(name, "Done");
  }
};

// Disabling flaky test on ASAN,  crbug.com/469249
#if !defined(ADDRESS_SANITIZER)
IN_PROC_BROWSER_TEST_F(AppCrashTest, HiddenWindows) {
  RunAppCrashTest("crashtest_hidden_windows");
}
#endif

Disable a flaky test.  See crbug.com/469249.

BUG=469249

TBR=kalman@chromium.org

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

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


//===- InlineAlways.cpp - Code to perform simple function inlining --------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements bottom-up inlining of functions into callees.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "inline"
#include "llvm/CallingConv.h"
#include "llvm/Instructions.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/Module.h"
#include "llvm/Type.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Support/CallSite.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/IPO/InlinerPass.h"
#include "llvm/Transforms/Utils/InlineCost.h"
#include "llvm/ADT/SmallPtrSet.h"

using namespace llvm;

namespace {

  // AlwaysInliner only inlines functions that are mark as "always inline".
  class VISIBILITY_HIDDEN AlwaysInliner : public Inliner {
    // Functions that are never inlined
    SmallPtrSet<const Function*, 16> NeverInline;
    InlineCostAnalyzer CA;
  public:
    // Use extremely low threshold.
    AlwaysInliner() : Inliner(&ID, -2000000000) {}
    static char ID; // Pass identification, replacement for typeid
    int getInlineCost(CallSite CS) {
      return CA.getInlineCost(CS, NeverInline);
    }
    float getInlineFudgeFactor(CallSite CS) {
      return CA.getInlineFudgeFactor(CS);
    }
    virtual bool doInitialization(CallGraph &CG);
  };
}

char AlwaysInliner::ID = 0;
static RegisterPass<AlwaysInliner>
X("always-inline", "Inliner that handles always_inline functions");

Pass *llvm::createAlwaysInlinerPass() { return new AlwaysInliner(); }

// doInitialization - Initializes the vector of functions that have not
// been annotated with the "always inline" attribute.
bool AlwaysInliner::doInitialization(CallGraph &CG) {

  Module &M = CG.getModule();

  for (Module::iterator I = M.begin(), E = M.end();
       I != E; ++I)
    if (!I->isDeclaration() && I->getNotes() != FN_NOTE_AlwaysInline)
      NeverInline.insert(I);

  return false;
}

Add custom inliner that handles only functions that are marked as always_inline.

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


#include "Inputs/HeaderWithSymbol.h"
#define FOO int bar;
FOO

int foo;

// RUN: not clang-rename -new-name=qux -offset=259 %s -- 2>&1 | FileCheck %s
// CHECK-NOT: CHECK
// CHECK: error: SourceLocation in file {{.*}}InvalidOffset.cpp at offset 259 is invalid

Add test case for r287758.

[clang-rename] Add test case for r287758.

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


// REQUIRES: shell
// RUN: rm -rf %t
// RUN: mkdir -p %t

// This is a reproducer for PR37091.
//
// Verify that no temporary files are left behind by the clang-tidy invocation.

// RUN: env TMPDIR=%t TEMP=%t TMP=%t clang-tidy %s -- --target=mips64
// RUN: rmdir %t

[Driver] Clean up tmp files when deleting Compilation objects

Summary:
In rL327851 the createUniqueFile() and createTemporaryFile()
variants that do not return the file descriptors were changed to
create empty files, rather than only check if the paths are free.
This change was done in order to make the functions race-free.

That change led to clang-tidy (and possibly other tools) leaving
behind temporary assembly files, of the form placeholder-*, when
using a target that does not support the internal assembler.

The temporary files are created when building the Compilation
object in stripPositionalArgs(), as a part of creating the
compilation database for the arguments after the double-dash. The
files are created by Driver::GetNamedOutputPath().

Fix this issue by cleaning out temporary files at the deletion of
Compilation objects.

This fixes https://bugs.llvm.org/show_bug.cgi?id=37091.

Reviewers: klimek, sepavloff, arphaman, aaron.ballman, john.brawn, mehdi_amini, sammccall, bkramer, alexfh, JDevlieghere

Reviewed By: aaron.ballman, JDevlieghere

Subscribers: erichkeane, lebedev.ri, Ka-Ka, cfe-commits

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

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


#include "tree_node.h"
#include "gtest\gtest.h"

/*
 This file will include all the test for the TreeNode class.
*/

TEST(TreeNodeTest, AddChild) {
	//Initialize a node with some children.
	TreeNode<int> focusNode;
	TreeNode<int> child1;
	TreeNode<int> child2;

	focusNode.addChild(&child1);
	focusNode.addChild(&child2);
	EXPECT_EQ(focusNode.getChildren().size(), 2);
}

TEST(TreeNodeTest, RemoveChild) {
	//Initialize a node with some children then remove them.
	TreeNode<int> focusNode;
	TreeNode<int> child1;
	TreeNode<int> child2;

	focusNode.addChild(&child1);
	focusNode.addChild(&child2);

	focusNode.removeChild(1);
	EXPECT_EQ(focusNode.getChildren().size(), 1);

	focusNode.removeChild(0);
	EXPECT_EQ(focusNode.getChildren().size(), 0);

	EXPECT_NO_THROW(focusNode.removeChild(0));
}

TEST(TreeNodeTest, AddParent) {
	//Initialize a node with a parent.
	TreeNode<int> root;
	TreeNode<int> focusNode;

	EXPECT_EQ(focusNode.getParent(), nullptr);

	focusNode.setParent(&root);
	EXPECT_EQ(focusNode.getParent(), &root);
}

TEST(TreeNodeTest, RemoveParent) {
	//Initialize a node with a parent and then remove it.
	TreeNode<int> root;
	TreeNode<int> focusNode;

	focusNode.setParent(&root);
	EXPECT_EQ(focusNode.getParent(), &root);

	focusNode.removeParent();
	EXPECT_EQ(focusNode.getParent(), nullptr);
}

TEST(TreeNodeTest, Value) {
	//Initialize a node with a value.
	TreeNode<int> focusNode;

	focusNode.setValue(1);
	EXPECT_EQ(focusNode.getValue(), 1);
}

Add test for the treenode.

Add test for the treenode.


// Chapter 25, exercise 5: write an infinite loop and execute it

#include<iostream>
#include<exception>

using namespace std;

int main()
try
{
    while (true)
        cout << "Looping!\n";
}
catch (exception& e) {
    cerr << "exception: " << e.what() << endl;
}
catch (...) {
    cerr << "exception\n";
    return 2;
}

Add Chapter 25, exercise 5

Add Chapter 25, exercise 5


#include <stdio.h>

int main(void)
{
    int N;

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

    /* Get the largest number in the power of two, which satisfies less than or equal to N */
    int v = 1;

    while(v <= N) v = v << 1;
    v = v >> 1;

    /* Calculate and print to screen */
    while(v > 0)
    {
        if(N >= v)
        {
            N -= v;
            putchar('1');
        }
        else
            putchar('0');

        v /= 2;
    }
    putchar('\n');

    return 0;
}

Add a solution of prob 3

Add a solution of prob 3


// Read lines from a stream

#include <sstream>
#include <string>

int main()
{
	std::istringstream stream{"This stream\n"
	                          "contains many\n"
	                          "lines.\n"};
	std::string line;

	while (std::getline(stream, line)) {
		// Process line
	}
}

// Process the contents of an input stream line-by-line.
//
// We use a [`std::istringstream`](cpp/io/basic_istringstream) as an
// example input stream ([8-10]) containing multiple lines (separated
// by `\n`). This stream could be replaced with
// [`std::cin`](cpp/io/cin) or a file stream, for example. On [11], we
// introduce a [`std::string`](cpp/string/basic_string) into which we
// will read each line of the stream.
//
// On [13-15], we use a `while` loop to iterate over each line of the
// stream. The condition of the loop is a call to
// [`std::getline`](cpp/string/getline), which extracts lines from
// `stream` into `line`. The result of this call will evaluate to
// `false` only when the extraction fails, such as when there are no
// lines left to extract.

Add "read lines from stream" sample

Add "read lines from stream" sample


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


class Solution {
public:
    bool isValidSerialization(string preorder) {
        int diff = 1;
        std::string temp = "";
        for (const auto &c : preorder) {
            if (c == ',') {
                --diff;
                if (diff < 0)
                    return false;
                if (temp != "#")
                    diff += 2;
                temp = "";
            } else {
                temp += c;
            }
        }
        --diff;
        if (diff < 0)
            return false;
        if (temp != "#")
            diff += 2;
        return diff == 0;
    }
};

Verify Preorder Serialization of a Binary Tree


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

class BinaryCode {
public:
  vector <string> decode(string message) {
    vector <string> result;
    unsigned len = message.length() + 2;
    int P[len];
    int Q[len];
    Q[0] = Q[len-1] = 0;
    for (unsigned i = 0; i < message.length(); i++) {
      Q[i+1] = message[i] - '0';
    }

    for (int init = 0; init <= 1; init++) {
      P[0] = 0;
      P[1] = init;
      for (unsigned i = 2; i < len; i++) {
        P[i] = Q[i-1] - P[i-1] - P[i-2];
      }

      string orig;
      if (P[len-1] != 0) {
        orig = "NONE";
      } else {
        for (unsigned i = 1; i <= message.length(); i++) {
          //cout << char('0' + P[i]) << " added..." << endl;
          if (P[i] == 0 || P[i] == 1) {
            orig += ('0' + P[i]);
          } else {
            orig = "NONE";
            break;
          }
        }
      }

      result.push_back(orig);
    }
    return result;
  }

  void disp(string message) {
    cout << decode(message)[0] << endl
         << decode(message)[1] << endl;
  }
};

int main() {
  BinaryCode bc;
  bc.disp("123210122");
  bc.disp("22111");
}

Solve SRM 144, Div 2, Problem BinaryCode


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

#include <bits/stdc++.h>

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

int vectorMul(IntPair a, IntPair b) {
    return a.first * b.second - b.first * a.second;
}

int scalarMul(IntPair a, IntPair b) {
    return a.first * b.first + a.second * b.second;
}

int main() {
    // number of vertices and coordinates of starting point
    int N, x, y;
    std::cin >> N >> x >> y;
    // vectors for all vertices (starting point --> curr vertex)
    IntPairs vectors;
    for (int i = 0; i < N; i++) {
        // polygon vertex
        int vx, vy;
        std::cin >> vx >> vy;
        vectors.push_back(IntPair(vx - x, vy - y));
    }
    double sum = 0;
    for (int i = 0; i < N; i++) {
        IntPair v1 = vectors[i];
        IntPair v2 = vectors[(i + 1) % N];
        sum += std::atan2(vectorMul(v1, v2), scalarMul(v1, v2));
    }
    bool outside = (std::fabs(sum) < 1e-9);
    std::cout << (outside ? "NO" : "YES") << std::endl;
    return 0;
}

Add PIP (point in polygon) problem

Add PIP (point in polygon) problem


// Decorator (compile-time)

class foo_concrete
{
	public:
		void do_work()
		{ }
};

template <typename Foo>
class foo_decorator
{
	public:
		foo_decorator(Foo& f)
			: f{f}
		{ }

		void do_work() {
			// Do something else here to decorate
			// the do_work function
			f.do_work();
		}

	private:
		Foo& f;
};

template <typename Foo>
void bar(Foo& f)
{
	f.do_work();
}

int main()
{
	foo_concrete f;
	foo_decorator<foo_concrete> decorated_f{f};

	bar(decorated_f);
}

// Wrap a class with a decorator to extend its functionality.
//
// On [3-8], we define the class that we wish to decorate,
// `foo_concrete`.
//
// The `foo_decorator` class template, on [10-26], implements the
// same interface as `foo_concrete` and wraps any other object with
// that interface, passed in to the constructor by reference on
// [14-16]. A `foo_decorator` object can be used anywhere a
// `foo_concrete` would be expected, but also decorates its member
// functions. That is, the `foo_decorator::do_work` function ([18-22])
// calls the wrapped object's `do_work` function, while also doing
// some extra work.
//
// To demonstrate, we wrap a `foo_concrete` with a `foo_decorator` on
// [36-37], and pass it to the `bar` function template on [39], which
// expects any object that implements the `do_work` function. In this
// case, the call to `do_work` on [31] will be decorated.

Add "compile-time decorator pattern" sample


#include "../../test.h"
#include "../../func/func-common.h"
#include <iostream>

TEST_CASE( "sensor get_option memory leak", "[live]" )
{
    // running this test with the following command:
    // `valgrind --leak-check=yes --show-leak-kinds=all --track-origins=yes ./unit-tests/build/utilities/memory/test-sensor-option/test-utilities-memory-sensor-option 2>&1 | grep depends`
    // should print nothing!

    auto devices = find_devices_by_product_line_or_exit(RS2_PRODUCT_LINE_DEPTH);
    if (devices.size() == 0) return;
    auto dev = devices[0];

    auto depth_sens = dev.first< rs2::depth_sensor >();
    // float option_value(depth_sens.get_option(RS2_OPTION_EXPOSURE));
    float option_value(depth_sens.get_option(RS2_OPTION_ENABLE_AUTO_EXPOSURE));

    std::cout << "Declare: BOOL::" << option_value << std::endl;
}

Add test for memory leak to be run with valgrind


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

#include "distortos/chip/lowLevelInitialization.hpp"

namespace distortos
{

namespace chip
{

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

void lowLevelInitialization()
{

}

}	// namespace chip

}	// namespace distortos

Add empty chip::lowLevelInitialization() for STM32F7


// Copyright © 2012 Lénaïc Bagnères, hnc@singularity.fr

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

//#include <hnc/header_you_test.hpp>
#include <hnc/test.hpp>
#include <hnc/to_string.hpp>

int main()
{
	int nb_test = 0;

	// Do test
	++nb_test;
	{
		// Do test
		nb_test -= hnc::test::warning(true, "Return 1 if the condition is true, 0 else\n");
	}
	std::cout << std::endl;

	hnc::test::warning(nb_test == 0, "hnc::header_you_test: " + hnc::to_string(nb_test) + " test fail!\n");

	return nb_test;
}

Add test file template (to create a new test)


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

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

class MinNumberOfCoints {
public:
  int min(const int val) {
    std::vector<int> solutions(val+1, 0);
    for (int idx = 1; idx <= val; ++idx) {
      int count = idx;
      for (size_t coinIdx = 0; coinIdx < Coins.size(); ++coinIdx) {
        auto currentCoin = Coins[coinIdx];
        if (idx > currentCoin) {
          count = std::min(count, 1 + solutions[idx - currentCoin]);
        } else if (idx == currentCoin) {
          count = std::min(count, 1);
        }
      }
      solutions[idx] = count;
    }

    // For debugging purpose.
    // print(solutions);

    return solutions[val];
  }

private:
  std::vector<int> Coins{1, 5, 8, 10, 15, 25};
};

int main() {
  MinNumberOfCoints solver;

  {
    int value = 5;
    std::cout << "Minimum number of coins for " << value << " is " << solver.min(value) << "\n";
  }

  {
    int value = 9;
    std::cout << "Minimum number of coins for " << value << " is " << solver.min(value) << "\n";
  }

  {
    int value = 21;
    std::cout << "Minimum number of coins for " << value << " is " << solver.min(value) << "\n";
  }
}

Add solution for the minimum number of coins problem.


/**
 * link: https://leetcode.com/problems/merge-two-sorted-lists/
 * Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
 */

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution
{
  public:
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2)
    {
        if (l1 == NULL)
            return l2;
        if (l2 == NULL)
            return l1;

        ListNode *head;
        ListNode *current = head = NULL;
        while (l1 && l2)
        {
            if (l1->val <= l2->val)
            {
                if (current == NULL)
                {
                    current = head = l1;
                }
                else
                {
                    current->next = l1;
                    current = current->next;
                }
                l1 = l1->next;
            }
            else
            {
                if (current == NULL)
                {
                    current = head = l2;
                }
                else
                {
                    current->next = l2;
                    current = current->next;
                }
                l2 = l2->next;
            }
            current->next = NULL;
        }

        if (l2)
            current->next = l2;
        if (l1)
            current->next = l1;
        return head;
    }
};

Add solution for 21. Merge Two Sorted Lists.


#include "wtf/event.h"

#include <fstream>

#include "testing/base/public/gunit.h"

namespace wtf {
namespace {

class EventTest : public ::testing::Test {
 protected:
  void TearDown() override {}

  EventDefinition CreateEventDefinition(const char *name_spec) {
    return EventDefinition::Create<int, const char*>(
        /*wire_id=*/0, EventClass::kScoped, /*flags=*/0, name_spec);
  }
};

TEST_F(EventTest, CheckNameSpecParsing) {
  std::string output;

  auto event = CreateEventDefinition("MyFunc");
  event.AppendName(&output);
  EXPECT_EQ(output, "MyFunc");
  output.clear();
  event.AppendArguments(&output);
  EXPECT_EQ(output, "int32 a0, ascii a1");

  output.clear();
  event = CreateEventDefinition("MyNamespace::MyClass::MyFunc");
  event.AppendName(&output);
  EXPECT_EQ(output, "MyNamespace#MyClass#MyFunc");
  output.clear();
  event.AppendArguments(&output);
  EXPECT_EQ(output, "int32 a0, ascii a1");

  output.clear();
  event = CreateEventDefinition("MyClass::MyFunc2:  arg1 , arg2");
  event.AppendName(&output);
  EXPECT_EQ(output, "MyClass#MyFunc2");
  output.clear();
  event.AppendArguments(&output);
  EXPECT_EQ(output, "int32 arg1, ascii arg2");

  output.clear();
  event = CreateEventDefinition("MyFunc2:  arg1 , arg2");
  event.AppendName(&output);
  EXPECT_EQ(output, "MyFunc2");
  output.clear();
  event.AppendArguments(&output);
  EXPECT_EQ(output, "int32 arg1, ascii arg2");

  output.clear();
  event = CreateEventDefinition("MyFunc3:  arg1");
  event.AppendName(&output);
  EXPECT_EQ(output, "MyFunc3");
  output.clear();
  event.AppendArguments(&output);
  EXPECT_EQ(output, "int32 arg1, ascii a1");
}

}  // namespace
}  // namespace wtf

int main(int argc, char** argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

Add test for event.cc changes to name_spec parsing


// RUN: rm -rf %t
// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -verify %s
// expected-no-diagnostics

#pragma clang module build sys_types
module sys_types {}
#pragma clang module contents
#pragma clang module begin sys_types
extern "C" {
  typedef union { bool b; } pthread_mutex_t;
}
#pragma clang module end
#pragma clang module endbuild

typedef union { bool b; } pthread_mutex_t;
#pragma clang module import sys_types

const pthread_mutex_t *m;

[modules] Add a regression test for merging anon decls in extern C contexts.

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


// Shared ownership

#include <memory>
#include <utility>

struct foo {};

void func(std::shared_ptr<foo> obj)
{ }

int main()
{
	std::shared_ptr<foo> obj = std::make_shared<foo>();
	pass_shared_ownership(obj);
}

// Share ownership of a dynamically allocated object with another
// unit of code.
//
// On [13], we create a [`std::shared_ptr`](cpp/memory/shared_ptr)
// which has ownership of a dynamically allocated `foo` object
// (allocated with the [`std::make_shared`](cpp/memory/shared_ptr/make_shared)
// utility function). [!14] then demonstrates sharing ownership of this
// object with a function. That is, both `main` and `func` have access
// to the same `foo` object. When ownership of an object is shared, it
// will only be destroyed when all `std::shared_ptr`s owning it are
// destroyed.
//
// In other cases, you may instead wish to [transfer unique ownership
// of an object](/common-tasks/memory-management/transfer-ownership-of-object.html).

// Shared ownership

#include <memory>
#include <utility>

struct foo {};

void func(std::shared_ptr<foo> obj)
{ }

int main()
{
	std::shared_ptr<foo> obj = std::make_shared<foo>();
	func(obj);
}

// Share ownership of a dynamically allocated object with another
// unit of code.
//
// On [13], we create a [`std::shared_ptr`](cpp/memory/shared_ptr)
// which has ownership of a dynamically allocated `foo` object
// (allocated with the [`std::make_shared`](cpp/memory/shared_ptr/make_shared)
// utility function). [!14] then demonstrates sharing ownership of this
// object with a function. That is, both `main` and `func` have access
// to the same `foo` object. When ownership of an object is shared, it
// will only be destroyed when all `std::shared_ptr`s owning it are
// destroyed.
//
// In other cases, you may instead wish to [transfer unique ownership
// of an object](/common-tasks/memory-management/transfer-ownership-of-object.html).

Correct shared ownership sample code

Correct shared ownership sample code


// 3. Longest Substring Without Repeating Characters
/**
 * Given a string, find the length of the longest substring without repeating characters.
 * For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3.
 * For "bbbbb" the longest substring is "b", with the length of 1.
 *
 * Tag: Hash Table, Two Pointers, String
 *
 * Author: Kuang Qin
 */

#include <iostream>
#include <string>
#include <unordered_map>

using namespace std;

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        // use two pointers to search a string with non-repeating characters
        int l = 0, r = 0, len = 0;

        // use a hash map to map current char to its last appeared location
        unordered_map<char, int> map;

        // use r to scan the string
        for (r = 0; r < s.size(); r++)
        {
            if (map.find(s[r]) != map.end())   // s[r] appears before
            {
                if (l <= map[s[r]])    // l can only go forward
                {
                    l = map[s[r]] + 1;    // update l to ensure non-repeating
                }
            }

            map[s[r]] = r;    // update last apeared location of s[r]

            if (len < r - l + 1)
            {
                len = r - l + 1;    // update max length
            }
        }

        return len;
    }
};

int main() {
    string s("abcabcbb");
    Solution mySolution;
    int res = mySolution.lengthOfLongestSubstring(s);
    cout << res << endl;
    return 0;
}

Add Solution for Problem 003

Add Solution for Problem 003


#include <cstdio>
#include <vector>

using namespace std;

const int N = 1 << 10;
vector <int> graph[N];
bool visited[N];
int m;

void input()
{
  scanf("%d\n", &m);

  for (int i = 0; i < m; i++)
  {
    int u, v;
    scanf("%d%d", &u, &v);
    graph[u].push_back(v);
  }
}

void dfs(int u)
{
  visited[u] = 1;
  printf("%d ", u);
  for (int i = 0; i < graph[u].size(); i++)
  {
    int v = graph[u][i];
    if (!visited[v])
    {
      dfs(v);
    }
  }
}

int main()
{
  input();
  dfs(1);
  printf("\n");

  return 0;
}

Add a solution for task 8b

Add a solution for task 8b


// Fixed time step
// C++11, C++14

#include <chrono>
#include <thread>

using namespace std::literals::chrono_literals;

void some_complex_work();

int main()
{
	using clock = std::chrono::steady_clock;
	clock::time_point next_time_point = clock::now() + 5s;

	some_complex_work();

	std::this_thread::sleep_until(next_time_point);
}

// Block the execution of a thread until a fixed point in time.
//
// For the purposes of this sample, we use
// [`std::chrono::steady_clock`](cpp/chrono/steady_clock) ([13]),
// although any other clock will suffice.
//
// On [14], we create a `clock::time_point` representing the point in
// time five seconds from now. To do so, we use `clock::now()` to get
// the current time point and add the duration of `5s` to it. Here we
// have used one of C++14's [duration literal
// suffixes](http://en.cppreference.com/w/cpp/chrono/duration#Literals)
// to representing a duration with the seconds suffix, `s`. The
// `using` directive on [7] is required in order to use these suffixes.
// For C++11, the duration can be constructed manually.
//
// After performing some complex work on [16], we then call
// [`std::this_thread::sleep_until`](cpp/thread/sleep_until) on [18],
// passing it the time point we computed earlier. This blocks the
// current thread until we have reached that time point, ensuring that
// execution continues exactly five seconds after the starting time,
// regardless of how much time the complex work took (unless it took
// more than five seconds).
//
// This technique is most commonly used in a loop to ensure that the
// loop iterates with a fixed time step. Alternatively, if you want to
// sleep for a fixed amount of time, see the [sleep
// sample](/common-tasks/sleep.html).

void some_complex_work() { }

Add fixed time step sample

Add fixed time step sample


#include <iostream>
#include <vector>
#include <thread>
#include <algorithm>
#include <cstdlib>

void accumulator_function2(const std::vector<int> &v, unsigned long long &acm, unsigned int beginIndex, unsigned int endIndex) {
    acm = 0;
    for (unsigned int i = beginIndex; i < endIndex; ++i) {
        acm += v[i];
    }
}

int main() {
    unsigned long long acm1 = 0;
    unsigned long long acm2 = 0;

    std::vector<int> v(1024);
    srand(time(nullptr));
    std::generate(v.begin(), v.end(), [&v]() { return rand() % v.size(); } );

    for_each(begin(v), end(v), [](int i) { std::cout << i << ' '; } );

    std::thread t1(accumulator_function2, std::ref(v), std::ref(acm1), 0, v.size() / 2);
    std::thread t2(accumulator_function2, std::ref(v), std::ref(acm2), v.size() / 2, v.size());

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

    std::cout << "acm1: " << acm1 << std::endl;
    std::cout << "acm2: " << acm2 << std::endl;
    std::cout << "acm1 + acm2: " << acm1 + acm2 << std::endl;

    return 0;
}

Add c++11 thread creation with function pointer. It generates random
vector of 1024 integers and creates two threads to summarize bottom and
top half respectfully.

Compile with:

g++ -std=c++11 thread_function_pointer.cpp -o thread_function_pointer -lpthread


#include "Software/NeuralNet.h"
#include "Software/Backpropagation.h"
#include <iostream>

/*
	This is example code which runs a Backpropagating neural network.
	It is supposed to double any input number.
	This is the example code from the readme of https://github.com/FidoProject/Fido

	To compile, run in terminal:
	fcc linear.cpp
	This will make an executable file a.out which will be this program.

	PS.
	Try tweaking the paramaters of the backprop initialization to make the nerual network more correct
*/

int main() {
	// Creates a neural network with
	// 1 input, 1 output, 2 hidden layers, 4 neurons per hidden layer, and a sigmoid activation function.
	net::NeuralNet neuralNetwork = net::NeuralNet(1, 1, 2, 4, "sigmoid");
	std::vector< std::vector<double> > input = { {1}, {2}, {5}, {6} };
	std::vector< std::vector<double> > correctOutput = { {2}, {4}, {10}, {12} };
	neuralNetwork.setOutputActivationFunction("simpleLinear");

	// Create backpropagation object with
	// a learning rate of 10%, a momentum term of 0.001, an acceptable error level of 5%,
	// and a maximum number of training iterations of 10000
	net::Backpropagation backprop = net::Backpropagation(0.1, 0.001, 0.05, 1000000);
	backprop.trainOnData(&neuralNetwork, input, correctOutput);

	// Cycle through inputs and print the outputs
	for (std::vector<double> current: input) {
		std::vector<double> final = neuralNetwork.getOutput(current);
		std::cout << "Correct answer: " << current[0] << "\tActual answer:" << final[0] << std::endl;
	}
}

Put example code in repo

Put example code in repo


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

#include "gm.h"

#include "SkCanvas.h"
#include "SkTextBlob.h"

namespace skiagm {
class TextBlobBlockReordering : public GM {
public:
    // This gm tests that textblobs translate properly when their draw order is different from their
    // flush order
    TextBlobBlockReordering() { }

protected:
    void onOnceBeforeDraw() override {
        SkTextBlobBuilder builder;

        // make textblob
        // Large text is used to trigger atlas eviction
        SkPaint paint;
        paint.setTextSize(56);
        const char* text = "AB";
        sk_tool_utils::set_portable_typeface(&paint);

        SkRect bounds;
        paint.measureText(text, strlen(text), &bounds);

        SkScalar yOffset = bounds.height();
        sk_tool_utils::add_to_text_blob(&builder, text, paint, 0, yOffset - 30);

        // build
        fBlob.reset(builder.build());
    }

    SkString onShortName() override {
        return SkString("textblobblockreordering");
    }

    SkISize onISize() override {
        return SkISize::Make(kWidth, kHeight);
    }

    // This draws the same text blob 3 times.  The second draw used a different
    // xfer mode so it doens't get batched with the first and third.
    // ultimately thye iwll be flushed in the order first, third, and then second
    void onDraw(SkCanvas* canvas) override {
        canvas->drawColor(sk_tool_utils::color_to_565(SK_ColorGRAY));

        SkPaint paint;
        canvas->translate(10, 40);

        SkRect bounds = fBlob->bounds();
        const int yDelta = SkScalarFloorToInt(bounds.height()) + 20;
        const int xDelta = SkScalarFloorToInt(bounds.width());

        canvas->drawTextBlob(fBlob, 0, 0, paint);

        canvas->translate(SkIntToScalar(xDelta), SkIntToScalar(yDelta));

	// draw a rect where the text should be, and then twiddle the xfermode
        // so we don't batch
        SkPaint redPaint;
        redPaint.setColor(SK_ColorRED);
        canvas->drawRect(bounds, redPaint);
        SkPaint srcInPaint(paint);
        srcInPaint.setXfermodeMode(SkXfermode::kSrcIn_Mode);
        canvas->drawTextBlob(fBlob, 0, 0, srcInPaint);

        canvas->translate(SkIntToScalar(xDelta), SkIntToScalar(yDelta));
        canvas->drawTextBlob(fBlob, 0, 0, paint);
    }

private:
    SkAutoTUnref<const SkTextBlob> fBlob;

    static const int kWidth = 275;
    static const int kHeight = 200;

    typedef GM INHERITED;
};

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

DEF_GM(return new TextBlobBlockReordering;)
}

Create new GM to target translations problems in GrAtlasTextContext

BUG=skia:
GOLD_TRYBOT_URL= https://gold.skia.org/search2?unt=true&query=source_type%3Dgm&master=false&issue=1721833005

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


/*
 * Copyright (c) 2021-2022-2022, Patrick Pelissier
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * + Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 * + Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <set>
#include "m-bptree.h"

BPTREE_DEF(tree_int, 5, int)

// Transform an integer 'i' into a M*LIB base item 'a'
#define TYPE_SET_INT(a, i) (a) = (i)

// Container OPLIST
#define CONT_OPL   BPTREE_OPLIST(tree_int, M_OPL_int())

// C++ Base class of the item in the container
#define BASE_CLASS int

// Transform an integer 'i' into a C++ base item 'a'
#define CLASS_SET_INT(a, i) (a) = (i)

// C++ Container class
#define CONT_CLASS std::set<int>

// Compare the M*LIB container a to the C++ container b
#define CMP_CONT(a, b) cmp_cont(a, b)

// Compate the M*LIB base object to the C++ base object
#define CMP_BASE(a, b) assert( (a) == (b) )

void cmp_cont(const tree_int_t a, const std::set<int> &b)
{
  tree_int_it_t ita;
  tree_int_it(ita, a);
  auto          itb = b.begin();
  while (itb != b.end()) {
    assert(!tree_int_end_p(ita));
    const int *b0 = tree_int_cref(ita);
    const int &b1 = *itb;
    CMP_BASE(*b0, b1);
    itb++;
    tree_int_next(ita);
  }
  assert(tree_int_end_p(ita));
}

#define DEFAULT_NUMBER 1000000

#define push_back insert
#include "check-generic.hpp"

Add check of B+Tree / Set

Add check of B+Tree / Set


// 034. Search for a Range
/**
 * Given a sorted array of integers, find the starting and ending position of a given target value.
 *
 * Your algorithm's runtime complexity must be in the order of O(log n).
 *
 * If the target is not found in the array, return [-1, -1].
 *
 * For example,
 * Given [5, 7, 7, 8, 8, 10] and target value 8,
 * return [3, 4].
 *
 * Tags: Array, Binary Search
 *
 * Similar Problems: (E)First Bad Version
 */

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

using namespace std;

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        vector<int> range;
        range.push_back(-1);
        range.push_back(-1);
        int n = nums.size();
        int left = 0, right = n - 1;
        if ((n == 0) || (nums[left] > target) || (nums[right] < target))
        {
            return range;
        }

        if (nums[left] == nums[right])
        {
            range[0] = 0;
            range[1] = n - 1;
            return range;
        }

        // binary search left: finding the first value >= target
        int mid = 0;
        while (left <= right)
        {
            mid = (left + right) / 2;
            if (target > nums[mid])
            {
                left = mid + 1;
            }
            else
            {
                right = mid - 1;
            }
        }
        range[0] = left;

        // binary search right: finding the last value <= target
        left = 0, right = n - 1;
        while (left <= right)
        {
            mid = (left + right) / 2;
            if (target < nums[mid])
            {
                right = mid - 1;
            }
            else
            {
                left = mid + 1;
            }
        }
        range[1] = right;

        // if first > last, not found
        if (range[0] > range[1])
        {
            range[0] = -1;
            range[1] = -1;
        }

        return range;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    vector<int> nums;
    nums.push_back(5);
    nums.push_back(7);
    nums.push_back(7);
    nums.push_back(8);
    nums.push_back(8);
    nums.push_back(10);
    int target = 10;

    Solution mySolution;
    vector<int> res = mySolution.searchRange(nums, target);
    cout << "[" << res[0] << "," << res[1] << "]" << endl;
    system("pause");

    return 0;
}

Add Solution for Problem 034

Add Solution for Problem 034


// 124. Binary Tree Maximum Path Sum
/**
 * Given a binary tree, find the maximum path sum.
 *
 * For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root.
 *
 * For example:
 * Given the below binary tree,
 *
 *       1
 *      / \
 *     2   3
 * Return 6.
 *
 * Tags: Tree, Depth-first Search
 *
 * Author: Kuang Qin
 */

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

using namespace std;

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

class Solution {
    int curMax;

public:
    int maxPathSum(TreeNode* root) {
        curMax = INT_MIN;
        dfs(root);
        return curMax;
    }

// if we look at each individual nodes, there are only 3 possiblities:
//   a) Left branch:   root->val + left
//   b) Right branch:  root->val + right
//   c) Both branches: root->val + left + right
//
// a) or b): it can be accumulated between different nodes, so we use them as the return value in the recursion
// c):       it can be only a local maximum, so we compare it to the global maximum and keep whichever is larger

    int dfs(TreeNode* root) {
        if (!root) return 0;

        int left  = max(dfs(root->left), 0);    // if left child val < 0, keep only the parent node value
        int right = max(dfs(root->right), 0);   // if right child val < 0, keep only the parent node value
        curMax = max(curMax, root->val + left + right);  // compare the global max to possible local max

        return root->val + max(left, right);    // choose whichever is larger
    }
};

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

Add Solution for Problem 124

Add Solution for Problem 124


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

#include "cling/Interpreter/RuntimeExceptions.h"

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

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

    cling_null_deref_exception::~cling_null_deref_exception() {}

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

Add forgotten to commit file.

Add forgotten to commit file.


/**
 * Longest Common Subsequence:
 * Given two strings, find longest common subsequence between them.
 * https://www.youtube.com/watch?v=NnD96abizww&index=2&list=PLrmLmBdmIlpsHaNTPP_jHHDx_os9ItYXr
 */
 #include <iostream>
 using namespace std;

void print(unsigned int **T, int M, int N) {
	for (int i = 0; i <= M; i++) {
		for (int j = 0; j <= N; j++) {
			cout<<T[i][j]<<" ";
		}
		cout<<endl;
	}
	cout<<endl;
}

int max(int a, int b) {
	return a > b ? a : b;
}

int findCommonSubsequence(char str1[], char str2[], int M, int N) {
	unsigned int solution = 0;
	unsigned int **T = new unsigned int*[M+1];
	for (int i = 0; i <= M; i++)
		T[i] = new unsigned int[N+1];
	//print(T, M, N);
	for (int i = 1; i <= M; i++) {
		for (int j = 1; j <= N; j++) {
			if (str1[j-1] == str2[i-1]) {
				T[i][j] = T[i-1][j-1] + 1;
			}
			else
				T[i][j] = max(T[i-1][j], T[i][j-1]);
		}
	}
	print(T, M, N);
	solution = T[M][N];
	for (int i = 0; i <= M; i++)
		delete [] T[i];
	delete [] T;
	return solution;
}

 int main() {
 	char str1[] = {'a', 'b', 'e', 'l', 'k', 'q', 'd'};
 	int N = sizeof (str1)/sizeof(str1[0]);
 	char str2[] = {'b','l','a','q','m', 'd', 'b'};
 	int M = sizeof (str2)/sizeof(str2[0]);

 	cout<<findCommonSubsequence(str1, str2, M, N)<<endl;
 	return 0;
 }

Implement longest common subsequence length

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


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

#include "chrome/browser/ui/crypto_module_password_dialog.h"

#include "base/logging.h"

namespace chrome {

void UnlockSlotsIfNecessary(const net::CryptoModuleList& modules,
                            CryptoModulePasswordReason reason,
                            const std::string& host,
                            const base::Closure& callback) {
  // TODO(bulach): implement me.
  NOTREACHED();
}

void UnlockCertSlotIfNecessary(net::X509Certificate* cert,
                               CryptoModulePasswordReason reason,
                               const std::string& host,
                               const base::Closure& callback) {
  // TODO(bulach): implement me.
  NOTREACHED();
}

}  // namespace chrome

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

#include "chrome/browser/ui/crypto_module_password_dialog.h"

#include "base/logging.h"

namespace chrome {

void UnlockSlotsIfNecessary(const net::CryptoModuleList& modules,
                            CryptoModulePasswordReason reason,
                            const std::string& host,
                            gfx::NativeWindow parent,
                            const base::Closure& callback) {
  // TODO(bulach): implement me.
  NOTREACHED();
}

void UnlockCertSlotIfNecessary(net::X509Certificate* cert,
                               CryptoModulePasswordReason reason,
                               const std::string& host,
                               gfx::NativeWindow parent,
                               const base::Closure& callback) {
  // TODO(bulach): implement me.
  NOTREACHED();
}

}  // namespace chrome

Fix the linux redux build.

Fix the linux redux build.

Broken at https://codereview.chromium.org/71013002 which modified
crypto_module_password_dialog.h and crypto_module_password_dialog_nss.cc but
not crypto_module_password_dialog_openssl.cc

BUG=None

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

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


/*
 * Copyright 2014-2015 CyberVision, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <boost/test/unit_test.hpp>

#include <thread>

#include "kaa/utils/KaaTimer.hpp"

namespace kaa {

std::int32_t counter = 0;

void increment(void) { counter++; }

void resetCounter() { counter = 0; }

BOOST_AUTO_TEST_SUITE(KaaTimerTestSuite)

BOOST_AUTO_TEST_CASE(SuccessTimerTriggerTest)
{
    std::size_t timeToWait = 4;
    KaaTimer<void (void)> timer;
    timer.start(timeToWait, [] { increment(); });

    std::this_thread::sleep_for(std::chrono::seconds(timeToWait / 2));

    BOOST_CHECK_EQUAL(counter, 0);

    std::this_thread::sleep_for(std::chrono::seconds(timeToWait / 2 + 1));

    BOOST_CHECK_EQUAL(counter, 1);
    resetCounter();
}

BOOST_AUTO_TEST_CASE(StopTimerTest)
{
    std::size_t timeToWait = 4;
    KaaTimer<void (void)> timer;
    timer.start(timeToWait, [] { increment(); });

    std::this_thread::sleep_for(std::chrono::seconds(timeToWait / 2));

    BOOST_CHECK_EQUAL(counter, 0);
    timer.stop();

    std::this_thread::sleep_for(std::chrono::seconds(timeToWait / 2 + 1));

    BOOST_CHECK_EQUAL(counter, 0);
    resetCounter();
}

BOOST_AUTO_TEST_SUITE_END()

}

Add unit test for timer implementation.

KAA-533: Add unit test for timer implementation.


#include <Rcpp.h>
#include "s2/s2latlng.h"
#include "s2/s2cellid.h"

//' @title
//' cell_center
//' @description
//' Get center of S2 cell containing a specified point
//'
//' @param lat latitude of interest (between -90 and +90)
//'
//' @param lng longitude of interest (between -180 and +180)
//'
//' @details
//' \code{cell_center} takes a single (lat,lng) point on the sphere, finds the
//' S2 leaf cell that contains this point and returns the center of this cell.
//' In S2 leaf cells have a very fine resolution, so the output is expected to
//' be very close to the input, and differences are typically on something like
//' the 5th decimal place.
//'
//' @examples
//' cell_center(57.0139595, 9.988967)
//'
//' @export
//[[Rcpp::export]]
Rcpp::NumericVector cell_center(double lat, double lng) {
  S2LatLng p = S2LatLng::FromDegrees(lat, lng);
  S2CellId id = S2CellId::FromLatLng(p);
  S2LatLng center = id.ToLatLng();
  Rcpp::NumericVector rslt(2);
  rslt[0] = center.lat().degrees();
  rslt[1] = center.lng().degrees();
  return rslt;
}

Add missing C++ source file.

Add missing C++ source file.


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

using namespace Halide;

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

    Func f, g;

    f(x, y) = x;
    g(x, y) = f(x-1, y+1) + f(x, y-1);
    f.store_root().compute_at(g, y).fold_storage(y, 2);

    Image<int> im = g.realize(100, 1000);

    printf("Should have gotten a bad fold!\n");
    return -1;
}

Add test for a bad fold.

Add test for a bad fold.


// Chapter 25, Try This 3: get bits example to work, try a few values

#include<iostream>
#include<iomanip>
#include<bitset>

using namespace std;

int main()
{
    int i;
    while (cin>>i)
        cout << dec << i << " == "
        << hex << "0x" << setw(8) << setfill('0') << i << " == "
        << bitset<8*sizeof(int)>(i) << '\n';
}

Add Chapter 25, Try This 3

Add Chapter 25, Try This 3


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

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

// Debugger is flaky on browser_tests on Windows: crbug.com/234166.
#if defined(OS_WIN)
#define MAYBE(x) DISABLED_##x
#else
#define MAYBE(x) x
#endif

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE(Debugger)) {
  ASSERT_TRUE(RunExtensionTest("debugger")) << message_;
}

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

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

// Debugger is flaky on browser_tests on Windows, Linux, and Chrome OS:
// crbug.com/234166.
#if defined(OS_WIN) || defined(OS_LINUX) || defined(OS_CHROMEOS)
#define MAYBE(x) DISABLED_##x
#else
#define MAYBE(x) x
#endif

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE(Debugger)) {
  ASSERT_TRUE(RunExtensionTest("debugger")) << message_;
}

Disable flaky ExtensionApiTest.Debugger on Linux and Chrome OS.

BUG=380082
TBR=kaznacheev
R=kaznacheev
NOTREECHECKS=true
NOTRY=true

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

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


#include <stdio.h>
#include <string>

class Shape {
 public:
  virtual void draw() = 0;
};

class Rectangle : public Shape {
 public:
  void draw() override { printf("Drawing Rectangle \n"); }
};

class Square : public Shape {
 public:
  void draw() override { printf("Drawing Square \n"); }
};

class Circle : public Shape {
 public:
  void draw() override { printf("Drawing Circle \n"); }
};

class ShapeFactory {
 public:
  Shape* GetShape(std::string str) {
    if (str.find("Rectangle") != std::string::npos) {
      return new Rectangle();
    } else if (str.find("Square") != std::string::npos) {
      return new Square();
    } else if (str.find("Circle") != std::string::npos) {
      return new Circle();
    } else {
      return nullptr;
    }
  }
};

int main(int argc, char const* argv[]) {
  ShapeFactory shapeFactory;
  Shape* shape1 = shapeFactory.GetShape("Rectangle");
  shape1->draw();
  Shape* shape2 = shapeFactory.GetShape("Square");
  shape2->draw();
  Shape* shape3 = shapeFactory.GetShape("Circle");
  shape3->draw();

  return 0;
}

Add Factory method design pattern.

Add Factory method design pattern.


class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int nlen = 1, n = nums.size();;
        if(n <= 1) return n;
        for(int i=1; i < nums.size();i++){
            if(nums[i] != nums[i-1]){
                nums[nlen++] = nums[i];
            }
        }
        return nlen;
    }
};

Remove Duplicates from Sorted Array

Remove Duplicates from Sorted Array


//
//  main.cpp
//  backToProblemSolving
//
//  Created by Khaled Abdelfattah on 6/27/17.
//  Copyright © 2017 Khaled Abdelfattah. All rights reserved.
//

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
#define MAX 1000000000
#define BASE1 23
#define BASE2 31
#define MOD1 1000000007
#define MOD2 217645177
#define EPS 1e-6
#define SIZE 20005

int n, m;
vector<pair<pair<int, int>, int>> edges;
int bestDist[SIZE];

void Bellman_Ford (int s) {
    memset(bestDist, INT_MAX, n + 1);
    bestDist[s] = 0;
    for (int i = 0; i < n - 1; i ++) {
        bool relaxed = false;
        for (int j = 0; j < edges.size(); j ++) {
            int from = edges[j].first.first, to = edges[j].first.second;
            int dist = edges[j].second;
            if (bestDist[from] + dist < bestDist[to]) {
                bestDist[to] = bestDist[from] + dist;
                relaxed = true;
            }
        }
        if (!relaxed)
            break;
    }
}

bool hasNegCycle () {
    for (int j = 0; j < edges.size(); j ++) {
        int from = edges[j].first.first, to = edges[j].first.second;
        int dist = edges[j].second;
        if (bestDist[from] + dist < bestDist[to]) {
            return true;
        }
    }
    return false;
}
int main() {
    n = 6;
    m = 5;
    edges.push_back(make_pair(make_pair(1, 2), -2));
    edges.push_back(make_pair(make_pair(1, 3), 5));
    edges.push_back(make_pair(make_pair(2, 3), -2));
    edges.push_back(make_pair(make_pair(3, 4), 7));
    edges.push_back(make_pair(make_pair(4, 5), -12));
    Bellman_Ford(1);
    for (int i = 1; i <= n; i ++)
        cout << bestDist[i] << " ";
    cout << endl;
    cout << hasNegCycle();
    return 0;
}

Add Bellman Ford Algorithm to graph search in c++


#include <iostream>
using namespace std;

/*
This represents the structure of the node of the Binary Search Tree.
*/

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

/*
This function adds new data into binary search tree (BST).
It takes root of the tree as parameter along with the new data to be inserted.
*/

node * add(node * root,int val)
{
    if(root == NULL)
    {
        node * newNode = new node;
        newNode->data = val;
        newNode->left=NULL;
        newNode->right=NULL;
        return newNode;
    }
    if(val > root->data)
        root->right=add(root->right,val);
    else
        root->left=add(root->left,val);
    return root;
}

/*
This function traverses the second tree and adds its nodes to tree 1.
It takes roots of tree 1 and tree 2 as parameters.
*/

node * merge(node * root1,node * root2)
{
    if(root2==NULL)
        return root1;
    merge(root1,root2->left);
    add(root1,root2->data);
    merge(root1,root2->right);
}

/*
This function prints the inorder traversal of the BST thus printing
a list of entered values in ascending order.It takes the root node as a parameter.
*/

void print_inorder(node *root)
{
    if(root==NULL)
    return;
    print_inorder(root->left);
    cout<<root->data<<" ";
    print_inorder(root->right);

}

int main()
{
    node * root1 =NULL;
    node * root2 =NULL;

    //  Insertion into tree1
    root1=add(root1,12);
    root1=add(root1,30);
    root1=add(root1,2);
    root1=add(root1,15);
    root1=add(root1,6);
    root1=add(root1,54);
    root1=add(root1,27);

    //Printing result
    print_inorder(root1);
    cout<<"\n";

    //  Insertion into tree2
    root2=add(root2,30);
    root2=add(root2,23);
    root2=add(root2,12);
    root2=add(root2,43);
    root2=add(root2,33);
    root2=add(root2,62);
    root2=add(root2,31);

    //Printing result
    print_inorder(root2);
    cout<<"\n";

    //  Merging the two trees

    merge(root1,root2);

    //  Printing merged tree

    print_inorder(root1);

    return 0;
}

Add merging of two Binary Search Trees

Add merging of two Binary Search Trees


#include "ec_gen.h"

Handle<ScopedEVP_PKEY> EC_generate(int &nidEc) {
	LOG_FUNC();

	Handle<ScopedEVP_PKEY> pkey;

	ScopedEC_KEY eckey(EC_KEY_new_by_curve_name(nidEc));

	if (eckey.isEmpty()) {
		THROW_OPENSSL("EC_KEY_new_by_curve_name");
	}
	if (!EC_KEY_generate_key(eckey.Get())) {
		THROW_OPENSSL("EC_KEY_generate_key");
	}

	pkey = Handle<ScopedEVP_PKEY>(new ScopedEVP_PKEY(EVP_PKEY_new()));

	if (EVP_PKEY_assign_EC_KEY(pkey->Get(), eckey.Get()) != 1) {
		THROW_OPENSSL("EVP_PKEY_assign_EC_KEY");
	}

	eckey.unref();

	return pkey;
}

#include "ec_gen.h"

Handle<ScopedEVP_PKEY> EC_generate(int &nidEc) {
	LOG_FUNC();

	Handle<ScopedEVP_PKEY> pkey;

	ScopedEC_KEY eckey(EC_KEY_new_by_curve_name(nidEc));

	if (eckey.isEmpty()) {
		THROW_OPENSSL("EC_KEY_new_by_curve_name");
	}
	if (!EC_KEY_generate_key(eckey.Get())) {
		THROW_OPENSSL("EC_KEY_generate_key");
	}

	/**
	 * Current flag is needed to get a CHROME like pkcs8, spki output
	 */
	EC_GROUP *group = (EC_GROUP *)EC_KEY_get0_group(eckey.Get());
	EC_GROUP_set_asn1_flag(group, OPENSSL_EC_NAMED_CURVE);

	pkey = Handle<ScopedEVP_PKEY>(new ScopedEVP_PKEY(EVP_PKEY_new()));

	if (EVP_PKEY_assign_EC_KEY(pkey->Get(), eckey.Get()) != 1) {
		THROW_OPENSSL("EVP_PKEY_assign_EC_KEY");
	}

	eckey.unref();

	return pkey;
}

Support CHROME like format for pkcs8, spki EC keys


class Solution {
public:
    bool checkString(string s) {
        bool b_found = false;
        for (const auto& c : s) {
            if (c == 'a' && b_found)
                return false;
            if (c == 'b')
                b_found = true;
        }
        return true;
    }
};

Check if All A's Appears Before All B's

Check if All A's Appears Before All B's


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

#include "build/build_config.h"
#include "chrome/browser/first_run/upgrade_util.h"

// The entry point for all invocations of Chromium, browser and renderer. On
// windows, this does nothing but load chrome.dll and invoke its entry point in
// order to make it easy to update the app from GoogleUpdate. We don't need
// that extra layer with on linux.

extern "C" {
int ChromeMain(int argc, const char** argv);
}

int main(int argc, const char** argv) {
  int return_code = ChromeMain(argc, argv);

#if defined(OS_LINUX)
  // Launch a new instance if we're shutting down because we detected an
  // upgrade in the persistent mode.
  upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded();
#endif

  return return_code;
}

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

#include "build/build_config.h"
#include "chrome/browser/first_run/upgrade_util.h"

// The entry point for all invocations of Chromium, browser and renderer. On
// windows, this does nothing but load chrome.dll and invoke its entry point in
// order to make it easy to update the app from GoogleUpdate. We don't need
// that extra layer with on linux.

#if defined(ADDRESS_SANITIZER) && defined(GOOGLE_CHROME_BUILD)
const char *kAsanDefaultOptions = "quarantine_size=1048576";

// Override the default ASan options for the Google Chrome executable.
// __asan_default_options should not be instrumented, because it is called
// before ASan is initialized.
extern "C"
__attribute__((no_address_safety_analysis))
const char *__asan_default_options() {
  return kAsanDefaultOptions;
}
#endif

extern "C" {
int ChromeMain(int argc, const char** argv);
}

int main(int argc, const char** argv) {
  int return_code = ChromeMain(argc, argv);

#if defined(OS_LINUX)
  // Launch a new instance if we're shutting down because we detected an
  // upgrade in the persistent mode.
  upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded();
#endif

  return return_code;
}

Set the default ASan options for the Official Chrome build.

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

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


#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include "outputtrack.h"

int main(int argc, char** argv)
{
	FILE* fpInput = fopen("../output.bin", "rb");
	if (fpInput == NULL)
	{
		printf("Error opening input file\n");
		exit(1);
	}

	//Loop over all events in the input file.
	//Number of events is not stored int the file, but we just read until we reach the end of file.
	//All values stored in the file are either int or float, so 32 bit.
	//Thus, we do not need to care about alignment. The same data structures must be used again for reading the file.
	int nEvents = 0;
	std::vector<unsigned int> ClusterIDs;
	while (!feof(fpInput))
	{
		int numTracks; //Must be int!
		OutputTrack track;
		fread(&numTracks, sizeof(numTracks), 1, fpInput);
		printf("Event: %d, Number of tracks: %d\n", nEvents, numTracks);
		for (int iTrack = 0;iTrack < numTracks;iTrack++)
		{
			fread(&track, sizeof(track), 1, fpInput);
			printf("Track %d Parameters: Alpha %f, X %f, Y %f, Z %f, SinPhi %f, DzDs %f, Q/Pt %f, Number of clusters %d, Fit OK %d\n", iTrack, track.Alpha, track.X, track.Y, track.Z, track.SinPhi, track.DzDs, track.QPt, track.NClusters, track.FitOK);
			if (track.NClusters > ClusterIDs.size()) ClusterIDs.resize(track.NClusters);
			fread(&ClusterIDs[0], sizeof(ClusterIDs[0]), track.NClusters, fpInput);
			printf("Cluster IDs:");
			for (int iCluster = 0;iCluster < track.NClusters;iCluster++)
			{
				printf(" %d", ClusterIDs[iCluster]);
			}
			printf("\n");
		}

		nEvents++;
	}
	fclose(fpInput);
}

Add example to read tracks from binary output file


// Test that the -c flag works.
// RUN: llvmc -c %s -o %t.o
// RUN: llvmc --linker=c++ %t.o -o %t
// RUN: %abs_tmp | grep hello
// XFAIL: vg
#include <iostream>

int main() {
    std::cout << "hello" << '\n';
}

Add a test for the -c flag.

llvmc: Add a test for the -c flag.

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


// 19. Remove Nth Node From End of List
/**
 * Given a linked list, remove the nth node from the end of list and return its head.
 *
 * For example,
 *
 * Given linked list: 1->2->3->4->5, and n = 2.
 *
 * After removing the second node from the end, the linked list becomes 1->2->3->5.
 *
 * Note:
 * Given n will always be valid.
 * Try to do this in one pass.
 *
 * Tags: Linked List, Two Pointers
 *
 * Author: Kuang Qin
 */

#include <iostream>

using namespace std;

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

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        // use a dummy node to mark the head of the list
        ListNode dummy(0);
        dummy.next = head;

        // set two pointer difference by n
        ListNode *slow = &dummy, *fast = slow;
        for (int i = 0; i < n; i++) {
            fast = fast->next;
        }

        // move fast to the last element
        // find the node to be removed: slow->next
        while (fast->next != NULL) {
            slow = slow->next;
            fast = fast->next;
        }

        // remove the node
        fast = slow->next;
        slow->next = fast->next;
        delete fast;

        return dummy.next;
    }
};

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

    return 0;
}

Add Solution for 019 Remove Nth Node From End of List