class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int cur = 0, count = 0, total = nums.size();
        for (auto iter = nums.begin(); iter != nums.end();) {
            if (iter == nums.begin()) {
                cur = *iter;
                count = 1;
                ++iter;
            } else {
                if (*iter == cur) {
                    if (count == 2) {
                        nums.erase(iter);
                        --total;
                    } else {
                        ++count;
                        ++iter;
                    }
                } else {
                    cur = *iter;
                    count = 1;
                    ++iter;
                }
            }
        }
        return total;
    }
};

Remove Duplicates from Sorted Array II

Remove Duplicates from Sorted Array II


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

typedef long long ll;

ll sol(ll n, int m) {
    ll a, b, c, d, r;
    a = 1; b = 0; c = 0; d = 1;
    while (n) {
        if (n&1) {
            r = ((d*b) + (c*a)) % m;
            b = (d*(b+a) + (c*b)) % m;
            a = r;
        }
        r = (c*c + d*d) % m;
        d = (d * (2*c + d)) % m;
        c = r;
        n >>= 1;
    }
    return (a+b) % m;
}

int main() {
    ll n;
    int b, r, c = 0;
    while (scanf("%lld %d", &n, &b) && (n || b)) {
        //r = ((sol(n, b) % b) + b) % b;
        r = (((2*sol(n, b) - 1) % b) + b) % b;
        printf("Case %d: %lld %d %d\n", ++c, n, b, r);
    }
    return 0;
}

Add quantas chamadas recursivas to cadernaveis

Signed-off-by: Luiz Reis <1c715962a18009093f7c9aeeb7b25a67803831c9@outlook.com>


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

extern "C" {
#if defined(GLES2_CONFORM_SUPPORT_ONLY)
#include "gpu/gles2_conform_support/gtf/gtf_stubs.h"
#else
#include "third_party/gles2_conform/GTF_ES/glsl/GTF/Source/eglNative.h"
#endif

GTFbool GTFNativeCreatePixmap(EGLNativeDisplayType nativeDisplay,
                              EGLDisplay eglDisplay, EGLConfig eglConfig,
                              const char *title, int width, int height,
                              EGLNativePixmapType *pNativePixmap) {
  return GTFtrue;
}

void GTFNativeDestroyPixmap(EGLNativeDisplayType nativeDisplay,
                            EGLNativePixmapType nativePixmap) {
}

}  // extern "C"

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

extern "C" {
#if defined(GLES2_CONFORM_SUPPORT_ONLY)
#include "gpu/gles2_conform_support/gtf/gtf_stubs.h"
#else
#include "third_party/gles2_conform/GTF_ES/glsl/GTF/Source/eglNative.h"
#endif

GTFbool GTFNativeCreatePixmap(EGLNativeDisplayType nativeDisplay,
                              EGLDisplay eglDisplay, EGLConfig eglConfig,
                              const char *title, int width, int height,
                              EGLNativePixmapType *pNativePixmap) {
  return GTFtrue;
}

void GTFNativeDestroyPixmap(EGLNativeDisplayType nativeDisplay,
                            EGLNativePixmapType nativePixmap) {
}

EGLImageKHR GTFCreateEGLImageExternal(
    int width, int height, int format,
    float r, float g, float b, float a, void** resource) {
  return (EGLImageKHR)NULL;
}

void GTFDestroyEGLImageExternal(EGLImageKHR image, void* resource) {
}

const int* GTFQueryFormatsEGLImageExternal(void) {
  return NULL;
}

GTFbool GTFIsAlphaFormatEGLImageExternal(int format) {
  return GTFfalse;
}

}  // extern "C"

Add a few stubs so we can link the latest OpenGL ES 2.0 conformance tests

BUG=83382

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

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


// Test on debug info to make sure that anon typedef info is emitted.
// RUN: %llvmgcc -S --emit-llvm -x c++ -g %s -o - | grep composite
typedef struct { int a; long b; } foo;
foo x;

Test case for llvm-gcc rev. 64648.

Test case for llvm-gcc rev. 64648.

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


// test cases for rule CWE-611

#include "tests.h"

// ---

typedef unsigned int XMLCh;

class XMLUni
{
public:
	static const XMLCh fgXercesDisableDefaultEntityResolution[];
};

class SAX2XMLReader
{
public:
	void setFeature(const XMLCh *feature, bool value);
	void parse(const InputSource &data);
};

class XMLReaderFactory
{
public:
	static SAX2XMLReader *createXMLReader();
};

// ---

void test3_1(InputSource &data) {
	SAX2XMLReader *p = XMLReaderFactory::createXMLReader();

	p->parse(data); // BAD (parser not correctly configured) [NOT DETECTED]
}

void test3_2(InputSource &data) {
	SAX2XMLReader *p = XMLReaderFactory::createXMLReader();

	p->setFeature(XMLUni::fgXercesDisableDefaultEntityResolution, true);
	p->parse(data); // GOOD
}

SAX2XMLReader *p_3_3 = XMLReaderFactory::createXMLReader();

void test3_3(InputSource &data) {
	p_3_3->parse(data); // BAD (parser not correctly configured) [NOT DETECTED]
}

SAX2XMLReader *p_3_4 = XMLReaderFactory::createXMLReader();

void test3_4(InputSource &data) {
	p_3_4->setFeature(XMLUni::fgXercesDisableDefaultEntityResolution, true);
	p_3_4->parse(data); // GOOD
}

SAX2XMLReader *p_3_5 = XMLReaderFactory::createXMLReader();

void test3_5_init() {
	p_3_5->setFeature(XMLUni::fgXercesDisableDefaultEntityResolution, true);
}

void test3_5(InputSource &data) {
	test3_5_init();
	p_3_5->parse(data); // GOOD
}

Add test cases for SAX2XMLReader.

C++: Add test cases for SAX2XMLReader.


/*
 * isr.c:
 *	Wait for Interrupt test program - ISR method
 *
 *	How to test:
 *	  Use the SoC's pull-up and pull down resistors that are avalable
 *	on input pins. So compile & run this program (via sudo), then
 *	in another terminal:
 *		gpio mode 0 up
 *		gpio mode 0 down
 *	at which point it should trigger an interrupt. Toggle the pin
 *	up/down to generate more interrupts to test.
 *
 * Copyright (c) 2013 Gordon Henderson.
 ***********************************************************************
 * This file is part of wiringPi:
 *	https://projects.drogon.net/raspberry-pi/wiringpi/
 *
 *    wiringPi is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU Lesser General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    wiringPi is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public License
 *    along with wiringPi.  If not, see <http://www.gnu.org/licenses/>.
 ***********************************************************************
 */

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <wiringPi.h>

// What GPIO input are we using?
//	This is a wiringPi pin number

#define	BUTTON_PIN	0

// globalCounter:
//	Global variable to count interrupts
//	Should be declared volatile to make sure the compiler doesn't cache it.

static volatile int globalCounter = 0 ;

void fallingEdge(void)
{
    ++globalCounter ;
    fprintf("fallingEdge, %d\n", globalCounter);
}

/*
 *********************************************************************************
 * main
 *********************************************************************************
 */

int main (void)
{
    int myCounter = 0 ;

    if (wiringPiSetup () < 0)
    {
        fprintf (stderr, "Unable to setup wiringPi: %s\n", strerror (errno)) ;
        return 1 ;
    }

    // Set the button pin to input mode
    pinMode(BUTTON_PIN, INPUT);
    // Set the pull up resistor to up to fix it at 3.3V so it reads high until button is pressed
    pullUpDnControl(BUTTON_PIN, PUD_UP);

    // Register the interrupt callback function
    if (wiringPiISR (BUTTON_PIN, INT_EDGE_FALLING, &fallingEdge) < 0) {
        fprintf (stderr, "Unable to setup ISR: %s\n", strerror (errno)) ;
        return 1 ;
    }

    for (;;)
    {
        printf ("Waiting ... ") ; fflush (stdout) ;

        while (myCounter == globalCounter)
            delay (100) ;

        printf (" Done. counter: %5d\n", globalCounter) ;
        myCounter = globalCounter ;
    }

    return 0 ;
}

Add a pin interrupt test

Add a pin interrupt test


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

using namespace Halide;

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

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

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

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

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

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

Add test to check implicit upcasting of float16_t works.

Former-commit-id: 4516e4579445ff475b4e040b0c9834e86b14c1eb


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

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

namespace base {
namespace android {

TEST(SysUtils, AmountOfPhysicalMemory) {
  // Check that the RAM size reported by sysconf() matches the one
  // computed by base::SysInfo::AmountOfPhysicalMemory().
  size_t sys_ram_size =
      static_cast<size_t>(sysconf(_SC_PHYS_PAGES) * PAGE_SIZE);
  EXPECT_EQ(sys_ram_size, SysInfo::AmountOfPhysicalMemory());
}

}  // namespace android
}  // namespace base

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

#include <unistd.h>

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

namespace base {
namespace android {

TEST(SysUtils, AmountOfPhysicalMemory) {
  // Check that the RAM size reported by sysconf() matches the one
  // computed by base::SysInfo::AmountOfPhysicalMemory().
  size_t sys_ram_size =
      static_cast<size_t>(sysconf(_SC_PHYS_PAGES) * PAGE_SIZE);
  EXPECT_EQ(sys_ram_size,
            static_cast<size_t>(SysInfo::AmountOfPhysicalMemory()));
}

}  // namespace android
}  // namespace base

