Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add arg for show mode
#include "stdafx.h" #include "ShowModeConverter.h" WORD ShowModeConverter::ToShowWindowFlag(const ShowMode& showMode) { if (showMode == SHOW_MODE_HIDE) { return SW_HIDE; } if (showMode == SHOW_MODE_NORMAL) { return SW_NORMAL; } if (showMode == SHOW_MODE_SHOW) { return SW_SHOW; } return 0; }
Add Linux event handler export function.
#include "LinuxEventHandler.h" #include "OSEventHandlerExport.h" std::shared_ptr<ni::EventHandler> GetOSEventHandler(ni::DeviceType devices) { return std::make_shared<ni::LinuxEventHandler>(devices); }
Remove Duplicates from Sorted Array II
// // Remove_Duplicates_from_Sorted_Array_2.cpp // leetcode // // Created by 邵建勇 on 15/5/11. // Copyright (c) 2015年 John Shaw. All rights reserved. // #include <stdio.h> #include <vector> using namespace std; class Solution { public: int removeDuplicates(vector<int>& nums) { if (nums.size() == 0) { return 0; } if (nums.size() <= 2) { return (int)nums.size(); } int index = 2; for (int i = 2; i < nums.size(); i++) { if (nums[index - 2] != nums[i]) { nums[index++] = nums[i]; } } return index; } };
Add file missed in r574.
#include <common/buffer.h> #include <event/action.h> #include <event/callback.h> #include <event/event.h> #include <event/event_system.h> Action * Callback::schedule(void) { return (EventSystem::instance()->schedule(this)); }
Remove Duplicates from sorted list (Made general case for unsorted list).
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <cmath> #include <cstring> #include <cstdio> #include <map> using namespace std; /* struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; */ class Solution { public: ListNode *deleteDuplicates(ListNode *head) { map<int, int> lookup; ListNode* mover = head; if (head == NULL) return head; lookup[head->val] = 1; int c = 2; while (mover != NULL) { if ((mover->next != NULL) && (lookup.find(mover->next->val) == lookup.end())) { lookup[mover->next->val] = c; c++; mover = mover->next; } else if (mover->next == NULL) return head; else mover->next = mover->next->next; } return head; } };
Add a streamed tcp conn unit test
#include "unittest/gtest.hpp" #include "arch/streamed_tcp.hpp" namespace unittest { namespace { /* `run_in_thread_pool()` starts a RethinkDB IO layer thread pool and calls the given function within a coroutine inside of it. */ struct starter_t : public thread_message_t { thread_pool_t *tp; boost::function<void()> fun; starter_t(thread_pool_t *tp, boost::function<void()> fun) : tp(tp), fun(fun) { } void run() { fun(); tp->shutdown(); } void on_thread_switch() { coro_t::spawn_now(boost::bind(&starter_t::run, this)); } }; void run_in_thread_pool(boost::function<void()> fun) { thread_pool_t thread_pool(1); starter_t starter(&thread_pool, fun); thread_pool.run(&starter); } void handle_echo_conn(boost::scoped_ptr<streamed_tcp_conn_t> &conn) { while (conn->get_istream().good()) { // Read a line and send it back std::string str; conn->get_istream() >> str; if (!conn->get_istream().fail()) { conn->get_ostream() << str << std::endl; // endl causes flush() } } } } /* anonymous namespace */ void run_tcp_stream_test() { int port = 10000 + rand() % 20000; streamed_tcp_listener_t listener(port, boost::bind(&handle_echo_conn, _1)); streamed_tcp_conn_t conn("localhost", port); std::string test_str = "0"; for (int i = 0; i < 8192 / 32; ++i, test_str += std::string(32, static_cast<char>('a' + (i % 26)))) { conn.get_ostream() << test_str.substr(0, i); conn.get_ostream() << test_str.substr(i) << std::endl; // endl causes flush() //fprintf(stderr, "sent stuff of size %lu\n", test_str.length()); std::string str; conn.get_istream() >> str; //fprintf(stderr, "got stuff\n"); EXPECT_TRUE(!conn.get_istream().fail()); EXPECT_EQ(str, test_str); } conn.get_ostream().flush(); } TEST(TCPStreamTest, StartStop) { run_in_thread_pool(&run_tcp_stream_test); } }
Add Chapter 24, exercise 10
// Chapter 24, exercise 10: test rand(); write a program that takes two integers // n and d and calls randint(n) d times; output the number of draws for each // [0:n) and see if there are any obvious biases #include<iostream> #include<iomanip> #include<cstdlib> #include<ctime> #include<map> using namespace std; inline int randint(int max) { return rand()%max; } inline int randint(int min, int max) { return randint(max-min)+min; } int main() try { while (true) { cout << "Enter biggest number: "; int n; cin >> n; cout << "Enter number of draws (0 to exit): "; int d; cin >> d; if (d==0) break; srand(time(0)); int r = 0; map<int,int> histo; for (int i = 0; i<d; ++i) ++histo[randint(n)]; for (int i= 0; i<n; ++i) { cout << setw(2) << i << ": "; for (int j = 0; j<histo[i]; ++j) cout << '*'; cout << '\n'; } } } catch (exception& e) { cerr << "Exception: " << e.what() << '\n'; } catch (...) { cerr << "Exception\n"; }
Add Maximum consecutive sum in c++
#include <bits/stdc++.h> using namespace std; int main() { int sum = 0; int max_sum = array[0]; for (int i = 0; i < length; ++i) { sum += array[i]; sum = max(0, sum); max_sum = max(sum, max_sum); } return max_sum; }
Add an example of JSON generation
// Copyright Louis Dionne 2015 // Distributed under the Boost Software License, Version 1.0. #include <boost/hana.hpp> #include <boost/hana/struct_macros.hpp> #include <iostream> #include <string> #include <type_traits> #include <utility> using namespace boost::hana; using namespace std::literals; std::string quote(std::string s) { return "\"" + s + "\""; } template <typename Xs> std::string join(Xs&& xs, std::string sep) { return fold.left(intersperse(std::forward<Xs>(xs), sep), "", _ + _); } template <typename T> auto to_json(T&& x) -> decltype(std::to_string(std::forward<T>(x))) { return std::to_string(std::forward<T>(x)); } std::string to_json(char c) { return quote({c}); } std::string to_json(std::string s) { return quote(s); } template <typename T> std::enable_if_t<models<Struct, T>(), std::string> to_json(T&& x) { auto as_tuple = to<Tuple>(std::forward<T>(x)); auto json = transform(std::move(as_tuple), fuse([](auto name, auto&& member) { return quote(to<char const*>(name)) + " : " + to_json(std::forward<decltype(member)&&>(member)); })); return "{" + join(std::move(json), ", ") + "}"; } template <typename Xs> std::enable_if_t<models<Sequence, Xs>(), std::string> to_json(Xs&& xs) { auto json = transform(std::forward<Xs>(xs), [](auto&& x) { return to_json(std::forward<decltype(x)&&>(x)); }); return "[" + join(std::move(json), ", ") + "]"; } struct Person { BOOST_HANA_DEFINE_STRUCT(Person, (std::string, name), (int, age) ); }; int main() { Person joe{"Joe", 30}; std::cout << to_json(make_tuple(1, 'c', joe)); }
Disable gvn non-local speculative loads under asan.
// Verifies that speculative loads from unions do not happen under asan. // RUN: %clangxx_asan -O0 %s -o %t && ASAN_OPTIONS=detect_leaks=0 %run %t 2>&1 // RUN: %clangxx_asan -O1 %s -o %t && ASAN_OPTIONS=detect_leaks=0 %run %t 2>&1 // RUN: %clangxx_asan -O2 %s -o %t && ASAN_OPTIONS=detect_leaks=0 %run %t 2>&1 // RUN: %clangxx_asan -O3 %s -o %t && ASAN_OPTIONS=detect_leaks=0 %run %t 2>&1 typedef union { short q; struct { short x; short y; int for_alignment; } w; } U; int main() { char *buf = new char[2]; buf[0] = buf[1] = 0x0; U *u = (U *)buf; return u->q == 0 ? 0 : u->w.y; }
Implement initial selectiondag printing support. This gets us a nice graph with no labels! :)
//===-- SelectionDAGPrinter.cpp - Implement SelectionDAG::viewGraph() -----===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This implements the SelectionDAG::viewGraph method. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/SelectionDAG.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/Function.h" #include "llvm/Support/GraphWriter.h" #include <fstream> using namespace llvm; /// viewGraph - Pop up a ghostview window with the reachable parts of the DAG /// rendered using 'dot'. /// void SelectionDAG::viewGraph() { std::string Filename = "/tmp/dag." + getMachineFunction().getFunction()->getName() + ".dot"; std::cerr << "Writing '" << Filename << "'... "; std::ofstream F(Filename.c_str()); if (!F) { std::cerr << " error opening file for writing!\n"; return; } WriteGraph(F, this); F.close(); std::cerr << "\n"; std::cerr << "Running 'dot' program... " << std::flush; if (system(("dot -Tps -Nfontname=Courier -Gsize=7.5,10 " + Filename + " > /tmp/dag.tempgraph.ps").c_str())) { std::cerr << "Error running dot: 'dot' not in path?\n"; } else { std::cerr << "\n"; system("gv /tmp/dag.tempgraph.ps"); } system(("rm " + Filename + " /tmp/dag.tempgraph.ps").c_str()); }
Add use-after-scope test which fails because of bug in clang
// RUN: %clangxx_asan -O0 -fsanitize-address-use-after-scope %s -o %t // RUN: not %run %t 'A' 2>&1 | FileCheck %s // RUN: not %run %t 'B' 2>&1 | FileCheck %s // Missing lifetime markers in test_a // https://bugs.llvm.org/show_bug.cgi?id=34353 // XFAIL: * struct B { B() : p('B') {} char p; }; struct C { const char *p; explicit C(const char *c) : p(c) {} C(const B &b) : p(&b.p) {} // NOLINT }; struct A { char p; explicit A() : p('C') {} const operator C() const { return C(&p); } }; volatile char r; void test_a() { C s = A(); r = *s.p; } void test_b() { C s = B(); r = *s.p; } int main(int argc, char **argv) { switch (argv[1][0]) { case 'A': test_a(); return 0; case 'B': test_b(); return 0; } return 1; } // CHECK: ERROR: AddressSanitizer: stack-use-after-scope
Disable a flaky test. See crbug.com/469249.
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/apps/app_browsertest_util.h" #include "extensions/test/extension_test_message_listener.h" // This class of BrowserTests is a helper to create tests related to crashes in // Chrome Apps. To be tested, the app will have to be placed as any other test // app (see PlatformAppBrowserTest) and will need to send a "Done" message back. // When the "Done" message is received, the test succeed. If it is not, it is // assumed that Chrome has crashed and the test will anyway fail. // // The entry in this file should be something like: // IN_PROC_BROWSER_TEST_F(AppCrashTest, <TEST_NAME>) { // ASSERT_TRUE(RunAppCrashTest("<DIRECTORY_TEST_NAME>")); // } class AppCrashTest : public extensions::PlatformAppBrowserTest { public: void RunAppCrashTest(const char* name) { LoadAndLaunchPlatformApp(name, "Done"); } }; IN_PROC_BROWSER_TEST_F(AppCrashTest, HiddenWindows) { RunAppCrashTest("crashtest_hidden_windows"); }
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/apps/app_browsertest_util.h" #include "extensions/test/extension_test_message_listener.h" // This class of BrowserTests is a helper to create tests related to crashes in // Chrome Apps. To be tested, the app will have to be placed as any other test // app (see PlatformAppBrowserTest) and will need to send a "Done" message back. // When the "Done" message is received, the test succeed. If it is not, it is // assumed that Chrome has crashed and the test will anyway fail. // // The entry in this file should be something like: // IN_PROC_BROWSER_TEST_F(AppCrashTest, <TEST_NAME>) { // ASSERT_TRUE(RunAppCrashTest("<DIRECTORY_TEST_NAME>")); // } class AppCrashTest : public extensions::PlatformAppBrowserTest { public: void RunAppCrashTest(const char* name) { LoadAndLaunchPlatformApp(name, "Done"); } }; // Disabling flaky test on ASAN, crbug.com/469249 #if !defined(ADDRESS_SANITIZER) IN_PROC_BROWSER_TEST_F(AppCrashTest, HiddenWindows) { RunAppCrashTest("crashtest_hidden_windows"); } #endif
Add custom inliner that handles only functions that are marked as always_inline.
//===- InlineAlways.cpp - Code to perform simple function inlining --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements bottom-up inlining of functions into callees. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "inline" #include "llvm/CallingConv.h" #include "llvm/Instructions.h" #include "llvm/IntrinsicInst.h" #include "llvm/Module.h" #include "llvm/Type.h" #include "llvm/Analysis/CallGraph.h" #include "llvm/Support/CallSite.h" #include "llvm/Support/Compiler.h" #include "llvm/Transforms/IPO.h" #include "llvm/Transforms/IPO/InlinerPass.h" #include "llvm/Transforms/Utils/InlineCost.h" #include "llvm/ADT/SmallPtrSet.h" using namespace llvm; namespace { // AlwaysInliner only inlines functions that are mark as "always inline". class VISIBILITY_HIDDEN AlwaysInliner : public Inliner { // Functions that are never inlined SmallPtrSet<const Function*, 16> NeverInline; InlineCostAnalyzer CA; public: // Use extremely low threshold. AlwaysInliner() : Inliner(&ID, -2000000000) {} static char ID; // Pass identification, replacement for typeid int getInlineCost(CallSite CS) { return CA.getInlineCost(CS, NeverInline); } float getInlineFudgeFactor(CallSite CS) { return CA.getInlineFudgeFactor(CS); } virtual bool doInitialization(CallGraph &CG); }; } char AlwaysInliner::ID = 0; static RegisterPass<AlwaysInliner> X("always-inline", "Inliner that handles always_inline functions"); Pass *llvm::createAlwaysInlinerPass() { return new AlwaysInliner(); } // doInitialization - Initializes the vector of functions that have not // been annotated with the "always inline" attribute. bool AlwaysInliner::doInitialization(CallGraph &CG) { Module &M = CG.getModule(); for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) if (!I->isDeclaration() && I->getNotes() != FN_NOTE_AlwaysInline) NeverInline.insert(I); return false; }
Add test case for r287758.
#include "Inputs/HeaderWithSymbol.h" #define FOO int bar; FOO int foo; // RUN: not clang-rename -new-name=qux -offset=259 %s -- 2>&1 | FileCheck %s // CHECK-NOT: CHECK // CHECK: error: SourceLocation in file {{.*}}InvalidOffset.cpp at offset 259 is invalid
Clean up tmp files when deleting Compilation objects
// REQUIRES: shell // RUN: rm -rf %t // RUN: mkdir -p %t // This is a reproducer for PR37091. // // Verify that no temporary files are left behind by the clang-tidy invocation. // RUN: env TMPDIR=%t TEMP=%t TMP=%t clang-tidy %s -- --target=mips64 // RUN: rmdir %t
Add test for the treenode.
#include "tree_node.h" #include "gtest\gtest.h" /* This file will include all the test for the TreeNode class. */ TEST(TreeNodeTest, AddChild) { //Initialize a node with some children. TreeNode<int> focusNode; TreeNode<int> child1; TreeNode<int> child2; focusNode.addChild(&child1); focusNode.addChild(&child2); EXPECT_EQ(focusNode.getChildren().size(), 2); } TEST(TreeNodeTest, RemoveChild) { //Initialize a node with some children then remove them. TreeNode<int> focusNode; TreeNode<int> child1; TreeNode<int> child2; focusNode.addChild(&child1); focusNode.addChild(&child2); focusNode.removeChild(1); EXPECT_EQ(focusNode.getChildren().size(), 1); focusNode.removeChild(0); EXPECT_EQ(focusNode.getChildren().size(), 0); EXPECT_NO_THROW(focusNode.removeChild(0)); } TEST(TreeNodeTest, AddParent) { //Initialize a node with a parent. TreeNode<int> root; TreeNode<int> focusNode; EXPECT_EQ(focusNode.getParent(), nullptr); focusNode.setParent(&root); EXPECT_EQ(focusNode.getParent(), &root); } TEST(TreeNodeTest, RemoveParent) { //Initialize a node with a parent and then remove it. TreeNode<int> root; TreeNode<int> focusNode; focusNode.setParent(&root); EXPECT_EQ(focusNode.getParent(), &root); focusNode.removeParent(); EXPECT_EQ(focusNode.getParent(), nullptr); } TEST(TreeNodeTest, Value) { //Initialize a node with a value. TreeNode<int> focusNode; focusNode.setValue(1); EXPECT_EQ(focusNode.getValue(), 1); }
Add Chapter 25, exercise 5
// Chapter 25, exercise 5: write an infinite loop and execute it #include<iostream> #include<exception> using namespace std; int main() try { while (true) cout << "Looping!\n"; } catch (exception& e) { cerr << "exception: " << e.what() << endl; } catch (...) { cerr << "exception\n"; return 2; }
Add a solution of prob 3
#include <stdio.h> int main(void) { int N; printf("Enter N= "); scanf("%d", &N); /* Get the largest number in the power of two, which satisfies less than or equal to N */ int v = 1; while(v <= N) v = v << 1; v = v >> 1; /* Calculate and print to screen */ while(v > 0) { if(N >= v) { N -= v; putchar('1'); } else putchar('0'); v /= 2; } putchar('\n'); return 0; }
Allow specific files and multiple inputs for picture testing tools.
/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Test.h" #include "picture_utils.h" #include "SkString.h" static void test_filepath_creation(skiatest::Reporter* reporter) { SkString result; SkString filename("test"); const char* dir = "test/path"; sk_tools::make_filepath(&result, dir, filename); REPORTER_ASSERT(reporter, result.equals("test/path/test")); } static void test_get_basename(skiatest::Reporter* reporter) { SkString result; SkString path("/path/basename"); sk_tools::get_basename(&result, path); REPORTER_ASSERT(reporter, result.equals("basename")); result.reset(); path.set("/path/dir/"); sk_tools::get_basename(&result, path); REPORTER_ASSERT(reporter, result.equals("dir")); result.reset(); path.set("path"); sk_tools::get_basename(&result, path); REPORTER_ASSERT(reporter, result.equals("path")); #if defined(SK_BUILD_FOR_WIN) result.reset(); path.set("path\\winbasename"); sk_tools::get_basename(&result, path); REPORTER_ASSERT(reporter, result.equals("winbasename")); result.reset(); path.set("path\\windir\\"); sk_tools::get_basename(&result, path); REPORTER_ASSERT(reporter, result.equals("windir")); #endif } static void TestPictureUtils(skiatest::Reporter* reporter) { test_filepath_creation(reporter); test_get_basename(reporter); } #include "TestClassDef.h" DEFINE_TESTCLASS("PictureUtils", PictureUtilsTestClass, TestPictureUtils)
Verify Preorder Serialization of a Binary Tree
class Solution { public: bool isValidSerialization(string preorder) { int diff = 1; std::string temp = ""; for (const auto &c : preorder) { if (c == ',') { --diff; if (diff < 0) return false; if (temp != "#") diff += 2; temp = ""; } else { temp += c; } } --diff; if (diff < 0) return false; if (temp != "#") diff += 2; return diff == 0; } };
Solve SRM 144, Div 2, Problem BinaryCode
#include <vector> #include <iostream> #include <string> using namespace std; class BinaryCode { public: vector <string> decode(string message) { vector <string> result; unsigned len = message.length() + 2; int P[len]; int Q[len]; Q[0] = Q[len-1] = 0; for (unsigned i = 0; i < message.length(); i++) { Q[i+1] = message[i] - '0'; } for (int init = 0; init <= 1; init++) { P[0] = 0; P[1] = init; for (unsigned i = 2; i < len; i++) { P[i] = Q[i-1] - P[i-1] - P[i-2]; } string orig; if (P[len-1] != 0) { orig = "NONE"; } else { for (unsigned i = 1; i <= message.length(); i++) { //cout << char('0' + P[i]) << " added..." << endl; if (P[i] == 0 || P[i] == 1) { orig += ('0' + P[i]); } else { orig = "NONE"; break; } } } result.push_back(orig); } return result; } void disp(string message) { cout << decode(message)[0] << endl << decode(message)[1] << endl; } }; int main() { BinaryCode bc; bc.disp("123210122"); bc.disp("22111"); }
Add "compile-time decorator pattern" sample
// Decorator (compile-time) class foo_concrete { public: void do_work() { } }; template <typename Foo> class foo_decorator { public: foo_decorator(Foo& f) : f{f} { } void do_work() { // Do something else here to decorate // the do_work function f.do_work(); } private: Foo& f; }; template <typename Foo> void bar(Foo& f) { f.do_work(); } int main() { foo_concrete f; foo_decorator<foo_concrete> decorated_f{f}; bar(decorated_f); } // Wrap a class with a decorator to extend its functionality. // // On [3-8], we define the class that we wish to decorate, // `foo_concrete`. // // The `foo_decorator` class template, on [10-26], implements the // same interface as `foo_concrete` and wraps any other object with // that interface, passed in to the constructor by reference on // [14-16]. A `foo_decorator` object can be used anywhere a // `foo_concrete` would be expected, but also decorates its member // functions. That is, the `foo_decorator::do_work` function ([18-22]) // calls the wrapped object's `do_work` function, while also doing // some extra work. // // To demonstrate, we wrap a `foo_concrete` with a `foo_decorator` on // [36-37], and pass it to the `bar` function template on [39], which // expects any object that implements the `do_work` function. In this // case, the call to `do_work` on [31] will be decorated.
Add test for memory leak to be run with valgrind
#include "../../test.h" #include "../../func/func-common.h" #include <iostream> TEST_CASE( "sensor get_option memory leak", "[live]" ) { // running this test with the following command: // `valgrind --leak-check=yes --show-leak-kinds=all --track-origins=yes ./unit-tests/build/utilities/memory/test-sensor-option/test-utilities-memory-sensor-option 2>&1 | grep depends` // should print nothing! auto devices = find_devices_by_product_line_or_exit(RS2_PRODUCT_LINE_DEPTH); if (devices.size() == 0) return; auto dev = devices[0]; auto depth_sens = dev.first< rs2::depth_sensor >(); // float option_value(depth_sens.get_option(RS2_OPTION_EXPOSURE)); float option_value(depth_sens.get_option(RS2_OPTION_ENABLE_AUTO_EXPOSURE)); std::cout << "Declare: BOOL::" << option_value << std::endl; }
Add empty chip::lowLevelInitialization() for STM32F7
/** * \file * \brief chip::lowLevelInitialization() implementation for STM32F7 * * \author Copyright (C) 2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "distortos/chip/lowLevelInitialization.hpp" namespace distortos { namespace chip { /*---------------------------------------------------------------------------------------------------------------------+ | global functions +---------------------------------------------------------------------------------------------------------------------*/ void lowLevelInitialization() { } } // namespace chip } // namespace distortos
Add test file template (to create a new test)
// Copyright © 2012 Lénaïc Bagnères, hnc@singularity.fr // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> //#include <hnc/header_you_test.hpp> #include <hnc/test.hpp> #include <hnc/to_string.hpp> int main() { int nb_test = 0; // Do test ++nb_test; { // Do test nb_test -= hnc::test::warning(true, "Return 1 if the condition is true, 0 else\n"); } std::cout << std::endl; hnc::test::warning(nb_test == 0, "hnc::header_you_test: " + hnc::to_string(nb_test) + " test fail!\n"); return nb_test; }
Add solution for the minimum number of coins problem.
#include <iostream> #include <vector> #include <limits> #include <algorithm> void print(std::vector<int> &solutions) { std::for_each(solutions.begin(), solutions.end(), [](auto item) { std::cout << item << " "; }); std::cout << "\n"; } class MinNumberOfCoints { public: int min(const int val) { std::vector<int> solutions(val+1, 0); for (int idx = 1; idx <= val; ++idx) { int count = idx; for (size_t coinIdx = 0; coinIdx < Coins.size(); ++coinIdx) { auto currentCoin = Coins[coinIdx]; if (idx > currentCoin) { count = std::min(count, 1 + solutions[idx - currentCoin]); } else if (idx == currentCoin) { count = std::min(count, 1); } } solutions[idx] = count; } // For debugging purpose. // print(solutions); return solutions[val]; } private: std::vector<int> Coins{1, 5, 8, 10, 15, 25}; }; int main() { MinNumberOfCoints solver; { int value = 5; std::cout << "Minimum number of coins for " << value << " is " << solver.min(value) << "\n"; } { int value = 9; std::cout << "Minimum number of coins for " << value << " is " << solver.min(value) << "\n"; } { int value = 21; std::cout << "Minimum number of coins for " << value << " is " << solver.min(value) << "\n"; } }
Add solution for 21. Merge Two Sorted Lists.
/** * link: https://leetcode.com/problems/merge-two-sorted-lists/ * Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. */ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { if (l1 == NULL) return l2; if (l2 == NULL) return l1; ListNode *head; ListNode *current = head = NULL; while (l1 && l2) { if (l1->val <= l2->val) { if (current == NULL) { current = head = l1; } else { current->next = l1; current = current->next; } l1 = l1->next; } else { if (current == NULL) { current = head = l2; } else { current->next = l2; current = current->next; } l2 = l2->next; } current->next = NULL; } if (l2) current->next = l2; if (l1) current->next = l1; return head; } };
Add test for event.cc changes to name_spec parsing
#include "wtf/event.h" #include <fstream> #include "testing/base/public/gunit.h" namespace wtf { namespace { class EventTest : public ::testing::Test { protected: void TearDown() override {} EventDefinition CreateEventDefinition(const char *name_spec) { return EventDefinition::Create<int, const char*>( /*wire_id=*/0, EventClass::kScoped, /*flags=*/0, name_spec); } }; TEST_F(EventTest, CheckNameSpecParsing) { std::string output; auto event = CreateEventDefinition("MyFunc"); event.AppendName(&output); EXPECT_EQ(output, "MyFunc"); output.clear(); event.AppendArguments(&output); EXPECT_EQ(output, "int32 a0, ascii a1"); output.clear(); event = CreateEventDefinition("MyNamespace::MyClass::MyFunc"); event.AppendName(&output); EXPECT_EQ(output, "MyNamespace#MyClass#MyFunc"); output.clear(); event.AppendArguments(&output); EXPECT_EQ(output, "int32 a0, ascii a1"); output.clear(); event = CreateEventDefinition("MyClass::MyFunc2: arg1 , arg2"); event.AppendName(&output); EXPECT_EQ(output, "MyClass#MyFunc2"); output.clear(); event.AppendArguments(&output); EXPECT_EQ(output, "int32 arg1, ascii arg2"); output.clear(); event = CreateEventDefinition("MyFunc2: arg1 , arg2"); event.AppendName(&output); EXPECT_EQ(output, "MyFunc2"); output.clear(); event.AppendArguments(&output); EXPECT_EQ(output, "int32 arg1, ascii arg2"); output.clear(); event = CreateEventDefinition("MyFunc3: arg1"); event.AppendName(&output); EXPECT_EQ(output, "MyFunc3"); output.clear(); event.AppendArguments(&output); EXPECT_EQ(output, "int32 arg1, ascii a1"); } } // namespace } // namespace wtf int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
Add a regression test for merging anon decls in extern C contexts.
// RUN: rm -rf %t // RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -verify %s // expected-no-diagnostics #pragma clang module build sys_types module sys_types {} #pragma clang module contents #pragma clang module begin sys_types extern "C" { typedef union { bool b; } pthread_mutex_t; } #pragma clang module end #pragma clang module endbuild typedef union { bool b; } pthread_mutex_t; #pragma clang module import sys_types const pthread_mutex_t *m;
Correct shared ownership sample code
// Shared ownership #include <memory> #include <utility> struct foo {}; void func(std::shared_ptr<foo> obj) { } int main() { std::shared_ptr<foo> obj = std::make_shared<foo>(); pass_shared_ownership(obj); } // Share ownership of a dynamically allocated object with another // unit of code. // // On [13], we create a [`std::shared_ptr`](cpp/memory/shared_ptr) // which has ownership of a dynamically allocated `foo` object // (allocated with the [`std::make_shared`](cpp/memory/shared_ptr/make_shared) // utility function). [!14] then demonstrates sharing ownership of this // object with a function. That is, both `main` and `func` have access // to the same `foo` object. When ownership of an object is shared, it // will only be destroyed when all `std::shared_ptr`s owning it are // destroyed. // // In other cases, you may instead wish to [transfer unique ownership // of an object](/common-tasks/memory-management/transfer-ownership-of-object.html).
// Shared ownership #include <memory> #include <utility> struct foo {}; void func(std::shared_ptr<foo> obj) { } int main() { std::shared_ptr<foo> obj = std::make_shared<foo>(); func(obj); } // Share ownership of a dynamically allocated object with another // unit of code. // // On [13], we create a [`std::shared_ptr`](cpp/memory/shared_ptr) // which has ownership of a dynamically allocated `foo` object // (allocated with the [`std::make_shared`](cpp/memory/shared_ptr/make_shared) // utility function). [!14] then demonstrates sharing ownership of this // object with a function. That is, both `main` and `func` have access // to the same `foo` object. When ownership of an object is shared, it // will only be destroyed when all `std::shared_ptr`s owning it are // destroyed. // // In other cases, you may instead wish to [transfer unique ownership // of an object](/common-tasks/memory-management/transfer-ownership-of-object.html).
Add a solution for task 8b
#include <cstdio> #include <vector> using namespace std; const int N = 1 << 10; vector <int> graph[N]; bool visited[N]; int m; void input() { scanf("%d\n", &m); for (int i = 0; i < m; i++) { int u, v; scanf("%d%d", &u, &v); graph[u].push_back(v); } } void dfs(int u) { visited[u] = 1; printf("%d ", u); for (int i = 0; i < graph[u].size(); i++) { int v = graph[u][i]; if (!visited[v]) { dfs(v); } } } int main() { input(); dfs(1); printf("\n"); return 0; }
Add fixed time step sample
// Fixed time step // C++11, C++14 #include <chrono> #include <thread> using namespace std::literals::chrono_literals; void some_complex_work(); int main() { using clock = std::chrono::steady_clock; clock::time_point next_time_point = clock::now() + 5s; some_complex_work(); std::this_thread::sleep_until(next_time_point); } // Block the execution of a thread until a fixed point in time. // // For the purposes of this sample, we use // [`std::chrono::steady_clock`](cpp/chrono/steady_clock) ([13]), // although any other clock will suffice. // // On [14], we create a `clock::time_point` representing the point in // time five seconds from now. To do so, we use `clock::now()` to get // the current time point and add the duration of `5s` to it. Here we // have used one of C++14's [duration literal // suffixes](http://en.cppreference.com/w/cpp/chrono/duration#Literals) // to representing a duration with the seconds suffix, `s`. The // `using` directive on [7] is required in order to use these suffixes. // For C++11, the duration can be constructed manually. // // After performing some complex work on [16], we then call // [`std::this_thread::sleep_until`](cpp/thread/sleep_until) on [18], // passing it the time point we computed earlier. This blocks the // current thread until we have reached that time point, ensuring that // execution continues exactly five seconds after the starting time, // regardless of how much time the complex work took (unless it took // more than five seconds). // // This technique is most commonly used in a loop to ensure that the // loop iterates with a fixed time step. Alternatively, if you want to // sleep for a fixed amount of time, see the [sleep // sample](/common-tasks/sleep.html). void some_complex_work() { }
Add c++11 thread creation with function pointer. It generates random vector of 1024 integers and creates two threads to summarize bottom and top half respectfully.
#include <iostream> #include <vector> #include <thread> #include <algorithm> #include <cstdlib> void accumulator_function2(const std::vector<int> &v, unsigned long long &acm, unsigned int beginIndex, unsigned int endIndex) { acm = 0; for (unsigned int i = beginIndex; i < endIndex; ++i) { acm += v[i]; } } int main() { unsigned long long acm1 = 0; unsigned long long acm2 = 0; std::vector<int> v(1024); srand(time(nullptr)); std::generate(v.begin(), v.end(), [&v]() { return rand() % v.size(); } ); for_each(begin(v), end(v), [](int i) { std::cout << i << ' '; } ); std::thread t1(accumulator_function2, std::ref(v), std::ref(acm1), 0, v.size() / 2); std::thread t2(accumulator_function2, std::ref(v), std::ref(acm2), v.size() / 2, v.size()); t1.join(); t2.join(); std::cout << "acm1: " << acm1 << std::endl; std::cout << "acm2: " << acm2 << std::endl; std::cout << "acm1 + acm2: " << acm1 + acm2 << std::endl; return 0; }
Put example code in repo
#include "Software/NeuralNet.h" #include "Software/Backpropagation.h" #include <iostream> /* This is example code which runs a Backpropagating neural network. It is supposed to double any input number. This is the example code from the readme of https://github.com/FidoProject/Fido To compile, run in terminal: fcc linear.cpp This will make an executable file a.out which will be this program. PS. Try tweaking the paramaters of the backprop initialization to make the nerual network more correct */ int main() { // Creates a neural network with // 1 input, 1 output, 2 hidden layers, 4 neurons per hidden layer, and a sigmoid activation function. net::NeuralNet neuralNetwork = net::NeuralNet(1, 1, 2, 4, "sigmoid"); std::vector< std::vector<double> > input = { {1}, {2}, {5}, {6} }; std::vector< std::vector<double> > correctOutput = { {2}, {4}, {10}, {12} }; neuralNetwork.setOutputActivationFunction("simpleLinear"); // Create backpropagation object with // a learning rate of 10%, a momentum term of 0.001, an acceptable error level of 5%, // and a maximum number of training iterations of 10000 net::Backpropagation backprop = net::Backpropagation(0.1, 0.001, 0.05, 1000000); backprop.trainOnData(&neuralNetwork, input, correctOutput); // Cycle through inputs and print the outputs for (std::vector<double> current: input) { std::vector<double> final = neuralNetwork.getOutput(current); std::cout << "Correct answer: " << current[0] << "\tActual answer:" << final[0] << std::endl; } }
Add check of B+Tree / Set
/* * Copyright (c) 2021-2022-2022, Patrick Pelissier * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * + Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * + Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <set> #include "m-bptree.h" BPTREE_DEF(tree_int, 5, int) // Transform an integer 'i' into a M*LIB base item 'a' #define TYPE_SET_INT(a, i) (a) = (i) // Container OPLIST #define CONT_OPL BPTREE_OPLIST(tree_int, M_OPL_int()) // C++ Base class of the item in the container #define BASE_CLASS int // Transform an integer 'i' into a C++ base item 'a' #define CLASS_SET_INT(a, i) (a) = (i) // C++ Container class #define CONT_CLASS std::set<int> // Compare the M*LIB container a to the C++ container b #define CMP_CONT(a, b) cmp_cont(a, b) // Compate the M*LIB base object to the C++ base object #define CMP_BASE(a, b) assert( (a) == (b) ) void cmp_cont(const tree_int_t a, const std::set<int> &b) { tree_int_it_t ita; tree_int_it(ita, a); auto itb = b.begin(); while (itb != b.end()) { assert(!tree_int_end_p(ita)); const int *b0 = tree_int_cref(ita); const int &b1 = *itb; CMP_BASE(*b0, b1); itb++; tree_int_next(ita); } assert(tree_int_end_p(ita)); } #define DEFAULT_NUMBER 1000000 #define push_back insert #include "check-generic.hpp"
Add Solution for Problem 034
// 034. Search for a Range /** * Given a sorted array of integers, find the starting and ending position of a given target value. * * Your algorithm's runtime complexity must be in the order of O(log n). * * If the target is not found in the array, return [-1, -1]. * * For example, * Given [5, 7, 7, 8, 8, 10] and target value 8, * return [3, 4]. * * Tags: Array, Binary Search * * Similar Problems: (E)First Bad Version */ #include "stdafx.h" #include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { vector<int> range; range.push_back(-1); range.push_back(-1); int n = nums.size(); int left = 0, right = n - 1; if ((n == 0) || (nums[left] > target) || (nums[right] < target)) { return range; } if (nums[left] == nums[right]) { range[0] = 0; range[1] = n - 1; return range; } // binary search left: finding the first value >= target int mid = 0; while (left <= right) { mid = (left + right) / 2; if (target > nums[mid]) { left = mid + 1; } else { right = mid - 1; } } range[0] = left; // binary search right: finding the last value <= target left = 0, right = n - 1; while (left <= right) { mid = (left + right) / 2; if (target < nums[mid]) { right = mid - 1; } else { left = mid + 1; } } range[1] = right; // if first > last, not found if (range[0] > range[1]) { range[0] = -1; range[1] = -1; } return range; } }; int _tmain(int argc, _TCHAR* argv[]) { vector<int> nums; nums.push_back(5); nums.push_back(7); nums.push_back(7); nums.push_back(8); nums.push_back(8); nums.push_back(10); int target = 10; Solution mySolution; vector<int> res = mySolution.searchRange(nums, target); cout << "[" << res[0] << "," << res[1] << "]" << endl; system("pause"); return 0; }
Add Solution for Problem 124
// 124. Binary Tree Maximum Path Sum /** * Given a binary tree, find the maximum path sum. * * For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root. * * For example: * Given the below binary tree, * * 1 * / \ * 2 3 * Return 6. * * Tags: Tree, Depth-first Search * * Author: Kuang Qin */ #include "stdafx.h" #include <windows.h> using namespace std; /** * Definition for a binary tree node. */ struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { int curMax; public: int maxPathSum(TreeNode* root) { curMax = INT_MIN; dfs(root); return curMax; } // if we look at each individual nodes, there are only 3 possiblities: // a) Left branch: root->val + left // b) Right branch: root->val + right // c) Both branches: root->val + left + right // // a) or b): it can be accumulated between different nodes, so we use them as the return value in the recursion // c): it can be only a local maximum, so we compare it to the global maximum and keep whichever is larger int dfs(TreeNode* root) { if (!root) return 0; int left = max(dfs(root->left), 0); // if left child val < 0, keep only the parent node value int right = max(dfs(root->right), 0); // if right child val < 0, keep only the parent node value curMax = max(curMax, root->val + left + right); // compare the global max to possible local max return root->val + max(left, right); // choose whichever is larger } }; int _tmain(int argc, _TCHAR* argv[]) { return 0; }
Add forgotten to commit file.
//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Baozeng Ding <sploving1@gmail.com> // author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch> //------------------------------------------------------------------------------ #include "cling/Interpreter/RuntimeExceptions.h" #include "clang/Basic/SourceLocation.h" #include "clang/Sema/Sema.h" #include "clang/Sema/SemaDiagnostic.h" namespace cling { namespace runtime { cling_null_deref_exception::cling_null_deref_exception( void* Loc, clang::Sema* S) : m_Location(*(unsigned *)Loc), m_Sema(S){} cling_null_deref_exception::~cling_null_deref_exception() {} void cling_null_deref_exception::what() throw() { clang::DiagnosticsEngine& Diag = m_Sema->getDiagnostics(); Diag.Report(clang::SourceLocation::getFromRawEncoding(m_Location), clang::diag::warn_null_arg); } } // end namespace runtime } // end namespace cling
Implement longest common subsequence length
/** * Longest Common Subsequence: * Given two strings, find longest common subsequence between them. * https://www.youtube.com/watch?v=NnD96abizww&index=2&list=PLrmLmBdmIlpsHaNTPP_jHHDx_os9ItYXr */ #include <iostream> using namespace std; void print(unsigned int **T, int M, int N) { for (int i = 0; i <= M; i++) { for (int j = 0; j <= N; j++) { cout<<T[i][j]<<" "; } cout<<endl; } cout<<endl; } int max(int a, int b) { return a > b ? a : b; } int findCommonSubsequence(char str1[], char str2[], int M, int N) { unsigned int solution = 0; unsigned int **T = new unsigned int*[M+1]; for (int i = 0; i <= M; i++) T[i] = new unsigned int[N+1]; //print(T, M, N); for (int i = 1; i <= M; i++) { for (int j = 1; j <= N; j++) { if (str1[j-1] == str2[i-1]) { T[i][j] = T[i-1][j-1] + 1; } else T[i][j] = max(T[i-1][j], T[i][j-1]); } } print(T, M, N); solution = T[M][N]; for (int i = 0; i <= M; i++) delete [] T[i]; delete [] T; return solution; } int main() { char str1[] = {'a', 'b', 'e', 'l', 'k', 'q', 'd'}; int N = sizeof (str1)/sizeof(str1[0]); char str2[] = {'b','l','a','q','m', 'd', 'b'}; int M = sizeof (str2)/sizeof(str2[0]); cout<<findCommonSubsequence(str1, str2, M, N)<<endl; return 0; }
Fix the linux redux build.
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/crypto_module_password_dialog.h" #include "base/logging.h" namespace chrome { void UnlockSlotsIfNecessary(const net::CryptoModuleList& modules, CryptoModulePasswordReason reason, const std::string& host, const base::Closure& callback) { // TODO(bulach): implement me. NOTREACHED(); } void UnlockCertSlotIfNecessary(net::X509Certificate* cert, CryptoModulePasswordReason reason, const std::string& host, const base::Closure& callback) { // TODO(bulach): implement me. NOTREACHED(); } } // namespace chrome
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/crypto_module_password_dialog.h" #include "base/logging.h" namespace chrome { void UnlockSlotsIfNecessary(const net::CryptoModuleList& modules, CryptoModulePasswordReason reason, const std::string& host, gfx::NativeWindow parent, const base::Closure& callback) { // TODO(bulach): implement me. NOTREACHED(); } void UnlockCertSlotIfNecessary(net::X509Certificate* cert, CryptoModulePasswordReason reason, const std::string& host, gfx::NativeWindow parent, const base::Closure& callback) { // TODO(bulach): implement me. NOTREACHED(); } } // namespace chrome
Add unit test for timer implementation.
/* * Copyright 2014-2015 CyberVision, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <boost/test/unit_test.hpp> #include <thread> #include "kaa/utils/KaaTimer.hpp" namespace kaa { std::int32_t counter = 0; void increment(void) { counter++; } void resetCounter() { counter = 0; } BOOST_AUTO_TEST_SUITE(KaaTimerTestSuite) BOOST_AUTO_TEST_CASE(SuccessTimerTriggerTest) { std::size_t timeToWait = 4; KaaTimer<void (void)> timer; timer.start(timeToWait, [] { increment(); }); std::this_thread::sleep_for(std::chrono::seconds(timeToWait / 2)); BOOST_CHECK_EQUAL(counter, 0); std::this_thread::sleep_for(std::chrono::seconds(timeToWait / 2 + 1)); BOOST_CHECK_EQUAL(counter, 1); resetCounter(); } BOOST_AUTO_TEST_CASE(StopTimerTest) { std::size_t timeToWait = 4; KaaTimer<void (void)> timer; timer.start(timeToWait, [] { increment(); }); std::this_thread::sleep_for(std::chrono::seconds(timeToWait / 2)); BOOST_CHECK_EQUAL(counter, 0); timer.stop(); std::this_thread::sleep_for(std::chrono::seconds(timeToWait / 2 + 1)); BOOST_CHECK_EQUAL(counter, 0); resetCounter(); } BOOST_AUTO_TEST_SUITE_END() }
Add missing C++ source file.
#include <Rcpp.h> #include "s2/s2latlng.h" #include "s2/s2cellid.h" //' @title //' cell_center //' @description //' Get center of S2 cell containing a specified point //' //' @param lat latitude of interest (between -90 and +90) //' //' @param lng longitude of interest (between -180 and +180) //' //' @details //' \code{cell_center} takes a single (lat,lng) point on the sphere, finds the //' S2 leaf cell that contains this point and returns the center of this cell. //' In S2 leaf cells have a very fine resolution, so the output is expected to //' be very close to the input, and differences are typically on something like //' the 5th decimal place. //' //' @examples //' cell_center(57.0139595, 9.988967) //' //' @export //[[Rcpp::export]] Rcpp::NumericVector cell_center(double lat, double lng) { S2LatLng p = S2LatLng::FromDegrees(lat, lng); S2CellId id = S2CellId::FromLatLng(p); S2LatLng center = id.ToLatLng(); Rcpp::NumericVector rslt(2); rslt[0] = center.lat().degrees(); rslt[1] = center.lng().degrees(); return rslt; }
Add test for a bad fold.
#include <stdio.h> #include "Halide.h" using namespace Halide; int main(int argc, char **argv) { Var x, y, c; Func f, g; f(x, y) = x; g(x, y) = f(x-1, y+1) + f(x, y-1); f.store_root().compute_at(g, y).fold_storage(y, 2); Image<int> im = g.realize(100, 1000); printf("Should have gotten a bad fold!\n"); return -1; }
Add Chapter 25, Try This 3
// Chapter 25, Try This 3: get bits example to work, try a few values #include<iostream> #include<iomanip> #include<bitset> using namespace std; int main() { int i; while (cin>>i) cout << dec << i << " == " << hex << "0x" << setw(8) << setfill('0') << i << " == " << bitset<8*sizeof(int)>(i) << '\n'; }
Disable flaky ExtensionApiTest.Debugger on Linux and Chrome OS.
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" // Debugger is flaky on browser_tests on Windows: crbug.com/234166. #if defined(OS_WIN) #define MAYBE(x) DISABLED_##x #else #define MAYBE(x) x #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE(Debugger)) { ASSERT_TRUE(RunExtensionTest("debugger")) << message_; }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" // Debugger is flaky on browser_tests on Windows, Linux, and Chrome OS: // crbug.com/234166. #if defined(OS_WIN) || defined(OS_LINUX) || defined(OS_CHROMEOS) #define MAYBE(x) DISABLED_##x #else #define MAYBE(x) x #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE(Debugger)) { ASSERT_TRUE(RunExtensionTest("debugger")) << message_; }
Add Factory method design pattern.
#include <stdio.h> #include <string> class Shape { public: virtual void draw() = 0; }; class Rectangle : public Shape { public: void draw() override { printf("Drawing Rectangle \n"); } }; class Square : public Shape { public: void draw() override { printf("Drawing Square \n"); } }; class Circle : public Shape { public: void draw() override { printf("Drawing Circle \n"); } }; class ShapeFactory { public: Shape* GetShape(std::string str) { if (str.find("Rectangle") != std::string::npos) { return new Rectangle(); } else if (str.find("Square") != std::string::npos) { return new Square(); } else if (str.find("Circle") != std::string::npos) { return new Circle(); } else { return nullptr; } } }; int main(int argc, char const* argv[]) { ShapeFactory shapeFactory; Shape* shape1 = shapeFactory.GetShape("Rectangle"); shape1->draw(); Shape* shape2 = shapeFactory.GetShape("Square"); shape2->draw(); Shape* shape3 = shapeFactory.GetShape("Circle"); shape3->draw(); return 0; }
Remove Duplicates from Sorted Array
class Solution { public: int removeDuplicates(vector<int>& nums) { int nlen = 1, n = nums.size();; if(n <= 1) return n; for(int i=1; i < nums.size();i++){ if(nums[i] != nums[i-1]){ nums[nlen++] = nums[i]; } } return nlen; } };
Add Bellman Ford Algorithm to graph search in c++
// // main.cpp // backToProblemSolving // // Created by Khaled Abdelfattah on 6/27/17. // Copyright © 2017 Khaled Abdelfattah. All rights reserved. // #include <bits/stdc++.h> using namespace std; typedef long long ll; #define MAX 1000000000 #define BASE1 23 #define BASE2 31 #define MOD1 1000000007 #define MOD2 217645177 #define EPS 1e-6 #define SIZE 20005 int n, m; vector<pair<pair<int, int>, int>> edges; int bestDist[SIZE]; void Bellman_Ford (int s) { memset(bestDist, INT_MAX, n + 1); bestDist[s] = 0; for (int i = 0; i < n - 1; i ++) { bool relaxed = false; for (int j = 0; j < edges.size(); j ++) { int from = edges[j].first.first, to = edges[j].first.second; int dist = edges[j].second; if (bestDist[from] + dist < bestDist[to]) { bestDist[to] = bestDist[from] + dist; relaxed = true; } } if (!relaxed) break; } } bool hasNegCycle () { for (int j = 0; j < edges.size(); j ++) { int from = edges[j].first.first, to = edges[j].first.second; int dist = edges[j].second; if (bestDist[from] + dist < bestDist[to]) { return true; } } return false; } int main() { n = 6; m = 5; edges.push_back(make_pair(make_pair(1, 2), -2)); edges.push_back(make_pair(make_pair(1, 3), 5)); edges.push_back(make_pair(make_pair(2, 3), -2)); edges.push_back(make_pair(make_pair(3, 4), 7)); edges.push_back(make_pair(make_pair(4, 5), -12)); Bellman_Ford(1); for (int i = 1; i <= n; i ++) cout << bestDist[i] << " "; cout << endl; cout << hasNegCycle(); return 0; }
Support CHROME like format for pkcs8, spki EC keys
#include "ec_gen.h" Handle<ScopedEVP_PKEY> EC_generate(int &nidEc) { LOG_FUNC(); Handle<ScopedEVP_PKEY> pkey; ScopedEC_KEY eckey(EC_KEY_new_by_curve_name(nidEc)); if (eckey.isEmpty()) { THROW_OPENSSL("EC_KEY_new_by_curve_name"); } if (!EC_KEY_generate_key(eckey.Get())) { THROW_OPENSSL("EC_KEY_generate_key"); } pkey = Handle<ScopedEVP_PKEY>(new ScopedEVP_PKEY(EVP_PKEY_new())); if (EVP_PKEY_assign_EC_KEY(pkey->Get(), eckey.Get()) != 1) { THROW_OPENSSL("EVP_PKEY_assign_EC_KEY"); } eckey.unref(); return pkey; }
#include "ec_gen.h" Handle<ScopedEVP_PKEY> EC_generate(int &nidEc) { LOG_FUNC(); Handle<ScopedEVP_PKEY> pkey; ScopedEC_KEY eckey(EC_KEY_new_by_curve_name(nidEc)); if (eckey.isEmpty()) { THROW_OPENSSL("EC_KEY_new_by_curve_name"); } if (!EC_KEY_generate_key(eckey.Get())) { THROW_OPENSSL("EC_KEY_generate_key"); } /** * Current flag is needed to get a CHROME like pkcs8, spki output */ EC_GROUP *group = (EC_GROUP *)EC_KEY_get0_group(eckey.Get()); EC_GROUP_set_asn1_flag(group, OPENSSL_EC_NAMED_CURVE); pkey = Handle<ScopedEVP_PKEY>(new ScopedEVP_PKEY(EVP_PKEY_new())); if (EVP_PKEY_assign_EC_KEY(pkey->Get(), eckey.Get()) != 1) { THROW_OPENSSL("EVP_PKEY_assign_EC_KEY"); } eckey.unref(); return pkey; }
Check if All A's Appears Before All B's
class Solution { public: bool checkString(string s) { bool b_found = false; for (const auto& c : s) { if (c == 'a' && b_found) return false; if (c == 'b') b_found = true; } return true; } };
Set the default ASan options for the Official Chrome build.
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "build/build_config.h" #include "chrome/browser/first_run/upgrade_util.h" // The entry point for all invocations of Chromium, browser and renderer. On // windows, this does nothing but load chrome.dll and invoke its entry point in // order to make it easy to update the app from GoogleUpdate. We don't need // that extra layer with on linux. extern "C" { int ChromeMain(int argc, const char** argv); } int main(int argc, const char** argv) { int return_code = ChromeMain(argc, argv); #if defined(OS_LINUX) // Launch a new instance if we're shutting down because we detected an // upgrade in the persistent mode. upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded(); #endif return return_code; }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "build/build_config.h" #include "chrome/browser/first_run/upgrade_util.h" // The entry point for all invocations of Chromium, browser and renderer. On // windows, this does nothing but load chrome.dll and invoke its entry point in // order to make it easy to update the app from GoogleUpdate. We don't need // that extra layer with on linux. #if defined(ADDRESS_SANITIZER) && defined(GOOGLE_CHROME_BUILD) const char *kAsanDefaultOptions = "quarantine_size=1048576"; // Override the default ASan options for the Google Chrome executable. // __asan_default_options should not be instrumented, because it is called // before ASan is initialized. extern "C" __attribute__((no_address_safety_analysis)) const char *__asan_default_options() { return kAsanDefaultOptions; } #endif extern "C" { int ChromeMain(int argc, const char** argv); } int main(int argc, const char** argv) { int return_code = ChromeMain(argc, argv); #if defined(OS_LINUX) // Launch a new instance if we're shutting down because we detected an // upgrade in the persistent mode. upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded(); #endif return return_code; }
Add a test for the -c flag.
// Test that the -c flag works. // RUN: llvmc -c %s -o %t.o // RUN: llvmc --linker=c++ %t.o -o %t // RUN: %abs_tmp | grep hello // XFAIL: vg #include <iostream> int main() { std::cout << "hello" << '\n'; }
Add Solution for 019 Remove Nth Node From End of List
// 19. Remove Nth Node From End of List /** * Given a linked list, remove the nth node from the end of list and return its head. * * For example, * * Given linked list: 1->2->3->4->5, and n = 2. * * After removing the second node from the end, the linked list becomes 1->2->3->5. * * Note: * Given n will always be valid. * Try to do this in one pass. * * Tags: Linked List, Two Pointers * * Author: Kuang Qin */ #include <iostream> using namespace std; /** * Definition for singly-linked list. */ struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} ListNode(int x, ListNode *p) : val(x), next(p) {} }; class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { // use a dummy node to mark the head of the list ListNode dummy(0); dummy.next = head; // set two pointer difference by n ListNode *slow = &dummy, *fast = slow; for (int i = 0; i < n; i++) { fast = fast->next; } // move fast to the last element // find the node to be removed: slow->next while (fast->next != NULL) { slow = slow->next; fast = fast->next; } // remove the node fast = slow->next; slow->next = fast->next; delete fast; return dummy.next; } }; int main() { ListNode node5(5), node4(4, &node5), node3(3, &node4), node2(2, &node3), node1(1, &node2); Solution sol; ListNode *newhead = sol.removeNthFromEnd(&node1, 5); for (ListNode *p = newhead; p != NULL; p = p->next) { cout << p->val << " "; } cout << endl; cin.get(); return 0; }
Delete Node in a BST
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: TreeNode* deleteNode(TreeNode* root, int key) { if (!root) return root; if (root->val < key) { root->right = deleteNode(root->right, key); } else if (root->val > key) { root->left = deleteNode(root->left, key); } else { if (!root->left && !root->right) { delete(root); return nullptr; } else if (!root->left && root->right) { auto ret = root->right; delete(root); return ret; } else if (root->left && !root->right) { auto ret = root->left; delete(root); return ret; } else { auto removal = root->right; while (removal->left) { removal = removal->left; } root->val = removal->val; root->right = deleteNode(root->right, root->val); } } return root; } };
Insert into a Binary Search Tree
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: TreeNode* insertIntoBST(TreeNode* root, int val) { if (!root) { TreeNode* newroot = new TreeNode{val}; return newroot; } if (val < root->val) { root->left = insertIntoBST(root->left, val); } else { root->right = insertIntoBST(root->right, val); } return root; } };
Add a solution for task 9a
#include <cstdio> using namespace std; const int N = 1 << 10; int a[N][N], m; int INF = 1 << 20; int n = 0; void input() { for (int i = 0; i < m; i++) { int u, v, d; scanf("%d%d%d", &u, &v, &d); a[u][v] = d; if (u > n) n = u; if (v > n) n = v; } } void floyd() { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (a[i][j] == 0) a[i][j] = INF; } } for (int k = 1; k <= n; k++) { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (a[i][j] > (a[i][k] + a[k][j])) { a[i][j] = a[i][k] + a[k][j]; } } } } for (int i = 1; i <= n; i++) { a[i][i] = 0; } } void print_graph() { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (a[i][j] == INF) printf("-1 "); else printf("%d ", a[i][j]); } printf("\n"); } } void clear_graph() { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { a[i][j] = 0; } } n = 0; } int main() { while (scanf("%d", &m) != EOF) { input(); floyd(); print_graph(); clear_graph(); } return 0; }
Add an example C++ code from real life
//kinda-sorta functional code from Real Life (tm): // The operator<() will sort this vector by version in descending order, // placing pure AutoCAD first in respective sequence of matching versions. std::sort (values.begin (), values.end ()); // The operator==() will eliminate adjacent elements with matching version // numbers (ignoring product code names). std::unique (values.begin (), values.end ()); // By now, we have only the values that we want to write to versionized CurVers. std::for_each (values.begin (), values.end (), boost::bind (&setCurVer, hModule, _1)); AutoCadInfoVector pureAcadsOnly; pureAcadsOnly.reserve (values.size ()); // Remove AutoCAD verticals if any remains. std::remove_copy_if (values.begin (), values.end (), std::back_inserter (pureAcadsOnly), std::not1 (std::mem_fun_ref (&AutoCadInfo::isPureAutoCad))); // Non-versionized CurVer will hold the latest pure AutoCAD, if available, // or some latest vertical otherwise. if (pureAcadsOnly.empty ()) setNonVersionizedCurVer (hModule, values[0]); else setNonVersionizedCurVer (hModule, pureAcadsOnly[0]);
Add test during development for parser.
#include "HSHumanoidNodeParser.hpp" namespace dynamicsJRLJapan { namespace HumanoidSpecificitiesData { namespace fusion = boost::fusion; namespace phoenix = boost::phoenix; namespace qi = boost::spirit::qi; namespace ascii = boost::spirit::ascii; int ReadXMLData3(std::string &aFileName, HumanoidNode &ast) { std::ifstream in((char *)aFileName.c_str(), std::ios_base::in); if (!in) { std::cerr << "Error: Could not open input file: " << aFileName << std::endl; return 1; } std::string storage; // We will read the contents here. in.unsetf(std::ios::skipws); // No white space skipping! std::copy( std::istream_iterator<char>(in), std::istream_iterator<char>(), std::back_inserter(storage)); struct HumanoidNode_parser<std::string::const_iterator> hsxml; // Our grammar using boost::spirit::ascii::space; std::string::const_iterator iter = storage.begin(); std::string::const_iterator end = storage.end(); // this will print something like: boost::fusion::vector2<int, double> display_attribute_of_parser(hsxml); bool r = phrase_parse(iter, end, hsxml, space, ast); if (r && iter == end) { std::cout << "-------------------------\n"; std::cout << "Parsing succeeded\n"; std::cout << "-------------------------\n"; return 0; } else { std::string::const_iterator some = iter+30; std::string context(iter, (some>end)?end:some); std::cout << "-------------------------\n"; std::cout << "Parsing failed\n"; std::cout << "stopped at: \": " << context << "...\"\n"; std::cout << "-------------------------\n"; return 1; } } }; }; int main() { namespace dhs=dynamicsJRLJapan::HumanoidSpecificitiesData; std::string aFileName("/home/stasse/devel/openrobots/share/hrp2_14/HRP2Specificities.xml"); dhs::HumanoidNode ahn; dhs::ReadXMLData3(aFileName,ahn); std::cout <<ahn <<std::endl; }
Add missing file from r300155.
//===--------------- RPCUtils.cpp - RPCUtils implementation ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // RPCUtils implementation. // //===----------------------------------------------------------------------===// #include "llvm/ExecutionEngine/Orc/RPCUtils.h" char llvm::orc::rpc::RPCFatalError::ID = 0; char llvm::orc::rpc::ConnectionClosed::ID = 0; char llvm::orc::rpc::ResponseAbandoned::ID = 0; char llvm::orc::rpc::CouldNotNegotiate::ID = 0; namespace llvm { namespace orc { namespace rpc { std::error_code ConnectionClosed::convertToErrorCode() const { return orcError(OrcErrorCode::RPCConnectionClosed); } void ConnectionClosed::log(raw_ostream &OS) const { OS << "RPC connection already closed"; } std::error_code ResponseAbandoned::convertToErrorCode() const { return orcError(OrcErrorCode::RPCResponseAbandoned); } void ResponseAbandoned::log(raw_ostream &OS) const { OS << "RPC response abandoned"; } CouldNotNegotiate::CouldNotNegotiate(std::string Signature) : Signature(std::move(Signature)) {} std::error_code CouldNotNegotiate::convertToErrorCode() const { return orcError(OrcErrorCode::RPCCouldNotNegotiateFunction); } void CouldNotNegotiate::log(raw_ostream &OS) const { OS << "Could not negotiate RPC function " << Signature; } } // end namespace rpc } // end namespace orc } // end namespace llvm
Add the solution to determine whether there's a cycle in a linked list.
#include<iostream> #include<cstdio> #include<cstdlib> using namespace std; struct Node { int data; Node* next; }; int HasCycle(Node* head) { Node* slow = head; Node* fast = head; while (fast != NULL && fast->next != NULL) { slow = slow->next; fast = fast->next->next; if (slow == fast) { break; } } return (fast == NULL || fast->next == NULL) ? 0 : 1; } int main() { Node *A, *B, *C, *D,*E,*F; A = new Node(); B= new Node(); C= new Node(); D = new Node(); E = new Node(); F= new Node(); // case 1: NULL list if(HasCycle(NULL)) cout<<"1"; else cout<<"0"; //case 2: A->next = B; B->next = C; C->next = A; if(HasCycle(A)) cout<<"1"; else cout<<"0"; //case 3: A->next = B; B->next = C; C->next = D; D->next = E; E->next = F; F->next = E; if(HasCycle(A)) cout<<"1"; else cout<<"0"; //case 4: A->next = B; B->next = C; C->next = D; D->next = E; E->next = F; F->next = NULL; if(HasCycle(A)) cout<<"1"; else cout<<"0"; // case 5: A->next = B; B->next = C; C->next = D; D->next = E; E->next = F; F->next = A; if(HasCycle(A)) cout<<"1"; else cout<<"0"; }
Write the main structure of the algorithm
// // main.c // SequentialSA // // Created by Vincent Ramdhanie on 11/27/14. // Copyright (c) 2014 Vincent Ramdhanie. All rights reserved. // #include <time.h> #include <iostream> #include <fstream> #include <iostream> #include "generator.h" #include "generator.cpp" int cost(); //cost function calculates the cost of a certain configuration void nextConfiguration(); //find another configuration void loadData(); //load all data from the input file //define some data structures int plots[PLOT_N][PLOT_M]; int main(int argc, const char * argv[]) { int S; double T; int N; srand(time(NULL)); generate(plots); print(plots); nextConfiguration();//initialize the array randomly S = cost(); T = TEMPERATURE; N = NUMBER_ITERATIONS; int SP; int deltaE; do{ printf("Intermediate value: %d\n", S); for(int i = 1; i <= N; i++){ nextConfiguration(); SP = cost(); deltaE = SP - S; if(deltaE < 0 || deltaE < T){ S = SP; } } T *= 0.99; }while(T > 0.1); printf("Final Value: %d\n", S); return 0; } void nextConfiguration(){ for(int i = 0; i < PLOT_N; i++){ for(int j = 0; j < PLOT_M; j++){ plots[i][j] = (rand() % 1000); } } } int cost(){ int sum = 0; for(int i = 0; i < PLOT_N; i++){ for(int j = 0; j < PLOT_M; j++){ sum += plots[i][j]; } } return sum; } void loadData(){ }
Add solution to week 11 Shapes problem
#include <iostream> #include <cmath> using std::cout; using std::cin; class Shape { public: virtual double perimeter() const = 0; virtual double area() const = 0; virtual void print() const = 0; }; class Rectangle: public Shape { protected: double a; double b; public: Rectangle(double _a, double _b): a(_a), b(_b) {} double perimeter() const { return 2 * (a + b); } double area() const { return a * b; } void print() const { cout << "Rectangle(" << a << ", " << b << ")\nPerimeter: " << perimeter() << "\nArea: " << area() << '\n'; } }; class Square: public Rectangle { public: Square(double _a): Rectangle(_a, _a) {} void print() const { cout << "Square(" << a << ")\nPerimeter: " << perimeter() << "\nArea: " << area() << '\n'; } }; class Circle: public Shape { double radius; public: Circle(double _radius): radius(_radius) {} double perimeter() const { return 2 * M_PI * radius; } double area() const { return M_PI * radius * radius; } void print() const { cout << "Circle(" << radius << ")\nPerimeter: " << perimeter() << "\nArea: " << area() << '\n'; } }; int main() { cout << "Choose an option (r - input a rectangle, s - input a square, c - input a circle): "; char option; cin >> option; Shape* shape = nullptr; if (option == 'r') { double a, b; cin >> a >> b; shape = new Rectangle(a, b); } else if (option == 's') { double a; cin >> a; shape = new Square(a); } else if (option == 'c') { double radius; cin >> radius; shape = new Circle(radius); } else { cout << "Option '" << option << "' doesn't exist."; return 0; } shape->print(); return 0; }
Add (failing) test that halide reports user error when called with OpenGL in bad state
#include <csetjmp> #include <unistd.h> #if defined(__APPLE__) #include <OpenGL/gl.h> #else #include <GL/gl.h> #endif #include "Halide.h" #include "HalideRuntimeOpenGL.h" std::string error_message; /* ** Don't rely on func.set_error_handler() mechanism, it doesn't seem to catch ** the user OpenGL state errors. That might be a separate bug. */ jmp_buf env; void on_sigabrt (int signum) { longjmp (env, 1); } void catching_stderr_abort(std::function<void ()> func) { auto ferr = tmpfile(); auto prev_stderr = dup(2); dup2(fileno(ferr), 2); if (setjmp (env) == 0) { auto prev_handler = signal(SIGABRT, &on_sigabrt); (func)(); signal(SIGABRT, prev_handler); } fseek(ferr, 0, SEEK_END); error_message.resize(ftell(ferr)); rewind(ferr); fread(&error_message[0], 1, error_message.size(), ferr); dup2(prev_stderr, 2); close(prev_stderr); } using namespace Halide; int main() { // This test must be run with an OpenGL target const Target &target = get_jit_target_from_environment(); if (!target.has_feature(Target::OpenGL)) { fprintf(stderr,"ERROR: This test must be run with an OpenGL target, e.g. by setting HL_JIT_TARGET=host-opengl.\n"); return 1; } Image<uint8_t> output(255, 10, 3); Var x, y, c; Func g; g(x, y, c) = Halide::cast<uint8_t>(255); g.bound(c, 0, 3); g.glsl(x, y, c); // Let Halide initialize OpenGL g.realize(output); // Bad OpenGL call leaves OpenGL in a bad state glEnableVertexAttribArray(-1); // Halide should report that the OpenGL context is in a bad state due to user code` catching_stderr_abort( [&] () { g.realize(output); } ); if (error_message.empty()) { fprintf(stderr, "Failed to report error in user OpenGL state\n"); return 1; } else if (error_message.find("user OpenGL state") == std::string::npos) { error_message.erase(error_message.size() - 1); // remove trailing newline fprintf(stderr, "Reported error '%s' rather than identifying error at 'user OpenGL state'\n", error_message.c_str()); return 1; } printf("Success!\n"); return 0; }
Add tests for dirty propagation
/** * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include <CSSLayout/CSSLayout.h> #include <gtest/gtest.h> TEST(CSSLayoutTest, dirty_propagation) { const CSSNodeRef root = CSSNodeNew(); CSSNodeStyleSetAlignItems(root, CSSAlignFlexStart); CSSNodeStyleSetWidth(root, 100); CSSNodeStyleSetHeight(root, 100); const CSSNodeRef root_child0 = CSSNodeNew(); CSSNodeStyleSetWidth(root_child0, 50); CSSNodeStyleSetHeight(root_child0, 20); CSSNodeInsertChild(root, root_child0, 0); const CSSNodeRef root_child1 = CSSNodeNew(); CSSNodeStyleSetWidth(root_child1, 50); CSSNodeStyleSetHeight(root_child1, 20); CSSNodeInsertChild(root, root_child1, 1); CSSNodeCalculateLayout(root, CSSUndefined, CSSUndefined, CSSDirectionLTR); CSSNodeStyleSetWidth(root_child0, 20); EXPECT_TRUE(CSSNodeIsDirty(root_child0)); EXPECT_FALSE(CSSNodeIsDirty(root_child1)); EXPECT_TRUE(CSSNodeIsDirty(root)); CSSNodeCalculateLayout(root, CSSUndefined, CSSUndefined, CSSDirectionLTR); EXPECT_FALSE(CSSNodeIsDirty(root_child0)); EXPECT_FALSE(CSSNodeIsDirty(root_child1)); EXPECT_FALSE(CSSNodeIsDirty(root)); } TEST(CSSLayoutTest, dirty_propagation_only_if_prop_changed) { const CSSNodeRef root = CSSNodeNew(); CSSNodeStyleSetAlignItems(root, CSSAlignFlexStart); CSSNodeStyleSetWidth(root, 100); CSSNodeStyleSetHeight(root, 100); const CSSNodeRef root_child0 = CSSNodeNew(); CSSNodeStyleSetWidth(root_child0, 50); CSSNodeStyleSetHeight(root_child0, 20); CSSNodeInsertChild(root, root_child0, 0); const CSSNodeRef root_child1 = CSSNodeNew(); CSSNodeStyleSetWidth(root_child1, 50); CSSNodeStyleSetHeight(root_child1, 20); CSSNodeInsertChild(root, root_child1, 1); CSSNodeCalculateLayout(root, CSSUndefined, CSSUndefined, CSSDirectionLTR); CSSNodeStyleSetWidth(root_child0, 50); EXPECT_FALSE(CSSNodeIsDirty(root_child0)); EXPECT_FALSE(CSSNodeIsDirty(root_child1)); EXPECT_FALSE(CSSNodeIsDirty(root)); }
Add Chapter 25, exercise 11
// Chapter 25, exercise 11: like exercise 10, but keep the bits in a bitset<32> #include<iostream> #include<bitset> using namespace std; int main() { bitset<32> bs; bs = 15121<<10; // PFN bs |= 6<<4; // CCA bs[3] = 1; // nonreachable bs[0] = 1; // global cout << "Using a bitset<32>:\n" << "PFN: " << ((bs>>10)&bitset<32>(0x3fffff)).to_ulong() << '\n' << "CCA: " << ((bs>>4)&bitset<32>(0x7)).to_ulong() << '\n' << "nonreachable: " << bs[3] << '\n' << "dirty: " << bs[2] << '\n' << "valid: " << bs[1] << '\n' << "global: " << bs[0] << '\n'; }
Add a small test case
#include "gfakluge.hpp" int main() { gfak::GFAKluge og; og.set_version(1); gfak::sequence_elem s; s.sequence = "ACCTT"; s.name = "11"; gfak::sequence_elem t; t.sequence = "TCAAGG"; t.name = "12"; gfak::sequence_elem u; u.sequence = "CTTGATT"; u.name = "13"; gfak::link_elem l; l.source_name = s.name; l.sink_name = t.name; l.source_orientation_forward = true; l.sink_orientation_forward = false; l.cigar = "4M"; gfak::link_elem m; m.source_name = t.name; m.sink_name = u.name; m.source_orientation_forward = false; m.sink_orientation_forward = true; m.cigar = "5M"; gfak::link_elem n; n.source_name = s.name; n.sink_name = u.name; n.source_orientation_forward = true; n.sink_orientation_forward = true; n.cigar = "3M"; gfak::path_elem p; p.name = "14"; p.segment_names = {s.name, t.name, u.name}; p.orientations = {true, false, true}; p.overlaps = {"4M", "5M"}; og.add_sequence(s); og.add_sequence(t); og.add_sequence(u); og.add_link(s, l); og.add_link(t, m); og.add_link(s, n); og.add_path(p.name, p); og.gfa_2_ize(); og.gfa_1_ize(); og.set_version(2.0); cout << og << endl; }
Test harness for the new TimeUtil::GetJulianDayNumber() function.
#include <iomanip> #include <iostream> #include "TimeUtil.h" int main() { std::cout << std::setprecision(10) << TimeUtil::GetJulianDayNumber() << '\n'; return 0; }
Add a solution for problem 164: Maximum Gap.
// Naive solution would first sort the numbers, then find the maximum gap. // But there is a better solution: use the pigeonhole principle. // Suppose the sorted sequence of arguments are a1, a2, ..., an. // There are n-1 gaps and the accumulated gap is an-a1. The average gap is // (an-a1)/(n-1). By the pigeonhole principle, the maximum gap is greater or // equal to the average. We could assign the numbers into n buckets [a1, a1+avg), // [a1+avg, a1+avg*2), ..., [a1+avg*(n-2), a1+avg*(n-1)), [an, an + avg). // The maximum gap can't be between two numbers in the same bucket. It must be the // maximum difference between the maximum of a lower bucket and the next minimum // of a higher bucket. Note the two buckets may not be consecutive because there // may be empty bucket. class Solution { public: int maximumGap(vector<int>& nums) { size_t n = nums.size(); if (n < 2) return 0; int maxi = *max_element(nums.begin(), nums.end()); int mini = *min_element(nums.begin(), nums.end()); int total_gap = maxi - mini; if (total_gap == 0) { //we need to divide total_gap later return 0; } vector<int> range_max(n, -1); vector<int> range_min(n, INT_MAX); for (size_t i = 0; i < n; ++i) { // The following statement is actually average=total_gap/(n-1), then (nums[i]-mini)/average // I write it as it is to avoid possible precision problems. int index = static_cast<long long>(nums[i]-mini)*(n-1)/total_gap; range_max[index] = std::max(range_max[index], nums[i]); range_min[index] = std::min(range_min[index], nums[i]); } int max_gap = 0, last = 0; for (size_t i = 1; i < n; ++i) { if (range_max[i] == -1) { continue; } max_gap = std::max(range_min[i]-range_max[last], max_gap); last = i; } return max_gap; } };
Add solution for chapter 17 test 11, 12, 13
#include <iostream> #include <bitset> #include <vector> using namespace std; template <unsigned N> class TestResult { template <unsigned M> friend ostream& operator<<(ostream&, TestResult<M>&); public: TestResult() = default; TestResult(unsigned long long u) : ans(u) { } TestResult(const string &s) : ans(s) { } TestResult(const char* cp) : ans(cp) { } //required by test 17.12 void set_answer(size_t index, bool answer = true) { ans.set(index, answer); } bool get_answer(size_t index) { return ans[index]; } size_t size() const { return ans.size(); } private: bitset<N> ans; }; template <unsigned N> ostream& operator<<(ostream &os, TestResult<N> &tr) { os << tr.ans; return os; } int main() { //test 17.11 TestResult<32> tr1(8); TestResult<10> tr2("1001010001"); cout << tr1 << endl; cout << tr2 << endl; //test 17.13 vector<bool> bvec = {1, 1, 1, 1, 1, 0, 0, 0, 0, 0}; TestResult<10> tr3; for(size_t i = 0; i != bvec.size(); ++ i) { tr3.set_answer(i, bvec[i]); } cout << tr3 << endl; //test get_answer //notice: low bit in the head for(size_t i = 0; i != tr3.size(); ++ i) { cout << tr3.get_answer(i) << ends; } cout << endl; return 0; }
Update URI validation regex to be more generic.
#include "IncomingConnectionValidator.hpp" #include <boost/algorithm/string.hpp> using namespace std; sip::IncomingConnectionValidator::IncomingConnectionValidator(std::string validUriExpression) : validUriExpression(validUriExpression), logger(log4cpp::Category::getInstance("IncomingConnectionValidator")) { vector<string> separateUris; boost::split(separateUris, validUriExpression, boost::is_any_of("\t ")); for (auto &uri : separateUris) { boost::replace_all(uri, ".", "\\."); boost::replace_all(uri, "*", "[\\+\\w]*"); uriRegexVec.push_back(boost::regex(uri)); } } bool sip::IncomingConnectionValidator::validateUri(std::string uri) { boost::regex addressRegex("[\"\\+\\w ]*<sip:([\\+\\w\\.]+@[\\w\\.]+)>"); boost::smatch s; if (not boost::regex_match(uri, s, addressRegex)) { logger.warn("URI has invalid format: %s", uri.c_str()); return false; } string rawAddress = s[1].str(); for (auto &reg : uriRegexVec) { if (boost::regex_match(rawAddress, s, reg)) { logger.info("URI %s is valid.", rawAddress.c_str()); return true; } } logger.info("URI %s not valid.", rawAddress.c_str()); return false; }
#include "IncomingConnectionValidator.hpp" #include <boost/algorithm/string.hpp> using namespace std; sip::IncomingConnectionValidator::IncomingConnectionValidator(std::string validUriExpression) : validUriExpression(validUriExpression), logger(log4cpp::Category::getInstance("IncomingConnectionValidator")) { vector<string> separateUris; boost::split(separateUris, validUriExpression, boost::is_any_of("\t ")); for (auto &uri : separateUris) { boost::replace_all(uri, ".", "\\."); boost::replace_all(uri, "*", "[\\+\\w]*"); uriRegexVec.push_back(boost::regex(uri)); } } bool sip::IncomingConnectionValidator::validateUri(std::string uri) { boost::regex addressRegex("[\"\\+\\w\\. ]*<?sip:([\\+\\w\\.]+@[\\w\\.]+)>?"); boost::smatch s; if (not boost::regex_match(uri, s, addressRegex)) { logger.warn("URI has invalid format: %s", uri.c_str()); return false; } string rawAddress = s[1].str(); for (auto &reg : uriRegexVec) { if (boost::regex_match(rawAddress, s, reg)) { logger.info("URI %s is valid.", rawAddress.c_str()); return true; } } logger.info("URI %s not valid.", rawAddress.c_str()); return false; }
Add algorithm to check if a number belong to fibo series.
#include <bits/stdc++.h> using namespace std; bool isPerfectSquare(int x){ int s = sqrt(x); return (s*s == x); } bool isFibonacci(int n){ // n is Fibinacci if one of 5*n*n + 4 or 5*n*n - 4 or both // is a perferct square, this is deduced of the discriminant //of binnets formule return isPerfectSquare(5*n*n + 4) || isPerfectSquare(5*n*n - 4); } // A utility function to test above functions int main() { for (int i = 1; i <= 10; i++) isFibonacci(i)? cout << i << " is a Fibonacci Number \n": cout << i << " is a not Fibonacci Number \n" ; return 0; }
Clean up C++ restrict test cases and add a test for restrict qualified methods.
// RUN: %llvmgxx -c -emit-llvm %s -o - | llvm-dis | grep noalias class foo { int member[4]; void bar(int * a); }; void foo::bar(int * a) __restrict { member[3] = *a; }
Add Solution for 066 Plus One
// 66. Plus One /** * Given a non-negative integer represented as a non-empty array of digits, plus one to the integer. * * You may assume the integer do not contain any leading zero, except the number 0 itself. * * The digits are stored such that the most significant digit is at the head of the list. * * Subscribe to see which companies asked this question * * Tags: Array, Math * * Similar Problems: (M) Multiply Strings, (E) Add Binary, (M) Plus One Linked List * * Author: Kuang Qin */ #include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> plusOne(vector<int>& digits) { int n = digits.size(), sum = 0, carry = 1; for (int i = n - 1; i >= 0; i--) { sum = digits[i] + carry; carry = sum / 10; digits[i] = sum % 10; if (!carry) break; // no change in the remaining digits } // if carry still exists after the most significant digit, the original array must be all '9' if (carry) { digits[0] = 1; digits.push_back(0); } return digits; } }; int main() { vector<int> digits = {9, 9, 9, 9}; Solution sol; vector<int> res = sol.plusOne(digits); for (int i = 0; i < res.size(); i++) { cout << res[i]; } cout << endl; cin.get(); return 0; }
Add solution for chapter 18, test 22
#include <iostream> using namespace std; class A { public: A() { cout << "A()" << endl; } }; class B : public A { public: B() { cout << "B()" << endl; } }; class C : public B { public: C() { cout << "C()" << endl; } }; class X { public: X() { cout << "X()" << endl; } }; class Y { public: Y() { cout << "Y()" << endl; } }; class Z : public X, public Y { public: Z() { cout << "Z()" << endl; } }; class MI : public C, public Z { public: MI() { cout << "MI()" << endl; } }; int main() { MI mi; }
Add a testcase for C++11 union support.
// RUN: %clang_cc1 -emit-llvm -g -triple x86_64-apple-darwin -std=c++11 %s -o - | FileCheck %s union E { int a; float b; int bb() { return a;} float aa() { return b;} E() { a = 0; } }; E e; // CHECK: metadata !{i32 {{.*}}, null, metadata !"E", metadata !6, i32 3, i64 32, i64 32, i64 0, i32 0, null, metadata !11, i32 0, null} ; [ DW_TAG_union_type ] // CHECK: metadata !{i32 {{.*}}, i32 0, metadata !10, metadata !"bb", metadata !"bb", metadata !"_ZN1E2bbEv", metadata !6, i32 6, metadata !17, i1 false, i1 false, i32 0, i32 0, null, i32 256, i1 false, null, null, i32 0, metadata !19, i32 6} ; [ DW_TAG_subprogram ] // CHECK: metadata !{i32 {{.*}}, i32 0, metadata !10, metadata !"aa", metadata !"aa", metadata !"_ZN1E2aaEv", metadata !6, i32 7, metadata !22, i1 false, i1 false, i32 0, i32 0, null, i32 256, i1 false, null, null, i32 0, metadata !24, i32 7} ; [ DW_TAG_subprogram ] // CHECK: metadata !{i32 {{.*}}, i32 0, metadata !10, metadata !"E", metadata !"E", metadata !"", metadata !6, i32 8, metadata !7, i1 false, i1 false, i32 0, i32 0, null, i32 256, i1 false, null, null, i32 0, metadata !27, i32 8} ; [ DW_TAG_subprogram ]
Add solution to second homework
#include <vector> #include <queue> #include <unordered_set> #include <iostream> using namespace std; void bfs(int S, const vector<vector<int>>& adjLists, vector<int>& results) { queue<int> toTraverse; toTraverse.push(S); unordered_set<int> traversed; traversed.emplace(S); while (!toTraverse.empty()) { int currentNode = toTraverse.front(); toTraverse.pop(); for (int successor : adjLists[currentNode - 1]) { if (traversed.find(successor) == traversed.end()) { toTraverse.push(successor); traversed.emplace(successor); results[successor - 1] = results[currentNode - 1] + 6; } } } } int main() { int T; cin >> T; for (int i = 0; i < T; ++i) { int N, M; cin >> N >> M; vector<vector<int>> adjLists(N); for (int j = 0; j < M; ++j) { int x, y; cin >> x >> y; adjLists[x - 1].push_back(y); adjLists[y - 1].push_back(x); } int S; cin >> S; vector<int> results(N, 0); bfs(S, adjLists, results); for (int j = 0; j < N; ++j) { if (j + 1 == S) { continue; } cout << (results[j] ? results[j] : -1) << ' '; } cout << '\n'; } return 0; }
Add initial opto model tests
// // TestOptocoupler.cpp // FxDSP // // Created by Hamilton Kibbe on 5/3/15. // Copyright (c) 2015 Hamilton Kibbe. All rights reserved. // #include "Optocoupler.h" #include <math.h> #include <gtest/gtest.h> TEST(OptocouplerSingle, Smoketest) { const Opto_t types[2] = {OPTO_LDR, OPTO_PHOTOTRANSISTOR}; float sinewave[10000]; float out[10000]; for (unsigned i = 0; i < 10000; ++i) { sinewave[i] = sinf((6000 * M_PI * i)/10000); // 3000Hz sinewave at 44100 } for (unsigned i = 0; i < sizeof(types); ++i) { Opto* opto = OptoInit(types[i], 0.5, 44100); ASSERT_NE((void*)opto, (void*)NULL); OptoProcess(opto, out, sinewave, 10000); OptoFree(opto); } } TEST(OptocouplerDouble, Smoketest) { const Opto_t types[2] = {OPTO_LDR, OPTO_PHOTOTRANSISTOR}; double sinewave[10000]; double out[10000]; for (unsigned i = 0; i < 10000; ++i) { sinewave[i] = sin((6000 * M_PI * i)/10000); // 3000Hz sinewave at 44100 } for (unsigned i = 0; i < sizeof(types); ++i) { OptoD* opto = OptoInitD(types[i], 0.5, 44100); ASSERT_NE((void*)opto, (void*)NULL); OptoProcessD(opto, out, sinewave, 10000); OptoFreeD(opto); } }
Enable to build empty components for Windows.
#ifdef _WINDOWS /* * NOTE: Some macros must be defined in project options of Visual Studio. * - NOMINMAX * To use std::min(), std::max(). * NOTE: Suppress some warnings of Visual Studio. * - C4251 */ #include <windows.h> BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } #endif
Remove TODO to remove 0 observed window checks on WindowObserver.
// 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 "ui/aura/window_observer.h" #include "base/logging.h" #include "ui/aura/window.h" namespace aura { WindowObserver::WindowObserver() : observing_(0) { } WindowObserver::~WindowObserver() { // TODO(flackr): Remove this check and observing_ counter when the cause of // http://crbug.com/365364 is discovered. CHECK_EQ(0, observing_); } void WindowObserver::OnObservingWindow(aura::Window* window) { if (!window->HasObserver(this)) observing_++; } void WindowObserver::OnUnobservingWindow(aura::Window* window) { if (window->HasObserver(this)) observing_--; } } // namespace aura
// 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 "ui/aura/window_observer.h" #include "base/logging.h" #include "ui/aura/window.h" namespace aura { WindowObserver::WindowObserver() : observing_(0) { } WindowObserver::~WindowObserver() { CHECK_EQ(0, observing_); } void WindowObserver::OnObservingWindow(aura::Window* window) { if (!window->HasObserver(this)) observing_++; } void WindowObserver::OnUnobservingWindow(aura::Window* window) { if (window->HasObserver(this)) observing_--; } } // namespace aura
Add unit test for HypreParVector::Read
// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "unit_tests.hpp" #include "mfem.hpp" namespace mfem { #ifdef MFEM_USE_MPI TEST_CASE("HypreParVector I/O", "[Parallel], [HypreParVector]") { // Create a test vector (two entries per rank) with entries increasing // sequentially. Write the vector to a file, read it into another vector, and // make sure we get the same answer. int world_size, rank; MPI_Comm_size(MPI_COMM_WORLD, &world_size); MPI_Comm_rank(MPI_COMM_WORLD, &rank); int size_per_rank = 2; HYPRE_BigInt glob_size = world_size*size_per_rank; std::vector<HYPRE_BigInt> col; if (HYPRE_AssumedPartitionCheck()) { int offset = rank*size_per_rank; col = {offset, offset + size_per_rank}; } else { col.resize(world_size+1); for (int i=0; i<world_size; ++i) { col[i] = i*size_per_rank; } } // Initialize vector and write to files HypreParVector v1(MPI_COMM_WORLD, glob_size, col.data()); for (int i=0; i<size_per_rank; ++i) { v1(i) = rank*size_per_rank + i; } v1.Print("vec"); // Check that we read the same vector from disk HypreParVector v2; v2.Read(MPI_COMM_WORLD, "vec"); v2 -= v1; REQUIRE(InnerProduct(v2, v2) == MFEM_Approx(0.0)); // Clean up std::string prefix = "vec."; std::string suffix = std::to_string(rank); remove((prefix + suffix).c_str()); remove((prefix + "INFO." + suffix).c_str()); } #endif // MFEM_USE_MPI } // namespace mfem
Add Solution for Problem 143
// 143_Reorder_List.cpp : Defines the entry point for the console application. /** * Given a singly linked list L: L0->L1->->Ln-1->Ln, * reorder it to: L0->Ln->L1->Ln-1->L2->Ln-2-> * * You must do this in-place without altering the nodes' values. * * For example, * Given {1,2,3,4}, reorder it to {1,4,2,3}. * * Tags: Linked List * * Author: Kuang Qin */ #include "stdafx.h" #include <iostream> using namespace std; /** * Definition for singly-linked list. */ struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} ListNode(int x, ListNode *p) : val(x), next(p) {} }; class Solution { public: void reorderList(ListNode* head) { if ((head == NULL) || (head->next == NULL)) { return; } // cut the list into two halves ListNode *slow = head, *fast = head->next; while (fast && fast->next) { slow = slow->next; fast = fast->next->next; } // reverse the second list ListNode *curr = slow->next, *prev = NULL; while (curr) { ListNode *next = curr->next; curr->next = prev; prev = curr; curr = next; } // terminate the list at the end of first half slow->next = NULL; // merge two lists while (prev) { ListNode *next1 = head->next, *next2 = prev->next; head->next = prev; prev->next = next1; head = next1; prev = next2; } } }; int _tmain(int argc, _TCHAR* argv[]) { ListNode node5(5), node4(4, &node5), node3(3, &node4), node2(2, &node3), node1(1, &node2); ListNode *head = &node1, *curr = head; cout << "Before Reorder:" << endl; while (curr) { cout << curr->val << " "; curr = curr->next; } cout << endl; Solution mySolution; mySolution.reorderList(head); curr = head; cout << "After Reorder:" << endl; while (curr) { cout << curr->val << " "; curr = curr->next; } cout << endl; system("pause"); return 0; }
Add solution to problem 3.
/* * Largest prime factor * * The prime factors of 13'195 are 5, 7, 13 and 29. * * What is the largest prime factor of the number 600'851'475'143? */ #include <algorithm> #include <cmath> #include <cstddef> #include <iostream> #include <vector> #include "sieve.hpp" constexpr Long number = 600'851'475'143; int main(int, char **) { std::vector<Long> primes; // Compute all prime numbers less than or equal to `sqrt(number)` do { sieve(primes, primes.size() + 100); } while(primes.back() < static_cast<Long>(std::sqrt(number))); auto it = std::find_if(primes.rbegin(), primes.rend(), [](Long x) { return x <= static_cast<Long>(std::sqrt(number)); }); it = std::find_if( it, primes.rend(), [](Long x) { return number % x == 0; }); auto maxFactor = (it != primes.rend() ? *it : number); std::cout << "Project Euler - Problem 3: Largest prime factor\n\n"; std::cout << "The largets prime factor of " << number << " is\n" << maxFactor << '\n'; }
Add serialization of minimal template unit-test that is broken
/* Copyright (c) 2014, Randolph Voorhies, Shane Grant All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of cereal nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES AND SHANE GRANT BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "common.hpp" #include <boost/test/unit_test.hpp> template <typename T> struct template_test_struct { T x; }; template <typename Archive, typename T> std::string save_minimal(Archive const &, template_test_struct<T> const & m) { return std::to_string(m.x); } template <typename Archive, typename T> void load_minimal(Archive const &, template_test_struct<T>& m, std::string const & str) { m.x = std::stoi(str); } template <class IArchive, class OArchive> void test_template_structs_minimal() { template_test_struct <uint32_t> mb_i; std::ostringstream os; { OArchive oar(os); oar(mb_i); } decltype(mb_i) mb_o; std::istringstream is(os.str()); { IArchive iar(is); iar(mb_o); } BOOST_CHECK(mb_i.x == mb_o.x); } BOOST_AUTO_TEST_CASE( template_test_struct_minimal_all ) { test_template_structs_minimal<cereal::BinaryInputArchive, cereal::BinaryOutputArchive>(); test_template_structs_minimal<cereal::PortableBinaryInputArchive, cereal::PortableBinaryOutputArchive>(); test_template_structs_minimal<cereal::XMLInputArchive, cereal::XMLOutputArchive>(); test_template_structs_minimal<cereal::JSONInputArchive, cereal::JSONOutputArchive>(); }
Test harness for the new SimpleXMLParser class.
/** \brief Test harness for the SimpleXmlParser class. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2015 Universitätsbiblothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include "SimpleXmlParser.h" #include "util.h" void Usage() { std::cerr << "Usage: " << progname << " xml_input\n"; std::exit(EXIT_FAILURE); } int main(int argc, char *argv[]) { progname = argv[0]; if (argc != 2) Usage(); const std::string input_filename(argv[1]); File input(input_filename, "rm"); if (not input) Error("can't open \"" + input_filename + "\" for reading!"); SimpleXmlParser::Type type; std::string data; std::map<std::string, std::string> attrib_map; SimpleXmlParser xml_parser(&input); while (xml_parser.getNext(&type, &attrib_map, &data)) { switch (type) { case SimpleXmlParser::UNINITIALISED: Error("we should never get here as UNINITIALISED should never be returned!"); case SimpleXmlParser::START_OF_DOCUMENT: std::cout << "START_OF_DOCUMENT()\n"; break; case SimpleXmlParser::END_OF_DOCUMENT: break; case SimpleXmlParser::ERROR: Error("we should never get here because SimpleXmlParser::getNext() should have returned false!"); case SimpleXmlParser::OPENING_TAG: std::cout << "OPENING_TAG(" << data; for (const auto &name_and_value : attrib_map) std::cout << ' ' << name_and_value.first << '=' << name_and_value.second; std::cout << ")\n"; break; case SimpleXmlParser::CLOSING_TAG: std::cout << "CLOSING_TAG(" << data << ")\n"; break; case SimpleXmlParser::CHARACTERS: std::cout << "CHARACTERS(" << data << ")\n"; break; } } Error("XML parsing error: " + xml_parser.getLastErrorMessage()); }
Add a program to take an encrypted text string, shift it by the input key, and print the decrypted string.
/***************************************************************************** * File: keyShiftCypher.cpp * * Description: Take an encrypted text string, shift it by the input key, and * print the decrypted string. * * Author: Tim Troxler * * Created: 1/5/2015 * ****************************************************************************/ // STL includes #include <string> #include <iostream> // Boost includes #include <boost/algorithm/string.hpp> static const int ALPHABET_LENGTH = 26; // Return if the character is in the alphabet or not // True if a-z // False all others inline bool isAlpha(const char c) { return (c >= 'a' && c <= 'z'); } // Shift each alphabetic character of the encrypted string by the // corresponding character in the key, and return the decrypted string. std::string solver(const std::string encrypted, const std::string key) { // Convert to lowercase for simplicity auto decrypted = encrypted; std::transform(decrypted.begin(), decrypted.end(), decrypted.begin(), ::tolower); const int keylength = key.length(); // Keep track of any whitespace or punctuation int ignoreChars = 0; // For each encrypted character... for(unsigned int cryptIdx = 0; cryptIdx < decrypted.length(); cryptIdx++) { auto c = decrypted.at(cryptIdx); // If in the lowercase alphabet... if(isAlpha(c)) { // Find the corresponding index in the key string const int keyIdx = (cryptIdx - ignoreChars) % keylength; // Shift the encrypted character by the key; wrap within the size // of the alphabet auto temp = ((c - key.at(keyIdx)) % ALPHABET_LENGTH); if(temp < 0) { temp += ALPHABET_LENGTH; } // Convert back to lowercase text decrypted[cryptIdx] = temp + 'a'; } else { ignoreChars++; } } return decrypted; } int main(int argc, char* argv[]) { // Very simple validation - require the 2 input strings // To do - any error handling if (argc != 3) { std::cout << "This program requires two strings as input:" << std::endl; std::cout << "keyShiftCypher.exe \"encrypted string\" \"keystring\"" << std::endl; } // Decrypt and display auto encrypted = std::string(argv[1]); auto key = std::string(argv[2]); std::cout << "Solving cyphertext '" << encrypted << "' with key '" << key << "'." << std::endl; auto decrypted = solver(encrypted, key); std::cout << decrypted << std::endl; return 0; }
Test cereal for a basic save and load operation
#include "UnitTest++/UnitTest++.h" #include <fstream> #include <cereal/archives/binary.hpp> SUITE( CerealTest ) { TEST( basicSaveAndLoad ) { const std::string saveFileName = "CerealTest"; const int expectedData = 42; int actualData = 666; { std::ofstream file( saveFileName, std::ios::binary ); CHECK( !file.fail() ); cereal::BinaryOutputArchive archive( file ); archive( expectedData ); } { std::ifstream file( saveFileName, std::ios::binary ); CHECK( !file.fail() ); cereal::BinaryInputArchive archive( file ); archive( actualData ); } CHECK_EQUAL( expectedData, actualData ); // Delete save file CHECK( !remove( saveFileName.data() ) ) ; } }
Add Solution for 203 Remove Linked List Elements
// 203. Remove Linked List Elements /** * Remove all elements from a linked list of integers that have value val. * * Example * Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 * Return: 1 --> 2 --> 3 --> 4 --> 5 * * Tags: Linked List * * Similar Problems: (E) Remove Element (E) Delete Node in a Linked List * * Author: Kuang Qin */ #include <iostream> using namespace std; /** * Definition for singly-linked list. */ struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} ListNode(int x, ListNode *p) : val(x), next(p) {} }; // iterative solution class Solution { public: ListNode* removeElements(ListNode* head, int val) { ListNode dummy(0); dummy.next = head; ListNode *prev = &dummy, *curr = head; while (curr != NULL) { if (curr->val == val) { prev->next = curr->next; } else { // move prev forward prev = curr; } curr = curr->next; } return dummy.next; } }; // recursive solution class Solution_recursive { public: ListNode* removeElements(ListNode* head, int val) { if (head == NULL) { return NULL; } head->next = removeElements(head->next, val); // return head->next if head is deleted return (head->val == val) ? head->next : head; } }; int main() { ListNode node7(6), node6(5, &node7), node5(4, &node6), node4(3, &node5), node3(6, &node4), node2(2, &node3), node1(1, &node2); Solution sol; ListNode *newhead = sol.removeElements(&node1, 6); for (ListNode *p = newhead; p != NULL; p = p->next) { cout << p->val << " "; } cout << endl; cin.get(); return 0; }
Add solution to the power problem
#include <iostream> using namespace std; int powLastFourDigits(int number, long long unsigned power) { number %= 10000; if (power == 0) return 1; return (powLastFourDigits(number, power - 1) * number) % 10000; } int powIterLastFourDigits(int number, long long unsigned power) { int result = 1; number %= 10000; for (long long unsigned i = 0; i < power; i++) result = (result * number) % 10000; return result; } int fastPowLastFourDigits(int number, long long unsigned power) { number %= 10000; if (power == 0) return 1; if (power == 1) return number; int t = fastPowLastFourDigits(number, power / 2); if (power % 2) return (t * t * number) % 10000; else return (t * t) % 10000; } void testPow() { for (int i = 10000; i < 10009; i++) { cout << "2 ^ " << i << ": pow: " << powLastFourDigits(2, i) << endl; cout << "2 ^ " << i << ": pow iter: " << powIterLastFourDigits(2, i) << endl; cout << "2 ^ " << i << ": fast pow: " << fastPowLastFourDigits(2, i) << endl; } cout << "13 ^ 100000000000000000 = " << fastPowLastFourDigits(13, 100000000000000000) << endl; } void printMenu() { cout << "1 - slow pow | 2 - iterative pow | 3 - fast pow | 4 - run tests | e - exit" << endl; } int main() { char choice; int n; long long unsigned pow; printMenu(); while (cin >> choice) { switch (choice) { case '1': cout << "Enter n: "; cin >> n; cout << "Enter power: "; cin >> pow; cout << powLastFourDigits(n, pow) << endl; break; case '2': cout << "Enter n: "; cin >> n; cout << "Enter power: "; cin >> pow; cout << powIterLastFourDigits(n, pow) << endl; break; case '3': cout << "Enter n: "; cin >> n; cout << "Enter power: "; cin >> pow; cout << fastPowLastFourDigits(n, pow) << endl; break; case '4': testPow(); break; case 'e': return 0; default: cout << "No such option. Try again." << endl; } printMenu(); } testPow(); return 0; }
Advance Program for Binary Search
// To find an element in increasing seq. of values #include <bits/stdc++.h> using namespace std; int arr[100]; int binary(int l,int r,int key) // Code template for Binary Search { while(l<=r) { int mid = (l+r)/2; if(arr[mid] == key) // key is the element to find { return mid; } else if( arr[mid] > key) { r = mid-1; } else { l = mid+1; } } return -1; // Not Found } int main() { int n,m,i; cin >> n; // Enter the size of the array for(i=0;i<n;i++) { cin >> arr[i]; } sort(arr,arr+n); // Hence the array is sorted cout<<"Enter the element to be searched\n"; cin >> m; int x = binary(0,n,m); cout << x<<"\n"; return 0; }
Reduce Array Size to The Half
class Solution { public: int minSetSize(vector<int>& arr) { std::unordered_map<int, int> m; for (const auto& num : arr) { auto iter = m.find(num); if (iter == m.end()) { m[num] = 1; } else { ++m[num]; } } int half = arr.size() / 2; std::vector<std::vector<int>> nums; for (auto iter = m.begin(); iter != m.end(); ++iter) { std::vector<int> cur(2, 0); cur[0] = iter->second; cur[1] = iter->first; nums.emplace_back(std::move(cur)); } std::sort(nums.begin(), nums.end(), [](std::vector<int>& a, std::vector<int>& b){ return a[0] > b[0]; }); int ret = 0; for (const auto& v : nums) { if (half <= 0) { break; } else { half -= v[0]; ++ret; } } return ret; } };
Add a test for a crash with unnamed NamedDecls
// Makes sure it doesn't crash. // XFAIL: linux // RUN: rm -rf %t // RUN: not %clang_cc1 %s -index-store-path %t/idx -std=c++14 // RUN: c-index-test core -print-record %t/idx | FileCheck %s namespace rdar32474406 { void foo(); typedef void (*Func_t)(); // CHECK: [[@LINE+4]]:1 | type-alias/C | c:record-hash-crash-invalid-name.cpp@N@rdar32474406@T@Func_t | Ref,RelCont | rel: 1 // CHECK-NEXT: RelCont | c:@N@rdar32474406 // CHECK: [[@LINE+2]]:14 | function/C | c:@N@rdar32474406@F@foo# | Ref,RelCont | rel: 1 // CHECK-NEXT: RelCont | c:@N@rdar32474406 Func_t[] = { foo }; // invalid decomposition }
Add problem: Flipping the matrix
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; // Enunciado: https://www.hackerrank.com/challenges/flipping-the-matrix int main() { unsigned q, n; cin >> q; for (int cq = 0; cq < q; ++cq) { cin >> n; // Cada elemento tiene 4 posiciones posibles mediante las operaciones dadas // Idea 3 (la buena): basta tomar el máximo de las 4 posiciones posibles para cada elemento del cuadrante vector<vector<unsigned>> m(2*n, vector<unsigned>(2*n)); for (auto& v : m) { for (unsigned& e : v) { cin >> e; } } long long unsigned sum = 0; for (unsigned i = 0; i < n; ++i) { for (unsigned j = 0; j < n; ++j) { // calcular las 4 posiciones simétricas respecto de los ejes centrales sum += max( m[i][j], max( m[2*n-i-1][j], max( m[i][2*n-j-1], m[2*n-i-1][2*n-j-1]))); } } cout << sum << endl; } return 0; }
Add a unit test for serialization
#include <memory> #include <string> #include <SFCGAL/all.h> #include <SFCGAL/Kernel.h> #include <SFCGAL/io/Serialization.h> #include <boost/test/unit_test.hpp> using namespace boost::unit_test ; using namespace SFCGAL ; BOOST_AUTO_TEST_SUITE( SFCGAL_io_WktReaderTest ) BOOST_AUTO_TEST_CASE( textTest ) { Kernel::Point_2 pt( 2.3, 4.5 ); Kernel::Point_2 rpt; std::ostringstream ostr; boost::archive::text_oarchive arc( ostr ); arc << pt; std::string str = ostr.str(); std::istringstream istr( str ); boost::archive::text_iarchive iarc( istr ); iarc >> rpt; BOOST_CHECK( pt == rpt ); } BOOST_AUTO_TEST_CASE( binaryTest ) { Kernel::Point_2 pt( 2.3, 4.5 ); Kernel::Point_2 rpt; std::ostringstream ostr; boost::archive::binary_oarchive arc( ostr ); arc << pt; std::string str = ostr.str(); std::istringstream istr( str ); boost::archive::binary_iarchive iarc( istr ); iarc >> rpt; BOOST_CHECK( pt == rpt ); } BOOST_AUTO_TEST_SUITE_END()
Add bench for image encodes
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Benchmark.h" #include "Resources.h" #include "SkBitmap.h" #include "SkData.h" #include "SkImageEncoder.h" class EncodeBench : public Benchmark { public: EncodeBench(const char* filename, SkImageEncoder::Type type, int quality) : fFilename(filename) , fType(type) , fQuality(quality) { // Set the name of the bench SkString name("Encode_"); name.append(filename); name.append("_"); switch (type) { case SkImageEncoder::kJPEG_Type: name.append("JPEG"); break; case SkImageEncoder::kPNG_Type: name.append("PNG"); break; case SkImageEncoder::kWEBP_Type: name.append("WEBP"); break; default: name.append("Unknown"); break; } fName = name; } bool isSuitableFor(Backend backend) override { return backend == kNonRendering_Backend; } const char* onGetName() override { return fName.c_str(); } void onPreDraw(SkCanvas*) override { #ifdef SK_DEBUG bool result = #endif GetResourceAsBitmap(fFilename, &fBitmap); SkASSERT(result); } void onDraw(int loops, SkCanvas*) override { for (int i = 0; i < loops; i++) { SkAutoTUnref<SkData> data(SkImageEncoder::EncodeData(fBitmap, fType, fQuality)); SkASSERT(data); } } private: const char* fFilename; const SkImageEncoder::Type fType; const int fQuality; SkString fName; SkBitmap fBitmap; }; // The Android Photos app uses a quality of 90 on JPEG encodes DEF_BENCH(return new EncodeBench("mandrill_512.png", SkImageEncoder::kJPEG_Type, 90)); DEF_BENCH(return new EncodeBench("color_wheel.jpg", SkImageEncoder::kJPEG_Type, 90)); // PNG encodes are lossless so quality should be ignored DEF_BENCH(return new EncodeBench("mandrill_512.png", SkImageEncoder::kPNG_Type, 90)); DEF_BENCH(return new EncodeBench("color_wheel.jpg", SkImageEncoder::kPNG_Type, 90)); // TODO: What is the appropriate quality to use to benchmark WEBP encodes? DEF_BENCH(return new EncodeBench("mandrill_512.png", SkImageEncoder::kWEBP_Type, 90)); DEF_BENCH(return new EncodeBench("color_wheel.jpg", SkImageEncoder::kWEBP_Type, 90));
Add solution to the second problem of the first test
#include <iostream> using namespace std; class Pizza { char name[30]; double price; public: Pizza(const char _name[] = "", double _price = 0): price(_price) { strcpy(name, _name); } double getPrice() { return price; } }; class Order { Pizza pizzas[20]; int pizzasCount; public: Order(): pizzasCount(0) {} void addPizza(const Pizza& pizza) { pizzas[pizzasCount++] = pizza; } double getTotalPrice() { double total = 0; for (int i = 0; i < pizzasCount; ++i) { total += pizzas[i].getPrice(); } return total; } }; class Client { char name[30]; Order orders[10]; int ordersCount; public: Client(const char _name[]): ordersCount(0) { strcpy(name, _name); } void addOrder(const Order& order) { orders[ordersCount++] = order; } double getOrdersPrice() { double ordersPrice = 0; for (int i = 0; i < ordersCount; ++i) { ordersPrice += orders[i].getTotalPrice(); } return ordersPrice; } }; int main() { Pizza capricciosa("Capricciosa", 9); Pizza margherita("Margherita", 6.5); Pizza calzone("Calzone", 8); Order order1; order1.addPizza(calzone); order1.addPizza(margherita); Order order2; order2.addPizza(capricciosa); order2.addPizza(margherita); order2.addPizza(capricciosa); Client ivan("Ivan"); ivan.addOrder(order1); ivan.addOrder(order2); cout << ivan.getOrdersPrice() << '\n'; return 0; }
Add compile unit size test
// This is a regression test on debug info to make sure we don't hit a compile unit size // issue with gdb. // RUN: %llvmgcc -S -O0 -g %s -o - | llvm-as | llc --disable-fp-elim -o Output/NoCompileUnit.s -f // RUN: as Output/NoCompileUnit.s -o Output/NoCompileUnit.o // RUN: g++ Output/NoCompileUnit.o -o Output/NoCompileUnit.exe // RUN: ( echo "break main"; echo "run" ; echo "p NoCompileUnit::pubname" ) > Output/NoCompileUnit.gdbin // RUN: gdb -q -batch -n -x Output/NoCompileUnit.gdbin Output/NoCompileUnit.exe | tee Output/NoCompileUnit.out | not grep '"low == high"' // XFAIL: i[1-9]86|alpha|ia64|arm class MamaDebugTest { private: int N; protected: MamaDebugTest(int n) : N(n) {} int getN() const { return N; } }; class BabyDebugTest : public MamaDebugTest { private: public: BabyDebugTest(int n) : MamaDebugTest(n) {} static int doh; int doit() { int N = getN(); int Table[N]; int sum = 0; for (int i = 0; i < N; ++i) { int j = i; Table[i] = j; } for (int i = 0; i < N; ++i) { int j = Table[i]; sum += j; } return sum; } }; int BabyDebugTest::doh; int main(int argc, const char *argv[]) { BabyDebugTest BDT(20); return BDT.doit(); }
Add unit test for Generic::GetZone() function
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include "gtest/gtest.h" #include <Rosetta/Actions/Generic.hpp> #include <Rosetta/Enums/CardEnums.hpp> #include <Rosetta/Games/Game.hpp> using namespace RosettaStone; TEST(Generic, GetZone) { GameConfig config; config.player1Class = CardClass::ROGUE; config.player2Class = CardClass::PALADIN; config.startPlayer = PlayerType::PLAYER1; config.doFillDecks = true; config.autoRun = false; Game game(config); game.StartGame(); game.ProcessUntil(Step::MAIN_START); Player& curPlayer = game.GetCurrentPlayer(); EXPECT_EQ(&curPlayer.GetDeckZone(), Generic::GetZone(curPlayer, ZoneType::DECK)); EXPECT_EQ(&curPlayer.GetFieldZone(), Generic::GetZone(curPlayer, ZoneType::PLAY)); EXPECT_EQ(&curPlayer.GetGraveyardZone(), Generic::GetZone(curPlayer, ZoneType::GRAVEYARD)); EXPECT_EQ(&curPlayer.GetHandZone(), Generic::GetZone(curPlayer, ZoneType::HAND)); EXPECT_EQ(&curPlayer.GetSecretZone(), Generic::GetZone(curPlayer, ZoneType::SECRET)); EXPECT_EQ(&curPlayer.GetSetasideZone(), Generic::GetZone(curPlayer, ZoneType::SETASIDE)); EXPECT_EQ(nullptr, Generic::GetZone(curPlayer, ZoneType::INVALID)); EXPECT_EQ(nullptr, Generic::GetZone(curPlayer, ZoneType::REMOVEDFROMGAME)); }
Implement algorithm to print symmetrix matrix
#include <iostream> using namespace std; int main() { int N = 4; char items[] = {'a', 'b', 'c', 'd'}; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { cout<<items[i^j]<<" "; } cout<<endl; } return 0; }
Add test for variadic functions.
#include "Output.h" Output output; void varArgFunc(int numParams, ...) { __builtin_va_list ap; __builtin_va_start(ap, numParams); for (int i = 0; i < numParams; i++) output << __builtin_va_arg(ap, int); __builtin_va_end(ap); } int main() { varArgFunc(4, 0xaaaaaaaa, 0xbbbbbbbb, 0xcccccccc, 0xdddddddd); // CHECK: 0xaaaaaaaa // CHECK: 0xbbbbbbbb // CHECK: 0xcccccccc // CHECK: 0xdddddddd }