Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add regression test for FixedpointCoordinate
#include <osrm/coordinate.hpp> #include <boost/test/unit_test.hpp> // Regression test for bug captured in #1347 BOOST_AUTO_TEST_CASE(regression_test_1347) { FixedPointCoordinate u(10 * COORDINATE_PRECISION, -100 * COORDINATE_PRECISION); FixedPointCoordinate v(10.001 * COORDINATE_PRECISION, -100.002 * COORDINATE_PRECISION); FixedPointCoordinate q(10.002 * COORDINATE_PRECISION, -100.001 * COORDINATE_PRECISION); float d1 = FixedPointCoordinate::ComputePerpendicularDistance(u, v, q); float ratio; FixedPointCoordinate nearest_location; float d2 = FixedPointCoordinate::ComputePerpendicularDistance(u, v, q, nearest_location, ratio); BOOST_CHECK_LE(std::abs(d1 - d2), 0.01); }
Add solution to first problem
#include <iostream> using namespace std; class BankAccount { char clientName[23]; char id[15]; double account; public: BankAccount(const char _clientName[], const char _id[], double _account) { strcpy(clientName, _clientName); strcpy(id, _id); account = _account; } void print() { cout << "Name: " << clientName << '\n' << "Account ID: " << id << '\n' << "Account: " << account << '\n'; } void transfer(double amount) { account += amount; } void draw(double amount) { account -= amount; } }; int main() { BankAccount bankAccount("Ivan", "1", 2000); bankAccount.print(); bankAccount.transfer(300); bankAccount.print(); bankAccount.draw(500); bankAccount.print(); return 0; }
Insert useful script for windows computers, standard input output.
#include <iostream> #include <stdio.h> using namespace std; int main (){ freopen("data.in", "r", stdin); freopen("data.out", "w", stdout); return 0; }
Add output test for write under reader lock
// RUN: %clangxx_tsan -O1 %s -o %t && %t 2>&1 | FileCheck %s #include <pthread.h> #include <unistd.h> pthread_rwlock_t rwlock; int GLOB; void *Thread1(void *p) { (void)p; pthread_rwlock_rdlock(&rwlock); // Write under reader lock. usleep(100); GLOB++; pthread_rwlock_unlock(&rwlock); return 0; } int main(int argc, char *argv[]) { pthread_rwlock_init(&rwlock, NULL); pthread_rwlock_rdlock(&rwlock); pthread_t t; pthread_create(&t, 0, Thread1, 0); volatile int x = GLOB; (void)x; pthread_rwlock_unlock(&rwlock); pthread_join(t, 0); pthread_rwlock_destroy(&rwlock); return 0; } // CHECK: WARNING: ThreadSanitizer: data race // CHECK: Write of size 4 at {{.*}} by thread 1: // CHECK: #0 Thread1(void*) {{.*}}write_in_reader_lock.cc:13 // CHECK: Previous read of size 4 at {{.*}} by main thread: // CHECK: #0 main {{.*}}write_in_reader_lock.cc:23
Add basic inverted index implementation in C++
#include <fstream> #include <iostream> #include <map> #include <sstream> #include <string> #include <vector> bool is_whitespace(char c) { return c == ' ' || c == '\t' || c == '\n'; } void add_words(std::vector<std::string> &dest, const std::string &s) { char *begin, *end; char t; end = begin = (char*)s.c_str(); while (*begin != '\0') { while (!is_whitespace(*end) && *end != '\0') end++; if (*end == '\0') { dest.push_back(std::string(begin)); break; } t = *end; *end = '\0'; dest.push_back(std::string(begin)); *end = t; for (begin = ++end; is_whitespace(*begin); begin = ++end); } } void populate_iindex(std::map<std::string, std::map<std::string, int>> &iindex, const std::string &fname) { std::ifstream in(fname); if (!in) throw in.rdstate(); std::stringstream txt; txt << in.rdbuf(); in.close(); std::vector<std::string> words; add_words(words, txt.str()); for (auto &w : words) iindex[w][fname] += 1; } int main() { std::map<std::string, std::map<std::string, int>> iindex; std::vector<std::string> files = {"bloom.cc", "cache.go", "quicksort.c", "self-repl.py"}; for (auto &f : files) populate_iindex(iindex, f); std::string input; while (std::cin.good()) { std::cout << "Enter your search term: "; if (!std::getline(std::cin, input) || !iindex.count(input)) goto endloop; for (auto &it : iindex[input]) std::cout << it.first << ": " << it.second << "\n"; endloop: std::cout << "\n"; } return 0; }
Add test that uses likely intrinsic to iterate over a circlular domain!
#include <Halide.h> #include <stdio.h> using namespace Halide; int count = 0; int my_trace(void *user_context, const halide_trace_event *ev) { if (ev->event == halide_trace_load) { count++; } return 0; } int main(int argc, char **argv) { Func f; Var x, y; Func in; in(x, y) = x + y; in.compute_root(); // Set f to zero f(x, y) = 0; // Then iterate over a circle, adding in(x, y) to f. Expr t = cast<int>(ceil(sqrt(10*10 - y*y))); f(x, y) += select(x > -t && x < t, likely(in(x, y)), 0); in.trace_loads(); f.set_custom_trace(my_trace); f.realize(20, 20); int c = 0; for (int y = 0; y < 20; y++) { for (int x = 0; x < 20; x++) { if (x*x + y*y < 10*10) c++; } } if (count != c) { printf("Func 'in' should only have been loaded from at points " "within the circle x*x + y*y < 10*10. It was loaded %d " "times, but there are %d points within that circle\n", count, c); return -1; } return 0; }
Disable new flaky test. BUG=353039 TBR=dtseng
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" #include "testing/gtest/include/gtest/gtest.h" namespace extensions { class AutomationApiTest : public ExtensionApiTest { public: virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE { ExtensionApiTest::SetUpCommandLine(command_line); command_line->AppendSwitch(::switches::kEnableAutomationAPI); } virtual void SetUpInProcessBrowserTestFixture() OVERRIDE { ExtensionApiTest::SetUpInProcessBrowserTestFixture(); } }; IN_PROC_BROWSER_TEST_F(AutomationApiTest, SanityCheck) { ASSERT_TRUE(RunComponentExtensionTest("automation/sanity_check")) << message_; } } // namespace extensions
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" #include "testing/gtest/include/gtest/gtest.h" namespace extensions { class AutomationApiTest : public ExtensionApiTest { public: virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE { ExtensionApiTest::SetUpCommandLine(command_line); command_line->AppendSwitch(::switches::kEnableAutomationAPI); } virtual void SetUpInProcessBrowserTestFixture() OVERRIDE { ExtensionApiTest::SetUpInProcessBrowserTestFixture(); } }; // http://crbug.com/353039 IN_PROC_BROWSER_TEST_F(AutomationApiTest, DISABLED_SanityCheck) { ASSERT_TRUE(RunComponentExtensionTest("automation/sanity_check")) << message_; } } // namespace extensions
Add a chat websocket test.
#include <silicon/api.hh> #include <silicon/remote_api.hh> #include <silicon/websocketpp.hh> using websocketpp::connection_hdl; struct session { static session* instantiate(connection_hdl c) { auto it = sessions.find(c); if (it != sessions.end()) return &(it->second); else { std::unique_lock<std::mutex> l(sessions_mutex); return &(sessions[c]); } } static session* find(std::string n) { for (auto& it : sessions) if (it.second.nickname == n) return &it.second; return 0; } std::string nickname; private: static std::mutex sessions_mutex; static std::map<connection_hdl, session> sessions; }; std::mutex session::sessions_mutex; std::map<connection_hdl, session> session::sessions; int main(int argc, char* argv[]) { using namespace sl; // The remote client api accessible from this server. auto client_api = make_remote_api( @broadcast(@from, @text), @pm(@from, @text) ); // The type of a client to call the remote api. typedef ws_client<decltype(client_api)> client; // The list of client. typedef ws_clients<decltype(client_api)> clients; // The server api accessible by the client. auto server_api = make_api( // Set nickname. @nick(@nick) = [] (auto p, session* s, client& c) { while(session::find(p.nick)) p.nick += "_"; s->nickname = p.nick; return D(@nick = s->nickname); }, // Broadcast a message to all clients. @broadcast(@message) = [] (auto p, session* s, clients& cs) { cs | [&] (client& c) { c.broadcast(s->nickname, p.message); }; }, // Private message. @pm(@to, @message) = [] (auto p, session* s, clients& cs) { cs | [&] (client& c2, session* s2) { if (s2->nickname == p.to) c2.pm(s->nickname, p.message); }; } ); websocketpp_json_serve(server_api, client_api, atoi(argv[1])); }
Add a C++ solution to the closed loops problem.
#include <iostream> //Function to find the number of closed loops in a given number. int closed_loops(int n){ int counter = 0; while(n!=0){ int r = n%10; if ((r==6) || (r==9) || (r==0)) counter++; if (r==8) counter+=2; n=n/10; } return counter; } // Driver function. int main() { int num1 = 2876; int num2 = 7589; int num3 = 1075; std::cout << closed_loops(num1) << std::endl; std::cout << closed_loops(num2) << std::endl; std::cout << closed_loops(num3) << std::endl; }
Add test missed from r143234.
// RUN: %clang_cc1 -fsyntax-only -verify -std=c++11 %s namespace StdExample { constexpr int f(void *) { return 0; } constexpr int f(...) { return 1; } constexpr int g1() { return f(0); } constexpr int g2(int n) { return f(n); } constexpr int g3(int n) { return f(n*0); } namespace N { constexpr int c = 5; constexpr int h() { return c; } } constexpr int c = 0; constexpr int g4() { return N::h(); } // FIXME: constexpr calls aren't recognized as ICEs yet, just as foldable. #define JOIN2(a, b) a ## b #define JOIN(a, b) JOIN2(a, b) #define CHECK(n, m) using JOIN(A, __LINE__) = int[n]; using JOIN(A, __LINE__) = int[m]; CHECK(f(0), 0) CHECK(f('0'), 1) CHECK(g1(), 0) CHECK(g2(0), 1) CHECK(g2(1), 1) CHECK(g3(0), 1) CHECK(g3(1), 1) CHECK(N::h(), 5) CHECK(g4(), 5) }
Add Solution for Problem 016
// 016. 3Sum Closest /** * Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. * Return the sum of the three integers. You may assume that each input would have exactly one solution. * * For example, given array S = {-1 2 1 -4}, and target = 1. * * The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). * * Tags: Array, Two Pointers * * Author: Kuang Qin */ #include "stdafx.h" #include <algorithm> #include <vector> using namespace std; class Solution { public: int threeSumClosest(vector<int>& nums, int target) { int n = nums.size(); if (n < 3) { return 0; } // sort the array sort(nums.begin(), nums.end()); // let the result be the possible maximum int result = nums[n - 1] + nums[n - 2] + nums[n - 3]; if (result <= target) { return result; } // let the result be the possible minimum result = nums[0] + nums[1] + nums[2]; if (result >= target) { return result; } for (int i = 0; i < n - 2; i++) { // use two pointers, adjust sum by moving left or right pointer int left = i + 1, right = n - 1; while (left < right) { int sum = nums[left] + nums[right] + nums[i]; if (abs(sum - target) < abs(result - target)) { result = sum; } if (sum < target) { left++; // make sum larger while ((left < right) && (nums[left] == nums[left - 1])) // skip duplicates from left { left++; } } else if (sum > target) { right--; // make sum smaller while ((left < right) && (nums[right] == nums[right + 1])) // skip duplicates from right { right--; } } else // sum == target { return sum; } } } return result; } }; int _tmain(int argc, _TCHAR* argv[]) { vector<int> nums; int target = 1; // nums = {-1, 2, 1, -4} nums.push_back(-1); nums.push_back(2); nums.push_back(1); nums.push_back(-4); Solution mySolution; int result = mySolution.threeSumClosest(nums, target); return 0; }
Solve problem 26 in C++
// Copyright 2016 Mitchell Kember. Subject to the MIT License. // Project Euler: Problem 26 // Reciprocal cycles #include <vector> namespace problem_26 { long recurring_cycle_len(const long n) { long dividend = 10; std::vector<long> remainders; while (dividend > 0) { // Check if the next remainder has ocurred before. const long rem = dividend % n; const auto end = remainders.end(); const auto it = std::find(remainders.begin(), end, rem); if (it != end) { return std::distance(it, end); } remainders.push_back(rem); dividend = rem * 10; } return 0; } long solve() { long result = 1; long max_len = 0; for (long i = 1; i < 1000; ++i) { const long len = recurring_cycle_len(i); if (len > max_len) { result = i; max_len = len; } } return result; } } // namespace problem_26
Add Creator's first unit test: create_model_test
/* * bacteria-core, core for cellular automaton * Copyright (C) 2016 Pavel Dolgov * * See the LICENSE file for terms of use. */ #include <boost/test/unit_test.hpp> #include "CoreConstants.hpp" #include "CoreGlobals.hpp" #include "Creator.hpp" BOOST_AUTO_TEST_CASE (create_model_test) { ModelPtr model = Creator::createModel( MIN_WIDTH, MIN_HEIGHT, 1, 1 ); BOOST_REQUIRE(model->getWidth() == MIN_WIDTH); BOOST_REQUIRE(model->getHeight() == MIN_HEIGHT); BOOST_REQUIRE(model->getBacteriaNumber(0) == 1); }
Add missing file from last commit
#include "abstractfieldwidgetfactory.h" using namespace KPeople; AbstractFieldWidgetFactory::AbstractFieldWidgetFactory(QObject *parent): QObject(parent) { } AbstractFieldWidgetFactory::~AbstractFieldWidgetFactory() { }
Add example for paging view
// Copyright 2016 otris software AG // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <ews/ews.hpp> #include <ews/ews_test_support.hpp> #include <cstdlib> #include <exception> #include <iostream> #include <ostream> #include <string> int main() { int res = EXIT_SUCCESS; ews::set_up(); try { const auto env = ews::test::environment(); auto service = ews::service(env.server_uri, env.domain, env.username, env.password); // First create some draft message ews::distinguished_folder_id drafts = ews::standard_folder::drafts; for (int i = 0; i < 20; i++) { auto message = ews::message(); message.set_subject("This is an e-mail message for our paging view"); std::vector<ews::mailbox> recipients; recipients.push_back(ews::mailbox("donald.duck@duckburg.com")); message.set_to_recipients(recipients); auto item_id = service.create_item(message, ews::message_disposition::save_only); } // Now iterate over all items in the folder // Starting at the end with an offset of 10 // Returning a number of 5 items per iteration // Until no more items are returned ews::paging_view view(5, 10, ews::paging_base_point::end); while (true) { auto item_ids = service.find_item(drafts, view); if (item_ids.empty()) { std::cout << "No more messages found!\n"; break; } for (const auto& id : item_ids) { auto msg = service.get_message(id); std::cout << msg.get_subject() << std::endl; } view.advance(); } } catch (std::exception& exc) { std::cout << exc.what() << std::endl; res = EXIT_FAILURE; } ews::tear_down(); return res; } // vim:et ts=4 sw=4
Add test for the last chapter of our C++ exception handling odyssey. llvmg++ now fully supports all C++ exception handling functionality.
#include <stdio.h> static unsigned NumAs = 0; struct A { unsigned ANum; A() : ANum(NumAs++) { printf("Created A #%d\n", ANum); } A(const A &a) : ANum(NumAs++) { printf("Copy Created A #%d\n", ANum); } ~A() { printf("Destroyed A #%d\n", ANum); } }; static bool ShouldThrow = false; int throws() try { if (ShouldThrow) throw 7; return 123; } catch (...) { printf("'throws' threw an exception: rethrowing!\n"); throw; } struct B { A a0, a1, a2; int i; A a3, a4; B(); ~B() { printf("B destructor!\n"); } }; B::B() try : i(throws()) { printf("In B constructor!\n"); } catch (int i) { printf("In B catch block with int %d: auto rethrowing\n", i); } int main() { { B b; // Shouldn't throw. } try { ShouldThrow = true; B b; } catch (...) { printf("Caught exception!\n"); } }
Add hello world example program
#include <agency/execution_policy.hpp> #include <iostream> void hello(agency::sequential_agent& self) { std::cout << "Hello, world from agent " << self.index() << std::endl; } int main() { // create 10 sequential_agents to execute the hello() task in bulk agency::bulk_invoke(agency::seq(10), hello); return 0; }
Add a test for stack unwinding in new and delete.
// RUN: %clangxx_asan -O0 %s -o %t && not %t 2>&1 | FileCheck %s --check-prefix=CHECK-%os --check-prefix=CHECK // RUN: %clangxx_asan -O1 %s -o %t && not %t 2>&1 | FileCheck %s --check-prefix=CHECK-%os --check-prefix=CHECK // RUN: %clangxx_asan -O2 %s -o %t && not %t 2>&1 | FileCheck %s --check-prefix=CHECK-%os --check-prefix=CHECK // RUN: %clangxx_asan -O3 %s -o %t && not %t 2>&1 | FileCheck %s --check-prefix=CHECK-%os --check-prefix=CHECK #include <stdlib.h> int main() { char * volatile x = new char[10]; delete[] x; return x[5]; // CHECK: {{.*ERROR: AddressSanitizer: heap-use-after-free on address}} // CHECK: {{0x.* at pc 0x.* bp 0x.* sp 0x.*}} // CHECK: {{READ of size 1 at 0x.* thread T0}} // CHECK: {{ #0 0x.* in main .*use-after-delete.cc:10}} // CHECK: {{0x.* is located 5 bytes inside of 10-byte region .0x.*,0x.*}} // CHECK: {{freed by thread T0 here:}} // CHECK-Linux: {{ #0 0x.* in operator delete\[\]}} // CHECK-Linux: {{ #1 0x.* in main .*use-after-delete.cc:9}} // CHECK: {{previously allocated by thread T0 here:}} // CHECK-Linux: {{ #0 0x.* in operator new\[\]}} // CHECK-Linux: {{ #1 0x.* in main .*use-after-delete.cc:8}} // CHECK: Shadow byte legend (one shadow byte represents 8 application bytes): // CHECK: Global redzone: // CHECK: ASan internal: }
Test for atomic handling in MSan.
// RUN: %clangxx_msan -m64 -O0 %s -o %t && %t int main(void) { int i; __sync_lock_test_and_set(&i, 0); return i; }
Add more unix domain socket experimental program.
#include <iostream> #include <thread> #include <glog/logging.h> #include "base/concurrent/wait_group.h" #include "base/strings/string_piece.h" #include "net/socket/socket_factory.h" #include "net/socket/unix_domain_client_socket.h" #include "net/socket/unix_domain_server_socket.h" using namespace std; const char* const UNIX_DOMAIN_SOCKET_PATH = "/tmp/uds-test.sock"; void run_server(concurrent::WaitGroup* wg) { net::UnixDomainServerSocket sock = net::SocketFactory::instance()->make_unix_domain_server_socket(); CHECK(sock.valid()); (void)unlink(UNIX_DOMAIN_SOCKET_PATH); CHECK(sock.bind(UNIX_DOMAIN_SOCKET_PATH)); CHECK(sock.listen(5)); wg->done(); net::UnixDomainSocket accepted = sock.accept(); CHECK(accepted.valid()); CHECK(sock.close()); char buf[7]; CHECK(accepted.read_exactly(buf, 7)); cout << "server: " << strings::StringPiece(buf, 7) << endl; } void run_client() { net::UnixDomainClientSocket sock = net::SocketFactory::instance()->make_unix_domain_client_socket(); CHECK(sock.valid()); CHECK(sock.connect(UNIX_DOMAIN_SOCKET_PATH)); cout << "client: foobar" << endl; sock.write("foobar", 7); } int main() { concurrent::WaitGroup wg; wg.add(1); thread server_thread(run_server, &wg); wg.wait_until_done(); thread client_thread(run_client); client_thread.join(); server_thread.join(); }
Fix CAN Interrupt Test (MBED_31)
#include "mbed.h" Ticker ticker; DigitalOut led1(LED1); DigitalOut led2(LED2); CAN can1(p9, p10); CAN can2(p30, p29); char counter = 0; void printmsg(char *title, CANMessage *msg) { printf("%s [%03X]", title, msg->id); for(char i = 0; i < msg->len; i++) { printf(" %02X", msg->data[i]); } printf("\n"); } void send() { printf("send()\n"); CANMessage msg = CANMessage(1337, &counter, 1); if(can1.write(msg)) { printmsg("Tx message:", &msg); counter++; } led1 = !led1; } void read() { CANMessage msg; printf("rx()\n"); if(can1.read(msg)) { printmsg("Rx message:", &msg); led2 = !led2; } } int main() { printf("main()\n"); ticker.attach(&send, 1); can1.attach(&read); while(1) { printf("loop()\n"); wait(1); } }
#include "mbed.h" Ticker ticker; DigitalOut led1(LED1); DigitalOut led2(LED2); CAN can1(p9, p10); CAN can2(p30, p29); char counter = 0; void printmsg(char *title, CANMessage *msg) { printf("%s [%03X]", title, msg->id); for(char i = 0; i < msg->len; i++) { printf(" %02X", msg->data[i]); } printf("\n"); } void send() { printf("send()\n"); CANMessage msg = CANMessage(1337, &counter, 1); if(can1.write(msg)) { printmsg("Tx message:", &msg); counter++; } led1 = !led1; } void read() { CANMessage msg; printf("rx()\n"); if(can2.read(msg)) { printmsg("Rx message:", &msg); led2 = !led2; } } int main() { printf("main()\n"); ticker.attach(&send, 1); can2.attach(&read); while(1) { printf("loop()\n"); wait(1); } }
Add test for non-contiguous gpu copy
#include <Halide.h> #include <stdio.h> using namespace Halide; int main(int argc, char **argv) { Var x, y; Image<int> full = lambda(x, y, x * y).realize(800, 600); buffer_t cropped = {0}; cropped.host = (uint8_t *)(&full(40, 80)); cropped.host_dirty = true; cropped.elem_size = 4; cropped.min[0] = 40; cropped.min[1] = 80; cropped.extent[0] = 128; cropped.extent[1] = 96; cropped.stride[0] = full.stride(0); cropped.stride[1] = full.stride(1); Buffer out(Int(32), &cropped); Func f; f(x, y) = x*y + 1; f.gpu_tile(x, y, 16, 16); f.realize(out); // Put something secret outside of the region that the func is // supposed to write to. full(500, 80) = 1234567; // Copy back the output. out.copy_to_host(); if (full(500, 80) != 1234567) { printf("Output value outside of the range evaluated was clobbered by copy-back from gpu!\n"); return -1; } printf("Success!\n"); return 0; }
Disable FeedbackApiTest.Basic on Win & Linux
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/message_loop/message_loop.h" #include "chrome/browser/extensions/api/feedback_private/feedback_private_api.h" #include "chrome/browser/extensions/extension_apitest.h" namespace extensions { class FeedbackApiTest: public ExtensionApiTest { public: FeedbackApiTest() {} virtual ~FeedbackApiTest() {} }; IN_PROC_BROWSER_TEST_F(FeedbackApiTest, Basic) { EXPECT_TRUE(RunExtensionTest("feedback_private/basic")) << message_; } } // namespace extensions
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/message_loop/message_loop.h" #include "chrome/browser/extensions/api/feedback_private/feedback_private_api.h" #include "chrome/browser/extensions/extension_apitest.h" namespace extensions { class FeedbackApiTest: public ExtensionApiTest { public: FeedbackApiTest() {} virtual ~FeedbackApiTest() {} }; // Fails on Linux/Win. http://crbug.com/408917 #if defined(OS_WIN) || defined(OS_LINUX) #define MAYBE_Basic DISABLED_Basic #else #define MAYBE_Basic Basic #endif IN_PROC_BROWSER_TEST_F(FeedbackApiTest, MAYBE_Basic) { EXPECT_TRUE(RunExtensionTest("feedback_private/basic")) << message_; } } // namespace extensions
Add useful algorithm to bin in c++.
#include <bits/stdc++.h> using namespace std; void toBin(int x){ for (int i =31; i>=0; --i){ cout << ((x&(1LL<<i))!=0); } } int main (){ toBin(10); return 0; }
Add pseudocode for top level file
#include hand_XXX_driver.h // No memory allocation outside init main{ /// This function will do all the necessary work to set up the hand: /// - Scan bus for slaves /// - If there's a hand of type XXX then /// - initialize hand [p0-m1] /// - configure hand /// Configurations for the hand will be read from a file, these will include: /// - Ethernet port to use /// - internal tuning and over-tension potection parameters /// - desired operation mode (PWM or tendon tension) int success = initialize_hand_XXX(); /// buffer where the commands (PWM or torque) to the robot motors will be written unsigned char *command_buffer; /// buffer where the status (sensor data) from the robot can be read from unsigned char *status_buffer; /// From here while(true) { /// This will use the command_buffer data to build an etherCAT frame and send it to the hand /// The etherCAT frame comes back with sensor data from the hand that can be read from the status_buffer send_and_receive_from_hand_XXX(command_buffer, status_buffer); /// Do stuff with the status data (compute next commands) /// Wait until time for next frame send_and_receive_from_hand_XXX(command_buffer, status_buffer); /// Waiting until next iteration } }
Add Chapter 3, exercise 2 (using stack in stack approach)
// 3.2 - design a stack with push, pop, peek and min, all in O(1) // improvement: only push to aux stack if new value is <= current minimum; only // pop from aux stack if value being popped is == current minimum - saves space // if many values are not the minimum. // alternative: define data structure to hold int plus the current minimum, // make stack of this data structure and just return the current minimum stored // in the top element if asked #include<stdexcept> #include<iostream> using namespace std; struct Node { Node* next; int val; Node(int v) :next(0), val(v) { } }; struct Stack { Node* top; void push(int v) { Node* n = new Node(v); n->next = top; top = n; } int pop() { if (top==0) throw exception("can't pop empty stack"); int v = top->val; Node* n = top->next; delete(top); top = n; return v; } int peek() { if (!top) throw exception("can't peek on empty stack"); return top->val; } Stack() :top(0) { } }; class Min_stack : public Stack { Stack min_stack; public: Min_stack() :Stack(), min_stack() { } void push(int v) { if (top==0 || v < min_stack.peek()) min_stack.push(v); else min_stack.push(min_stack.peek()); Stack::push(v); // must be last, otherwise top!=0 } int pop() { min_stack.pop(); return Stack::pop(); } int min() { return min_stack.peek(); } }; int main() try { Min_stack ms; //ms.peek(); // throws //ms.pop(); // throws ms.push(1); ms.push(2); cout << "Minimum in {1,2}: " << ms.min() << '\n'; ms.push(3); ms.push(-1); ms.push(4); ms.push(5); cout << "Minimum in {1,2,3,-1,4,5}: " << ms.min() << '\n'; cout << "\nPopping all:\n"; while (ms.top) cout << ms.pop() << '\n'; ms.pop(); // throws } catch (exception& e) { cerr << "Exception: " << e.what() << '\n'; } catch (...) { cerr << "Exception\n"; }
Add raw string literal versus C preprocessor test, suggested by James Dennett.
// RUN: %clang_cc1 -std=c++11 -fsyntax-only %s // RUN: %clang_cc1 -std=c++98 -fsyntax-only -verify %s // expected-error@8 {{in c++98 only}} #if 0 R"( #else #error in c++98 only)" #endif
Convert time in millisecs to hh:mm:ss
#include <stdio.h> using namespace std; // converts the time in millis to // human readable format in hh:mm:ss // I/P: 901000 // O/P: 00:15:01 void convertTime(int timeInMillis) { // convert millisecs into secs int secs = timeInMillis/1000; // convert secs into minutes and round off if it reaches 60 int mins = secs/60 % 60; // convert secs into hrs and round off if it reaches 24 int hrs = (secs/(60*60)) % 24; // print the time in the format hh:mm:ss printf("%02d:%02d:%02d\n", hrs, mins, secs%60); } int main() { convertTime(901000); convertTime(3601000); return 0; }
Add Solution for 143 Reorder List
// 143. Reorder List /** * Given a singly linked list L: L0->L1->...->Ln-1->Ln, * reorder it to: L0->Ln->L1->Ln-1->L2->Ln-2->... * * You must do this in-place without altering the nodes' values. * * For example, * Given {1,2,3,4}, reorder it to {1,4,2,3}. * * Tags: Linked List * * Author: Kuang Qin */ #include <iostream> using namespace std; /** * Definition for singly-linked list. */ struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} ListNode(int x, ListNode *p) : val(x), next(p) {} }; class Solution { public: void reorderList(ListNode* head) { if (head == NULL || head->next == NULL) { return; } // divide the list into two parts ListNode *slow = head, *fast = head->next; while (fast != NULL && fast->next != NULL) { slow = slow->next; fast = fast->next->next; } // reverse the second part of the list from slow->next ListNode *curr = slow->next, *prev = NULL; while (curr != NULL) { ListNode *next = curr->next; curr->next = prev; prev = curr; curr = next; } // connect two lists slow->next = NULL; while (head != NULL && prev != NULL) { ListNode *next = prev->next; prev->next = head->next; head->next = prev; head = prev->next; prev = next; } return; } }; int main() { ListNode node5(5), node4(4, &node5), node3(3, &node4), node2(2, &node3), node1(1, &node2); Solution sol; ListNode *head = &node1; sol.reorderList(head); for (ListNode *p = head; p != NULL; p = p->next) { cout << p->val << " "; } cout << endl; cin.get(); return 0; }
Set up PCH for MSVC.NET
/* GNE - Game Networking Engine, a portable multithreaded networking library. * Copyright (C) 2001 Jason Winnebeck (gillius@mail.rit.edu) * Project website: http://www.rit.edu/~jpw9607/ * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ //this CPP file only for precompiled header #include "../include/gnelib/gneintern.h"
Add unit tests for typedefs.
/* * Copyright (c) 2016 Kartik Kumar, Dinamica Srl (me@kartikkumar.com) * Distributed under the MIT License. * See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT */ #include <map> #include <typeinfo> #include <vector> #include <catch.hpp> #include "rvdsim/typedefs.hpp" namespace rvdsim { namespace tests { TEST_CASE( "Test typedefs", "[typedef]" ) { REQUIRE( typeid( Real ) == typeid( double ) ); REQUIRE( typeid( Vector3 ) == typeid( std::vector< Real > ) ); REQUIRE( typeid( Vector6 ) == typeid( std::vector< Real > ) ); REQUIRE( typeid( StateHistory ) == typeid( std::map< Real, Vector6 > ) ); REQUIRE( typeid( ThrustHistory ) == typeid( std::map< Real, Vector3 > ) ); } } // namespace tests } // namespace rvdsim
Add unit tests for ygo::deck::Format
#include <boost/test/unit_test.hpp> #include <ygo/deck/Format.h> #include <ygo/deck/DB.h> struct Format_Fixture { Format_Fixture() { ygo::deck::DB::get().path("test/card.db"); } }; BOOST_FIXTURE_TEST_SUITE(Format, Format_Fixture) BOOST_AUTO_TEST_CASE(Create) { auto formatDates = ygo::deck::Format::formatDates(); for (auto&& f : formatDates) { ygo::deck::Format formatA(ygo::data::Format::ADVANCED, f); BOOST_CHECK_EQUAL(formatA.formatDate(), f); BOOST_CHECK(formatA.format() == ygo::data::Format::ADVANCED); ygo::deck::Format formatT(ygo::data::Format::TRADITIONAL, f); BOOST_CHECK_EQUAL(formatT.formatDate(), f); BOOST_CHECK(formatT.format() == ygo::data::Format::TRADITIONAL); } } BOOST_AUTO_TEST_CASE(Invalid) { try { ygo::deck::Format f(ygo::data::Format::ADVANCED, "InvalidFormat"); BOOST_CHECK_EQUAL(0, 1); } catch (std::runtime_error& e) { BOOST_CHECK_EQUAL(1, 1); } } BOOST_AUTO_TEST_CASE(Limits) { ygo::deck::Format formatA(ygo::data::Format::ADVANCED, "April 2004"); ygo::deck::Format formatT(ygo::data::Format::TRADITIONAL, "April 2004"); BOOST_CHECK_EQUAL(0, formatA.cardCount("Change of Heart")); BOOST_CHECK_EQUAL(1, formatT.cardCount("Change of Heart")); BOOST_CHECK_EQUAL(1, formatA.cardCount("Mage Power")); BOOST_CHECK_EQUAL(1, formatT.cardCount("Mage Power")); BOOST_CHECK_EQUAL(2, formatA.cardCount("Creature Swap")); BOOST_CHECK_EQUAL(2, formatT.cardCount("Creature Swap")); BOOST_CHECK_EQUAL(3, formatA.cardCount("Kuriboh")); BOOST_CHECK_EQUAL(3, formatT.cardCount("Kuriboh")); } BOOST_AUTO_TEST_SUITE_END()
Add test for last commit
// RUN: clang-cc -fsyntax-only -verify %s template<typename T> struct X0 { void f(); template<typename U> void g(U); struct Nested { }; static T member; }; int &use_X0_int(X0<int> x0i, // expected-note{{implicit instantiation first required here}} int i) { x0i.f(); // expected-note{{implicit instantiation first required here}} x0i.g(i); // expected-note{{implicit instantiation first required here}} X0<int>::Nested nested; // expected-note{{implicit instantiation first required here}} return X0<int>::member; // expected-note{{implicit instantiation first required here}} } template<> void X0<int>::f() { // expected-error{{after instantiation}} } template<> template<> void X0<int>::g(int) { // expected-error{{after instantiation}} } template<> struct X0<int>::Nested { }; // expected-error{{after instantiation}} template<> int X0<int>::member = 17; // expected-error{{after instantiation}} template<> struct X0<int> { }; // expected-error{{after instantiation}} // Example from the standard template<class T> class Array { /* ... */ }; template<class T> void sort(Array<T>& v) { /* ... */ } struct String {}; void f(Array<String>& v) { sort(v); // expected-note{{required}} // use primary template // sort(Array<T>&), T is String } template<> void sort<String>(Array<String>& v); // // expected-error{{after instantiation}} template<> void sort<>(Array<char*>& v); // OK: sort<char*> not yet used
Add Windows test for handle_segv and SetUnhandledExceptionFilter
// RUN: %clang_cl_asan -O0 %s -Fe%t // RUN: env ASAN_OPTIONS=handle_segv=0 %run %t 2>&1 | FileCheck %s --check-prefix=USER // RUN: env ASAN_OPTIONS=handle_segv=1 not %run %t 2>&1 | FileCheck %s --check-prefix=ASAN // Test the default. // RUN: not %run %t 2>&1 | FileCheck %s --check-prefix=ASAN // This test exits zero when its unhandled exception filter is set. ASan should // not disturb it when handle_segv=0. // USER: in main // USER: in SEHHandler // ASAN: in main // ASAN: ERROR: AddressSanitizer: access-violation #include <windows.h> #include <stdio.h> static long WINAPI SEHHandler(EXCEPTION_POINTERS *info) { DWORD exception_code = info->ExceptionRecord->ExceptionCode; if (exception_code == EXCEPTION_ACCESS_VIOLATION) { fprintf(stderr, "in SEHHandler\n"); fflush(stdout); TerminateProcess(GetCurrentProcess(), 0); } return EXCEPTION_CONTINUE_SEARCH; } int main() { SetUnhandledExceptionFilter(SEHHandler); fprintf(stderr, "in main\n"); volatile int *p = nullptr; *p = 42; }
Split Array into Consecutive Subsequences
class Solution { public: bool isPossible(vector<int>& nums) { int st=0; for(int i=1; i<nums.size(); i++){ if(nums[i]-nums[i-1]>1){ if(!work(nums,st,i-1)) return false; st = i; } } return work(nums,st,nums.size()-1); } bool work(vector<int>& nums, int f, int r){ vector<int> count(nums[r]-nums[f]+1,0); for(int i=f;i<=r;i++){ count[nums[i]-nums[f]]++; } vector<int> one(nums[r]-nums[f]+2,0), two(nums[r]-nums[f]+2,0), tot(nums[r]-nums[f]+2,0); for(int i=0;i<nums[r]-nums[f]+1;i++){ if(count[i]<one[i]+two[i]) return false; two[i+1]=one[i]; one[i+1]=max(0,count[i]-tot[i]); tot[i+1]=count[i]; } if(one[nums[r]-nums[f]+1]==0 & two[nums[r]-nums[f]+1]==0) return true; return false; } };
Add dynamic convex hull trick, stolen from niklasb
const ll is_query = -(1LL<<62); struct Line { ll m, b; mutable function<const Line*()> succ; bool operator<(const Line& rhs) const { if (rhs.b != is_query) return m < rhs.m; const Line* s = succ(); if (!s) return 0; ll x = rhs.m; return b - s->b < (s->m - m) * x; } }; struct HullDynamic : public multiset<Line> { // will maintain upper hull for maximum bool bad(iterator y) { auto z = next(y); if (y == begin()) { if (z == end()) return 0; return y->m == z->m && y->b <= z->b; } auto x = prev(y); if (z == end()) return y->m == x->m && y->b <= x->b; return (x->b - y->b)*(z->m - y->m) >= (y->b - z->b)*(y->m - x->m); } void insert_line(ll m, ll b) { auto y = insert({ m, b }); y->succ = [=] { return next(y) == end() ? 0 : &*next(y); }; if (bad(y)) { erase(y); return; } while (next(y) != end() && bad(next(y))) erase(next(y)); while (y != begin() && bad(prev(y))) erase(prev(y)); } ll eval(ll x) { auto l = *lower_bound((Line) { x, is_query }); return l.m * x + l.b; } };
Make a standard input/output socket module mostly for testing purposes.
#include "sockets.h" class StandardInputOutput : public Socket { public: StandardInputOutput(); unsigned int apiVersion() { return 3000; } std::string receive(); void sendData(const std::string& data); }; StandardInputOutput::StandardInputOutput() : connected(true) {} std::string StandardInputOutput::receive() { std::string recvLine; std::getline(std::cin, recvLine); return recvLine; } void StandardInputOutput::sendData(const std::string& data) { std::cout << data << std::endl; }
Add unit test for SVMOcas
#include <shogun/classifier/svm/SVMOcas.h> #include <shogun/features/DataGenerator.h> #include <shogun/features/DenseFeatures.h> #include <shogun/evaluation/ROCEvaluation.h> #include <gtest/gtest.h> #include <iostream> using namespace shogun; TEST(SVMOcasTest,train) { index_t num_samples = 100, dim = 10; float64_t mean_shift = 1.0; CMath::init_random(5); SGMatrix<float64_t> data = CDataGenerator::generate_mean_data(num_samples, dim, mean_shift); CDenseFeatures<float64_t> features(data); SGVector<index_t> train_idx(100), test_idx(100); SGVector<float64_t> labels(100); for (index_t i = 0, j = 0; i < data.num_cols; ++i) { if (i % 2 == 0) train_idx[j] = i; else test_idx[j++] = i; labels[i/2] = (i < 100) ? 1.0 : -1.0; } CDenseFeatures<float64_t>* train_feats = (CDenseFeatures<float64_t>*)features.copy_subset(train_idx); CDenseFeatures<float64_t>* test_feats = (CDenseFeatures<float64_t>*)features.copy_subset(test_idx); CBinaryLabels* ground_truth = new CBinaryLabels(labels); CSVMOcas* ocas = new CSVMOcas(1.0, train_feats, ground_truth); ocas->train(); CLabels* pred = ocas->apply(test_feats); CROCEvaluation roc; float64_t err = CMath::abs(roc.evaluate(pred, ground_truth)-0.7684); EXPECT_TRUE(err < 10E-12); SG_UNREF(ocas); SG_UNREF(train_feats); SG_UNREF(test_feats); }
Add simple c++ insert test
#include "skiplist.hh" #include <vector> #include <thread> #include <iostream> static unsigned int seed; void insert(Skiplist *s, int n) { for (int x=0; x < n; x++) { unsigned r = rand_r(&seed); int *v = (int *) skiplist_malloc(sizeof(int)); *v = r; Item *itm = newItem(v, sizeof(int)); Skiplist_Insert(s, itm); } } int main() { srand(time(NULL)); int i = 100; Skiplist *s = newSkiplist(); std::vector<std::thread> threads; for (int x=0; x < 8; x++) { threads.push_back(std::thread(&insert,s, 1000000)); } for (auto& th : threads) th.join(); exit(0); int count = 0; Node *p = s->head; while (p) { if (p->itm->l == 4) { count++; // std::cout<<"itm "<<count<<" - "<<*((int *)(p->itm->data))<<std::endl; } NodeRef r = Node_getNext(p, 0); p = r.ptr; } std::cout<<count<<std::endl; }
Return number of set bits if int is palindrome. Question commented inside.
/* Given a number, return the number of set bits of the number if binary representation of the number is a palindrome, else return ­1. Condition : You can’t use array or any other data structure. Eg . Input 37 Output ­1 Input 165 Output 4 */ #include <iostream> #include <string> #include <algorithm> using namespace std; int count_bits1(int a) { int ans = 0; for (int i = 0; i < 32; i++) { if (((a >> i) & 1) == 1) ans++; } return ans; } int length(int a) { int pos = 0; for (int i = 0; i < 32; i++) { if (((a >> i) & 1) == 1) pos = i; } return pos; } int main() { int input = 165; int no1 = count_bits1(input); int len = length(input); for (int i = 0; i <= len/2; i++) { //cout << "for i equal to " << i << " the bits are " << ((input >> i) & 1) << " " << ((input >> (len - i)) & 1) << endl; if (((input >> i) & 1) == ((input >> (len - i)) & 1)) ; else return -1; } return no1; }
Add a testcase for __ubsan_default_options() function.
// RUN: %clangxx -fsanitize=integer -fsanitize-recover=integer %s -o %t // RUN: not %t 2>&1 | FileCheck %s // __ubsan_default_options() doesn't work on Darwin. // XFAIL: darwin #include <stdint.h> extern "C" const char *__ubsan_default_options() { return "halt_on_error=1"; } int main() { (void)(uint64_t(10000000000000000000ull) + uint64_t(9000000000000000000ull)); // CHECK: ubsan_options.cc:[[@LINE-1]]:44: runtime error: unsigned integer overflow return 0; }
Remove Duplicates from Sorted Array II.
/** * Remove Duplicates from Sorted Array II * * cpselvis(cpselvis@gmail.com) * September 21th, 2016 */ #include<iostream> #include<vector> #include<unordered_map> using namespace std; class Solution { public: int removeDuplicates(vector<int>& nums) { unordered_map<int, int> umap; int ret = nums.size(); for (int i = 0; i < nums.size(); ) { if (umap[nums[i]] < 2) { umap[nums[i]] ++; i ++; } else { nums.erase(nums.begin() + i); ret --; } } return ret; } }; int main(int argc, char **argv) { Solution s; int nums[6] = {1, 1, 1, 2, 2, 3}; vector<int> vec(nums + 0, nums + 6); cout << s.removeDuplicates(vec) << endl; }
Test case for naming of conversion function template specializations
// RUN: %clang_cc1 -fsyntax-only -verify %s struct A { template <class T> operator T*(); }; template <class T> A::operator T*() { return 0; } template <> A::operator char*(){ return 0; } // specialization template A::operator void*(); // explicit instantiation int main() { A a; int *ip; ip = a.operator int*(); } // PR5742 namespace PR5742 { template <class T> struct A { }; template <class T> struct B { }; struct S { template <class T> operator T(); } s; void f() { s.operator A<A<int> >(); s.operator A<B<int> >(); s.operator A<B<A<int> > >(); } } // PR5762 class Foo { public: template <typename T> operator T(); template <typename T> T As() { return this->operator T(); } template <typename T> T As2() { return operator T(); } int AsInt() { return this->operator int(); } }; template float Foo::As(); template double Foo::As2(); // Partial ordering with conversion function templates. struct X0 { template<typename T> operator T*() { T x; x = 17; // expected-error{{read-only variable is not assignable}} } template<typename T> operator T*() const; // expected-note{{explicit instantiation refers here}} template<typename T> operator const T*() const { T x = T(); return x; // expected-error{{cannot initialize return object of type 'char const *' with an lvalue of type 'char'}} } }; template X0::operator const char*() const; // expected-note{{'X0::operator char const *<char>' requested here}} template X0::operator const int*(); // expected-note{{'X0::operator int const *<int const>' requested here}} template X0::operator float*() const; // expected-error{{explicit instantiation of undefined function template}} void test_X0(X0 x0, const X0 &x0c) { x0.operator const int*(); x0.operator float *(); x0c.operator const char*(); }
Debug log implementation to use the STM32 HAL UART implementation. Redirects (f)printf HAL_UART_Transmit using a UART_HandleTypeDef that must be provided as DEBUG_UART_HANDLE
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. 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 "tensorflow/lite/micro/debug_log.h" #include <stm32f4xx_hal.h> #include <stm32f4xx_hal_uart.h> #include <cstdio> #ifdef __GNUC__ #define PUTCHAR_PROTOTYPE int __io_putchar(int ch) #else #define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f) #endif /* __GNUC__ */ extern UART_HandleTypeDef DEBUG_UART_HANDLE; PUTCHAR_PROTOTYPE { HAL_UART_Transmit(&DEBUG_UART_HANDLE, (uint8_t *)&ch, 1, HAL_MAX_DELAY); return ch; } extern "C" void DebugLog(const char *s) { fprintf(stderr, "%s", s); }
Add empty chip::lowLevelInitialization() for STM32L4
/** * \file * \brief chip::lowLevelInitialization() implementation for STM32L4 * * \author Copyright (C) 2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "distortos/chip/lowLevelInitialization.hpp" namespace distortos { namespace chip { /*---------------------------------------------------------------------------------------------------------------------+ | global functions +---------------------------------------------------------------------------------------------------------------------*/ void lowLevelInitialization() { } } // namespace chip } // namespace distortos
Add benchmark for testing umat vs mat for optical flow
/* * optical_flow_mat_benchmark.cpp * * Created on: May 22, 2016 * Author: Cody W. Eilar <Cody.Eilar@Gmail.com> */ #include <celero/Celero.h> #include "../readers/video_file_reader.h" #include "../datatypes/image.h" #include "../optical_flow/motion_estimation.h" #include "../optical_flow/optical_flow.h" #include "../optical_flow/lk_flow.h" #include "../optical_flow/farneback_flow.h" #include "opencv2/core/utility.hpp" #include "opencv2/highgui.hpp" #include "opencv2/videoio.hpp" #include <opencv2/imgproc/imgproc.hpp> #include <string> CELERO_MAIN namespace oflow { const std::string filename{ "/Users/cody/Dropbox/CodyShared/PreProposal_AOLMEFall2015/" "ActivityClassifier/data/writing/Cropped/seg2.mov"}; BASELINE(OpticalFlowBenchmarks, NoGpuSupport, 3, 3) { std::shared_ptr<oflow::VideoFileReader> f( new oflow::VideoFileReader(filename)); oflow::MotionEstimation<oflow::VideoFileReader, cv::Mat> me(f); std::shared_ptr<oflow::FarneBackFlow> my_flow(new oflow::FarneBackFlow()); me.EstimateMotion(my_flow); } BENCHMARK(OpticalFlowBenchmarks, GpuSupport, 3, 3) { std::shared_ptr<oflow::VideoFileReader> f( new oflow::VideoFileReader(filename)); oflow::MotionEstimation<oflow::VideoFileReader, cv::UMat> me(f); std::shared_ptr<oflow::FarneBackFlow> my_flow(new oflow::FarneBackFlow()); me.EstimateMotion(my_flow); } }
Add author solution for problem
#include<iostream> #include<set> const int MAXN = 300042; int A[MAXN]; int main() { std::cin.tie(0); std::ios::sync_with_stdio(0); int n, q; std::cin >> n >> q; for(int i = 0; i < n; ++i) std::cin >> A[i]; std::set<int> break_points; for(int i = 1; i < n; ++i) { if(A[i] <= A[i - 1]) break_points.insert(i); } for(int i = 0; i < q; ++i) { char c; int x, y; std::cin >> c >> x >> y; if(c == '=') { A[x] = y; if(x > 0) { if(A[x] <= A[x - 1]) break_points.insert(x); else break_points.erase(x); } if(x < n - 1) { if(A[x + 1] <= A[x]) break_points.insert(x + 1); else break_points.erase(x + 1); } } else // ? { // [ x, y ) -> ( x, y ) auto it = break_points.upper_bound(x); std::cout << (it != break_points.end() && *it >= y) << '\n'; } } }
Comment enum matching assert to allow changes in Blink.
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Use this file to assert that *_list.h enums that are meant to do the bridge // from Blink are valid. #include "base/macros.h" #include "content/public/common/screen_orientation_values.h" #include "third_party/WebKit/public/platform/WebScreenOrientation.h" namespace content { #define COMPILE_ASSERT_MATCHING_ENUM(expected, actual) \ COMPILE_ASSERT(int(expected) == int(actual), mismatching_enums) COMPILE_ASSERT_MATCHING_ENUM(blink::WebScreenOrientationPortraitPrimary, PORTRAIT_PRIMARY); COMPILE_ASSERT_MATCHING_ENUM(blink::WebScreenOrientationLandscapePrimary, LANDSCAPE_PRIMARY); COMPILE_ASSERT_MATCHING_ENUM(blink::WebScreenOrientationPortraitSecondary, PORTRAIT_SECONDARY); COMPILE_ASSERT_MATCHING_ENUM(blink::WebScreenOrientationLandscapeSecondary, LANDSCAPE_SECONDARY); } // namespace content
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Use this file to assert that *_list.h enums that are meant to do the bridge // from Blink are valid. #include "base/macros.h" #include "content/public/common/screen_orientation_values.h" #include "third_party/WebKit/public/platform/WebScreenOrientation.h" namespace content { #define COMPILE_ASSERT_MATCHING_ENUM(expected, actual) \ COMPILE_ASSERT(int(expected) == int(actual), mismatching_enums) // TODO(mlamouri): this is temporary to allow to change the enum in Blink. // COMPILE_ASSERT_MATCHING_ENUM(blink::WebScreenOrientationPortraitPrimary, // PORTRAIT_PRIMARY); // COMPILE_ASSERT_MATCHING_ENUM(blink::WebScreenOrientationLandscapePrimary, // LANDSCAPE_PRIMARY); // COMPILE_ASSERT_MATCHING_ENUM(blink::WebScreenOrientationPortraitSecondary, // PORTRAIT_SECONDARY); // COMPILE_ASSERT_MATCHING_ENUM(blink::WebScreenOrientationLandscapeSecondary, // LANDSCAPE_SECONDARY); } // namespace content
Implement basic, but useful Tokeniser tests.
// This file is part of playd. // playd is licenced under the MIT license: see LICENSE.txt. /** * @file * Tests for the Tokeniser class. */ #include "catch.hpp" #include "../io/tokeniser.hpp" SCENARIO("Tokenisers can handle complete, unquoted commands", "[tokeniser]") { GIVEN("A fresh Tokeniser") { Tokeniser t; WHEN("the Tokeniser is fed a nullary command") { auto words = t.Feed("stop\n"); THEN("one line is returned") { REQUIRE(words.size() == 1); } THEN("the line contains one word") { REQUIRE(words[0].size() == 1); } THEN("the word is the nullary command") { REQUIRE(words[0][0] == "stop"); } } WHEN("the Tokeniser is fed a unary command") { auto words = t.Feed("seek 10s\n"); THEN("one line is returned") { REQUIRE(words.size() == 1); } THEN("the line contains two words") { REQUIRE(words[0].size() == 2); } THEN("the first word is the command") { REQUIRE(words[0][0] == "seek"); } THEN("the second word is the argument") { REQUIRE(words[0][1] == "10s"); } } } }
Add test for logging the implicit "this" argument for C++ member functions.
// Intercept the implicit 'this' argument of class member functions. // // RUN: %clangxx_xray -g -std=c++11 %s -o %t // RUN: rm log-args-this-* || true // RUN: XRAY_OPTIONS="patch_premain=true verbosity=1 xray_logfile_base=log-args-this-" %run %t // // XFAIL: arm || aarch64 || mips // UNSUPPORTED: powerpc64le #include "xray/xray_interface.h" #include <cassert> class A { public: [[clang::xray_always_instrument, clang::xray_log_args(1)]] void f() { // does nothing. } }; volatile uint64_t captured = 0; void handler(int32_t, XRayEntryType, uint64_t arg1) { captured = arg1; } int main() { __xray_set_handler_arg1(handler); A instance; instance.f(); __xray_remove_handler_arg1(); assert(captured == (uint64_t)&instance); }
Disable ExtensionApiTest.Tabs on Mac. TEST=no random redness on Mac OS X 10.6 bot BUG=37387 TBR=skerner@
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/browser.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/common/pref_names.h" // TODO(skerner): This test is flaky in chromeos. Figure out why and fix. #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) #define MAYBE_Tabs DISABLED_Tabs #else #define MAYBE_Tabs Tabs #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) { StartHTTPServer(); // The test creates a tab and checks that the URL of the new tab // is that of the new tab page. Make sure the pref that controls // this is set. browser()->profile()->GetPrefs()->SetBoolean( prefs::kHomePageIsNewTabPage, true); ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_; }
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/browser.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/common/pref_names.h" // TODO(skerner): This test is flaky in chromeos and on Mac OS X 10.6. Figure // out why and fix. #if (defined(OS_LINUX) && defined(TOOLKIT_VIEWS)) || defined(OS_MACOSX) #define MAYBE_Tabs DISABLED_Tabs #else #define MAYBE_Tabs Tabs #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) { StartHTTPServer(); // The test creates a tab and checks that the URL of the new tab // is that of the new tab page. Make sure the pref that controls // this is set. browser()->profile()->GetPrefs()->SetBoolean( prefs::kHomePageIsNewTabPage, true); ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_; }
Add Solution for Problem 149
// 149. Max Points on a Line /** * Given n points on a 2D plane, find the maximum number of points that lie on the same straight line. * * Tags: Hash Table, Math * * Author: Kuang Qin */ #include "stdafx.h" #include <vector> #include <unordered_map> using namespace std; /** * Definition for a point. */ struct Point { int x; int y; Point() : x(0), y(0) {} Point(int a, int b) : x(a), y(b) {} }; // Hash Table // Time: O(n^2) class Solution { public: int maxPoints(vector<Point>& points) { int n = points.size(); if (n < 2) { return n; } // use a hash table to store slopes of lines containing a specific point unordered_map<double, int> slope; int count = 0; // results for (int i = 0; i < n - 1; i++) { int duplicates = 1; // duplicate points counter int vertical = 0; // vertical slope counter for (int j = i + 1; j < n; j++) { // duplicate points if (points[j].x == points[i].x && points[j].y == points[i].y) { duplicates++; continue; } // points on a vertical line if (points[j].x == points[i].x) { vertical++; continue; } // points on a certain slope float k = (float)(points[j].y - points[i].y) / (points[j].x - points[i].x); if (slope.find(k) == slope.end()) { slope[k] = 1; } else { slope[k]++; } } // scan the hash table for the max value count = max(count, vertical + duplicates); for (auto it = slope.begin(); it != slope.end(); it++) { if (it->second + duplicates > count) { count = it->second + duplicates; } } slope.clear(); } return count; } }; int _tmain(int argc, _TCHAR* argv[]) { return 0; }
Use std::make_tuple in return multiple values sample
// Return multiple values #include <tuple> std::tuple<int, bool, float> foo() { return {128, true, 1.5f}; } int main() { int obj1; bool obj2; float obj3; std::tie(obj1, obj2, obj3) = foo(); } // Return multiple values of different types from a function. // // The `foo` function on [5-8] returns a // [`std::tuple`](cpp/utility/tuple) representing multiple values // of different types. // // On [16], we call this function and use [`std::tie`](cpp/utility/tuple/tie) // to assign the return values to each of the given objects. // If we cannot create the objects prior to this call, we can // alternatively store the resulting `std::tuple` object and use // [`std::get`](cpp/utility/tuple/get) to get the values from it. // // If the values are closely and logically related, consider composing // them into a `struct` or `class`.
// Return multiple values #include <tuple> std::tuple<int, bool, float> foo() { return std::make_tuple(128, true, 1.5f); } int main() { int obj1; bool obj2; float obj3; std::tie(obj1, obj2, obj3) = foo(); } // Return multiple values of different types from a function. // // The `foo` function on [5-8] returns a // [`std::tuple`](cpp/utility/tuple) representing multiple values // of different types. We make use of the // [`std::make_tuple`](cpp/utility/tuple/make_tuple) utility function // to create the `std::tuple` object. // // On [16], we call this function and use [`std::tie`](cpp/utility/tuple/tie) // to assign the return values to each of the given objects. // If we cannot create the objects prior to this call, we can // alternatively store the resulting `std::tuple` object and use // [`std::get`](cpp/utility/tuple/get) to get the values from it. // // If the values are closely and logically related, consider composing // them into a `struct` or `class`.
Add solution for 17.8 problem.
#include <iostream> #include <tuple> #include <vector> namespace { struct Person { int weight; int height; }; bool operator>(const Person &a, const Person &b) { return std::tie(a.weight, a.height) > std::tie(b.weight, b.height); } bool operator<(const Person &a, const Person &b) { return std::tie(a.weight, a.height) < std::tie(b.weight, b.height); } bool operator==(const Person &a, const Person &b) { return std::tie(a.weight, a.height) == std::tie(b.weight, b.height); } using container_type = std::vector<Person>; void print(const container_type &data) { if (data.empty()) return; auto iter = data.cbegin(); std::cout << "(" << iter->weight << "," << iter->height << ")"; ++iter; for (; iter != data.cend(); ++iter) { std::cout << " (" << iter->weight << "," << iter->height << ")"; } std::cout << "\n"; } struct CircusTower { void search(const container_type &data) { size_t N = data.size(); size_t max_height = 0; for (size_t i = 0; i < (N - 1); ++i) { size_t current_height = 1; Person prev = data[i]; for (size_t j = i + 1; j < N; ++j) { if (is_valid(prev, data[j])) { prev = data[j]; ++current_height; } } max_height = std::max(max_height, current_height); } print(data); std::cout << "max height: " << max_height << "\n"; } bool is_valid(const Person &a, const Person &b) { return (a.weight <= b.weight) && (a.height <= b.height); } }; } // namespace int main() { CircusTower tower; { container_type data1{{65, 100}, {70, 150}, {56, 90}, {75, 190}, {60, 95}, {68, 100}}; std::sort(data1.begin(), data1.end()); tower.search(data1); } { container_type data1{{65, 160}, {70, 150}, {66, 90}}; std::sort(data1.begin(), data1.end()); tower.search(data1); } }
Fix Framework::programDirectory on OS X
//TODO remove unused imports #include <climits> #include <cstring> #include <unistd.h> #include <sys/stat.h> #include <algorithm> #include <string> #include <core/loader.h> #include <core/module.h> #include <core/logger.h> #include <core/framework.h> namespace lms{ std::string Framework::programDirectory(){ static std::string directory; if(directory.empty()) { char path[PATH_MAX]; memset (path, 0, PATH_MAX); if (readlink("/proc/self/exe", path, PATH_MAX) == -1) { perror("readlink failed"); exit(1); } //get programmdirectory // TODO optimize this a bit directory = path; directory = directory.substr(0, directory.rfind("/")); directory = directory.substr(0, directory.rfind("/")); directory = directory + "/"; } //std::cout << "ProgramDirectory: " << directory << std::endl; return directory; } }
//TODO remove unused imports #include <climits> #include <cstring> #include <unistd.h> #include <sys/stat.h> #include <algorithm> #include <string> #include <core/loader.h> #include <core/module.h> #include <core/logger.h> #include <core/framework.h> #ifdef __APPLE__ #include <mach-o/dyld.h> #endif namespace lms{ std::string Framework::programDirectory(){ static std::string directory; if(directory.empty()) { char path[PATH_MAX]; memset (path, 0, PATH_MAX); #ifdef __APPLE__ uint32_t size = PATH_MAX; if( _NSGetExecutablePath(path, &size) == 0 ) { char* fullpath = realpath(path, NULL); if( !fullpath ) { perror("realpath failed"); exit(1); } directory = fullpath; } else { perror("_NSGetExecutablePath failed"); exit(1); } #else if (readlink("/proc/self/exe", path, PATH_MAX) == -1) { perror("readlink failed"); exit(1); } directory = path; #endif // TODO optimize this a bit directory = directory.substr(0, directory.rfind("/")); directory = directory.substr(0, directory.rfind("/")); directory = directory + "/"; } //std::cout << "ProgramDirectory: " << directory << std::endl; return directory; } }
Add Forgotten test for: Fix template parameter default args missed if redecled
// RUN: %clang_cc1 -fsyntax-only -verify %s // expected-no-diagnostics namespace llvm { template<typename T > struct StringSet; template<int I > struct Int; template <typename Inner, template <typename> class Outer> struct TemplTempl; } namespace lld { using llvm::StringSet; using llvm::Int; using llvm::TemplTempl; }; namespace llvm { template<typename T > struct StringSet; } template<typename T> struct Temp{}; namespace llvm { template<typename T = int> struct StringSet{}; template<int I = 5> struct Int{}; template <typename Inner, template <typename> class Outer = Temp> struct TemplTempl{}; }; namespace lld { StringSet<> s; Int<> i; TemplTempl<int> tt; }
Use URLFetcherFactory for 3-arg overload of URLFetcher::Create
// 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 "net/url_request/url_fetcher.h" #include "net/url_request/url_fetcher_factory.h" #include "net/url_request/url_fetcher_impl.h" namespace net { URLFetcher::~URLFetcher() {} // static URLFetcher* net::URLFetcher::Create( const GURL& url, URLFetcher::RequestType request_type, URLFetcherDelegate* d) { return new URLFetcherImpl(url, request_type, d); } // static URLFetcher* net::URLFetcher::Create( int id, const GURL& url, URLFetcher::RequestType request_type, URLFetcherDelegate* d) { URLFetcherFactory* factory = URLFetcherImpl::factory(); return factory ? factory->CreateURLFetcher(id, url, request_type, d) : new URLFetcherImpl(url, request_type, d); } // static void net::URLFetcher::CancelAll() { URLFetcherImpl::CancelAll(); } // static void net::URLFetcher::SetEnableInterceptionForTests(bool enabled) { URLFetcherImpl::SetEnableInterceptionForTests(enabled); } // static void net::URLFetcher::SetIgnoreCertificateRequests(bool ignored) { URLFetcherImpl::SetIgnoreCertificateRequests(ignored); } } // namespace net
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/url_request/url_fetcher.h" #include "net/url_request/url_fetcher_factory.h" #include "net/url_request/url_fetcher_impl.h" namespace net { URLFetcher::~URLFetcher() {} // static URLFetcher* net::URLFetcher::Create( const GURL& url, URLFetcher::RequestType request_type, URLFetcherDelegate* d) { return URLFetcher::Create(0, url, request_type, d); } // static URLFetcher* net::URLFetcher::Create( int id, const GURL& url, URLFetcher::RequestType request_type, URLFetcherDelegate* d) { URLFetcherFactory* factory = URLFetcherImpl::factory(); return factory ? factory->CreateURLFetcher(id, url, request_type, d) : new URLFetcherImpl(url, request_type, d); } // static void net::URLFetcher::CancelAll() { URLFetcherImpl::CancelAll(); } // static void net::URLFetcher::SetEnableInterceptionForTests(bool enabled) { URLFetcherImpl::SetEnableInterceptionForTests(enabled); } // static void net::URLFetcher::SetIgnoreCertificateRequests(bool ignored) { URLFetcherImpl::SetIgnoreCertificateRequests(ignored); } } // namespace net
Add unit tests for user C bindings
#include <boost/test/unit_test.hpp> #include <ygo/deck/c/User.h> #include <ygo/deck/c/DB.h> struct User_Fixture { User_Fixture() { DB_NAME(set_path)("test/card.db"); } }; BOOST_FIXTURE_TEST_SUITE(User, User_Fixture) BOOST_AUTO_TEST_CASE(Create) { auto user = USER_NAME(new_create)("Test"); auto name = USER_NAME(name)(user); BOOST_CHECK_EQUAL(std::string(name), "Test"); USER_NAME(delete_name)(name); USER_NAME(delete)(user); } BOOST_AUTO_TEST_CASE(Open) { auto user = USER_NAME(new)("Test"); auto name = USER_NAME(name)(user); BOOST_CHECK_EQUAL(std::string(name), "Test"); USER_NAME(delete_name)(name); USER_NAME(delete)(user); } BOOST_AUTO_TEST_CASE(Unknown) { auto user = USER_NAME(new)("NotKnown"); BOOST_CHECK(user == nullptr); } BOOST_AUTO_TEST_CASE(Remove) { auto user = USER_NAME(new)("Test"); auto name = USER_NAME(name)(user); BOOST_CHECK_EQUAL(std::string(name), "Test"); USER_NAME(remove)(user); USER_NAME(delete_name)(name); USER_NAME(delete)(user); auto user2 = USER_NAME(new)("Test"); BOOST_CHECK(user2 == nullptr); } BOOST_AUTO_TEST_SUITE_END()
Revert "BinEditor: Remove unused file"
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "markup.h" /*! \class BinEditor::Markup \brief The Markup class defines the range of the binary editor. Used for displaying class layouts by the debugger. \note Must not have linkage - used for soft dependencies. \sa Debugger::Internal::MemoryAgent */
Convert Sorted Array to Binary Search Tree
/** * 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* transfer(vector<int>& nums, int start, int end){ if(start > end) return NULL; else if(start == end) return new TreeNode(nums[start]); int mid = start + (end - start) / 2; TreeNode* root = new TreeNode(nums[mid]); root->left = transfer(nums, start, mid - 1); root->right = transfer(nums, mid + 1, end); return root; } TreeNode* sortedArrayToBST(vector<int>& nums) { return transfer(nums, 0, nums.size() - 1); } };
Fix typo in key existence sample
// Check existence of a key // C++11 #include <map> #include <string> int main() { std::map<std::string, int> m = {{"a", 1}, {"b", 2}, {"c", 3}}; if (m.count("b")) { // We know "b" is in m } } // Check if a particular key is in an associative container. // // On [9], we create a [`std::map`](cpp/container/map) as an example // associative container and initialize it with key-value pairs. // // On [11], we count the number of occurrences of the key `"b"` in `m` // by using the memeber function [`count`](cpp/container/map/count). // If `"b"` is in `m`, `count` will return 1; otherwise it will return // 0. // // Note: in C++14, an instance of the searched key will not be created // if the container's comparator is // [transparent](http://stackoverflow.com/q/20317413/150634) and // supports the appropriate comparison without conversions.
// Check existence of a key // C++11 #include <map> #include <string> int main() { std::map<std::string, int> m = {{"a", 1}, {"b", 2}, {"c", 3}}; if (m.count("b")) { // We know "b" is in m } } // Check if a particular key is in an associative container. // // On [9], we create a [`std::map`](cpp/container/map) as an example // associative container and initialize it with key-value pairs. // // On [11], we count the number of occurrences of the key `"b"` in `m` // by using the member function [`count`](cpp/container/map/count). // If `"b"` is in `m`, `count` will return 1; otherwise it will return // 0. // // Note: in C++14, an instance of the searched key will not be created // if the container's comparator is // [transparent](http://stackoverflow.com/q/20317413/150634) and // supports the appropriate comparison without conversions.
Fix origin propagation for select of floats.
// Regression test for origin propagation in "select i1, float, float". // https://code.google.com/p/memory-sanitizer/issues/detail?id=78 // RUN: %clangxx_msan -O2 -fsanitize-memory-track-origins %s -o %t && not %run %t >%t.out 2>&1 // RUN: FileCheck %s < %t.out // RUN: %clangxx_msan -O2 -fsanitize-memory-track-origins=2 %s -o %t && not %run %t >%t.out 2>&1 // RUN: FileCheck %s < %t.out #include <stdio.h> #include <sanitizer/msan_interface.h> int main() { volatile bool b = true; float x, y; __msan_allocated_memory(&x, sizeof(x)); __msan_allocated_memory(&y, sizeof(y)); float z = b ? x : y; if (z > 0) printf(".\n"); // CHECK: Uninitialized value was created by a heap allocation // CHECK: {{#0 0x.* in .*__msan_allocated_memory}} // CHECK: {{#1 0x.* in main .*select_float_origin.cc:}}[[@LINE-6]] return 0; }
Add test for previous commit.
// RUN: %clang_cc1 %s -triple=arm-linux-gnueabi -target-abi aapcs -emit-llvm -o - | FileCheck %s class SMLoc { const char *Ptr; public: SMLoc(); SMLoc(const SMLoc &RHS); }; SMLoc foo(void *p); void bar(void *x) { foo(x); } void zed(SMLoc x); void baz() { SMLoc a; zed(a); } // CHECK: declare arm_aapcscc void @_Z3fooPv(%class.SMLoc* sret, i8*) // CHECK: declare arm_aapcscc void @_Z3zed5SMLoc(%class.SMLoc*)
Add script to test install
#include <boost/lambda/lambda.hpp> #include <iostream> #include <iterator> #include <algorithm> int main() { using namespace boost::lambda; typedef std::istream_iterator<int> in; std::for_each( in(std::cin), in(), std::cout << (_1 * 3) << " " ); }
Create a class to look at difference in time for constructors
#include <iostream> #include <chrono> struct Test { Test(long N) : n(N) { long sum = 0; for (long i = 0; i < n; ++i) { sum += i; } } Test() : n(1e8) { Test(n); } long n; }; // struct Test int main(int argc, char* argv[]) { const long N(1e8); auto start = std::chrono::system_clock::now(); Test t1 = Test(N); auto stop = std::chrono::system_clock::now(); std::cout << "Test t1 = Test() took " << (stop - start).count() << " to initialize\n"; start = std::chrono::system_clock::now(); Test t2(N); stop = std::chrono::system_clock::now(); std::cout << "Test t2(N) took " << (stop - start).count() << " s to initialize\n"; return 0; }
Add a test for double version of mdivide_left_sped.
#include <stan/math/matrix/mdivide_left_spd.hpp> #include <stan/math/matrix/typedefs.hpp> #include <gtest/gtest.h> TEST(MathMatrix,mdivide_left_spd_val) { using stan::math::mdivide_left_spd; stan::math::matrix_d Ad(2,2); stan::math::matrix_d I; Ad << 2.0, 3.0, 3.0, 7.0; I = mdivide_left_spd(Ad,Ad); EXPECT_NEAR(1.0,I(0,0),1.0E-12); EXPECT_NEAR(0.0,I(0,1),1.0E-12); EXPECT_NEAR(0.0,I(1,0),1.0E-12); EXPECT_NEAR(1.0,I(1,1),1.0e-12); }
Update gpu/angle_end2end_tets with recent file move
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/at_exit.h" #include "base/bind.h" #include "base/command_line.h" #include "base/message_loop/message_loop.h" #include "base/test/launcher/unit_test_launcher.h" #include "base/test/test_suite.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/angle/src/tests/end2end_tests/ANGLETest.h" namespace { int RunHelper(base::TestSuite* test_suite) { base::MessageLoop message_loop; return test_suite->Run(); } } // namespace int main(int argc, char** argv) { base::CommandLine::Init(argc, argv); testing::InitGoogleMock(&argc, argv); testing::AddGlobalTestEnvironment(new ANGLETestEnvironment()); base::TestSuite test_suite(argc, argv); int rt = base::LaunchUnitTestsSerially( argc, argv, base::Bind(&RunHelper, base::Unretained(&test_suite))); return rt; }
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/at_exit.h" #include "base/bind.h" #include "base/command_line.h" #include "base/message_loop/message_loop.h" #include "base/test/launcher/unit_test_launcher.h" #include "base/test/test_suite.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/angle/src/tests/test_utils/ANGLETest.h" namespace { int RunHelper(base::TestSuite* test_suite) { base::MessageLoop message_loop; return test_suite->Run(); } } // namespace int main(int argc, char** argv) { base::CommandLine::Init(argc, argv); testing::InitGoogleMock(&argc, argv); testing::AddGlobalTestEnvironment(new ANGLETestEnvironment()); base::TestSuite test_suite(argc, argv); int rt = base::LaunchUnitTestsSerially( argc, argv, base::Bind(&RunHelper, base::Unretained(&test_suite))); return rt; }
Test fix-it added in r152198.
// RUN: %clang_cc1 -Wc++11-compat -verify -std=c++98 %s // RUN: cp %s %t // RUN: not %clang_cc1 -Wc++11-compat -Werror -x c++ -std=c++98 -fixit %t // RUN: %clang_cc1 -Wall -pedantic-errors -Wc++11-compat -Werror -x c++ -std=c++98 %t // This is a test of the code modification hints for C++11-compatibility problems. #define bar "bar" const char *p = "foo"bar; // expected-warning {{will be treated as a user-defined literal suffix}}
Add thread cached ints benchmark
/* * Copyright 2018-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/Benchmark.h> #include <folly/synchronization/detail/ThreadCachedInts.h> using namespace folly; void runTest(int iters) { BenchmarkSuspender susp; detail::ThreadCachedInts<void> counters; counters.increment(0); susp.dismiss(); // run the test loop for (int i = 0; i < iters; i++) { counters.increment(0); } } BENCHMARK_DRAW_LINE(); BENCHMARK(Increment, iters) { runTest(iters); } BENCHMARK_DRAW_LINE(); int main(int argc, char* argv[]) { gflags::ParseCommandLineFlags(&argc, &argv, true); folly::runBenchmarks(); return 0; }
Fix use of an uninitialized value.
#include <stddef.h> #include "util/timer.h" #define MS_PER_SECOND 1000 unsigned long openxc::util::time::startupTimeMs() { static unsigned long startupTime = time::systemTimeMs(); return startupTime; } unsigned long openxc::util::time::uptimeMs() { return systemTimeMs() - startupTimeMs(); } /* Private: Return the period in ms given the frequency in hertz. */ float frequencyToPeriod(float frequency) { return 1 / frequency * MS_PER_SECOND; } bool openxc::util::time::shouldTick(FrequencyClock* clock) { if(clock == NULL) { return true; } unsigned long (*timeFunction)() = clock->timeFunction != NULL ? clock->timeFunction : systemTimeMs; float elapsedTime = timeFunction() - clock->lastTick; bool tick = false; if(!clock->started || clock->frequency == 0 || elapsedTime >= frequencyToPeriod(clock->frequency)) { tick = true; clock->lastTick = timeFunction(); clock->started = true; } return tick; } void openxc::util::time::initializeClock(FrequencyClock* clock) { clock->lastTick = -1; clock->frequency = 0; clock->timeFunction = systemTimeMs; }
#include <stddef.h> #include "util/timer.h" #define MS_PER_SECOND 1000 unsigned long openxc::util::time::startupTimeMs() { static unsigned long startupTime = time::systemTimeMs(); return startupTime; } unsigned long openxc::util::time::uptimeMs() { return systemTimeMs() - startupTimeMs(); } /* Private: Return the period in ms given the frequency in hertz. */ float frequencyToPeriod(float frequency) { return 1 / frequency * MS_PER_SECOND; } bool openxc::util::time::shouldTick(FrequencyClock* clock) { if(clock == NULL) { return true; } unsigned long (*timeFunction)() = clock->timeFunction != NULL ? clock->timeFunction : systemTimeMs; float elapsedTime = timeFunction() - clock->lastTick; bool tick = false; if(!clock->started || clock->frequency == 0 || elapsedTime >= frequencyToPeriod(clock->frequency)) { tick = true; clock->lastTick = timeFunction(); clock->started = true; } return tick; } void openxc::util::time::initializeClock(FrequencyClock* clock) { clock->lastTick = -1; clock->frequency = 0; clock->timeFunction = systemTimeMs; clock->started = false; }
Fix memory leak in HidServiceTest.Create from r285774
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <vector> #include "base/message_loop/message_loop.h" #include "device/hid/hid_service.h" #include "testing/gtest/include/gtest/gtest.h" namespace device { TEST(HidServiceTest, Create) { base::MessageLoopForIO message_loop; HidService* service = HidService::Create(message_loop.message_loop_proxy()); ASSERT_TRUE(service); std::vector<HidDeviceInfo> devices; service->GetDevices(&devices); for (std::vector<HidDeviceInfo>::iterator it = devices.begin(); it != devices.end(); ++it) { ASSERT_TRUE(it->device_id != kInvalidHidDeviceId); } } } // namespace device
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <vector> #include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "device/hid/hid_service.h" #include "testing/gtest/include/gtest/gtest.h" namespace device { TEST(HidServiceTest, Create) { base::MessageLoopForIO message_loop; scoped_ptr<HidService> service( HidService::Create(message_loop.message_loop_proxy())); ASSERT_TRUE(service); std::vector<HidDeviceInfo> devices; service->GetDevices(&devices); for (std::vector<HidDeviceInfo>::iterator it = devices.begin(); it != devices.end(); ++it) { ASSERT_TRUE(it->device_id != kInvalidHidDeviceId); } } } // namespace device
Add "multiple return values" sample
// Return multiple values #include <tuple> #include <string> std::tuple<int, bool, std::string> foo() { return {128, true, "hello"}; } int main() { int obj1; bool obj2; std::string obj3; std::tie(obj1, obj2, obj3) = foo(); } // Return multiple values of different types from a function. // // The `foo` function on [6-9] returns a // [`std::tuple`](cpp/utility/tuple) representing multiple values // of different types. // // On [17], the [`std::tie`](cpp/utility/tuple/tie) helper function // ensures that each of the return values is assigned to each of the // given objects. This approach only works if it is reasonable to // declare the objects earlier. // // When we cannot use `std::tie`, we can simply // store the resulting `std::tuple` object and use // [`std::get`](cpp/utility/tuple/get) to get the values from it.
Add example for the room functions
// Copyright 2018 otris software AG // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <ews/ews.hpp> #include <ews/ews_test_support.hpp> #include <exception> #include <iostream> #include <ostream> #include <stdlib.h> #include <string> int main() { int res = EXIT_SUCCESS; ews::set_up(); try { const auto env = ews::test::environment(); auto service = ews::service(env.server_uri, env.domain, env.username, env.password); auto room_lists = service.get_room_lists(); if (room_lists.empty()) { std::cout << "There are no room lists configured\n"; } else { for (const auto& room_list : room_lists) { std::cout << "The room list " << room_list.name() << " contains the following rooms:\n"; auto rooms = service.get_rooms(room_list); if (rooms.empty()) { std::cout << "This room list does not contain any rooms\n"; } else { for (const auto& room : rooms) { std::cout << room.name() << "\n"; } } } } } catch (std::exception& exc) { std::cout << exc.what() << std::endl; res = EXIT_FAILURE; } ews::tear_down(); return res; } // vim:et ts=4 sw=4
Add C++ program that does not depend on libstdc++ but still uses many c++ features. This is for testing compilers.
/* A c++ program that can be linked without libstdc++ */ #include <cstdio> //Seems to be ok, requires libc #include <cstdlib> class C { public: C(int x) { data = x; mem = (int *)malloc(sizeof*mem); } ~C() { printf("Destroying C object with data = %i\n",data); free(mem); } protected: int data; int *mem; }; //Templates are ok template<int N> int retN() { // This is ok (normal static data) static double f[] = {1,2,3}; // Creating a static object bring in locking /* Brings in __cxa_guard_acquire/release static C cintemplate(19); */ return N+f[0]; } static C cstatic(5); //This is also ok with g++/gcc int main(void) { C cstack(12); /* Requires libstdc++ C *cp = new C(17); delete cp; */ printf("ret12: %i\n",retN<12>()); return 0; }
Add solution for chapter 17 test 25
#include <iostream> #include <string> #include <regex> using namespace std; using namespace std::regex_constants; int main() { string phone = "(\\()?(\\d{3})(\\))?([-. ])?(\\d{3})([-. ])?(\\d{4})"; regex r(phone); string s; string fmt = "$2.$5.$7"; while(getline(cin, s)) { cout << regex_replace(s, r, fmt, match_prev_avail) << endl; } return 0; }
Test case for OpenCL 1.1 Sampler Objects
/* test OpenCL 1.1 Sampler Objects (section 5.5) */ #include "utest_helper.hpp" void compiler_sampler(void) { OCL_ASSERT(ctx != 0); cl_sampler s; cl_int err; int a1[] = {CL_TRUE, CL_FALSE}, a2[] = {CL_ADDRESS_MIRRORED_REPEAT, CL_ADDRESS_REPEAT, CL_ADDRESS_CLAMP_TO_EDGE, CL_ADDRESS_CLAMP, CL_ADDRESS_NONE}, a3[] = {CL_FILTER_NEAREST, CL_FILTER_LINEAR}, a4[] = {CL_SAMPLER_REFERENCE_COUNT, CL_SAMPLER_CONTEXT, CL_SAMPLER_NORMALIZED_COORDS, CL_SAMPLER_ADDRESSING_MODE, CL_SAMPLER_FILTER_MODE}; char pv[1000]; size_t pv_size; int i, j, k, l; for(i=0; i<2; i++) for(j=0; j<5; j++) for(k=0; k<2; k++) { s = clCreateSampler(ctx, a1[i], a2[j], a3[k], &err); OCL_ASSERT(err == CL_SUCCESS); OCL_CALL(clRetainSampler, s); OCL_CALL(clReleaseSampler, s); for(l=0; l<5; l++) OCL_CALL(clGetSamplerInfo, s, a4[l], 1000, pv, &pv_size); OCL_CALL(clReleaseSampler, s); } } MAKE_UTEST_FROM_FUNCTION(compiler_sampler);
Add solution for chapter 18 test 3
#include <iostream> #include <fstream> #include <vector> #include <memory> using namespace std; void exercise1(int *b, int *e) { try { vector<int> v(b, e); int *p = new int[v.size()]; ifstream in("ins"); throw p; } catch(int *p) { delete[] p; } } void exercise2(int *b, int *e) { try { vector<int> v(b, e); unique_ptr<int[]> p(new int[v.size()]); ifstream in("ins"); } catch(...) { } } void exercise3(int *b, int *e) { vector<int> v(b, e); int* p = new int[v.size()]; ifstream in("ins"); try { throw p; } catch(...) { delete[] p; } delete[] p; } int main() { int a[] = {1, 2, 3, 4}; int *b = std::begin(a), *e = std::end(a); exercise1(b, e); exercise2(b, e); exercise3(b, e); return 0; }
Add solution for problem 4.1
#include "data.hpp" #include "graph.hpp" #include <string> #include <vector> namespace { enum Status : uint8_t { NONE, VISITED, PROCESSED }; template <typename Graph> struct DFS { using index_type = unsigned int; explicit DFS(Graph &g) : graph(g), states(g.get_number_of_vertexes(), NONE) {} // Perform DFS traversal from given vertex. void pre_order(const std::vector<index_type> &vids) { std::vector<index_type> stack(vids.cbegin(), vids.cend()); while (!stack.empty()) { auto vid = stack.back(); stack.pop_back(); visit(vid); auto range = graph.edges(vid); for (auto iter = range.begin; iter != range.end; ++iter) { if (states[*iter] == NONE) { // Only check in a vertex if it has not been visited yet. stack.push_back(*iter); } } } } void reset_states() { states.assign(states.size(), NONE); // Reset node status } void visit(const index_type vid) { if (states[vid] == NONE) { states[vid] = VISITED; fmt::print("visit: {}\n", vid); } } Graph graph; std::vector<index_type> states; }; } // namespace int main() { auto g = experiments::directed_graph(); g.print(); using graph_type = decltype(g); DFS<graph_type> dfs(g); // Visit node 0. dfs.pre_order({0}); // Visit node 1. dfs.pre_order({1}); }
Add Chapter 2, exercise 1: eliminate duplicates in linked list
// 2.1 - remove duplicates from unsorted linked list // uses STL list and set #include<iostream> #include<list> #include<set> using namespace std; typedef list<int>::iterator iter; typedef list<int>::const_iterator c_iter; void remove_duplicates(list<int>& l) { set<int> vals; iter p = l.begin(); while (p != l.end()) { if (vals.find(*p) != vals.end()) p = l.erase(p); else { vals.insert(*p); ++p; } } } void print(const list<int>& l) { for (c_iter p = l.begin(); p!=l.end(); ++p) cout << *p << '\n'; } void test(list<int>& l) { cout << "Before:\n"; print(l); remove_duplicates(l); cout << "\nAfter:\n"; print(l); cout << '\n'; } int main() { list<int> l1; test(l1); list<int> l2 = { 1 }; test(l2); list<int> l3 = { 1, 1 }; test(l3); list<int> l4 = { 1, 2, 3 }; test(l4); list<int> l5 = { 1, 2, 3, 1, 4, 1, 5, 5, 5 }; test(l5); }
Add missing test case for PR8230
// RUN: %clang_cc1 -fsyntax-only -verify %s void g(); void f(); // expected-note 9{{candidate function}} void f(int); // expected-note 9{{candidate function}} template<class T> void t(T); // expected-note 3{{candidate function}} template<class T> void t(T*); // expected-note 3{{candidate function}} template<class T> void u(T); int main() { { bool b = (void (&)(char))f; } // expected-error{{does not match required type}} { bool b = (void (*)(char))f; } // expected-error{{does not match required type}} { bool b = (void (&)(int))f; } //ok { bool b = (void (*)(int))f; } //ok { bool b = static_cast<void (&)(char)>(f); } // expected-error{{does not match}} { bool b = static_cast<void (*)(char)>(f); } // expected-error{{address of overloaded function}} { bool b = static_cast<void (&)(int)>(f); } //ok { bool b = static_cast<void (*)(int)>(f); } //ok { bool b = reinterpret_cast<void (&)(char)>(f); } // expected-error{{cannot resolve}} { bool b = reinterpret_cast<void (*)(char)>(f); } // expected-error{{cannot resolve}} { bool b = reinterpret_cast<void (*)(char)>(g); } //ok { bool b = static_cast<void (*)(char)>(g); } // expected-error{{not allowed}} { bool b = reinterpret_cast<void (&)(int)>(f); } // expected-error{{cannot resolve}} { bool b = reinterpret_cast<void (*)(int)>(f); } // expected-error{{cannot resolve}} { bool b = (int (&)(char))t; } // expected-error{{does not match}} { bool b = (int (*)(char))t; } // expected-error{{does not match}} { bool b = (void (&)(int))t; } //ok { bool b = (void (*)(int))t; } //ok { bool b = static_cast<void (&)(char)>(t); } //ok { bool b = static_cast<void (*)(char)>(t); } //ok { bool b = static_cast<void (&)(int)>(t); } //ok { bool b = static_cast<void (*)(int)>(t); } //ok { bool b = reinterpret_cast<void (&)(char)>(t); } // expected-error{{cannot resolve}} { bool b = reinterpret_cast<void (*)(char)>(t); } // expected-error{{cannot resolve}} { bool b = reinterpret_cast<int (*)(char)>(g); } //ok { bool b = static_cast<int (*)(char)>(t); } // expected-error{{cannot be static_cast}} { bool b = static_cast<int (&)(char)>(t); } // expected-error{{does not match required}} { bool b = static_cast<void (&)(char)>(f); } // expected-error{{does not match}} }
Add rdtsc snippet and wrapper script
//usr/bin/g++ "$0" -o /tmp/Rdtsc && exec /tmp/Rdtsc "$@" /* * Copyright (c) 2015-2018 Agalmic Ventures LLC (www.agalmicventures.com) * * 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 <cstdint> #include <cstdio> #include <cstdlib> static inline uint64_t rdtsc() { uint64_t tsc; asm volatile ( //A is EDX:EAX "rdtsc" : "=A" (tsc) : : ); return tsc; } int main() { uint64_t time = rdtsc(); std::printf("%llu\n", time); }
Add tests for the user defined subsystem interface²
#include "stdafx.h" #include "engineBootstrap.hpp" #include <catch/catch.hpp> namespace Annwvyn { class TestEvent : public AnnUserSpaceEvent { public: TestEvent(const std::string& message) : AnnUserSpaceEvent("TestEvent"), storedMessage(message) { } std::string getMessage() const { return storedMessage; } private: std::string storedMessage; }; class TestSubSystem : public AnnUserSubSystem { public: TestSubSystem() : AnnUserSubSystem("Test Subsystem"), dispatchedYet(false) { } virtual ~TestSubSystem() { } bool needUpdate() override { return true; } void update() override { if (!dispatchedYet) { if (AnnGetEngine()->getTimeFromStartupSeconds() > 3) { dispatchEvent(std::make_shared<TestEvent>("Message!")); dispatchedYet = true; } } } private: bool dispatchedYet; }; class TestListener : LISTENER { public: TestListener(bool& state) : constructListener(), hash(AnnGetStringUtility()->hash("TestEvent")), state(state) {} void EventFromUserSubsystem(AnnUserSpaceEvent& e, AnnUserSpaceEventLauncher* /*origin*/) override { if (e.getType() == hash) { AnnDebug() << "got message : " << static_cast<TestEvent&>(e).getMessage(); state = true; } } private: AnnUserSpaceEvent::AnnUserSpaceEventTypeHash hash; bool& state; }; TEST_CASE("Test register subsystem") { auto GameEngine = bootstrapTestEngine("UserSubSystemTest"); auto testSystem = std::make_shared<TestSubSystem>(); REQUIRE(testSystem); GameEngine->registerUserSubSystem(testSystem); REQUIRE(GameEngine->isUserSubSystem(testSystem)); } TEST_CASE("Test user events") { auto GameEngine = bootstrapTestEngine("UserSubSystemTest"); AnnGetOnScreenConsole()->setVisible(true); GameEngine->refresh(); auto testSystem = std::make_shared<TestSubSystem>(); REQUIRE(testSystem); GameEngine->registerUserSubSystem(testSystem); REQUIRE(GameEngine->isUserSubSystem(testSystem)); auto state = false; auto testListener = std::make_shared<TestListener>(state); REQUIRE(testListener); AnnGetEventManager()->addListener(testListener); //TODO make reseting this timer easier AnnGetVRRenderer()->getTimer()->reset(); while (GameEngine->getTimeFromStartupSeconds() < 6) GameEngine->refresh(); REQUIRE(state); } }
Add solution for chapter 16 test 42.
#include <iostream> #include <string> using namespace std; template <typename T> void g(T &&val) { T t = val; t -= 1;//for test if(val == t) { cout << "T is reference" << endl; } else { cout << "T is not reference" << endl; } } template <typename T> void g3(const T& val) { T t = val; t -= 1;//for test if(val == t) { cout << "T is reference" << endl; } else { cout << "T is not reference" << endl; } } int main() { //test 16.42 int i = 0; const int ci = i; g(i);// T is int& // g(ci);// T is const int & g(i * ci);//T is int g(i = ci); //test 16.44 g3(i); g3(ci); g3(i * ci); }
Remove gived elements from vector.
/** * Remove Element * * cpselvis(cpselvis@gmail.com) * August 24th, 2016 */ #include<iostream> #include<vector> using namespace std; class Solution { public: int removeElement(vector<int>& nums, int val) { int i; for (i = 0; i < nums.size(); ) { if (nums[i] == val) { nums.erase(nums.begin() + i); } else { i ++; } } return i; } }; int main(int argc, char **argv) { int arr[4] = {3, 2, 2, 3}; vector<int> nums(arr + 0, arr + 4); Solution s; cout << s.removeElement(nums, 3) << endl; }
Add simple function for printing some freshly generated keys.
#include <openssl/bn.h> #include <openssl/ecdsa.h> #include <openssl/ec.h> #include <openssl/evp.h> #include <openssl/err.h> #include <stdio.h> main() { EC_KEY *eckey; BN_CTX *ctx; ctx = BN_CTX_new(); if(!ctx) { printf("failed to create bn ctx\n"); return 1; } eckey = EC_KEY_new_by_curve_name(NID_X9_62_prime192v3); if (eckey == NULL) { printf("failed to initialize curve\n"); return 1; } if (EC_KEY_generate_key(eckey) == 0) { printf("failed to generate key\n"); return 1; } printf("private key: %s\n", BN_bn2hex(EC_KEY_get0_private_key(eckey))); printf("public key: %s\n", EC_POINT_point2hex(EC_KEY_get0_group(eckey), EC_KEY_get0_public_key(eckey), POINT_CONVERSION_COMPRESSED, ctx)); BN_CTX_free(ctx); return 0; }
Add tests for library version of is_convertible
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // type_traits // is_convertible // Test the fallback implementation. #define _LIBCPP_USE_IS_CONVERTIBLE_FALLBACK #include "is_convertible.pass.cpp"
Add conversion Roman numbers to integer value.
#include <unordered_map> #include <iostream> using namespace std; int romanToInteger(const string& s) { unordered_map<char, int> T = { { 'I', 1 }, { 'V', 5 }, { 'X', 10 }, { 'L', 50 }, { 'C', 100 }, { 'D', 500 }, { 'M', 1000 } }; int sum = T[s.back()]; for (int i = s.length() - 2; i >= 0; i--) { if (T[s[i]] < T[s[i + 1]]) { sum -= T[s[i]]; } else { sum += T[s[i]]; } } return sum; } int main() { string s; cin >> s; cout << romanToInteger(s) << endl; return 0; }
Add Solution for Problem 077
// 77. Combinations /** * Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. * * For example, * If n = 4 and k = 2, a solution is: * * [ * [2,4], * [3,4], * [2,3], * [1,2], * [1,3], * [1,4], * ] * * Tags: Backtracking * * Similar Problems: (M) Combination Sum, (M) Permutations * * Author: Kuang Qin */ #include "stdafx.h" #include <vector> using namespace std; class Solution { void backtrack(vector<vector<int>> &res, vector<int> &comb, int index, int n, int k) { if (k == comb.size()) { // size == k, record results res.push_back(comb); return; } for (int i = index; i <= n; i++) { comb.push_back(i); backtrack(res, comb, i + 1, n, k); comb.pop_back(); } return; } public: vector<vector<int>> combine(int n, int k) { vector<vector<int>> res; if (n < 1 || k < 1) { return res; } vector<int> comb; backtrack(res, comb, 1, n, k); return res; } }; int _tmain(int argc, _TCHAR* argv[]) { Solution mySolution; vector<vector<int>> res = mySolution.combine(4, 2); return 0; }
Add test case for insertion sort
/* This program tests soring algorithms defined in sort.h */ #include<iostream> #include<vector> #include "sort.h" // My implementation of some sorting algorithms on std::vector of int // Displays vector void printVector(std::vector<int> A){ for(auto x: A){ std::cout<<x<<" "; } std::cout<<std::endl; } // Tests insertion sort on vector A void testInsertionSort(std::vector<int> A){ std::cout<<"Before: "; printVector(A); insertionSort(A); std::cout<<"After: "; printVector(A); } // tests insertion sort on several different inputs void testInsertionSort(){ std::vector<int> v1 = {10,9,8,7,6,5,4,3,2,1}; testInsertionSort(v1); std::vector<int> v2 = {5,4,3,2,1}; testInsertionSort(v2); std::vector<int> v3 = {1,2,3,4,5,6,7,8,9,10}; testInsertionSort(v3); std::vector<int> v4 = {6,5,4,7,8,9,9,5,4,9,2,0,3,1,5,9,8,7,4,5,6,3}; testInsertionSort(v4); // test on empty vector std::vector<int> v5; testInsertionSort(v5); std::vector<int> v6 = {2,4,-6,1,-9,3,0}; testInsertionSort(v6); std::vector<int> v7 = {1,2,3,4,5,6,7,8,9,0}; testInsertionSort(v7); } int main(){ // test insertion sort testInsertionSort(); return 0; }
Add a simple test for indexing namespaces
// Test is line- and column-sensitive; see below. namespace std { namespace rel_ops { void f(); } } namespace std { void g(); } // FIXME: using directives, namespace aliases // RUN: c-index-test -test-load-source all %s | FileCheck %s // CHECK: load-namespaces.cpp:3:11: Namespace=std:3:11 (Definition) Extent=[3:11 - 7:2] // CHECK: load-namespaces.cpp:4:13: Namespace=rel_ops:4:13 (Definition) Extent=[4:13 - 6:4] // CHECK: load-namespaces.cpp:5:10: FunctionDecl=f:5:10 Extent=[5:10 - 5:13] // CHECK: load-namespaces.cpp:9:11: Namespace=std:9:11 (Definition) Extent=[9:11 - 11:2] // CHECK: load-namespaces.cpp:10:8: FunctionDecl=g:10:8 Extent=[10:8 - 10:11]
Convert BST to Greater Tree
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { int presum=0; public: TreeNode* convertBST(TreeNode* root) { inorder(root); return root; } private: void inorder(TreeNode* root){ if(!root) return; inorder(root->right); root->val+=presum; presum+=(root->val-presum); inorder(root->left); } };
Remove Duplicates from Sorted Array II
class Solution { public: int removeDuplicates(vector<int>& nums) { int cur = 0, count = 0, total = nums.size(); for (auto iter = nums.begin(); iter != nums.end();) { if (iter == nums.begin()) { cur = *iter; count = 1; ++iter; } else { if (*iter == cur) { if (count == 2) { nums.erase(iter); --total; } else { ++count; ++iter; } } else { cur = *iter; count = 1; ++iter; } } } return total; } };
Add quantas chamadas recursivas to cadernaveis
#include <bits/stdc++.h> using namespace std; typedef long long ll; ll sol(ll n, int m) { ll a, b, c, d, r; a = 1; b = 0; c = 0; d = 1; while (n) { if (n&1) { r = ((d*b) + (c*a)) % m; b = (d*(b+a) + (c*b)) % m; a = r; } r = (c*c + d*d) % m; d = (d * (2*c + d)) % m; c = r; n >>= 1; } return (a+b) % m; } int main() { ll n; int b, r, c = 0; while (scanf("%lld %d", &n, &b) && (n || b)) { //r = ((sol(n, b) % b) + b) % b; r = (((2*sol(n, b) - 1) % b) + b) % b; printf("Case %d: %lld %d %d\n", ++c, n, b, r); } return 0; }
Add a few stubs so we can link the latest OpenGL ES 2.0 conformance tests
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. extern "C" { #if defined(GLES2_CONFORM_SUPPORT_ONLY) #include "gpu/gles2_conform_support/gtf/gtf_stubs.h" #else #include "third_party/gles2_conform/GTF_ES/glsl/GTF/Source/eglNative.h" #endif GTFbool GTFNativeCreatePixmap(EGLNativeDisplayType nativeDisplay, EGLDisplay eglDisplay, EGLConfig eglConfig, const char *title, int width, int height, EGLNativePixmapType *pNativePixmap) { return GTFtrue; } void GTFNativeDestroyPixmap(EGLNativeDisplayType nativeDisplay, EGLNativePixmapType nativePixmap) { } } // extern "C"
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. extern "C" { #if defined(GLES2_CONFORM_SUPPORT_ONLY) #include "gpu/gles2_conform_support/gtf/gtf_stubs.h" #else #include "third_party/gles2_conform/GTF_ES/glsl/GTF/Source/eglNative.h" #endif GTFbool GTFNativeCreatePixmap(EGLNativeDisplayType nativeDisplay, EGLDisplay eglDisplay, EGLConfig eglConfig, const char *title, int width, int height, EGLNativePixmapType *pNativePixmap) { return GTFtrue; } void GTFNativeDestroyPixmap(EGLNativeDisplayType nativeDisplay, EGLNativePixmapType nativePixmap) { } EGLImageKHR GTFCreateEGLImageExternal( int width, int height, int format, float r, float g, float b, float a, void** resource) { return (EGLImageKHR)NULL; } void GTFDestroyEGLImageExternal(EGLImageKHR image, void* resource) { } const int* GTFQueryFormatsEGLImageExternal(void) { return NULL; } GTFbool GTFIsAlphaFormatEGLImageExternal(int format) { return GTFfalse; } } // extern "C"
Test case for llvm-gcc rev. 64648.
// Test on debug info to make sure that anon typedef info is emitted. // RUN: %llvmgcc -S --emit-llvm -x c++ -g %s -o - | grep composite typedef struct { int a; long b; } foo; foo x;
Add test cases for SAX2XMLReader.
// test cases for rule CWE-611 #include "tests.h" // --- typedef unsigned int XMLCh; class XMLUni { public: static const XMLCh fgXercesDisableDefaultEntityResolution[]; }; class SAX2XMLReader { public: void setFeature(const XMLCh *feature, bool value); void parse(const InputSource &data); }; class XMLReaderFactory { public: static SAX2XMLReader *createXMLReader(); }; // --- void test3_1(InputSource &data) { SAX2XMLReader *p = XMLReaderFactory::createXMLReader(); p->parse(data); // BAD (parser not correctly configured) [NOT DETECTED] } void test3_2(InputSource &data) { SAX2XMLReader *p = XMLReaderFactory::createXMLReader(); p->setFeature(XMLUni::fgXercesDisableDefaultEntityResolution, true); p->parse(data); // GOOD } SAX2XMLReader *p_3_3 = XMLReaderFactory::createXMLReader(); void test3_3(InputSource &data) { p_3_3->parse(data); // BAD (parser not correctly configured) [NOT DETECTED] } SAX2XMLReader *p_3_4 = XMLReaderFactory::createXMLReader(); void test3_4(InputSource &data) { p_3_4->setFeature(XMLUni::fgXercesDisableDefaultEntityResolution, true); p_3_4->parse(data); // GOOD } SAX2XMLReader *p_3_5 = XMLReaderFactory::createXMLReader(); void test3_5_init() { p_3_5->setFeature(XMLUni::fgXercesDisableDefaultEntityResolution, true); } void test3_5(InputSource &data) { test3_5_init(); p_3_5->parse(data); // GOOD }
Add test to check implicit upcasting of float16_t works.
#include "Halide.h" #include <stdio.h> #include <cmath> using namespace Halide; // FIXME: We should use a proper framework for this. See issue #898 void h_assert(bool condition, const char *msg) { if (!condition) { printf("FAIL: %s\n", msg); abort(); } } int main() { Halide::Func f; Halide::Var x, y; // Function mixes type, the float16_t should be implicitly upcast // to a float f(x, y) = 0.25f + float16_t(0.75); // Use JIT for computation Image<float> simple = f.realize(10, 3); // Assert some basic properties of the image h_assert(simple.extent(0) == 10, "invalid width"); h_assert(simple.extent(1) == 3, "invalid height"); h_assert(simple.min(0) == 0, "unexpected non zero min in x"); h_assert(simple.min(1) == 0, "unexpected non zero min in y"); h_assert(simple.channels() == 1, "invalid channels"); h_assert(simple.dimensions() == 2, "invalid number of dimensions"); // Read result back for (int x = simple.min(0); x < simple.extent(0); ++x) { for (int y = simple.min(1); y < simple.extent(1); ++y) { h_assert(simple(x, y) == 1.0f, "Invalid value read back"); } } printf("Success!\n"); return 0; }
Fix comparison between signed and unsigned integer expressions.
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <unistd.h> #include "base/sys_info.h" #include "testing/gtest/include/gtest/gtest.h" namespace base { namespace android { TEST(SysUtils, AmountOfPhysicalMemory) { // Check that the RAM size reported by sysconf() matches the one // computed by base::SysInfo::AmountOfPhysicalMemory(). size_t sys_ram_size = static_cast<size_t>(sysconf(_SC_PHYS_PAGES) * PAGE_SIZE); EXPECT_EQ(sys_ram_size, SysInfo::AmountOfPhysicalMemory()); } } // namespace android } // namespace base
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <unistd.h> #include "base/sys_info.h" #include "testing/gtest/include/gtest/gtest.h" namespace base { namespace android { TEST(SysUtils, AmountOfPhysicalMemory) { // Check that the RAM size reported by sysconf() matches the one // computed by base::SysInfo::AmountOfPhysicalMemory(). size_t sys_ram_size = static_cast<size_t>(sysconf(_SC_PHYS_PAGES) * PAGE_SIZE); EXPECT_EQ(sys_ram_size, static_cast<size_t>(SysInfo::AmountOfPhysicalMemory())); } } // namespace android } // namespace base
Add file missed in r574.
#include <common/buffer.h> #include <event/action.h> #include <event/callback.h> #include <event/event.h> #include <event/event_system.h> Action * Callback::schedule(void) { return (EventSystem::instance()->schedule(this)); }
Add a solution of prob 1
#include <stdio.h> int main(void) { int sum = 0, count = 0; do { int num; printf("Enter the num= "); scanf("%d", &num); sum += (++count % 2 == 1) ? num : -num; } while(sum != 0); printf("Result: %d\n", count); return 0; }