Fix comparison between signed and unsigned integer expressions.

Only see on internal bots.

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

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


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


#include <stdio.h>

int main(void)
{
    int sum = 0, count = 0;

    do
    {
        int num;

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

        sum += (++count % 2 == 1) ? num : -num;
    }
    while(sum != 0);

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

    return 0;
}

Add a solution of prob 1

Add a solution of prob 1


#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>

#define FPGA_MANAGER_BASE 0xFF706000
#define FPGA_GPO_OFFSET 0x10
#define FPGA_GPI_OFFSET 0x14

int main()
{
    int dev_mem = open("/dev/mem", O_RDWR);

    if(dev_mem == 0) {
        perror("open");
        exit(EXIT_FAILURE);
    }

    unsigned char *mem = (unsigned char *)mmap(0, 64, PROT_READ | PROT_WRITE, /* MAP_NOCACHE | */ MAP_SHARED , dev_mem, FPGA_MANAGER_BASE);

    if(mem == 0) {
        perror("mmap");
        exit(EXIT_FAILURE);
    }

    volatile unsigned long *gpo = (unsigned long*)(mem + FPGA_GPO_OFFSET);
    volatile unsigned long *gpi = (unsigned long*)(mem + FPGA_GPI_OFFSET);

    printf("gpi = 0x%08lX\n", *gpi);
    *gpo = 0xCAFEBABE;

    if(1) {
        long int i = 0;
        while(1) *gpo = i++;
    }

    exit(EXIT_SUCCESS);
}

Add ARM-to-FPGA 32-bit raw I/O example

Add ARM-to-FPGA 32-bit raw I/O example


/**
 * Copyright (c) 2016-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <getopt.h>

#include "DexCommon.h"

void print_usage() {
  fprintf(stderr, "Usage: dexgrep <classname> <dexfile 1> <dexfile 2> ...\n");
}

int main(int argc, char* argv[]) {
  bool files_only = false;
  char c;
  static const struct option options[] = {
    { "files-without-match", no_argument, nullptr, 'l' },
  };
  while ((c = getopt_long(
            argc,
            argv,
            "hl",
            &options[0],
            nullptr)) != -1) {
    switch (c) {
      case 'l':
        files_only = true;
        break;
      case 'h':
        print_usage();
        return 0;
      default:
        print_usage();
        return 1;
    }
  }

  if (optind == argc) {
    fprintf(stderr, "%s: no dex files given\n", argv[0]);
    print_usage();
    return 1;
  }

  const char* search_str = argv[optind];

  for (int i = optind + 1; i < argc; ++i) {
    const char* dexfile = argv[i];
    ddump_data rd;
    open_dex_file(dexfile, &rd);

    auto size = rd.dexh->class_defs_size;
    for (uint32_t j = 0; j < size; j++) {
      dex_class_def* cls_def = rd.dex_class_defs + j;
      char* name = dex_string_by_type_idx(&rd, cls_def->typeidx);
      if (strstr(name, search_str) != nullptr) {
        if (files_only) {
          printf("%s\n", dexfile);
        } else {
          printf("%s: %s\n", dexfile, name);
        }
      }
    }
  }
}

Add dexgrep tool -- grep for class definitions

Summary:
Often, I don't want to dexdump an entire APK -- just the dex(es) that
contain the classes I'm interested in. This makes it easy to figure out which
dexes are of interest.

Reviewed By: bertmaher

Differential Revision: D4575313

fbshipit-source-id: 4212a6d16312895a0a2535a11dcbfb9c1ca1163d


// Chapter 21, Try This 3: define a vector<Record>, initialise it with four
// records of your choice, and compute their total price using the functions
// given

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

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

struct Record {
    Record(double up, int un) : unit_price(up), units(un) { }
    double unit_price;
    int units;  // number of units sold
};

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

double price(double v, const Record& r)
{
    return v + r.unit_price * r.units;  // calculate price and accumulate
}

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

void f(const vector<Record>& vr)
{
    double total = accumulate(vr.begin(),vr.end(),0.0,price);
    cout << "Total is " << total << "\n";
}

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

int main()
try {
    Record rec1 = Record(10.9,15);
    Record rec2 = Record(25.5,3);
    Record rec3 = Record(101,75);
    Record rec4 = Record(5.33,27);
    vector<Record> vr;
    vr.push_back(rec1);
    vr.push_back(rec2);
    vr.push_back(rec3);
    vr.push_back(rec4);
    f(vr);
}
catch (Range_error& re) {
    cerr << "bad index: " << re.index << "\n";
}
catch (exception& e) {
    cerr << "exception: " << e.what() << endl;
}
catch (...) {
    cerr << "exception\n";
}

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

Add Chapter 21, Try This 3

Add Chapter 21, Try This 3


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

#include <ews/ews.hpp>
#include <ews/ews_test_support.hpp>
#include <exception>
#include <iostream>
#include <ostream>
#include <stdlib.h>
#include <string>

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

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

        ews::distinguished_folder_id inbox = ews::standard_folder::inbox;
        ews::distinguished_folder_id trash =
            ews::standard_folder::deleted_items;

        auto folder_ids = service.find_folder(inbox);
        if (!folder_ids.empty())
        {
            // Move the first folder to the deleted items folder
            auto new_id = service.move_folder(folder_ids.front(), trash);

            // Move the folder back to the inbox,
            // using the newly created folder id
            service.move_folder(new_id, inbox);
        }
    }
    catch (std::exception& exc)
    {
        std::cout << exc.what() << std::endl;
        res = EXIT_FAILURE;
    }

    ews::tear_down();
    return res;
}

Add example for MoveFolder operation

Add example for MoveFolder operation


// Chapter 25, exercise 10: write an example that initializes a PPN, then reads
// and prints each field value, then changes each field value (by assigning to
// the field) and prints the result. Repeat, but store the PPN information in a
// 32-bit unsigned integer and use bit manipulation operators to access the bits
// in the word.

#include<iostream>

using namespace std;

struct PPN {
    unsigned int PFN : 22;
    int : 3;
    unsigned int CCA : 3;
    bool nonreachable : 1;
    bool dirty : 1;
    bool valid : 1;
    bool global : 1;
};

int main()
{
    PPN pn;
    pn.PFN = 0;
    pn.CCA = 0;
    pn.nonreachable = 0;
    pn.dirty = 0;
    pn.valid = 0;
    pn.global = 0;
    cout << "PFN: " << pn.PFN << '\n'
        << "CCA: " << pn.CCA << '\n'
        << "nonreachable: " << pn.nonreachable << '\n'
        << "dirty: " << pn.dirty << '\n'
        << "valid: " << pn.valid << '\n'
        << "global: " << pn.global << '\n';
    pn.PFN = 15121;
    pn.CCA = 6;
    pn.nonreachable = 1;
    pn.dirty = 0;
    pn.valid = 0;
    pn.global = 1;
        cout << "\nAfter changing values:\n"
        << "PFN: " << pn.PFN << '\n'
        << "CCA: " << pn.CCA << '\n'
        << "nonreachable: " << pn.nonreachable << '\n'
        << "dirty: " << pn.dirty << '\n'
        << "valid: " << pn.valid << '\n'
        << "global: " << pn.global << '\n';

    unsigned int pni = 0;
    pni = 15121<<10;    // PFN
    pni |= 6<<4;        // CCA
    pni |= 1<<3;        // nonreachable
    pni |= 1;           // global
    cout << "\nUsing an unsigned int:\n"
        << "PFN: " << ((pni>>10)&0x3fffff) << '\n'
        << "CCA: " << ((pni>>4)&0x7) << '\n'
        << "nonreachable: " << ((pni>>3)&1) << '\n'
        << "dirty: " << ((pni>>2)&1) << '\n'
        << "valid: " << ((pni>>1)&1) << '\n'
        << "global: " << (pni&1) << '\n';
}

Add Chapter 25, exercise 10

Add Chapter 25, exercise 10


/**
 * Floyd Warshall's Algorithm for All Pairs shortest path problem
 */
 #include <iostream>
 #include <limits.h>
 #define V 4
 #define INF INT_MAX
 using namespace std;

void print(int array[][V]) {
 	for (int i = 0; i < V; i++) {
 		for (int j = 0; j < V; j++) {
 			if (array[i][j] == INF)
 				cout<<"INF ";
 			else
 				cout<<array[i][j]<<" ";
 		}
 		cout<<endl;
 	}
 }

 void floyd_warshall(int graph[][V]) {
 	int dist[V][V], i, j, k;

 	for (i = 0; i < V; i++)
 		for(j = 0; j < V; j++)
 			dist[i][j] = graph[i][j];

 	for (k = 0; k < V; k++) {
 		for (j = 0; j < V; j++) {
 			for (i = 0; i < V; i++) {
 				if (dist[i][k] != INF && dist[k][j] != INF && dist[i][k] + dist[k][j] < dist[i][j])
 					dist[i][j] = dist[i][k] + dist[k][j];
 			}
 		}
 	}
 	print(dist);
 }

 int main() {
 	int graph[][V] = { {0,   5,  INF, 10},
                        {INF, 0,   3, INF},
                        {INF, INF, 0,   1},
                        {INF, INF, INF, 0}
                  	  };
    cout<<"Input Graph: \n";
    print(graph);
    cout<<"Solution: \n";
    floyd_warshall(graph);
    return 0;
}

