Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add a test for thread-safe malloc
#include "mbed.h" #include "test_env.h" #include "rtos.h" #if defined(MBED_RTOS_SINGLE_THREAD) #error [NOT_SUPPORTED] test not supported #endif #define NUM_THREADS 5 #define THREAD_STACK_SIZE 256 DigitalOut led1(LED1); volatile bool should_exit = false; volatile bool allocation_failure = false; void task_using_malloc(void) { void* data; while (1) { // Repeatedly allocate and free memory data = malloc(100); if (data != NULL) { memset(data, 0, 100); } else { allocation_failure = true; } free(data); if (should_exit) { return; } } } int main() { Thread *thread_list[NUM_THREADS]; int test_time = 15; GREENTEA_SETUP(20, "default_auto"); // Allocate threads for the test for (int i = 0; i < NUM_THREADS; i++) { thread_list[i] = new Thread(osPriorityNormal, THREAD_STACK_SIZE); if (NULL == thread_list[i]) { allocation_failure = true; } thread_list[i]->start(task_using_malloc); } // Give the test time to run while (test_time) { led1 = !led1; Thread::wait(1000); test_time--; } // Join and delete all threads should_exit = 1; for (int i = 0; i < NUM_THREADS; i++) { if (NULL == thread_list[i]) { continue; } thread_list[i]->join(); delete thread_list[i]; } GREENTEA_TESTSUITE_RESULT(!allocation_failure); }
Add test failing on hexagon.
#include <stdio.h> #include "Halide.h" using namespace Halide; int main(int argc, char **argv) { //int W = 64*3, H = 64*3; const int W = 128, H = 48; Image<uint16_t> in(W, H, 2); for (int c = 0; c < 2; c++) { for (int y = 0; y < H; y++) { for (int x = 0; x < W; x++) { in(x, y, c) = rand() & 0xff; } } } Var x("x"), y("y"); Func interleaved("interleaved"); interleaved(x, y) = select(x%2 == 0, in(x, y, 0), in(x, y, 1)); Target target = get_jit_target_from_environment(); if (target.has_gpu_feature()) { interleaved.gpu_tile(x, y, 16, 16); } else if (target.features_any_of({Target::HVX_64, Target::HVX_128})) { interleaved.hexagon().vectorize(x, 32); } else { Var xo("xo"), yo("yo"); interleaved.tile(x, y, xo, yo, x, y, 8, 8).vectorize(x); } Image<uint16_t> out = interleaved.realize(W, H, target); for (int y = 0; y < H; y++) { for (int x = 0; x < W; x++) { uint16_t correct = x%2 == 0 ? in(x, y, 0) : in(x, y, 1); if (out(x, y) != correct) { printf("out(%d, %d) = %d instead of %d\n", x, y, out(x, y), correct); return -1; } } } printf("Success!\n"); return 0; }
Add string generator for war
#ifndef MAIN_CPP #define MAIN_CPP #include <algorithm> #include <vector> #include <iostream> int main() { std::vector<char> cards = {'1','1','1','1','2','2','2','2','3','3','3','3','4','4','4','4','5','5','5','5','6','6','6','6','7','7','7','7','8','8','8','8','9','9','9','9','T','T','T','T','J','J','J','J','Q','Q','Q','Q','K','K','K','K'}; std::vector<char> player1; std::vector<char> player2; std::random_shuffle(cards.begin(), cards.end()); for(int i = 0; i < 26; i++) { player1.push_back(cards[i]); std::cout << player1[i]; } std::cout << "\n"; for(int i = 0; i < 26; i++) { player2.push_back(cards[i+26]); std::cout << player2[i]; } }; #endif
Add explanation about auto and arrays.
#include <array> // C++17 only // requires template argument deduction for class templates namespace std { template <typename... T> array(T... t) -> array<std::common_type_t<T...>, sizeof...(t)>; } int main() { int a[] = {1,2,3}; int b[] {4,5,6}; // See: https://stackoverflow.com/q/7107606 // not allowed as {1, 2, 3, 4} is purely a syntactic construct- it is not an expression and does not have a type, // therefore, auto cannot deduce its type from it. //auto c[] = {1,2,3}; //auto d[] {4,5,6}; // Alternative via std::array (see above), but not quite the same... // https://stackoverflow.com/q/6114067 std::array e{1, 2, 3, 4}; }
Add 199 Binary Tree Right Side View
#include <stddef.h> // 199 Binary Tree Right Side View /** * Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. * * For example: * Given the following binary tree, * 1 <--- * / \ * 2 3 <--- * \ \ * 5 4 <--- * You should return [1, 3, 4]. * * Tag: Tree, Depth First Search, Breadth First Search * * Author: Yanbin Lu */ #include <vector> #include <string.h> #include <stdio.h> #include <algorithm> #include <iostream> #include <map> #include <queue> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: vector<int> rightSideView(TreeNode* root) { vector<int> res; if(!root) return res; // using level order traverse // use a queue to store all nodes in the current level queue<TreeNode*> q; q.push(root); while(!q.empty()){ int n = q.size(); for(int i = 0; i < n;i++){ TreeNode* node = q.front(); q.pop(); if(node->left) q.push(node->left); if(node->right) q.push(node->right); // push the last node (right most node) to res if(i == n-1) res.push_back(node->val); } } return res; } }; int main() { // creat a binary tree TreeNode* root = new TreeNode(0); root->left = new TreeNode(3); root->right = new TreeNode(2); root->left->right = new TreeNode(5); Solution* sol = new Solution(); vector<int> res = sol->rightSideView(root); for(int i = 0; i < res.size(); i++) cout<<res[i]<<std::endl; char c; std::cin>>c; return 0; }
Add tests from the Itanium C++ ABI spec.
// RUN: %clang_cc1 %s -triple=x86_64-apple-darwin10 -emit-llvm-only -fdump-vtable-layouts 2>&1 | FileCheck %s /// Examples from the Itanium C++ ABI specification. /// http://www.codesourcery.com/public/cxx-abi/ namespace Test1 { // This is from http://www.codesourcery.com/public/cxx-abi/cxx-vtable-ex.html // CHECK: Vtable for 'Test1::A' (5 entries). // CHECK-NEXT: 0 | offset_to_top (0) // CHECK-NEXT: 1 | Test1::A RTTI // CHECK-NEXT: -- (Test1::A, 0) vtable address -- // CHECK-NEXT: 2 | void Test1::A::f() // CHECK-NEXT: 3 | void Test1::A::g() // CHECK-NEXT: 4 | void Test1::A::h() struct A { virtual void f (); virtual void g (); virtual void h (); int ia; }; void A::f() {} }
Add failing opengl test using an inline reduction
#include "Halide.h" 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; } Func f; Var x, y, c; RDom r(0, 10); f(x, y, c) = sum(r); f.bound(c, 0, 3).glsl(x, y, c); f.realize(100, 100, 3); printf("Success!\n"); return 0; }
Add an example of iteration over (some) variables in a cell with boost::mpl.
/* Example of iterating over cell's variables using boost::mpl. Copyright 2015 Ilja Honkonen 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 copyright holders nor the names of their 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 THE COPYRIGHT HOLDER OR 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 "iostream" #include "boost/mpl/for_each.hpp" #include "boost/mpl/vector.hpp" #include "gensimcell.hpp" using namespace std; struct variable1 { using data_type = int; }; struct variable2 { using data_type = float; }; struct variable3 { using data_type = char; }; int main(int, char**) { gensimcell::Cell< gensimcell::Never_Transfer, variable1, variable2, variable3 > cell; cell[variable1()] = 3; cell[variable2()] = 1.5; cell[variable3()] = '3'; // lambda with auto argument requires C++14, // see documentation of boost::mpl::for_each // on how to support older compilers boost::mpl::for_each< boost::mpl::vector<variable1, variable3> >( [&cell](auto variable){ cout << cell[variable] << " "; } ); cout << endl; // prints 3 3 return 0; }
Add SmallString unit test. - Patch by Ryan Flynn!
//===- llvm/unittest/ADT/SmallStringTest.cpp ------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // SmallString unit tests. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/ADT/SmallString.h" #include <stdarg.h> #include <climits> #include <cstring> using namespace llvm; namespace { // Test fixture class class SmallStringTest : public testing::Test { protected: typedef SmallString<40> StringType; StringType theString; void assertEmpty(StringType & v) { // Size tests EXPECT_EQ(0u, v.size()); EXPECT_TRUE(v.empty()); // Iterator tests EXPECT_TRUE(v.begin() == v.end()); } }; // New string test. TEST_F(SmallStringTest, EmptyStringTest) { SCOPED_TRACE("EmptyStringTest"); assertEmpty(theString); EXPECT_TRUE(theString.rbegin() == theString.rend()); } TEST_F(SmallStringTest, AppendUINT64_MAX) { SCOPED_TRACE("AppendUINT64_MAX"); theString.clear(); assertEmpty(theString); theString.append_uint(UINT64_MAX); EXPECT_TRUE(0 == strcmp(theString.c_str(),"18446744073709551615")); } TEST_F(SmallStringTest, AppendINT64_MIN) { SCOPED_TRACE("AppendINT64_MIN"); theString.clear(); assertEmpty(theString); theString.append_sint(INT64_MIN); EXPECT_TRUE(0 == strcmp(theString.c_str(),"-9223372036854775808")); } }
Add unit tests for alfons
#include "catch.hpp" #include "tangram.h" #include "style/textStyle.h" #include "alfons/textBatch.h" #include "alfons/textShaper.h" #include "alfons/atlas.h" #include "alfons/alfons.h" #include "alfons/fontManager.h" #include "text/lineWrapper.h" #include <memory> namespace Tangram { struct ScratchBuffer : public alfons::MeshCallback { void drawGlyph(const alfons::Quad& q, const alfons::AtlasGlyph& atlasGlyph) override {} void drawGlyph(const alfons::Rect& q, const alfons::AtlasGlyph& atlasGlyph) override {} }; struct AtlasCallback : public alfons::TextureCallback { void addTexture(alfons::AtlasID id, uint16_t textureWidth, uint16_t textureHeight) override {} void addGlyph(alfons::AtlasID id, uint16_t gx, uint16_t gy, uint16_t gw, uint16_t gh, const unsigned char* src, uint16_t padding) override {} }; TEST_CASE("Ensure empty line is given when giving empty shape to alfons", "[Core][Alfons]") { AtlasCallback atlasCb; ScratchBuffer buffer; alfons::LineMetrics metrics; alfons::TextShaper shaper; alfons::GlyphAtlas atlas(atlasCb); alfons::TextBatch batch(atlas, buffer); alfons::FontManager fontManager; auto font = fontManager.addFont("default", alf::InputSource("fonts/NotoSans-Regular.ttf"), 24); auto line = shaper.shape(font, ""); metrics = drawWithLineWrapping(line, batch, 15, TextLabelProperty::Align::center, 1.0); REQUIRE(line.shapes().size() == 0); } }
Test whether element generator template works
#include <boost/test/unit_test.hpp> #include "../unittest_config.h" #include "test_element.h" #include "clotho/mutation/element_generator.hpp" typedef clotho::powersets::element_key_of< test_element >::key_type key_type; struct test_key_generator { key_type operator()( key_type & k ) { return k; } }; typedef clotho::mutations::element_generator< test_element, test_key_generator > elem_generator; BOOST_AUTO_TEST_SUITE( test_element_generation ) /** * Test that the expected width per block is initialized correctly * */ BOOST_AUTO_TEST_CASE( key_generator_test ) { test_key_generator tkg; elem_generator gen( tkg ); key_type k = 0.25; test_element te = gen(k); BOOST_REQUIRE_MESSAGE( te.k == k, "Unexpected key: " << te.k << "(" << k << ")" ); } BOOST_AUTO_TEST_SUITE_END()
Remove a DEAL_II_NAMESPACE_CLOSE which has been added accidentally.
//--------------------------------------------------------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 2006 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //--------------------------------------------------------------------------- #include <base/config.h> #include <cmath> #include <limits> DEAL_II_NAMESPACE_OPEN namespace deal_II_numbers { bool is_finite (const double x) { #ifdef DEAL_II_HAVE_ISFINITE return std::isfinite (x); #else // check against infinities. not // that if x is a NaN, then both // comparisons will be false return ((x >= -std::numeric_limits<double>::max()) && DEAL_II_NAMESPACE_CLOSE (x <= std::numeric_limits<double>::max())); #endif } } DEAL_II_NAMESPACE_CLOSE
//--------------------------------------------------------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 2006 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //--------------------------------------------------------------------------- #include <base/config.h> #include <cmath> #include <limits> DEAL_II_NAMESPACE_OPEN namespace deal_II_numbers { bool is_finite (const double x) { #ifdef DEAL_II_HAVE_ISFINITE return std::isfinite (x); #else // check against infinities. not // that if x is a NaN, then both // comparisons will be false return ((x >= -std::numeric_limits<double>::max()) && (x <= std::numeric_limits<double>::max())); #endif } } DEAL_II_NAMESPACE_CLOSE
Add a test that prints out the current build type
// Copyright (c) 2011 Timur Iskhodzhanov and MIPT students. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gtest/gtest.h" #include "base/common.h" TEST(CommonTest, DebugOrRelease) { #ifdef NDEBUG printf("NDEBUG defined, this is a Release build\n"); #else printf("NDEBUG is not defined, this is a Debug build\n"); #endif }
Add Sema test case for exception-specifiers implicitly added to destructors.
// RUN: %clang_cc1 -fexceptions -verify %s struct A { }; struct B { }; struct X0 { virtual ~X0() throw(A); // expected-note{{overridden virtual function is here}} }; struct X1 { virtual ~X1() throw(B); // expected-note{{overridden virtual function is here}} }; struct X2 : public X0, public X1 { }; // expected-error 2{{exception specification of overriding function is more lax than base version}}
Add a Example Integrations with SFML graphics library
#include <SFML\Graphics.hpp> #include "Vector2d.h" int main() { sf::CircleShape object(15, 3); sf::Vector2f vector2f; //original compatible vector2f object from SFML Vector2d vector2d; //vector from Vector2d class, if you want to compute vector first you must create vector object, becouse it have float type components x & y vector2d = Vector2d::pointToPointVector(-13, 14, 21, 24); //Compute point to point vector vector2f.x = vector2d.x; //We can initiate vector SFML vector class vector2d, becouse the components have the same type - Float vector2f.y = vector2d.y; //Vector2d use float type as x & y components, but if You like You can convert to other primitive type using reinterpreter_cast<> object.move(vector2f); //Now you can translate object's with sfml compatible vector object.setRotation(Vector2d::rotationInDegreesFromVector(-13, 14, 21, 24)); //if you want the moved object was rotated in the direction of movement return EXIT_SUCCESS; }
Add Example 11.34 from Aho'72
// Attempting to replicate the CFG from Figure 11.25 of Aho and Ullman 1972. #include <iostream> int main() { unsigned n; std::cin >> n; int *A = new int[n]; int i = -1; int sum = 0; _2: ++i; _3: if (A[i] % 2 == 0) { goto _4; } _7: sum += A[i]; goto _2; _4: if (i < n && A[i] % 3 == 0) { ++i; goto _4; } _5: if (i < n && A[i] % 5 != 0) { goto _2; } _6: sum += A[i++]; if (i < n) { goto _3; } std::cout << sum << '\n'; delete[] A; }
Add a C++20 version of the existing turing machine test.
// RUN: %clang_cc1 -verify -std=c++2a %s // expected-no-diagnostics const unsigned halt = (unsigned)-1; enum Dir { L, R }; struct Action { bool tape; Dir dir; unsigned next; }; using State = Action[2]; // An infinite tape! struct Tape { constexpr Tape() = default; constexpr ~Tape() { if (l) { l->r = nullptr; delete l; } if (r) { r->l = nullptr; delete r; } } constexpr Tape *left() { if (!l) { l = new Tape; l->r = this; } return l; } constexpr Tape *right() { if (!r) { r = new Tape; r->l = this; } return r; } Tape *l = nullptr; bool val = false; Tape *r = nullptr; }; // Run turing machine 'tm' on tape 'tape' from state 'state'. Return number of // steps taken until halt. constexpr unsigned run(const State *tm) { Tape *tape = new Tape; unsigned state = 0; unsigned steps = 0; for (state = 0; state != halt; ++steps) { auto [val, dir, next_state] = tm[state][tape->val]; tape->val = val; tape = (dir == L ? tape->left() : tape->right()); state = next_state; } delete tape; return steps; } // 3-state busy beaver. S(bb3) = 21. constexpr State bb3[] = { { { true, R, 1 }, { true, R, halt } }, { { true, L, 1 }, { false, R, 2 } }, { { true, L, 2 }, { true, L, 0 } } }; static_assert(run(bb3) == 21, ""); // 4-state busy beaver. S(bb4) = 107. constexpr State bb4[] = { { { true, R, 1 }, { true, L, 1 } }, { { true, L, 0 }, { false, L, 2 } }, { { true, R, halt }, { true, L, 3 } }, { { true, R, 3 }, { false, R, 0 } } }; static_assert(run(bb4) == 107, "");
Initialize the global message center instance to NULL
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/message_center/message_center.h" #include "base/observer_list.h" #include "ui/message_center/message_center_impl.h" namespace message_center { //------------------------------------------------------------------------------ namespace { static MessageCenter* g_message_center; } // static void MessageCenter::Initialize() { DCHECK(g_message_center == NULL); g_message_center = new MessageCenterImpl(); } // static MessageCenter* MessageCenter::Get() { DCHECK(g_message_center); return g_message_center; } // static void MessageCenter::Shutdown() { DCHECK(g_message_center); delete g_message_center; g_message_center = NULL; } MessageCenter::MessageCenter() { } MessageCenter::~MessageCenter() { } } // namespace message_center
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/message_center/message_center.h" #include "base/observer_list.h" #include "ui/message_center/message_center_impl.h" namespace message_center { //------------------------------------------------------------------------------ namespace { static MessageCenter* g_message_center = NULL; } // static void MessageCenter::Initialize() { DCHECK(g_message_center == NULL); g_message_center = new MessageCenterImpl(); } // static MessageCenter* MessageCenter::Get() { DCHECK(g_message_center); return g_message_center; } // static void MessageCenter::Shutdown() { DCHECK(g_message_center); delete g_message_center; g_message_center = NULL; } MessageCenter::MessageCenter() { } MessageCenter::~MessageCenter() { } } // namespace message_center
Check in avx2 internals in new directory
// Copyright 2014 Irfan Hamid // // 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 "Enable.hpp" #include <immintrin.h> #include <cmath> #include "Avx2Internals.hpp" namespace khyber { namespace avx2 { void InternalAdd(size_t size, sp_t* sum, sp_t* augend, const sp_t* addend) { __m256* pSum = (__m256*)sum; __m256* pAugend = (__m256*)augend; __m256* pAddend = (__m256*)addend; size_t i; for ( i = 0; i < (size >> 3); ++i ) { pSum[i] = _mm256_add_ps(pAugend[i], pAddend[i]); } i <<= 3; for ( ; i < size; ++i ) { sum[i] = augend[i] + addend[i]; } } void InternalNegate(size_t size, sp_t *dst, sp_t *src) { __m256i* pDst = (__m256i*)dst; __m256i* pSrc = (__m256i*)src; __m256i mask = _mm256_set_epi32(0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000); size_t i; for ( i = 0; i < (size >> 3); ++i ) { pDst[i] = _mm256_xor_si256(pSrc[i], mask); } i <<= 3; for ( ; i < size; ++i ) { dst[i] = -src[i]; } } } }
Add a test for invalid assumptions on the alignment of exceptions
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // UNSUPPORTED: libcxxabi-no-exceptions // This test checks that the compiler does not make incorrect assumptions // about the alignment of the exception (only in that specific case, of // course). // // There was a bug where Clang would emit a call to memset assuming a 16-byte // aligned exception even when back-deploying to older Darwin systems where // exceptions are 8-byte aligned, which caused a segfault on those systems. struct exception { exception() : x(0) { } virtual ~exception() { } int x; }; struct foo : exception { }; int main() { try { throw foo(); } catch (...) { } return 0; }
Add PCCA summer camp practice
/************************************************************************* > File Name: PA.cpp > Author: Gavin Lee > School: National Chiao Tung University > Team: NCTU_Ragnorok > Mail: sz110010@gmail.com > Created Time: Mon 04 Apr 2016 10:33:00 PM CST ************************************************************************/ #include <bits/stdc++.h> using namespace std; bool prefix(string,string); int main() { int t; scanf("%d", &t); while(t--) { int n; scanf("%d", &n); string str[10000]; for(int i = 0; i < n; ++i) cin >> str[i]; sort(str, str+n); bool che = true; for(int i = 0; i < n-1; ++i) { if(prefix(str[i],str[i+1])) { che = false; break; } } if(che) cout << "YES" << endl; else cout << "NO" << endl; } return 0; } bool prefix(string a, string b) { if(a.length() > b.length()) return false; for(int i = 0; i < a.length(); ++i) { if(a[i] != b[i]) return false; } return true; }
Add solution to same prime factors problem
#include <iostream> using std::cout; using std::boolalpha; bool is_factor(int factor, int number) { return number % factor == 0; } bool is_prime(int number) { if (number == 2) { return true; } for (int i = 2; i < number; ++i) { if (is_factor(i, number)) { return false; } } return true; } bool is_prime_factor(int factor, int number) { return is_factor(factor, number) && is_prime(factor); } bool has_prime_factors_of(int number1, int number2) { for (int i = 2; i <= number2; ++i) { if (is_prime_factor(i, number2) && !is_factor(i, number1)) { return false; } } return true; } bool has_same_prime_factors(int number1, int number2) { return has_prime_factors_of(number1, number2) && has_prime_factors_of(number2, number1); } int main() { cout << boolalpha << has_same_prime_factors(10, 20) << '\n'; cout << boolalpha << has_same_prime_factors(10, 60) << '\n'; return 0; }
Remove Duplicates from Sorted List II.
/** * Remove Duplicates from Sorted List II * * cpselvis(cpselvis@gmail.com) * Oct 9th, 2016 */ #include<iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* deleteDuplicates(ListNode* head) { if (head == NULL || head -> next == NULL) return head; ListNode *dummy = new ListNode(-1); dummy -> next = head; head = dummy; while (head -> next != NULL && head -> next -> next != NULL) { if (head -> next -> val == head -> next -> next -> val) { int val = head -> next -> val; while (head -> next != NULL && head -> next -> val == val) { head -> next = head -> next -> next; } } else { head = head -> next; } } return dummy -> next; } }; int main(int argc, char **argv) { ListNode *head = new ListNode(1); head -> next = new ListNode(2); head -> next -> next = new ListNode(3); head -> next -> next -> next = new ListNode(3); head -> next -> next -> next -> next = new ListNode(4); head -> next -> next -> next -> next -> next = new ListNode(4); head -> next -> next -> next -> next -> next -> next = new ListNode(5); Solution s; ListNode *node = s.deleteDuplicates(head); while(node != NULL) { cout << node -> val << endl; node = node -> next; } }
Add test which detects bugs undetectable before r288563
// RUN: %clangxx_asan %stdcxx11 -O1 -fsanitize-address-use-after-scope %s -o %t && \ // RUN: not %run %t 2>&1 | FileCheck %s struct IntHolder { const IntHolder& Self() const { return *this; } int val = 3; }; const IntHolder *saved; int main(int argc, char *argv[]) { saved = &IntHolder().Self(); int x = saved->val; // BOOM // CHECK: ERROR: AddressSanitizer: stack-use-after-scope // CHECK: #0 0x{{.*}} in main {{.*}}use-after-scope-temp2.cc:[[@LINE-2]] return x; }
Check if Binary String Has at Most One Segment of Ones
class Solution { public: bool checkOnesSegment(string s) { bool flag = false; bool cont_flag = false; for (const auto &c : s) { if (c == '1') { if (flag && !cont_flag) { return false; } flag = true; cont_flag = true; } else { cont_flag = false; } } return true; } };
Add folder for storage the problem with primes.
#include <iostream> #include <math.h> using namespace std; typedef long long ll; bool is_prime(ll n){ if (n<=1) return false; if (n==2) return true; if (n%2==0) return false; ll root = sqrt(n); for (int i=3; i<= root; i+=2){ if(n%i == 0 ) return false; } return true; } int main(){ cout << is_prime(23234) << endl; cout << is_prime(2) << endl; cout << is_prime(7454) << endl; cout << is_prime(976) << endl; cout << is_prime(1973) << endl; return 0; }
Add 96 Unique Binary Search Trees
// 96 Unique Binary Search Trees /** * Given n, how many structurally unique BST's (binary search trees) that store values 1...n? * * For example, * Given n = 3, there are a total of 5 unique BST's. * * 1 3 3 2 1 * \ / / / \ \ * 3 2 1 1 3 2 * / / \ \ * 2 1 2 3 * * Tag: Tree, Dynamic Programming * * Author: Yanbin Lu */ #include <stddef.h> #include <vector> #include <string.h> #include <stdio.h> #include <algorithm> #include <iostream> #include <map> #include <queue> using namespace std; class Solution { public: int numTrees(int n) { if(n<=1) return 1; vector<int> dp(n+1,0); dp[0] = 1; dp[1] = 1; for(int i = 2; i<=n;i++) // set i as the root compute the number of trees on left side and right side for(int j = 1; j<=i;j++) dp[i] += dp[j-1]*dp[i-j]; return dp[n]; } }; int main() { Solution* sol = new Solution(); cout << sol->numTrees(5) << endl; cout << sol->numTrees(1) << endl; cout << sol->numTrees(500) << endl; char c; std::cin>>c; return 0; }
Add another C++14 constexpr test case.
// RUN: %clang_cc1 -std=c++1y -verify %s // expected-no-diagnostics constexpr void copy(const char *from, unsigned long count, char *to) { unsigned long n = (count + 7) / 8; switch(count % 8) { case 0: do { *to++ = *from++; case 7: *to++ = *from++; case 6: *to++ = *from++; case 5: *to++ = *from++; case 4: *to++ = *from++; case 3: *to++ = *from++; case 2: *to++ = *from++; case 1: *to++ = *from++; } while(--n > 0); } } struct S { char stuff[14]; constexpr S() : stuff{} { copy("Hello, world!", 14, stuff); } }; constexpr bool streq(const char *a, const char *b) { while (*a && *a == *b) ++a, ++b; return *a == *b; } static_assert(streq(S().stuff, "Hello, world!"), "should be same"); static_assert(!streq(S().stuff, "Something else"), "should be different");
Test for generate terms was added
/* * Copyright (C) 2015 deipi.com LLC and contributors. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include <stdlib.h> #include <stdint.h> #include "test_generate_terms.h" #include <check.h> START_TEST(numeric_test) { ck_assert_int_eq(numeric_test(), 0); } END_TEST START_TEST(date_test) { ck_assert_int_eq(date_test(), 0); } END_TEST START_TEST(geo_test) { ck_assert_int_eq(geo_test(), 0); } END_TEST Suite* Generate_Terms(void) { Suite *s = suite_create("Testing Generation of terms"); TCase *n = tcase_create("Generation numerical terms"); TCase *d = tcase_create("Generation of terms for dates"); TCase *g = tcase_create("Generation of terms for geospatials"); tcase_add_test(n, numeric_test); tcase_add_test(d, date_test); tcase_add_test(g, geo_test); suite_add_tcase(s, n); suite_add_tcase(s, d); suite_add_tcase(s, g); return s; } int main(void) { Suite *st = Generate_Terms(); SRunner *sr = srunner_create(st); srunner_run_all(sr, CK_NORMAL); int number_failed = srunner_ntests_failed(sr); srunner_free(sr); return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; }
Add (failing) unit test to demonstrate CGSolver bug with indefinite preconditioner.
// Copyright (c) 2010-2020, 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 "mfem.hpp" #include "catch.hpp" using namespace mfem; class FakeSolver : public Solver { private: Operator& op; public: FakeSolver(Operator& op_) : Solver(op_.Height()), op(op_) { } void SetOperator(const Operator &op) { } void Mult(const Vector& x, Vector& y) const { op.Mult(x, y); } }; TEST_CASE("CGSolver", "[Indefinite]") { // Define indefinite SparseMatrix SparseMatrix indefinite(2, 2); indefinite.Add(0, 1, 1.0); indefinite.Add(1, 0, 1.0); indefinite.Finalize(); Vector v(2); v(0) = 1.0; v(1) = -1.0; Vector x(2); x = 0.0; // check indefinite operator CGSolver cg; cg.SetOperator(indefinite); cg.SetPrintLevel(1); cg.Mult(v, x); REQUIRE(!cg.GetConverged()); // check indefinite preconditioner IdentityOperator identity(2); FakeSolver indefprec(indefinite); CGSolver cg2; cg2.SetOperator(identity); cg2.SetPreconditioner(indefprec); cg2.SetPrintLevel(1); x = 0.0; cg2.Mult(v, x); REQUIRE(!cg2.GetConverged()); }
Add the missing test case for folder view.
#include <QApplication> #include <QMainWindow> #include <QToolBar> #include <QDir> #include <QDebug> #include "../core/folder.h" #include "../foldermodel.h" #include "../folderview.h" #include "../cachedfoldermodel.h" #include "../proxyfoldermodel.h" #include "../pathedit.h" int main(int argc, char** argv) { QApplication app(argc, argv); QMainWindow win; Fm::FolderView folder_view; win.setCentralWidget(&folder_view); auto home = Fm2::FilePath::fromLocalPath(QDir().homePath().toLocal8Bit().constData()); Fm::CachedFolderModel* model = Fm::CachedFolderModel::modelFromPath(home); auto proxy_model = new Fm::ProxyFolderModel(); proxy_model->sort(Fm::FolderModel::ColumnFileName, Qt::AscendingOrder); proxy_model->setSourceModel(model); folder_view.setModel(proxy_model); QToolBar toolbar; win.addToolBar(Qt::TopToolBarArea, &toolbar); Fm::PathEdit edit; edit.setText(home.toString().get()); toolbar.addWidget(&edit); auto action = new QAction("Go"); toolbar.addAction(action); QObject::connect(action, &QAction::triggered, [&]() { auto path = Fm2::FilePath(edit.text().toLocal8Bit().constData()); auto new_model = Fm::CachedFolderModel::modelFromPath(path); proxy_model->setSourceModel(new_model); }); win.show(); return app.exec(); }
Add unit test for Map class -User Story 8
#include <gtest/gtest.h> #include <array> #include <memory> #include "Map.hpp" struct MapTest : public :: testing :: Test{ std::shared_ptr<Map> setmap = std::make_shared<Map>(); }; TEST_F(MapTest, LoadMapSwitchTest) { EXPECT_EQ(10,(setmap->getGridmap(1)).size()); EXPECT_FALSE((setmap->getGridmap(1)).empty()); EXPECT_FALSE((setmap->getGridmap(2)).empty()); EXPECT_FALSE((setmap->getGridmap(3)).empty()); EXPECT_FALSE((setmap->getGridmap(4)).empty()); } TEST_F(MapTest, SetstartTest) { EXPECT_EQ(std::make_pair(2, 3),setmap->SetStart(2,3)); } TEST_F(MapTest, SetgoalTest) { EXPECT_EQ(std::make_pair(4, 6),setmap->SetGoal(4,6)); }
Add another failing use-after-scope test
// RUN: %clangxx_asan -O1 -mllvm -asan-use-after-scope=1 %s -o %t && \ // RUN: not %run %t 2>&1 | FileCheck %s // XFAIL: * // FIXME: This works only for arraysize <= 8. char *p = 0; int main() { { char x[1024] = {}; p = x; } return *p; // BOOM }
Fix build for boost 1.66
--- src/rpcclient.cpp.orig 2017-05-18 01:39:08 UTC +++ src/rpcclient.cpp @@ -39,7 +39,7 @@ Object CallRPC(const string& strMethod, // Connect to localhost bool fUseSSL = GetBoolArg("-rpcssl", false); asio::io_service io_service; - ssl::context context(io_service, ssl::context::sslv23); + ssl::context context(ssl::context::sslv23); context.set_options(ssl::context::no_sslv2); asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context); SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
Add tests for generalized lambda capture (C++14). NFC.
// RUN: %clang_cc1 -std=c++14 -fsyntax-only -analyze -analyzer-checker=core,deadcode,debug.ExprInspection -verify %s int clang_analyzer_eval(int); void generalizedCapture() { int v = 7; auto lambda = [x=v]() { return x; }; int result = lambda(); clang_analyzer_eval(result == 7); // expected-warning {{TRUE}} } void sideEffectsInGeneralizedCapture() { int v = 7; auto lambda = [x=v++]() { return x; }; clang_analyzer_eval(v == 8); // expected-warning {{TRUE}} int r1 = lambda(); int r2 = lambda(); clang_analyzer_eval(r1 == 7); // expected-warning {{TRUE}} clang_analyzer_eval(r2 == 7); // expected-warning {{TRUE}} clang_analyzer_eval(v == 8); // expected-warning {{TRUE}} } int addOne(int p) { return p + 1; } void inliningInGeneralizedCapture() { int v = 7; auto lambda = [x=addOne(v)]() { return x; }; int result = lambda(); clang_analyzer_eval(result == 8); // expected-warning {{TRUE}} } void caseSplitInGeneralizedCapture(bool p) { auto lambda = [x=(p ? 1 : 2)]() { return x; }; int result = lambda(); clang_analyzer_eval(result == 1); // expected-warning {{FALSE}} expected-warning {{TRUE}} }
Implement Knight in Tours problem
#include <iostream> #define N 8 using namespace std; // A utility function to check the valid indexes // of N*N chess board bool isSafe(int x, int y, int sol[N][N]) { return (x >= 0 && y >= 0 && x < N && y < N && sol[x][y] == -1); } /** * Print the solution */ void printSolution(int sol[N][N]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { cout<<sol[i][j]<<" "; } cout<<endl; } } bool solveKTUtil(int x, int y, int movei, int sol[N][N], int xMove[N], int yMove[N]) { int k, next_x, next_y; if (movei == N*N) return true; /* Try all next moves from the current coordinate x, y */ for (k = 0; k < 8; k++) { next_x = x + xMove[k]; next_y = y + yMove[k]; if (isSafe(next_x, next_y, sol)) { sol[next_x][next_y] = movei; if (solveKTUtil(next_x, next_y, movei+1, sol, xMove, yMove) == true) return true; else sol[next_x][next_y] = -1;// backtracking } } return false; } void solveKT() { int sol[N][N]; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { sol[i][j] = -1; } } /* xMove[] and yMove[] define next move of Knight. xMove[] is for next value of x coordinate yMove[] is for next value of y coordinate */ int xMove[8] = { 2, 1, -1, -2, -2, -1, 1, 2 }; int yMove[8] = { 1, 2, 2, 1, -1, -2, -2, -1 }; sol[0][0] = 0; /* Start from 0,0 and explore all tours using solveKTUtil() */ if (solveKTUtil(0, 0, 1, sol, xMove, yMove) == false) { cout<<"Solution does not exists"; return; } else { printSolution(sol); } } int main() { solveKT(); return 0; }
Add a basic testcase for the "variable is not needed" warning and one that regressed in r168519.
// RUN: %clang_cc1 -fsyntax-only -verify -Wall %s namespace test1 { static int abc = 42; // expected-warning {{variable 'abc' is not needed and will not be emitted}} template <typename T> int foo(void) { return abc; } } namespace test2 { struct bah { }; namespace { struct foo : bah { static char bar; virtual void zed(); }; void foo::zed() { bar++; } char foo::bar=0; } bah *getfoo() { return new foo(); } }
Add numeric integration using Simpson's method.
double integrate(double (*f)(double), double a, double b, double delta = 1) { if(abs(a - b) < delta) { return (b-a)/6 * (f(a) + 4 * f((a+b)/2) + f(b)); } return integrate(f, a, (a+b)/2, delta) + integrate(f, (a+b)/2, b, delta); }
Edit distance between two strings
#include<iostream> using namespace std; int main() { string s1,s2; cout<<"Enter the two strings:"; cin>>s1>>s2; int l1=s1.length(); int l2=s2.length(); int d[l1+1][l2+1]; for(int i=0;i<=l1;i++) for(int j=0;j<=l2;j++){ if(i==0) d[0][j]=j; else if(j==0) d[i][0]=i; else if(s1[i-1]==s2[j-1]) d[i][j]=d[i-1][j-1]; else d[i][j]=1+min(d[i-1][j],min(d[i][j-1],d[i-1][j-1])); } cout<<"Edit distance is "<<d[l1][l2]<<".\n"; }
Add a simple C++ example.
#include <iostream> #include <string> #include "ucl++.h" int main(int argc, char **argv) { std::string input, err; input.assign((std::istreambuf_iterator<char>(std::cin)), std::istreambuf_iterator<char>()); auto obj = ucl::Ucl::parse(input, err); if (obj) { std::cout << obj.dump(UCL_EMIT_CONFIG) << std::endl; for (const auto &o : obj) { std::cout << o.dump(UCL_EMIT_CONFIG) << std::endl; } } else { std::cerr << "Error: " << err << std::endl; return 1; } }
Solve problem 17 in C++
// Copyright 2016 Mitchell Kember. Subject to the MIT License. // Project Euler: Problem 17 // Number letter counts namespace problem_17 { long solve() { constexpr long and_word = 3; constexpr long hundred = 7; constexpr long one_thousand = 3 + 8; constexpr long a = 0+3+3+5+4+4+3+5+5+4; // 0, 1, ..., 9 constexpr long b = 3+6+6+8+8+7+7+9+8+8; // 10, 11, ..., 19 constexpr long c = 6+6+5+5+5+7+6+6; // 20, 30, ..., 90 constexpr long s99 = 10*c + 9*a + b; constexpr long result = 10*s99 + (100*a + 9*100*hundred) + 9*99*and_word + one_thousand; return result; } } // namespace problem_17
Add merge sort implementation for singly linked list
/** * Merge sort algorithm. One of the efficient sorting algorithm. Works * on the principle of divide and conquer strategy. * * Very well suited especially for linked lists. Unlike array, in linked * lists, we can insert items in the middle in O(1) space and O(1) time. * So, merge operation can be implemented without extra space. */ /** * Merge sort algorithm on Singly linked list. */ #include <bits/stdc++.h> using namespace std; // Singly Linked list node structure struct node { int data; struct node* next; }; struct node* merge(struct node* a, struct node* b) { struct node* result = NULL; if (a == NULL) return(b); else if (b == NULL) return(a); if (a->data <= b->data) { result = a; result->next = merge(a->next, b); } else { result = b; result->next = merge(a, b->next); } return(result); } void split(struct node* source, struct node** frontRef, struct node** backRef) { struct node* fast; struct node* slow; if (source==NULL || source->next==NULL) { *frontRef = source; *backRef = NULL; } else { slow = source; fast = source->next; while (fast != NULL) { fast = fast->next; if (fast != NULL) { slow = slow->next; fast = fast->next; } } // 'slow' pointer is before the midpoint in the list // so splitting in two at that point. *frontRef = source; *backRef = slow->next; slow->next = NULL; } } void mergeSort(struct node** headRef) { struct node* a; struct node* b; if (*headRef == NULL || (*headRef)->next == NULL) return; // Split the list into two sublists. split(*headRef, &a, &b); // Recursively sort the sublists. mergeSort(&a); mergeSort(&b); *headRef = merge(a, b); } void push(node** head, int val) { node* newNode = new node; newNode->data = val; newNode->next = *head; *head = newNode; } int main() { int n; cin >> n; struct node *l = NULL; for (int i = 0; i < n; i++) { int val; cin >> val; push(&l, val); } mergeSort(&l); // Print the sorted list while(l != NULL) { cout << l->data << ' '; l = l->next; } cout << endl; return 0; } // Time Complexity is O(nlogn). // Space Complexity is constant.
Convert satoshiwords to test case.
/* * Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * 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 <boost/test/unit_test.hpp> #include <bitcoin/bitcoin.hpp> BOOST_AUTO_TEST_SUITE(satoshi_words) #ifndef ENABLE_TESTNET BOOST_AUTO_TEST_CASE(satoshi_words_mainnet) { // Create genesis block. auto block = bc::genesis_block(); // Genesis block contains a single coinbase transaction. BOOST_REQUIRE_EQUAL(block.transactions.size(), 1); // Get first transaction in block (coinbase). const bc::transaction_type& coinbase_tx = block.transactions[0]; // Coinbase tx has a single input. BOOST_REQUIRE_EQUAL(coinbase_tx.inputs.size(), 1); const bc::transaction_input_type& coinbase_input = coinbase_tx.inputs[0]; // Convert the input script to its raw format. const bc::data_chunk& raw_message = bc::save_script(coinbase_input.script); // Convert to a string after removing the 8 byte checksum. BOOST_REQUIRE_GT(raw_message.size(), 8u); std::string message; message.resize(raw_message.size() - 8); std::copy(raw_message.begin() + 8, raw_message.end(), message.begin()); BOOST_REQUIRE_EQUAL(message, "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks"); } #endif BOOST_AUTO_TEST_SUITE_END()
Add missing test for -Wunneeded-member-functions.
// RUN: %clang_cc1 -fsyntax-only -verify -Wunneeded-member-function %s namespace { class A { void g() {} // expected-warning {{is not needed and will not be emitted}} template <typename T> void foo() { g(); } }; }
Make sure GetHighResTime() doesn't get inlined because it is a slow function anyway since it calls QueryPerformanceCounter(). Also, it is often used when profiling, and when it gets inlined, it makes the disassembly look confusing.
#include "df_hi_res_time.h" #define WIN32_LEAN_AND_MEAN #include <Windows.h> static double g_tickInterval = -1.0; static double g_timeShift = 0.0; inline double GetLowLevelTime(); static void InitialiseHighResTime() { LARGE_INTEGER count; QueryPerformanceFrequency(&count); g_tickInterval = 1.0 / (double)count.QuadPart; g_timeShift = GetLowLevelTime(); } inline double GetLowLevelTime() { if (g_tickInterval < 0.0) InitialiseHighResTime(); LARGE_INTEGER count; QueryPerformanceCounter(&count); return (double)count.QuadPart * g_tickInterval; } double GetHighResTime() { double timeNow = GetLowLevelTime(); timeNow -= g_timeShift; return timeNow; } void SleepMillisec(int milliseconds) { Sleep(milliseconds); }
#include "df_hi_res_time.h" #define WIN32_LEAN_AND_MEAN #include <Windows.h> static double g_tickInterval = -1.0; static double g_timeShift = 0.0; inline double GetLowLevelTime(); static void InitialiseHighResTime() { LARGE_INTEGER count; QueryPerformanceFrequency(&count); g_tickInterval = 1.0 / (double)count.QuadPart; g_timeShift = GetLowLevelTime(); } inline double GetLowLevelTime() { if (g_tickInterval < 0.0) InitialiseHighResTime(); LARGE_INTEGER count; QueryPerformanceCounter(&count); return (double)count.QuadPart * g_tickInterval; } __declspec(noinline) double GetHighResTime() { double timeNow = GetLowLevelTime(); timeNow -= g_timeShift; return timeNow; } void SleepMillisec(int milliseconds) { Sleep(milliseconds); }
Add a test for multiple Func's that are compute_root when compiling for a GPU target.
#include <Halide.h> #include <iostream> using namespace Halide; int main(int argc, char *argv[]) { Var x; Func kernel1; kernel1(x) = floor(x / 3.0f); Func kernel2; kernel2(x) = sqrt(4 * x * x) + kernel1(x); Func kernel3; kernel3(x) = cast<int32_t>(x + kernel2(x)); Target target = get_target_from_environment(); if (target.features & Target::CUDA || target.features & Target::OpenCL) { kernel1.cuda_tile(x, 32).compute_root(); kernel2.cuda_tile(x, 32).compute_root(); kernel3.cuda_tile(x, 32); } Image<int32_t> result = kernel3.realize(256); for (int i = 0; i < 256; i ++) assert(result(i) == static_cast<int32_t>(floor(i / 3.0f) + sqrt(4 * i * i) + i)); std::cout << "Success!" << std::endl; }
Add the second codeforces problem
/* * Copyright (C) 2015 Pavel Dolgov * * See the LICENSE file for terms of use. */ /* http://codeforces.com/contest/527/submission/13054549 */ #include <iostream> #include <vector> int main() { int n; std::cin >> n; /* Sieve of Eratosthenes */ std::vector<char> prime(n+1, true); prime[0] = prime[1] = false; for (int i = 2; i <= n; i++) { if (1ll * i * i <= n) { for (int x = i * i; x <= n; x += i) { prime[x] = false; } } } typedef std::vector<int> Ints; Ints result; for (int i = 0; i <= n; i++) { if (prime[i]) { int s = 1; while (s <= n / i) { s *= i; result.push_back(s); } } } std::cout << result.size() << std::endl; for (Ints::const_iterator i = result.begin(); i != result.end(); i++) { std::cout << *i << " "; } std::cout << std::endl; return 0; }
Add a solution for problem 208: Implement Trie (Prefix Tree).
// Common implementation. Note below I add a NodeAfterPrefix to remove duplicate code // in search and startsWith. I also add a ~Trie() destructor to prevent memory leak. // Since the interface of Trie doesn't need to expose TrieNode, it's actually better // to implement TrieNode as a inner class of Trie. class TrieNode { static const int kNumChar = 26; TrieNode* successors[kNumChar]; bool is_node_; friend class Trie; public: // Initialize your data structure here. TrieNode(): is_node_(false) { fill(successors, successors + kNumChar, nullptr); } }; class Trie { public: Trie(): root_(new TrieNode) {} // Inserts a word into the trie. void insert(const string& word) { TrieNode* current = root_; for (char c: word) { if (current->successors[c-'a'] == nullptr) { current->successors[c-'a'] = new TrieNode; } current = current->successors[c-'a']; } current->is_node_ = true; } // Returns if the word is in the trie. bool search(const string& word) { TrieNode* p = NodeAfterPrefix(word); return p != nullptr && p->is_node_; } // Returns if there is any word in the trie // that starts with the given prefix. bool startsWith(const string& prefix) { TrieNode* p = NodeAfterPrefix(prefix); return p != nullptr; } ~Trie() { DeleteNodes(root_); } private: TrieNode* NodeAfterPrefix(const string& prefix) { TrieNode* current = root_; for (char c: prefix) { if (current->successors[c-'a'] == nullptr) { return nullptr; } current = current->successors[c-'a']; } return current; } void DeleteNodes(TrieNode* n) { for (int i = 0; i < TrieNode::kNumChar; ++i) { if (n->successors[i] != nullptr) { DeleteNodes(n->successors[i]); } } delete n; } TrieNode* root_; }; // Your Trie object will be instantiated and called as such: // Trie trie; // trie.insert("somestring"); // trie.search("key");
Enable Kannada, Farsi and Telugu on CrOS
// 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 <string> #if defined(OS_CHROMEOS) #include "base/basictypes.h" #include "base/string_util.h" #endif namespace l10n_util { // Return true blindly for now. bool IsLocaleSupportedByOS(const std::string& locale) { #if !defined(OS_CHROMEOS) return true; #else // We don't have translations yet for am, fa and sw. // We don't have fonts for te and kn, yet. // TODO(jungshik): Once the above issues are resolved, change this back // to return true. static const char* kUnsupportedLocales[] = {"am", "fa", "kn", "sw", "te"}; for (size_t i = 0; i < arraysize(kUnsupportedLocales); ++i) { if (LowerCaseEqualsASCII(locale, kUnsupportedLocales[i])) return false; } return true; #endif } } // namespace l10n_util
// 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 <string> #if defined(OS_CHROMEOS) #include "base/basictypes.h" #include "base/string_util.h" #endif namespace l10n_util { // Return true blindly for now. bool IsLocaleSupportedByOS(const std::string& locale) { #if !defined(OS_CHROMEOS) return true; #else // We don't have translations yet for am, and sw. // TODO(jungshik): Once the above issues are resolved, change this back // to return true. static const char* kUnsupportedLocales[] = {"am", "sw"}; for (size_t i = 0; i < arraysize(kUnsupportedLocales); ++i) { if (LowerCaseEqualsASCII(locale, kUnsupportedLocales[i])) return false; } return true; #endif } } // namespace l10n_util
Solve problem 20 in C++
// Copyright 2016 Mitchell Kember. Subject to the MIT License. // Project Euler: Problem 20 // Factorial digit sum #include "common.hpp" #include <gmpxx.h> namespace problem_20 { long solve() { mpz_class n(1); for (long i = 2; i <= 100; ++i) { n *= i; } return common::sum_of_digits(n); } } // namespace problem_20
Add solution for problem 083 Remove Duplicates from Sorted List
//083 Remove Duplicates from Sorted List /* *Given a sorted linked list, delete all duplicates such that each element appear only once. * *For example, *Given 1->1->2, return 1->2. *Given 1->1->2->3->3, return 1->2->3. * *Tag: Linked List * *Author: Linsen Wu */ #include "stdafx.h" //Definition for singly-linked list. struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* deleteDuplicates(ListNode* head) { if (head == NULL) { return NULL; } ListNode* current = head->next; ListNode* previous = head; while (current != NULL) { if (previous->val == current->val) { current = current->next; if (current == NULL) { previous->next = NULL; } } else { previous->next = current; previous = current; current = current->next; } } return head; } }; int _tmain(int argc, _TCHAR* argv[]) { return 0; }
Test to check how different variable implementations
#define BOOST_TEST_MODULE test_experimental #include <stdexcept> #include <memory> #include <boost/test/included/unit_test.hpp> #include "variable.hxx" #include "function.hxx" BOOST_AUTO_TEST_SUITE(test_experimental) double sum(std::vector<double> & args) { double res(0.); for (unsigned i = 0; i < args.size(); ++i) { res += double(args[i]); } return res; } struct compsetup { compsetup() : myfuncvar(NULL), myvar(NULL), varsum(NULL) { myfuncvar = std::make_shared<function>(); // 1 myvar = std::make_shared<variable>(); // 1 fnbase_vec vars {myfuncvar, myvar}; varsum = std::make_shared<function>(sum, vars); // 1+1 } ~compsetup() {} fnbase_ptr myfuncvar; fnbase_ptr myvar; fnbase_ptr varsum; }; BOOST_FIXTURE_TEST_CASE(compare_variable_impl, compsetup) { BOOST_CHECK_EQUAL(2, *varsum); } BOOST_AUTO_TEST_SUITE_END()
Document bug with condition variables and static linking (C++)
// Bug in clang/gcc or perhaps libc/nptl around static linking and condition // variables. // // Fails: clang++ -std=c++11 -static -o cv cv.cc -lpthread // // Workaround: // clang++ -std=c++11 -static -o cv cv.cc -Wl,--whole-archive -lpthread \ // -Wl,--no-whole-archive // #include <condition_variable> #include <iostream> using namespace std; int main( void ) { { condition_variable cv; } cout << "No fault!" << endl; return 0; }
Add a c++ inheritance example
#include <iostream> class A { public: void f(); void g(); }; class B : public A { public: void f(); }; class C { public: virtual void f(); void g(); }; class D : public C { public: void f(); }; void A::f() { std::cout << "A\n"; } void A::g() { f(); } void B::f() { std::cout << "B\n"; } void C::f() { std::cout << "C\n"; } void C::g() { f(); } void D::f() { std::cout << "D\n"; } int main() { B b; A &a = b; a.g(); // A D d; C &c = d; c.g(); // D return 0; }
Update Check BST or not
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ /* Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. Example 1: 2 / \ 1 3 Binary tree [2,1,3], return true. Example 2: 1 / \ 2 3 Binary tree [1,2,3], return false. */ class Solution { public: TreeNode* prev = NULL; bool isValidBST(TreeNode* root) { if (root) { if (!isValidBST(root->left)) return false; if (prev && root->val <= prev->val) return false; prev = root; cout<<prev->val<<endl; return isValidBST(root->right); } return true; } };
Add solution for chapter 17 test 29, test 30
#include <iostream> #include <random> #include <ctime> using namespace std; int generate_random_number(unsigned long long seed = time(0), const int a = 0, const int b = 9) { static default_random_engine e; static uniform_int_distribution<unsigned> u(a, b); e.seed(seed); return u(e); } int main() { for(int i = 0; i != 20; ++ i) { cout << generate_random_number() << endl; } return 0; }
Add tests of the Read struct
/* * ============================================================================ * * Filename: test-io.cc * Description: Tests of the IO module. * License: GPLv3+ * Author: Kevin Murray, spam@kdmurray.id.au * * ============================================================================ */ #include "catch.hpp" #include "qc-io.hh" TEST_CASE("Read access and clearing", "[Read]") { qcpp::Read read; SECTION("Filling read members works") { read.name = "Name"; read.sequence = "ACGT"; read.quality = "IIII"; REQUIRE(read.name.size() == 4); REQUIRE(read.sequence.size() == 4); REQUIRE(read.quality.size() == 4); } SECTION("Clearing a read empties members") { read.clear(); REQUIRE(read.name.size() == 0); REQUIRE(read.sequence.size() == 0); REQUIRE(read.quality.size() == 0); } }
Add Ben Deane's unique_ptr guideline from his Twitter.
// Ben Deane: // https://twitter.com/ben_deane/status/964549956437606400 // https://t.co/mkOX0mf8jt // When giving unique_ptr a custom deleter, prefer a stateless functor type over // a function pointer type. The implementation won't have to store the pointer // or call through it, and EBO means no overhead. #include <memory> struct custom_deleter_t { void operator()(int *) {} }; int main() { using T = std::unique_ptr<int, void (*)(int *)>; using U = std::unique_ptr<int, custom_deleter_t>; static_assert(sizeof(T) == sizeof(int *) * 2); static_assert(sizeof(U) == sizeof(int *)); }
Add Solution for Problem 031
// 031. Next Permutation /** * Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. * * If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). * * The replacement must be in-place, do not allocate extra memory. * * Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. * 1,2,3 1,3,2 * 3,2,1 1,2,3 * 1,1,5 1,5,1 * * Tags: Array * * Similar Problems: (M) Permutations (M) Permutations II (M) Permutation Sequence (M) Palindrome Permutation II * * Author: Kuang Qin */ #include "stdafx.h" #include <vector> #include <iostream> using namespace std; class Solution { public: void nextPermutation(vector<int>& nums) { int n = nums.size(); if (n < 2) { return; } // start from the last element, search for the first pair in ascending order int i = n - 1; while ((i > 0) && (nums[i - 1] >= nums[i])) { i--; } // if found, start from the last element, search for the first element that is larger if (i != 0) { int j = n - 1; while ((j >= i) && (nums[i - 1] >= nums[j])) { j--; } // swap these two elements swap(nums[i - 1], nums[j]); } // reverse the rest of the array reverse(nums.begin() + i, nums.end()); return; } }; int _tmain(int argc, _TCHAR* argv[]) { vector<int> nums; nums.push_back(1); nums.push_back(6); nums.push_back(6); nums.push_back(3); cout << "Current Permutation: "; for (int i = 0; i < nums.size(); i++) { cout << nums[i] << " "; } cout << endl; Solution mySolution; mySolution.nextPermutation(nums); cout << "Next Permutation: "; for (int i = 0; i < nums.size(); i++) { cout << nums[i] << " "; } cout << endl; system("pause"); return 0; }
Add solution for 190 Reverse Bits
//190. Reverse Bits /* *Reverse bits of a given 32 bits unsigned integer. * *For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000). * *Follow up: *If this function is called many times, how would you optimize it? * *Related problem: Reverse Integer * *Tag: Bit Manipulation * *Author: Linsen Wu */ #include "stdafx.h" #include <stdint.h> class Solution { public: uint32_t reverseBits(uint32_t n) { uint32_t left = 0x80000000; uint32_t right = 0x00000001; for (int i = 0; i < 16; i++) { uint32_t leftbit = n & left; uint32_t rightbit = n & right; leftbit = leftbit >> 31-i*2; rightbit = rightbit << 31-i*2; n = n & ~left & ~right; n = n | leftbit | rightbit; left = left >> 1; right = right << 1; } return n; } }; int _tmain(int argc, _TCHAR* argv[]) { uint32_t input = 0x80000000; Solution _solution; _solution.reverseBits(input); return 0; }
Remove Duplicates from Sorted List II
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* deleteDuplicates(ListNode* head) { if (!head) return 0; if (!head->next) return head; int val = head->val; ListNode* p = head->next; if (p->val != val) { head->next = deleteDuplicates(p); return head; } else { while (p && p->val == val) p = p->next; return deleteDuplicates(p); } } };
Add missing file preventing compilation
// We need our declaration #include "../../include/Utils/Dump.hpp" namespace Utils { // Produce a nice hexdump of the given byte array void hexDump(Strings::FastString & out, const uint8 * const array, const uint32 length, const uint32 colSize, const bool withAddress, const bool withCharVal) { uint32 i = 0; for (; i < length; i++) { if ((i % colSize) == 0) { // Output the charVal if any present if (withCharVal && i) { out += " "; for (uint32 j = i - colSize; j < i; j++) { out += Strings::FastString::Print("%c", array[j] < 32 ? '.' : array[j]); } } out += "\n"; if (withAddress) out += Strings::FastString::Print("%08X ", i); } out += Strings::FastString::Print("%02X ", (unsigned int)array[i]); } // Output the charVal if any present if (withCharVal && i) { for (uint32 k = 0; k < colSize - (i % colSize); k++) out += " "; out += " "; for (uint32 j = i - colSize; j < i; j++) { out += Strings::FastString::Print("%c", array[j] < 32 ? '.' : array[j]); } } } }
Add missing source file for New_Session_Ticket msg
/* * Session Tickets * (C) 2012 Jack Lloyd * * Released under the terms of the Botan license */ #include <botan/internal/tls_messages.h> #include <botan/internal/tls_extensions.h> #include <botan/internal/tls_reader.h> #include <botan/tls_record.h> #include <botan/loadstor.h> namespace Botan { namespace TLS { New_Session_Ticket::New_Session_Ticket(const MemoryRegion<byte>& buf) : m_ticket_lifetime_hint(0) { if(buf.size() >= 4) { m_ticket_lifetime_hint = load_be<u32bit>(&buf[0], 0); m_ticket.resize(buf.size() - 4); copy_mem(&m_ticket[0], &buf[4], buf.size() - 4); } } MemoryVector<byte> New_Session_Ticket::serialize() const { MemoryVector<byte> buf(4 + m_ticket.size()); store_be(m_ticket_lifetime_hint, &buf[0]); copy_mem(&buf[4], &m_ticket[0], m_ticket.size()); return buf; } } }
Convert Sorted Array to Binary Search Tree.
/** * Convert Sorted Array to Binary Search Tree * * cpselvis(cpselvis@gmail.com) * September 25th, 2016 */ #include<iostream> #include<vector> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: TreeNode* sortedArrayToBST(vector<int>& nums) { return dfs(nums, 0, nums.size()); } TreeNode* dfs(vector<int> &nums, int left, int right) { if (left > right) { return NULL; } int mid = (left + right) >> 1; TreeNode *node = new TreeNode(nums[mid]); node -> left = dfs(nums, left, mid - 1); node -> right = dfs(nums, mid + 1, right); return node; } }; int main(int argc, char **argv) { Solution s; vector<int> vec({1, 2, 4, 5, 6 ,7 , 8}); s.sortedArrayToBST(vec); }
Add simple vec2 addition test case
#include "test.h" #include "../src/vec2.h" using namespace jogurt; NUMERIC_TEST_CASE("2D vector addition", "[vec2]") { vec2<T> v0 = { 1, 10 }; vec2<T> v1 = { 20, 2 }; vec2<T> v2 = { 4, 40 }; SECTION("Zero is the neutral element") { REQUIRE(v0 + zero2<T>() == v0); REQUIRE(v1 + zero2<T>() == v1); REQUIRE(v0 - zero2<T>() == v0); REQUIRE(v1 - zero2<T>() == v1); } SECTION("Is comutative") { REQUIRE(v0 + v1 == v1 + v0); REQUIRE(v0 - v1 == -(v1 - v0)); } SECTION("Is associative") { REQUIRE((v0 + v1) + v2 == v0 + (v1 + v2)); } SECTION("Subtracting is adding the opposite") { REQUIRE(v0 - v1 == v0 + (-v1)); REQUIRE(v1 - v0 == v1 + (-v0)); } SECTION("Addition is distributive over multiplication") { REQUIRE(2 * (v0 + v1) == 2 * v0 + 2 * v1); REQUIRE(3 * (v1 - v2) == 3 * v1 - 3 * v2); } }
Add solution 389. Find the Difference
/* * https://leetcode.com/problems/find-the-difference/ * Given two strings s and t which consist of only lowercase letters. * String t is generated by random shuffling string s and then add one more letter at a random position. * Find the letter that was added in t. Example: Input: s = "abcd" t = "abcde" Output: e Explanation: 'e' is the letter that was added. */ class Solution { public: char findTheDifference(string s, string t) { map<char, int> hash; for(int i = 0; i < t.size(); i++) { hash[t[i]] = (hash.count(t[i]) == 0) ? 1 : hash[t[i]] + 1; } for(int i = 0; i < s.size(); i++) { hash[s[i]] -= 1; } char res; for_each(begin(hash), end(hash), [&res](std::map<char, int>::reference element) { if(element.second == 1) res = element.first; }); return res; } };
Create gtest entry-point in tester project.
/** * @file main.cpp * @brief Tester project entry-point. * @author zer0 * @date 2016-11-01 */ #include <gtest/gtest.h> int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
Sort Even and Odd Indices Independently
class Solution { public: vector<int> sortEvenOdd(vector<int>& nums) { if (nums.empty()) return nums; std::vector<int> odd, even; for (int i = 0; i < nums.size(); ++i) { if (i % 2 == 0) { even.emplace_back(nums[i]); } else { odd.emplace_back(nums[i]); } } std::sort(even.begin(), even.end()); std::sort(odd.begin(), odd.end(), [](int i, int j){ return i > j; }); for (int i = 0; i < even.size(); ++i) { nums[i*2] = even[i]; if ((i*2+1) < nums.size()) nums[i*2+1] = odd[i]; } return nums; } };
Tweak 4-way parallel output to work on pins 12-15 on esp8266 - keep blocked out for now, needs some more testing.
#define FASTLED_INTERNAL #include "FastLED.h" /// Simplified form of bits rotating function. Based on code found here - http://www.hackersdelight.org/hdcodetxt/transpose8.c.txt - rotating /// data into LSB for a faster write (the code using this data can happily walk the array backwards) void transpose8x1_noinline(unsigned char *A, unsigned char *B) { uint32_t x, y, t; // Load the array and pack it into x and y. y = *(unsigned int*)(A); x = *(unsigned int*)(A+4); // pre-transform x t = (x ^ (x >> 7)) & 0x00AA00AA; x = x ^ t ^ (t << 7); t = (x ^ (x >>14)) & 0x0000CCCC; x = x ^ t ^ (t <<14); // pre-transform y t = (y ^ (y >> 7)) & 0x00AA00AA; y = y ^ t ^ (t << 7); t = (y ^ (y >>14)) & 0x0000CCCC; y = y ^ t ^ (t <<14); // final transform t = (x & 0xF0F0F0F0) | ((y >> 4) & 0x0F0F0F0F); y = ((x << 4) & 0xF0F0F0F0) | (y & 0x0F0F0F0F); x = t; *((uint32_t*)B) = y; *((uint32_t*)(B+4)) = x; }
Test for the new FileUtil::GetFileName() functions.
/** \file xml_parser_test.cc * \brief Tests the FileUtil::GetFileName() function. * \author Dr. Johannes Ruscheinski */ /* Copyright (C) 2015, Library of the University of Tübingen 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 <stdexcept> #include "FileUtil.h" #include "util.h" __attribute__((noreturn)) void Usage() { std::cerr << "usage: " << ::progname << " path\n"; std::exit(EXIT_FAILURE); } int main(int argc, char *argv[]) { ::progname = argv[0]; if (argc != 2) Usage(); try { FILE *file(std::fopen(argv[1], "r")); std::cout << "File pointer points to \"" << FileUtil::GetFileName(file) << "\".\n"; } catch(const std::exception &x) { Error("caught exception: " + std::string(x.what())); } }
Add missing file from prior commit.
//===--- ProtocolConformance.cpp - AST Protocol Conformance -----*- C++ -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file implements the protocol conformance data structures. // //===----------------------------------------------------------------------===// #include "swift/AST/ASTContext.h" #include "swift/AST/ProtocolConformance.h" using namespace swift; void *ProtocolConformance::operator new(size_t bytes, ASTContext &context, unsigned alignment) { return context.Allocate(bytes, alignment); } #define CONFORMANCE_SUBCLASS_DISPATCH(Method, Args) \ switch (getKind()) { \ case ProtocolConformanceKind::Normal: \ static_assert(&ProtocolConformance::Method != \ &NormalProtocolConformance::Method, \ "Must override NormalProtocolConformance::" #Method); \ return cast<NormalProtocolConformance>(this)->Method Args; \ case ProtocolConformanceKind::Specialized: \ static_assert(&ProtocolConformance::Method != \ &InheritedProtocolConformance::Method, \ "Must override InheritedProtocolConformance::" #Method); \ return cast<SpecializedProtocolConformance>(this)->Method Args; \ case ProtocolConformanceKind::Inherited: \ static_assert(&ProtocolConformance::Method != \ &InheritedProtocolConformance::Method, \ "Must override InheritedProtocolConformance::" #Method); \ return cast<InheritedProtocolConformance>(this)->Method Args; \ } /// Get the protocol being conformed to. ProtocolDecl *ProtocolConformance::getProtocol() const { CONFORMANCE_SUBCLASS_DISPATCH(getProtocol, ()) } /// Get the module that contains the conforming extension or type declaration. Module *ProtocolConformance::getContainingModule() const { CONFORMANCE_SUBCLASS_DISPATCH(getContainingModule, ()) } /// Retrieve the complete set of type witnesses. const TypeWitnessMap &ProtocolConformance::getTypeWitnesses() const { CONFORMANCE_SUBCLASS_DISPATCH(getTypeWitnesses, ()) } const WitnessMap &ProtocolConformance::getWitnesses() const { CONFORMANCE_SUBCLASS_DISPATCH(getWitnesses, ()) } const InheritedConformanceMap & ProtocolConformance::getInheritedConformances() const { CONFORMANCE_SUBCLASS_DISPATCH(getInheritedConformances, ()) } /// Determine whether the witness for the given requirement /// is either the default definition or was otherwise deduced. bool ProtocolConformance::usesDefaultDefinition(ValueDecl *requirement) const { CONFORMANCE_SUBCLASS_DISPATCH(usesDefaultDefinition, (requirement)) }
Add test file with main method
#include <iostream> #include "node.h" #include "car.h" using namespace traffic; int main(int argc, char* argv[]) { std::shared_ptr<Node> Rochester (new Node); std::shared_ptr<Node> Buffalo (new Node); Node::LinkNeighbors(Rochester, Buffalo, 60.0); std::cout << Rochester->GetDistanceFrom(Buffalo) << std::endl; return 0; }
Add a simple experiment to test one particular optimization
#include <atomic> extern "C" { #if 0 } #endif const std::memory_order mo_rlx = std::memory_order_relaxed; const std::memory_order mo_rel = std::memory_order_release; const std::memory_order mo_acq = std::memory_order_acquire; const std::memory_order mo_acq_rel = std::memory_order_acq_rel; int load_store(std::atomic<int> *x, std::atomic<int> *y) { int r = y->load(mo_acq); x->store(1, mo_rel); return r; } int load_cas(std::atomic<int> *x, std::atomic<int> *y) { int r = y->load(mo_acq); x->compare_exchange_weak(r, 20, mo_rel, mo_rlx); return r; } int main() { return 0; } }
Add test for self-referencing emplace test.
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <vector> // template <class... Args> iterator emplace(const_iterator pos, Args&&... args); #include <vector> #include <cassert> int main() { #ifndef _LIBCPP_HAS_NO_GENERALIZED_INITIALIZERS { std::vector<int> v; v.reserve(3); v = { 1, 2, 3 }; v.emplace(v.begin(), v.back()); assert(v[0] == 3); } { std::vector<int> v; v.reserve(4); v = { 1, 2, 3 }; v.emplace(v.begin(), v.back()); assert(v[0] == 3); } #endif // _LIBCPP_HAS_NO_GENERALIZED_INITIALIZERS }
Add test for incorrect self-intersections w/Triangles.
#include "tests/gtest/gtest.h" #include <cmath> #include "pbrt.h" #include "rng.h" #include "shape.h" #include "sampling.h" #include "shapes/triangle.h" static Float p(RNG &rng) { Float logu = Lerp(rng.UniformFloat(), -8., 8); return std::pow(10, logu); } TEST(Triangle, Reintersect) { for (int i = 0; i < 1000; ++i) { RNG rng(i); // Triangle vertices Point3f v[3]; for (int j = 0; j < 3; ++j) for (int k = 0; k < 3; ++k) v[j][k] = p(rng); // Create the corresponding Triangle. Transform identity; int indices[3] = {0, 1, 2}; std::vector<std::shared_ptr<Shape>> triVec = CreateTriangleMesh(&identity, &identity, false, 1, indices, 3, v, nullptr, nullptr, nullptr, nullptr, nullptr); EXPECT_EQ(1, triVec.size()); std::shared_ptr<Shape> tri = triVec[0]; // Sample a point on the triangle surface to shoot the ray toward. Point2f u; u[0] = rng.UniformFloat(); u[1] = rng.UniformFloat(); Interaction pTri = tri->Sample(u); // Choose a ray origin. Point3f o; for (int j = 0; j < 3; ++j) o[j] = p(rng); // Intersect the ray with the triangle. Ray r(o, pTri.p - o); Float tHit; SurfaceInteraction isect; if (!tri->Intersect(r, &tHit, &isect, false)) // We should almost always find an intersection, but rarely // miss, due to round-off error. Just do another go-around in // this case. continue; // Now trace a bunch of rays leaving the intersection point. for (int j = 0; j < 10000; ++j) { // Random direction leaving the intersection point. Point2f u; u[0] = rng.UniformFloat(); u[1] = rng.UniformFloat(); Vector3f w = UniformSampleSphere(u); Ray rOut = isect.SpawnRay(w); EXPECT_FALSE(tri->IntersectP(rOut)); SurfaceInteraction spawnIsect; Float tHit; EXPECT_FALSE(tri->Intersect(rOut, &tHit, &isect, false)); // Choose a random point to trace rays to. Point3f p2; for (int k = 0; k < 3; ++k) p2[k] = p(rng); rOut = isect.SpawnRayTo(p2); EXPECT_FALSE(tri->IntersectP(rOut)); EXPECT_FALSE(tri->Intersect(rOut, &tHit, &isect, false)); } } }
Add noilerplate code for Binary Search Trees.
#include <bits/stdc++.h> using namespace std; typedef struct node node; struct Node{ int data; Node *left; Node *right; Node(const int & value, Node *lt = NULL, Node *rt = NULL): data(value), left(lt), right(rt) {} }; class BST{ public: BST(): root(NULL) {} ~BST(){ destroy_tree(); } void insert(int key); node* search(int key); void destroy_tree(); private: Node *root; };
Enable Android executables (like skia_launcher) to redirect SkDebugf output to stdout as well as the system logs.
/* * Copyright 2006 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkTypes.h" static const size_t kBufferSize = 256; #define LOG_TAG "skia" #include <android/log.h> void SkDebugf(const char format[], ...) { va_list args; va_start(args, format); __android_log_vprint(ANDROID_LOG_DEBUG, LOG_TAG, format, args); va_end(args); }
/* * Copyright 2006 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkTypes.h" static const size_t kBufferSize = 256; #define LOG_TAG "skia" #include <android/log.h> static bool gSkDebugToStdOut = false; extern "C" void AndroidSkDebugToStdOut(bool debugToStdOut) { gSkDebugToStdOut = debugToStdOut; } void SkDebugf(const char format[], ...) { va_list args; va_start(args, format); __android_log_vprint(ANDROID_LOG_DEBUG, LOG_TAG, format, args); // Print debug output to stdout as well. This is useful for command // line applications (e.g. skia_launcher) if (gSkDebugToStdOut) { vprintf(format, args); } va_end(args); }
Fix range check for rb_fix2uint
#include "capi/ruby.h" extern "C" { unsigned long rb_fix2uint(VALUE obj) { unsigned long num = rb_num2ulong(obj); if((int)num < 0) { rb_raise(rb_eRangeError, "integer too small to convert into unsigned int"); } if((unsigned int)num != num) { rb_raise(rb_eRangeError, "integer too big to convert into unsigned int"); } return num; } long rb_fix2int(VALUE obj) { long num = rb_num2long(obj); if((int)num != num) { rb_raise(rb_eRangeError, "integer too big to convert into unsigned int"); } return num; } }
#include "capi/ruby.h" extern "C" { unsigned long rb_fix2uint(VALUE obj) { unsigned long num = rb_num2ulong(obj); if((long)num < 0) { rb_raise(rb_eRangeError, "integer too small to convert into unsigned int"); } if((unsigned int)num != num) { rb_raise(rb_eRangeError, "integer too big to convert into unsigned int"); } return num; } long rb_fix2int(VALUE obj) { long num = rb_num2long(obj); if((int)num != num) { rb_raise(rb_eRangeError, "integer too big to convert into unsigned int"); } return num; } }
Swap pairs in linked list.
/** * Swap Nodes in Pairs * Dummy head. * cpselvis (cpselvis@gmail.com) * August 22th, 2016 */ #include<iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* swapPairs(ListNode* head) { ListNode *dummy = new ListNode(-1); dummy -> next = head; ListNode *prev = dummy; while (head && head -> next) { ListNode *next = head -> next -> next; prev -> next = head -> next; prev -> next -> next = head; head -> next = next; prev = head; head = next; } return dummy -> next; } }; int main(int argc, char **argv) { ListNode *l1 = new ListNode(1); l1 -> next = new ListNode(2); l1 -> next -> next = new ListNode(3); l1 -> next -> next -> next = new ListNode(4); Solution s; ListNode *l2 = s.swapPairs(l1); while (l2 != NULL) { cout << l2 -> val << endl; l2 = l2 -> next; } }
Add equations for some summatories.
/* Summatories */ int main(){ sum(i) from 1 to n = n(n+1)/2 sum(i^2) from 1 to n = n(n+1)(2n+1)/6 sum(i^3) from 1 to n = (n^2(n+1)^2)/4 }
Delete Operation for Two Strings
class Solution { public: int minDistance(string word1, string word2) { int dp[word1.size()+1][word2.size()+1]; for (int i = 0; i <= word1.size(); ++i) { for (int j = 0; j <= word2.size(); ++j) { dp[i][j] = 0; } } for (int i = 0; i <= word1.size(); ++i) { for (int j = 0; j <= word2.size(); ++j) { if (i == 0 || j == 0) { dp[i][j] = 0; } else { if (word1[i-1] == word2[j-1]) { dp[i][j] = dp[i-1][j-1] + 1; } else { dp[i][j] = std::max(dp[i][j-1], dp[i-1][j]); } } } } return word1.size() + word2.size() - 2 * dp[word1.size()][word2.size()]; } };
Add C++ solution for prims algorithm in graphs section
#include <bits/stdc++.h> #define NO_OF_NODES 8 using namespace std; struct node { int fr, to, cost; }p[6]; int c = 0, temp1 = 0, temp = 0; void prims(int *a, int b[][NO_OF_NODES], int i, int j) { a[i] = 1; while (c < 6) { int min = 999; for (int i = 0; i < NO_OF_NODES; i++) { if (a[i] == 1) { for (int j = 0; j < NO_OF_NODES; ) { if (b[i][j] >= min || b[i][j] == 0) { j++; } else if (b[i][j] < min) { min = b[i][j]; temp = i; temp1 = j; } } } } a[temp1] = 1; p[c].fr = temp; p[c].to = temp1; p[c].cost = min; c++; b[temp][temp1] = b[temp1][temp]=1000; } for (int k = 0; k < NO_OF_NODES-1; k++) { cout<<"Source node: "<<p[k].fr<<endl; cout<<"Destination node: "<<p[k].to<<endl; cout<<"Weight of node: "<<p[k].cost<<"\n\n"; } } int main() { int a[NO_OF_NODES]; for (int i = 0; i < NO_OF_NODES; i++) { a[i] = 0; } int b[NO_OF_NODES][NO_OF_NODES]; for (int i = 0; i < NO_OF_NODES; i++) { cout<<"enter values for "<<(i+1)<<" row"<<endl; for (int j = 0; j < NO_OF_NODES; j++) { cin>>b[i][j]; } } prims(a, b, 0, 0); return 0; }
Add the solution to "Anagram".
#include <iostream> #include <string> using namespace std; int anagram(string s) { int len = s.size(); if (len & 1) return -1; int flag[26] = {0}; for (int i = len / 2; i < len; i++) { flag[s[i] - 'a']++; } int res = len / 2; for (int i = 0; i < len / 2; i++) { if (flag[s[i] - 'a']) { flag[s[i] - 'a']--; res--; } } return res; } int main() { int T; cin >> T; while (T--) { string s; cin >> s; cout << anagram(s) << endl; } return 0; }
Cut Off Trees for Golf Event
class Solution { public: int cutOffTree(vector<vector<int>>& forest) { if(forest.empty()) return 0; if(forest[0].empty()) return 0; vector<vector<int>> t; for(int i=0;i<forest.size();i++){ for(int j=0;j<forest[0].size();j++){ if(forest[i][j]>1){ t.push_back({forest[i][j],i,j}); } } } sort(t.begin(),t.end()); int ans=0,x=0,y=0; for(int i=0;i<t.size();i++){ int add=bfs(forest,x,y,t[i][1],t[i][2]); if(add==-1) return -1; ans+=add; x=t[i][1]; y=t[i][2]; } return ans; } int bfs(vector<vector<int>>& forest,int i,int j,int fi,int fj){ if(i==fi && j==fj) return 0; queue<pair<int, int>> q; q.push(make_pair(i,j)); vector<vector<bool>> visited(forest.size(),vector<bool>(forest[0].size(),false)); visited[i][j]=true; int step=0; vector<vector<int>> dir={{1,0},{-1,0},{0,1},{0,-1}}; while(q.size()){ step++; int size=q.size(); for(int i=0;i<size;i++){ int row=q.front().first; int col=q.front().second; q.pop(); for(int i=0;i<dir.size();i++){ int r=row+dir[i][0]; int c=col+dir[i][1]; if (r<0||r>=forest.size()||c<0||c>=forest[0].size()||visited[r][c]==1||forest[r][c]==0) continue; if (r==fi&&c==fj) return step; visited[r][c]=1; q.push(make_pair(r,c)); } } } return -1; } };
Add Chapter 25, exercise 6
// Chapter 25, exercise 6: write an infinite loop that is hard to recognize as // an infinite loop #include<iostream> #include<exception> using namespace std; int main() try { for (char ch = 0; ch<250; ++ch) cout << int(ch) << '\n'; } catch (exception& e) { cerr << "exception: " << e.what() << endl; } catch (...) { cerr << "exception\n"; return 2; }
Rearrange Array Elements by Sign
class Solution { public: vector<int> rearrangeArray(vector<int>& nums) { std::vector<int> pos, neg, ret; for (const auto& i : nums) { if (i > 0) { pos.emplace_back(std::move(i)); } else { neg.emplace_back(std::move(i)); } } for (int i = 0; i < pos.size(); ++i) { nums[i*2] = std::move(pos[i]); nums[i*2+1] = std::move(neg[i]); } return nums; } };
Check if MSVC compiler supports OpenMP
/// /// @file has_openmp.cpp /// @brief Used to check if MSVC compiler supports OpenMP. /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <omp.h> #include <iostream> int main() { std::cout << "OpenMP version (yyyymm) : " << _OPENMP << std::endl << "Number of CPU cores : " << omp_get_max_threads() << std::endl; return 0; }
Insert at tail of list
/* Insert Node at the end of a linked list head pointer input could be NULL as well for empty list Node is defined as struct Node { int data; struct Node *next; } */ Node* Insert(Node *head,int data) { Node* tmp = new Node(); tmp->data = data; tmp->next = NULL; if (head == NULL) { return tmp; } else { if (head->next == NULL) { head->next = tmp; return head; } Insert(head->next, data); return head; } }
Add a test for __asan_gen_ globals labels on Darwin.
// Make sure __asan_gen_* strings have the correct prefixes on Darwin // ("L" in __TEXT,__cstring, "l" in __TEXT,__const // RUN: %clang_asan %s -S -o %t.s // RUN: cat %t.s | FileCheck %s || exit 1 int x, y, z; int main() { return 0; } // CHECK: .section{{.*}}__TEXT,__const // CHECK: l___asan_gen_ // CHECK: .section{{.*}}__TEXT,__cstring,cstring_literals // CHECK: L___asan_gen_ // CHECK: L___asan_gen_ // CHECK: L___asan_gen_
Change names of the interface on net part.
// Created on November 19, 2013 by Lu, Wangshan. #include <boost/asio.hpp> #include <diffusion/factory.hpp> namespace diffusion { class NetReader : public Reader { public: NetReader(std::string const & listening_ip_address, std::uint16_t listening_port); virtual bool has_next(); virtual ByteBuffer get_next(); private: }; } // namespace diffusion
// Created on November 19, 2013 by Lu, Wangshan. #include <boost/asio.hpp> #include <diffusion/factory.hpp> namespace diffusion { class NetReader : public Reader { public: NetReader(std::string const & listening_ip_address, std::uint16_t listening_port); virtual bool can_read(); virtual ByteBuffer read(); private: }; } // namespace diffusion
Test solver on the hardest sudoku
#include <iostream> #include "sudoku.h" int main(int argc, char* argv[]) { //Hardest sudoku : http://www.mirror.co.uk/news/weird-news/worlds-hardest-sudoku-can-you-242294 std::string chain = "005300000800000020070010500400005300010070006003200080060500009004000030000009700"; Sudoku s; for(int i = 0; i < chain.size(); ++i) if(chain[i] != '0') s.setValue(i, chain[i]-'0'); std::cout << s << std::endl; Sudoku::solve(s); std::cout << s << std::endl; return 0; }
Add "use RAII classes" sample
// Use RAII classes #include <map> #include <memory> #include <string> #include <vector> int main() { std::vector<int> vec = {1, 2, 3, 4, 5}; std::map<std::string, int> map = {{"Foo", 10}, {"Bar", 20}}; std::string str = "Some text"; std::unique_ptr<int> ptr1 = std::make_unique<int>(8); std::shared_ptr<int> ptr2 = std::make_shared<int>(16); } // Avoid manual memory management by using classes that implement // RAII. // // Every object created on [10-14] will internally manage some // dynamically allocated memory (allocated with the `new` keyword). // They are all, however, implemented such that they deallocate that // memory when they are destroyed (that is, when they go out of // scope). This practice is known as RAII. // // The user of these classes does not need to perform manual memory // management, reducing the risk of memory leaks and other bugs. In // fact, the use of `new` and `delete` can be avoided entirely by // using these RAII types. // // Likewise, it is good practice to [ensure your own classes also // implement the RAII idiom](/common-tasks/classes/encapsulate-memory-management.html).
Use the DFS to solve the problem.
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode * flipTree(TreeNode *root) { TreeNode* new_node = root; if (!root || !root->left) return root; new_node = flipTree(root->left); root->left->left = root->right; root->left->right = root; root->right = root->left = nullptr; return new_node; } TreeNode* upsideDownBinaryTree(TreeNode* root) { return flipTree(root); } };
Delete duplicate nodes from sorted list
/* * Problem: Delete duplicate-value nodes from a sorted linked list * Author: Anirudha Bose <ani07nov@gmail.com> Remove all duplicate elements from a sorted linked list Node is defined as struct Node { int data; struct Node *next; } */ Node* RemoveDuplicates(Node *head) { if(head == NULL || head->next == NULL) return head; Node *list = new Node; list = head; while(list->next != NULL) { if(list->data == list->next->data) list->next = list->next->next; else list = list->next; } return head; }
Mark an external variable external.
//----------------------------------------------------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //----------------------------------------------------------------------- // when linking with the object file generated from this file, calling // aborts() will not abort the program, but simply resume // operation. while usually useless, this is used in the test to // generate the output of a triggered assertion without aborting the // program. we do this, since we sometimes want to test that some code // actually generates an assertion, which would otherwise be // impossible #include <base/logstream.h> namespace deal_II_exceptions { namespace internals { unsigned int n_treated_exceptions; } } extern "C" void abort() #ifdef DEAL_II_ABORT_NOTHROW_EXCEPTION throw () #endif { deallog << "Abort!!!" << std::endl; deal_II_exceptions::internals::n_treated_exceptions = 0; }
//----------------------------------------------------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //----------------------------------------------------------------------- // when linking with the object file generated from this file, calling // aborts() will not abort the program, but simply resume // operation. while usually useless, this is used in the test to // generate the output of a triggered assertion without aborting the // program. we do this, since we sometimes want to test that some code // actually generates an assertion, which would otherwise be // impossible #include <base/logstream.h> namespace deal_II_exceptions { namespace internals { extern unsigned int n_treated_exceptions; } } extern "C" void abort() #ifdef DEAL_II_ABORT_NOTHROW_EXCEPTION throw () #endif { deallog << "Abort!!!" << std::endl; deal_II_exceptions::internals::n_treated_exceptions = 0; }
Add tests (copy constructor, virtual destructor)
#define BOOST_TEST_MODULE test_types #include <type_traits> #include <boost/test/included/unit_test.hpp> #include <boost/test/test_case_template.hpp> #include <boost/mpl/list.hpp> #include "variable.hxx" #include "boolean.hxx" #include "function.hxx" typedef boost::mpl::list<variable,boolean,function> types; BOOST_AUTO_TEST_SUITE(test_types) BOOST_AUTO_TEST_CASE_TEMPLATE(default_constructor, T, types) { BOOST_CHECK(std::is_default_constructible<T>::value); } BOOST_AUTO_TEST_CASE_TEMPLATE(destructible, T, types) { BOOST_CHECK(std::is_destructible<T>::value); } BOOST_AUTO_TEST_CASE_TEMPLATE(assignable, T, types) { // copy assignable: operator=(const Type& other) BOOST_CHECK(std::is_copy_assignable<T>::value); // above implies move assignable (don't understand exactly) BOOST_CHECK(std::is_move_assignable<T>::value); } BOOST_AUTO_TEST_SUITE_END()
#define BOOST_TEST_MODULE test_types #include <type_traits> #include <boost/test/included/unit_test.hpp> #include <boost/test/test_case_template.hpp> #include <boost/mpl/list.hpp> #include "variable.hxx" #include "boolean.hxx" #include "function.hxx" typedef boost::mpl::list<variable,boolean,function> types; BOOST_AUTO_TEST_SUITE(test_types) BOOST_AUTO_TEST_CASE_TEMPLATE(default_constructible, T, types) { BOOST_CHECK(std::is_default_constructible<T>::value); } BOOST_AUTO_TEST_CASE_TEMPLATE(copy_constructible, T, types) { BOOST_CHECK(std::is_copy_constructible<T>::value); } BOOST_AUTO_TEST_CASE_TEMPLATE(move_constructible, T, types) { BOOST_CHECK(std::is_move_constructible<T>::value); } BOOST_AUTO_TEST_CASE_TEMPLATE(destructible, T, types) { BOOST_CHECK(std::is_destructible<T>::value); } BOOST_AUTO_TEST_CASE_TEMPLATE(has_virtual_destructor, T, types) { BOOST_CHECK(std::has_virtual_destructor<T>::value); } BOOST_AUTO_TEST_CASE_TEMPLATE(assignable, T, types) { // copy assignable: operator=(const Type& other) BOOST_CHECK(std::is_copy_assignable<T>::value); // above implies move assignable (don't understand exactly) BOOST_CHECK(std::is_move_assignable<T>::value); } BOOST_AUTO_TEST_SUITE_END()
Insert node at tail (cpp)
/* Insert Node at the end of a linked list head pointer input could be NULL as well for empty list Node is defined as struct Node { int data; struct Node *next; } */ Node* Insert(Node *head,int data) { // Complete this method Node *newNode = (Node *)malloc(sizeof(Node)); newNode->data = data; if (!head) { return newNode; } Node *lastNode = NULL; Node *node = head; while (node) { lastNode = node; node = node->next; } lastNode->next = newNode; return head; }
Add mix test for normal_lccdf
#include <test/unit/math/test_ad.hpp> #include <limits> TEST(mathMixScalFun, lccdf_derivatives) { auto f = [](const double mu, const double sigma) { return [=](const auto& y) { return stan::math::normal_lccdf(y, mu, sigma); }; }; stan::test::expect_ad(f(0.0, 1.0), -50.0); stan::test::expect_ad(f(0.0, 1.0), -20.0 * stan::math::SQRT_TWO); stan::test::expect_ad(f(0.0, 1.0), -5.5); stan::test::expect_ad(f(0.0, 1.0), 0.0); stan::test::expect_ad(f(0.0, 1.0), 0.15); stan::test::expect_ad(f(0.0, 1.0), 1.14); stan::test::expect_ad(f(0.0, 1.0), 3.00); stan::test::expect_ad(f(0.0, 1.0), 10.00); stan::test::expect_ad(f(-1.0, 2.0), 1.50); stan::test::expect_ad(f(2.0, 1.0), 0.50); // thid order autodiff tests can fail at borders of piecewise function stan::test::ad_tolerances tols; tols.grad_hessian_grad_hessian_ = 1e1; stan::test::expect_ad(tols, f(0.0, 1.0), 0.1 * stan::math::SQRT_TWO); }
Fix compile errors on win32, update Qt submodule to fix compile errors there
#include <bts/blockchain/address.hpp> #include <bts/blockchain/pts_address.hpp> #include <bts/blockchain/types.hpp> #include <bts/utilities/key_conversion.hpp> #include <fc/crypto/elliptic.hpp> #include <fc/io/json.hpp> #include <fc/reflect/variant.hpp> #include <fc/filesystem.hpp> #include <fc/variant_object.hpp> #include <fc/exception/exception.hpp> #include <iostream> using namespace bts::blockchain; int main( int argc, char** argv ) { if( argc == 2 ) { fc::ecc::private_key k; try{ auto key = bts::blockchain::public_key_type(std::string(argv[1])); auto obj = fc::mutable_variant_object(); obj["public_key"] = public_key_type(key); obj["native_address"] = bts::blockchain::address(key); obj["pts_address"] = bts::blockchain::pts_address(key); std::cout << fc::json::to_pretty_string(obj); return 0; } catch (fc::exception e) { std::cout << e.to_detail_string(); } } return -1; }
#include <bts/blockchain/address.hpp> #include <bts/blockchain/pts_address.hpp> #include <bts/blockchain/types.hpp> #include <bts/utilities/key_conversion.hpp> #include <fc/crypto/elliptic.hpp> #include <fc/io/json.hpp> #include <fc/reflect/variant.hpp> #include <fc/filesystem.hpp> #include <fc/variant_object.hpp> #include <fc/exception/exception.hpp> #include <iostream> using namespace bts::blockchain; int main( int argc, char** argv ) { if( argc == 2 ) { try { bts::blockchain::public_key_type key(argv[1]); fc::mutable_variant_object obj; obj["public_key"] = key; obj["native_address"] = bts::blockchain::address((fc::ecc::public_key_data)key); obj["pts_address"] = bts::blockchain::pts_address((fc::ecc::public_key)key); std::cout << fc::json::to_pretty_string(obj); return 0; } catch (fc::exception e) { std::cout << e.to_detail_string(); } } return -1; }
Update input keys in game, for Floating Options
///////////////////////////////////////// // // OpenLieroX // // code under LGPL, based on JasonBs work, // enhanced by Dark Charlie and Albert Zeyer // // ///////////////////////////////////////// // Floating options window file // Created 24/9/08 // Karel Petranek
///////////////////////////////////////// // // OpenLieroX // // code under LGPL, based on JasonBs work, // enhanced by Dark Charlie and Albert Zeyer // // ///////////////////////////////////////// // Floating options window file // Created 24/9/08 // Karel Petranek #include "Options.h" #include "CClient.h" void UpdateGameInputs() { // Setup the controls cClient->getWorm(0)->SetupInputs( tLXOptions->sPlayerControls[0] ); // TODO: setup also more viewports if(cClient->getNumWorms() >= 2) cClient->getWorm(1)->SetupInputs( tLXOptions->sPlayerControls[1] ); cClient->getViewports()[0].setupInputs( tLXOptions->sPlayerControls[0] ); cClient->getViewports()[1].setupInputs( tLXOptions->sPlayerControls[1] ); }