Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add ARM-to-FPGA 32-bit raw I/O example
#include <cstdio> #include <cstdlib> #include <unistd.h> #include <fcntl.h> #include <sys/mman.h> #define FPGA_MANAGER_BASE 0xFF706000 #define FPGA_GPO_OFFSET 0x10 #define FPGA_GPI_OFFSET 0x14 int main() { int dev_mem = open("/dev/mem", O_RDWR); if(dev_mem == 0) { perror("open"); exit(EXIT_FAILURE); } unsigned char *mem = (unsigned char *)mmap(0, 64, PROT_READ | PROT_WRITE, /* MAP_NOCACHE | */ MAP_SHARED , dev_mem, FPGA_MANAGER_BASE); if(mem == 0) { perror("mmap"); exit(EXIT_FAILURE); } volatile unsigned long *gpo = (unsigned long*)(mem + FPGA_GPO_OFFSET); volatile unsigned long *gpi = (unsigned long*)(mem + FPGA_GPI_OFFSET); printf("gpi = 0x%08lX\n", *gpi); *gpo = 0xCAFEBABE; if(1) { long int i = 0; while(1) *gpo = i++; } exit(EXIT_SUCCESS); }
Add dexgrep tool -- grep for class definitions
/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include <cstdio> #include <cstring> #include <cstdlib> #include <getopt.h> #include "DexCommon.h" void print_usage() { fprintf(stderr, "Usage: dexgrep <classname> <dexfile 1> <dexfile 2> ...\n"); } int main(int argc, char* argv[]) { bool files_only = false; char c; static const struct option options[] = { { "files-without-match", no_argument, nullptr, 'l' }, }; while ((c = getopt_long( argc, argv, "hl", &options[0], nullptr)) != -1) { switch (c) { case 'l': files_only = true; break; case 'h': print_usage(); return 0; default: print_usage(); return 1; } } if (optind == argc) { fprintf(stderr, "%s: no dex files given\n", argv[0]); print_usage(); return 1; } const char* search_str = argv[optind]; for (int i = optind + 1; i < argc; ++i) { const char* dexfile = argv[i]; ddump_data rd; open_dex_file(dexfile, &rd); auto size = rd.dexh->class_defs_size; for (uint32_t j = 0; j < size; j++) { dex_class_def* cls_def = rd.dex_class_defs + j; char* name = dex_string_by_type_idx(&rd, cls_def->typeidx); if (strstr(name, search_str) != nullptr) { if (files_only) { printf("%s\n", dexfile); } else { printf("%s: %s\n", dexfile, name); } } } } }
Add Chapter 21, Try This 3
// Chapter 21, Try This 3: define a vector<Record>, initialise it with four // records of your choice, and compute their total price using the functions // given #include "../lib_files/std_lib_facilities.h" #include<numeric> //------------------------------------------------------------------------------ struct Record { Record(double up, int un) : unit_price(up), units(un) { } double unit_price; int units; // number of units sold }; //------------------------------------------------------------------------------ double price(double v, const Record& r) { return v + r.unit_price * r.units; // calculate price and accumulate } //------------------------------------------------------------------------------ void f(const vector<Record>& vr) { double total = accumulate(vr.begin(),vr.end(),0.0,price); cout << "Total is " << total << "\n"; } //------------------------------------------------------------------------------ int main() try { Record rec1 = Record(10.9,15); Record rec2 = Record(25.5,3); Record rec3 = Record(101,75); Record rec4 = Record(5.33,27); vector<Record> vr; vr.push_back(rec1); vr.push_back(rec2); vr.push_back(rec3); vr.push_back(rec4); f(vr); } catch (Range_error& re) { cerr << "bad index: " << re.index << "\n"; } catch (exception& e) { cerr << "exception: " << e.what() << endl; } catch (...) { cerr << "exception\n"; } //------------------------------------------------------------------------------
Add example for MoveFolder operation
// Copyright 2016 otris software AG // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <ews/ews.hpp> #include <ews/ews_test_support.hpp> #include <exception> #include <iostream> #include <ostream> #include <stdlib.h> #include <string> int main() { int res = EXIT_SUCCESS; ews::set_up(); try { const auto env = ews::test::environment(); auto service = ews::service(env.server_uri, env.domain, env.username, env.password); ews::distinguished_folder_id inbox = ews::standard_folder::inbox; ews::distinguished_folder_id trash = ews::standard_folder::deleted_items; auto folder_ids = service.find_folder(inbox); if (!folder_ids.empty()) { // Move the first folder to the deleted items folder auto new_id = service.move_folder(folder_ids.front(), trash); // Move the folder back to the inbox, // using the newly created folder id service.move_folder(new_id, inbox); } } catch (std::exception& exc) { std::cout << exc.what() << std::endl; res = EXIT_FAILURE; } ews::tear_down(); return res; }
Add Chapter 25, exercise 10
// Chapter 25, exercise 10: write an example that initializes a PPN, then reads // and prints each field value, then changes each field value (by assigning to // the field) and prints the result. Repeat, but store the PPN information in a // 32-bit unsigned integer and use bit manipulation operators to access the bits // in the word. #include<iostream> using namespace std; struct PPN { unsigned int PFN : 22; int : 3; unsigned int CCA : 3; bool nonreachable : 1; bool dirty : 1; bool valid : 1; bool global : 1; }; int main() { PPN pn; pn.PFN = 0; pn.CCA = 0; pn.nonreachable = 0; pn.dirty = 0; pn.valid = 0; pn.global = 0; cout << "PFN: " << pn.PFN << '\n' << "CCA: " << pn.CCA << '\n' << "nonreachable: " << pn.nonreachable << '\n' << "dirty: " << pn.dirty << '\n' << "valid: " << pn.valid << '\n' << "global: " << pn.global << '\n'; pn.PFN = 15121; pn.CCA = 6; pn.nonreachable = 1; pn.dirty = 0; pn.valid = 0; pn.global = 1; cout << "\nAfter changing values:\n" << "PFN: " << pn.PFN << '\n' << "CCA: " << pn.CCA << '\n' << "nonreachable: " << pn.nonreachable << '\n' << "dirty: " << pn.dirty << '\n' << "valid: " << pn.valid << '\n' << "global: " << pn.global << '\n'; unsigned int pni = 0; pni = 15121<<10; // PFN pni |= 6<<4; // CCA pni |= 1<<3; // nonreachable pni |= 1; // global cout << "\nUsing an unsigned int:\n" << "PFN: " << ((pni>>10)&0x3fffff) << '\n' << "CCA: " << ((pni>>4)&0x7) << '\n' << "nonreachable: " << ((pni>>3)&1) << '\n' << "dirty: " << ((pni>>2)&1) << '\n' << "valid: " << ((pni>>1)&1) << '\n' << "global: " << (pni&1) << '\n'; }
Add floyd warshall all pairs shortest path
/** * Floyd Warshall's Algorithm for All Pairs shortest path problem */ #include <iostream> #include <limits.h> #define V 4 #define INF INT_MAX using namespace std; void print(int array[][V]) { for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { if (array[i][j] == INF) cout<<"INF "; else cout<<array[i][j]<<" "; } cout<<endl; } } void floyd_warshall(int graph[][V]) { int dist[V][V], i, j, k; for (i = 0; i < V; i++) for(j = 0; j < V; j++) dist[i][j] = graph[i][j]; for (k = 0; k < V; k++) { for (j = 0; j < V; j++) { for (i = 0; i < V; i++) { if (dist[i][k] != INF && dist[k][j] != INF && dist[i][k] + dist[k][j] < dist[i][j]) dist[i][j] = dist[i][k] + dist[k][j]; } } } print(dist); } int main() { int graph[][V] = { {0, 5, INF, 10}, {INF, 0, 3, INF}, {INF, INF, 0, 1}, {INF, INF, INF, 0} }; cout<<"Input Graph: \n"; print(graph); cout<<"Solution: \n"; floyd_warshall(graph); return 0; }
Add solution to problem 10.
/* * Summation of primes * * The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. * * Find the sum of all the primes below two million. */ #include <iostream> #include <numeric> #include <vector> #include "sieve.hpp" constexpr Long limit = 2'000'000; int main(int, char **) { auto primes = sieve(limit - 1); auto sum = std::accumulate(primes.begin(), primes.end(), Long()); std::cout << "Project Euler - Problem 10: Summation of primes\n\n"; std::cout << "The sum of all prime numbers below " << limit << " is\n" << sum << '\n'; }
Add merge sort c++ source code
#include <bits/stdc++.h> using namespace std; void merge(vector<int>& v, int beg1, int half, int beg2){ int szL, szR; szL = half-beg1+1; szR = beg2-half; //create auxiliar arrays; int left[szL], right[szR]; for (int i = 0; i < szL; i++) left[i] = v[beg1 + i]; for (int i = 0; i < szR; i++) right[i] = v[half + 1 + i]; //merge aux into v int i= 0, j= 0, k= beg1; while (i<szL && j<szR) v[k++] = (left[i]<right[j])?left[i++]:right[j++]; while (i < szL) v[k++] = left[i++]; while (j < szR) v[k++] = right[j++]; } void mergeSort(vector<int>& v, int l, int r){ if (l >= r) return; int half = l+(r-l)/2; mergeSort(v, l, half); mergeSort(v, half+1, r); merge(v, l, half, r); }
Upgrade Blink to milliseconds-based last modified filetimes, part 6.
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/child/file_info_util.h" #include "base/logging.h" #include "third_party/WebKit/public/platform/WebFileInfo.h" namespace content { void FileInfoToWebFileInfo(const base::File::Info& file_info, blink::WebFileInfo* web_file_info) { DCHECK(web_file_info); // Blink now expects NaN as uninitialized/null Date. if (file_info.last_modified.is_null()) { web_file_info->modificationTime = std::numeric_limits<double>::quiet_NaN(); web_file_info->modificationTimeMS = std::numeric_limits<double>::quiet_NaN(); } else { web_file_info->modificationTime = file_info.last_modified.ToJsTime(); web_file_info->modificationTimeMS = file_info.last_modified.ToJsTime(); } web_file_info->length = file_info.size; if (file_info.is_directory) web_file_info->type = blink::WebFileInfo::TypeDirectory; else web_file_info->type = blink::WebFileInfo::TypeFile; } static_assert(std::numeric_limits<double>::has_quiet_NaN, "should have quiet NaN"); } // namespace content
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/child/file_info_util.h" #include "base/logging.h" #include "third_party/WebKit/public/platform/WebFileInfo.h" namespace content { void FileInfoToWebFileInfo(const base::File::Info& file_info, blink::WebFileInfo* web_file_info) { DCHECK(web_file_info); // Blink now expects NaN as uninitialized/null Date. if (file_info.last_modified.is_null()) web_file_info->modificationTime = std::numeric_limits<double>::quiet_NaN(); else web_file_info->modificationTime = file_info.last_modified.ToJsTime(); web_file_info->length = file_info.size; if (file_info.is_directory) web_file_info->type = blink::WebFileInfo::TypeDirectory; else web_file_info->type = blink::WebFileInfo::TypeFile; } static_assert(std::numeric_limits<double>::has_quiet_NaN, "should have quiet NaN"); } // namespace content
Add convolutional auto encoder unit test
//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <deque> #include "dll_test.hpp" #include "dll/neural/conv_layer.hpp" #include "dll/neural/deconv_layer.hpp" #include "dll/pooling/mp_layer.hpp" #include "dll/pooling/upsample_layer.hpp" #include "dll/dbn.hpp" #include "dll/trainer/stochastic_gradient_descent.hpp" #include "mnist/mnist_reader.hpp" #include "mnist/mnist_utils.hpp" TEST_CASE("conv/ae/1", "[dense][dbn][mnist][sgd][ae]") { typedef dll::dbn_desc< dll::dbn_layers< dll::conv_desc<1, 28, 28, 2, 5, 5, dll::activation<dll::function::SIGMOID>>::layer_t, dll::mp_layer_3d_desc<2, 24, 24, 1, 2, 2>::layer_t, dll::upsample_layer_3d_desc<2, 12, 12, 1, 2, 2>::layer_t, dll::deconv_desc<2, 24, 24, 1, 5, 5, dll::activation<dll::function::SIGMOID>>::layer_t >, dll::trainer<dll::sgd_trainer>, dll::batch_size<20>>::dbn_t dbn_t; auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 1, 28, 28>>(1000); REQUIRE(!dataset.training_images.empty()); dll_test::mnist_scale(dataset); auto dbn = std::make_unique<dbn_t>(); dbn->display(); dbn->learning_rate = 0.1; auto ft_error = dbn->fine_tune_ae(dataset.training_images, 25); std::cout << "ft_error:" << ft_error << std::endl; CHECK(ft_error < 0.3); auto test_error = dll::test_set_ae(*dbn, dataset.test_images); std::cout << "test_error:" << test_error << std::endl; REQUIRE(test_error < 0.3); }
Add some useful ecuations over a circle.
//Some useful equations int main(){ //area portion of a circle A = pi*r^2 * (theta/(2*pi)) //area chord of a circle A = R * R * acos((R - h)/R) - (R - h) * sqrt(2 * R * h - h * h) // h is the height of the chord }
Set default values for datatype & pixelformat.
#include <osgDB/ImageOptions> using namespace osgDB; ImageOptions::ImageOptions() { init(); } ImageOptions::ImageOptions(const std::string& str) { init(); _str = str; } void ImageOptions::init() { _sourceImageSamplingMode = NEAREST; _sourceImageWindowMode = ALL_IMAGE; _destinationImageWindowMode = ALL_IMAGE; }
#include <osgDB/ImageOptions> using namespace osgDB; ImageOptions::ImageOptions() { init(); } ImageOptions::ImageOptions(const std::string& str) { init(); _str = str; } void ImageOptions::init() { _sourceImageSamplingMode = NEAREST; _sourceImageWindowMode = ALL_IMAGE; _destinationImageWindowMode = ALL_IMAGE; _destinationDataType = GL_NONE; _destinationPixelFormat = GL_NONE; }
Test file for CFMM tree added.
#include "fastlib/fastlib.h" #include "fastlib/tree/statistic.h" #include "general_spacetree.h" #include "contrib/dongryel/fast_multipole_method/fmm_stat.h" #include "subspace_stat.h" #include "cfmm_tree.h" #include "mlpack/kde/dataset_scaler.h" int main(int argc, char *argv[]) { fx_init(argc, argv, NULL); const char *fname = fx_param_str_req(NULL, "data"); Matrix dataset; data::Load(fname, &dataset); int leaflen = fx_param_int(NULL, "leaflen", 30); int min_required_ws_index = fx_param_int(NULL, "min_ws_index", 2); printf("Constructing the tree...\n"); fx_timer_start(NULL, "cfmm_tree_build"); ArrayList<Matrix *> matrices; matrices.Init(1); matrices[0] = &dataset; ArrayList<Vector *> targets; const char *target_fname = fx_param_str_req(NULL, "target"); Matrix target_incoming; data::Load(target_fname, &target_incoming); Vector target; target.Init(target_incoming.n_cols()); for(index_t i = 0; i < target.length(); i++) { target[i] = target_incoming.get(0, i); } targets.Init(1); targets[0] = &target; ArrayList< ArrayList<index_t> > old_from_new; ArrayList< ArrayList<proximity::CFmmTree< EmptyStatistic<Matrix> > *> > nodes_in_each_level; proximity::CFmmTree<EmptyStatistic<Matrix> > *root; root = proximity::MakeCFmmTree (matrices, targets, leaflen, min_required_ws_index, 2, &nodes_in_each_level, &old_from_new); fx_timer_stop(NULL, "cfmm_tree_build"); for(index_t i = 0; i < nodes_in_each_level.size(); i++) { for(index_t j = 0; j < nodes_in_each_level[i].size(); j++) { printf("%u ", (nodes_in_each_level[i][j])->node_index()); } printf("\n"); } printf("Finished constructing the tree...\n"); // Print the tree. root->Print(); // Clean up the memory used by the tree... delete root; fx_done(fx_root); return 0; }
Add unittests for summary requests
#include "gtest/gtest.h" #include <typeinfo> #include "request_message.h" #include "requests.pb.h" class TypeVisitor : public traffic::RequestVisitor { public: enum Type { SUMMARY, STATISTIC, ERROR, NOTSET }; private: Type _t; protected: void visit(traffic::StatisticRequest const &) { _t = STATISTIC; } void visit(traffic::SummaryRequest const &) { _t = SUMMARY; } void visit(traffic::ErrorRequest const &) { _t = ERROR; } public: TypeVisitor() : _t(NOTSET) { } Type visited() const { return _t; } }; std::string summary_message() { requests::Request req; req.set_version(1); requests::Summary *summary(req.mutable_summary()); summary->mutable_range()->set_start(1UL); summary->mutable_range()->set_end(2UL); summary->add_addresses("peng1"); summary->add_addresses("peng2"); summary->add_addresses("peng3"); summary->add_addresses("peng4"); return req.SerializeAsString(); } // Test that basic message serializing work TEST(MessagesRequest, deserialize_summary_request) { std::string bytes(summary_message()); traffic::RequestMessage::ptr_t msg( traffic::RequestMessage::parse_message(bytes.c_str(), bytes.size())); ASSERT_EQ(typeid(traffic::SummaryRequest), typeid(*msg)); TypeVisitor v; msg->accept(v); ASSERT_EQ(TypeVisitor::SUMMARY, v.visited()); traffic::SummaryRequest* summary(dynamic_cast<traffic::SummaryRequest*>(msg.get())); ASSERT_NE(nullptr, summary); EXPECT_EQ(1, summary->range().start()); EXPECT_EQ(2, summary->range().end()); ASSERT_EQ(4U, summary->addresses().size()); EXPECT_EQ("peng1", summary->addresses().at(0)); EXPECT_EQ("peng2", summary->addresses().at(1)); EXPECT_EQ("peng3", summary->addresses().at(2)); EXPECT_EQ("peng4", summary->addresses().at(3)); } /** * Shut down the protobuf library after the tests to make valgrind happy */ namespace { class ShutdownEnvironment : public ::testing::Environment { public: void TearDown() { google::protobuf::ShutdownProtobufLibrary(); } }; #ifndef NDEBUG ::testing::Environment* const shutdown_env = ::testing::AddGlobalTestEnvironment(new ShutdownEnvironment); #endif }
Test of rendering text as outlines
#if defined(HAVE_CAIRO) #include "catch.hpp" #include <mapnik/map.hpp> #include <mapnik/load_map.hpp> #include <mapnik/cairo/cairo_renderer.hpp> #include <sstream> #include <cairo-pdf.h> static cairo_status_t write( void *closure, const unsigned char *data, unsigned int length) { std::ostream & ss = *static_cast<std::ostream*>(closure); ss.write(reinterpret_cast<char const *>(data), length); return ss ? CAIRO_STATUS_SUCCESS : CAIRO_STATUS_WRITE_ERROR; } static void render(std::ostream & output, bool text_outlines) { const std::string map_style = R"STYLE( <Map> <Style name="1"> <Rule> <TextSymbolizer placement="point" face-name="DejaVu Sans Book" > "Text" </TextSymbolizer> </Rule> </Style> <Layer name="1"> <StyleName>1</StyleName> <Datasource> <Parameter name="type">csv</Parameter> <Parameter name="inline"> x, y 0, 0 </Parameter> </Datasource> </Layer> </Map> )STYLE"; mapnik::Map map(256, 256); mapnik::load_map_string(map, map_style); const std::string fontdir("fonts"); REQUIRE(map.register_fonts(fontdir, true)); const mapnik::box2d<double> bbox(-1, -1, 1, 1); map.zoom_to_box(bbox); mapnik::cairo_surface_ptr surface( // It would be better to use script surface, // but it's not included in the Mason Cairo library. cairo_pdf_surface_create_for_stream( write, &output, map.width(), map.height()), mapnik::cairo_surface_closer()); mapnik::cairo_ptr image_context( mapnik::create_context(surface)); mapnik::cairo_renderer<mapnik::cairo_ptr> ren( map, image_context, 1.0, 0, 0, text_outlines); ren.apply(); cairo_surface_finish(&*surface); } TEST_CASE("cairo_renderer") { SECTION("text_outlines") { { std::stringstream output; render(output, true); // Output should not contain any fonts CHECK(output.str().find("/Font") == std::string::npos); } { std::stringstream output; render(output, false); // Check fonts are there if text_outlines == false CHECK(output.str().find("/Font") != std::string::npos); } } } #endif
Add serialization tests for entities.
#include "gtest/gtest.h" #include "src/common/entity/Block.h" #include "src/common/entity/Bomb.h" #include "src/common/entity/Bonus.h" #include "src/common/entity/Character.h" #include "src/common/entity/Fire.h" #include "src/common/entity/Wall.h" #include "src/common/net/Deserializer.h" using namespace common::entity; using namespace common::net; TEST(EntitySerializationTest, Serialization) { QByteArray buffer; QDataStream in(&buffer, QIODevice::OpenModeFlag::WriteOnly); QDataStream out(&buffer, QIODevice::OpenModeFlag::ReadOnly); Block block(QPoint(1,2)); in << block; auto block_out = Deserializer::DeserializeEntity(out); EXPECT_EQ(block, *static_cast<Block*>(block_out.get())); Bomb bomb(QPoint(3,4), 123, 456, 2); in << bomb; auto bomb_out = Deserializer::DeserializeEntity(out); EXPECT_EQ(bomb, *static_cast<Bomb*>(bomb_out.get())); Bonus bonus(QPoint(1,2)); in << bonus; auto bonus_out = Deserializer::DeserializeEntity(out); EXPECT_EQ(bonus, *static_cast<Bonus*>(bonus_out.get())); Character character(QPoint(5,4), 2, 5, 3); in << character; auto character_out = Deserializer::DeserializeEntity(out); EXPECT_EQ(character, *static_cast<Character*>(character_out.get())); Fire fire(QPoint(8,9), 456); in << fire; auto fire_out = Deserializer::DeserializeEntity(out); EXPECT_EQ(fire, *static_cast<Fire*>(fire_out.get())); Wall wall(QPoint(5,4)); in << wall; auto wall_out = Deserializer::DeserializeEntity(out); EXPECT_EQ(wall, *static_cast<Wall*>(wall_out.get())); }
Copy List with Random Pointer
/** * Definition for singly-linked list with a random pointer. * struct RandomListNode { * int label; * RandomListNode *next, *random; * RandomListNode(int x) : label(x), next(NULL), random(NULL) {} * }; */ class Solution { public: RandomListNode *copyRandomList(RandomListNode *head) { if(!head) return NULL; unordered_map<RandomListNode*, RandomListNode*> m; RandomListNode *cur=head; RandomListNode *newhead=new RandomListNode(head->label); RandomListNode *newh=newhead; m[cur]=newh; while(cur->next){ cur=cur->next; newh->next=new RandomListNode(cur->label); m[cur]=newh->next; newh=newh->next; } cur=head; newh=newhead; while(cur){ if(cur->random==NULL){ newh->random=NULL; }else{ newh->random=m[cur->random]; } cur=cur->next; newh=newh->next; } return newhead; } };
Add Naive find over strings.
#include <bits/stdc++.h> using namespace std; int main(){ string needle = "CD", haystack ="MANICD"; if(haystack.find(needle) != string::npos) cout << "Gotcha!!!"; else cout << "Not Gotcha"; cout << endl; return 0; }
Create unit test file for datastore api
#include "stdafx.h" #include "CppUnitTest.h" using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; namespace You { namespace DataStore { namespace UnitTests { TEST_CLASS(DataStoreApiTest) { public: //TEST_METHOD(TestMethod1) { // // TODO: Your test code here //} }; } // namespace UnitTests } // namespace DataStore } // namespace You
Add unit test for acc::getAccDevProps
/* Copyright 2020 Sergei Bastrakov * * This file is part of alpaka. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <alpaka/acc/AccDevProps.hpp> #include <alpaka/acc/Traits.hpp> #include <alpaka/test/acc/TestAccs.hpp> #include <catch2/catch.hpp> //----------------------------------------------------------------------------- TEMPLATE_LIST_TEST_CASE( "getAccDevProps", "[acc]", alpaka::test::acc::TestAccs) { using Acc = TestType; using Dev = alpaka::dev::Dev<Acc>; using Pltf = alpaka::pltf::Pltf<Dev>; Dev const dev(alpaka::pltf::getDevByIdx<Pltf>(0u)); auto const devProps = alpaka::acc::getAccDevProps<Acc>(dev); REQUIRE(devProps.m_gridBlockExtentMax.prod() > 0); // Note: this causes signed overflow for some configurations, // will be fixed separately // REQUIRE(devProps.m_blockThreadExtentMax.prod() > 0); REQUIRE(devProps.m_threadElemExtentMax.prod() > 0); REQUIRE(devProps.m_gridBlockCountMax > 0); REQUIRE(devProps.m_blockThreadCountMax > 0); REQUIRE(devProps.m_threadElemCountMax > 0); REQUIRE(devProps.m_multiProcessorCount > 0); REQUIRE(devProps.m_sharedMemSizeBytes > 0); }
Fix build. Forgot to explictly add file while patching. BUG=none TEST=none TBR=rsleevi
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/test/webdriver/commands/response.h" #include "base/json/json_writer.h" #include "base/logging.h" #include "base/values.h" namespace webdriver { namespace { // Error message taken from: // http://code.google.com/p/selenium/wiki/JsonWireProtocol#Response_Status_Codes const char* const kStatusKey = "status"; const char* const kValueKey = "value"; const char* const kMessageKey = "message"; const char* const kScreenKey = "screen"; const char* const kClassKey = "class"; const char* const kStackTraceFileNameKey = "stackTrace.fileName"; const char* const kStackTraceLineNumberKey = "stackTrace.lineNumber"; } // namespace Response::Response() { SetStatus(kSuccess); SetValue(Value::CreateNullValue()); } Response::~Response() {} ErrorCode Response::GetStatus() const { int status; if (!data_.GetInteger(kStatusKey, &status)) NOTREACHED(); return static_cast<ErrorCode>(status); } void Response::SetStatus(ErrorCode status) { data_.SetInteger(kStatusKey, status); } const Value* Response::GetValue() const { Value* out = NULL; LOG_IF(WARNING, !data_.Get(kValueKey, &out)) << "Accessing unset response value."; // Should never happen. return out; } void Response::SetValue(Value* value) { data_.Set(kValueKey, value); } void Response::SetError(ErrorCode error_code, const std::string& message, const std::string& file, int line) { DictionaryValue* error = new DictionaryValue; error->SetString(kMessageKey, message); error->SetString(kStackTraceFileNameKey, file); error->SetInteger(kStackTraceLineNumberKey, line); SetStatus(error_code); SetValue(error); } void Response::SetField(const std::string& key, Value* value) { data_.Set(key, value); } std::string Response::ToJSON() const { std::string json; base::JSONWriter::Write(&data_, false, &json); return json; } } // namespace webdriver
Add pallindromic substring algorithm to find if a substring of a string is pallindrome or not.
#include <bits/stdc++.h> using namespace std; vector< vector<bool> > dp; string s; void preprocess() { int n = s.size(); //single letter is always a pallindrome for(int i = 0; i < n; ++i) dp[i][i] = true; //if adjacent letters are same then they are pallindrome for(int i = 0; i < n - 1; ++i) if(s[i] == s[i + 1]) dp[i][i + 1] = true; //if s[i] == s[j] and between i + 1 and j - 1 is pallindrome //then from i to j is also a pallindrome for(int gap = 2; gap < n; ++gap) { for(int i = 0; i + gap < n; ++i) { int j = gap + i; if(s[i] == s[j] and dp[i + 1][j - 1]) dp[i][j] = true; } } } bool is_pallindrome(int l, int r) { return dp[l][r]; } int main() { std :: ios_base :: sync_with_stdio(false); cin.tie(NULL), cout.tie(NULL); cin >> s; dp.assign(s.size(), vector<bool>(s.size(), false)); preprocess(); int l, r; cin >> l >> r; l--, r--; if(is_pallindrome(l, r)) cout << "Substring is a pallindrome" << endl; else cout << "Substring is not a pallindrome" << endl; }
Use test font manager for SVG fuzzer
/* * Copyright 2020 Google, LLC * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "fuzz/Fuzz.h" void fuzz_SVGCanvas(Fuzz* f); extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { auto fuzz = Fuzz(SkData::MakeWithoutCopy(data, size)); fuzz_SVGCanvas(&fuzz); return 0; }
/* * Copyright 2020 Google, LLC * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "fuzz/Fuzz.h" #include "src/core/SkFontMgrPriv.h" #include "tools/fonts/TestFontMgr.h" void fuzz_SVGCanvas(Fuzz* f); extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { gSkFontMgr_DefaultFactory = &ToolUtils::MakePortableFontMgr; auto fuzz = Fuzz(SkData::MakeWithoutCopy(data, size)); fuzz_SVGCanvas(&fuzz); return 0; }
Test source file - initial commit.
#include "naive_bayes.h" #include <iostream> int main(int argc, char* argv[]) { NaiveBayes nb; nb.set_training_data_file(std::string("training.dat")); nb.add_training_data("Buy cheap viagra SPAM"); nb.add_training_data("Buy cheap airlines airlines tickets HAM"); nb.add_training_data("Dear friend I am the king of Persia king SPAM"); nb.add_training_data("Hello friend I am from Persia you must be from New York HAM"); nb.add_training_data("Hi friend how are you doing I love you HAM"); nb.add_training_data("New York is a big city HAM"); nb.train(); std::string class_ = nb.classify(std::string("Buy cheap viagra tickets")); std::cout << "Your message is " << class_ << std::endl; class_ = nb.classify(std::string("Hello friend how are you")); std::cout << "Your message is " << class_ << std::endl; class_ = nb.classify(std::string("Dhaka is a big city")); std::cout << "Your message is " << class_ << std::endl; return 0; }
Define the methods declared in read-and-write-data header file
#include <read_and_write_data.h> using namespace std; void importData(FileReader &reader, vector<DataObject> &data) { // Definition goes here!! } void exportData(FileWriter &writer, const vector<DataObject> &data) { // Definition goes here!! }
Add a C++ test. Just using C things now
#include <rmc.h> // Ok first make sure the regular old C ones still work void mp_send(rmc_int *flag, rmc_int *data) { VEDGE(wdata, wflag); L(wdata, rmc_store(data, 42)); L(wflag, rmc_store(flag, 1)); } int mp_recv(rmc_int *flag, int *data) { int rf; XEDGE(rflag, rdata); do { LS(rflag, rf = rmc_load(flag)); } while (rf == 0); LS(rdata, int rd = *data); return rd; }
Add example to read tracks from binary output file
#include <stdio.h> #include <stdlib.h> #include <vector> #include "outputtrack.h" int main(int argc, char** argv) { FILE* fpInput = fopen("../output.bin", "rb"); if (fpInput == NULL) { printf("Error opening input file\n"); exit(1); } //Loop over all events in the input file. //Number of events is not stored int the file, but we just read until we reach the end of file. //All values stored in the file are either int or float, so 32 bit. //Thus, we do not need to care about alignment. The same data structures must be used again for reading the file. int nEvents = 0; std::vector<unsigned int> ClusterIDs; while (!feof(fpInput)) { int numTracks; //Must be int! OutputTrack track; fread(&numTracks, sizeof(numTracks), 1, fpInput); printf("Event: %d, Number of tracks: %d\n", nEvents, numTracks); for (int iTrack = 0;iTrack < numTracks;iTrack++) { fread(&track, sizeof(track), 1, fpInput); printf("Track %d Parameters: Alpha %f, X %f, Y %f, Z %f, SinPhi %f, DzDs %f, Q/Pt %f, Number of clusters %d, Fit OK %d\n", iTrack, track.Alpha, track.X, track.Y, track.Z, track.SinPhi, track.DzDs, track.QPt, track.NClusters, track.FitOK); if (track.NClusters > ClusterIDs.size()) ClusterIDs.resize(track.NClusters); fread(&ClusterIDs[0], sizeof(ClusterIDs[0]), track.NClusters, fpInput); printf("Cluster IDs:"); for (int iCluster = 0;iCluster < track.NClusters;iCluster++) { printf(" %d", ClusterIDs[iCluster]); } printf("\n"); } nEvents++; } fclose(fpInput); }
Replace std::shared_ptr with pointer and make the constructor explicit
#include "EntityManager.h" namespace zmc { EntityManager::EntityManager(std::shared_ptr<ComponentManager> componentManager) : mLastEntityID(0) , mComponentManager(componentManager) { } EntityManager::~EntityManager() { } int EntityManager::getEntityCount() { return mEntityMap.size(); } void EntityManager::removeEntity(int entityID) { auto found = mEntityMap.find(entityID); //No entity if (found == mEntityMap.end()) return; mEntityMap.erase(entityID); } void EntityManager::removeEntitiesInGroup(int groupIdentifier) { for (std::pair<const int, std::unique_ptr<BaseEntity>> &pair : mEntityMap) { if (pair.second->getGroup() == groupIdentifier) mEntityMap.erase(pair.second->getEntityID()); } } std::vector<BaseEntity *> EntityManager::getEntitiesInGroup(int groupIdentifier) { std::vector<BaseEntity*> group; for (std::pair<const int, std::unique_ptr<BaseEntity>> &pair : mEntityMap) { if (pair.second->getGroup() == groupIdentifier) { group.push_back(mEntityMap.at(pair.second->getEntityID()).get()); } } return group; } }
#include "EntityManager.h" namespace zmc { EntityManager::EntityManager(ComponentManager *componentManager) : mLastEntityID(0) , mComponentManager(componentManager) { } EntityManager::~EntityManager() { } int EntityManager::getEntityCount() { return mEntityMap.size(); } void EntityManager::removeEntity(int entityID) { auto found = mEntityMap.find(entityID); //No entity if (found == mEntityMap.end()) return; mEntityMap.erase(entityID); } void EntityManager::removeEntitiesInGroup(int groupIdentifier) { for (std::pair<const int, std::unique_ptr<BaseEntity>> &pair : mEntityMap) { if (pair.second->getGroup() == groupIdentifier) mEntityMap.erase(pair.second->getEntityID()); } } std::vector<BaseEntity *> EntityManager::getEntitiesInGroup(int groupIdentifier) { std::vector<BaseEntity*> group; for (std::pair<const int, std::unique_ptr<BaseEntity>> &pair : mEntityMap) { if (pair.second->getGroup() == groupIdentifier) { group.push_back(mEntityMap.at(pair.second->getEntityID()).get()); } } return group; } }
Add a test for Neon vector mangling
// RUN: %clang_cc1 %s -emit-llvm -o - | FileCheck %s typedef float float32_t; typedef signed char poly8_t; typedef short poly16_t; typedef unsigned long long uint64_t; typedef __attribute__((neon_vector_type(2))) int int32x2_t; typedef __attribute__((neon_vector_type(4))) int int32x4_t; typedef __attribute__((neon_vector_type(1))) uint64_t uint64x1_t; typedef __attribute__((neon_vector_type(2))) uint64_t uint64x2_t; typedef __attribute__((neon_vector_type(2))) float32_t float32x2_t; typedef __attribute__((neon_vector_type(4))) float32_t float32x4_t; typedef __attribute__((neon_polyvector_type(16))) poly8_t poly8x16_t; typedef __attribute__((neon_polyvector_type(8))) poly16_t poly16x8_t; // CHECK: 16__simd64_int32_t void f1(int32x2_t v) { } // CHECK: 17__simd128_int32_t void f2(int32x4_t v) { } // CHECK: 17__simd64_uint64_t void f3(uint64x1_t v) { } // CHECK: 18__simd128_uint64_t void f4(uint64x2_t v) { } // CHECK: 18__simd64_float32_t void f5(float32x2_t v) { } // CHECK: 19__simd128_float32_t void f6(float32x4_t v) { } // CHECK: 17__simd128_poly8_t void f7(poly8x16_t v) { } // CHECK: 18__simd128_poly16_t void f8(poly16x8_t v) { }
Add test forgotten in r181388.
// RUN: %clang_cc1 -std=c++1y -fsyntax-only -verify %s -DMAX=1234 -fconstexpr-steps 1234 // RUN: %clang_cc1 -std=c++1y -fsyntax-only -verify %s -DMAX=10 -fconstexpr-steps 10 // RUN: %clang -std=c++1y -fsyntax-only -Xclang -verify %s -DMAX=12345 -fconstexpr-steps=12345 // This takes a total of n + 4 steps according to our current rules: // - One for the compound-statement that is the function body // - One for the 'for' statement // - One for the 'int k = 0;' statement // - One for each of the n evaluations of the compound-statement in the 'for' body // - One for the 'return' statemnet constexpr bool steps(int n) { for (int k = 0; k != n; ++k) {} return true; // expected-note {{step limit}} } static_assert(steps((MAX - 4)), ""); // ok static_assert(steps((MAX - 3)), ""); // expected-error {{constant}} expected-note{{call}}
Solve problem 21 in C++
// Copyright 2016 Mitchell Kember. Subject to the MIT License. // Project Euler: Problem 21 // Amicable numbers #include "common.hpp" #include <array> namespace problem_21 { long solve() { typedef std::vector<long>::size_type sz_t; constexpr sz_t max = 10000; std::vector<long> sums(max); for (sz_t i = 1; i < max; ++i) { sums[i] = common::sum_proper_divisors(static_cast<long>(i)); } long total = 0; for (sz_t i = 1; i < max; ++i) { sz_t si = static_cast<sz_t>(sums[i]); if (i < si && si < max && static_cast<sz_t>(sums[si]) == i) { total += i; total += si; } } return total; } } // namespace problem_21
Add unit tests for matrices
// This file is distributed under the MIT license. // See the LICENSE file for details. #include <cassert> #include <visionaray/math/math.h> #include <gtest/gtest.h> using namespace visionaray; //------------------------------------------------------------------------------------------------- // Helper functions // // nested for loop over matrices -------------------------- template <typename Func> void for_each_mat4_e(Func f) { for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { f(i, j); } } } // get rows and columns ----------------------------------- vec4 get_row(mat4 const& m, int i) { assert( i >= 0 && i < 4 ); return vec4( m(i, 0), m(i, 1), m(i, 2), m(i, 3) ); } vec4 get_col(mat4 const& m, int j) { assert( j >= 0 && j < 4 ); return m(j); } TEST(Matrix, Inverse) { //------------------------------------------------------------------------- // mat4 // mat4 I = mat4::identity(); // make some non-singular matrix mat4 A = make_rotation(vec3(1, 0, 0), constants::pi<float>() / 4); mat4 B = inverse(A); mat4 C = A * B; for_each_mat4_e( [&](int i, int j) { EXPECT_FLOAT_EQ(C(i, j), I(i, j)); } ); } TEST(Matrix, Mult) { //------------------------------------------------------------------------- // mat4 // // make some non-singular matrices mat4 A = make_rotation(vec3(1, 0, 0), constants::pi<float>() / 4); mat4 B = make_translation(vec3(3, 4, 5)); mat4 C = A * B; for_each_mat4_e( [&](int i, int j) { float d = dot(get_row(A, i), get_col(B, j)); EXPECT_FLOAT_EQ(C(i, j), d); } ); } TEST(Matrix, Transpose) { //------------------------------------------------------------------------- // mat4 // // make some non-singular matrix mat4 A = make_rotation(vec3(1, 0, 0), constants::pi<float>() / 4); mat4 B = transpose(A); for_each_mat4_e( [&](int i, int j) { EXPECT_FLOAT_EQ(A(i, j), B(j, i)); } ); }
Test harness for the HtmlParser class.
// Test harness for the HtmlParser class. #include <iostream> #include <cstdlib> #include "FileUtil.h" #include "HtmlParser.h" #include "util.h" void Usage() { std::cerr << "Usage: " << ::progname << " html_filename\n"; std::exit(EXIT_FAILURE); } class Parser: public HtmlParser { public: Parser(const std::string &document): HtmlParser(document) { } virtual void notify(const HtmlParser::Chunk &chunk); }; void Parser::notify(const HtmlParser::Chunk &chunk) { std::cout << chunk.toString() << '\n'; } int main(int argc, char *argv[]) { ::progname = argv[1]; if (argc != 2) Usage(); try { const std::string input_filename(argv[1]); std::string html_document; if (not FileUtil::ReadString(input_filename, &html_document)) ERROR("failed to read an HTML document from \"" + input_filename + "\"!"); Parser parser(html_document); parser.parse(); } catch (const std::exception &x) { ERROR(x.what()); } }
Add test case that exposes the out of bound errors in apply split
#include "Halide.h" #include "test/common/check_call_graphs.h" #include <stdio.h> using namespace Halide; int main(int argc, char **argv) { Func f("f"), input("input"); Var x("x"), y("y"), c("c"); f(x, y, c) = x + y + c; f.reorder(c, x, y); Var yo("yo"), yi("yi"); f.split(y, yo, yi, 2, TailStrategy::RoundUp); Var yoo("yoo"), yoi("yoi"); f.split(yo, yoo, yoi, 64, TailStrategy::GuardWithIf); Buffer<int> im = f.realize(3000, 2000, 3); auto func = [](int x, int y, int c) { return x + y + c; }; if (check_image(im, func)) { return -1; } return 0; }
Set up the bare structure of the source
/********************************************************************* ** Author: Zach Colbert ** Date: 27 September 2017 ** Description: A simple input/output program with mathematical operations. By prompting the user for three floats, the program will calculate and output a sum. *********************************************************************/ #include <iostream> using namespace std; // A simple input/output program with mathematical operations. int main() { }
Add a test case for PR17575.
// RUN: %clang_cc1 -fsyntax-only -verify %s // expected-no-diagnostics void bar(); namespace foo { using ::bar; } using foo::bar; void bar() {} void f(); using ::f; void f() {}
Add unit test for Character class
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <Utils/TestUtils.hpp> #include "gtest/gtest.h" #include <Rosetta/Games/Game.hpp> #include <Rosetta/Models/Character.hpp> using namespace RosettaStone; using namespace TestUtils; TEST(Character, Health) { GameConfig config; config.player1Class = CardClass::ROGUE; config.player2Class = CardClass::PALADIN; config.startPlayer = PlayerType::PLAYER1; config.doFillDecks = true; config.autoRun = false; Game game(config); game.StartGame(); game.ProcessUntil(Step::MAIN_START); Player& curPlayer = game.GetCurrentPlayer(); auto& curField = curPlayer.GetFieldZone(); auto card1 = GenerateMinionCard("minion1", 3, 6); PlayMinionCard(curPlayer, card1); EXPECT_EQ(curField[0]->GetHealth(), 6); curField[0]->SetDamage(2); EXPECT_EQ(curField[0]->GetHealth(), 4); curField[0]->SetHealth(8); EXPECT_EQ(curField[0]->GetDamage(), 0); EXPECT_EQ(curField[0]->GetHealth(), 8); curField[0]->SetHealth(0); EXPECT_EQ(curField[0]->isDestroyed, true); } TEST(Character, SpellPower) { GameConfig config; config.player1Class = CardClass::ROGUE; config.player2Class = CardClass::PALADIN; config.startPlayer = PlayerType::PLAYER1; config.doFillDecks = true; config.autoRun = false; Game game(config); game.StartGame(); game.ProcessUntil(Step::MAIN_START); Player& curPlayer = game.GetCurrentPlayer(); auto& curField = curPlayer.GetFieldZone(); auto card1 = GenerateMinionCard("minion1", 3, 6); PlayMinionCard(curPlayer, card1); EXPECT_EQ(curField[0]->GetSpellPower(), 0); curField[0]->SetSpellPower(4); EXPECT_EQ(curField[0]->GetSpellPower(), 4); }
Add a (currently failing) RTTI layout test.
// RUN: %clang_cc1 %s -triple=x86_64-apple-darwin10 -emit-llvm -O3 -o - | FileCheck %s #include <typeinfo> class __pbase_type_info : public std::type_info { public: unsigned int __flags; const std::type_info *__pointee; enum __masks { __const_mask = 0x1, __volatile_mask = 0x2, __restrict_mask = 0x4, __incomplete_mask = 0x8, __incomplete_class_mask = 0x10 }; }; template<typename T> const T& to(const std::type_info &info) { return static_cast<const T&>(info); } struct Incomplete; // CHECK: define i32 @_Z1fv() int f() { if (to<__pbase_type_info>(typeid(Incomplete *)).__flags != __pbase_type_info::__incomplete_mask) return 1; // Success! return 0; } #ifdef HARNESS extern "C" void printf(const char *, ...); int main() { int result = f(); if (result == 0) printf("success!\n"); else printf("test %d failed!\n", result); return result; } #endif
Test for llvm-gcc commit 81037.
// RUN: %llvmgxx %s -emit-llvm -fapple-kext -S -o - // The extra check in 71555 caused this to crash on Darwin X86 // in an assert build. class foo { virtual ~foo (); }; foo::~foo(){}
Add testing code for min-counting.
#include "cmbf.h" #include <unordered_map> using namespace sketch::cmbf; int main(int argc, char *argv[]) { cmbf_exp_t thing(4, 16, 1); cmbf_t thingexact(4, 16, 5); auto [x, y] = thing.est_memory_usage(); std::fprintf(stderr, "stack space: %zu\theap space:%zu\n", x, y); size_t nitems = argc > 1 ? std::strtoull(argv[1], nullptr, 10): 100000; std::vector<uint64_t> items; std::mt19937_64 mt; while(items.size() < nitems) items.emplace_back(mt()); for(const auto el: thing.ref()) { assert(unsigned(el) == 0); } auto &ref = thing.ref(); for(const auto item: items) thing.add_conservative(item), thingexact.add_conservative(item); //, std::fprintf(stderr, "Item %" PRIu64 " has count %u\n", item, unsigned(thing.est_count(item))); std::unordered_map<uint64_t, uint64_t> histexact, histapprox; for(const auto j: items) { //std::fprintf(stderr, "est count: %zu\n", size_t(thing.est_count(j))); ++histapprox[thing.est_count(j)]; ++histexact[thingexact.est_count(j)]; } for(const auto &pair: histexact) { std::fprintf(stderr, "Exact %" PRIu64 "\t%" PRIu64 "\n", pair.first, pair.second); } for(const auto &pair: histapprox) { std::fprintf(stderr, "Approx %" PRIu64 "\t%" PRIu64 "\n", pair.first, pair.second); } }
Print alignment and size of fundamantal and user-defined types
#include <iostream> #include <iomanip> #include <type_traits> #include <typeinfo> #include <typeindex> class A { }; class A1 { char c; }; class A2 { char c1; char c2; }; class B { char c; int i; }; class C { char c; int i; double d; }; class D { int i; char c; double d; }; class E { char c[6]; int i; double d; }; class F { char c[6]; int i; }; using namespace std; template<class T> class AlignmentSizeInfo; template <class T> ostream& operator<<(ostream& out, const AlignmentSizeInfo<T>& alignsize) { out << right << setw(3) << alignment_of<T>::value << " " << setw(3) << sizeof(T) << " " << left << setw(13) << type_index(typeid(T)).name() << endl; return out; } template <class T> class AlignmentSizeInfo { public: AlignmentSizeInfo() { cout << *this; } }; int main(int argc, char *argv[]) { AlignmentSizeInfo<char> asChar; AlignmentSizeInfo<int> asInt; AlignmentSizeInfo<double> asDouble; AlignmentSizeInfo<A> asA; AlignmentSizeInfo<A1> asA1; AlignmentSizeInfo<A2> asA2; AlignmentSizeInfo<B> asB; AlignmentSizeInfo<C> asC; AlignmentSizeInfo<D> asD; AlignmentSizeInfo<E> asE; AlignmentSizeInfo<F> asF; }
Add the test that was supposed to be included with r223162.
// RUN: %clang_cc1 -fsyntax-only -verify %s int w = z.; // expected-error {{use of undeclared identifier 'z'}} \ // expected-error {{expected unqualified-id}} int x = { y[ // expected-error {{use of undeclared identifier 'y'}} \ // expected-note {{to match this '['}} \ // expected-note {{to match this '{'}} \ // expected-error {{expected ';' after top level declarator}} // The errors below all occur on the last line of the file, so splitting them // among multiple lines doesn't work. // expected-error {{expected expression}} expected-error {{expected ']'}} expected-error {{expected '}'}}
Check If a String Contains All Binary Codes of Size K
class Solution { public: bool hasAllCodes(string s, int k) { if (k > s.size()) { return false; } int need = 1 << k; for (int i = 0; i <= (s.size()-k); ++i) { std::string cur = s.substr(i, k); auto iter = s_.find(cur); if (iter == s_.end()) { s_.emplace(cur); --need; if (need == 0) return true; } } return false; } private: std::unordered_set<std::string> s_; };
Add another testcase missed from r284905.
// RUN: %clang_cc1 -std=c++1z -verify %s void f() noexcept; void (&r)() = f; void (&s)() noexcept = r; // expected-error {{cannot bind}} void (&cond1)() noexcept = true ? r : f; // expected-error {{cannot bind}} void (&cond2)() noexcept = true ? f : r; // expected-error {{cannot bind}} // FIXME: Strictly, the rules in p4 don't allow this, because the operand types // are not of the same type other than cv-qualifiers, but we consider that to // be a defect, and instead allow reference-compatible types here. void (&cond3)() = true ? r : f; void (&cond4)() = true ? f : r;
Add solution to problem 1
#include <iostream> using std::cout; using std::endl; template <typename T> struct Node { T data; Node *next; Node(T _data, Node *_next = nullptr) : data(_data), next(_next) {} }; template <typename T> class Stack { Node<T> *top; int size; void clear() { while (!isEmpty()) { pop(); } } void copy(const Stack& other) { size = other.size; if (other.top == nullptr) top = nullptr; else { Node<T> *currOther = other.top; Node<T> *curr = new Node<T>(currOther->data); top = curr; currOther = currOther->next; while (currOther != nullptr) { curr->next = new Node<T>(currOther->data); curr = curr->next; currOther = currOther->next; } } } public: Stack() { top = nullptr; size = 0; } Stack(const Stack& other) { copy(other); } Stack& operator=(const Stack& other) { if (this != &other) { clear(); copy(other); } return *this; } ~Stack() { clear(); } int getSize() const { return size; } bool isEmpty() const { return top == nullptr; } const T& getTop() const { return top->data; } void push(const T element) { top = new Node<T>(element, top); size++; } void pop() { Node<T> *toDel = top; top = top->next; delete toDel; size--; } void print() { Node<T> *curr = top; while (curr != nullptr) { cout << curr->data << " "; curr = curr->next; } cout << endl; } }; int main() { Stack<int> s1; cout << s1.isEmpty() << endl; s1.push(5); cout << s1.isEmpty() << endl; s1.push(7); s1.push(9); cout << s1.getTop() << endl; cout << s1.getSize() << endl; s1.print(); Stack<int> s2 = s1; s2.print(); s2.pop(); s2.push(12); s1.print(); s2.print(); s1 = s2; s1.print(); s2.print(); return 0; }
Remove Duplicates From Sorted Array II
// // RemoveDuplicatesFromSortedArrayII.cpp // c++ // // Created by sure on 1/20/15. // Copyright (c) 2015 Shuo Li. All rights reserved. // // http://blog.csdn.net/myjiayan/article/details/26334279 // Gives me a better solution. Implement it in C++ #include <stdio.h> class Solution { public: int removeDuplicates(int A[], int n) { if (n == 0) { return 0; } int times = 0; int index = 0; for (int i = 0; i < n; i ++) { if (A[index] == A[i]) { times ++; if (times == 2) { index ++; A[index] = A[i]; } } else { index ++; A[index] = A[i]; times = 1; } } return (index + 1); } }; int main() { Solution *s = new Solution(); int A[5] = {1, 1, 1, 2, 3}; s->removeDuplicates(A, 5); }
Add solution for chapter 18 test 16, test 17
#include <iostream> namespace Exercise { int ivar = 0; double dvar = 0; const int limit = 1000; } int ivar = 0; //using namespace Exercise; //using Exercise::ivar; //using Exercise::dvar; //using Exercise::limit; void manip() { // using namespace Exercise; using Exercise::ivar; using Exercise::dvar; using Exercise::limit; double dvar = 3.1416; int iobj = limit + 1; ++ ivar; ++ ::ivar; } int main() { return 0; }
Add a test case that goes with the last commit
// RUN: clang -fsyntax-only -verify %s template<typename T> struct A { }; template<typename T, typename U = A<T*> > struct B : U { }; template<> struct A<int*> { void foo(); }; template<> struct A<float*> { void bar(); }; void test(B<int> *b1, B<float> *b2) { b1->foo(); b2->bar(); }
Test for the algorithm output
#include <stdio.h> #include <stdlib.h> #include "gtest/gtest.h" #include "test_helper/samples_reader.h" #include "fortune_points/diagram/site.h" #include "fortune_points/diagram/voronoi.h" #include "fortune_points/algorithm/fortune.h" #include "fortune_points/geom/floating_point.h" namespace{ const int NUMBER_OF_TESTS = 26; const std::string TEST_INPUT_DIR = "fortune_points/__tests__/algorithm/sites_input_samples/input"; const std::string TEST_OUTPUT_DIR = "fortune_points/__tests__/algorithm/diagram_output_samples/output"; TEST(FortuneAlgorithmTest, DiagramTest){ for(int i = 0; i < NUMBER_OF_TESTS; i++){ std::string testCase = std::to_string(i); std::vector<Site> sites; read_algorithm_input(TEST_INPUT_DIR+testCase+".in",sites); std::vector<Edge> correctEdges, computedEdges; std::vector<Vertice> correctVertices, computedVertices; read_algorithm_output(TEST_OUTPUT_DIR+testCase+".out", correctEdges, correctVertices); fortune(sites,computedEdges,computedVertices); std::string failMSG = "Fail on input " + testCase + "."; ASSERT_EQ(computedEdges.size(), correctEdges.size()) << failMSG; for(int j = 0; j < (int)correctEdges.size(); j++){ //printf("ID: %d\n",computedEdges[j].id); //printf("Sites: %d %d\n",computedEdges[j].s0,computedEdges[j].s1); //printf("Bisector: %lf %lf %lf\n",computedEdges[j].l.a,computedEdges[j].l.b,computedEdges[j].l.c); ASSERT_NEAR(correctEdges[j].l.a,computedEdges[j].l.a,EPS) << failMSG; ASSERT_NEAR(correctEdges[j].l.b,computedEdges[j].l.b,EPS) << failMSG; ASSERT_NEAR(correctEdges[j].l.c,computedEdges[j].l.c,EPS) << failMSG; } ASSERT_EQ(computedVertices.size(), correctVertices.size()) << failMSG; for(int j = 0; j < (int)correctVertices.size(); j++){ //printf("%lf,%lf\n",computedVertices[j].x,computedVertices[j].y); ASSERT_NEAR(correctVertices[j].x,computedVertices[j].x,EPS) << failMSG; ASSERT_NEAR(correctVertices[j].y,computedVertices[j].y,EPS) << failMSG; } printf("%s\n",("Succeed on input " + testCase + ".").c_str()); } } }
Remove default case from fully covered switch.
//===-- PPCPredicates.cpp - PPC Branch Predicate Information --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the PowerPC branch predicates. // //===----------------------------------------------------------------------===// #include "PPCPredicates.h" #include "llvm/Support/ErrorHandling.h" #include <cassert> using namespace llvm; PPC::Predicate PPC::InvertPredicate(PPC::Predicate Opcode) { switch (Opcode) { default: llvm_unreachable("Unknown PPC branch opcode!"); case PPC::PRED_EQ: return PPC::PRED_NE; case PPC::PRED_NE: return PPC::PRED_EQ; case PPC::PRED_LT: return PPC::PRED_GE; case PPC::PRED_GE: return PPC::PRED_LT; case PPC::PRED_GT: return PPC::PRED_LE; case PPC::PRED_LE: return PPC::PRED_GT; case PPC::PRED_NU: return PPC::PRED_UN; case PPC::PRED_UN: return PPC::PRED_NU; } }
//===-- PPCPredicates.cpp - PPC Branch Predicate Information --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the PowerPC branch predicates. // //===----------------------------------------------------------------------===// #include "PPCPredicates.h" #include "llvm/Support/ErrorHandling.h" #include <cassert> using namespace llvm; PPC::Predicate PPC::InvertPredicate(PPC::Predicate Opcode) { switch (Opcode) { case PPC::PRED_EQ: return PPC::PRED_NE; case PPC::PRED_NE: return PPC::PRED_EQ; case PPC::PRED_LT: return PPC::PRED_GE; case PPC::PRED_GE: return PPC::PRED_LT; case PPC::PRED_GT: return PPC::PRED_LE; case PPC::PRED_LE: return PPC::PRED_GT; case PPC::PRED_NU: return PPC::PRED_UN; case PPC::PRED_UN: return PPC::PRED_NU; } llvm_unreachable("Unknown PPC branch opcode!"); }
Add test for special cases of assignment
#include "catch.hpp" #include "etl/fast_vector.hpp" #include "etl/fast_matrix.hpp" TEST_CASE( "deep_assign/vec<mat>", "deep_assign" ) { etl::fast_vector<etl::fast_matrix<double, 2, 3>, 2> a; a = 0.0; for(auto& v : a){ for(auto& v2 : v){ REQUIRE(v2 == 0.0); } } } TEST_CASE( "deep_assign/mat<vec>", "deep_assign" ) { etl::fast_matrix<etl::fast_vector<double, 2>, 2, 3> a; a = 0.0; for(auto& v : a){ for(auto& v2 : v){ REQUIRE(v2 == 0.0); } } } TEST_CASE( "deep_assign/mat<mat>", "deep_assign" ) { etl::fast_matrix<etl::fast_matrix<double, 2, 3>, 2, 3> a; a = 0.0; for(auto& v : a){ for(auto& v2 : v){ REQUIRE(v2 == 0.0); } } }
Add a test illustrating our current inability to properly cope with the point of instantation of a member function of a class template specialization
// RUN: clang-cc -fsyntax-only -verify %s // XFAIL // Note: we fail this test because we perform template instantiation // at the end of the translation unit, so argument-dependent lookup // finds functions that occur after the point of instantiation. Note // that GCC fails this test; EDG passes the test in strict mode, but // not in relaxed mode. namespace N { struct A { }; struct B : public A { }; int& f0(A&); } template<typename T, typename Result> struct X0 { void test_f0(T t) { Result r = f0(t); }; }; void test_f0() { X0<N::A, int&> xA; xA.test_f0(N::A()); X0<N::B, int&> xB; xB.test_f0(N::B()); } namespace N { char& f0(B&); }
Add the solution to "Two arrays".
#include <iostream> #include <algorithm> using namespace std; bool cmp(int a, int b) { return a > b; } int main() { int T; cin >> T; while (T--) { int n, k; cin >> n >> k; int *a = new int[n]; int *b = new int[n]; for (int i = 0; i < n; i++) { cin >> a[i]; } for (int i = 0; i < n; i++) { cin >> b[i]; } sort(a, a + n); sort(b, b + n, cmp); bool flag = true; for (int i = n - 1; i >= 0; i--) { if (a[i] + b[i] < k) { flag = false; break; } } if (flag) cout << "YES" << endl; else cout << "NO" << endl; delete [] a; delete [] b; } return 0; }
Add guidance assembly unit test stub
#include "engine/guidance/assemble_overview.hpp" #include "engine/guidance/assemble_geometry.hpp" #include "engine/guidance/assemble_steps.hpp" #include "engine/guidance/assemble_route.hpp" #include "engine/guidance/assemble_leg.hpp" #include <boost/test/unit_test.hpp> #include <boost/test/test_case_template.hpp> BOOST_AUTO_TEST_SUITE(guidance_assembly) BOOST_AUTO_TEST_CASE(rfc4648_test_vectors) { using namespace osrm::engine::guidance; using namespace osrm::engine; // TODO(daniel-j-h): } BOOST_AUTO_TEST_SUITE_END()
Test program for finding bugs in connected_components.
#include <iostream> #include <cvd/connected_components.h> #include <cvd/image.h> using namespace std; using namespace CVD; int main() { for(int i=0; i < (1<<9); i++) { cout << "------------------------\n" << i << endl; int j=i; vector<ImageRef> p; for(int y=0; y < 3; y++) for(int x=0; x < 3; x++) { if(j&1) p.push_back(ImageRef(x, y)); j>>=1; } vector<vector<ImageRef> > v; connected_components(p, v); Image<char> im(ImageRef(3,3), '.'); for(unsigned int j=0; j <v.size(); j++) for(unsigned int k=0; k <v[j].size(); k++) im[v[j][k]]=65+j; cout << "Created " << v.size() << " groups\n"; cout.write(im.data(), 3); cout << endl; cout.write(im.data()+3, 3); cout << endl; cout.write(im.data()+6, 3); cout << endl; cout << endl; cin.get(); } }
Add implementation of Treap in C++
#include <cstdlib> #include <iostream> #include <string> #include <utility> #include <vector> using namespace std; // Treap has 2 main operations that are O(log(n)): // - split(t, k) -> split t into 2 trees, one with all keys <= k, the other with the rest // - merge(t1, t2) -> merge 2 trees where keys of t1 are smaller than any key in t2 struct Tree { Tree* left; Tree* right; int key; int value; int priority; Tree(int k, int v) { left = right = 0; key = k; value = v; priority = rand(); } }; pair<Tree*, Tree*> split(Tree* t, int k) { if (t == 0) return make_pair(nullptr, nullptr); if (t->key <= k) { auto p = split(t->right, k); t->right = p.first; return make_pair(t, p.second); } auto p = split(t->left, k); t->left = p.second; return make_pair(p.first, t); } Tree* merge(Tree* t1, Tree* t2) { if (t1 == 0) return t2; if (t2 == 0) return t1; if (t1->priority >= t2->priority) { t1->right = merge(t1->right, t2); return t1; } t2->left = merge(t1, t2->left); return t2; } // More complex operations can be implemented using only merge and split. See for example insert. Tree* insert(Tree* t, int k, int v) { Tree* n = new Tree(k, v); auto p = split(t, k); return merge(p.first, merge(n, p.second)); } void print(Tree* t, int level = 0) { if (t->right) print(t->right, level + 1); cout << string(4 * level, ' ') << "key: " << t->key << ", value: " << t->value << ", priority:" << t->priority << endl; if (t->left) print(t->left, level + 1); } void destroy(Tree* t) { if (t->left) destroy(t->left); if (t->right) destroy(t->right); delete t; } int main() { Tree* root = nullptr; for (int i = 0; i < 10; ++i) { int k = rand() % 10; root = insert(root, k, i); } print(root); destroy(root); }
Add Code for finding all nodes at a distanc of K from a given node in a binary tree.
#include <iostream> #include <queue> using namespace std; // Code for finding all nodes at a distanc of K from a given node in a binary tree. class Node { public: int data; Node *left; Node *right; Node(int x) { data = x; left = NULL; right = NULL; } }; // Function for finding nodes in subtree of tree at distance of K from the given node. void subtreeNodes(Node *root, int k, vector<Node *> &ans) { if (root == NULL || k < 0) return; if (k == 0) { ans.push_back(root); return; } subtreeNodes(root->left, k - 1, ans); subtreeNodes(root->right, k - 1, ans); } int findNodes(Node *root, int key, int k, vector<Node *> &ans) { if (root == NULL || k < 0) return -1; if (root->data == key) { subtreeNodes(root, k, ans); return k - 1; } int lDist = findNodes(root->left, key, k, ans); if (lDist >= 0) { if (lDist == 0) { ans.push_back(root); return -1; } subtreeNodes(root->right, lDist - 1, ans); return lDist - 1; } int rDist = findNodes(root->right, key, k, ans); if (rDist >= 0) { if (rDist == 0) { ans.push_back(root); return -1; } subtreeNodes(root->left, rDist - 1, ans); return rDist - 1; } return -1; } vector<Node *> findNodesAtK(Node *root, int key, int k) { vector<Node *> ans; findNodes(root, key, k, ans); return ans; } int main() { Node *root = new Node(5); root->left = new Node(9); root->right = new Node(6); root->right->right = new Node(8); root->right->left = new Node(3); root->right->left->left = new Node(16); root->right->left->left->right = new Node(66); root->left->right = new Node(10); vector<Node *> ans = findNodesAtK(root, 8, 3); for (auto e : ans) { cout << e->data << " "; } cout << endl; return 0; }
Add extended euclidean theorem algorithm.
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector < ll > vl; vl arr(3); /* returs gcd(a,b) and find the coeficcients of bezout such that d = ax + by arr[0] gcd arr[1] x arr[2] y */ void extended(ll a, ll b){ ll y =0; ll x =1; ll xx =0; ll yy =1; while(b){ ll q = a / b; ll t = b; b = a%b; a = t; t = xx; xx = x-q*xx; x = t; t = yy; yy = y -q*yy; y = t; } arr[0] = a; arr[1] = x; arr[2] = y; } int main(){ ll a = 20, b = 50; extended(a,b); printf("gcd(%lld, %lld) = %lld = %lld * %lld + %lld * %lld\n", a, b, arr[0], a,arr[1], b, arr[2]); return 0; }
Add example showing the basic usage scenario for static_ptr.
/* * (C) Copyright 2016 Mirantis Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: * Radoslaw Zarzynski <rzarzynski@mirantis.com> */ #include <iostream> #include "static_ptr.hpp" class Interface { public: virtual ~Interface() {}; virtual void print_name() const noexcept = 0; }; class Base1 : public Interface { long member[2]; public: virtual void print_name() const noexcept override { std::cout << "Base1" << std::endl; } }; class Base2 : public Interface { long member[4]; public: virtual ~Base2() { std::cout << "Base2 dted" << std::endl; } virtual void print_name() const noexcept override { std::cout << "Base2" << std::endl; } }; class Factory { static constexpr size_t max_size = sizeof(Base1) > sizeof(Base2) ? sizeof(Base1) : sizeof(Base2); public: static constexpr size_t get_max_size() { return max_size; } // cannot use get_max_size here due to a language quirk static static_ptr<Interface, max_size> make_instance(bool first_one) { if (first_one) { return Base1(); } else { return Base2(); } } }; int main (void) { std::cout << "max size: " << Factory::get_max_size() << std::endl; static_ptr<Interface, Factory::get_max_size()> ptr = Base2(); ptr->print_name(); return 0; }
Revert "remove test temporarily to debug"
#include <gtest/gtest.h> TEST(MathMeta, ensure_c11_features_present) { int s[] = {2, 4}; auto f = [&s](auto i) { return i + s[0]; }; EXPECT_EQ(4, f(2)); }
Add code to insert node in doubly linked list
#include<iostream> using namespace std; class Node{ public: int data; Node *prev, *next; Node(){} Node(int d){ data=d; prev=NULL; next=NULL; } Node *insertNode(Node *head, int d){ Node *np=new Node(d); Node *t=head; if(head==NULL) return np; while(t->next!=NULL) t=t->next; t->next=np; np->prev=t; return head; } Node *insertNodePos(Node *head, int d, int pos){ Node *np=new Node(d); Node *t=head; if(pos==1){ np->next=head; head->prev=np; head=np; return head; } int c=1; while(c<pos-1){ t=t->next; c++; } if(t->next!=NULL){ Node *tm=t->next; np->next=tm; tm->prev=np; } t->next=np; np->prev=t; return head; } void displayList(Node *head){ cout<<"\nElements of the list are:\n"; while(head){ cout<<head->data<<"\n"; head=head->next; } } }; int main() { int n,p,pos,d; Node np; Node *head=NULL; cout<<"Enter the number of elements: "; cin>>n; for(int i=0;i<n;i++){ cout<<"\nEnter element "<<i+1<<": "; cin>>p; head=np.insertNode(head,p); } cout<<"\nEnter the position where you wish to insert the element: "; cin>>pos; if(pos>n+1) cout<<"\nSorry! The position you entered is out of bounds.\n"; else{ cout<<"\nInput the data of the node: "; cin>>d; head=np.insertNodePos(head,d,pos); } np.displayList(head); }
Change 262430 by wsharp@WSHARP-380 on 2006/12/04 07:26:06
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version 1.1 (the * "License"); you may not use this file except in compliance with the License. You may obtain * a copy of the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, WITHOUT * WARRANTY OF ANY KIND, either express or implied. See the License for the specific * language governing rights and limitations under the License. * * The Original Code is [Open Source Virtual Machine.] * * The Initial Developer of the Original Code is Adobe System Incorporated. Portions created * by the Initial Developer are Copyright (C)[ 2004-2006 ] Adobe Systems Incorporated. All Rights * Reserved. * * Contributor(s): Adobe AS3 Team * * Alternatively, the contents of this file may be used under the terms of either the GNU * General Public License Version 2 or later (the "GPL"), or the GNU Lesser General Public * License Version 2.1 or later (the "LGPL"), in which case the provisions of the GPL or the * LGPL are applicable instead of those above. If you wish to allow use of your version of this * file only under the terms of either the GPL or the LGPL, and not to allow others to use your * version of this file under the terms of the MPL, indicate your decision by deleting provisions * above and replace them with the notice and other provisions required by the GPL or the * LGPL. If you do not delete the provisions above, a recipient may use your version of this file * under the terms of any one of the MPL, the GPL or the LGPL. * ***** END LICENSE BLOCK ***** */ #include "avmplus.h" namespace avmplus { namespace NativeID { #include "builtin.cpp" } }
Add runner agent with concepts example.
#include <atomic> #include <chrono> #include <thread> #include <utility> #include <fmt/printf.h> #include <gsl/gsl_assert> template <typename Agent> concept IsAgent = requires(Agent agent) { {agent.doWork()}; }; template <typename Agent> requires IsAgent<Agent> class Runner { public: Runner(Agent &&agent) : m_agent(std::forward<Agent>(agent)) {} constexpr void start() { m_running = true; m_thread = std::thread([&]() { run(); }); } constexpr void run() { while (m_running) { m_agent.doWork(); } } constexpr void stop() { m_running = false; m_thread.join(); } ~Runner() { Expects(m_running == false); } private: Agent m_agent; std::thread m_thread; std::atomic<bool> m_running{false}; }; template <typename Agent> Runner(Agent &&)->Runner<Agent>; class HelloWorldAgent { public: void doWork() noexcept { fmt::print("Hello, {}!\n", "Nanosecond"); } }; int main() { using namespace std::chrono_literals; auto runner = Runner{HelloWorldAgent{}}; runner.start(); std::this_thread::sleep_for(2s); runner.stop(); return 0; }
Add One Row to Tree
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { struct Item { int level; TreeNode* root; }; public: TreeNode* addOneRow(TreeNode* root, int val, int depth) { if (depth == 1) { TreeNode *newroot = new TreeNode(val); if (root) { newroot->left = root; } return newroot; } if (!root) { return root; } std::queue<Item> q; q.push(Item{1, root}); while (!q.empty()) { Item cur = q.front(); q.pop(); if ((cur.level+1) < depth) { if (cur.root->left) { q.push(Item{cur.level+1, cur.root->left}); } if (cur.root->right) { q.push(Item{cur.level+1, cur.root->right}); } } else if ((cur.level+1) == depth) { // found TreeNode *newleft = new TreeNode{val}; TreeNode *newright = new TreeNode{val}; newleft->left = cur.root->left; newright->right = cur.root->right; cur.root->left = newleft; cur.root->right = newright; } else { break; } } return root; } };
Add libFuzzer style fuzzer for NullGLCanvas for use on OSS-Fuzz.
/* * Copyright 2018 Google, LLC * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "../Fuzz.h" void fuzz_NullGLCanvas(Fuzz* f); extern "C" { // Set default LSAN options. const char *__lsan_default_options() { // Don't print the list of LSAN suppressions on every execution. return "print_suppressions=0"; } int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { auto fuzz = Fuzz(SkData::MakeWithoutCopy(data, size)); fuzz_NullGLCanvas(&fuzz); return 0; } } // extern "C"
Increase Sequence - 466D - Codeforces
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int mod = 1e9 + 7; int a[2010]; int dp[2010][2010]; int main(void) { int n, h; scanf("%d %d", &n, &h); for (int i = 1; i <= n; i++) scanf("%d", &a[i]); // fill up the base cases dp[1][0] = (a[1] == h || a[1] + 1 == h) ? 1 : 0; // left alone OR opened and closed dp[1][1] = (a[1] + 1 == h) ? 1 : 0; // opened and did not close for (int i = 2; i <= n; i++) { // the value of open must satisfy one of the following equations // a[i] + open = h => open = h - a[i]; // a[i] + open + 1 = h => open = h - a[i] - 1; for (int open = max(h - a[i] - 1, 0); open <= min(h - a[i], i); open++) { if (a[i] + open == h) { // do nothing dp[i][open] = (dp[i][open] + dp[i - 1][open]) % mod; // close one if (open > 0) dp[i][open] = (dp[i][open] + dp[i - 1][open - 1]) % mod; } else if (a[i] + open + 1 == h) { // open one here and close it as well dp[i][open] = (dp[i][open] + dp[i - 1][open]) % mod; // have open + 1 from earlier and close one of them dp[i][open] = (dp[i][open] + (dp[i - 1][open + 1] * (ll)(open + 1)) % mod) % mod; // have open from earlier, close one of them and open your own dp[i][open] = (dp[i][open] + (dp[i - 1][open] * (ll)open) % mod) % mod; } } } printf("%d\n", dp[n][0]); return 0; }
Add max sub array implementaion in C++
#include <algorithm> #include <iostream> #include <vector> template<typename T> T kadane_method(const std::vector<T>& v){ T ret = 0; std::for_each(v.begin(), v.end(), [c_max = 0, max = 0, &ret](T m) mutable { c_max = c_max + m; // the ccurrent max is a negative number, // we can't use that cuz it will not give us // the maximum sum if (c_max < 0) c_max = 0; // we have to check if there is a new max // if c_max is greater than it means there is a new max so we // have to use that instead. if (max < c_max) max = c_max; //std::cout << "m: " << m << " c_max: " // << c_max << " max: " << max << '\n'; ret = max; }); return ret; } int main() { std::cout << kadane_method<int>({-2, -3, 4, -1, -2, 1, 5, -3}) << '\n'; std::cout << kadane_method<int>({-2, 1, -3, 4, -1, 2, 1, -5, 4}) << '\n'; std::cout << kadane_method<int>({2, 3, 7, -5, -1, 4, -10}) << '\n'; }
Add basic wrapper for Douglas-Peucker
/* 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/. */ /* psimpl-c Copyright (c) 2013 Jamie Bullock <jamie@jamiebullock.com> Based on psimpl Copyright (c) 2010-2011 Elmar de Koning <edekoning@gmail.com> */ #include "psimpl-c.h" #include "psimpl/psimpl.h" #include <stdio.h> double *psimpl_simplify_douglas_peucker( psimpl_LineDimension dimensions, uint64_t points, double tolerance, double *original_points, double *simplified_points ) { double *original_end = original_points + (points * dimensions); switch (dimensions) { case psimpl_LineDimension_1D: return psimpl::simplify_douglas_peucker <1> (original_points, original_end, tolerance, simplified_points); case psimpl_LineDimension_2D: return psimpl::simplify_douglas_peucker <2> (original_points, original_end, tolerance, simplified_points); case psimpl_LineDimension_3D: return psimpl::simplify_douglas_peucker <3> (original_points, original_end, tolerance, simplified_points); default: fprintf(stderr, "Error: invalid dimensions: %d\n", dimensions); return NULL; break; } }
Add method to unify all exit nodes of a method
//===- SimplifyCFG.cpp - CFG Simplification Routines -------------*- C++ -*--=// // // This file provides several routines that are useful for simplifying CFGs in // various ways... // //===----------------------------------------------------------------------===// #include "llvm/Analysis/SimplifyCFG.h" #include "llvm/BasicBlock.h" #include "llvm/Method.h" #include "llvm/iTerminators.h" #include "llvm/iOther.h" #include "llvm/Type.h" // UnifyAllExitNodes - Unify all exit nodes of the CFG by creating a new // BasicBlock, and converting all returns to unconditional branches to this // new basic block. The singular exit node is returned. // // If there are no return stmts in the Method, a null pointer is returned. // BasicBlock *cfg::UnifyAllExitNodes(Method *M) { vector<BasicBlock*> ReturningBlocks; // Loop over all of the blocks in a method, tracking all of the blocks that // return. // for(Method::iterator I = M->begin(), E = M->end(); I != E; ++I) if ((*I)->getTerminator()->getInstType() == Instruction::Ret) ReturningBlocks.push_back(*I); if (ReturningBlocks.size() == 0) return 0; // No blocks return else if (ReturningBlocks.size() == 1) return ReturningBlocks.front(); // Already has a single return block // Otherwise, we need to insert a new basic block into the method, add a PHI // node (if the function returns a value), and convert all of the return // instructions into unconditional branches. // BasicBlock *NewRetBlock = new BasicBlock("", M); if (M->getReturnType() != Type::VoidTy) { // If the method doesn't return void... add a PHI node to the block... PHINode *PN = new PHINode(M->getReturnType()); NewRetBlock->getInstList().push_back(PN); // Add an incoming element to the PHI node for every return instruction that // is merging into this new block... for (vector<BasicBlock*>::iterator I = ReturningBlocks.begin(), E = ReturningBlocks.end(); I != E; ++I) PN->addIncoming((*I)->getTerminator()->getOperand(0), *I); // Add a return instruction to return the result of the PHI node... NewRetBlock->getInstList().push_back(new ReturnInst(PN)); } else { // If it returns void, just add a return void instruction to the block NewRetBlock->getInstList().push_back(new ReturnInst()); } // Loop over all of the blocks, replacing the return instruction with an // unconditional branch. // for (vector<BasicBlock*>::iterator I = ReturningBlocks.begin(), E = ReturningBlocks.end(); I != E; ++I) { delete (*I)->getInstList().pop_back(); // Remove the return insn (*I)->getInstList().push_back(new BranchInst(NewRetBlock)); } return NewRetBlock; }
Add Chapter 20, exercise 4
// Chapter 20, Exercise 04: Find and fix the errors in the Jack-and-Jill example // from 20.3.1 by using STL techniques throughout. #include "../lib_files/std_lib_facilities.h" double* get_from_jack(int* count) { string ifname = "pics_and_txt/chapter20_ex02_in1.txt"; ifstream ifs(ifname.c_str()); if (!ifs) error("Can't open input file ",ifname); // Elegantly read input into vector first vector<double> v; double d; while (ifs>>d) v.push_back(d); *count = v.size(); double* data = new double[*count]; for (int i = 0; i<v.size(); ++i) data[i] = v[i]; return data; } vector<double>* get_from_jill() { string ifname = "pics_and_txt/chapter20_ex02_in2.txt"; ifstream ifs(ifname.c_str()); if (!ifs) error ("Can't open input file ",ifname); vector<double>* v = new vector<double>; double d; while (ifs>>d) (*v).push_back(d); return v; } // return an iterator to the element in [first:last) that has the highest value template<class Iterator> Iterator high(Iterator first, Iterator last) { if (first==last) error("No highest value in empty sequence"); Iterator high = first; for (Iterator p = first; p!=last; ++p) if (*high<*p) high = p; return high; } void fct() { int jack_count = 0; double* jack_data = get_from_jack(&jack_count); vector<double>* jill_data = get_from_jill(); double* jack_high = high(jack_data,jack_data+jack_count); vector<double>& v = *jill_data; double* jill_high = high(&v[0],&v[0]+v.size()); cout << "Jill's high " << *jill_high << "; Jack's high " << *jack_high; delete[] jack_data; delete jill_data; } int main() try { fct(); } catch (Range_error& re) { cerr << "bad index: " << re.index << "\n"; } catch (exception& e) { cerr << "exception: " << e.what() << endl; } catch (...) { cerr << "exception\n"; }
Fix media and content unittests on Android debug bots
// Copyright 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 "media/base/media.h" #include "base/logging.h" // This file is intended for platforms that don't need to load any media // libraries (e.g., Android and iOS). namespace media { bool InitializeMediaLibrary(const base::FilePath& module_dir) { return true; } void InitializeMediaLibraryForTesting() { } bool IsMediaLibraryInitialized() { return true; } } // namespace media
// Copyright 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 "media/base/media.h" #include "base/logging.h" #if defined(OS_ANDROID) #include "base/android/jni_android.h" #include "media/base/android/media_jni_registrar.h" #endif // This file is intended for platforms that don't need to load any media // libraries (e.g., Android and iOS). namespace media { bool InitializeMediaLibrary(const base::FilePath& module_dir) { return true; } void InitializeMediaLibraryForTesting() { #if defined(OS_ANDROID) // Register JNI bindings for android. JNIEnv* env = base::android::AttachCurrentThread(); RegisterJni(env); #endif } bool IsMediaLibraryInitialized() { return true; } } // namespace media
Add test cases for ConditionVariable
/* mbed Microcontroller Library * Copyright (c) 2017 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "mbed.h" #include "greentea-client/test_env.h" #include "unity.h" #include "utest.h" #include "rtos.h" #if defined(MBED_RTOS_SINGLE_THREAD) #error [NOT_SUPPORTED] test not supported #endif using namespace utest::v1; #define TEST_STACK_SIZE 512 #define TEST_DELAY 10 static int change_counter = 0; static Mutex mutex; static ConditionVariable cond(mutex); void increment_on_signal() { mutex.lock(); cond.wait(); change_counter++; mutex.unlock(); } void test_notify_one() { Thread t1(osPriorityNormal, TEST_STACK_SIZE); Thread t2(osPriorityNormal, TEST_STACK_SIZE); change_counter = 0; t1.start(increment_on_signal); t2.start(increment_on_signal); wait_ms(TEST_DELAY); TEST_ASSERT_EQUAL(0, change_counter); mutex.lock(); cond.notify_one(); mutex.unlock(); wait_ms(TEST_DELAY); TEST_ASSERT_EQUAL(1, change_counter); mutex.lock(); cond.notify_one(); mutex.unlock(); t1.join(); t2.join(); } void test_notify_all() { Thread t1(osPriorityNormal, TEST_STACK_SIZE); Thread t2(osPriorityNormal, TEST_STACK_SIZE); change_counter = 0; t1.start(increment_on_signal); t2.start(increment_on_signal); wait_ms(TEST_DELAY); TEST_ASSERT_EQUAL(0, change_counter); mutex.lock(); cond.notify_all(); mutex.unlock(); wait_ms(TEST_DELAY); TEST_ASSERT_EQUAL(2, change_counter); t1.join(); t2.join(); } utest::v1::status_t test_setup(const size_t number_of_cases) { GREENTEA_SETUP(10, "default_auto"); return verbose_test_setup_handler(number_of_cases); } Case cases[] = { Case("Test notify one", test_notify_one), Case("Test notify all", test_notify_all), }; Specification specification(test_setup, cases); int main() { return !Harness::run(specification); }
Add a test case for PR1420
// Test case for PR1420 // RUN: %llvmgxx %s -O0 -o %t.exe // RUN: %t.exe > %t.out // RUN: grep {sizeof(bitFieldStruct) == 8} %t.out // RUN: grep {Offset bitFieldStruct.i = 0} %t.out // RUN: grep {Offset bitFieldStruct.c2 = 7} %t.out // XFAIL: * #include <stdio.h> class bitFieldStruct { public: int i; unsigned char c:7; int s:17; char c2; }; int main() { printf("sizeof(bitFieldStruct) == %d\n", sizeof(bitFieldStruct)); if (sizeof(bitFieldStruct) != 2 * sizeof(int)) printf("bitFieldStruct should be %d but is %d \n", 2 * sizeof(int), sizeof(bitFieldStruct)); bitFieldStruct x; char* xip = (char*) &x.i; char* xc2p = (char*) &x.c2; printf("Offset bitFieldStruct.i = %d\n", xip - xip); printf("Offset bitFieldStruct.c2 = %d\n", xc2p - xip); return 0; }
Add struct alignement test example.
#include <cassert> #include <cstdint> #include <iostream> #include <malloc.h> #include <new> class alignas(32) Vec3d { double x, y, z; }; int main() { std::cout << "sizeof(Vec3d) is " << sizeof(Vec3d) << '\n'; std::cout << "alignof(Vec3d) is " << alignof(Vec3d) << '\n'; auto Vec = Vec3d{}; auto pVec = new Vec3d[10]; if (reinterpret_cast<uintptr_t>(&Vec) % alignof(Vec3d) == 0) { std::cout << "Vec is aligned to alignof(Vec3d)!\n"; } else { std::cout << "Vec is not aligned to alignof(Vec3d)!\n"; } if (reinterpret_cast<uintptr_t>(pVec) % alignof(Vec3d) == 0) { std::cout << "pVec is aligned to alignof(Vec3d)!\n"; } else { std::cout << "pVec is not aligned to alignof(Vec3d)!\n"; } delete[] pVec; }
Add the forgotten test file.
// RUN: %clang_analyze_cc1 -analyzer-checker=core,unix -verify %s // expected-no-diagnostics // Test functions that are called "memcpy" but aren't the memcpy // we're looking for. Unfortunately, this test cannot be put into // a namespace. The out-of-class weird memcpy needs to be recognized // as a normal C function for the test to make sense. typedef __typeof(sizeof(int)) size_t; void *memcpy(void *, const void *, size_t); struct S { static S s1, s2; // A weird overload within the class that accepts a structure reference // instead of a pointer. void memcpy(void *, const S &, size_t); void test_in_class_weird_memcpy() { memcpy(this, s2, 1); // no-crash } }; // A similarly weird overload outside of the class. void *memcpy(void *, const S &, size_t); void test_out_of_class_weird_memcpy() { memcpy(&S::s1, S::s2, 1); // no-crash }
Add testcase missed yesterday. Patch from Paul Robinson.
// RUN: %clangxx -g -O0 %s -emit-llvm -S -o - | FileCheck %s // PR14471 class C { static int a; const static int const_a = 16; protected: static int b; const static int const_b = 17; public: static int c; const static int const_c = 18; int d; }; int C::a = 4; int C::b = 2; int C::c = 1; int main() { C instance_C; instance_C.d = 8; return C::c; } // The definition of C::a drives the emission of class C, which is // why the definition of "a" comes before the declarations while // "b" and "c" come after. // CHECK: metadata !"a", {{.*}} @_ZN1C1aE, metadata ![[DECL_A:[0-9]+]]} ; [ DW_TAG_variable ] [a] {{.*}} [def] // CHECK: ![[DECL_A]] = metadata {{.*}} [ DW_TAG_member ] [a] [line {{.*}}, size 0, align 0, offset 0] [private] [static] // CHECK: metadata !"const_a", {{.*}} [ DW_TAG_member ] [const_a] [line {{.*}}, size 0, align 0, offset 0] [private] [static] // CHECK: ![[DECL_B:[0-9]+]] {{.*}} metadata !"b", {{.*}} [ DW_TAG_member ] [b] [line {{.*}}, size 0, align 0, offset 0] [protected] [static] // CHECK: metadata !"const_b", {{.*}} [ DW_TAG_member ] [const_b] [line {{.*}}, size 0, align 0, offset 0] [protected] [static] // CHECK: ![[DECL_C:[0-9]+]] {{.*}} metadata !"c", {{.*}} [ DW_TAG_member ] [c] [line {{.*}}, size 0, align 0, offset 0] [static] // CHECK: metadata !"const_c", {{.*}} [ DW_TAG_member ] [const_c] [line {{.*}}, size 0, align 0, offset 0] [static] // CHECK: metadata !"b", {{.*}} @_ZN1C1bE, metadata ![[DECL_B]]} ; [ DW_TAG_variable ] [b] {{.*}} [def] // CHECK: metadata !"c", {{.*}} @_ZN1C1cE, metadata ![[DECL_C]]} ; [ DW_TAG_variable ] [c] {{.*}} [def]
Implement tests for NULL iterators for <array> re: N3644
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // <array> // iterator, const_iterator #include <array> #include <iterator> #include <cassert> int main() { { typedef std::array<int, 5> C; C c; C::iterator i; i = c.begin(); C::const_iterator j; j = c.cbegin(); assert(i == j); } { typedef std::array<int, 0> C; C c; C::iterator i; i = c.begin(); C::const_iterator j; j = c.cbegin(); assert(i == j); } #if _LIBCPP_STD_VER > 11 { // N3664 testing { typedef std::array<int, 5> C; C::iterator ii1{}, ii2{}; C::iterator ii4 = ii1; C::const_iterator cii{}; assert ( ii1 == ii2 ); assert ( ii1 == ii4 ); assert ( ii1 == cii ); assert ( !(ii1 != ii2 )); assert ( !(ii1 != cii )); // C c; // assert ( ii1 != c.cbegin()); // assert ( cii != c.begin()); // assert ( cii != c.cend()); // assert ( ii1 != c.end()); } { typedef std::array<int, 0> C; C::iterator ii1{}, ii2{}; C::iterator ii4 = ii1; C::const_iterator cii{}; assert ( ii1 == ii2 ); assert ( ii1 == ii4 ); assert ( ii1 == cii ); assert ( !(ii1 != ii2 )); assert ( !(ii1 != cii )); // C c; // assert ( ii1 != c.cbegin()); // assert ( cii != c.begin()); // assert ( cii != c.cend()); // assert ( ii1 != c.end()); } } #endif }
Prepare exercise 4 from chapter 9.
// 9.exercise.04.cpp // // Look at the headache-inducing last example of §8.4. Indent it properly and // explain the meaning of the construct. Note that the example doesn't do // anything meaningful; it is pure obfuscation. // // COMMENTS int maint() try { return 0; } catch(exception& e) { cerr << e.what() << '\n'; return 1; } catch(...) { cerr << "Unknown exception!\n"; return 2; }
Add solution to task 1
#include <iostream> #include <cstring> using namespace std; class Card { char title[100]; char author[100]; unsigned int count; public: Card(const char _title[], const char _author[], unsigned int _count) { strcpy(title, _title); strcpy(author, _author); count = _count; } void print() { cout << "Title: " << title << endl; cout << "Author: " << author << endl; cout << "Count of available copies: " << count << endl; } }; int main() { Card winFriendsInfluencePeople = Card("How to win friends and influence people", "Dale Carnegie", 3); winFriendsInfluencePeople.print(); return 0; }
Add solution to the first problem - '3D point'
#include <iostream> #include <cmath> using namespace std; class Point3D { double x; double y; double z; public: double getX() { return x; } double getY() { return y; } double getZ() { return z; } void setX(double newX) { x = newX; } void setY(double newY) { y = newY; } void setZ(double newZ) { z = newZ; } void translate(Point3D translationVector) { setX(getX() + translationVector.getX()); setY(getY() + translationVector.getY()); setZ(getZ() + translationVector.getZ()); } double distanceTo(Point3D other) { return sqrt(pow(getX() - other.getX(), 2) + pow(getY() - other.getY(), 2) + pow(getZ() - other.getZ(), 2)); } void print() { cout << '(' << getX() << ", " << getY() << ", " << getZ() << ')' << '\n'; } }; void testTranslate() { Point3D point; point.setX(3); point.setY(5); point.setZ(2); Point3D translationVector; translationVector.setX(4); translationVector.setY(7); translationVector.setZ(1); point.translate(translationVector); point.print(); } void testDistanceBetween() { Point3D firstPoint; firstPoint.setX(3); firstPoint.setY(5); firstPoint.setZ(2); Point3D secondPoint; secondPoint.setX(4); secondPoint.setY(1); secondPoint.setZ(7); cout << firstPoint.distanceTo(secondPoint) << '\n'; } int main() { testTranslate(); testDistanceBetween(); return 0; }
Add a test for re-initialising FDR mode (NFC)
// RUN: %clangxx_xray -g -std=c++11 %s -o %t // RUN: rm xray-log.fdr-reinit* || true // RUN: XRAY_OPTIONS="verbosity=1" %run %t // RUN: rm xray-log.fdr-reinit* || true #include "xray/xray_log_interface.h" #include <cassert> #include <cstddef> #include <thread> volatile uint64_t var = 0; std::atomic_flag keep_going = ATOMIC_FLAG_INIT; [[clang::xray_always_instrument]] void __attribute__((noinline)) func() { ++var; } int main(int argc, char *argv[]) { // Start a thread that will just keep calling the function, to spam calls to // the function call handler. keep_going.test_and_set(std::memory_order_acquire); std::thread t([] { while (keep_going.test_and_set(std::memory_order_acquire)) func(); }); static constexpr char kConfig[] = "buffer_size=1024:buffer_max=10:no_file_flush=true"; // Then we initialize the FDR mode implementation. assert(__xray_log_select_mode("xray-fdr") == XRayLogRegisterStatus::XRAY_REGISTRATION_OK); auto init_status = __xray_log_init_mode("xray-fdr", kConfig); assert(init_status == XRayLogInitStatus::XRAY_LOG_INITIALIZED); // Now we patch the instrumentation points. __xray_patch(); // Spin for a bit, calling func() enough times. for (auto i = 0; i < 1 << 20; ++i) func(); // Then immediately finalize the implementation. auto finalize_status = __xray_log_finalize(); assert(finalize_status == XRayLogInitStatus::XRAY_LOG_FINALIZED); // Once we're here, we should then flush. auto flush_status = __xray_log_flushLog(); assert(flush_status == XRayLogFlushStatus::XRAY_LOG_FLUSHED); // Without doing anything else, we should re-initialize. init_status = __xray_log_init_mode("xray-fdr", kConfig); assert(init_status == XRayLogInitStatus::XRAY_LOG_INITIALIZED); // Then we spin for a bit again calling func() enough times. for (auto i = 0; i < 1 << 20; ++i) func(); // Then immediately finalize the implementation. finalize_status = __xray_log_finalize(); assert(finalize_status == XRayLogInitStatus::XRAY_LOG_FINALIZED); // Once we're here, we should then flush. flush_status = __xray_log_flushLog(); assert(flush_status == XRayLogFlushStatus::XRAY_LOG_FLUSHED); // Finally, we should signal the sibling thread to stop. keep_going.clear(std::memory_order_release); // Then join. t.join(); }
Set scale factor to the value in gsettings
// Copyright (c) 2014 GitHub, Inc. All rights reserved. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/browser/atom_browser_main_parts.h" #include "base/command_line.h" #include "base/strings/string_number_conversions.h" #include "library_loaders/libgio.h" #include "ui/gfx/switches.h" namespace atom { namespace { const char* kInterfaceSchema = "org.gnome.desktop.interface"; const char* kScaleFactor = "scale-factor"; } // namespace void AtomBrowserMainParts::SetDPIFromGSettings() { LibGioLoader libgio_loader; // Try also without .0 at the end; on some systems this may be required. if (!libgio_loader.Load("libgio-2.0.so.0") && !libgio_loader.Load("libgio-2.0.so")) { VLOG(1) << "Cannot load gio library. Will fall back to gconf."; return; } GSettings* client = libgio_loader.g_settings_new(kInterfaceSchema); if (!client) { VLOG(1) << "Cannot create gsettings client."; return; } gchar** keys = libgio_loader.g_settings_list_keys(client); if (!keys) { g_object_unref(client); return; } // Check if the "scale-factor" settings exsits. gchar** iter = keys; while (*iter) { if (strcmp(*iter, kScaleFactor) == 0) break; iter++; } if (*iter) { guint scale_factor = libgio_loader.g_settings_get_uint( client, kScaleFactor); if (scale_factor >= 1) { base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kForceDeviceScaleFactor, base::UintToString(scale_factor)); } } g_strfreev(keys); g_object_unref(client); } } // namespace atom
Fix GoQuicSpdyServerStreamGoWrapper not returning correct len
#include "go_quic_spdy_server_stream_go_wrapper.h" #include "net/quic/quic_session.h" #include "net/quic/quic_data_stream.h" #include "go_functions.h" GoQuicSpdyServerStreamGoWrapper::GoQuicSpdyServerStreamGoWrapper(net::QuicStreamId id, net::QuicSession* session, void* go_quic_spdy_server_stream) : net::QuicDataStream(id, session), go_quic_spdy_server_stream_(go_quic_spdy_server_stream) { } GoQuicSpdyServerStreamGoWrapper::~GoQuicSpdyServerStreamGoWrapper() { } // TODO(hodduc) more more implementation // uint32 GoQuicSpdyServerStreamGoWrapper::ProcessData(const char* data, uint32 data_len) { if (data_len > INT_MAX) { LOG(DFATAL) << "Data length too long: " << data_len; return 0; } uint32_t ret_data_len = DataStreamProcessorProcessData_C(go_quic_spdy_server_stream_, data, data_len); return data_len; }
#include "go_quic_spdy_server_stream_go_wrapper.h" #include "net/quic/quic_session.h" #include "net/quic/quic_data_stream.h" #include "go_functions.h" GoQuicSpdyServerStreamGoWrapper::GoQuicSpdyServerStreamGoWrapper(net::QuicStreamId id, net::QuicSession* session, void* go_quic_spdy_server_stream) : net::QuicDataStream(id, session), go_quic_spdy_server_stream_(go_quic_spdy_server_stream) { } GoQuicSpdyServerStreamGoWrapper::~GoQuicSpdyServerStreamGoWrapper() { } // TODO(hodduc) more more implementation // uint32 GoQuicSpdyServerStreamGoWrapper::ProcessData(const char* data, uint32 data_len) { if (data_len > INT_MAX) { LOG(DFATAL) << "Data length too long: " << data_len; return 0; } uint32_t ret_data_len = DataStreamProcessorProcessData_C(go_quic_spdy_server_stream_, data, data_len); return ret_data_len; }
Add a solution for task 1a
#include <cstdio> #include <cstring> using namespace std; int binary_to_decimal(char * number) { int result = 0; int power = 0; for (int i = strlen(number) - 1; i >= 0; i--) { int x = number[i] - '0'; result += x * (1 << power); power++; } return result; } int octal_to_decimal(char * number) { int result = 0; int number_length = strlen(number); for (int i = 0; i < number_length; i++) { result += number[i] - '0'; if (i < number_length - 1) { result *= 8; } } return result; } int hexadecimal_to_decimal(char *number) { int number_length = strlen(number); char result[100] = ""; for (int i = 0; i < number_length; i++) { if (number[i] == '0') strcat(result, "0000"); else if (number[i] == '1') strcat(result, "0001"); else if (number[i] == '2') strcat(result, "0010"); else if (number[i] == '3') strcat(result, "0011"); else if (number[i] == '4') strcat(result, "0100"); else if (number[i] == '5') strcat(result, "0101"); else if (number[i] == '6') strcat(result, "0110"); else if (number[i] == '7') strcat(result, "0111"); else if (number[i] == '8') strcat(result, "1000"); else if (number[i] == '9') strcat(result, "1001"); else if (number[i] == 'A') strcat(result, "1010"); else if (number[i] == 'B') strcat(result, "1011"); else if (number[i] == 'C') strcat(result, "1100"); else if (number[i] == 'D') strcat(result, "1101"); else if (number[i] == 'E') strcat(result, "1110"); else if (number[i] == 'F') strcat(result, "1111"); } return binary_to_decimal(result); } int main() { int numeral_system; char number[100]; while (scanf("%d%s", &numeral_system, number)) { if (numeral_system == 2) printf("%d\n", binary_to_decimal(number)); else if (numeral_system == 8) printf("%d\n", octal_to_decimal(number)); else if (numeral_system == 16) printf("%d\n", hexadecimal_to_decimal(number)); } return 0; }
Add test that GDAL plugin does not upsample.
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include "catch.hpp" #include <mapnik/datasource.hpp> #include <mapnik/datasource_cache.hpp> #include <mapnik/raster.hpp> #include <mapnik/util/fs.hpp> namespace { mapnik::datasource_ptr get_gdal_ds(std::string const& file_name, boost::optional<mapnik::value_integer> band) { std::string gdal_plugin("./plugins/input/gdal.input"); if (!mapnik::util::exists(gdal_plugin)) { return mapnik::datasource_ptr(); } mapnik::parameters params; params["type"] = std::string("gdal"); params["file"] = file_name; if (band) { params["band"] = *band; } auto ds = mapnik::datasource_cache::instance().create(params); REQUIRE(ds != nullptr); return ds; } } // anonymous namespace TEST_CASE("gdal") { SECTION("upsampling") { std::string dataset = "test/data/tiff/ndvi_256x256_gray32f_tiled.tif"; mapnik::datasource_ptr ds = get_gdal_ds(dataset, 1); if (!ds) { // GDAL plugin not built. return; } mapnik::box2d<double> envelope = ds->envelope(); CHECK(envelope.width() == 256); CHECK(envelope.height() == 256); // Indicate four times bigger resolution. mapnik::query::resolution_type resolution(2.0, 2.0); mapnik::query query(envelope, resolution, 1.0); auto features = ds->features(query); auto feature = features->next(); mapnik::raster_ptr raster = feature->get_raster(); REQUIRE(raster != nullptr); CHECK(raster->data_.width() == 256); CHECK(raster->data_.height() == 256); } } // END TEST CASE
Add solution for chapter 18, test 29
#include <iostream> using namespace std; class Class { public: Class() { cout << "Class()" << endl; } }; class Base : public Class { public: Base() { cout << "Base()" << endl; } }; class D1 : virtual public Base { public: D1() { cout << "D1()" << endl; } }; class D2 : virtual public Base { public: D2() { cout << "D2()" << endl; } }; class MI : public D1, public D2 { public: MI() { cout << "MI()" << endl; } }; class Final : public MI, public Class { public: Final() { cout << "Final()" << endl; } }; int main() { //(a)(b) Final f; //(c) Base *pb = nullptr; Class *pc = nullptr; MI *pmi = nullptr; D2 *pd2 = nullptr; // pb = new Class;//invalid conversion // pc = new Final;//'Class' is an ambiguous base of 'Final' // pmi = pb;//invalid conversion // pd2 = pmi;//ok return 0; }
Add example of clang attributes for prevention of use after move.
#include <iostream> #include <cassert> class [[clang::consumable(unconsumed)]] Object { public: Object() {} Object(Object&& other) { other.invalidate(); } [[clang::callable_when(unconsumed)]] void do_something() { assert(m_valid); } private: [[clang::set_typestate(consumed)]] void invalidate() { m_valid = false; } bool m_valid { true }; }; int main(int, char**) { Object object; auto other = std::move(object); object.do_something(); return 0; }
Add an experiment that tests some bitfield stuff
#include <atomic> #include <thread> #include <iostream> struct thing { unsigned int a : 15; unsigned int b : 15; }; thing x; void f1(int n) { for (int i = 0; i < n; i++) { x.a++; } } void f2(int n) { for (int i = 0; i < n; i++) { x.b++; } } int main() { std::cout << sizeof(thing) << "\n"; std::thread t1(f1, 1000000); std::thread t2(f2, 1000000); t1.join(); t2.join(); std::cout << x.a << " " << x.b << "\n"; return 0; }
Add new test that shows failure in DerivativeApproximation
//---------------------------- crash_04.cc --------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 2005, 2006 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------- crash_04.cc --------------------------- // trigger a problem in DerivativeApproximation with memory handling #include <base/logstream.h> #include <lac/vector.h> #include <grid/tria.h> #include <grid/grid_generator.h> #include <grid/tria_accessor.h> #include <dofs/hp_dof_handler.h> #include <fe/fe_dgq.h> #include <numerics/derivative_approximation.h> #include <fstream> template <int dim> void test () { Triangulation<dim> tria; GridGenerator::hyper_cube(tria); tria.refine_global (1); hp::FECollection<dim> fe_collection; fe_collection.push_back (FE_DGQ<dim> (1)); hp::DoFHandler<dim> dof_handler(tria); dof_handler.distribute_dofs (fe_collection); Vector<double> v(dof_handler.n_dofs()); Vector<float> e(tria.n_active_cells()); DerivativeApproximation::approximate_gradient (dof_handler, v, e); } int main () { std::ofstream logfile("crash_04/output"); logfile.precision(2); deallog.attach(logfile); deallog.depth_console(0); deallog.threshold_double(1.e-10); test<1> (); test<2> (); test<3> (); deallog << "OK" << std::endl; }
Add minimal testcase for optimizer bug in FParser.
// Simple example file for the the fparser optimization bug // (c) 2014 by Daniel Schwen // ======================================================== // $CXX -o optimizer_bug optimizer_bug.cc -I ../../../installed/include/libmesh/ ../../../build/contrib/fparser/.libs/libfparser_la-fp* #include "../fparser.hh" #include <iostream> #include <fstream> #include <string> int main() { std::ofstream myfile; double p[3] = {0.0, 2.0, 0.1}; const double step = 0.01; FunctionParser fparser; // The White Whale std::string func = "c*2*(1-c)^2 - c^2*(1-c)*2"; // Parse the input expression into bytecode fparser.Parse(func, "c"); #ifdef FUNCTIONPARSER_SUPPORT_DEBUGGING std::cout << "Input Expression:\n" << func << std::endl; fparser.PrintByteCode(std::cout); std::cout << std::endl; #endif // eval into file myfile.open ("pre.dat"); for (p[0]=0.0; p[0]<=1.0; p[0]+=0.01) myfile << p[0] << ' ' << fparser.Eval(p) << std::endl; myfile.close(); FunctionParser fparser2(fparser); // output optimized version fparser.Optimize(); #ifdef FUNCTIONPARSER_SUPPORT_DEBUGGING std::cout << "Optimized Input Expression:\n" << func << std::endl; fparser.PrintByteCode(std::cout); std::cout << std::endl; #endif // eval into file myfile.open ("post.dat"); for (p[0]=0.0; p[0]<=1.0; p[0]+=0.01) myfile << p[0] << ' ' << fparser.Eval(p) << std::endl; myfile.close(); // compute difference double diff = 0.0; for (p[0]=0.0; p[0]<=1.0; p[0]+=step) diff+=step*(fparser.Eval(p)-fparser2.Eval(p)); std::cout << "Integral of f_optimized()-f_original() on [0,1] = " << diff << " (should be ~0.0)" << std::endl; return 0; }
Add solution for chapter 19, test 13
#include <iostream> #include <string> #include "test16_62_Sales_data.h" using namespace std; int main() { Sales_data item("book1", 4, 30.0), *p = &item; auto pdata = &Sales_data::isbn; cout << (item.*pdata)() << endl; cout << (p ->* pdata)() << endl; return 0; }
Test for the new FileUtil::GetFileName() functions.
/** \file xml_parser_test.cc * \brief Tests the FileUtil::GetFileName() function. * \author Dr. Johannes Ruscheinski */ /* Copyright (C) 2015, Library of the University of Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <stdexcept> #include "FileUtil.h" #include "util.h" __attribute__((noreturn)) void Usage() { std::cerr << "usage: " << ::progname << " path\n"; std::exit(EXIT_FAILURE); } int main(int argc, char *argv[]) { ::progname = argv[0]; if (argc != 2) Usage(); try { FILE *file(std::fopen(argv[1], "r")); std::cout << "File pointer points to \"" << FileUtil::GetFileName(file) << "\".\n"; } catch(const std::exception &x) { Error("caught exception: " + std::string(x.what())); } }
Add in Intel TBB tests
#include "tbb/parallel_sort.h" #include <math.h> using namespace tbb; const int N = 100000; float a[N], b[N], c[N], d[N]; void SortExample() { for( int i = 0; i < N; i++ ) { a[i] = sin((double)i); b[i] = cos((double)i); c[i] = 1/sin((double)i); d[i] = 1/cos((double)i); } parallel_sort(a, a + N); parallel_sort(b, b + N, std::greater<float>()); parallel_sort(c); parallel_sort(d, std::greater<float>()); } int main( void ) { SortExample(); return 0; }
Add basic test for Vec2
#include "gtest/gtest.h" #include "gmock/gmock.h" #include "Vec2i.h" TEST(TestVec2i, DisplacingDirectionWithOffsetWillWrap ) { ASSERT_EQ( Knights::EDirection::kWest, Knights::wrapDirection( Knights::EDirection::kNorth, -1 ) ); ASSERT_EQ( Knights::EDirection::kNorth, Knights::wrapDirection( Knights::EDirection::kEast, -1 ) ); ASSERT_EQ( Knights::EDirection::kEast, Knights::wrapDirection( Knights::EDirection::kSouth, -1 ) ); ASSERT_EQ( Knights::EDirection::kSouth, Knights::wrapDirection( Knights::EDirection::kWest, -1 ) ); ASSERT_EQ( Knights::EDirection::kNorth, Knights::wrapDirection( Knights::EDirection::kNorth, -4 ) ); ASSERT_EQ( Knights::EDirection::kEast, Knights::wrapDirection( Knights::EDirection::kEast, -4 ) ); ASSERT_EQ( Knights::EDirection::kSouth, Knights::wrapDirection( Knights::EDirection::kSouth, -4 ) ); ASSERT_EQ( Knights::EDirection::kWest, Knights::wrapDirection( Knights::EDirection::kWest, -4 ) ); ASSERT_EQ( Knights::EDirection::kEast, Knights::wrapDirection( Knights::EDirection::kNorth, +1 ) ); ASSERT_EQ( Knights::EDirection::kSouth, Knights::wrapDirection( Knights::EDirection::kEast, +1 ) ); ASSERT_EQ( Knights::EDirection::kWest, Knights::wrapDirection( Knights::EDirection::kSouth, +1 ) ); ASSERT_EQ( Knights::EDirection::kNorth, Knights::wrapDirection( Knights::EDirection::kWest, +1 ) ); ASSERT_EQ( Knights::EDirection::kNorth, Knights::wrapDirection( Knights::EDirection::kNorth, +4 ) ); ASSERT_EQ( Knights::EDirection::kEast, Knights::wrapDirection( Knights::EDirection::kEast, +4 ) ); ASSERT_EQ( Knights::EDirection::kSouth, Knights::wrapDirection( Knights::EDirection::kSouth, +4 ) ); ASSERT_EQ( Knights::EDirection::kWest, Knights::wrapDirection( Knights::EDirection::kWest, +4 ) ); }
Add the vpsc library for IPSEPCOLA features
/** * * Authors: * Tim Dwyer <tgdwyer@gmail.com> * * Copyright (C) 2005 Authors * * This version is released under the CPL (Common Public License) with * the Graphviz distribution. * A version is also available under the LGPL as part of the Adaptagrams * project: http://sourceforge.net/projects/adaptagrams. * If you make improvements or bug fixes to this code it would be much * appreciated if you could also contribute those changes back to the * Adaptagrams repository. */ #include "variable.h" std::ostream& operator <<(std::ostream &os, const Variable &v) { os << "(" << v.id << "=" << v.position() << ")"; return os; }
Make sure C++ protection shows up in debug info
// RUN: %llvmgxx -O0 -emit-llvm -S -g -o - %s | grep 'uint 1,' && // RUN: %llvmgxx -O0 -emit-llvm -S -g -o - %s | grep 'uint 2,' class A { public: int x; protected: int y; private: int z; }; A a;
Add image generation demo file.
// // Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu> // Creation Date: Mon 18 Apr 2022 06:34:46 PM UTC // Last Modified: Mon 18 Apr 2022 06:34:49 PM UTC // Filename: imagedemo.cpp // URL: https://github.com/craigsapp/humlib/blob/master/cli/imagedemo.cpp // Syntax: C++11 // vim: ts=3 noexpandtab nowrap // // Description: Demonstration of how to use PixelColor class // to create simple images. // #include "humlib.h" #include <iostream> using namespace hum; using namespace std; void processFile (HumdrumFile& infile, Options& options); double calculateNpviRhythm (HumdrumFile& infile, Options& option); double calculateCvPitch (HumdrumFile& infile, Options& options); string getReference (HumdrumFile& infile, const string& targetKey); /////////////////////////////////////////////////////////////////////////// int main(int argc, char** argv) { Options options; options.define("x|columns=i:4", "Number of columns in image"); options.define("y|rows=i:4", "Number of rows in image"); options.process(argc, argv); int rows = options.getInteger("rows"); int cols = options.getInteger("columns"); vector<vector<PixelColor>> image; for (int y=0; y<(int)image.size(); y++) { for (int x=0; x<(int)image[y].size(); x++) { image[y][x].setRedF((double)y/rows); image[y][x].setBlueF((double)x/cols); } } // Output image header: cout << "P3" << endl; cout << cols << " " << rows << endl; cout << 255 << endl; // Output image pixels: for (int y=0; y<(int)image.size(); y++) { for (int x=0; x<(int)image[y].size(); x++) { cout << image[y][x] << " "; } cout << endl; } return 0; }
Divide a String Into Groups of Size k
class Solution { public: vector<string> divideString(string s, int k, char fill) { std::vector<std::string> ret; std::string cur; for (int i = 0; i < s.size(); i += k) { ret.emplace_back(s.substr(i, k)); } while (ret[ret.size()-1].size() < k) { ret[ret.size()-1] += fill; } return ret; } };
Validate if a binary tree is BST
/** * 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: inline bool isLeaf(TreeNode* n) { return n->left == NULL && n->right == NULL; } bool isValidBSTInternal(TreeNode* root, int& minVal, int& maxVal) { int currMin, currMax; if (root == NULL) { return true; } if (isLeaf(root)) { minVal = maxVal = root->val; return true; } if (root->left) { if (!isValidBSTInternal(root->left, minVal, maxVal)) { return false; } if (root->val <= maxVal) { return false; } currMin = min(root->val, minVal); currMax = max(root->val, maxVal); } else { currMin = currMax = root->val; } if (root->right) { if (!isValidBSTInternal(root->right, minVal, maxVal)) { return false; } if (root->val >= minVal) { return false; } minVal = min(minVal, currMin); maxVal = max(maxVal, currMax); } else { minVal = currMin; maxVal = currMax; } return true; } bool isValidBST(TreeNode* root) { int minVal, maxVal; return isValidBSTInternal(root, minVal, maxVal); } };
Disable DownloadsApiTest.DownloadsApiTest because it is too flaky and times out too often.
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" class DownloadsApiTest : public ExtensionApiTest { public: void SetUpCommandLine(CommandLine* command_line) OVERRIDE { ExtensionApiTest::SetUpCommandLine(command_line); command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis); } void SetUpTempDownloadsDir() { ASSERT_TRUE(tmpdir.CreateUniqueTempDir()); browser()->profile()->GetPrefs()->SetFilePath( prefs::kDownloadDefaultDirectory, tmpdir.path()); } private: ScopedTempDir tmpdir; }; IN_PROC_BROWSER_TEST_F(DownloadsApiTest, DownloadsApiTest) { SetUpTempDownloadsDir(); ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("downloads")) << message_; }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" class DownloadsApiTest : public ExtensionApiTest { public: void SetUpCommandLine(CommandLine* command_line) OVERRIDE { ExtensionApiTest::SetUpCommandLine(command_line); command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis); } void SetUpTempDownloadsDir() { ASSERT_TRUE(tmpdir.CreateUniqueTempDir()); browser()->profile()->GetPrefs()->SetFilePath( prefs::kDownloadDefaultDirectory, tmpdir.path()); } private: ScopedTempDir tmpdir; }; // This test is disabled. See bug http://crbug.com/130950 IN_PROC_BROWSER_TEST_F(DownloadsApiTest, DISABLED_DownloadsApiTest) { SetUpTempDownloadsDir(); ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("downloads")) << message_; }