Add floyd warshall all pairs shortest path

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


/*
 * Summation of primes
 *
 * The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
 *
 * Find the sum of all the primes below two million.
 */

#include <iostream>
#include <numeric>
#include <vector>

#include "sieve.hpp"

constexpr Long limit = 2'000'000;

int main(int, char **) {
    auto primes = sieve(limit - 1);
    auto sum = std::accumulate(primes.begin(), primes.end(), Long());

    std::cout << "Project Euler - Problem 10: Summation of primes\n\n";
    std::cout << "The sum of all prime numbers below " << limit << " is\n"
              << sum << '\n';
}

Add solution to problem 10.

Add solution to problem 10.


#include <bits/stdc++.h>

using namespace std;

void merge(vector<int>& v, int beg1, int half, int beg2){
    int szL, szR;
    szL = half-beg1+1;
    szR = beg2-half;
    //create auxiliar arrays;
    int left[szL], right[szR];
    for (int i = 0; i < szL; i++)
        left[i] = v[beg1 + i];
    for (int i = 0; i < szR; i++)
        right[i] = v[half + 1 + i];
    //merge aux into v
    int i= 0, j= 0, k= beg1;
    while (i<szL && j<szR)
        v[k++] = (left[i]<right[j])?left[i++]:right[j++];
    while (i < szL)
        v[k++] = left[i++];
    while (j < szR)
        v[k++] = right[j++];
}

void mergeSort(vector<int>& v, int l, int r){
    if (l >= r)
        return;
    int half = l+(r-l)/2;
    mergeSort(v, l, half);
    mergeSort(v, half+1, r);

    merge(v, l, half, r);
}

Add merge sort c++ source code

Add merge sort c++ source code


#include "data.hpp"
#include "graph.hpp"
#include "dag_loop.hpp"
#include <string>
#include <vector>

// We will need two bfs operations to check that there is a path from node A to node B.
namespace graph {
    namespace algorithms {
    } // namespace algorithms

    template <typename Graph>
    bool detect_loop(Graph & g) {
        g.print();
        using graph_type = Graph;
        using Policy = graph::algorithms::BasicPolicy<graph_type>;
        graph::algorithms::LoopDetector<Policy> dfs(g);
        return dfs.traverse();
    }

} // namespace graph

int main() {
    // Has loop
    auto g1 = experiments::directed_graph_with_loop();
    fmt::print("The given graph {}\n", (graph::detect_loop<decltype(g1)>(g1) ? "has a cycle." : "is DAG."));

    // Does not have loop
    auto g2 = experiments::directed_graph();
    fmt::print("The given graph {}\n", graph::detect_loop(g2) ? "has loop." : "is DAG.");
}

Add a DQG cycle detection algorithm.

Add a DQG cycle detection algorithm.


class Solution {
public:
    bool isSumEqual(string firstWord, string secondWord, string targetWord) {
        return (convert(firstWord) + convert(secondWord)) == convert(targetWord);
    }
private:
    int convert(std::string word) {
        int ret = 0, index = 0;
        while (index < word.size() && word[index] == '0') {
            ++index;
        }
        while (index < word.size()) {
            ret *= 10;
            ret += word[index] - 'a';
            ++index;
        }
        return ret;
    }
};

Check if Word Equals Summation of Two Words


// 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 "content/child/file_info_util.h"

#include "base/logging.h"
#include "third_party/WebKit/public/platform/WebFileInfo.h"

namespace content {

void FileInfoToWebFileInfo(const base::File::Info& file_info,
                           blink::WebFileInfo* web_file_info) {
  DCHECK(web_file_info);
  // Blink now expects NaN as uninitialized/null Date.
  if (file_info.last_modified.is_null()) {
    web_file_info->modificationTime = std::numeric_limits<double>::quiet_NaN();
    web_file_info->modificationTimeMS =
        std::numeric_limits<double>::quiet_NaN();
  } else {
    web_file_info->modificationTime = file_info.last_modified.ToJsTime();
    web_file_info->modificationTimeMS = file_info.last_modified.ToJsTime();
  }
  web_file_info->length = file_info.size;
  if (file_info.is_directory)
    web_file_info->type = blink::WebFileInfo::TypeDirectory;
  else
    web_file_info->type = blink::WebFileInfo::TypeFile;
}

static_assert(std::numeric_limits<double>::has_quiet_NaN,
              "should have quiet NaN");

}  // namespace content

// 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 "content/child/file_info_util.h"

#include "base/logging.h"
#include "third_party/WebKit/public/platform/WebFileInfo.h"

namespace content {

void FileInfoToWebFileInfo(const base::File::Info& file_info,
                           blink::WebFileInfo* web_file_info) {
  DCHECK(web_file_info);
  // Blink now expects NaN as uninitialized/null Date.
  if (file_info.last_modified.is_null())
    web_file_info->modificationTime = std::numeric_limits<double>::quiet_NaN();
  else
    web_file_info->modificationTime = file_info.last_modified.ToJsTime();
  web_file_info->length = file_info.size;
  if (file_info.is_directory)
    web_file_info->type = blink::WebFileInfo::TypeDirectory;
  else
    web_file_info->type = blink::WebFileInfo::TypeFile;
}

static_assert(std::numeric_limits<double>::has_quiet_NaN,
              "should have quiet NaN");

}  // namespace content

Upgrade Blink to milliseconds-based last modified filetimes, part 6.

Have content::FileInfoToWebFileInfo() no longer fill in
WebFileInfo::modificationTimeMS; it is now unused by Blink.

Once landed, this lets Blink remove the WebFileInfo field entirely.

This is part 6 in the following patch series,

