Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add Levy flight example back; updated to use al::RingBuffer
/* Allocore Example: Lévy flight Description: A Lévy flight is a random walk where the step size is determined by a function that is heavy-tailed. This example uses a Cauchy distribution. Author: Lance Putnam, 9/2011 */ #include "allocore/io/al_App.hpp" using namespace al; class MyApp : public App{ public: RingBuffer<Vec3f> A; Mesh vert; MyApp(): A(8000) { nav().pos(0,0,4); initWindow(); window().displayMode(window().displayMode() | Window::MULTISAMPLE); } virtual void onAnimate(double dt){ for(int i=0; i<4; ++i){ Vec3f p; rnd::ball<3>(p.elems()); float r = p.magSqr(); float l = 0.04; // spread of steps; lower is more flighty float v = l/(r+l*l) * 0.1; // map uniform to Cauchy distribution p = p.sgn() * v; p += A.newest(); A.write(p); } vert.primitive(Graphics::LINE_STRIP); vert.reset(); for(int i=0; i<A.fill(); ++i){ float f = float(i)/A.size(); vert.vertex(A.read(i)); Vec3f dr = A.read(i+1) - A.read(i-1); vert.color(HSV((1-f)*0.2, al::clip(dr.mag()*4 + 0.2), 1-f)); } } virtual void onDraw(Graphics& g, const Viewpoint& v){ g.draw(vert); } }; int main(){ MyApp().start(); }
Add file to demonstrate use of function pointer.
#include <iostream> #include <cmath> using namespace std; double integrate(double (*f)(double x), double a, double b) { int N = 10; double h = (b-a)/N; double integral = 0.0; for(int i=0; i<N; i++) { double x = a + (i+0.5)*h; integral += (*f)(x)*h; } return integral; } int main() { cout << integrate(exp, 0.0, 1.0) << endl; cout << integrate(sin, 0.0, M_PI/4.0) << endl; }
Test for kmeans coordinator added
/** * Copyright 2014 Open Connectome Project (http://openconnecto.me) * Written by Disa Mhembere (disa) * * This file is part of FlashGraph. * * 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 "matrix/kmeans_coordinator.h" int main (int argc, char* argv []) { if (argc < 6) { fprintf(stderr, "usage: ./test_kmeans_coordinator nthreads " "nrow ncol k datafile\n"); exit(911); } unsigned nthreads = atoi(argv[1]); unsigned nrow = atoi(argv[2]); unsigned ncol = atoi(argv[3]); unsigned k = atoi(argv[4]); std::string fn = argv[5]; printf("nthreads: %u\n", nthreads); printf("nrow: %u\n", nrow); printf("ncol: %u\n", ncol); unsigned nnodes = numa_num_task_nodes(); std::cout << "We have " << nnodes << " NUMA nodes\n"; kmeans_coordinator::ptr kc = kmeans_coordinator::create( nthreads, nnodes, nrow, ncol, k, fn); return(EXIT_SUCCESS); }
Add a test for message passing.
// Test if message passing works // Should on x86, not on arm // Basically always just doesn't see the write at all. // Probably need to loop. #include <atomic> #include <stdio.h> // Note that writing the test in C++ is kind of bogus, since // the *compiler* can reorder. std::atomic<long> data = {0}; std::atomic<long> ready = {0}; int thread0() { data.store(1, std::memory_order_relaxed); ready.store(1, std::memory_order_relaxed); return 0; } int thread1() { int rready = ready.load(std::memory_order_relaxed); int rdata = data.load(std::memory_order_relaxed); return (rdata<<1) | rready; } void reset() { data.store(0, std::memory_order_relaxed); ready.store(0, std::memory_order_relaxed); } // Formatting results int result_counts[4]; void process_results(int *r) { int idx = r[1]; result_counts[idx]++; } void summarize_results() { for (int r0 = 0; r0 <= 1; r0++) { for (int r1 = 0; r1 <= 1; r1++) { int idx = (r1<<1) | r0; printf("ready=%d data=%d: %d\n", r0, r1, result_counts[idx]); } } } typedef int (test_fn)(); test_fn *test_fns[] = {thread0, thread1}; int thread_count = 2;
Add tests showing we discard all-default messages
/// \file stream.cpp /// /// Unit tests for stream functions #include "../stream.hpp" #include "vg.pb.h" #include "catch.hpp" #include <sstream> #include <iostream> namespace vg { namespace unittest { using namespace std; TEST_CASE("Protobuf messages that are all default can be stored and retrieved", "[stream]") { stringstream datastream; // Write one empty message REQUIRE(stream::write<Graph>(datastream, 1, [](size_t i) { return Graph(); })); // Look for it int seen = 0; stream::for_each<Graph>(datastream, [&](const Graph& item) { seen++; }); // Make sure it comes back REQUIRE(seen == 1); } TEST_CASE("Protobuf messages can be written and read back", "[stream]") { stringstream datastream; // Define some functions to make and check fake Protobuf objects using message_t = Position; auto get_message = [&](size_t index) { message_t item; item.set_node_id(index); cerr << "Made item " << index << endl; return item; }; size_t index_expected = 0; auto check_message = [&](const message_t& item) { cerr << "Read item " << item.node_id() << endl; REQUIRE(item.node_id() == index_expected); index_expected++; }; // Serialize some objects REQUIRE(stream::write<message_t>(datastream, 10, get_message)); auto data = datastream.str(); for (size_t i = 0; i < data.size(); i++) { ios state(nullptr); state.copyfmt(cerr); cerr << setfill('0') << setw(2) << hex << (int)(uint8_t)data[i] << " "; if (i % 8 == 7) { cerr << endl; } cerr.copyfmt(state); } cerr << endl; // Read them back stream::for_each<message_t>(datastream, check_message); } } }
Add a test for diagnose_if.
// RUN: %clang_cc1 -Wpedantic -fsyntax-only %s -verify void foo() __attribute__((diagnose_if(1, "", "error"))); // expected-warning{{'diagnose_if' is a clang extension}} void foo(int a) __attribute__((diagnose_if(a, "", "error"))); // expected-warning{{'diagnose_if' is a clang extension}} // FIXME: When diagnose_if gets a CXX11 spelling, this should be enabled. #if 0 [[clang::diagnose_if(a, "", "error")]] void foo(double a); #endif
Add macro to compare old and new propagation methods
#include <ctime> #include <iostream> #include "PremModel.h" #include "PMNS_Fast.h" using namespace std; int main(int argc, char **argv){ int minM = 0; int maxM = 2; if(argc>1){ string test = argv[1]; if(test=="new") maxM = 1; if(test=="old") minM = 1; } int ntries = 1e4; if(maxM-minM<2) ntries = 1e3; OscProb::PMNS_Fast p; // PREM Model OscProb::PremModel prem; // Fill path for cosT prem.FillPath(-1); // Give path to calculator p.SetPath(prem.GetNuPath()); double oldTime = 0; double newTime = 0; for(int m=minM; m<maxM; m++){ int myTime = clock(); for(int i=0; i<ntries; i++){ //p.SetDm(3, (1 -2*(i%2)) * 2.5e-3); //p.SetEnergy(2 + (i%2)); p.SetOldProp(m); p.Prob(1,0); } double timeSec = double(clock() - myTime) / CLOCKS_PER_SEC; if(m) oldTime = timeSec; else newTime = timeSec; } cout << "Old time = " << oldTime << endl; cout << "New time = " << newTime << endl; if(maxM-minM==2) cout << "Speedup = " << oldTime/newTime << " times" << endl; }
Add the test case from PR 14044 to ensure it doesn't regress.
// RUN: %clang_cc1 -verify -chain-include %s %s // PR 14044 #ifndef PASS1 #define PASS1 class S { void f(struct Test); }; #else ::Tesy *p; // expected-error {{did you mean 'Test'}} // expected-note@-4 {{'Test' declared here}} #endif
Add a missing implementation of CommitText in MockIBusEngineService.
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromeos/dbus/ibus/mock_ibus_engine_service.h" namespace chromeos { MockIBusEngineService::MockIBusEngineService() { } MockIBusEngineService::~MockIBusEngineService() { } void MockIBusEngineService::SetEngine(IBusEngineHandlerInterface* handler) { } void MockIBusEngineService::UnsetEngine() { } void MockIBusEngineService::RegisterProperties( const IBusPropertyList& property_list) { } void MockIBusEngineService::UpdatePreedit(const IBusText& ibus_text, uint32 cursor_pos, bool is_visible, IBusEnginePreeditFocusOutMode mode) { } void MockIBusEngineService::UpdateAuxiliaryText(const IBusText& ibus_text, bool is_visible) { } void MockIBusEngineService::UpdateLookupTable( const IBusLookupTable& lookup_table, bool is_visible) { } void MockIBusEngineService::UpdateProperty(const IBusProperty& property) { } void MockIBusEngineService::ForwardKeyEvent(uint32 keyval, uint32 keycode, uint32 state) { } void MockIBusEngineService::RequireSurroundingText() { } } // namespace chromeos
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromeos/dbus/ibus/mock_ibus_engine_service.h" namespace chromeos { MockIBusEngineService::MockIBusEngineService() { } MockIBusEngineService::~MockIBusEngineService() { } void MockIBusEngineService::SetEngine(IBusEngineHandlerInterface* handler) { } void MockIBusEngineService::UnsetEngine() { } void MockIBusEngineService::RegisterProperties( const IBusPropertyList& property_list) { } void MockIBusEngineService::UpdatePreedit(const IBusText& ibus_text, uint32 cursor_pos, bool is_visible, IBusEnginePreeditFocusOutMode mode) { } void MockIBusEngineService::UpdateAuxiliaryText(const IBusText& ibus_text, bool is_visible) { } void MockIBusEngineService::UpdateLookupTable( const IBusLookupTable& lookup_table, bool is_visible) { } void MockIBusEngineService::UpdateProperty(const IBusProperty& property) { } void MockIBusEngineService::ForwardKeyEvent(uint32 keyval, uint32 keycode, uint32 state) { } void MockIBusEngineService::RequireSurroundingText() { } void MockIBusEngineService::CommitText(const std::string& text) { } } // namespace chromeos
Add central limiting theorem method
#include "test.h" #include "lcg.h" // By central limiting theorem, // U ~ [0, 1] // S = sum U_i for i = 1 to M // S ~ N(M / 2, M / 12) // Z = (S - M / 2) / sqrt(M / 12) // Z ~ N(0, 1) template <class T, class RNG, int M> static inline T clt(RNG& r) { static T inv = 1 / std::sqrt(T(M) / 12); T sum = 0; for (int i = 0; i < M; i++) sum += r(); return (sum - M / T(2)) * inv; } template <class T, int M> static void clt(T* data, size_t count) { LCG r; for (size_t i = 0; i < count; i++) data[i] = clt<T, LCG, M>(r); } #define CLT_TEST(M)\ static void normaldistf_clt##M(float* data, size_t count) {\ clt<float, M>(data, count);\ }\ static void normaldist_clt##M(double* data, size_t count) {\ clt<double, M>(data, count);\ }\ REGISTER_TEST(clt##M) CLT_TEST(4); CLT_TEST(8); CLT_TEST(16);
Add c++ fatorial template meta programming example
#include <iostream> template <int N> int fat() { return N * fat<N-1>(); } template <> int fat<1>() { return 1; } int main() { const int fat5 = fat<5>(); std::cout << fat5 << std::endl; }
Prepare test case for performance test of SGD
//======================================================================= // 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 "catch.hpp" #include "dll/neural/dense_layer.hpp" #include "dll/dbn.hpp" #include "dll/trainer/stochastic_gradient_descent.hpp" #include "mnist/mnist_reader.hpp" #include "mnist/mnist_utils.hpp" // This test case is done to benchmark the performance of SGD TEST_CASE("dbn/sgd/perf/1", "[dbn][mnist][sgd][perf]") { using dbn_t = dll::dbn_desc< dll::dbn_layers< dll::dense_desc<28 * 28, 500>::layer_t, dll::dense_desc<500, 250>::layer_t, dll::dense_desc<250, 10, dll::activation<dll::function::SOFTMAX>>::layer_t>, dll::momentum, dll::batch_size<100>, dll::trainer<dll::sgd_trainer>>::dbn_t; auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(2000); REQUIRE(!dataset.training_images.empty()); mnist::binarize_dataset(dataset); auto dbn = std::make_unique<dbn_t>(); auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 50); std::cout << "ft_error:" << ft_error << std::endl; CHECK(ft_error < 5e-2); auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor()); std::cout << "test_error:" << test_error << std::endl; REQUIRE(test_error < 0.2); }
Edit distance, classic problem, need to recheck
#include <iostream> #include <string> #include <vector> #include <set> #include <unordered_set> #include <map> #include <unordered_map> #include <queue> #include <stack> #include <algorithm> #include <functional> #include <utility> #include <cstdio> #include <cstdlib> using namespace std; // dist[i][j] = the dist between word1[0...i-1] and word2[0...j-1] // Recursion: // dist[i][j] = dist[i-1][j-1] + 0 / 1 word1[i-1] == word2[j-1] or not // = dist[i-1][j] + 1 // = dist[i][j-1] + 1 // Init: // dist[0][j] = j; // dist[i][0] = i; // Complexity: O(n1*n2) time & space overhead int minDistance(string word1, string word2) { int n1 = word1.size(); int n2 = word2.size(); vector<vector<int> > dist(n1 + 1, vector<int>(n2 + 1, 0)); // init for (int i = 0; i <= n1; ++i) dist[i][0] = i; for (int j = 0; j <= n2; ++j) dist[0][j] = j; // bottom to up for (int i = 1; i <= n1; ++i) { for (int j = 1; j <= n2; ++j) { int tmp = 0; if (word1[i-1] == word2[j-1]) tmp = dist[i-1][j-1]; else tmp = dist[i-1][j-1] + 1; tmp = min(tmp, dist[i-1][j] + 1); tmp = min(tmp, dist[i][j-1] + 1); dist[i][j] = tmp; } } return dist[n1][n2]; }
Correct bug in InitDeviceScaleFactor - hidden variable.
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/base/win/dpi_setup.h" #include "ui/base/layout.h" #include "ui/gfx/display.h" #include "ui/gfx/win/dpi.h" namespace ui { namespace win { void InitDeviceScaleFactor() { float scale = 1.0f; if (gfx::IsHighDPIEnabled()) { float scale = gfx::Display::HasForceDeviceScaleFactor() ? gfx::Display::GetForcedDeviceScaleFactor() : gfx::GetDPIScale(); // Quantize to nearest supported scale factor. scale = ui::GetImageScale(ui::GetSupportedScaleFactor(scale)); } gfx::InitDeviceScaleFactor(scale); } } // namespace win } // namespace ui
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/base/win/dpi_setup.h" #include "ui/base/layout.h" #include "ui/gfx/display.h" #include "ui/gfx/win/dpi.h" namespace ui { namespace win { void InitDeviceScaleFactor() { float scale = 1.0f; if (gfx::IsHighDPIEnabled()) { scale = gfx::Display::HasForceDeviceScaleFactor() ? gfx::Display::GetForcedDeviceScaleFactor() : gfx::GetDPIScale(); // Quantize to nearest supported scale factor. scale = ui::GetImageScale(ui::GetSupportedScaleFactor(scale)); } gfx::InitDeviceScaleFactor(scale); } } // namespace win } // namespace ui
Add test for OSS-Fuzz 813
/* * (C) 2017 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include "tests.h" #if defined(BOTAN_HAS_ASN1) #include <botan/der_enc.h> #include <botan/ber_dec.h> #endif namespace Botan_Tests { #if defined(BOTAN_HAS_ASN1) namespace { Test::Result test_ber_stack_recursion() { Test::Result result("BER stack recursion"); // OSS-Fuzz #813 GitHub #989 try { const std::vector<uint8_t> in(10000000, 0); Botan::DataSource_Memory input(in.data(), in.size()); Botan::BER_Decoder dec(input); while(dec.more_items()) { Botan::BER_Object obj; dec.get_next(obj); } } catch(Botan::Decoding_Error&) { } result.test_success("No crash"); return result; } } class ASN1_Tests : public Test { public: std::vector<Test::Result> run() override { std::vector<Test::Result> results; results.push_back(test_ber_stack_recursion()); return results; } }; BOTAN_REGISTER_TEST("asn1", ASN1_Tests); #endif }
Add some code to output the bit patterns for various ways of generating NaN and Inf, compile with -lm
#include <stdio.h> #include <math.h> #include <string> #include <sstream> template <class T> T from_str(const std::string & str){ std::istringstream sin(str); T ret; sin >> ret; return ret; } void print(double a){ printf("%.20f, %llX\n", a, *((unsigned long long *) &a)); } int main(int argc, char **argv){ double i = from_str<double>(argv[1]); print(sqrt(-1)); print(1.0/i); print(-1.0/i); print(0.0/i); print(-0.0/i); print((1.0/i)/(-1.0/i)); print((1.0/i) + 3.0); print((-1.0/i) + 3.0); print(3.0/(1.0/i)); return 0; }
Add unit tests to assign operation
#include <catch.hpp> #include "Chip8.hpp" #include "CPU.hpp" namespace { using namespace Core8; SCENARIO("CPUs can assign the value of one register to another", "[assign]") { GIVEN("A CPU with some initialized registers") { CPU cpu{}; cpu.writeRegister(Chip8::REGISTER::V0, 0x01); cpu.writeRegister(Chip8::REGISTER::VC, 0xCB); cpu.writeRegister(Chip8::REGISTER::VF, 0xFF); WHEN("the CPU assigns one register to another") { cpu.setInstruction(0x8100); cpu.decode(); cpu.execute(); cpu.setInstruction(0x8DC0); cpu.decode(); cpu.execute(); cpu.setInstruction(0x8EF0); cpu.decode(); cpu.execute(); THEN("the target register holds a copy of the source register") { REQUIRE(cpu.readRegister(Chip8::REGISTER::V1) == 0x01); REQUIRE(cpu.readRegister(Chip8::REGISTER::VD) == 0xCB); REQUIRE(cpu.readRegister(Chip8::REGISTER::VE) == 0xFF); } AND_THEN("the source register remains unchanged") { REQUIRE(cpu.readRegister(Chip8::REGISTER::V0) == 0x01); REQUIRE(cpu.readRegister(Chip8::REGISTER::VC) == 0xCB); REQUIRE(cpu.readRegister(Chip8::REGISTER::VF) == 0xFF); } } } } } // unnamed namespace
Add stub for unit-testing the color conversion.
// ========================================================================== // // This file is part of DO++, a basic set of libraries in C++ for computer // vision. // // Copyright (C) 2014 David Ok <david.ok8@gmail.com> // // 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 <limits> #include <stdint.h> #include <vector> #include <gtest/gtest.h> #include "pixel.hpp" #include "color_conversion.hpp" using namespace std; using namespace DO; // ========================================================================== // int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
Print the total execution time.
#include <mach/mach_time.h> #include <string> #include <stdio.h> #define LAPS 10000000 std::wstring s = L"siebenhundertsiebenundsiebzigtausendsiebenhundertsiebenundsiebzig"; int main(void) { uint64_t count = 0; uint64_t start = mach_absolute_time(); for (auto i = 0; i < LAPS; i++) { for (auto c : s) { count++; asm volatile("" : "+r" (count)); } } uint64_t delta = mach_absolute_time() - start; printf("%f ns/lap\n", (double)delta / (double)LAPS); return 0; }
#include <mach/mach_time.h> #include <string> #include <stdio.h> #define LAPS 10000000 std::wstring s = L"siebenhundertsiebenundsiebzigtausendsiebenhundertsiebenundsiebzig"; int main(void) { uint64_t count = 0; uint64_t start = mach_absolute_time(); for (auto i = 0; i < LAPS; i++) { for (auto c : s) { count++; asm volatile("" : "+r" (count)); } } uint64_t delta = mach_absolute_time() - start; printf("%f nanoseconds\n", (double)delta); printf("%f ns/lap\n", (double)delta / (double)LAPS); return 0; }
Remove duplicate elements of an array.
/** * Remove Duplicates from Sorted Array * * cpselvis (cpselvis@gmail.com) * August 23th, 2016 */ #include<iostream> #include<vector> using namespace std; class Solution { public: int removeDuplicates(vector<int>& nums) { int prev, len = 0; for (int i = 0; i < nums.size(); ) { if (nums[i] != prev) { len ++; prev = nums[i]; i ++; } else { nums.erase(nums.begin() + i); } } return len; } }; int main(int argc, char **argv) { int arr[3] = {1, 1, 2}; vector<int> nums(arr + 0, arr + 3); Solution s; cout << s.removeDuplicates(nums) << endl; }
Add solution to the dynamic array problem
#include <iostream> using namespace std; class DynamicArray { int* elements; int size; int capacity; void resize() { // increase capacity capacity *= 2; // allocate new memory int* newElements = new int[capacity]; // copy old array for (int i = 0; i < size; ++i) { newElements[i] = elements[i]; } // free old memory delete[] elements; // assign new memory to elements elements = newElements; } void copy(const DynamicArray& other) { elements = new int[other.capacity]; for (int i = 0; i < other.size; ++i) { elements[i] = other.elements[i]; } size = other.size; capacity = other.capacity; } public: DynamicArray(int _capacity = 8): size(0), capacity(_capacity) { elements = new int[capacity]; } DynamicArray(const DynamicArray& other) { copy(other); } DynamicArray& operator=(const DynamicArray& other) { if (this != &other) { delete[] elements; copy(other); } return *this; } ~DynamicArray() { delete[] elements; } int getSize() const { return size; } int getAt(int index) const { return elements[index]; } void addAtEnd(int element) { if (size == capacity) { resize(); } elements[size] = element; size++; } void removeLast() { size--; } void addAt(int element, int index) { if (size == capacity) { resize(); } for (int i = size; i > index; --i) { elements[i] = elements[i - 1]; } elements[index] = element; size++; } void removeAt(int index) { for (int i = index; i < size - 1; ++i) { elements[i] = elements[i + 1]; } size--; } }; int main() { DynamicArray d1; d1.addAtEnd(1); d1.addAtEnd(2); d1.addAtEnd(3); DynamicArray d2; d2.addAtEnd(2); d2 = d1; d1.addAt(10, 0); cout << d1.getAt(0) << '\n'; cout << d2.getAt(0) << '\n'; return 0; }
Test application to read in an .ics file and export it to .vcs.
/* This file is part of libkcal. Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org> Copyright (C) 2005 Reinhold Kainhofer <reinhold@kainhofer.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "calendarlocal.h" #include "vcalformat.h" #include "filestorage.h" #include <kaboutdata.h> #include <kapplication.h> #include <kdebug.h> #include <klocale.h> #include <kcmdlineargs.h> #include <qfile.h> #include <qfileinfo.h> using namespace KCal; static const KCmdLineOptions options[] = { { "verbose", "Verbose output", 0 }, { "+input", "Name of input file", 0 }, { "+output", "Name of output file", 0 }, KCmdLineLastOption }; int main( int argc, char **argv ) { KAboutData aboutData("testvcalexport", "Part of LibKCal's test suite. Checks if export to vCalendar still works correctly.", "0.1"); KCmdLineArgs::init( argc, argv, &aboutData ); KCmdLineArgs::addCmdLineOptions( options ); KApplication app/*( false, false )*/; KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); if ( args->count() != 2 ) { args->usage( "Wrong number of arguments." ); } QString input = QFile::decodeName( args->arg( 0 ) ); QString output = QFile::decodeName( args->arg( 1 ) ); QFileInfo outputFileInfo( output ); output = outputFileInfo.absFilePath(); kdDebug(5800) << "Input file: " << input << endl; kdDebug(5800) << "Output file: " << output << endl; CalendarLocal cal( QString::fromLatin1("UTC") ); if ( !cal.load( input ) ) return 1; FileStorage storage( &cal, output, new VCalFormat ); if ( !storage.save() ) return 1; return 0; }
Make GreenTea respect STDIO baud rate
#include "greentea-client/greentea_serial.h" SingletonPtr<GreenteaSerial> greentea_serial; GreenteaSerial::GreenteaSerial() : mbed::RawSerial(USBTX, USBRX) {};
#include "greentea-client/greentea_serial.h" SingletonPtr<GreenteaSerial> greentea_serial; GreenteaSerial::GreenteaSerial() : mbed::RawSerial(USBTX, USBRX, MBED_CONF_PLATFORM_STDIO_BAUD_RATE) {};
Add Chapter 25, exercise 3
// Chapter 25, exercise 3: initialize a 32-bit signed int with the bit patterns // and print the result: // - all zeros // - all ones // - alternating ones and zeros (starting with leftmost one) // - alternating zeros and ones (starting with leftomst zero) // - 110011001100... // - 001100110011... // - all-one bytes and all-zero bytes starting with all-one byte // - all-one bytes and all-zero bytes starting with all-zero byte // // Repeat with unsigned int. #include<iostream> #include<iomanip> #include<bitset> using namespace std; template<class T> void print(T s) { cout << bitset<32>(s) << " is " << s << '\n'; } int main() try { cout << "Signed integer:\n"; int s = 0x0; print(s); s = ~s; print(s); s = 0xaaaaaaaa; print(s); s = ~s; print(s); s = 0xcccccccc; print(s); s = ~s; print(s); s = 0xff00ff00; print(s); s = ~s; print(s); cout << "\nUnsigned integer:\n"; unsigned int u = 0x0; print(u); u = ~u; print(u); u = 0xaaaaaaaa; print(u); u = ~u; print(u); u = 0xcccccccc; print(u); u = ~u; print(u); u = 0xff00ff00; print(u); u = ~u; print(u); } catch (exception& e) { cerr << "Exception: " << e.what() << '\n'; } catch (...) { cerr << "Exception\n"; }
Add first test for LabelCollisionForce.
#include "../test.h" #include "../../src/forces/label_collision_force.h" #include "../../src/forces/label_state.h" namespace Forces { TEST(Test_LabelCollisionForce, NoForceIfLabelsDontCollide) { LabelCollisionForce force; Eigen::Vector2f size(0.1f, 0.1f); LabelState label(1, "Tested label", Eigen::Vector3f(0, 0, 0), size); label.labelPosition2D = Eigen::Vector2f(0, 0); LabelState other(2, "Other label", Eigen::Vector3f(1, 1, 0), size); label.labelPosition2D = Eigen::Vector2f(1, 1); LabellerFrameData frameData(1.0f, Eigen::Matrix4f::Identity(), Eigen::Matrix4f::Identity()); auto labels = std::vector<LabelState>{ label, other }; auto result = force.calculateForce(label, labels, frameData); EXPECT_Vector2f_NEAR(Eigen::Vector2f(0, 0), result, 0.0001f); } } // namespace Forces
Add tests for `class contents`
/* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/publicdomain/zero/1.0/ */ #include "contents.hh" #include "catch.hpp" using namespace vick; TEST_CASE("contents construction coordinates", "[contents]") { #define TESTS \ /* always start at `y = 0`, `x = 0` */ \ do { \ REQUIRE(c.y == 0); \ REQUIRE(c.x == 0); \ } while (0) SECTION("contents()") { contents c; TESTS; } SECTION("contents({})") { contents c({}); TESTS; } SECTION("contents({\"hi\", \"bye\"})") { contents c({"hi", "bye"}); TESTS; } #undef TESTS } TEST_CASE("contents::push_back", "[contents]") { contents c; REQUIRE(c.cont.size() == 0); c.push_back("hello"); c.push_back("world"); REQUIRE(c.cont.size() == 2); REQUIRE(c.cont[0] == "hello"); REQUIRE(c.cont[1] == "world"); } TEST_CASE("contents::yx", "[contents]") { contents c; c.waiting_for_desired = false; // require that it moves out of bounds without checking c.yx(3, 1); REQUIRE(c.y == 3); REQUIRE(c.x == 1); REQUIRE_FALSE(c.waiting_for_desired); // ensure it doesn't modify waiting_for_desired c.waiting_for_desired = true; c.yx(0, 5); REQUIRE(c.y == 0); REQUIRE(c.x == 5); REQUIRE(c.waiting_for_desired); } TEST_CASE("contents `copy/move` `assignment/construction`", "[contents]") { contents n({"asdf", "jkl;"}); n.yx(1, 1); #define TESTS \ do { \ REQUIRE(c.y == 1); \ REQUIRE(c.x == 1); \ REQUIRE(c.cont.size() == 2); \ REQUIRE(c.cont[0] == "asdf"); \ REQUIRE(c.cont[1] == "jkl;"); \ } while (0) SECTION("copy assignment") { contents c; c = n; TESTS; } SECTION("move assignment") { contents c; c = std::move(n); TESTS; } SECTION("copy construction") { contents c(n); TESTS; } SECTION("move construction") { contents c(std::move(n)); TESTS; } #undef TESTS }
Add unit test for option parsing
#include "option_types.hh" #include "unit_tests.hh" namespace Kakoune { UnitTest test_option_parsing{[]{ auto check = [](auto&& value, StringView str) { auto repr = option_to_string(value); kak_assert(repr == str); std::decay_t<decltype(value)> parsed; option_from_string(str, parsed); kak_assert(parsed == value); }; check(123, "123"); check(true, "true"); check(Vector<String>{"foo", "bar:", "baz"}, "foo:bar\\::baz"); check(HashMap<String, int>{{"foo", 10}, {"b=r", 20}, {"b:z", 30}}, "foo=10:b\\=r=20:b\\:z=30"); check(DebugFlags::Keys | DebugFlags::Hooks, "hooks|keys"); }}; }
Add an example benchmark for methods in `engine_util_spatial`.
// Copyright 2021 DeepMind Technologies Limited // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // A benchmark for comparing different implementations of engine_util_spatial methods. #include <benchmark/benchmark.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <absl/base/attributes.h> #include <mujoco/mjdata.h> #include <mujoco/mujoco.h> #include "src/engine/engine_util_blas.h" #include "src/engine/engine_util_spatial.h" #include "test/fixture.h" namespace mujoco { namespace { // ------------- quaternion-vector rotation ---------------------------- void BM_RotVecQuat(benchmark::State& state) { MujocoErrorTestGuard guard; // Create axis-angle and convert to a quaternion mjtNum quat[4]; const mjtNum angle = 33 * M_PI / 180; mjtNum vec[] = {0.2672612419124244, 0.5345224838248488, 0.8017837257372732}; mju_axisAngle2Quat(quat, vec, angle); for (auto s : state) { mjtNum result[3]; mju_rotVecQuat(result, vec, quat); benchmark::DoNotOptimize(result); } state.SetItemsProcessed(state.iterations()); } BENCHMARK(BM_RotVecQuat); } // namespace } // namespace mujoco
Add some short metaprogramming examples
#include <utility> template <std::size_t I, typename T> struct holder { T t; }; template <typename Sequence, typename... Ts> struct tuple_impl; template <std::size_t... I, typename... Ts> struct tuple_impl<std::index_sequence<I...>, Ts...> : holder<I, Ts>... {}; template <typename... Ts> using tuple = tuple_impl<std::make_index_sequence<sizeof...(Ts)>, Ts...>; template <std::size_t I, typename T> T &get(holder<I, T> &h) { return h.t; } template <typename T, std::size_t I> T &get(holder<I, T> &h) { return h.t; } #include <iostream> #include <string> void test_tuple() { tuple<int, std::string> t{1, "hello"}; std::cout << get<1>(t) << "\n"; std::cout << get<0>(t) << "\n"; get<int>(t) = 5; get<std::string>(t) = "world"; std::cout << get<1>(t) << "\n"; std::cout << get<0>(t) << "\n"; } #include <variant> template <typename... F> struct overload : F... { using F::operator()...; }; template <typename... F> overload(F...)->overload<F...>; void test_overload() { std::variant<int, std::string> v; v = std::string("hello"); std::visit( overload{[](int i) { std::cout << i << " int \n"; }, [](const std::string &s) { std::cout << s << " string \n"; }}, v); } int main() { test_tuple(); test_overload(); }
Add test case for PR5290; this bug was fixed with the non-class rvalue de-cv-qualification fixes.
// RUN: %clang_cc1 -std=c++0x -fsyntax-only -verify %s // PR5290 int const f0(); void f0_test() { decltype(0, f0()) i = 0; // expected-warning{{expression result unused}} i = 0; } struct A { int a[1]; A() { } }; typedef A const AC; int &f1(int*); float &f2(int const*); void test_f2() { float &fr = f2(AC().a); }
Fix handling of multiplication by a constant with a number of trailing zeroes.
// RUN: %clangxx_msan -m64 -O2 %s -o %t && %run %t #include <sanitizer/msan_interface.h> struct S { S(int a0) : a(a0) {} int a; int b; }; // Here S is passed to FooRun as a 64-bit integer. // This triggers an optimization where 10000 * s.a is transformed into // ((*(uint64_t *)&s) * (10000 * 2**32)) >> 32 // Test that MSan understands that this kills the uninitialized high half of S // (i.e. S::b). void FooRun(S s) { int64_t x = 10000 * s.a; __msan_check_mem_is_initialized(&x, sizeof(x)); } int main(void) { S z(1); // Take &z to ensure that it is built on stack. S *volatile p = &z; FooRun(z); return 0; }
Add a test of searching in order
#include <stdio.h> #include <string> #include <fstream> #include <iostream> #include <sstream> #include <string.h> /* 1000 in 9 seconds so each one takes ~0.01s - fine 10x faster than haskell */ std::string readFile(const char* file) { std::ifstream f; std::stringstream ss; f.open(file, std::ios::in | std::ios::binary); if (f.fail()) printf("doh\n"); ss << f.rdbuf(); if (!f && !f.eof()) printf("doh\n"); f.close(); return ss.str(); } int main() { std::string x = readFile("output/bullet.ids"); const char* s = x.c_str(); std::cout << "Paused, press enter to continue..."; std::cin.get(); for (int i = 1; i <= 1000; i++) { char buf[3]; buf[0] = '?'; buf[1] = i; buf[2] = 0; char* c = strstr(s, buf); printf("%i %i\n", i, c == 0 ? -1 : c - s); } std::cout << "Done"; return 0; }
Add Chapter 25, exercise 9
// Chapter 25, exercise 9: without using standard headers such as <limits>, // compute the number of bits in an int and determine wether char is signed or // unsigned #include<iostream> using namespace std; int main() { int n = 0; int i = 1; while (true) { cout << "1 at bit " << n << ": " << (i<<n) << '\n'; if ((i<<n) < (i<<(n-1))) break; ++n; } cout << "int has " << n+1 << " bits (hitting the sign bit when shifting " << "by " << n << " positions).\n\n"; char ch = -1; if (ch==-1) cout << "char is signed\n"; else // ch becomes 255 cout << "char is unsigned\n"; }
Disable ExtensionApiTest.Wallpaper as it's flaky.
// 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 "chrome/browser/extensions/extension_apitest.h" #include "net/dns/mock_host_resolver.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Wallpaper) { host_resolver()->AddRule("a.com", "127.0.0.1"); ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionTest("wallpaper")) << message_; }
// 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 "chrome/browser/extensions/extension_apitest.h" #include "net/dns/mock_host_resolver.h" // Disabled due to flakiness. See http://crbug.com/468632. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Wallpaper) { host_resolver()->AddRule("a.com", "127.0.0.1"); ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionTest("wallpaper")) << message_; }
Add a test case for r208215 [stack buffer overflow in <iostream>]
// RUN: %clang_cl_asan -O0 %s -Fe%t // RUN: echo "42" | %run %t 2>&1 | FileCheck %s #include <iostream> int main() { int i; std::cout << "Type i: "; std::cin >> i; return 0; // CHECK: Type i: // CHECK-NOT: AddressSanitizer: stack-buffer-overflow on address [[ADDR:0x[0-9a-f]+]] }
Add bfs source code in c++
#include <bits/stdc++.h> using namespace std; vector<int> G[MAX]; /* this visited array should be initialized with false eg.: memset(visited, false, sizeof visited) */ bool visited[MAX]; void BFS(int first) { queue<int>Q; Q.push(first); while (!Q.empty()) { int act = Q.front(); visited[act] = true; Q.pop(); for (int i= 0; i< G[act].size(); i++) if (!visited[G[act][i]]) Q.push(G[act][i]); } }
Add test case for DBN
#include "catch.hpp" #include "dll/rbm.hpp" #include "dll/dbn.hpp" #include "dll/vector.hpp" #include "dll/labels.hpp" #include "dll/test.hpp" #include "mnist/mnist_reader.hpp" #include "mnist/mnist_utils.hpp" TEST_CASE( "dbn/mnist_1", "rbm::simple" ) { typedef dll::dbn< dll::layer<28 * 28, 100, dll::in_dbn, dll::momentum, dll::batch_size<25>, dll::init_weights>, dll::layer<100, 200, dll::in_dbn, dll::momentum, dll::batch_size<25>>, dll::layer<200, 10, dll::in_dbn, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>> dbn_t; auto dataset = mnist::read_dataset<std::vector, vector, double>(); REQUIRE(!dataset.training_images.empty()); dataset.training_images.resize(200); dataset.training_labels.resize(200); mnist::binarize_dataset(dataset); auto labels = dll::make_fake(dataset.training_labels); auto dbn = make_unique<dbn_t>(); dbn->pretrain(dataset.training_images, 5); dbn->fine_tune(dataset.training_images, labels, 5, 50); auto error = test_set(dbn, dataset.training_images, dataset.training_labels, dll::predictor()); REQUIRE(error < 1e-2); }
Test that we emit a subrange type for vlas.
// RUN: %clang_cc1 -emit-llvm -g -triple x86_64-apple-darwin %s -o - | FileCheck %s // CHECK: DW_TAG_subrange_type struct StructName { int member[]; }; struct StructName SN;
Add a template test that requires canonical expression comparison
// RUN: clang-cc -fsyntax-only -verify %s // XFAIL template<int N, int M> struct A0 { void g0(); }; template<int X, int Y> void f0(A0<X, Y>) { } // expected-note{{previous}} template<int N, int M> void f0(A0<M, N>) { } template<int V1, int V2> void f0(A0<V1, V2>) { } // expected-error{{redefinition}} template<int X, int Y> void f1(A0<0, (X + Y)>) { } // expected-note{{previous}} template<int X, int Y> void f1(A0<0, (X - Y)>) { } template<int A, int B> void f1(A0<0, (A + B)>) { } // expected-error{{redefinition}} template<int X, int Y> void A0<X, Y>::g0() { }
Determine Whether Matrix Can Be Obtained By Rotation
class Solution { public: bool findRotation(vector<vector<int>>& mat, vector<vector<int>>& target) { if (check(mat, target)) return true; rotate(mat); if (check(mat, target)) return true; rotate(mat); if (check(mat, target)) return true; rotate(mat); if (check(mat, target)) return true; return false; } private: void rotate(std::vector<std::vector<int>>& matrix) { int length = matrix.size(); for(int i=0; i<=length/2; ++i) { for(int j=i; j<length-i-1; ++j) { int temp = matrix[i][j]; matrix[i][j] = matrix[length-1-j][i]; matrix[length-1-j][i] = matrix[length-1-i][length-1-j]; matrix[length-1-i][length-1-j] = matrix[j][length-1-i]; matrix[j][length-1-i] = temp; } } } bool check(std::vector<std::vector<int>>& matrix, std::vector<std::vector<int>>& target) { int length = matrix.size(); for (int i = 0; i < length; ++i) { for (int j = 0; j < length; ++j) { if (matrix[i][j] != target[i][j]) return false; } } return true; } };
Add solution for chapter 17 test 1, test 2
#include <iostream> #include <tuple> #include <vector> #include <utility> using namespace std; int main() { //test 17.1 auto ituple = make_tuple(10, 20, 30); size_t sz = tuple_size<decltype(ituple)>::value; cout << sz << endl; // for(size_t i = 0; i != sz; ++ i) { // const size_t ii = i; // cout << get<ii>(ituple) << ends; // } cout << endl; //test 17.2 tuple<string, vector<string>, pair<string, int>> t("string", {"string", "in", "vector"}, {"string in pair", 0}); cout << get<0>(t) << endl; cout << get<1>(t)[0] << endl; cout << get<2>(t).first << endl; return 0; }
Add Solution for 009 Palindrome Number
// 9. Palindrome Number /** * Determine whether an integer is a palindrome. Do this without extra space. * * Some hints: * Could negative integers be palindromes? (ie, -1) * * If you are thinking of converting the integer to string, note the restriction of using extra space. * * You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. * How would you handle such case? * * There is a more generic way of solving this problem. * * Tags: Math * * Similar Problems: (E) Palindrome Linked List * * Author: Kuang Qin */ #include <iostream> #include <string> using namespace std; class Solution { public: bool isPalindrome(int x) { if (x < 0 || (x != 0 && x % 10 == 0)) { // negative integers and integers that end with 0 are not palindrome return false; } int rev = 0; while (x > rev) { // reverse the integer till half then compare, no overflow risk rev *= 10; rev += x % 10; x /= 10; } // even digits: x == rev if palindrome // odd digits: x == rev / 10 if padlindrome return (x == rev || x == rev / 10); } }; int main() { int x = 1221; Solution sol; bool ans = sol.isPalindrome(x); cout << ans << endl; cin.get(); return 0; }
Add library (Union find tree)
// Verified: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_1_A struct union_find { vector<int> par; vector<int> rank; union_find (int n) : par(n), rank(n, 0) { REP(i,n)par[i]=i; } int find (int x) { if (par[x] == x) return x; else return par[x] = find(par[x]); } bool same (int x, int y) { return find(x) == find(y); } void unite (int x, int y) { x = find(x); y = find(y); if (x == y) return; if (rank[x] < rank[y]) par[x] = y; else { par[y] = x; if (rank[x] == rank[y]) rank[x]++; } } };
Add indicator platform to icarus.
#include "variant/indicator_platform.hpp" #include <hal.h> IndicatorPlatform::IndicatorPlatform() { } void IndicatorPlatform::set(IndicatorIntent intent, bool value) { switch(intent) { case HEARTBEAT: //palWritePad(GPIOE, GPIOE_LED3_RED, value); break; case VEHICLE_ARMED: //palWritePad(GPIOE, GPIOE_LED4_BLUE, value); break; } }
Add a simple halide file that starts from the low level IR and generates an object file
#include <stdio.h> #include "Halide.h" #include <iostream> #include <string> #define SIZE 10 void generate_function(std::string f_name, int size, int pos, int val) { std::string buff_name = "myOutBuff"; halide_dimension_t *shape = new halide_dimension_t[1]; shape[0].min = 0; shape[0].extent = 10; shape[0].stride = 1; Halide::Buffer<> buffer = Halide::Buffer<>(Halide::UInt(8), NULL, 1, shape, buff_name); Halide::Internal::Parameter p = Halide::Internal::Parameter(Halide::UInt(8), true, 1, buff_name); p.set_buffer(buffer); Halide::Expr halideTrue = Halide::Internal::const_true(); Halide::Internal::Stmt s = Halide::Internal::Store::make(buff_name, Halide::Expr(val), Halide::Expr(pos), p, halideTrue); std::cout << s << std::endl; s = unpack_buffers(s); std::vector<Halide::Argument> args_vect; Halide::Argument arg(buff_name, Halide::Argument::Kind::OutputBuffer, Halide::UInt(8), 1); args_vect.push_back(arg); Halide::Target target = Halide::get_host_target(); Halide::Module m(f_name, target); Halide::Internal::LoweredFunc ss = Halide::Internal::LoweredFunc(f_name, args_vect, s, Halide::Internal::LoweredFunc::External); std::cout << ss << std::endl; m.append(ss); Halide::Outputs output = Halide::Outputs().object(f_name + ".o"); m.compile(output); m.compile(Halide::Outputs().c_header(f_name + ".h")); } int main(int argc, char* argv[]){ int pos = 5; int val = 3; generate_function("my_func", SIZE, pos, val); return 0; }
Revert r227195 - aura: Set max pending frames to the default instead of 1 with ubercomp.
// 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 "content/renderer/gpu/delegated_compositor_output_surface.h" namespace content { DelegatedCompositorOutputSurface::DelegatedCompositorOutputSurface( int32 routing_id, uint32 output_surface_id, const scoped_refptr<ContextProviderCommandBuffer>& context_provider, scoped_ptr<cc::SoftwareOutputDevice> software) : CompositorOutputSurface(routing_id, output_surface_id, context_provider, software.Pass(), true) { capabilities_.delegated_rendering = true; } } // namespace content
// 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 "content/renderer/gpu/delegated_compositor_output_surface.h" namespace content { DelegatedCompositorOutputSurface::DelegatedCompositorOutputSurface( int32 routing_id, uint32 output_surface_id, const scoped_refptr<ContextProviderCommandBuffer>& context_provider, scoped_ptr<cc::SoftwareOutputDevice> software) : CompositorOutputSurface(routing_id, output_surface_id, context_provider, software.Pass(), true) { capabilities_.delegated_rendering = true; capabilities_.max_frames_pending = 1; } } // namespace content
Add solution for chapter 16 test 63 64
#include <iostream> #include <vector> #include <string> #include <cstring> using namespace std; //solution for test 16.63 16.64 template <typename T> typename vector<T>::size_type countTimes(const vector<T> &vec, const T &target) { typename vector<T>::size_type time = 0; for(auto elem : vec) { if(elem == target) { ++ time; } } return time; } template <> vector<const char*>::size_type countTimes(const vector<const char*> &vec, const char* const &target) { cout << "specialization " << ends; vector<const char*>::size_type time = 0; for(auto elem : vec) { if(strcmp(elem, target) == 0) { ++ time; } } return time; } int main() { vector<int> ivec = {1, 2, 2, 3, 4, 1, 2, 4, 6}; cout << countTimes(ivec, 2) << endl; vector<double> dvec = {1.0, 2.0, 3.0, 2.0, 4.0, 1.0, 2.0}; cout << countTimes(dvec, 1.0) << endl; vector<const char*> cvec = {"a", "b", "a", "c"}; const char* c = "f"; cout << countTimes(cvec, c) << endl; vector<string> svec = {"a", "b", "a", "c"}; string s = "f"; cout << countTimes(svec, s) << endl; }
Add useful function to know if a number is even or odd.
#include <iostream> #define isOdd(x) (x & 0x01) using namespace std; int main (){ int a =57; int b= 32; cout << isOdd(a) << endl; cout << isOdd(b) << endl; return 0; }
Add solution for chapter 16 test 49.
#include <iostream> using namespace std; template <typename T> void f(T t) { cout << "f(T)" << endl; } template <typename T> void f(const T* t) { cout << "f(const T*)" << endl; } template <typename T> void g(T t) { cout << "g(T)" << endl; } template <typename T> void g(T* t) { cout << "g(T*)" << endl; } int main() { int i = 42, *p = &i; const int ci = 0, *p2 = &ci; g(42);//g(T) g(p);//g(T*) g(ci);//g(T) g(p2);//g(T*) f(42);//f(T) f(p);//f(T) f(ci);//f(T) f(p2);//f(const T*) }
Add some tests for ChunkedVector
#include "chunked-vector.hh" #include <gtest/gtest.h> namespace nix { TEST(ChunkedVector, InitEmpty) { auto v = ChunkedVector<int, 2>(100); ASSERT_EQ(v.size(), 0); } TEST(ChunkedVector, GrowsCorrectly) { auto v = ChunkedVector<int, 2>(100); for (auto i = 1; i < 20; i++) { v.add(i); ASSERT_EQ(v.size(), i); } } TEST(ChunkedVector, AddAndGet) { auto v = ChunkedVector<int, 2>(100); for (auto i = 1; i < 20; i++) { auto [i2, idx] = v.add(i); auto & i3 = v[idx]; ASSERT_EQ(i, i2); ASSERT_EQ(&i2, &i3); } } TEST(ChunkedVector, ForEach) { auto v = ChunkedVector<int, 2>(100); for (auto i = 1; i < 20; i++) { v.add(i); } int count = 0; v.forEach([&count](int elt) { count++; }); ASSERT_EQ(count, v.size()); } TEST(ChunkedVector, OverflowOK) { // Similar to the AddAndGet, but intentionnally use a small // initial ChunkedVector to force it to overflow auto v = ChunkedVector<int, 2>(2); for (auto i = 1; i < 20; i++) { auto [i2, idx] = v.add(i); auto & i3 = v[idx]; ASSERT_EQ(i, i2); ASSERT_EQ(&i2, &i3); } } }
Add Tarjan for SCC + binconnected components. Needs further testing.
// TODO: retest this code. It was tested once, but had to be pushed for backup purposes. // DO TEST IT BEFORE PROPER USE. // Tarjan for SCC and Edge Biconnected Componentes - O(n + m) #include <bits/stdc++.h> using namespace std; const int N = 1e5+5; vector<int> adj[N], st; int num[N], low[N], vis[N], cnt, scc[N], sccn=1; void dfs(int u, int p) { num[u] = low[u] = ++cnt; int ch = 0; st.push_back(u), vis[u] = 1; for(int v : adj[u]) { if (!num[v]) dfs(v, u); // Uncomment below for biconnected components. if (vis[v]/* and v != p*/) low[u] = min(low[u], low[v]); } if (low[u] == num[u]) while(1) { int v = st.back(); st.pop_back(); scc[v] = sccn, vis[v] = 0; if (v == u) { sccn++; break; } } } void tarjan(int n) { for(int i=1; i<=n; ++i) if (!num[i]) dfs(i, -1); }
Add simple algorithm over c++ to get the permutations.
#include <stdio.h> #include <algorithm> #include <iterator> #include <vector> using namespace std; typedef vector <int > vi; inline void show(vi &data, int &size){ for (int i=0; i<size; i++) printf("%d \t", data[i]); printf("\n"); } inline void permutation(vi data, int size){ sort(data.begin(), data.end()); do { show(data, size); }while(next_permutation(data.begin(), data.end())); show(data, size); } int main(){ int size = 3 ; int data[] = {1,4,-1}; vi vals(begin(data), end(data)); permutation(vals, size); return 0; }
Fix MaxChannels test; 32 -> 100.
/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "voice_engine/test/auto_test/fixtures/before_initialization_fixture.h" #include <cstdlib> class VoeBaseMiscTest : public BeforeInitializationFixture { }; using namespace testing; TEST_F(VoeBaseMiscTest, MaxNumChannelsIs32) { EXPECT_EQ(32, voe_base_->MaxNumOfChannels()); } TEST_F(VoeBaseMiscTest, GetVersionPrintsSomeUsefulInformation) { char char_buffer[1024]; memset(char_buffer, 0, sizeof(char_buffer)); EXPECT_EQ(0, voe_base_->GetVersion(char_buffer)); EXPECT_THAT(char_buffer, ContainsRegex("VoiceEngine")); }
/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "voice_engine/test/auto_test/fixtures/before_initialization_fixture.h" #include <cstdlib> class VoeBaseMiscTest : public BeforeInitializationFixture { }; using namespace testing; TEST_F(VoeBaseMiscTest, MaxNumChannelsIs100) { EXPECT_EQ(100, voe_base_->MaxNumOfChannels()); } TEST_F(VoeBaseMiscTest, GetVersionPrintsSomeUsefulInformation) { char char_buffer[1024]; memset(char_buffer, 0, sizeof(char_buffer)); EXPECT_EQ(0, voe_base_->GetVersion(char_buffer)); EXPECT_THAT(char_buffer, ContainsRegex("VoiceEngine")); }
Move debug info tests for scoped enums into a separate file.
// RUN: %clang_cc1 -std=c++11 -emit-llvm -g -o - %s | FileCheck %s // Test that we are emitting debug info and base types for scoped enums. // CHECK: [ DW_TAG_enumeration_type ] [Color] {{.*}} [from int] enum class Color { gray }; void f(Color); void g() { f(Color::gray); } // CHECK: [ DW_TAG_enumeration_type ] [Colour] {{.*}} [from int] enum struct Colour { grey }; void h(Colour); void i() { h(Colour::grey); } // CHECK: [ DW_TAG_enumeration_type ] [Couleur] {{.*}} [from unsigned char] enum class Couleur : unsigned char { gris }; void j(Couleur); void k() { j(Couleur::gris); }
Add the forgotten file. splice is only a stub.
//////////////////////////////////////////////////////////////////////////////// /// @brief fundamental types for the optimisation and execution of AQL /// /// @file arangod/Aql/Types.cpp /// /// DISCLAIMER /// /// Copyright 2010-2014 triagens GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is triAGENS GmbH, Cologne, Germany /// /// @author Max Neunhoeffer /// @author Copyright 2014, triagens GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "Aql/Types.h" using namespace triagens::aql; using Json = triagens::basics::Json; AqlValue::~AqlValue () { switch (_type) { case JSON: { delete _json; return; } case DOCVEC: { for (auto it = _vector->begin(); it != _vector->end(); ++it) { delete *it; } delete _vector; return; } case RANGE: { return; } default: return; } } AqlValue* AqlValue::clone () const { switch (_type) { case JSON: { return new AqlValue(new Json(_json->copy())); } case DOCVEC: { auto c = new vector<AqlItemBlock*>; c->reserve(_vector->size()); for (auto it = _vector->begin(); it != _vector->end(); ++it) { c->push_back((*it)->slice(0, (*it)->size())); } return new AqlValue(c); } case RANGE: { return new AqlValue(_range._low, _range._high); } default: return nullptr; } } //////////////////////////////////////////////////////////////////////////////// /// @brief splice multiple blocks, note that the new block now owns all /// AqlValue pointers in the old blocks, therefore, the latter are all /// set to nullptr, just to be sure. //////////////////////////////////////////////////////////////////////////////// AqlItemBlock* AqlItemBlock::splice(std::vector<AqlItemBlock*>& blocks) { return nullptr; }
Delete Doubly Linked List Node.
#include <stdio.h> #include <stdlib.h> typedef struct _NODE { int data; _NODE* next; _NODE* prev; } NODE; void push(NODE** head_ref, int data) { NODE* node = new NODE(); node->data = data; node->next = *head_ref; node->prev = NULL; if (*head_ref != nullptr) { (*head_ref)->prev = node; } *head_ref = node; } void printList(NODE* node) { while (node) { printf("%d ", node->data); node = node->next; } } void deleteNode(NODE** head_ref, NODE* dNode) { if (*head_ref == nullptr || dNode == nullptr) { return; } if (*head_ref == dNode) { *head_ref = dNode->next; } if (dNode->next != nullptr) { dNode->next->prev = dNode->prev; } if (dNode->prev != nullptr) { dNode->prev->next = dNode->next; } free(dNode); } int main(int argc, char const* argv[]) { /* Start with the empty list */ NODE* head = nullptr; /* Let us create the doubly linked list 10<->8<->4<->2 */ push(&head, 2); push(&head, 4); push(&head, 8); push(&head, 10); printf("\n Original Linked list "); printList(head); /* delete nodes from the doubly linked list */ deleteNode(&head, head); /*delete first node*/ deleteNode(&head, head->next); /*delete middle node*/ deleteNode(&head, head->next); /*delete last node*/ /* Modified linked list will be NULL<-8->NULL */ printf("\n Modified Linked list "); printList(head); return 0; }
Remove Duplicates from Sorted List II
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* deleteDuplicates(ListNode* head) { if(NULL == head || NULL == head->next) return head; ListNode *prev = head, *current = head->next; int v = head->val; while(current){ bool dup = false; while(current && current->val == v){ dup = true; current = current->next; } if(dup){ if(head->val == v){ head = prev = current; }else{ prev->next = current; } }else if(prev && prev->next != current){ prev = prev->next; } if(current){ v = current->val; current = current->next; } } return head; } };
Test for llvm-gcc checkin 89898.
// RUN: %llvmgxx %s -S -o - | FileCheck %s // Make sure pointers are passed as pointers, not converted to int. // The first load should be of type i8** in either 32 or 64 bit mode. // This formerly happened on x86-64, 7375899. class StringRef { public: const char *Data; long Len; }; void foo(StringRef X); void bar(StringRef &A) { // CHECK: @_Z3barR9StringRef // CHECK: load i8** foo(A); // CHECK: ret void }
Add simple led tutorial code
#include <gpio.h> // gpio pin controllling int main() { // defines the variable ledPin and refers it to an GPIO-Pin auto ledPin = gpio::output_pin(15); // loop 10 times for (int i = 0; i < 10; i++) { // pin is set true, pin is HIGH, LED is on ledPin.set_state(true); // pause for 500ms, status is on hold and stays true delay(500); // pin set false again, pin is LOW, LED is off ledPin.set_state(false); // 500ms pause delay(500); } return EXIT_SUCCESS; }
Add solution for chapter 17 test 24
#include <iostream> #include <string> #include <regex> using namespace std; int main() { string phone = "(\\()?(\\d{3})(\\))?([-. ])?(\\d{3})([-. ])?(\\d{4})"; regex r(phone); string s; string fmt = "$2.$5.$7"; while(getline(cin, s)) { cout << regex_replace(s, r, fmt) << endl; } return 0; }
Add Solution for 371 Sum of Two Integers
// 371. Sum of Two Integers /** * Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. * * Example: * Given a = 1 and b = 2, return 3. * * Tags: Bit Manipulation * * Similar Problems: (M) Add Two Numbers * * Author: Kuang Qin */ #include <iostream> using namespace std; class Solution { public: int getSum(int a, int b) { return b == 0 ? a : getSum(a ^ b, (a & b) << 1); } }; int main() { Solution sol; cout << sol.getSum(1, 2) << endl; cin.get(); return 0; }
Add algorithm for computing the center of a circle based on three points.
#include <bits/stdc++.h> using namespace std; // Constants const double PI = acos(-1); struct point { double x; double y; point (){} point (double _x, double _y){ x = _x; y = _y; } }; inline point get_center(point A, point B, point C){ float yDelta_a = B.y - A.y; float xDelta_a = B.x - A.x; float yDelta_b = C.y - B.y; float xDelta_b = C.x - B.x; point center; float aSlope = yDelta_a/xDelta_a; float bSlope = yDelta_b/xDelta_b; center.x = (aSlope*bSlope*(A.y - C.y) + bSlope*(A.x + B.x) - aSlope*(B.x+C.x) )/(2* (bSlope-aSlope) ); center.y = -1*(center.x - (A.x+B.x)/2)/aSlope + (A.y+B.y)/2; return center; }
Prepare exercise 4 from chapter 8.
// 8.exercise.04.cpp // // An int can hold integers only up to a maximum number. Find an approximation // of that maximum number by using fibonacci(). // // COMMENTS #include "std_lib_facilities.h" void print(const string& label, const vector<int>& data) // Only read arguments, so it safe to pass them by const-reference { cout << label << ": { "; for (int i : data) cout << i << ' '; cout << "}\n"; } int check_add(int a, int b) // Adds two integers performing overflow control to avoid undefined behavior. // (Search for INT32-C on https://www.securecoding.cert.org) { if (((b > 0) && (a > (numeric_limits<int>::max() - b))) || ((b < 0) && (a < (numeric_limits<int>::min() - b)))) error("check_add(): integer add overflows."); else return a+b; } void fibonacci(int x, int y, vector<int>& v, int n) // Generates a Fibonacci sequence of n values into v, starting with values x // and y (integers passed by value, and we are modifying v, so it is passed by // reference). // Preconditions: // Vector must be empty // To simplify, n must be equal or greater than two. { if (v.size() != 0) error("fibonacci(): Non empty vector passed as argument."); if (n < 2) error("fibonacci(): n must be al least 2."); v.push_back(x); v.push_back(y); for (int i = 2; i < n; ++i) //v.push_back(v[i-2] + v[i-1]); v.push_back(check_add(v[i-2],v[i-1])); } int main() // Test the fibonacci function try { return 0; } catch(exception& e) { cerr << e.what() << '\n'; return 1; } catch(...) { cerr << "Unknwon exception!!\n"; return 2; }
Fix crasher in DownloadCompletionBlocker BUG=130324
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/download/download_completion_blocker.h" #include "base/logging.h" DownloadCompletionBlocker::DownloadCompletionBlocker() : is_complete_(false) { } DownloadCompletionBlocker::~DownloadCompletionBlocker() { } void DownloadCompletionBlocker::CompleteDownload() { DCHECK(!is_complete_); is_complete_ = true; if (callback_.is_null()) return; callback_.Run(); callback_.Reset(); }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/download/download_completion_blocker.h" #include "base/logging.h" DownloadCompletionBlocker::DownloadCompletionBlocker() : is_complete_(false) { } DownloadCompletionBlocker::~DownloadCompletionBlocker() { } void DownloadCompletionBlocker::CompleteDownload() { // Do not run |callback_| more than once. if (is_complete_) return; is_complete_ = true; if (callback_.is_null()) return; callback_.Run(); // |callback_| may delete |this|, so do not rely on |this| after running // |callback_|! }
Add a test showing that nodebug is accepted in methods too. Patch by Paul Robinson.
// RUN: %clang_cc1 %s -verify -fsyntax-only // Note: most of the 'nodebug' tests are in attr-nodebug.c. // expected-no-diagnostics class c { void t3() __attribute__((nodebug)); };
Package Datagram Class Behaviour defined
#include "PackageDatagram.h" // Constructors PackageDatagram::PackageDatagram(char* data, unsigned int length, char* ip, int port) { this->data = new char[length]; memcpy(this->data, data, length); this->length = length; memcpy(this->ip, ip, sizeof this->ip); this->port = port; } PackageDatagram::PackageDatagram(unsigned int length) { this->length = length; } PackageDatagram::~PackageDatagram(){ } // Public Methods char* PackageDatagram::getIp(){ return ip; } unsigned int PackageDatagram::getLength(){ return length; } int PackageDatagram::getPort(){ return port; } char* PackageDatagram::getData(){ return data; } void PackageDatagram::setPort(int port) { this->port = port; } void PackageDatagram::setIp(char* ip) { for(int i=0; i < 16; i++){ this->ip[i] = ip[i]; } } void PackageDatagram::setData(char* data){ this->data = data; }
Patch for r148243 which was left behind.
// RUN: %clang_cc1 %s -emit-llvm-only // CHECK that we don't crash. int main(void){ int x = 12; // Make sure we don't crash when constant folding the case 4 // statement due to the case 5 statement contained in the do loop switch (4) { case 4: do { case 5: x++;} while (x < 100); } return x; }
Change switch name to "--raw"
// Copyright (c) 2013 Stanislas Polu. // Copyright (c) 2012 The Chromium Authors. // See the LICENSE file. #include "exo/exo_browser/common/switches.h" namespace switches { // Makes ExoBrowser use the given path for its data directory. const char kExoBrowserDataPath[] = "data-path"; // Prevents the launch of Exo and runs the ExoBrowser in "raw" mode const char kExoBrowserRaw[] = "exo-browser"; // Allow access to external pages during layout tests. const char kAllowExternalPages[] = "allow-external-pages"; // Enable accelerated 2D canvas. const char kEnableAccelerated2DCanvas[] = "enable-accelerated-2d-canvas"; // Encode binary layout test results (images, audio) using base64. const char kEncodeBinary[] = "encode-binary"; } // namespace switches
// Copyright (c) 2013 Stanislas Polu. // Copyright (c) 2012 The Chromium Authors. // See the LICENSE file. #include "exo/exo_browser/common/switches.h" namespace switches { // Makes ExoBrowser use the given path for its data directory. const char kExoBrowserDataPath[] = "data-path"; // Prevents the launch of Exo and runs the ExoBrowser in "raw" mode const char kExoBrowserRaw[] = "raw"; // Allow access to external pages during layout tests. const char kAllowExternalPages[] = "allow-external-pages"; // Enable accelerated 2D canvas. const char kEnableAccelerated2DCanvas[] = "enable-accelerated-2d-canvas"; // Encode binary layout test results (images, audio) using base64. const char kEncodeBinary[] = "encode-binary"; } // namespace switches
Test explicit specialization involving multiple template<> headers
// RUN: clang-cc -fsyntax-only -verify %s template<class T1> class A { template<class T2> class B { void mf(); }; }; template<> template<> class A<int>::B<double>; template<> template<> void A<char>::B<char>::mf(); template<> void A<char>::B<int>::mf(); // expected-error{{requires 'template<>'}}
Print Users' Database. For testing.
#include <stdio.h> #include <stdlib.h> #include <sqlite3.h> #include <string> static int callback(void *data, int argc, char **argv, char **azColName){ int i; fprintf(stderr, "%s: ", (const char*)data); for(i=0; i<argc; i++){ printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL"); } printf("\n"); return 0; } int main(int argc, char* argv[]) { sqlite3 *db_user; sqlite3 *db_file; char *zErrMsg = 0; int rc; const char* data = "Callback function called"; /* Open database */ rc = sqlite3_open("UsersTable.db", &db_user); if( rc ){ fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db_user)); exit(0); } else{ fprintf(stderr, "Opened database successfully\n"); } /* Create merged SQL statement */ /* sql = "DELETE from COMPANY where ID=2; " */ std::string sql = "SELECT * from UsersTable"; /* Execute SQL statement */ rc = sqlite3_exec(db_user, sql.c_str(), callback, (void*)data, &zErrMsg); if( rc != SQLITE_OK ){ fprintf(stderr, "SQL error: %s\n", zErrMsg); /*sqlite3_free(zErrMsg);*/ } else{ fprintf(stdout, "Operation done successfully\n"); } sqlite3_close(db_user); /* Open database */ rc = sqlite3_open("FilesTable.db", &db_file); if( rc ){ fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db_file)); exit(0); } else{ fprintf(stderr, "Opened database successfully\n"); } /* Create merged SQL statement */ /* sql = "DELETE from COMPANY where ID=2; " */ sql = "SELECT * from FilesTable"; /* Execute SQL statement */ rc = sqlite3_exec(db_file, sql.c_str(), callback, (void*)data, &zErrMsg); if( rc != SQLITE_OK ){ fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } else{ fprintf(stdout, "Operation done successfully\n"); } sqlite3_close(db_file); return 0; }
Add Chapter 25, Try This 5
// Chapter 25, Try This 5: int, char, unsigned char and signed char example // using si = 128 #include<iostream> using namespace std; template<class T> void print(T i) { cout << i << '\t'; } void print(char i) { cout << int(i) << '\t'; } void print(signed char i) { cout << int(i) << '\t'; } void print(unsigned char i) { cout << int(i) << '\t'; } int main() { int si = 128; // 00000000000000000000000010000000 is 128 char c = si; // 10000000 is -128 unsigned char uc = si; // 10000000 is 128 signed char sc = si; // 10000000 is -128 print(si); print(c); print(uc); print(sc); cout << '\n'; }
Add host info (add new files).
//===--- HostInfo.cpp - Host specific information -----------------------*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/Driver/HostInfo.h" using namespace clang::driver; HostInfo::HostInfo(const char *_Arch, const char *_Platform, const char *_OS) : Arch(_Arch), Platform(_Platform), OS(_OS) { } HostInfo::~HostInfo() { } // Darwin Host Info DarwinHostInfo::DarwinHostInfo(const char *Arch, const char *Platform, const char *OS) : HostInfo(Arch, Platform, OS) { // FIXME: How to deal with errors? // We can only call 4.2.1 for now. GCCVersion[0] = 4; GCCVersion[1] = 2; GCCVersion[2] = 1; } bool DarwinHostInfo::useDriverDriver() const { return true; } ToolChain *DarwinHostInfo::getToolChain(const ArgList &Args, const char *ArchName) const { return 0; } // Unknown Host Info UnknownHostInfo::UnknownHostInfo(const char *Arch, const char *Platform, const char *OS) : HostInfo(Arch, Platform, OS) { } bool UnknownHostInfo::useDriverDriver() const { return false; } ToolChain *UnknownHostInfo::getToolChain(const ArgList &Args, const char *ArchName) const { return 0; }
Add a test to verify that the DriveDisabled policy prevents Drive access for realz.
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/drive/drive_system_service.h" #include "chrome/browser/ui/browser.h" #include "chrome/test/base/in_process_browser_test.h" namespace drive { class DriveSystemServiceBrowserTest : public InProcessBrowserTest { }; // Verify DriveSystemService is created during login. IN_PROC_BROWSER_TEST_F(DriveSystemServiceBrowserTest, CreatedDuringLogin) { EXPECT_TRUE(DriveSystemServiceFactory::FindForProfile(browser()->profile())); } } // namespace drive
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/drive/drive_system_service.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/in_process_browser_test.h" namespace drive { class DriveSystemServiceBrowserTest : public InProcessBrowserTest { }; // Verify DriveSystemService is created during login. IN_PROC_BROWSER_TEST_F(DriveSystemServiceBrowserTest, CreatedDuringLogin) { EXPECT_TRUE(DriveSystemServiceFactory::FindForProfile(browser()->profile())); } IN_PROC_BROWSER_TEST_F(DriveSystemServiceBrowserTest, DisableDrivePolicyTest) { // First make sure the pref is set to its default value which should permit // drive. browser()->profile()->GetPrefs()->SetBoolean(prefs::kDisableDrive, false); drive::DriveSystemService* drive_service = drive::DriveSystemServiceFactory::GetForProfile(browser()->profile()); EXPECT_TRUE(drive_service); // ...next try to disable drive. browser()->profile()->GetPrefs()->SetBoolean(prefs::kDisableDrive, true); drive_service = drive::DriveSystemServiceFactory::GetForProfile(browser()->profile()); EXPECT_FALSE(drive_service); } } // namespace drive
Add 104 Maximum Depth of Binary Tree
// 104 Maximum Depth of Binary Tree /** * Given a binary tree, find its maximum depth. * * The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. * * Author: Yanbin Lu */ #include <stddef.h> #include <vector> #include <string.h> #include <stdio.h> #include <algorithm> #include <iostream> #include <map> #include <queue> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: int maxDepth(TreeNode* root) { if(root) return 1 + max(maxDepth(root->left), maxDepth(root->right)); else return 0; } }; int main() { TreeNode* root = new TreeNode(0); root->left = new TreeNode(1); root->right = new TreeNode(2); root->left->right = new TreeNode(3); Solution* sol = new Solution(); cout << sol->maxDepth(root) << endl; char c; std::cin>>c; return 0; }
Add missing test case for r332639
// RUN: %clang_cc1 -o /dev/null -emit-llvm -std=c++17 -triple x86_64-pc-windows-msvc %s struct Foo { virtual void f(); virtual void g(); }; void Foo::f() {} void Foo::g() {} template <void (Foo::*)()> void h() {} void x() { h<&Foo::f>(); h<&Foo::g>(); }
Add solution for chapter 17 test 22
#include <iostream> #include <string> #include <regex> using namespace std; bool valid(const smatch &m) { if(m[1].matched) { return m[3].matched && m[4].matched == 0; } else { return m[3].matched == 0 && m[4].str() == m[7].str(); } } int main() { string phone = "(\\()?(\\d{3})(\\))?([-.])?([ ]+)?(\\d{3})([-.])?([ ]+)?(\\d{4})"; regex r(phone); string s; while(getline(cin, s)) { for(sregex_iterator it(s.begin(), s.end(), r), it_end; it != it_end; ++ it) { if(valid(*it)) { cout << "valid: " << it -> str() << endl; } else { cout << "not valid: " << it -> str() << endl; } } } return 0; }
Add a comment, and fix macro name.
/** * @file version.cpp * @author Ryan Curtin * * The implementation of GetVersion(). */ #include "version.hpp" #include <sstream> // If we are not a git revision, just use the macros to assemble the version // name. std::string mlpack::util::GetVersion() { #ifndef __MLPACK_SUBVERSION std::stringstream o; o << "mlpack " << __MLPACK_VERSION_MAJOR << "." << __MLPACK_VERSION_MINOR << "." << __MLPACK_VERSION_PATCH; return o.str(); #else #include "svnversion.hpp" #endif }
/** * @file version.cpp * @author Ryan Curtin * * The implementation of GetVersion(). */ #include "version.hpp" #include <sstream> // If we are not a git revision, just use the macros to assemble the version // name. std::string mlpack::util::GetVersion() { #ifndef __MLPACK_GIT_VERSION std::stringstream o; o << "mlpack " << __MLPACK_VERSION_MAJOR << "." << __MLPACK_VERSION_MINOR << "." << __MLPACK_VERSION_PATCH; return o.str(); #else // This file is generated by CMake as necessary and contains just a return // statement with the git revision in it. #include "gitversion.hpp" #endif }
Test case for anonymous unions in C++
// RUN: clang -fsyntax-only -verify %s struct X { union { float f3; double d2; } named; union { int i; float f; union { float f2; mutable double d; }; }; void test_unqual_references(); struct { int a; float b; }; void test_unqual_references_const() const; mutable union { // expected-error{{anonymous union at class scope must not have a storage specifier}} float c1; double c2; }; }; void X::test_unqual_references() { i = 0; f = 0.0; f2 = f; d = f; f3 = 0; // expected-error{{use of undeclared identifier 'f3'}} a = 0; } void X::test_unqual_references_const() const { d = 0.0; f2 = 0; // expected-error{{read-only variable is not assignable}} a = 0; // expected-error{{read-only variable is not assignable}} } void test_unqual_references(X x, const X xc) { x.i = 0; x.f = 0.0; x.f2 = x.f; x.d = x.f; x.f3 = 0; // expected-error{{no member named 'f3'}} x.a = 0; xc.d = 0.0; xc.f = 0; // expected-error{{read-only variable is not assignable}} xc.a = 0; // expected-error{{read-only variable is not assignable}} } struct Redecl { int x; // expected-note{{previous declaration is here}} class y { }; union { int x; // expected-error{{member of anonymous union redeclares 'x'}} float y; double z; // FIXME: note here double zz; // expected-note{{previous definition is here}} }; int z; // FIXME: should complain here! void zz(); // expected-error{{redefinition of 'zz' as different kind of symbol}} }; union { // expected-error{{anonymous unions at namespace or global scope must be declared 'static'}} int int_val; float float_val; }; static union { int int_val2; float float_val2; }; void f() { int_val2 = 0; float_val2 = 0.0; } void g() { union { int i; float f; }; i = 0; f = 0.0; }
Add set of tests for SerialiseList
/* * Copyright (C) 2016 deipi.com LLC and contributors. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "test_serialise_list.h" #include "gtest/gtest.h" TEST(StringListTest, StringList) { EXPECT_EQ(test_StringList(), 0); } TEST(CartesianListTest, CartesianList) { EXPECT_EQ(test_CartesianList(), 0); } TEST(RangeListTest, RangeList) { EXPECT_EQ(test_RangeList(), 0); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
Create unit test file for datastore api
#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
Check that leak sanitizer works in the forked process
// Test that leaks detected after forking without exec(). // RUN: %clangxx_lsan %s -o %t && not %run %t 2>&1 | FileCheck %s #include <assert.h> #include <stdlib.h> #include <sys/wait.h> #include <unistd.h> int main() { pid_t pid = fork(); assert(pid >= 0); if (pid > 0) { int status = 0; waitpid(pid, &status, 0); assert(WIFEXITED(status)); return WEXITSTATUS(status); } else { malloc(1337); // CHECK: LeakSanitizer: detected memory leaks } return 0; }
Split Linked List in Parts
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: vector<ListNode*> splitListToParts(ListNode* root, int k) { int d=depth(root); vector<int> ls; while(k>0){ ls.push_back(d/k); d-=d/k; k--; } vector<ListNode*> ans; ListNode* prev=root; while(ls.size() && root){ while(ls.back()>1){ root=root->next; ls.back()--; } ListNode* tmp=root; root=root->next; tmp->next=NULL; ans.push_back(prev); prev=root; ls.pop_back(); } while(ls.size()){ ans.push_back(NULL); ls.pop_back(); } return ans; } int depth(ListNode* root){ if(!root) return 0; return 1+depth(root->next); } };
Add useful algorithm to find all possible substrings of size k of a set of characters.
#include<bits/stdc++.h> #define debug(x) cout << #x << " = "<< x << endl #define pb push_back /* Algorithm to find all possible substrings of size k given a set of values */ using namespace std; set<string> subs; //print all possible substrings of size k void substringSizek(char set[], string prefix, int n, int k){ //Base case if( 0 == k){ cout << prefix <<endl; subs.insert(prefix); return; } for( int i=0; i < n ; ++i){ string newprefix = prefix + set[i]; //k is decreased because we add a new caracter substringSizek(set, newprefix, n, k-1); } } void init(char set[], int k){ int n = strlen(set); substringSizek(set, "", n, k); } int main(){ char set[3] ={'a', 'b'}; int k = 3; init(set, k); /* aaa aab aba abb baa bab bba bbb */ }
Remove chars in s2 from s1
// remove chars in s1 which are present in the s2 #include <iostream> #include <string> using namespace std; void removeChars(string &s1, string &s2) { int map[256] = {0}; int s2_len = s2.length(); for (int i = 0; i < s2_len; i++) { map[s2[i]] = 1; } int s1_len = s1.length(); string result; for (int i = 0; i < s1_len; i++) { if (!map[s1[i]]) result.push_back(s1[i]); } cout<<result<<endl; } int main() { string s1 = "hello world"; string s2 = "aeiou"; removeChars(s1, s2); return 0; }
Add a hack to force the linker to fetch Object.o
//===- RustWrapper.cpp - Rust wrapper for core functions --------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines alternate interfaces to core functions that are more // readily callable by Rust's FFI. // //===----------------------------------------------------------------------===// #include "llvm-c/Core.h" #include "llvm-c/Object.h" #include <cstdlib> static char *LLVMRustError; extern "C" LLVMMemoryBufferRef LLVMRustCreateMemoryBufferWithContentsOfFile(const char *Path) { LLVMMemoryBufferRef MemBuf = NULL; LLVMCreateMemoryBufferWithContentsOfFile(Path, &MemBuf, &LLVMRustError); return MemBuf; } extern "C" const char *LLVMRustGetLastError(void) { return LLVMRustError; }
//===- RustWrapper.cpp - Rust wrapper for core functions --------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines alternate interfaces to core functions that are more // readily callable by Rust's FFI. // //===----------------------------------------------------------------------===// #include "llvm-c/Core.h" #include "llvm-c/Object.h" #include <cstdlib> static char *LLVMRustError; extern "C" LLVMMemoryBufferRef LLVMRustCreateMemoryBufferWithContentsOfFile(const char *Path) { LLVMMemoryBufferRef MemBuf = NULL; LLVMCreateMemoryBufferWithContentsOfFile(Path, &MemBuf, &LLVMRustError); return MemBuf; } extern "C" const char *LLVMRustGetLastError(void) { return LLVMRustError; } LLVMOpaqueObjectFile* (*RustHackToFetchObjectO)(LLVMOpaqueMemoryBuffer*) = LLVMCreateObjectFile;
Add unit tests for point.
/* * Unit tests for the Point3 class. * Author: Dino Wernli */ #include <gtest/gtest.h> #include "util/point3.h" TEST(Point3, Distance) { Point3 p(1, 2, 3); EXPECT_DOUBLE_EQ(0, Point3::Distance(p, p)); Point3 q(1, 2, 4); EXPECT_DOUBLE_EQ(1, Point3::Distance(p, q)); Point3 r(1, 2, 1); EXPECT_DOUBLE_EQ(2, Point3::Distance(p, r)); } TEST(Point3, SquaredDistance) { Point3 p(1, 2, 3); EXPECT_DOUBLE_EQ(0, Point3::SquaredDistance(p, p)); Point3 q(1, 2, 4); EXPECT_DOUBLE_EQ(1, Point3::SquaredDistance(p, q)); Point3 r(1, 2, 1); EXPECT_DOUBLE_EQ(4, Point3::SquaredDistance(p, r)); }
Add a solution of prob 4
#include <stdio.h> int get_gcd(const int num1, const int num2) { /* Euclidean algorithm */ /* Base case */ if(num1 < num2) return get_gcd(num2, num1); /* Swap two numbers; num2 should be less than num1 */ if(num1 % num2 == 0) return num2; /* num2 is GCD */ /* Recursive case */ return get_gcd(num1 % num2, num2); } int main(void) { int num1, num2; printf("Enter a num1= "); scanf("%d", &num1); printf("Enter a num2= "); scanf("%d", &num2); printf("Result: %d\n", get_gcd(num1, num2)); return 0; }
Add specific header to help find boost location.
/* * Copyright (C) 2009, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ // This file is used by the package script to determine Boost location # include <boost/foreach.hpp>
Print 2-D matrix in clockwise spiral order.
/* * Written by Nitin Kumar Maharana * nitin.maharana@gmail.com */ //Print 2-D matrix in clockwise spiral order. #include <iostream> #include <vector> using namespace std; void printSpiral(vector<vector<int>>& input) { int top, bottom, left, right, direction; top = left = 0; bottom = input.size()-1; right = input[0].size()-1; direction = 0; while(top <= bottom && left <= right) { if(direction == 0) { for(int i = left; i <= right; i++) cout << input[top][i] << " "; top++; direction = 1; }else if(direction == 1) { for(int i = top; i <= bottom; i++) cout << input[i][right] << " "; right--; direction = 2; }else if(direction == 2) { for(int i = right; i >= left; i--) cout << input[bottom][i] << " "; bottom--; direction = 3; }else { for(int i = bottom; i >= top; i--) cout << input[i][left] << " "; left++; direction = 0; } } return; } int main(void) { int arr[] = {1,2,3,4}; vector<vector<int>> input(4, vector<int>(arr, arr+4)); printSpiral(input); cout << endl; return 0; }
Check whether given tree satisfies children sum property.
#include <stdio.h> typedef struct _NODE { int data; _NODE* left; _NODE* right; } NODE; NODE* newNode(int data) { NODE* node = new NODE(); node->data = data; node->left = nullptr; node->right = nullptr; return node; } bool isSumProperty(NODE* root) { int left_node_data = 0; int right_node_data = 0; if (root == NULL || (root->left == NULL && root->right == NULL)) { return true; } else { if (root->left) { left_node_data = root->left->data; } if (root->right) { right_node_data = root->right->data; } if ((root->data == (left_node_data + right_node_data)) && isSumProperty(root->left) && isSumProperty(root->right)) return true; else return false; } } int main(int argc, char const* argv[]) { NODE* root = newNode(10); root->left = newNode(8); root->right = newNode(2); root->left->left = newNode(3); root->left->right = newNode(5); root->right->right = newNode(2); if (isSumProperty(root)) printf("The given tree satisfies the children sum property "); else printf("The given tree does not satisfy the children sum property "); return 0; }
Add a test for "external" API that checks the dup suppression is based on the caller PC
// RUN: %clangxx_tsan %s -o %t // RUN: %deflake %run %t 2>&1 | FileCheck %s #include <thread> #import "../test.h" extern "C" { void *__tsan_external_register_tag(const char *object_type); void *__tsan_external_assign_tag(void *addr, void *tag); void __tsan_external_read(void *addr, void *caller_pc, void *tag); void __tsan_external_write(void *addr, void *caller_pc, void *tag); void __tsan_write8(void *addr); } void *tag; __attribute__((no_sanitize("thread"))) void ExternalWrite(void *addr) { __tsan_external_write(addr, __builtin_return_address(0), tag); } int main(int argc, char *argv[]) { barrier_init(&barrier, 2); tag = __tsan_external_register_tag("HelloWorld"); fprintf(stderr, "Start.\n"); // CHECK: Start. for (int i = 0; i < 4; i++) { void *opaque_object = malloc(16); std::thread t1([opaque_object] { ExternalWrite(opaque_object); barrier_wait(&barrier); }); std::thread t2([opaque_object] { barrier_wait(&barrier); ExternalWrite(opaque_object); }); // CHECK: WARNING: ThreadSanitizer: race on a library object t1.join(); t2.join(); } fprintf(stderr, "First phase done.\n"); // CHECK: First phase done. for (int i = 0; i < 4; i++) { void *opaque_object = malloc(16); std::thread t1([opaque_object] { ExternalWrite(opaque_object); barrier_wait(&barrier); }); std::thread t2([opaque_object] { barrier_wait(&barrier); ExternalWrite(opaque_object); }); // CHECK: WARNING: ThreadSanitizer: race on a library object t1.join(); t2.join(); } fprintf(stderr, "Second phase done.\n"); // CHECK: Second phase done. } // CHECK: ThreadSanitizer: reported 2 warnings
Add Chapter 23, exercise 8
// Chapter 23, exercise 8: modify program from 23.8.7 to take as input a pattern // and a file name, then output numbered lines (line-number: line) that contain // a match of the pattern. No match - no output #include<regex> #include<iostream> #include<iomanip> #include<string> #include<fstream> #include<sstream> #include<stdexcept> using namespace std; int main() try { while (true) { string pat; cout << "Enter pattern (q to exit): "; getline(cin,pat); // read pattern if (pat=="q") break; regex pattern; try { pattern = pat; // this checks pat } catch (regex_error) { cerr << "Not a valid regular expression: " << pat << '\n'; continue; } string fname; cout << "Enter file name: "; getline(cin,fname); ifstream ifs(fname); if (!ifs) throw runtime_error("Can't open " + fname); string line; int lineno = 0; while (getline(ifs,line)) { ++lineno; smatch matches; if (regex_search(line,matches,pattern)) cout << setw(3) << lineno << ": " << line << '\n'; } } } catch (exception& e) { cerr << "Exception: " << e.what() << '\n'; } catch (...) { cerr << "Exception\n"; }
Add test skeleton for HttpInterface
#include <catch.hpp> #define private public #include <libgearbox_http_interface_p.h> #include <libgearbox_http_interface.cpp> TEST_CASE("Test libgearbox_http_interface", "[http]") { SECTION("") { } }
Migrate from llvm/test/FrontendC++ and FileCheckize.
// RUN: %clang_cc1 -emit-llvm %s -o - | FileCheck %s // CHECK-NOT: ZN12basic_stringIcEC1Ev // CHECK: ZN12basic_stringIcED1Ev // CHECK: ZN12basic_stringIcED1Ev template<class charT> class basic_string { public: basic_string(); ~basic_string(); }; template <class charT> __attribute__ ((__visibility__("hidden"), __always_inline__)) inline basic_string<charT>::basic_string() { } template <class charT> inline basic_string<charT>::~basic_string() { } typedef basic_string<char> string; extern template class basic_string<char>; int main() { string s; }
Add new file for crash testing.
#include <stdio.h> #include <signal.h> #include <string.h> #include <unistd.h> static void CrashCatcher(int sig) { const char *msg; switch (sig) { case SIGILL: msg = "CRASHED: SIGILL\n"; break; case SIGTRAP: msg = "CRASHED: SIGTRAP\n"; break; case SIGABRT: msg = "CRASHED: SIGABRT\n"; break; case SIGFPE: msg = "CRASHED: SIGFPE\n"; break; case SIGBUS: msg = "CRASHED: SIGBUS\n"; break; case SIGSEGV: msg = "CRASHED: SIGSEGV\n"; break; case SIGSYS: msg = "CRASHED: SIGSYS\n"; break; default: msg = "CRASHED: SIG????\n"; break; } write(STDERR_FILENO, msg, strlen(msg)); _exit(0); } static void CatchCrashes(void) __attribute__((used,constructor)); static void CatchCrashes(void) { // Disable buffering on stdout so that everything is printed before crashing. setbuf(stdout, 0); signal(SIGILL, CrashCatcher); signal(SIGTRAP, CrashCatcher); signal(SIGABRT, CrashCatcher); signal(SIGFPE, CrashCatcher); signal(SIGBUS, CrashCatcher); signal(SIGSEGV, CrashCatcher); signal(SIGSYS, CrashCatcher); }
Update origin for the entire destination range on memory store.
// Check that 8-byte store updates origin for the full store range. // RUN: %clangxx_msan -fsanitize-memory-track-origins -m64 -O0 %s -o %t && not %run %t >%t.out 2>&1 // RUN: FileCheck %s < %t.out && FileCheck %s < %t.out // RUN: %clangxx_msan -fsanitize-memory-track-origins -m64 -O2 %s -o %t && not %run %t >%t.out 2>&1 // RUN: FileCheck %s < %t.out && FileCheck %s < %t.out #include <sanitizer/msan_interface.h> int main() { uint64_t *volatile p = new uint64_t; uint64_t *volatile q = new uint64_t; *p = *q; char *z = (char *)p; return z[6]; // CHECK: WARNING: MemorySanitizer: use-of-uninitialized-value // CHECK: in main {{.*}}origin-store-long.cc:[[@LINE-2]] // CHECK: Uninitialized value was created by a heap allocation // CHECK: in main {{.*}}origin-store-long.cc:[[@LINE-8]] }
Add Solution for 1 Two Sum
//1. Two Sum /** * Given an array of integers, return indices of the two numbers such that they add up to a specific target. * You may assume that each input would have exactly one solution. * * Example: * Given nums = [2, 7, 11, 15], target = 9, * Because nums[0] + nums[1] = 2 + 7 = 9, * return [0, 1]. * * The return format had been changed to zero-based indices. Please read the above updated description carefully. * * Tags: Array, Hash Table * * Similar Problems: (M) 3Sum, (M) 4Sum, (M) Two Sum II - Input array is sorted, (E) Two Sum III - Data structure design * * Author: Kuang Qin */ #include <iostream> #include <unordered_map> #include <vector> using namespace std; class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { int len = nums.size(); vector<int> res; unordered_map<int, int> map; for (int i = 0; i < len; i++) { int diff = target - nums[i]; if (map.find(diff) != map.end()) // use hash map to quick search, if found, ouput the result { res.push_back(map[diff]); res.push_back(i); break; } // Save the numbers into an unordered map when searching map[nums[i]] = i; } return res; } }; int main() { vector<int> nums = {2, 7, 11, 15}; int target = 9; Solution sol; vector<int> ans = sol.twoSum(nums, target); cout << "[" << ans[0] << ", " << ans[1] << "]" << endl; cin.get(); return 0; }
Add test for antique effect
#include <gtest/gtest.h> #include "photoeffects.hpp" using namespace cv; TEST(photoeffects, AntiqueTest) { Mat image(10, 10, CV_8UC1); EXPECT_EQ(10, antique(image).cols); }
Add a test for clang-tidy using the clang-cl driver.
// RUN: clang-tidy -checks=-*,modernize-use-nullptr %s -- --driver-mode=cl /DTEST1 /DFOO=foo /DBAR=bar | FileCheck -implicit-check-not="{{warning|error}}:" %s int *a = 0; // CHECK: :[[@LINE-1]]:10: warning: use nullptr #ifdef TEST1 int *b = 0; // CHECK: :[[@LINE-1]]:10: warning: use nullptr #endif #define foo 1 #define bar 1 #if FOO int *c = 0; // CHECK: :[[@LINE-1]]:10: warning: use nullptr #endif #if BAR int *d = 0; // CHECK: :[[@LINE-1]]:10: warning: use nullptr #endif
Print all path from root to leaf.
#include <stdio.h> typedef struct _NODE { int data; _NODE* left; _NODE* right; } NODE; NODE* newnode(int data) { NODE* node = new NODE(); node->data = data; node->left = nullptr; node->right = nullptr; return node; } void printPathUtil(int* path, int len) { for (int i = 0; i < len; i++) { printf("%d ", path[i]); } printf("\n"); } void printPathRec(NODE* root, int path[], int len) { if (root == nullptr) return; path[len] = root->data; len++; if (root->left == nullptr && root->right == nullptr) { printPathUtil(path, len); } else { printPathRec(root->left, path, len); printPathRec(root->right, path, len); } } void printPaths(NODE* root) { int path[10]; printPathRec(root, path, 0); } int main(int argc, char const* argv[]) { NODE* root = newnode(10); root->left = newnode(8); root->right = newnode(2); root->left->left = newnode(3); root->left->right = newnode(5); root->right->left = newnode(2); printPaths(root); return 0; }