1: [blink] add WebFileInfo::modificationTimeMS [ https://codereview.chromium.org/873723004/ ]
2: [chromium] fill in modificationTimeMS [ https://codereview.chromium.org/884413002/ ]
3: [blink] make use of modificationTimeMS [ https://codereview.chromium.org/884393002/ ]
4: [chromium] set modificationTime to something msec-based [ https://codereview.chromium.org/862203003/ ]
5: [blink] switch to modificationTime [ https://codereview.chromium.org/882343002/ ]
6: [chromium] *this one* [ https://codereview.chromium.org/890523002/ ]
7: [blink] remove modificationTimeMS [ https://codereview.chromium.org/869613005/ ]

R=jochen
BUG=451747

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

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


//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <deque>

#include "dll_test.hpp"

#include "dll/neural/conv_layer.hpp"
#include "dll/neural/deconv_layer.hpp"
#include "dll/pooling/mp_layer.hpp"
#include "dll/pooling/upsample_layer.hpp"
#include "dll/dbn.hpp"
#include "dll/trainer/stochastic_gradient_descent.hpp"

#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"

TEST_CASE("conv/ae/1", "[dense][dbn][mnist][sgd][ae]") {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::conv_desc<1, 28, 28, 2, 5, 5, dll::activation<dll::function::SIGMOID>>::layer_t,
            dll::mp_layer_3d_desc<2, 24, 24, 1, 2, 2>::layer_t,
            dll::upsample_layer_3d_desc<2, 12, 12, 1, 2, 2>::layer_t,
            dll::deconv_desc<2, 24, 24, 1, 5, 5, dll::activation<dll::function::SIGMOID>>::layer_t
        >, dll::trainer<dll::sgd_trainer>, dll::batch_size<20>>::dbn_t dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 1, 28, 28>>(1000);
    REQUIRE(!dataset.training_images.empty());

    dll_test::mnist_scale(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->display();

    dbn->learning_rate = 0.1;

    auto ft_error = dbn->fine_tune_ae(dataset.training_images, 25);
    std::cout << "ft_error:" << ft_error << std::endl;

    CHECK(ft_error < 0.3);

    auto test_error = dll::test_set_ae(*dbn, dataset.test_images);
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.3);
}

Add convolutional auto encoder unit test


//Some useful equations
int main(){
  //area portion of a circle
  A = pi*r^2 * (theta/(2*pi))
  //area chord of a circle
  A = R * R * acos((R - h)/R) - (R - h) * sqrt(2 * R * h - h * h)
    // h is the height of the chord

}

Add some useful ecuations over a circle.


#include <osgDB/ImageOptions>

using namespace osgDB;

ImageOptions::ImageOptions()
{
    init();
}

ImageOptions::ImageOptions(const std::string& str)
{
    init();
    _str = str;
}

void ImageOptions::init()
{
    _sourceImageSamplingMode = NEAREST;
    _sourceImageWindowMode = ALL_IMAGE;

    _destinationImageWindowMode = ALL_IMAGE;
}

#include <osgDB/ImageOptions>

using namespace osgDB;

ImageOptions::ImageOptions()
{
    init();
}

ImageOptions::ImageOptions(const std::string& str)
{
    init();
    _str = str;
}

void ImageOptions::init()
{
    _sourceImageSamplingMode = NEAREST;
    _sourceImageWindowMode = ALL_IMAGE;

    _destinationImageWindowMode = ALL_IMAGE;

    _destinationDataType = GL_NONE;
    _destinationPixelFormat = GL_NONE;
}

Set default values for datatype & pixelformat.


#include "fastlib/fastlib.h"
#include "fastlib/tree/statistic.h"
#include "general_spacetree.h"
#include "contrib/dongryel/fast_multipole_method/fmm_stat.h"
#include "subspace_stat.h"
#include "cfmm_tree.h"
#include "mlpack/kde/dataset_scaler.h"

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

  fx_init(argc, argv, NULL);

  const char *fname = fx_param_str_req(NULL, "data");
  Matrix dataset;
  data::Load(fname, &dataset);

  int leaflen = fx_param_int(NULL, "leaflen", 30);
  int min_required_ws_index = fx_param_int(NULL, "min_ws_index", 2);

  printf("Constructing the tree...\n");
  fx_timer_start(NULL, "cfmm_tree_build");

  ArrayList<Matrix *> matrices;
  matrices.Init(1);
  matrices[0] = &dataset;

  ArrayList<Vector *> targets;
  const char *target_fname = fx_param_str_req(NULL, "target");

  Matrix target_incoming;

  data::Load(target_fname, &target_incoming);

  Vector target;
  target.Init(target_incoming.n_cols());

  for(index_t i = 0; i < target.length(); i++) {
    target[i] = target_incoming.get(0, i);
  }
  targets.Init(1);
  targets[0] = ⌖

  ArrayList< ArrayList<index_t> > old_from_new;
  ArrayList< ArrayList<proximity::CFmmTree< EmptyStatistic<Matrix> > *> > nodes_in_each_level;
  proximity::CFmmTree<EmptyStatistic<Matrix> > *root;
  root = proximity::MakeCFmmTree
    (matrices, targets, leaflen, min_required_ws_index, 2,
     &nodes_in_each_level, &old_from_new);

  fx_timer_stop(NULL, "cfmm_tree_build");

  for(index_t i = 0; i < nodes_in_each_level.size(); i++) {
    for(index_t j = 0; j < nodes_in_each_level[i].size(); j++) {
      printf("%u ", (nodes_in_each_level[i][j])->node_index());
    }
    printf("\n");
  }

  printf("Finished constructing the tree...\n");

  // Print the tree.
  root->Print();

  // Clean up the memory used by the tree...
  delete root;

  fx_done(fx_root);
  return 0;
}

Test file for CFMM tree added.

Test file for CFMM tree added.


#include "gtest/gtest.h"

#include <typeinfo>

#include "request_message.h"
#include "requests.pb.h"

class TypeVisitor : public traffic::RequestVisitor
{
public:
	enum Type {
		SUMMARY,
		STATISTIC,
		ERROR,
		NOTSET
	};

private:
	Type _t;

protected:
	void visit(traffic::StatisticRequest const &) { _t = STATISTIC; }
	void visit(traffic::SummaryRequest const &) { _t = SUMMARY; }
	void visit(traffic::ErrorRequest const &) { _t = ERROR; }

public:
	TypeVisitor() : _t(NOTSET) { }

	Type visited() const { return _t; }
};

std::string summary_message()
{
	requests::Request req;
	req.set_version(1);

	requests::Summary *summary(req.mutable_summary());
	summary->mutable_range()->set_start(1UL);
	summary->mutable_range()->set_end(2UL);

	summary->add_addresses("peng1");
	summary->add_addresses("peng2");
	summary->add_addresses("peng3");
	summary->add_addresses("peng4");

	return req.SerializeAsString();
}

// Test that basic message serializing work
TEST(MessagesRequest, deserialize_summary_request) {
	std::string bytes(summary_message());

	traffic::RequestMessage::ptr_t msg(
			traffic::RequestMessage::parse_message(bytes.c_str(),
							       bytes.size()));

	ASSERT_EQ(typeid(traffic::SummaryRequest), typeid(*msg));

	TypeVisitor v;
	msg->accept(v);
	ASSERT_EQ(TypeVisitor::SUMMARY, v.visited());

	traffic::SummaryRequest* summary(dynamic_cast<traffic::SummaryRequest*>(msg.get()));

	ASSERT_NE(nullptr, summary);
	EXPECT_EQ(1, summary->range().start());
	EXPECT_EQ(2, summary->range().end());

	ASSERT_EQ(4U, summary->addresses().size());
	EXPECT_EQ("peng1", summary->addresses().at(0));
	EXPECT_EQ("peng2", summary->addresses().at(1));
	EXPECT_EQ("peng3", summary->addresses().at(2));
	EXPECT_EQ("peng4", summary->addresses().at(3));

}

/**
 * Shut down the protobuf library after the tests to make valgrind happy
 */
namespace {

class ShutdownEnvironment : public ::testing::Environment
{
public:
	void TearDown()
	{
		google::protobuf::ShutdownProtobufLibrary();
	}
};

#ifndef NDEBUG
::testing::Environment* const shutdown_env =
	::testing::AddGlobalTestEnvironment(new ShutdownEnvironment);
#endif
}

Add unittests for summary requests

Add unittests for summary requests

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


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        return recur(nums, 0, nums.size()-1);
    }
private:
    TreeNode* recur(std::vector<int>& nums, int begin, int end) {
        if (begin > end) {
            return nullptr;
        }
        int mid = (begin + end) / 2;
        TreeNode* root = new TreeNode{nums[mid]};
        root->left = recur(nums, begin, mid-1);
        root->right = recur(nums, mid+1, end);
        return root;
    }
};

Convert Sorted Array to Binary Search Tree


#if defined(HAVE_CAIRO)
#include "catch.hpp"

#include <mapnik/map.hpp>
#include <mapnik/load_map.hpp>
#include <mapnik/cairo/cairo_renderer.hpp>

#include <sstream>

#include <cairo-pdf.h>

static cairo_status_t write(
	void *closure,
    const unsigned char *data,
    unsigned int length)
{
	std::ostream & ss = *static_cast<std::ostream*>(closure);
	ss.write(reinterpret_cast<char const *>(data), length);
    return ss ? CAIRO_STATUS_SUCCESS : CAIRO_STATUS_WRITE_ERROR;
}

static void render(std::ostream & output, bool text_outlines)
{
    const std::string map_style = R"STYLE(
<Map>
    <Style name="1">
        <Rule>
            <TextSymbolizer
                placement="point"
                face-name="DejaVu Sans Book"
                >
                "Text"
            </TextSymbolizer>
        </Rule>
    </Style>
    <Layer name="1">
        <StyleName>1</StyleName>
        <Datasource>
            <Parameter name="type">csv</Parameter>
            <Parameter name="inline">
			x, y
			0, 0
			</Parameter>
        </Datasource>
    </Layer>
</Map>
    )STYLE";

	mapnik::Map map(256, 256);
	mapnik::load_map_string(map, map_style);

    const std::string fontdir("fonts");
    REQUIRE(map.register_fonts(fontdir, true));

    const mapnik::box2d<double> bbox(-1, -1, 1, 1);
	map.zoom_to_box(bbox);

    mapnik::cairo_surface_ptr surface(
        // It would be better to use script surface,
        // but it's not included in the Mason Cairo library.
        cairo_pdf_surface_create_for_stream(
            write, &output, map.width(), map.height()),
        mapnik::cairo_surface_closer());
    mapnik::cairo_ptr image_context(
        mapnik::create_context(surface));
    mapnik::cairo_renderer<mapnik::cairo_ptr> ren(
        map, image_context, 1.0, 0, 0, text_outlines);
    ren.apply();
    cairo_surface_finish(&*surface);
}

TEST_CASE("cairo_renderer") {

SECTION("text_outlines") {

    {
        std::stringstream output;
        render(output, true);

        // Output should not contain any fonts
        CHECK(output.str().find("/Font") == std::string::npos);
    }

    {
        std::stringstream output;
        render(output, false);

        // Check fonts are there if text_outlines == false
        CHECK(output.str().find("/Font") != std::string::npos);
    }
}

}

#endif

Test of rendering text as outlines

cairo: Test of rendering text as outlines


#include "gtest/gtest.h"

#include "src/common/entity/Block.h"
#include "src/common/entity/Bomb.h"
#include "src/common/entity/Bonus.h"
#include "src/common/entity/Character.h"
#include "src/common/entity/Fire.h"
#include "src/common/entity/Wall.h"
#include "src/common/net/Deserializer.h"

using namespace common::entity;
using namespace common::net;

TEST(EntitySerializationTest, Serialization) {
  QByteArray buffer;
  QDataStream in(&buffer, QIODevice::OpenModeFlag::WriteOnly);
  QDataStream out(&buffer, QIODevice::OpenModeFlag::ReadOnly);

  Block block(QPoint(1,2));
  in << block;
  auto block_out = Deserializer::DeserializeEntity(out);
  EXPECT_EQ(block, *static_cast<Block*>(block_out.get()));

  Bomb bomb(QPoint(3,4), 123, 456, 2);
  in << bomb;
  auto bomb_out = Deserializer::DeserializeEntity(out);
  EXPECT_EQ(bomb, *static_cast<Bomb*>(bomb_out.get()));

  Bonus bonus(QPoint(1,2));
  in << bonus;
  auto bonus_out = Deserializer::DeserializeEntity(out);
  EXPECT_EQ(bonus, *static_cast<Bonus*>(bonus_out.get()));

  Character character(QPoint(5,4), 2, 5, 3);
  in << character;
  auto character_out = Deserializer::DeserializeEntity(out);
  EXPECT_EQ(character, *static_cast<Character*>(character_out.get()));

  Fire fire(QPoint(8,9), 456);
  in << fire;
  auto fire_out = Deserializer::DeserializeEntity(out);
  EXPECT_EQ(fire, *static_cast<Fire*>(fire_out.get()));

  Wall wall(QPoint(5,4));
  in << wall;
  auto wall_out = Deserializer::DeserializeEntity(out);
  EXPECT_EQ(wall, *static_cast<Wall*>(wall_out.get()));
}

Add serialization tests for entities.

Add serialization tests for entities.


/**
 * Definition for singly-linked list with a random pointer.
 * struct RandomListNode {
 *     int label;
 *     RandomListNode *next, *random;
 *     RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
 * };
 */
class Solution {
public:
    RandomListNode *copyRandomList(RandomListNode *head) {
        if(!head) return NULL;
        unordered_map<RandomListNode*, RandomListNode*> m;
        RandomListNode *cur=head;
        RandomListNode *newhead=new RandomListNode(head->label);
        RandomListNode *newh=newhead;
        m[cur]=newh;
        while(cur->next){
            cur=cur->next;
            newh->next=new RandomListNode(cur->label);
            m[cur]=newh->next;
            newh=newh->next;
        }
        cur=head;
        newh=newhead;
        while(cur){
            if(cur->random==NULL){
                newh->random=NULL;
            }else{
                newh->random=m[cur->random];
            }
            cur=cur->next;
            newh=newh->next;
        }
        return newhead;
    }
};

Copy List with Random Pointer

Copy List with Random Pointer


#include <bits/stdc++.h>

using namespace std;

int main(){
  string needle = "CD", haystack ="MANICD";
  if(haystack.find(needle) != string::npos) cout << "Gotcha!!!";
  else cout << "Not Gotcha";
  cout << endl;
  return 0;
}

Add Naive find over strings.

Add Naive find over strings.


#include "stdafx.h"
#include "CppUnitTest.h"

using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;

namespace You {
namespace DataStore {
namespace UnitTests {
TEST_CLASS(DataStoreApiTest) {
public:
	//TEST_METHOD(TestMethod1) {
	//	// TODO: Your test code here
	//}

};

}  // namespace UnitTests
}  // namespace DataStore
}  // namespace You

Create unit test file for datastore api

Create unit test file for datastore api


/* Copyright 2020 Sergei Bastrakov
 *
 * This file is part of alpaka.
 *
 * 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 <alpaka/acc/AccDevProps.hpp>
#include <alpaka/acc/Traits.hpp>

#include <alpaka/test/acc/TestAccs.hpp>

#include <catch2/catch.hpp>

//-----------------------------------------------------------------------------
TEMPLATE_LIST_TEST_CASE( "getAccDevProps", "[acc]", alpaka::test::acc::TestAccs)
{
    using Acc = TestType;
    using Dev = alpaka::dev::Dev<Acc>;
    using Pltf = alpaka::pltf::Pltf<Dev>;
    Dev const dev(alpaka::pltf::getDevByIdx<Pltf>(0u));
    auto const devProps = alpaka::acc::getAccDevProps<Acc>(dev);

    REQUIRE(devProps.m_gridBlockExtentMax.prod() > 0);
    // Note: this causes signed overflow for some configurations,
    // will be fixed separately
    // REQUIRE(devProps.m_blockThreadExtentMax.prod() > 0);
    REQUIRE(devProps.m_threadElemExtentMax.prod() > 0);
    REQUIRE(devProps.m_gridBlockCountMax > 0);
    REQUIRE(devProps.m_blockThreadCountMax > 0);
    REQUIRE(devProps.m_threadElemCountMax > 0);
    REQUIRE(devProps.m_multiProcessorCount > 0);
    REQUIRE(devProps.m_sharedMemSizeBytes > 0);
}

Add unit test for acc::getAccDevProps

Add unit test for acc::getAccDevProps


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

#include "chrome/test/webdriver/commands/response.h"

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

namespace webdriver {

namespace {

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

}  // namespace

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

Response::~Response() {}

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

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

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

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

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

  SetStatus(error_code);
  SetValue(error);
}

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

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

}  // namespace webdriver

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

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

git-svn-id: http://src.chromium.org/svn/trunk/src@75507 4ff67af0-8c30-449e-8e8b-ad334ec8d88c

Former-commit-id: 3bf4e114abe2567b8d816c029d3a8a3c65ba2693


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

vector< vector<bool> > dp;
string s;

void preprocess() {
	int n = s.size();

	//single letter is always a pallindrome
	for(int i = 0; i < n; ++i)
		dp[i][i] = true;

	//if adjacent letters are same then they are pallindrome
	for(int i = 0; i < n - 1; ++i)
		if(s[i] == s[i + 1])
			dp[i][i + 1] = true;

	//if s[i] == s[j] and between i + 1 and j - 1 is pallindrome
	//then from i to j is also a pallindrome
	for(int gap = 2; gap < n; ++gap) {
		for(int i = 0; i + gap < n; ++i) {
			int j = gap + i;
			if(s[i] == s[j] and dp[i + 1][j - 1])
				dp[i][j] = true;
		}
	}
}

bool is_pallindrome(int l, int r) {
	return dp[l][r];
}

int main() {
	std :: ios_base :: sync_with_stdio(false);
	cin.tie(NULL), cout.tie(NULL);

	cin >> s;
	dp.assign(s.size(), vector<bool>(s.size(), false));

	preprocess();

	int l, r;
	cin >> l >> r;
	l--, r--;

	if(is_pallindrome(l, r))
		cout << "Substring is a pallindrome" << endl;
	else
		cout << "Substring is not a pallindrome" << endl;
}

Add pallindromic substring algorithm to find if a substring of a string is pallindrome or not.


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

#include "fuzz/Fuzz.h"

void fuzz_SVGCanvas(Fuzz* f);

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

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

#include "fuzz/Fuzz.h"
#include "src/core/SkFontMgrPriv.h"
#include "tools/fonts/TestFontMgr.h"

void fuzz_SVGCanvas(Fuzz* f);

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

Use test font manager for SVG fuzzer

Use test font manager for SVG fuzzer

Change-Id: Ia4f96278e076d300b432b362db5df6b1a1654f3d
Reviewed-on: https://skia-review.googlesource.com/c/skia/+/301218
Commit-Queue: Zepeng Hu <4bcd4d3e41511d83d8c7cefb39b37c1439b78c03@google.com>
Reviewed-by: Kevin Lubick <7cdab2cfab351f23814786ba39716e90eed69047@google.com>


#include "naive_bayes.h"

#include <iostream>

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

  nb.set_training_data_file(std::string("training.dat"));

  nb.add_training_data("Buy cheap viagra SPAM");
  nb.add_training_data("Buy cheap airlines airlines tickets HAM");
  nb.add_training_data("Dear friend I am the king of Persia king SPAM");
  nb.add_training_data("Hello friend I am from Persia you must be from New York HAM");
  nb.add_training_data("Hi friend how are you doing I love you HAM");
  nb.add_training_data("New York is a big city HAM");

  nb.train();

  std::string class_ = nb.classify(std::string("Buy cheap viagra tickets"));
  std::cout << "Your message is " << class_ << std::endl;

  class_ = nb.classify(std::string("Hello friend how are you"));
  std::cout << "Your message is " << class_ << std::endl;

  class_ = nb.classify(std::string("Dhaka is a big city"));
  std::cout << "Your message is " << class_ << std::endl;

  return 0;
}

Test source file - initial commit.

Test source file - initial commit.


#include <read_and_write_data.h>
using namespace std;

void importData(FileReader &reader, vector<DataObject> &data) {
	// Definition goes here!!
}

void exportData(FileWriter &writer, const vector<DataObject> &data) {
	// Definition goes here!!
}

Define the methods declared in read-and-write-data header file


#include <rmc.h>

// Ok first make sure the regular old C ones still work
void mp_send(rmc_int *flag, rmc_int *data) {
    VEDGE(wdata, wflag);
    L(wdata, rmc_store(data, 42));
    L(wflag, rmc_store(flag, 1));
}

int mp_recv(rmc_int *flag, int *data) {
    int rf;
    XEDGE(rflag, rdata);
    do {
        LS(rflag, rf = rmc_load(flag));
    } while (rf == 0);
    LS(rdata, int rd = *data);
    return rd;
}

Add a C++ test. Just using C things now

Add a C++ test. Just using C things now


#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


#include "EntityManager.h"

namespace zmc
{
EntityManager::EntityManager(std::shared_ptr<ComponentManager> componentManager)
    : mLastEntityID(0)
    , mComponentManager(componentManager)
{
}

EntityManager::~EntityManager()
{

}

int EntityManager::getEntityCount()
{
    return mEntityMap.size();
}

void EntityManager::removeEntity(int entityID)
{
    auto found = mEntityMap.find(entityID);
    //No entity
    if (found == mEntityMap.end())
        return;
    mEntityMap.erase(entityID);
}

void EntityManager::removeEntitiesInGroup(int groupIdentifier)
{
    for (std::pair<const int, std::unique_ptr<BaseEntity>> &pair : mEntityMap) {
        if (pair.second->getGroup() == groupIdentifier)
            mEntityMap.erase(pair.second->getEntityID());
    }
}

std::vector<BaseEntity *> EntityManager::getEntitiesInGroup(int groupIdentifier)
{
    std::vector<BaseEntity*> group;
    for (std::pair<const int, std::unique_ptr<BaseEntity>> &pair : mEntityMap) {
        if (pair.second->getGroup() == groupIdentifier) {
            group.push_back(mEntityMap.at(pair.second->getEntityID()).get());
        }
    }
    return group;
}
}

#include "EntityManager.h"

namespace zmc
{
EntityManager::EntityManager(ComponentManager *componentManager)
    : mLastEntityID(0)
    , mComponentManager(componentManager)
{
}

EntityManager::~EntityManager()
{

}

int EntityManager::getEntityCount()
{
    return mEntityMap.size();
}

void EntityManager::removeEntity(int entityID)
{
    auto found = mEntityMap.find(entityID);
    //No entity
    if (found == mEntityMap.end())
        return;
    mEntityMap.erase(entityID);
}

void EntityManager::removeEntitiesInGroup(int groupIdentifier)
{
    for (std::pair<const int, std::unique_ptr<BaseEntity>> &pair : mEntityMap) {
        if (pair.second->getGroup() == groupIdentifier)
            mEntityMap.erase(pair.second->getEntityID());
    }
}

std::vector<BaseEntity *> EntityManager::getEntitiesInGroup(int groupIdentifier)
{
    std::vector<BaseEntity*> group;
    for (std::pair<const int, std::unique_ptr<BaseEntity>> &pair : mEntityMap) {
        if (pair.second->getGroup() == groupIdentifier) {
            group.push_back(mEntityMap.at(pair.second->getEntityID()).get());
        }
    }
    return group;
}
}

Replace std::shared_ptr with pointer and make the constructor explicit


// RUN: %clang_cc1 %s -emit-llvm -o - | FileCheck %s

typedef float float32_t;
typedef signed char poly8_t;
typedef short poly16_t;
typedef unsigned long long uint64_t;

typedef __attribute__((neon_vector_type(2))) int int32x2_t;
typedef __attribute__((neon_vector_type(4))) int int32x4_t;
typedef __attribute__((neon_vector_type(1))) uint64_t uint64x1_t;
typedef __attribute__((neon_vector_type(2))) uint64_t uint64x2_t;
typedef __attribute__((neon_vector_type(2))) float32_t float32x2_t;
typedef __attribute__((neon_vector_type(4))) float32_t float32x4_t;
typedef __attribute__((neon_polyvector_type(16))) poly8_t  poly8x16_t;
typedef __attribute__((neon_polyvector_type(8)))  poly16_t poly16x8_t;

// CHECK: 16__simd64_int32_t
void f1(int32x2_t v) { }
// CHECK: 17__simd128_int32_t
void f2(int32x4_t v) { }
// CHECK: 17__simd64_uint64_t
void f3(uint64x1_t v) { }
// CHECK: 18__simd128_uint64_t
void f4(uint64x2_t v) { }
// CHECK: 18__simd64_float32_t
void f5(float32x2_t v) { }
// CHECK: 19__simd128_float32_t
void f6(float32x4_t v) { }
// CHECK: 17__simd128_poly8_t
void f7(poly8x16_t v) { }
// CHECK: 18__simd128_poly16_t
void f8(poly16x8_t v) { }

Add a test for Neon vector mangling

Add a test for Neon vector mangling

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


// RUN: %clang_cc1 -std=c++1y -fsyntax-only -verify %s -DMAX=1234 -fconstexpr-steps 1234
// RUN: %clang_cc1 -std=c++1y -fsyntax-only -verify %s -DMAX=10 -fconstexpr-steps 10
// RUN: %clang -std=c++1y -fsyntax-only -Xclang -verify %s -DMAX=12345 -fconstexpr-steps=12345

// This takes a total of n + 4 steps according to our current rules:
//  - One for the compound-statement that is the function body
//  - One for the 'for' statement
//  - One for the 'int k = 0;' statement
//  - One for each of the n evaluations of the compound-statement in the 'for' body
//  - One for the 'return' statemnet
constexpr bool steps(int n) {
  for (int k = 0; k != n; ++k) {}
  return true; // expected-note {{step limit}}
}

static_assert(steps((MAX - 4)), ""); // ok
static_assert(steps((MAX - 3)), ""); // expected-error {{constant}} expected-note{{call}}

Add test forgotten in r181388.

Add test forgotten in r181388.

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


// Copyright 2016 Mitchell Kember. Subject to the MIT License.
// Project Euler: Problem 21
// Amicable numbers

#include "common.hpp"

#include <array>

namespace problem_21 {

long solve() {
	typedef std::vector<long>::size_type sz_t;

	constexpr sz_t max = 10000;
	std::vector<long> sums(max);
	for (sz_t i = 1; i < max; ++i) {
		sums[i] = common::sum_proper_divisors(static_cast<long>(i));
	}

	long total = 0;
	for (sz_t i = 1; i < max; ++i) {
		sz_t si = static_cast<sz_t>(sums[i]);
		if (i < si && si < max && static_cast<sz_t>(sums[si]) == i) {
			total += i;
			total += si;
		}
	}
	return total;
}

} // namespace problem_21

Solve problem 21 in C++

Solve problem 21 in C++


// This file is distributed under the MIT license.
// See the LICENSE file for details.

#include <cassert>

#include <visionaray/math/math.h>

#include <gtest/gtest.h>

using namespace visionaray;

//-------------------------------------------------------------------------------------------------
// Helper functions
//

// nested for loop over matrices --------------------------

template <typename Func>
void for_each_mat4_e(Func f)
{
    for (int i = 0; i < 4; ++i)
    {
        for (int j = 0; j < 4; ++j)
        {
            f(i, j);
        }
    }
}

// get rows and columns -----------------------------------

vec4 get_row(mat4 const& m, int i)
{
    assert( i >= 0 && i < 4 );

    return vec4(
        m(i, 0),
        m(i, 1),
        m(i, 2),
        m(i, 3)
        );
}

vec4 get_col(mat4 const& m, int j)
{
    assert( j >= 0 && j < 4 );

    return m(j);
}

TEST(Matrix, Inverse)
{

    //-------------------------------------------------------------------------
    // mat4
    //

    mat4 I = mat4::identity();

    // make some non-singular matrix
    mat4 A = make_rotation(vec3(1, 0, 0), constants::pi<float>() / 4);
    mat4 B = inverse(A);
    mat4 C = A * B;

    for_each_mat4_e(
        [&](int i, int j)
        {
            EXPECT_FLOAT_EQ(C(i, j), I(i, j));
        }
        );
}

TEST(Matrix, Mult)
{

    //-------------------------------------------------------------------------
    // mat4
    //

    // make some non-singular matrices
    mat4 A = make_rotation(vec3(1, 0, 0), constants::pi<float>() / 4);
    mat4 B = make_translation(vec3(3, 4, 5));
    mat4 C = A * B;

    for_each_mat4_e(
        [&](int i, int j)
        {
            float d = dot(get_row(A, i), get_col(B, j));
            EXPECT_FLOAT_EQ(C(i, j), d);
        }
        );
}

TEST(Matrix, Transpose)
{

    //-------------------------------------------------------------------------
    // mat4
    //

    // make some non-singular matrix
    mat4 A = make_rotation(vec3(1, 0, 0), constants::pi<float>() / 4);
    mat4 B = transpose(A);

    for_each_mat4_e(
        [&](int i, int j)
        {
            EXPECT_FLOAT_EQ(A(i, j), B(j, i));
        }
        );
}

Add unit tests for matrices

Add unit tests for matrices


// Test harness for the HtmlParser class.
#include <iostream>
#include <cstdlib>
#include "FileUtil.h"
#include "HtmlParser.h"
#include "util.h"

void Usage() {
    std::cerr << "Usage: " << ::progname << " html_filename\n";
    std::exit(EXIT_FAILURE);
}

class Parser: public HtmlParser {
public:
    Parser(const std::string &document): HtmlParser(document) { }
    virtual void notify(const HtmlParser::Chunk &chunk);
};

void Parser::notify(const HtmlParser::Chunk &chunk) {
    std::cout << chunk.toString() << '\n';
}

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

    try {
        const std::string input_filename(argv[1]);
        std::string html_document;
        if (not FileUtil::ReadString(input_filename, &html_document))
            ERROR("failed to read an HTML document from \"" + input_filename + "\"!");

        Parser parser(html_document);
        parser.parse();
    } catch (const std::exception &x) {
        ERROR(x.what());
    }
}

Test harness for the HtmlParser class.

Test harness for the HtmlParser class.


#include "Halide.h"
#include "test/common/check_call_graphs.h"

#include <stdio.h>

using namespace Halide;

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

    f(x, y, c) = x + y + c;

    f.reorder(c, x, y);
    Var yo("yo"), yi("yi");
    f.split(y, yo, yi, 2, TailStrategy::RoundUp);

    Var yoo("yoo"), yoi("yoi");
    f.split(yo, yoo, yoi, 64, TailStrategy::GuardWithIf);

    Buffer<int> im = f.realize(3000, 2000, 3);
    auto func = [](int x, int y, int c) {
        return x + y + c;
    };
    if (check_image(im, func)) {
        return -1;
    }

    return 0;
}

Add test case that exposes the out of bound errors in apply split


/*********************************************************************
** Author: Zach Colbert
** Date: 27 September 2017
** Description: A simple input/output program with mathematical operations. By prompting the user for three floats, the program will calculate and output a sum.
*********************************************************************/

#include <iostream>
using namespace std;

// A simple input/output program with mathematical operations.
int main()
{

}

Set up the bare structure of the source

Set up the bare structure of the source


// RUN: %clang_cc1 -fsyntax-only -verify %s
// expected-no-diagnostics

void bar();
namespace foo { using ::bar; }
using foo::bar;
void bar() {}

void f();
using ::f;
void f() {}

Add a test case for PR17575.

Add a test case for PR17575.

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


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

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

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

#include <Rosetta/Games/Game.hpp>
#include <Rosetta/Models/Character.hpp>

using namespace RosettaStone;
using namespace TestUtils;

TEST(Character, Health)
{
    GameConfig config;
    config.player1Class = CardClass::ROGUE;
    config.player2Class = CardClass::PALADIN;
    config.startPlayer = PlayerType::PLAYER1;
    config.doFillDecks = true;
    config.autoRun = false;

    Game game(config);
    game.StartGame();
    game.ProcessUntil(Step::MAIN_START);

    Player& curPlayer = game.GetCurrentPlayer();

    auto& curField = curPlayer.GetFieldZone();

    auto card1 = GenerateMinionCard("minion1", 3, 6);
    PlayMinionCard(curPlayer, card1);
    EXPECT_EQ(curField[0]->GetHealth(), 6);

    curField[0]->SetDamage(2);
    EXPECT_EQ(curField[0]->GetHealth(), 4);

    curField[0]->SetHealth(8);
    EXPECT_EQ(curField[0]->GetDamage(), 0);
    EXPECT_EQ(curField[0]->GetHealth(), 8);

    curField[0]->SetHealth(0);
    EXPECT_EQ(curField[0]->isDestroyed, true);
}

TEST(Character, SpellPower)
{
    GameConfig config;
    config.player1Class = CardClass::ROGUE;
    config.player2Class = CardClass::PALADIN;
    config.startPlayer = PlayerType::PLAYER1;
    config.doFillDecks = true;
    config.autoRun = false;

    Game game(config);
    game.StartGame();
    game.ProcessUntil(Step::MAIN_START);

    Player& curPlayer = game.GetCurrentPlayer();

    auto& curField = curPlayer.GetFieldZone();

    auto card1 = GenerateMinionCard("minion1", 3, 6);
    PlayMinionCard(curPlayer, card1);
    EXPECT_EQ(curField[0]->GetSpellPower(), 0);

    curField[0]->SetSpellPower(4);
    EXPECT_EQ(curField[0]->GetSpellPower(), 4);
}

Add unit test for Character class

test: Add unit test for Character class


// RUN: %clang_cc1 %s -triple=x86_64-apple-darwin10 -emit-llvm -O3 -o - | FileCheck %s
#include <typeinfo>

class __pbase_type_info : public std::type_info {
public:
  unsigned int __flags;
  const std::type_info *__pointee;

  enum __masks {
    __const_mask = 0x1,
    __volatile_mask = 0x2,
    __restrict_mask = 0x4,
    __incomplete_mask = 0x8,
    __incomplete_class_mask = 0x10
  };
};

template<typename T> const T& to(const std::type_info &info) {
return static_cast<const T&>(info);
}
struct Incomplete;

// CHECK: define i32 @_Z1fv()
int f() {
  if (to<__pbase_type_info>(typeid(Incomplete *)).__flags != __pbase_type_info::__incomplete_mask)
    return 1;

  // Success!
  return 0;
}

#ifdef HARNESS
extern "C" void printf(const char *, ...);

int main() {
  int result = f();

  if (result == 0)
    printf("success!\n");
  else
    printf("test %d failed!\n", result);

  return result;
}
#endif

Add a (currently failing) RTTI layout test.

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


// RUN: %llvmgxx %s -emit-llvm -fapple-kext -S -o -
// The extra check in 71555 caused this to crash on Darwin X86
// in an assert build.
class foo {
 virtual ~foo ();
};
foo::~foo(){}

Test for llvm-gcc commit 81037.

Test for llvm-gcc commit 81037.

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


#include "cmbf.h"
#include <unordered_map>

using namespace sketch::cmbf;

int main(int argc, char *argv[]) {
    cmbf_exp_t thing(4, 16, 1);
    cmbf_t thingexact(4, 16, 5);
    auto [x, y] = thing.est_memory_usage();
    std::fprintf(stderr, "stack space: %zu\theap space:%zu\n", x, y);
    size_t nitems = argc > 1 ? std::strtoull(argv[1], nullptr, 10): 100000;
    std::vector<uint64_t> items;
    std::mt19937_64 mt;
    while(items.size() < nitems) items.emplace_back(mt());
    for(const auto el: thing.ref()) {
        assert(unsigned(el) == 0);
    }
    auto &ref = thing.ref();
    for(const auto item: items) thing.add_conservative(item), thingexact.add_conservative(item);
    //, std::fprintf(stderr, "Item %" PRIu64 " has count %u\n", item, unsigned(thing.est_count(item)));
    std::unordered_map<uint64_t, uint64_t> histexact, histapprox;
    for(const auto j: items) {
        //std::fprintf(stderr, "est count: %zu\n", size_t(thing.est_count(j)));
        ++histapprox[thing.est_count(j)];
        ++histexact[thingexact.est_count(j)];
    }
    for(const auto &pair: histexact) {
        std::fprintf(stderr, "Exact %" PRIu64 "\t%" PRIu64 "\n", pair.first, pair.second);
    }
    for(const auto &pair: histapprox) {
        std::fprintf(stderr, "Approx %" PRIu64 "\t%" PRIu64 "\n", pair.first, pair.second);
    }
}

Add testing code for min-counting.

Add testing code for min-counting.


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

using std::string;
using std::vector;

bool isunique (const string& s);
bool isuniqueV2 (const string& s);

int main()
{
    string s = "cciao";

    if (isuniqueV2(s))
        std::cout << "All characters are unique" << std::endl;
    else
        std::cout << "Characters not unique "<< std::endl;
    return 0;
}

bool isunique (const string& s)
{
    if (s.size() > 128)
        return false;
    //we are taking ASCII
    vector<bool> char_set(128);
    for (string::size_type i=0; i<s.size(); ++i) {
        int val = s.at(i);
        if (char_set[val])
            return false;

        char_set[val] = true;
    }
   return true;
}

bool isuniqueV2 (const string& s)
{
    if (s.size() > 128)
        return false;
    //we are taking ASCII
    int check = 0;
    for (string::size_type i=0; i<s.size(); ++i) {
        int val = s.at(i) - 'a';
        int a = 'a';
        std::cout << val << " a " <<  a << std::endl;
        if ( (check & (1 << val)) > 0  )
            return false;

        check |= (1 << val);
    }
   return true;
}

Check if a string contain just unique charachers


#include <iostream>
#include <iomanip>
#include <type_traits>
#include <typeinfo>
#include <typeindex>

class A { };

class A1 {  char c;  };

class A2 {  char c1; char c2; };

class B {  char c;    int i; };

class C {  char c;    int i;    double d; };

class D {  int i;     char c;    double d; };

class E {  char c[6];  int i;    double d;  };

class F {  char c[6];  int i;  };

using namespace std;

template<class T> class AlignmentSizeInfo;

template <class T>
ostream& operator<<(ostream& out, const AlignmentSizeInfo<T>& alignsize)
{
    out << right
    << setw(3) << alignment_of<T>::value << " "
    << setw(3) << sizeof(T) <<  "  "
    << left << setw(13) << type_index(typeid(T)).name()
    << endl;

    return out;
}

template <class T>
class AlignmentSizeInfo
{
    public:
        AlignmentSizeInfo() {
            cout << *this;
        }
};

int main(int argc, char *argv[])
{
    AlignmentSizeInfo<char> asChar;
    AlignmentSizeInfo<int> asInt;
    AlignmentSizeInfo<double> asDouble;
    AlignmentSizeInfo<A> asA;
    AlignmentSizeInfo<A1> asA1;
    AlignmentSizeInfo<A2> asA2;
    AlignmentSizeInfo<B> asB;
    AlignmentSizeInfo<C> asC;
    AlignmentSizeInfo<D> asD;
    AlignmentSizeInfo<E> asE;
    AlignmentSizeInfo<F> asF;
}

Print alignment and size of fundamantal and user-defined types


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

int w = z.;  // expected-error {{use of undeclared identifier 'z'}} \
             // expected-error {{expected unqualified-id}}

int x = { y[  // expected-error {{use of undeclared identifier 'y'}} \
              // expected-note {{to match this '['}} \
              // expected-note {{to match this '{'}} \
              // expected-error {{expected ';' after top level declarator}}

// The errors below all occur on the last line of the file, so splitting them
// among multiple lines doesn't work.
// expected-error {{expected expression}} expected-error {{expected ']'}} expected-error {{expected '}'}}

Add the test that was supposed to be included with r223162.

The test case is based on the reduction from PR21679 and has to be
freestanding to work correctly, since some of the expected errors (and
some of the problems that were fixed) only occur when the end of the
file is reached.

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


class Solution {
public:
    bool hasAllCodes(string s, int k) {
        if (k > s.size()) {
            return false;
        }
        int need = 1 << k;
        for (int i = 0; i <= (s.size()-k); ++i) {
            std::string cur = s.substr(i, k);
            auto iter = s_.find(cur);
            if (iter == s_.end()) {
                s_.emplace(cur);
                --need;
                if (need == 0)
                    return true;
            }
        }
        return false;
    }
private:
    std::unordered_set<std::string> s_;
};

Check If a String Contains All Binary Codes of Size K


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

void f() noexcept;
void (&r)() = f;
void (&s)() noexcept = r; // expected-error {{cannot bind}}

void (&cond1)() noexcept = true ? r : f; // expected-error {{cannot bind}}
void (&cond2)() noexcept = true ? f : r; // expected-error {{cannot bind}}
// FIXME: Strictly, the rules in p4 don't allow this, because the operand types
// are not of the same type other than cv-qualifiers, but we consider that to
// be a defect, and instead allow reference-compatible types here.
void (&cond3)() = true ? r : f;
void (&cond4)() = true ? f : r;

Add another testcase missed from r284905.

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


#include <iostream>

using std::cout;
using std::endl;

template <typename T>
struct Node {
    T data;
    Node *next;

    Node(T _data, Node *_next = nullptr) :
            data(_data), next(_next) {}
};

template <typename T>
class Stack {
    Node<T> *top;
    int size;

    void clear() {
        while (!isEmpty()) {
            pop();
        }
    }

    void copy(const Stack& other) {
        size = other.size;
        if (other.top == nullptr)
            top = nullptr;
        else {
            Node<T> *currOther = other.top;
            Node<T> *curr = new Node<T>(currOther->data);
            top = curr;
            currOther = currOther->next;
            while (currOther != nullptr) {
                curr->next = new Node<T>(currOther->data);
                curr = curr->next;
                currOther = currOther->next;
            }
        }
    }

public:

    Stack() {
        top = nullptr;
        size = 0;
    }

    Stack(const Stack& other) {
        copy(other);
    }

    Stack& operator=(const Stack& other) {
        if (this != &other) {
            clear();
            copy(other);
        }

        return *this;
    }

    ~Stack() {
        clear();
    }

    int getSize() const {
        return size;
    }

    bool isEmpty() const {
        return top == nullptr;
    }

    const T& getTop() const {
        return top->data;
    }

    void push(const T element) {
        top = new Node<T>(element, top);
        size++;
    }

    void pop() {
        Node<T> *toDel = top;
        top = top->next;
        delete toDel;
        size--;
    }

    void print() {
        Node<T> *curr = top;
        while (curr != nullptr) {
            cout << curr->data << " ";
            curr = curr->next;
        }
        cout << endl;
    }
};

int main() {
    Stack<int> s1;
    cout << s1.isEmpty() << endl;
    s1.push(5);
    cout << s1.isEmpty() << endl;
    s1.push(7);
    s1.push(9);
    cout << s1.getTop() << endl;
    cout << s1.getSize() << endl;
    s1.print();
    Stack<int> s2 = s1;
    s2.print();
    s2.pop();
    s2.push(12);
    s1.print();
    s2.print();
    s1 = s2;
    s1.print();
    s2.print();

    return 0;
}

Add solution to problem 1

Add solution to problem 1


//
//  RemoveDuplicatesFromSortedArrayII.cpp
//  c++
//
//  Created by sure on 1/20/15.
//  Copyright (c) 2015 Shuo Li. All rights reserved.
//
// http://blog.csdn.net/myjiayan/article/details/26334279
// Gives me a better solution. Implement it in C++

#include <stdio.h>

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        if (n == 0) {
            return 0;
        }
        int times = 0;
        int index = 0;
        for (int i = 0; i < n; i ++) {
            if (A[index] == A[i]) {
                times ++;
                if (times == 2) {
                    index ++;
                    A[index] = A[i];
                }
            } else {
                index ++;
                A[index] = A[i];
                times = 1;
            }
        }
        return (index + 1);
    }
};

int main() {
    Solution *s = new Solution();
    int A[5] = {1, 1, 1, 2, 3};
    s->removeDuplicates(A, 5);
}

Remove Duplicates From Sorted Array II

Remove Duplicates From Sorted Array II


// RUN: %clang_cc1 -triple x86_64-unknown-unknown -ast-dump %s | FileCheck -strict-whitespace %s

void testArrayInitExpr()
{
    int a[10];
    auto l = [a]{
    };
    // CHECK: |-ArrayInitLoopExpr 0x{{[^ ]*}} <col:15> 'int [10]'
    // CHECK: | `-ArrayInitIndexExpr 0x{{[^ ]*}} <<invalid sloc>> 'unsigned long'
}

Add dump tests for ArrayInitLoopExpr and ArrayInitIndexExpr

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


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

bool circleSortRec(int a[], int low, int high)
{
    bool swapped = false;

    if (low == high)
        return false;

    int lo = low, hi = high;

    while (lo < hi)
    {

        if (a[lo] > a[hi])
        {
            swap(a[lo], a[hi]);
            swapped = true;
        }
        lo++;
        hi--;
    }

    if (lo == hi)
        if (a[lo] > a[hi + 1])
        {
            swap(a[low], a[hi+1]);
            swapped = true;
        }

    int mid = (high - low) / 2;
    bool firstHalf = circleSortRec(a, low, low+mid);
    bool secondHalf = circleSortRec(a, low+mid+1, high);

    return swapped || firstHalf || secondHalf;
}

void circleSort(int a[], int n)
{

    while (circleSortRec(a, 0, n-1))
    {
       ;
    }
}

int main()
{
    int a[] = {7, 5, 3, 1, 2, 4, 6, 8};
    int n = sizeof(a)/sizeof(a[0]);

    printf("\nUnsorted : ");
    for (int i=0; i<n; i++)
        cout << a[i] << " ";

    circleSort(a, n);

    printf("\nSorted : ");
    for (int i=0; i<n; i++)
        cout << a[i] << " ";

    return 0;
}

Add "Circle sort" to the list

Add "Circle sort" to the list

I cant find and c++ folder in Circle sort folder so i go here to put it down :<


#include <iostream>

namespace Exercise {
    int ivar = 0;
    double dvar = 0;
    const int limit = 1000;
}

int ivar = 0;
//using namespace Exercise;
//using Exercise::ivar;
//using Exercise::dvar;
//using Exercise::limit;

void manip() {
//    using namespace Exercise;
using Exercise::ivar;
using Exercise::dvar;
using Exercise::limit;
    double dvar = 3.1416;
    int iobj = limit + 1;
    ++ ivar;
    ++ ::ivar;
}

int main() {
    return 0;
}

Add solution for chapter 18 test 16, test 17


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

template<typename T> struct A { };

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

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

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

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

Add a test case that goes with the last commit

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


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

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

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

Test for the algorithm output

Test for the algorithm output


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

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

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

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

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

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

Remove default case from fully covered switch.

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


#include "catch.hpp"

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

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

    a = 0.0;

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

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

    a = 0.0;

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

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

    a = 0.0;

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

Add test for special cases of assignment


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

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

  int& f0(A&);
}

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

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

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

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

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


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

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

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

Add the solution to "Two arrays".

Add the solution to "Two arrays".


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

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

BOOST_AUTO_TEST_SUITE(guidance_assembly)

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

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

BOOST_AUTO_TEST_SUITE_END()

Add guidance assembly unit test stub

Add guidance assembly unit test stub


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

using namespace std;
using namespace CVD;

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

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

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

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

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

}

Test program for finding bugs in connected_components.

There is a bug.


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

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

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

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

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

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

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

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

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

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

Add implementation of Treap in C++

Add implementation of Treap in C++


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

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

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

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

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

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

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

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

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


#include <bits/stdc++.h>

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

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

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

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

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

Add extended euclidean theorem algorithm.


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

#include <iostream>

#include "static_ptr.hpp"

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

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

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

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

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

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

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

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

  return 0;
}

Add example showing the basic usage scenario for static_ptr.

Signed-off-by: Radoslaw Zarzynski <a52790b05ba389f3162dc3512ddfd95cc95e8d6a@mirantis.com>


#include <gtest/gtest.h>

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

Revert "remove test temporarily to debug"

This reverts commit 489b5dae75d6b097e706dcabca581e1edfe5625b.


#include<iostream>

using namespace std;

class Node{
	public:

	int data;
	Node *prev, *next;

	Node(){}

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

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

		if(head==NULL)
			return np;

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

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

		return head;
	}

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

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

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

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

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

		return head;
	}

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

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

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

	cout<<"Enter the number of elements: ";
	cin>>n;

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

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

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

	np.displayList(head);
}

Add code to insert node in doubly linked list


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

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

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

	missing one file from last checkin


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

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

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

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

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

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

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

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

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

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

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

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

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

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

  runner.stop();

  return 0;
}

Add runner agent with concepts example.

Add runner agent with concepts example.


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

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

Add One Row to Tree

Add One Row to Tree