Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Use JoinPath over a fixed string for building paths.
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/platform/resource_loader.h" #include "tensorflow/core/platform/env.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/status.h" #include "tensorflow/core/platform/test.h" namespace tensorflow { const char kDataDependencyPath[] = "tensorflow/core/platform/resource_loader.h"; TEST(ResourceLoaderTest, FindsAndOpensFile) { string filepath = GetDataDependencyFilepath(kDataDependencyPath); Status s = Env::Default()->FileExists(filepath); EXPECT_TRUE(s.ok()) << "No file found at this location: " << filepath; } } // namespace tensorflow
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/platform/resource_loader.h" #include "tensorflow/core/platform/env.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/path.h" #include "tensorflow/core/platform/status.h" #include "tensorflow/core/platform/test.h" namespace tensorflow { namespace { string DataDependencyPath() { return io::JoinPath("tensorflow", "core", "platform", "resource_loader.h"); } TEST(ResourceLoaderTest, FindsAndOpensFile) { string filepath = GetDataDependencyFilepath(DataDependencyPath()); Status s = Env::Default()->FileExists(filepath); EXPECT_TRUE(s.ok()) << "No file found at this location: " << filepath; } } // namespace } // namespace tensorflow
Add noexcept test for offsetof macro per [support.types]/p4.
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// #include <cstddef> #ifndef offsetof #error offsetof not defined #endif int main() { }
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// #include <cstddef> #ifndef offsetof #error offsetof not defined #endif struct A { int x; }; int main() { #if (__has_feature(cxx_noexcept)) static_assert(noexcept(offsetof(A, x)), ""); #endif }
Revert "Add a missing target requirement."
// RUN: rm -rf %t // RUN: pp-trace -ignore FileChanged,MacroDefined %s -x objective-c++ -undef -target x86_64 -std=c++11 -fmodules -fcxx-modules -fmodules-cache-path=%t -I%S -I%S/Input | FileCheck --strict-whitespace %s // REQUIRES: x86-registered-target // CHECK: --- @import Level1A; // CHECK-NEXT: - Callback: moduleImport // CHECK-NEXT: ImportLoc: "{{.*}}{{[/\\]}}pp-trace-modules.cpp:[[@LINE-3]]:2" // CHECK-NEXT: Path: [{Name: Level1A, Loc: "{{.*}}{{[/\\]}}pp-trace-modules.cpp:[[@LINE-4]]:9"}] // CHECK-NEXT: Imported: Level1A @import Level1B.Level2B; // CHECK-NEXT: - Callback: moduleImport // CHECK-NEXT: ImportLoc: "{{.*}}{{[/\\]}}pp-trace-modules.cpp:[[@LINE-3]]:2" // CHECK-NEXT: Path: [{Name: Level1B, Loc: "{{.*}}{{[/\\]}}pp-trace-modules.cpp:[[@LINE-4]]:9"}, {Name: Level2B, Loc: "{{.*}}{{[/\\]}}pp-trace-modules.cpp:[[@LINE-4]]:17"}] // CHECK-NEXT: Imported: Level2B // CHECK-NEXT: - Callback: EndOfMainFile // CHECK-NEXT: ...
// RUN: rm -rf %t // RUN: pp-trace -ignore FileChanged,MacroDefined %s -x objective-c++ -undef -target x86_64 -std=c++11 -fmodules -fcxx-modules -fmodules-cache-path=%t -I%S -I%S/Input | FileCheck --strict-whitespace %s // CHECK: --- @import Level1A; // CHECK-NEXT: - Callback: moduleImport // CHECK-NEXT: ImportLoc: "{{.*}}{{[/\\]}}pp-trace-modules.cpp:[[@LINE-3]]:2" // CHECK-NEXT: Path: [{Name: Level1A, Loc: "{{.*}}{{[/\\]}}pp-trace-modules.cpp:[[@LINE-4]]:9"}] // CHECK-NEXT: Imported: Level1A @import Level1B.Level2B; // CHECK-NEXT: - Callback: moduleImport // CHECK-NEXT: ImportLoc: "{{.*}}{{[/\\]}}pp-trace-modules.cpp:[[@LINE-3]]:2" // CHECK-NEXT: Path: [{Name: Level1B, Loc: "{{.*}}{{[/\\]}}pp-trace-modules.cpp:[[@LINE-4]]:9"}, {Name: Level2B, Loc: "{{.*}}{{[/\\]}}pp-trace-modules.cpp:[[@LINE-4]]:17"}] // CHECK-NEXT: Imported: Level2B // CHECK-NEXT: - Callback: EndOfMainFile // CHECK-NEXT: ...
Set define for Tizen accelerometer
#include <Input.h> namespace nme { #if !defined(IPHONE) && !defined(WEBOS) && !defined(ANDROID) && !defined(BLACKBERRY) bool GetAcceleration(double &outX, double &outY, double &outZ) { return false; } #endif }
#include <Input.h> namespace nme { #if !defined(IPHONE) && !defined(WEBOS) && !defined(ANDROID) && !defined(BLACKBERRY) && !defined(TIZEN) bool GetAcceleration(double &outX, double &outY, double &outZ) { return false; } #endif }
Remove CHECK for strdup symbol that comes from the CRT
// RUN: %clang_cl_asan -O0 %s -Fe%t // RUN: not %run %t 2>&1 | FileCheck %s #include <stdio.h> #include <string.h> #include <malloc.h> int main() { char *ptr = _strdup("Hello"); int subscript = 1; ptr[subscript] = '3'; printf("%s\n", ptr); fflush(0); // CHECK: H3llo subscript = -1; ptr[subscript] = 42; // CHECK: AddressSanitizer: heap-buffer-overflow on address [[ADDR:0x[0-9a-f]+]] // CHECK: WRITE of size 1 at [[ADDR]] thread T0 // CHECK: {{#0 .* main .*}}intercept_strdup.cc:[[@LINE-3]] // CHECK: [[ADDR]] is located 1 bytes to the left of 6-byte region // CHECK: allocated by thread T0 here: // CHECK: {{#0 .* malloc }} // CHECK: {{#1 .*strdup}} // CHECK: {{#2 .* main .*}}intercept_strdup.cc:[[@LINE-16]] free(ptr); }
// RUN: %clang_cl_asan -O0 %s -Fe%t // RUN: not %run %t 2>&1 | FileCheck %s #include <stdio.h> #include <string.h> #include <malloc.h> int main() { char *ptr = _strdup("Hello"); int subscript = 1; ptr[subscript] = '3'; printf("%s\n", ptr); fflush(0); // CHECK: H3llo subscript = -1; ptr[subscript] = 42; // CHECK: AddressSanitizer: heap-buffer-overflow on address [[ADDR:0x[0-9a-f]+]] // CHECK: WRITE of size 1 at [[ADDR]] thread T0 // CHECK: {{#0 .* main .*}}intercept_strdup.cc:[[@LINE-3]] // CHECK: [[ADDR]] is located 1 bytes to the left of 6-byte region // CHECK: allocated by thread T0 here: // CHECK: {{#0 .* malloc }} // FIXME: llvm-symbolizer can't find strdup in the CRT. // CHECKX: {{#1 .*strdup}} // CHECK: {{#2 .* main .*}}intercept_strdup.cc:[[@LINE-17]] free(ptr); }
Disable test under asan: it uses a lot of stack, and asan increases the per-frame stack usage enough to cause it to hit our stack limit. This is not ideal; we should find a better way of dealing with this, such as increasing our stack allocation when built with ASan.
// RUN: %clang_cc1 -fsyntax-only -verify -ftemplate-backtrace-limit 2 %s template<int N, typename T> struct X : X<N+1, T*> {}; // expected-error-re@3 {{recursive template instantiation exceeded maximum depth of 1024{{$}}}} // expected-note@3 {{instantiation of template class}} // expected-note@3 {{skipping 1023 contexts in backtrace}} // expected-note@3 {{use -ftemplate-depth=N to increase recursive template instantiation depth}} X<0, int> x; // expected-note {{in instantiation of}}
// RUN: %clang_cc1 -fsyntax-only -verify -ftemplate-backtrace-limit 2 %s // // FIXME: Disable this test when Clang was built with ASan, because ASan // increases our per-frame stack usage enough that this test no longer fits // within our normal stack space allocation. // REQUIRES: not_asan template<int N, typename T> struct X : X<N+1, T*> {}; // expected-error-re@8 {{recursive template instantiation exceeded maximum depth of 1024{{$}}}} // expected-note@8 {{instantiation of template class}} // expected-note@8 {{skipping 1023 contexts in backtrace}} // expected-note@8 {{use -ftemplate-depth=N to increase recursive template instantiation depth}} X<0, int> x; // expected-note {{in instantiation of}}
Change analysis name from "pca" to "PCA"
// Qt includes #include <QDebug> // Visomics includes #include "voAnalysis.h" #include "voAnalysisFactory.h" #include "voQObjectFactory.h" #include "voPCAStatistics.h" //---------------------------------------------------------------------------- class voAnalysisFactoryPrivate { public: voQObjectFactory<voAnalysis> AnalysisFactory; }; //---------------------------------------------------------------------------- // voAnalysisFactoryPrivate methods //---------------------------------------------------------------------------- // voAnalysisFactory methods //---------------------------------------------------------------------------- voAnalysisFactory::voAnalysisFactory():d_ptr(new voAnalysisFactoryPrivate) { this->registerAnalysis<voPCAStatistics>("pca"); } //----------------------------------------------------------------------------- voAnalysisFactory::~voAnalysisFactory() { } //----------------------------------------------------------------------------- voAnalysis* voAnalysisFactory::createAnalysis(const QString& className) { Q_D(voAnalysisFactory); return d->AnalysisFactory.Create(className); } //----------------------------------------------------------------------------- QStringList voAnalysisFactory::registeredAnalysisNames() const { Q_D(const voAnalysisFactory); return d->AnalysisFactory.registeredObjectKeys(); } //----------------------------------------------------------------------------- template<typename AnalysisClassType> void voAnalysisFactory::registerAnalysis(const QString& analysisName) { Q_D(voAnalysisFactory); if (analysisName.isEmpty()) { qCritical() << "Failed to register analysis - analysisName is an empty string"; return; } if (this->registeredAnalysisNames().contains(analysisName)) { return; } d->AnalysisFactory.registerObject<AnalysisClassType>(analysisName); }
// Qt includes #include <QDebug> // Visomics includes #include "voAnalysis.h" #include "voAnalysisFactory.h" #include "voQObjectFactory.h" #include "voPCAStatistics.h" //---------------------------------------------------------------------------- class voAnalysisFactoryPrivate { public: voQObjectFactory<voAnalysis> AnalysisFactory; }; //---------------------------------------------------------------------------- // voAnalysisFactoryPrivate methods //---------------------------------------------------------------------------- // voAnalysisFactory methods //---------------------------------------------------------------------------- voAnalysisFactory::voAnalysisFactory():d_ptr(new voAnalysisFactoryPrivate) { this->registerAnalysis<voPCAStatistics>("PCA"); } //----------------------------------------------------------------------------- voAnalysisFactory::~voAnalysisFactory() { } //----------------------------------------------------------------------------- voAnalysis* voAnalysisFactory::createAnalysis(const QString& className) { Q_D(voAnalysisFactory); return d->AnalysisFactory.Create(className); } //----------------------------------------------------------------------------- QStringList voAnalysisFactory::registeredAnalysisNames() const { Q_D(const voAnalysisFactory); return d->AnalysisFactory.registeredObjectKeys(); } //----------------------------------------------------------------------------- template<typename AnalysisClassType> void voAnalysisFactory::registerAnalysis(const QString& analysisName) { Q_D(voAnalysisFactory); if (analysisName.isEmpty()) { qCritical() << "Failed to register analysis - analysisName is an empty string"; return; } if (this->registeredAnalysisNames().contains(analysisName)) { return; } d->AnalysisFactory.registerObject<AnalysisClassType>(analysisName); }
Use consistent symbols in example
/** @file @brief Implementation @date 2014 @author Ryan Pavlik <ryan@sensics.com> <http://sensics.com> */ // Copyright 2014 Sensics, 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. // Internal Includes #include <ogvr/PluginKit/PluginRegistrationC.h> // Library/third-party includes // - none // Standard includes // - none OGVR_PLUGIN(org_opengoggles_example_NullTracker) { return LIBFUNC_SUCCESS; }
/** @file @brief Implementation @date 2014 @author Ryan Pavlik <ryan@sensics.com> <http://sensics.com> */ // Copyright 2014 Sensics, 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. // Internal Includes #include <ogvr/PluginKit/PluginRegistrationC.h> // Library/third-party includes // - none // Standard includes // - none OGVR_PLUGIN(org_opengoggles_example_NullTracker) { return OGVR_PLUGIN_SUCCESS; }
Fix GPIO pin numbers to match MRAA change
#include <signal.h> #include <unistd.h> #include "mraa.hpp" bool running = true; bool relay_state = false; int last_touch; void sig_handler(int signo) { if (signo == SIGINT) running = false; } int main(int argc, char* argv[]) { mraa::Gpio* touch_gpio = new mraa::Gpio(492); mraa::Gpio* relay_gpio = new mraa::Gpio(463); mraa::Result response; int touch; signal(SIGINT, sig_handler); response = touch_gpio->dir(mraa::DIR_IN); if (response != mraa::SUCCESS) return 1; response = relay_gpio->dir(mraa::DIR_OUT); if (response != mraa::SUCCESS) return 1; relay_gpio->write(relay_state); while (running) { touch = touch_gpio->read(); if (touch == 1 && last_touch == 0) { relay_state = !relay_state; response = relay_gpio->write(relay_state); usleep(100000); } last_touch = touch; } delete relay_gpio; delete touch_gpio; return response; }
#include <signal.h> #include <unistd.h> #include "mraa.hpp" bool running = true; bool relay_state = false; int last_touch; void sig_handler(int signo) { if (signo == SIGINT) running = false; } int main(int argc, char* argv[]) { mraa::Gpio* touch_gpio = new mraa::Gpio(29); mraa::Gpio* relay_gpio = new mraa::Gpio(27); mraa::Result response; int touch; signal(SIGINT, sig_handler); response = touch_gpio->dir(mraa::DIR_IN); if (response != mraa::SUCCESS) return 1; response = relay_gpio->dir(mraa::DIR_OUT); if (response != mraa::SUCCESS) return 1; relay_gpio->write(relay_state); while (running) { touch = touch_gpio->read(); if (touch == 1 && last_touch == 0) { relay_state = !relay_state; response = relay_gpio->write(relay_state); usleep(100000); } last_touch = touch; } delete relay_gpio; delete touch_gpio; return response; }
Check that file ends with a newline (1 issue)
/* Copyright (C) 2008 Patrick Spendrin <ps_ml@gmx.de> This file is part of the KDE project This library is free software you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License aint with this library see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "GeoSceneXmlDataSource.h" #include "global.h" namespace Marble { GeoSceneXmlDataSource::GeoSceneXmlDataSource( const QString& name ) : GeoSceneAbstractDataset( name ) { } GeoSceneXmlDataSource::~GeoSceneXmlDataSource() { } QString GeoSceneXmlDataSource::filename() const { return m_filename; } void GeoSceneXmlDataSource::setFilename( const QString& fileName ) { m_filename = fileName; } QString GeoSceneXmlDataSource::type() { return "xmldatasource"; } }
/* Copyright (C) 2008 Patrick Spendrin <ps_ml@gmx.de> This file is part of the KDE project This library is free software you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License aint with this library see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "GeoSceneXmlDataSource.h" #include "global.h" namespace Marble { GeoSceneXmlDataSource::GeoSceneXmlDataSource( const QString& name ) : GeoSceneAbstractDataset( name ) { } GeoSceneXmlDataSource::~GeoSceneXmlDataSource() { } QString GeoSceneXmlDataSource::filename() const { return m_filename; } void GeoSceneXmlDataSource::setFilename( const QString& fileName ) { m_filename = fileName; } QString GeoSceneXmlDataSource::type() { return "xmldatasource"; } }
Remove unnecessary includes in template .cc
#include <sstream> #include <string> #include <ccspec/matcher.h> namespace ccspec { namespace matchers { // Public methods. template <typename U> template <typename V> bool Eq<U>::match(V actual_value) const { return actual_value == this->expected_value(); } template <typename U> std::string Eq<U>::desc() const { std::ostringstream s; s << "should equal " << this->expected_value(); return s.str(); } // Private methods. template<typename U> Eq<U>::Eq(U expected_value) : Matcher<Eq<U>, U>(expected_value) {} // Friend functions. template<typename U> Eq<U> eq(U expected_value) { return Eq<U>(expected_value); } } // namespace matchers } // namespace ccspec
#include <sstream> namespace ccspec { namespace matchers { // Public methods. template <typename U> template <typename V> bool Eq<U>::match(V actual_value) const { return actual_value == this->expected_value(); } template <typename U> std::string Eq<U>::desc() const { std::ostringstream s; s << "should equal " << this->expected_value(); return s.str(); } // Private methods. template<typename U> Eq<U>::Eq(U expected_value) : Matcher<Eq<U>, U>(expected_value) {} // Friend functions. template<typename U> Eq<U> eq(U expected_value) { return Eq<U>(expected_value); } } // namespace matchers } // namespace ccspec
Disable SCUs on non MSVC builds.
#include "All.h" #include "Common.cpp" #include "WhisperPeer.cpp"
#ifdef _MSC_VER #include "All.h" #include "Common.cpp" #include "WhisperPeer.cpp" #endif
Disable this test on Linux, because it will fail as soon as WebKit's version is rolled forward.
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/ui_test_utils.h" #include "net/base/mock_host_resolver.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebSocket) { FilePath websocket_root_dir; PathService::Get(chrome::DIR_TEST_DATA, &websocket_root_dir); websocket_root_dir = websocket_root_dir.AppendASCII("layout_tests") .AppendASCII("LayoutTests"); ui_test_utils::TestWebSocketServer server(websocket_root_dir); ASSERT_TRUE(RunExtensionTest("websocket")) << message_; }
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/ui_test_utils.h" #include "net/base/mock_host_resolver.h" // Disable this test on Linux, because it fails // http://crbug.com/40976 #if defined(OS_LINUX) #define WebSocket DISABLED_WebSocket #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebSocket) { FilePath websocket_root_dir; PathService::Get(chrome::DIR_TEST_DATA, &websocket_root_dir); websocket_root_dir = websocket_root_dir.AppendASCII("layout_tests") .AppendASCII("LayoutTests"); ui_test_utils::TestWebSocketServer server(websocket_root_dir); ASSERT_TRUE(RunExtensionTest("websocket")) << message_; }
Remove old and unnecessary cast
#include "xchainer/testing/numeric.h" #include <cassert> #include "xchainer/dtype.h" #include "xchainer/error.h" #include "xchainer/scalar.h" namespace xchainer { namespace testing { bool AllClose(const Array& a, const Array& b, double rtol, double atol) { if (a.shape() != b.shape()) { throw DimensionError("cannot compare Arrays of different shapes"); } if (a.dtype() != b.dtype()) { throw DtypeError("cannot compare Arrays of different Dtypes"); } return VisitDtype(a.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; auto total_size = a.shape().total_size(); auto adata = static_cast<const T*>(a.data().get()); auto bdata = static_cast<const T*>(b.data().get()); auto at = static_cast<const T>(atol); auto rt = static_cast<const T>(rtol); for (decltype(total_size) i = 0; i < total_size; i++) { if (std::abs(adata[i] - bdata[i]) > at + rt * std::abs(bdata[i])) { return false; } } return true; }); } } // namespace testing } // namespace xchainer
#include "xchainer/testing/numeric.h" #include <cassert> #include "xchainer/dtype.h" #include "xchainer/error.h" #include "xchainer/scalar.h" namespace xchainer { namespace testing { bool AllClose(const Array& a, const Array& b, double rtol, double atol) { if (a.shape() != b.shape()) { throw DimensionError("cannot compare Arrays of different shapes"); } if (a.dtype() != b.dtype()) { throw DtypeError("cannot compare Arrays of different Dtypes"); } return VisitDtype(a.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; auto total_size = a.shape().total_size(); auto* adata = static_cast<const T*>(a.data().get()); auto* bdata = static_cast<const T*>(b.data().get()); for (decltype(total_size) i = 0; i < total_size; i++) { if (std::abs(adata[i] - bdata[i]) > atol + rtol * std::abs(bdata[i])) { return false; } } return true; }); } } // namespace testing } // namespace xchainer
Use new RTCZero epoch API's
// Copyright (c) Arduino. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include <time.h> #include <sys/time.h> #include <RTCZero.h> RTCZero rtc; extern "C" { int _gettimeofday(struct timeval* tp, void* /*tzvp*/) { struct tm tm; tm.tm_isdst = -1; tm.tm_yday = 0; tm.tm_wday = 0; tm.tm_year = rtc.getYear() + 100; tm.tm_mon = rtc.getMonth() + 1; tm.tm_mday = rtc.getDay(); tm.tm_hour = rtc.getHours(); tm.tm_min = rtc.getMinutes(); tm.tm_sec = rtc.getSeconds(); tp->tv_sec = mktime(&tm); tp->tv_usec = 0; return 0; } int settimeofday(const struct timeval* tp, const struct timezone* /*tzp*/) { struct tm* tmp = gmtime(&tp->tv_sec); rtc.begin(); rtc.setDate(tmp->tm_mday, tmp->tm_mon - 1, tmp->tm_year - 100); rtc.setTime(tmp->tm_hour, tmp->tm_min, tmp->tm_sec); return 0; } }
// Copyright (c) Arduino. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include <time.h> #include <sys/time.h> #include <RTCZero.h> RTCZero rtc; extern "C" { int _gettimeofday(struct timeval* tp, void* /*tzvp*/) { tp->tv_sec = rtc.getEpoch(); tp->tv_usec = 0; return 0; } int settimeofday(const struct timeval* tp, const struct timezone* /*tzp*/) { rtc.begin(); rtc.setEpoch(tp->tv_sec); return 0; } }
Make gpsd positionprovider plugin compile with gpsd API 3, as of gpsd 2.90+.
// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2009 Eckhart Wörner <ewoerner@kde.org> // #include "GpsdConnection.h" #include "MarbleDebug.h" using namespace Marble; GpsdConnection::GpsdConnection( QObject* parent ) : QObject( parent ), m_timer( 0 ) { gps_data_t* data = m_gpsd.open(); if ( data ) { connect( &m_timer, SIGNAL( timeout() ), this, SLOT( update() ) ); m_timer.start( 1000 ); } else mDebug() << "Connection to gpsd failed, no position info available."; } void GpsdConnection::update() { gps_data_t* data = m_gpsd.query( "o" ); if ( data ) emit gpsdInfo( *data ); } #include "GpsdConnection.moc"
// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2009 Eckhart Wörner <ewoerner@kde.org> // #include "GpsdConnection.h" #include "MarbleDebug.h" using namespace Marble; GpsdConnection::GpsdConnection( QObject* parent ) : QObject( parent ), m_timer( 0 ) { gps_data_t* data = m_gpsd.open(); if ( data ) { #if GPSD_API_MAJOR_VERSION == 3 m_gpsd.stream( WATCH_ENABLE ); #endif connect( &m_timer, SIGNAL( timeout() ), this, SLOT( update() ) ); m_timer.start( 1000 ); } else mDebug() << "Connection to gpsd failed, no position info available."; } void GpsdConnection::update() { gps_data_t* data; #if GPSD_API_MAJOR_VERSION == 2 data = m_gpsd.query( "o" ); #elif GPSD_API_MAJOR_VERSION == 3 while ((data = m_gpsd.poll()) && !(data->set & POLICY_SET)) { data = m_gpsd.poll(); } #endif if ( data ) emit gpsdInfo( *data ); } #include "GpsdConnection.moc"
Remove rogue print statement from test
// Copyright 2014 MongoDB Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "catch.hpp" #include "helpers.hpp" #include <bsoncxx/builder/stream/document.hpp> #include <bsoncxx/json.hpp> #include <mongocxx/result/delete.hpp> TEST_CASE("delete", "[delete][result]") { bsoncxx::builder::stream::document build; build << "_id" << bsoncxx::oid{bsoncxx::oid::init_tag} << "nRemoved" << bsoncxx::types::b_int64{1}; mongocxx::result::bulk_write b(bsoncxx::document::value(build.view())); mongocxx::result::delete_result delete_result(std::move(b)); SECTION("returns correct removed count") { std::cout << bsoncxx::to_json(build.view()); REQUIRE(delete_result.deleted_count() == 1); } }
// Copyright 2014 MongoDB Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "catch.hpp" #include "helpers.hpp" #include <bsoncxx/builder/stream/document.hpp> #include <bsoncxx/json.hpp> #include <mongocxx/result/delete.hpp> TEST_CASE("delete", "[delete][result]") { bsoncxx::builder::stream::document build; build << "_id" << bsoncxx::oid{bsoncxx::oid::init_tag} << "nRemoved" << bsoncxx::types::b_int64{1}; mongocxx::result::bulk_write b(bsoncxx::document::value(build.view())); mongocxx::result::delete_result delete_result(std::move(b)); SECTION("returns correct removed count") { REQUIRE(delete_result.deleted_count() == 1); } }
Fix - Failed to returns the syscall names
/* ** Copyright (C) - Triton ** ** This program is under the terms of the LGPLv3 License. */ #include <iostream> #include <Syscalls.h> #include <TritonTypes.h> extern const char *syscallmap[]; const char *syscallNumberLinux64ToString(uint64 syscallNumber) { if (syscallNumber > 0 && syscallNumber < (uint64) NB_SYSCALL) return syscallmap[syscallNumber]; else return nullptr; }
/* ** Copyright (C) - Triton ** ** This program is under the terms of the LGPLv3 License. */ #include <iostream> #include <Syscalls.h> #include <TritonTypes.h> extern const char *syscallmap[]; const char *syscallNumberLinux64ToString(uint64 syscallNumber) { if (syscallNumber >= 0 && syscallNumber < (uint64) NB_SYSCALL) return syscallmap[syscallNumber]; else return nullptr; }
Replace posix_memalign with memalign in test.
// Test that LargeAllocator unpoisons memory before releasing it to the OS. // RUN: %clangxx_asan %s -o %t // The memory is released only when the deallocated chunk leaves the quarantine, // otherwise the mmap(p, ...) call overwrites the malloc header. // RUN: ASAN_OPTIONS=quarantine_size=1 %t #include <assert.h> #include <stdlib.h> #include <string.h> #include <sys/mman.h> int main() { const int kPageSize = 4096; void *p = NULL; posix_memalign(&p, kPageSize, 1024 * 1024); free(p); char *q = (char *)mmap(p, kPageSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON | MAP_FIXED, 0, 0); assert(q == p); memset(q, 42, kPageSize); munmap(q, kPageSize); return 0; }
// Test that LargeAllocator unpoisons memory before releasing it to the OS. // RUN: %clangxx_asan %s -o %t // The memory is released only when the deallocated chunk leaves the quarantine, // otherwise the mmap(p, ...) call overwrites the malloc header. // RUN: ASAN_OPTIONS=quarantine_size=1 %t #include <assert.h> #include <malloc.h> #include <string.h> #include <sys/mman.h> int main() { const int kPageSize = 4096; void *p = memalign(kPageSize, 1024 * 1024); free(p); char *q = (char *)mmap(p, kPageSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON | MAP_FIXED, 0, 0); assert(q == p); memset(q, 42, kPageSize); munmap(q, kPageSize); return 0; }
Fix duplicate test code introduced by running "patch -p0" twice
// Test that we use the suppressions from __asan_default_suppressions. // RUN: %clangxx_asan %s -o %t && not %run %t 2>&1 | FileCheck %s extern "C" { const char *__asan_default_suppressions() { return "FooBar"; } } // CHECK: AddressSanitizer: failed to parse suppressions int main() {} // Test that we use the suppressions from __asan_default_suppressions. // RUN: %clangxx_asan %s -o %t && not %run %t 2>&1 | FileCheck %s extern "C" { const char *__asan_default_suppressions() { return "FooBar"; } } // CHECK: AddressSanitizer: failed to parse suppressions int main() {}
// Test that we use the suppressions from __asan_default_suppressions. // RUN: %clangxx_asan %s -o %t && not %run %t 2>&1 | FileCheck %s extern "C" { const char *__asan_default_suppressions() { return "FooBar"; } } // CHECK: AddressSanitizer: failed to parse suppressions int main() {}
Update test output to k2.
#include <tests.hh> BEGIN_TEST(values, client, ) client.setErrorCallback(callback(&dump)); client.setCallback(callback(&dump), "output"); client.send("output << 1;"); //= D output 1 client.send("output << \"coin\";"); //= D output "coin" client.send("error << non.existent;"); //= E error 1.39-50: Unknown identifier: non.existent //= E error 1.39-50: EXPR evaluation failed client.send("var mybin = BIN 10 mybin header;1234567890;output << mybin;"); //= D output BIN 10 mybin header;1234567890 client.send("output << [\"coin\", 5, [3, mybin, 0]];"); //= D output ["coin", 5, [3, BIN 10 mybin header;1234567890, 0]] sleep(5); END_TEST
#include <tests.hh> BEGIN_TEST(values, client, ) client.setErrorCallback(callback(&dump)); client.setCallback(callback(&dump), "output"); client.send("output << 1;"); //= D output 1 client.send("output << \"coin\";"); //= D output "coin" client.send("error << nonexistent;"); //= E error 1.39-49: lookup failed: nonexistent client.send("var mybin = BIN 10 mybin header;1234567890;output << mybin;"); //= D output BIN 10 mybin header;1234567890 client.send("output << [\"coin\", 5, [3, mybin, 0]];"); //= D output ["coin", 5, [3, BIN 10 mybin header;1234567890, 0]] sleep(5); END_TEST
Remove check that causes more harm than good.
/* * User.cpp * * Created on: May 1, 2017 * Author: Daniel */ #include "User.hpp" using namespace std; User::User(string cuname, string chash) { uname = cuname; hash = chash; commandfd = 0; mediafd = 0; sessionkey = 0; } User::~User() { // TODO Auto-generated destructor stub } string User::getUname() { return uname; } string User::getHash() { return hash; } uint32_t User::getCommandfd() { return commandfd; } void User::setCommandfd(uint32_t newCommandfd) { if(newCommandfd > 4) { commandfd = newCommandfd; } } uint32_t User::getMediafd() { return mediafd; } void User::setMediafd(uint32_t newMediafd) { if(newMediafd > 4) { mediafd = newMediafd; } } uint64_t User::getSessionkey() { return sessionkey; } void User::setSessionkey(uint64_t newSessionkey) { sessionkey = newSessionkey; }
/* * User.cpp * * Created on: May 1, 2017 * Author: Daniel */ #include "User.hpp" using namespace std; User::User(string cuname, string chash) { uname = cuname; hash = chash; commandfd = 0; mediafd = 0; sessionkey = 0; } User::~User() { // TODO Auto-generated destructor stub } string User::getUname() { return uname; } string User::getHash() { return hash; } uint32_t User::getCommandfd() { return commandfd; } void User::setCommandfd(uint32_t newCommandfd) { commandfd = newCommandfd; } uint32_t User::getMediafd() { return mediafd; } void User::setMediafd(uint32_t newMediafd) { mediafd = newMediafd; } uint64_t User::getSessionkey() { return sessionkey; } void User::setSessionkey(uint64_t newSessionkey) { sessionkey = newSessionkey; }
Mark ExtensionApiTest.ExecuteScript DISABLED because it's not only flaky, but crashy and it has been ignored for weeks!
// Copyright (c) 20109 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "net/base/mock_host_resolver.h" // This test failed at times on the Vista dbg builder and has been marked as // flaky for now. Bug http://code.google.com/p/chromium/issues/detail?id=28630 IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_ExecuteScript) { // We need a.com to be a little bit slow to trigger a race condition. host_resolver()->AddRuleWithLatency("a.com", "127.0.0.1", 500); host_resolver()->AddRule("b.com", "127.0.0.1"); host_resolver()->AddRule("c.com", "127.0.0.1"); StartHTTPServer(); ASSERT_TRUE(RunExtensionTest("executescript/basic")) << message_; ASSERT_TRUE(RunExtensionTest("executescript/in_frame")) << message_; ASSERT_TRUE(RunExtensionTest("executescript/permissions")) << message_; }
// Copyright (c) 20109 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "net/base/mock_host_resolver.h" // EXTREMELY flaky, crashy, and bad. See http://crbug.com/28630 and don't dare // to re-enable without a real fix or at least adding more debugging info. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_ExecuteScript) { // We need a.com to be a little bit slow to trigger a race condition. host_resolver()->AddRuleWithLatency("a.com", "127.0.0.1", 500); host_resolver()->AddRule("b.com", "127.0.0.1"); host_resolver()->AddRule("c.com", "127.0.0.1"); StartHTTPServer(); ASSERT_TRUE(RunExtensionTest("executescript/basic")) << message_; ASSERT_TRUE(RunExtensionTest("executescript/in_frame")) << message_; ASSERT_TRUE(RunExtensionTest("executescript/permissions")) << message_; }
Revert "Avoid hang in vepalib::ws::Acceptor::accept_main on systems where"
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "acceptor.h" #include <vespa/vespalib/net/socket_spec.h> #include <functional> #ifdef __APPLE__ #include <poll.h> #endif namespace vespalib::ws { void Acceptor::accept_main(Handler<Socket> &socket_handler) { #ifdef __APPLE__ _server_socket.set_blocking(false); #endif while (!_is_closed) { #ifdef __APPLE__ pollfd fds; fds.fd = _server_socket.get_fd(); fds.events = POLLIN; fds.revents = 0; int res = poll(&fds, 1, 10); if (res < 1 || fds.revents == 0 || _is_closed) { continue; } #endif SocketHandle handle = _server_socket.accept(); if (handle.valid()) { #ifdef __APPLE__ handle.set_blocking(true); #endif socket_handler.handle(std::make_unique<SimpleSocket>(std::move(handle))); } } } Acceptor::Acceptor(int port_in, Handler<Socket> &socket_handler) : _server_socket(port_in), _is_closed(false), _accept_thread(&Acceptor::accept_main, this, std::ref(socket_handler)) { } Acceptor::~Acceptor() { _server_socket.shutdown(); _is_closed = true; _accept_thread.join(); } } // namespace vespalib::ws
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "acceptor.h" #include <vespa/vespalib/net/socket_spec.h> #include <functional> namespace vespalib::ws { void Acceptor::accept_main(Handler<Socket> &socket_handler) { while (!_is_closed) { SocketHandle handle = _server_socket.accept(); if (handle.valid()) { socket_handler.handle(std::make_unique<SimpleSocket>(std::move(handle))); } } } Acceptor::Acceptor(int port_in, Handler<Socket> &socket_handler) : _server_socket(port_in), _is_closed(false), _accept_thread(&Acceptor::accept_main, this, std::ref(socket_handler)) { } Acceptor::~Acceptor() { _server_socket.shutdown(); _is_closed = true; _accept_thread.join(); } } // namespace vespalib::ws
Add source for demo of odd VS 2013 behaviour
#include <iostream> int main(int argc, char* argv[]) { }
#include <functional> #include <type_traits> #include <iostream> int main(int argc, char* argv []) { auto f_1 = [](int x) { return x; }; std::cout << "auto f_1 = [](int x) { return x; };\n"; auto f_2 = [](int x, int y) { return x + y; }; std::cout << "auto f_2 = [](int x, int y) { return x + y; };\n"; std::cout << "\n"; std::cout << "std::is_constructible<std::function<int(int)>, decltype(f_1)>::value " << std::is_constructible<std::function<int(int)>, decltype(f_1)>::value << "\n"; std::cout << "std::is_constructible<std::function<int(int)>, decltype(f_2)>::value " << std::is_constructible<std::function<int(int)>, decltype(f_2)>::value << "\n"; std::cout << "\n"; std::cout << "std::is_constructible<std::function<int(int,int)>, decltype(f_1)>::value " << std::is_constructible<std::function<int(int, int)>, decltype(f_1)>::value << "\n"; std::cout << "std::is_constructible<std::function<int(int,int)>, decltype(f_2)>::value " << std::is_constructible<std::function<int(int, int)>, decltype(f_2)>::value << "\n"; std::function<int(int)> f_i_i(f_1); //std::function<int(int)> f_i_ii(f_2); // does not compile as it is not constructible //std::function<int(int,int)> f_ii_i(f_1); // does not compile as it is not constructible std::function<int(int,int)> f_ii_ii(f_2); return 0; }
Revert 64157 - Marking ExtensionApiTest.Infobars as FAILS until 10.5 issue is resolved. Reverting in order to create a proper CL for it. BUG=60990
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" #if defined(TOOLKIT_VIEWS) #define MAYBE_Infobars Infobars #elif defined(OS_MACOSX) // Temporarily marking as FAILS. See http://crbug.com/60990 for details. #define MAYBE_Infobars FAILS_Infobars #else // Need to finish port to Linux. See http://crbug.com/39916 for details. #define MAYBE_Infobars DISABLED_Infobars #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) { // TODO(finnur): Remove once infobars are no longer experimental (bug 39511). CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("infobars")) << message_; }
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" #if defined(TOOLKIT_VIEWS) || defined(OS_MACOSX) #define MAYBE_Infobars Infobars #else // Need to finish port to Linux. See http://crbug.com/39916 for details. #define MAYBE_Infobars DISABLED_Infobars #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) { // TODO(finnur): Remove once infobars are no longer experimental (bug 39511). CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("infobars")) << message_; }
Add a test for !ptr-to-member (should fail)
// RUN: %clang_cc1 -fsyntax-only -verify %s -std=c++0x struct S { int i; int mem(int); }; int foo(int S::* ps, S *s) { return (s->*ps)(1); // expected-error {{called object type 'int' is not a function or function pointer}} } struct S2 { int bitfield : 1; }; int S2::*pf = &S2::bitfield; // expected-error {{address of bit-field requested}} struct S3 { void m(); }; void f3(S3* p, void (S3::*m)()) { p->*m; // expected-error {{a bound member function may only be called}} (void)(p->*m); // expected-error {{a bound member function may only be called}} (void)(void*)(p->*m); // expected-error {{a bound member function may only be called}} (void)reinterpret_cast<void*>(p->*m); // expected-error {{a bound member function may only be called}} if (p->*m) {} // expected-error {{a bound member function may only be called}} p->m; // expected-error {{a bound member function may only be called}} }
// RUN: %clang_cc1 -fsyntax-only -verify %s -std=c++0x struct S { int i; int mem(int); }; int foo(int S::* ps, S *s) { return (s->*ps)(1); // expected-error {{called object type 'int' is not a function or function pointer}} } struct S2 { int bitfield : 1; }; int S2::*pf = &S2::bitfield; // expected-error {{address of bit-field requested}} struct S3 { void m(); }; void f3(S3* p, void (S3::*m)()) { p->*m; // expected-error {{a bound member function may only be called}} (void)(p->*m); // expected-error {{a bound member function may only be called}} (void)(void*)(p->*m); // expected-error {{a bound member function may only be called}} (void)reinterpret_cast<void*>(p->*m); // expected-error {{a bound member function may only be called}} if (p->*m) {} // expected-error {{a bound member function may only be called}} if (!p->*m) {} // expected-error {{a bound member function may only be called}} if (p->m) {}; // expected-error {{a bound member function may only be called}} if (!p->m) {}; // expected-error {{a bound member function may only be called}} }
Update OS test, avoid hard-coded values
// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2016-2017 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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 <common.cxx> #include <kernel/os.hpp> CASE("version() returns string representation of OS version") { EXPECT(OS::version() != ""); EXPECT(OS::version().front() == 'v'); } CASE("cycles_since_boot() returns clock cycles since boot") { EXPECT(OS::cycles_since_boot() != 0ull); } CASE("page_size() returns page size") { EXPECT(OS::page_size() == 4096u); } CASE("page_nr_from_addr() returns page number from address") { EXPECT(OS::page_nr_from_addr(512) == 0u); }
// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2016-2017 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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 <common.cxx> #include <kernel/os.hpp> CASE("version() returns string representation of OS version") { EXPECT(OS::version() != ""); EXPECT(OS::version().front() == 'v'); } CASE("cycles_since_boot() returns clock cycles since boot") { EXPECT(OS::cycles_since_boot() != 0ull); } CASE("page_size() returns page size") { EXPECT(OS::page_size() == 4096u); } CASE("page_nr_from_addr() returns page number from address") { EXPECT(OS::addr_to_page(512) == 0u); EXPECT(OS::page_to_addr(1) > 0u); }
Clean up after running tests.
#define BOOST_TEST_NO_MAIN #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE "VAST Unit Test Suite" #include "test.h" #include "vast/configuration.h" #include "vast/logger.h" int main(int argc, char* argv[]) { vast::configuration config; config.load("/dev/null"); vast::init(config); boost::unit_test::unit_test_log.set_stream(vast::logger::get()->console()); char const* args[] = {"", "--log_level=test_suite"}; auto rc = boost::unit_test::unit_test_main( &init_unit_test, sizeof(args) / sizeof(char*), const_cast<char**>(args)); if (rc) LOG(error, core) << "unit test suite exited with error code " << rc; return rc; }
#define BOOST_TEST_NO_MAIN #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE "VAST Unit Test Suite" #include <ze.h> #include "test.h" #include "vast/configuration.h" #include "vast/logger.h" int main(int argc, char* argv[]) { vast::configuration config; config.load("/dev/null"); vast::init(config); boost::unit_test::unit_test_log.set_stream(vast::logger::get()->console()); auto rc = boost::unit_test::unit_test_main(&init_unit_test, argc, argv); if (rc) LOG(error, core) << "unit test suite exited with error code " << rc; ze::rm(ze::logger::filename()); ze::shutdown(); return rc; }
Move variable definition to the point just before it is needed.
#include <iostream> #include "pool.h" #include "machine.h" #include "job.h" int main () { Pool machine_pool; Job first_job(1, "one"); machine_pool.add_machine(Machine("one")); machine_pool.add_machine(Machine("two")); machine_pool.add_job(first_job); machine_pool.add_job(Job(2, "two")); std::cout << "Job 1 moveable: " << first_job.moveable() << std::endl; return 0; }
#include <iostream> #include "pool.h" #include "machine.h" #include "job.h" int main () { Pool machine_pool; machine_pool.add_machine(Machine("one")); machine_pool.add_machine(Machine("two")); Job first_job(1, "one"); machine_pool.add_job(first_job); machine_pool.add_job(Job(2, "two")); std::cout << "Job 1 moveable: " << first_job.moveable() << std::endl; return 0; }
Remove unneeded includes from the image loader
// Copyright (C) 2018 Elviss Strazdins // This file is part of the Ouzel engine. #include "LoaderImage.hpp" #include "Cache.hpp" #include "graphics/ImageDataSTB.hpp" #include "graphics/Texture.hpp" #define STBI_NO_PSD #define STBI_NO_HDR #define STBI_NO_PIC #define STBI_NO_GIF #define STBI_NO_PNM #include "stb_image.h" namespace ouzel { namespace assets { LoaderImage::LoaderImage(): Loader(TYPE, {"jpg", "jpeg", "png", "bmp", "tga"}) { } bool LoaderImage::loadAsset(const std::string& filename, const std::vector<uint8_t>& data, bool mipmaps) { graphics::ImageDataSTB image; if (!image.init(data)) return false; std::shared_ptr<graphics::Texture> texture(new graphics::Texture()); if (!texture->init(image.getData(), image.getSize(), 0, mipmaps ? 0 : 1, image.getPixelFormat())) return false; cache->setTexture(filename, texture); return true; } } // namespace assets } // namespace ouzel
// Copyright (C) 2018 Elviss Strazdins // This file is part of the Ouzel engine. #include "LoaderImage.hpp" #include "Cache.hpp" #include "graphics/ImageDataSTB.hpp" #include "graphics/Texture.hpp" namespace ouzel { namespace assets { LoaderImage::LoaderImage(): Loader(TYPE, {"jpg", "jpeg", "png", "bmp", "tga"}) { } bool LoaderImage::loadAsset(const std::string& filename, const std::vector<uint8_t>& data, bool mipmaps) { graphics::ImageDataSTB image; if (!image.init(data)) return false; std::shared_ptr<graphics::Texture> texture(new graphics::Texture()); if (!texture->init(image.getData(), image.getSize(), 0, mipmaps ? 0 : 1, image.getPixelFormat())) return false; cache->setTexture(filename, texture); return true; } } // namespace assets } // namespace ouzel
Define a function setWindowToBlack() to create a window with a black background.
/* * Project: Particle Fire Explosion * Stage: 1 * File: main.cpp * Author: suyashd95 */ #include <iostream> #include <SDL.h> using namespace std; int main() { if(SDL_Init(SDL_INIT_VIDEO) < 0) { cout << "SDL_Init failed." << endl; return 1; } cout << "SDL_Init succeeded." << endl; SDL_Quit(); return 0; }
/* * Project: Particle Fire Explosion * Stage: 1 * File: main.cpp * Author: suyashd95 */ #include <iostream> #include <SDL.h> using namespace std; void setWindowToBlack(SDL_Window* window) { // We must call SDL_CreateRenderer in order for draw calls to affect this window. SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, 0); // Select the color for drawing. It is set to black here. SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE); // Clear the entire screen to our selected color. SDL_RenderClear(renderer); // Up until now everything was drawn behind the scenes. This will show the new, black contents of the window. SDL_RenderPresent(renderer); } int main() { const int SCREEN_WIDTH = 800; const int SCREEN_HEIGHT = 600; if (SDL_Init(SDL_INIT_VIDEO) < 0) { cout << "SDL_Init Failed." << endl; return 1; } // Create an application window. SDL_Window* window = SDL_CreateWindow("Particle Fire Explosion", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); // Set Window background to Black. setWindowToBlack(window); // Check that window has been successfully created if(window == NULL) { // Same as if(!window) printf("Could not show window: %s\n", SDL_GetError()); // Outputs the error code/statement for debugging purposes SDL_Quit(); return 2; } bool quit = false; SDL_Event event; while(!quit) { // Update particles // Draw particles // Check for messages/events while(SDL_PollEvent(&event)) { if(event.type == SDL_QUIT) { quit = true; } } } // SDL_Delay(10000); Pauses or delays the execution of the program SDL_DestroyWindow(window); SDL_Quit(); return 0; }
Mark ExtensionApiTest.Popup as FLAKY, it is still flaky.
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Popup) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("popup")) << message_; }
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" // Flaky, http://crbug.com/46601. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_Popup) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("popup")) << message_; }
Fix setting NULL as db column value
/* * Illarionserver - server for the game Illarion * Copyright 2011 Illarion e.V. * * This file is part of Illarionserver. * * Illarionserver is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * Illarionserver 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 General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * Illarionserver. If not, see <http://www.gnu.org/licenses/>. */ #include "db/QueryAssign.hpp" using namespace Database; QueryAssign::QueryAssign(const Connection &connection) : connection(connection) { } void QueryAssign::addAssignColumnNull(const std::string &column) { Query::appendToStringList(assignColumns, Query::escapeAndChainKeys("", column) + " = nullptr"); } std::string &QueryAssign::buildQuerySegment() { return assignColumns; }
/* * Illarionserver - server for the game Illarion * Copyright 2011 Illarion e.V. * * This file is part of Illarionserver. * * Illarionserver is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * Illarionserver 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 General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * Illarionserver. If not, see <http://www.gnu.org/licenses/>. */ #include "db/QueryAssign.hpp" using namespace Database; QueryAssign::QueryAssign(const Connection &connection) : connection(connection) { } void QueryAssign::addAssignColumnNull(const std::string &column) { Query::appendToStringList(assignColumns, Query::escapeAndChainKeys("", column) + " = NULL"); } std::string &QueryAssign::buildQuerySegment() { return assignColumns; }
Add vector comparision test case
#include <Value.h> namespace tests { namespace valueSuite { TEST(ValueSuite, UInt8Test) { Value<uint8_t, 1, 3, true> v0={{{13, 37}, {1, 1}, {3, 7}}}; Value<uint8_t, 1, 3, true> v2={{{73, 1}, {3, 1}, {7, 1}}}; EXPECT_EQ(v0, v0) << "Equally assigned values are not equal"; EXPECT_NE(v0, v2) << "Unequally assigned values are equal"; EXPECT_FALSE(v0==v2) << "Unequally assigned values are equal"; } }}
#include <Value.h> namespace tests { namespace valueSuite { TEST(ValueSuite, uInt8Test) { Value<uint8_t, 1, 3, true> v0={{{13, 37}, {1, 1}, {3, 7}}}; Value<uint8_t, 1, 3, true> v2={{{73, 1}, {3, 1}, {7, 1}}}; EXPECT_EQ(v0, v0) << "Equally assigned values are not equal"; EXPECT_NE(v0, v2) << "Unequally assigned values are equal"; EXPECT_FALSE(v0==v2) << "Unequally assigned values are equal"; EXPECT_FALSE((v0<v2).prod()) << "Vector comparision failed"; } }}
Enable the statistics in the task only if the user want to display the stats.
#include "Simulation.hpp" using namespace aff3ct; using namespace aff3ct::simulation; Simulation ::Simulation(const factory::Simulation::parameters& simu_params) : params(simu_params) { } Simulation ::~Simulation() { } void Simulation ::build_communication_chain() { _build_communication_chain(); for (auto &m : modules) for (auto mm : m.second) if (mm != nullptr) for (auto &t : mm->tasks) { t.second->set_autoexec (true); t.second->set_autoalloc(true); t.second->set_stats (true); // enable the debug mode in the modules if (params.debug) { t.second->set_debug(true); if (params.debug_limit) t.second->set_debug_limit((uint32_t)params.debug_limit); if (params.debug_precision) t.second->set_debug_precision((uint8_t)params.debug_precision); } } }
#include "Simulation.hpp" using namespace aff3ct; using namespace aff3ct::simulation; Simulation ::Simulation(const factory::Simulation::parameters& simu_params) : params(simu_params) { } Simulation ::~Simulation() { } void Simulation ::build_communication_chain() { _build_communication_chain(); for (auto &m : modules) for (auto mm : m.second) if (mm != nullptr) for (auto &t : mm->tasks) { t.second->set_autoexec (true); t.second->set_autoalloc(true); if (params.statistics) t.second->set_stats(true); // enable the debug mode in the modules if (params.debug) { t.second->set_debug(true); if (params.debug_limit) t.second->set_debug_limit((uint32_t)params.debug_limit); if (params.debug_precision) t.second->set_debug_precision((uint8_t)params.debug_precision); } } }
Send triggered events to the instances and the controllers
#include "engine/events-manager.h" #include "engine/game-manager.h" void EventsManager::EventsLoop(sf::RenderWindow* window) { sf::Event event; auto instances = GameManager::GetInstancesManager(); while (window->pollEvent(event)) { switch (event.type) { case sf::Event::Closed: window->close(); break; case sf::Event::KeyPressed: instances->KeyPressed(event.key); break; case sf::Event::KeyReleased: instances->KeyReleased(event.key); break; case sf::Event::MouseButtonPressed: instances->MousePressed(event.mouseButton); break; case sf::Event::MouseButtonReleased: instances->MouseReleased(event.mouseButton); break; case sf::Event::MouseMoved: instances->MouseMoved(event.mouseMove); break; default: break; } } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Q)) { window->close(); } } void EventsManager::Trigger(GameEvent event) { }
#include "engine/events-manager.h" #include "engine/game-manager.h" void EventsManager::EventsLoop(sf::RenderWindow* window) { sf::Event event; auto instances = GameManager::GetInstancesManager(); while (window->pollEvent(event)) { switch (event.type) { case sf::Event::Closed: window->close(); break; case sf::Event::KeyPressed: instances->KeyPressed(event.key); break; case sf::Event::KeyReleased: instances->KeyReleased(event.key); break; case sf::Event::MouseButtonPressed: instances->MousePressed(event.mouseButton); break; case sf::Event::MouseButtonReleased: instances->MouseReleased(event.mouseButton); break; case sf::Event::MouseMoved: instances->MouseMoved(event.mouseMove); break; default: break; } } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Q)) { window->close(); } } void EventsManager::Trigger(GameEvent event) { auto mapController = GameManager::GetMapController(); mapController->EventTriggered(event); auto playerController = GameManager::GetPlayerController(); playerController->EventTriggered(event); auto instances = GameManager::GetInstancesManager(); instances->EventTriggered(event); }
Test adding items to the db
#include "Course.h" #include <cstdio> #include <iostream> using namespace std; int main() { if (remove("test-0.sqlite") != 0) { cout << "Error with deletion of database file\n"; } else { cout << "Database file successfully deleted\n"; } // test instantiation of a Course object. cout << "Testing instantiation of a Course object:" << endl; Course course("test-0"); cout << "Created " << course.getName() << endl; cout << "All Assignments:" << endl; for (auto it : course.assignments) { cout << it.first << "=>" << it.second << '\n'; } }
#include "Course.h" #include "Assignment.h" #include <cstdio> #include <iostream> using namespace std; int main() { if (remove("test-0.sqlite") != 0) { cout << "Error with deletion of database file\n"; } else { cout << "Database file successfully deleted\n"; } // test instantiation of a Course object. cout << "Testing instantiation of a Course object:" << endl; Course course("test-0"); cout << "Created " << course.getName() << endl; cout << "All Assignments: " << course.assignments.size() << endl; cout << "All Categories: " << course.categories.size() << endl; cout << "All Students: " << course.students.size() << endl; cout << "All Submitted: " << course.submitted.size() << endl; // Test adding items to the db Category c1(0, "Homework", 20, course.getDb()); Category c2(0, "Labs", 30, course.getDb()); Category c3(0, "Exams", 50, course.getDb()); c1.insert(); c2.insert(); c3.insert(); course.categories[c1.getId()] = &c1; course.categories[c2.getId()] = &c2; course.categories[c3.getId()] = &c3; for (auto it : course.categories) { cout << it.first << " " << it.second->getName() << endl; } }
Add c++11 thread creation with functor object. It generates random vector of 1024 integers and creates two threads to summarize bottom and top half respectfully.
#include <iostream> #include <vector> #include <thread> #include <algorithm> #include <cstdlib> class AccumulatorFunctor { public: void operator() (const std::vector<int> &v, unsigned long long &acm, unsigned int beginIndex, unsigned int endIndex) { acm = 0; for (unsigned int i = beginIndex; i < endIndex; ++i) { acm += v[i]; } } unsigned long long acm; }; int main() { std::vector<int> v(1024); srand(time(nullptr)); std::generate(v.begin(), v.end(), [&v]() { return rand() % v.size(); } ); for_each(begin(v), end(v), [](int i) { std::cout << i << ' '; } ); AccumulatorFunctor accumulator1 = AccumulatorFunctor(); AccumulatorFunctor accumulator2 = AccumulatorFunctor(); std::thread t1(std::ref(accumulator1), std::ref(v), 0, v.size() / 2); std::thread t2(std::ref(accumulator2), std::ref(v), v.size() / 2, v.size()); t1.join(); t2.join(); std::cout << "acm1: " << accumulator1.acm << std::endl; std::cout << "acm2: " << accumulator2.acm << std::endl; std::cout << "acm1 + acm2: " << accumulator1.acm + accumulator2.acm << std::endl; return 0; }
Test case for revision 69683.
// RUN: %llvmgcc -c -g %s -o - | llc -fast -f -o %t.s // RUN: %compile_c %t.s -o %t.o // PR4025 template <typename _Tp> class vector { public: ~vector () { } }; class Foo { ~Foo(); class FooImpl *impl_; }; namespace { class Bar; } class FooImpl { vector<Bar*> thing; }; Foo::~Foo() { delete impl_; }
Add cpp program for postorder recursive Traversal
#include<iostream> using namespace std; struct node { int data; struct node *left; struct node *right; }; struct node *createNode(int val) { struct node *temp = (struct node *)malloc(sizeof(struct node)); temp->data = val; temp->left = temp->right = NULL; return temp; } void postorder(struct node *root) { if (root != NULL) { postorder(root->left); postorder(root->right); cout<<root->data<<" "; } } struct node* insertNode(struct node* node, int val) { if (node == NULL) return createNode(val); if (val < node->data) node->left = insertNode(node->left, val); else if (val > node->data) node->right = insertNode(node->right, val); return node; } int main() { struct node *root = NULL; root = insertNode(root, 4); insertNode(root, 5); insertNode(root, 2); insertNode(root, 9); insertNode(root, 1); insertNode(root, 3); cout<<"Post-Order traversal of the Binary Search Tree is: "; postorder(root); return 0; }
Add tests for new feature
// The MIT License (MIT) // Copyright (c) 2014 Rapptz // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #include <catch.hpp> #include <jsonpp/value.hpp> TEST_CASE("accessors", "[subscripts-accessors]") { json::value v = { json::object{ {"test", 1} }, nullptr, "my_string", 1.0 }; json::value o = json::object{ {"key", "value"}, {"int", 1} }; SECTION("get from json::array") { REQUIRE(v[0].is<json::object>()); REQUIRE(v[1].is<json::null>()); REQUIRE(v[2].is<std::string>()); REQUIRE(v[3].is<double>()); REQUIRE(v[3].is<float>()); REQUIRE(v[3].is<int>()); REQUIRE(v[4].is<json::null>()); //Never throw, return json::null }; SECTION("get from json::object") { REQUIRE(o["key"].is<std::string>()); REQUIRE(o["int"].is<int>()); REQUIRE(o["unexist"].is<json::null>()); //Never throw, return json::null }; SECTION("get from complex structure") { REQUIRE(v[0]["test"].is<int>()); REQUIRE(v[0]["test"].as<int>() == 1); }; }
Add implementation of Shared Pointer
/* * Copyright (C) 2015-2016 Pavel Dolgov * * See the LICENSE file for terms of use. */ #include <bits/stdc++.h> struct Foo { public: Foo() { std::cout << "Foo's constructor." << std::endl; } ~Foo() { std::cout << "Foo's destructor." << std::endl; } }; template<typename T> class SharedPtr { private: struct Storage { int counter; T* obj; }; Storage* storage_; public: SharedPtr(): storage_(0) { reset(); } explicit SharedPtr(T* obj): storage_(0) { reset(obj); } SharedPtr(const SharedPtr& ptr): storage_(0) { reset(ptr); } ~SharedPtr() { reset(); } bool empty() { return storage_ == 0; } void reset() { if (storage_ != 0) { storage_->counter -= 1; if (storage_->counter == 0) { delete storage_->obj; delete storage_; } storage_ = 0; } } void reset(T* t) { reset(); if (t != 0) { storage_ = new Storage(); storage_->obj = t; storage_->counter = 1; } } void reset(const SharedPtr& ptr) { reset(); if (ptr.storage_ != 0) { storage_ = ptr.storage_; storage_->counter += 1; } } SharedPtr& operator=(const SharedPtr& ptr) { reset(ptr); return *this; } }; int main() { std::cout << "zer0main's shared pointer" << std::endl; SharedPtr<Foo> foo_ptr = SharedPtr<Foo>(new Foo()); std::cout << "foo_ptr is empty: " << foo_ptr.empty() << std::endl; SharedPtr<Foo> foo_ptr2 = foo_ptr; std::cout << "foo_ptr is empty: " << foo_ptr.empty() << std::endl; foo_ptr.reset(); std::cout << "foo_ptr is empty: " << foo_ptr.empty() << std::endl; foo_ptr.reset(new Foo()); std::cout << "foo_ptr is empty: " << foo_ptr.empty() << std::endl; foo_ptr.reset(foo_ptr2); SharedPtr<Foo> foo_ptr3; std::cout << "foo_ptr3 is empty: " << foo_ptr3.empty() << std::endl; foo_ptr3 = foo_ptr2; std::cout << "foo_ptr3 is empty: " << foo_ptr3.empty() << std::endl; return 0; }
Add solution for 190. Reverse Bits.
/** * link: https://leetcode.com/problems/reverse-bits/ */ class Solution { public: uint32_t reverseBits(uint32_t n) { bitset<32> res(n); string str = res.to_string(); reverse(str.begin(), str.end()); return bitset<32>(str).to_ulong(); } };
Add C++ binary search implementation (recursive and iterative)
#include <cassert> #include <vector> template <class RandomAccessIterator, class KeyValue, class DefaultValue> DefaultValue recursive_binary_search( RandomAccessIterator start, RandomAccessIterator end, KeyValue key, DefaultValue default_value) { if (start == end) { return default_value; } RandomAccessIterator middle = start + ((end - start) / 2); if (*middle == key) { return middle; } else if (*middle < key) { return recursive_binary_search(middle + 1, end, key, default_value); } else { return recursive_binary_search(start, middle, key, default_value); } } template <class RandomAccessIterator, class Value> RandomAccessIterator recursive_binary_search(RandomAccessIterator first, RandomAccessIterator last, Value key) { return recursive_binary_search(first, last, key, last); } template <class RandomAccessIterator, class Value> RandomAccessIterator iterative_binary_search(RandomAccessIterator first, RandomAccessIterator last, Value key) { RandomAccessIterator start, end; start = first; end = last; while (start != end) { RandomAccessIterator middle = start + ((end - start) / 2); if (*middle == key) { return middle; } else if (*middle < key) { start = middle + 1; } else { end = middle; } } return last; } int main(int argc, char** argv) { int seq[] = {1, 1, 2, 5, 9, 11, 11, 11, 12, 18, 29, 37, 38, 40, 67, 78, 94, 94}; std::vector<int> sorted_seq(seq, seq + (sizeof seq / sizeof seq[0])); assert(recursive_binary_search(sorted_seq.begin(), sorted_seq.end(), 12) == sorted_seq.begin() + 8); assert(recursive_binary_search(sorted_seq.begin(), sorted_seq.end(), 13) == sorted_seq.end()); assert(iterative_binary_search(sorted_seq.begin(), sorted_seq.end(), 12) == sorted_seq.begin() + 8); assert(iterative_binary_search(sorted_seq.begin(), sorted_seq.end(), 13) == sorted_seq.end()); return 0; }
Test for llvm-gcc patch 73564.
// RUN: %llvmgxx -c -emit-llvm %s -o /dev/null -g // This crashes if we try to emit debug info for TEMPLATE_DECL members. template <class T> class K2PtrVectorBase {}; template <class T> class K2Vector {}; template <class U > class K2Vector<U*> : public K2PtrVectorBase<U*> {}; class ScriptInfoManager { void PostRegister() ; template <class SI> short ReplaceExistingElement(K2Vector<SI*>& v); }; void ScriptInfoManager::PostRegister() {}
Add framework for image annotation implementation
#include "fish_detector/image_annotator/image_annotation.h" namespace fish_detector { namespace image_annotator { ImageAnnotation::ImageAnnotation(const std::string& image_file, const std::string& species, const std::string& subspecies, uint64_t id, const Rect &rect) : image_file_(image_file) , species_(species) , subspecies_(subspecies) , id_(id) , rect_(rect) { } ImageAnnotation::ImageAnnotation() : image_file_() , species_() , subspecies_() , id_(0) , rect_(0, 0, 0, 0) { } pt::ptree ImageAnnotation::write() const { pt::ptree tree; return tree; } void ImageAnnotation::read(const pt::ptree &tree) { } ImageAnnotationList::ImageAnnotationList() : list_() , by_file_() , by_species_() { } void ImageAnnotationList::insert(const ImageAnnotation &annotation) { } void ImageAnnotationList::remove(const std::string &image_file, uint64_t id) { } void ImageAnnotationList::write() const { } void ImageAnnotationList::read(const std::vector<std::string> &filenames) { } }} // namespace fish_detector::image_annotator
Divide two numbers (use substract.)
/** * Divide Two Integers * * cpselvis (cpselvis@gmail.com) * August 25th, 2016 */ #include<iostream> #include<cmath> using namespace std; class Solution { public: int divide(int dividend, int divisor) { if (divisor == 0 || (dividend == INT_MIN && divisor == -1)) { return INT_MAX; } int sign = ((dividend > 0) ^ (divisor > 0 )) ? -1 : 1; // ^ in C++ means XOR, when condition returns same result , then value is 0, or value is 1. long long int dvd = labs(dividend); // abs is only used for int type, when input is long int, use labs, float, use fabs. long long int dvr = labs(divisor); int ret = 0; while (dvd >= dvr) { int multiple = 1; long long int tmp = dvr; while (dvd >= (tmp << 1)) { tmp <<= 1; multiple <<= 1; } dvd -= tmp; ret += multiple; } return ret * sign; } }; int main(int argc, char **argv) { Solution s; cout << s.divide(6, 2) << endl; cout << s.divide(-1, 1) << endl; cout << s.divide(-2147483648, 1) << endl; }
Create Evaluate reverse polish notation.cpp
class Solution { public: stack<int> sta; bool isNum(string str) { if (str.size() > 1) return true; if (str[0] >= '0' && str[0] <= '9') return true; return false; } int evalRPN(vector<string>& tokens) { int a, b, i; string s; for (i = 0; i < tokens.size(); i++) { s = tokens[i]; if (isNum(s)){ int num = 0; int sig = 1; int begin = 0; if (s[0] == '+') { sig = 1; begin = 1; } else if (s[0] == '-') { sig = -1; begin = 1; } for (int j = begin; j < s.size(); j++) num = num*10 + s[j] - '0'; sta.push(num*sig); } else { if (s.size() != 1) { //assert(0); break; } if (sta.size() < 2) { //assert(0); break; } //notice devide zero. b = sta.top(); sta.pop(); a = sta.top(); sta.pop(); switch (s[0]) { case '+': a = a+b; break; case '-': a = a-b; break; case '*': a = a*b; break; case '/': a = a/b; break; default : break;//assert(0); } sta.push(a); } } if (s.size() != 1) { // assert(0); } a = sta.top(); return a; } };
Test harness for the new SimpleXMLParser class.
/** \brief Test harness for the SimpleXmlParser class. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2015 Universitätsbiblothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include "SimpleXmlParser.h" #include "util.h" void Usage() { std::cerr << "Usage: " << progname << " xml_input\n"; std::exit(EXIT_FAILURE); } int main(int argc, char *argv[]) { progname = argv[0]; if (argc != 2) Usage(); const std::string input_filename(argv[1]); File input(input_filename, "rm"); if (not input) Error("can't open \"" + input_filename + "\" for reading!"); SimpleXmlParser::Type type; std::string data; std::map<std::string, std::string> attrib_map; SimpleXmlParser xml_parser(&input); while (xml_parser.getNext(&type, &attrib_map, &data)) { switch (type) { case SimpleXmlParser::UNINITIALISED: Error("we should never get here as UNINITIALISED should never be returned!"); case SimpleXmlParser::START_OF_DOCUMENT: std::cout << "START_OF_DOCUMENT()\n"; break; case SimpleXmlParser::END_OF_DOCUMENT: break; case SimpleXmlParser::ERROR: Error("we should never get here because SimpleXmlParser::getNext() should have returned false!"); case SimpleXmlParser::OPENING_TAG: std::cout << "OPENING_TAG(" << data; for (const auto &name_and_value : attrib_map) std::cout << ' ' << name_and_value.first << '=' << name_and_value.second; std::cout << ")\n"; break; case SimpleXmlParser::CLOSING_TAG: std::cout << "CLOSING_TAG(" << data << ")\n"; break; case SimpleXmlParser::CHARACTERS: std::cout << "CHARACTERS(" << data << ")\n"; break; } } Error("XML parsing error: " + xml_parser.getLastErrorMessage()); }
Add test for previously unflattenables
/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkAlphaThresholdFilter.h" #include "SkImage.h" #include "Test.h" static void test_flattenable(skiatest::Reporter* r, const SkFlattenable* f, const char* desc) { if (f) { SkFlattenable::Factory factory = f->getFactory(); REPORTER_ASSERT(r, factory); if (factory) { if (!SkFlattenable::FactoryToName(factory)) { ERRORF(r, "SkFlattenable::FactoryToName() fails with %s.", desc); } } } } DEF_TEST(FlattenableFactoryToName, r) { SkIRect rects[2]; rects[0] = SkIRect::MakeXYWH(0, 150, 500, 200); rects[1] = SkIRect::MakeXYWH(150, 0, 200, 500); SkRegion region; region.setRects(rects, 2); SkAutoTUnref<SkImageFilter> filter( SkAlphaThresholdFilter::Create(region, 0.2f, 0.7f)); test_flattenable(r, filter, "SkAlphaThresholdFilter()"); SkBitmap bm; bm.allocN32Pixels(8, 8); bm.eraseColor(SK_ColorCYAN); SkAutoTUnref<SkImage> image(SkImage::NewFromBitmap(bm)); SkAutoTUnref<SkShader> shader(image->newShader(SkShader::kClamp_TileMode, SkShader::kClamp_TileMode)); test_flattenable(r, shader, "SkImage::newShader()"); }
Implement Snakes and Ladders using BFS
// http://www.geeksforgeeks.org/snake-ladder-problem-2/ #include <iostream> #include <cstring> #include <queue> using namespace std; struct QNode { int v; // vertex int d; //distance; }; int getMinDice(int moves[], int N) { bool *visited = new bool[N]; memset(visited, false, sizeof(visited)); queue<QNode> q; QNode qN = {0, 0}; // start node q.push(qN); visited[0] = true; QNode qE; while (!q.empty()) { qE = q.front(); cout<<"pop: "<<qE.v<<" "<<qE.d<<endl; q.pop(); int v = qE.v; if (v == N-1) break; for (int j = v+1; j <= v+6 && j < N; j++) { if (!visited[j]) { QNode qN; qN.d = qE.d+1; visited[j] = true; if (moves[j] != -1) { qN.v = moves[j]; } else { qN.v = j; } cout<<"push: "<<qN.v<<" "<<qN.d<<endl; q.push(qN); } } } delete [] visited; return qE.d; } int main() { int N = 30; // Board Size; int moves[N]; memset(moves, -1, sizeof(moves)); // snakes positions moves[26] = 0; moves[20] = 8; moves[16] = 9; moves[18] = 6; // ladder positions moves[10] = 25; moves[2] = 21; moves[4] = 7; moves[19] = 28; cout<<"The min number of dices required to reach destination is: "<<getMinDice(moves, N)<<endl; return 0; }
Add solution to spiral traversal of matrix problem
#include <iostream> using std::cout; const int MAX = 20; void spiral_traversal(int matrix[][MAX], int rows, int cols) { int start_row = 0; int end_row = rows - 1; int start_column = 0; int end_column = cols - 1; while (start_row <= end_row && start_column <= end_column) { for (int i = start_column; i <= end_column; ++i) { cout << matrix[start_row][i] << ' '; } ++start_row; for (int i = start_row; i <= end_row; ++i) { cout << matrix[i][end_column] << ' '; } --end_column; if (start_row <= end_row) { for (int i = end_column; i >= start_column; --i) { cout << matrix[end_row][i] << ' '; } --end_row; } if (start_column <= end_column) { for (int i = end_row; i >= start_row; --i) { cout << matrix[i][start_column] << ' '; } ++start_column; } } } int main() { int matrix[MAX][MAX] = { {1, 2, 3, 4, 5, 6}, {7, 8, 9, 10, 11, 12}, {13, 14, 15, 16, 17, 18} }; spiral_traversal(matrix, 3, 6); return 0; }
Add test for time interpolator
#include "testing/gtest.hh" #include "geometry/spatial/time_interpolator.hh" namespace geometry { namespace spatial { TEST(TimeInterpolatorTest, time_interpolator) { const estimation::TimePoint t0 = {}; const estimation::TimeDuration dt = estimation::to_duration(1.0); const std::vector<geometry::spatial::TimeControlPoint> points = { geometry::spatial::TimeControlPoint{t0, jcc::Vec3(0.0, 0.0, 0.0)}, geometry::spatial::TimeControlPoint{t0 + dt, jcc::Vec3(1.0, 1.0, 1.0)}, geometry::spatial::TimeControlPoint{t0 + (2 * dt), jcc::Vec3(5.0, 5.0, 5.0)}, }; const TimeInterpolator interp(points); constexpr double EPS = 1e-6; { const auto error = (*interp(t0) - points[0].value).norm(); EXPECT_LT(error, EPS); } { const auto error = (*interp(t0 + dt) - points[1].value).norm(); EXPECT_LT(error, EPS); } { // Nothing at the end point EXPECT_FALSE(interp(t0 + (2 * dt))); const estimation::TimePoint t = t0 + estimation::to_duration(1.9999); const auto interp_at_t = interp(t); ASSERT_TRUE(interp_at_t); const auto error = (*interp_at_t - points[2].value).norm(); EXPECT_LT(error, 1e-3); } { const estimation::TimePoint t = t0 + estimation::to_duration(0.5); const auto error = (*interp(t) - jcc::Vec3(0.5, 0.5, 0.5)).norm(); EXPECT_LT(error, EPS); } { const estimation::TimePoint t = t0 + estimation::to_duration(1.5); const auto error = (*interp(t) - jcc::Vec3(3.0, 3.0, 3.0)).norm(); EXPECT_LT(error, EPS); } } } // namespace spatial } // namespace geometry
Add Chapter 19, exercise 13
// Chapter 19, exercise 13: Tracer class where constructor and destructor print // strings (given as argument to constructor). Use it to see where RAII objects // will do their job (local objects, member objects, global objects, objects // allocated with new...), then add copy constructor and copy assignment to see // when copying is done #include "../lib_files/std_lib_facilities.h" //------------------------------------------------------------------------------ class Tracer { string msg; public: Tracer(const string& s) : msg(s) { cout << "Constructed " << msg << "\n"; } Tracer(const Tracer& t) : msg(t.msg) { cout << "Copy constructed from " << msg << "\n"; } Tracer& operator=(const Tracer& t) { msg = t.msg; cout << "Copy assigned " << msg << "\n"; return *this; } ~Tracer() { cout << "Destroyed " << msg << "\n"; } void set_msg(const string& s) { msg = s; } }; //------------------------------------------------------------------------------ struct Test { Test(const string& s) : val(Tracer(s)) { } Tracer val; }; //------------------------------------------------------------------------------ Tracer global("global"); //------------------------------------------------------------------------------ int main() try { { Tracer t_scope("allocated in local scope"); } // immediately destroyed Tracer copy_global = global; cout << "and renamed to 'local copy of global'\n"; copy_global.set_msg("local copy of global"); Tracer local("local"); Test member("as member object"); Tracer* local_ptr = new Tracer("allocated with new"); // leaks! Tracer t_cpyassign = *local_ptr; cout << "and renamed to 'copy assigned from pointer'\n"; t_cpyassign.set_msg("copy assigned from pointer"); } catch (exception& e) { cerr << "exception: " << e.what() << endl; } catch (...) { cerr << "exception\n"; }
Add Solution for 043 Multiply Strings
// 43. Multiply Strings /** * Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2. * * Note: * * 1. The length of both num1 and num2 is < 110. * 2. Both num1 and num2 contains only digits 0-9. * 3. Both num1 and num2 does not contain any leading zero. * 4. You must not use any built-in BigInteger library or convert the inputs to integer directly. * * Tags: Math, String * * Similar Problems: (M) Add Two Numbers, (E) Plus One, (E) Add Binary, (E) Add Strings * * Author: Kuang Qin */ #include <iostream> #include <string> #include <vector> using namespace std; class Solution { public: string multiply(string num1, string num2) { if (num1 == "0" || num2 == "0") return "0"; // product length will not exceed the total length of two multipliers int n1 = num1.size(), n2 = num2.size(), n = n1 + n2; vector<int> product(n, 0); // add result from multiplying by digit for (int i = n1 - 1; i >= 0; i--) { for (int j = n2 - 1; j >= 0; j--) { product[i + j + 1] += (num1[i] - '0') * (num2[j] - '0'); } } // make each digit valid for (int i = n - 1; i > 0; i--) { product[i - 1] += product[i] / 10; // higher digit product[i] = product[i] % 10; // lower digit } // convert into string string res(""); if (product[0] != 0) // first digit could be zero res += product[0] + '0'; for (int i = 1; i < n; i++) res += product[i] + '0'; return res; } }; int main() { string num1("2143"), num2("2"); Solution sol; string p = sol.multiply(num1, num2); cout << num1 << " * " << num2 << " = " << p << endl; cin.get(); return 0; }
Create : 521 Cheeses and a Mousetrap
#include <iostream> using namespace std; int main() { int N, K; cin >> N >> K; if (K == 0 || K > N) { cout << 0 << endl; return 0; } if (N % 2 == 1 && K == (N + 1) / 2) { cout << N - 1 << endl; } else { cout << N - 2 << endl; } return 0; }
Add test case for fix of linkage bug that miscompiled variable templates instantiated from similarly named local types (cf. r212233)
// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -emit-llvm -std=c++1y -O1 -disable-llvm-optzns %s -o - | FileCheck %s -check-prefix=CHECKA -check-prefix=CHECK // RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -emit-llvm -std=c++1y -O1 -disable-llvm-optzns -fcxx-exceptions %s -o - | FileCheck %s -check-prefix=CHECKB -check-prefix=CHECK // expected-no-diagnostics // The variable template specialization x<Foo> generated in each file // should be 'internal global' and not 'linkonce_odr global'. template <typename T> int x = 42; // CHECK-DAG: @_Z1xIZL3foovE3FooE = internal global // CHECK-DAG: define internal dereferenceable(4) i32* @_ZL3foov( static int &foo() { struct Foo { }; // CHECK-DAG: ret i32* @_Z1xIZL3foovE3FooE return x<Foo>; } #if !__has_feature(cxx_exceptions) // File A // CHECKA-DAG: define dereferenceable(4) i32* @_Z3barv( int &bar() { // CHECKA-DAG: %call = call dereferenceable(4) i32* @_ZL3foov() return foo(); } #else // File B // CHECKB-DAG: declare dereferenceable(4) i32* @_Z3barv( int &bar(); int main() { // CHECKB-DAG: %call = call dereferenceable(4) i32* @_Z3barv() // CHECKB-DAG: %call1 = call dereferenceable(4) i32* @_ZL3foov() &bar() == &foo() ? throw 0 : (void)0; // Should not throw exception at runtime. } #endif // end of Files A and B
Add test case for insertion, retrieval and display
/* This program tests class LinkedList */ #include<iostream> #include<vector> #include "linkedlist.h" // tests insertion void testInsert(){ std::cout<<"Test Insert\n"; // define vector of values std::vector<int> values = {6,5,4,3,2,1}; // create linked list LinkedList ll; // insert values into linked list (always at beginning i.e. index 0) for(auto x: values){ ll.insertFirst(x); } // display linked list ll.print(); // insert 100 at end ll.insertLast(100); // display linked list ll.print(); // insert in between ll.insert_node(3,5000); // display linked list ll.print(); } // tests valueAt() and getLength() void testB(){ std::cout<<"Test B\n"; // define vector of values std::vector<int> values = {6,5,4,3,2,1}; // create linked list LinkedList ll; // insert values into linked list (always at beginning i.e. index 0) for(auto x: values){ ll.insertFirst(x); } // insert 100 at end ll.insertLast(1000); // insert in between ll.insert_node(3,5000); // display linked list ll.print(); std::cout<<"Length: "<<ll.getLength(); for(int i=0;i<ll.getLength();i++){ std::cout<<"\nValut at "<<i<<": "<<ll.valueAt(i); } } int main(){ // test insert testInsert(); // test B testB(); return 0; }
Remove Duplicates from Sorted List II
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* deleteDuplicates(ListNode* head) { ListNode* dummy = new ListNode(), *pre = dummy; dummy->next = head; bool in = false; while (head && head->next) { if (in) { if (head->val != head->next->val) { pre->next = head->next; in = false; } head = head->next; } else { if (head->val == head->next->val) { in = true; } else { pre = pre->next; } head = head->next; } } if (in) pre->next = nullptr; return dummy->next; } };
Add first version of C++ stl deque.
#include <iostream> #include <deque> using namespace std; // This is a very well known problem that can easily be found // in google as 'maximum sliding window' where basically we are // moving over an array printing each max value for each sub-array // (or window). You can take a look to the explanation and // code from: // http://articles.leetcode.com/sliding-window-maximum/ void printKMax(int arr[], int n, int k){ deque <int> q; // First we need to take care of the first window. // We will ensure that the highest element of the window is always in // the front of the deque, for that reason on each iteration (i) we // remove all the elements in the back of the deque with lower that // the current element in the array. This is done in this first while // loop. for (int i = 0; i < k; i++) { while(!q.empty() && arr[i] >= arr[q.back()]) { q.pop_back(); } //Each element in the array 'arr' is added at some time into the // queue elements with lower value that the current maximum one // are removed with the previous while loop. q.push_back(i); } // Section 2. // By this point we already checked the first window and all the remaining // sections will be taken care in the next for loop. for (int i = k; i < n; i++) { cout << arr[q.front()] << " "; while (!q.empty() && arr[i] >= arr[q.back()]) q.pop_back(); //let's remove the elements that are out of the window from the front. // As you can see we are attacking the deque in the front as well, but // now we only remove the elements that are not part of the subarray // and for that reason not valid. while(!q.empty() && q.front() <= i-k) q.pop_front(); q.push_back(i); } cout << arr[q.front()] << " "; cout << endl; } int main(){ int t; cin >> t; while(t>0) { int n,k; cin >> n >> k; int i; int arr[n]; for(i=0;i<n;i++) cin >> arr[i]; printKMax(arr, n, k); t--; } return 0; }
Add code generation test for r86500.
// RUN: clang-cc %s -emit-llvm -o - | FileCheck %s // Check that call to constructor for struct A is generated correctly. struct A { A(int x = 2); }; struct B : public A {}; B x; // CHECK: call void @_ZN1AC1Ei
Fix conflict between r174685 and r174645 (rename -fmodule-cache-path <foo> to -fmodules-cache-path=<foo>).
// RUN: rm -rf %t // RUN: %clang_cc1 -x objective-c++ -fmodules -fmodule-cache-path %t -I %S/Inputs %s -verify // expected-no-diagnostics @import cxx_many_overloads; void g() { f(N::X<0>()); }
// RUN: rm -rf %t // RUN: %clang_cc1 -x objective-c++ -fmodules -fmodules-cache-path=%t -I %S/Inputs %s -verify // expected-no-diagnostics @import cxx_many_overloads; void g() { f(N::X<0>()); }
Add one more test for the handling of stack origins.
// Test that on the second entry to a function the origins are still right. // RUN: %clangxx_msan -m64 -O0 %s -o %t && not %run %t >%t.out 2>&1 // RUN: FileCheck %s < %t.out // RUN: %clangxx_msan -m64 -O1 %s -o %t && not %run %t >%t.out 2>&1 // RUN: FileCheck %s < %t.out // RUN: %clangxx_msan -m64 -O2 %s -o %t && not %run %t >%t.out 2>&1 // RUN: FileCheck %s < %t.out // RUN: %clangxx_msan -m64 -O3 %s -o %t && not %run %t >%t.out 2>&1 // RUN: FileCheck %s < %t.out // RUN: %clangxx_msan -fsanitize-memory-track-origins -m64 -O0 %s -o %t && not %run %t >%t.out 2>&1 // RUN: FileCheck %s < %t.out && FileCheck %s --check-prefix=CHECK-ORIGINS < %t.out // RUN: %clangxx_msan -fsanitize-memory-track-origins -m64 -O1 %s -o %t && not %run %t >%t.out 2>&1 // RUN: FileCheck %s < %t.out && FileCheck %s --check-prefix=CHECK-ORIGINS < %t.out // RUN: %clangxx_msan -fsanitize-memory-track-origins -m64 -O2 %s -o %t && not %run %t >%t.out 2>&1 // RUN: FileCheck %s < %t.out && FileCheck %s --check-prefix=CHECK-ORIGINS < %t.out // RUN: %clangxx_msan -fsanitize-memory-track-origins -m64 -O3 %s -o %t && not %run %t >%t.out 2>&1 // RUN: FileCheck %s < %t.out && FileCheck %s --check-prefix=CHECK-ORIGINS < %t.out #include <stdlib.h> extern "C" int f(int depth) { if (depth) return f(depth - 1); int x; int *volatile p = &x; return *p; } int main(int argc, char **argv) { return f(1); // CHECK: WARNING: MemorySanitizer: use-of-uninitialized-value // CHECK: {{#0 0x.* in main .*stack-origin2.cc:}}[[@LINE-2]] // CHECK-ORIGINS: Uninitialized value was created by an allocation of 'x' in the stack frame of function 'f' // CHECK-ORIGINS: {{#0 0x.* in f .*stack-origin2.cc:}}[[@LINE-14]] // CHECK: SUMMARY: MemorySanitizer: use-of-uninitialized-value {{.*stack-origin2.cc:.* main}} }
Add test for dynamic stack allocation
#include "cxx_runtime.h" #include "output.h" Output output; int bar(char *buffer, int size) { char tmp[size * 2]; int index = 0; output << "enter bar\n"; for (int i = 0; i < size; i++) { if (buffer[i] == 'i') { tmp[index++] = '~'; tmp[index++] = 'i'; } else tmp[index++] = buffer[i]; } memcpy(buffer, tmp, index); return index; } int main() { char foo[256] = "this is a test"; int newLen = bar(foo, strlen(foo)); for (int i = 0; i < newLen; i++) output << foo[i]; // CHECK: th~is ~is a test }
Add solution to homework 1
#include <iostream> #include <fstream> #include <stack> using std::ifstream; using std::ofstream; using std::ios; using std::cout; using std::stack; bool is_digit(char c) { return c >= '0' && c <= '9'; } void apply_operation(char operation, stack<double>& operands) { double second_operand = operands.top(); operands.pop(); double first_operand = operands.top(); operands.pop(); switch (operation) { case '+': operands.push(first_operand + second_operand); break; case '-': operands.push(first_operand - second_operand); break; case '*': operands.push(first_operand * second_operand); break; case '/': operands.push(first_operand / second_operand); break; } } void write_result(ofstream& results, stack<double>& operands) { results.write((const char*)&operands.top(), sizeof(double)); operands.pop(); } void calculate_expressions() { ifstream expressions("expressions.txt"); ofstream results("results.bin", ios::trunc | ios::binary); stack<double> operands; while (!expressions.eof()) { char next_character = expressions.peek(); if (is_digit(next_character)) { double operand; expressions >> operand; operands.push(operand); } else { char operation; expressions >> operation; apply_operation(operation, operands); } if (expressions.peek() == ';') { write_result(results, operands); } expressions.ignore(2, ' '); } write_result(results, operands); results.close(); expressions.close(); } void print_results() { ifstream results("results.bin", ios::binary); double result; while (results.read((char*)&result, sizeof(double))) { cout << result << ' '; } results.close(); } int main() { calculate_expressions(); print_results(); cout << '\n'; return 0; }
Add basic test for -style=none.
// RUN: grep -Ev "// *[A-Z-]+:" %s > %t.cpp // RUN: clang-format -style=none -i %t.cpp // RUN: FileCheck -strict-whitespace -input-file=%t.cpp %s // CHECK: int i; int i;
Add wrapper for user tuto 01
#include "Halide.h" #include "wrapper_tutorial_01.h" #include "tiramisu/utils.h" #include <cstdlib> #include <iostream> int main(int, char **) { int N = 10; Halide::Buffer<int32_t> output(N); init_buffer(output, (int32_t)9); std::cout << "Array (after initialization)" << std::endl; print_buffer(output); function0(output.raw_buffer()); std::cout << "Array after the Halide pipeline" << std::endl; print_buffer(output); Halide::Buffer<int32_t> expected(N); init_buffer(expected, (int32_t)7); compare_buffers("tutorial_01", output, expected); return 0; }
Add a new SkMemory implementation that uses mozalloc instead of malloc
/* * Copyright 2011 Google Inc. * Copyright 2012 Mozilla Foundation * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkTypes.h" #include "mozilla/mozalloc.h" #include "mozilla/mozalloc_abort.h" #include "mozilla/mozalloc_oom.h" void sk_throw() { SkDEBUGFAIL("sk_throw"); mozalloc_abort("Abort from sk_throw"); } void sk_out_of_memory(void) { SkDEBUGFAIL("sk_out_of_memory"); mozalloc_handle_oom(0); } void* sk_malloc_throw(size_t size) { return sk_malloc_flags(size, SK_MALLOC_THROW); } void* sk_realloc_throw(void* addr, size_t size) { return moz_xrealloc(addr, size); } void sk_free(void* p) { moz_free(p); } void* sk_malloc_flags(size_t size, unsigned flags) { return (flags & SK_MALLOC_THROW) ? moz_xmalloc(size) : moz_malloc(size); }
Print all paths from root to node separately.
// Print all root to leaf paths of a binary tree /* Algorithm: initialize: pathlen = 0, path[1000] // 1000 is some max limit for paths, it can change // printPathsRecur traverses nodes of tree in preorder printPathsRecur(tree, path[], pathlen) 1) If node is not NULL then a) push data to path array: path[pathlen] = node->data. b) increment pathlen pathlen++ 2) If node is a leaf node then print the path array. 3) Else a) Call printPathsRecur for left subtree printPathsRecur(node->left, path, pathLen) b) Call printPathsRecur for right subtree. printPathsRecur(node->right, path, pathLen) */ #include <iostream> using namespace std; struct Node{ int data; struct Node *left; struct Node *right; }; void printArray(int A[], int len){ int i; for(i=0; i<len; i++) cout<<A[i]; cout<<"\n"; } void printPathsRecur(struct Node *root, int path[], int pathLen){ if(root == NULL) return; path[pathLen] = root->data; pathLen++; // if it's a leaf, print the path that led there if(root->left == NULL && root->right == NULL){ printArray(path, pathLen); } else{ // try both subtrees printPathsRecur(root->left, path, pathLen); printPathsRecur(root->right, path, pathLen); } } void printPaths(struct Node *root){ int path[1000]; printPathsRecur(root, path, 0); } struct Node *newNode(int x){ struct Node *newptr = new Node; newptr->data = x; newptr->left = NULL; newptr->right = NULL; return newptr; } int main(){ struct Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); printPaths(root); return 0; }
Add Chapter 26, exercise 12
// Chapter 26, exercise 12: generate random floating point numbers and sort them // using std::sort(). Measure time used to sort 500,000 doubles and 5,000,000 // doubles. #include<ctime> #include<cstdlib> #include<iostream> #include<exception> #include<vector> #include<limits> #include<algorithm> using namespace std; //------------------------------------------------------------------------------ inline double drand(double min, double max) { double d = double(rand()) / RAND_MAX; return min + d * (max-min); } //------------------------------------------------------------------------------ int main() try { srand(time(0)); vector<int> sizes = {500000, 5000000, 10000000}; for (int i = 0; i<sizes.size(); ++i) { cout << "Sorting " << sizes[i] << " doubles:\n"; double t = 0; for (int j = 0; j<3; ++j) { vector<double> v(sizes[i]); for (int i = 0; i<v.size(); ++i) v[i] = drand(numeric_limits<double>::min()/2, numeric_limits<double>::max()/2); clock_t t1 = clock(); if (t1 == clock_t(-1)) throw exception("sorry, no clock"); sort(v.begin(),v.end()); clock_t t2 = clock(); if (t2 == clock_t(-1)) throw exception("sorry, clock overflow"); t += double(t2-t1)/CLOCKS_PER_SEC; } cout << "Time: " << t/3 << " seconds\n\n"; } } catch (exception& e) { cerr << e.what() << endl; } catch (...) { cerr << "exception \n"; } //------------------------------------------------------------------------------
Add solution 412. Fizz Buzz
/* * https://leetcode.com/problems/fizz-buzz/ * Write a program that outputs the string representation of numbers from 1 to n. * But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. * For numbers which are multiples of both three and five output “FizzBuzz”. */ class Solution { public: vector<string> fizzBuzz(int n) { vector<string> res; for(int i = 1; i <= n; i++) { if((i % 3 == 0) && (i % 5 == 0)) res.push_back("FizzBuzz"); else if (i % 3 == 0) res.push_back("Fizz"); else if (i % 5 == 0) res.push_back("Buzz"); else { stringstream ss; ss<<i; res.push_back(ss.str()); ss.clear(); } } return res; } };
Disable flakily timing out QUnitBrowserTestRunner.Remoting_Webapp_Js_Unittest
// 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 "base/path_service.h" #include "chrome/test/remoting/qunit_browser_test_runner.h" #if defined(OS_MACOSX) #include "base/mac/foundation_util.h" #endif // !defined(OS_MACOSX) namespace remoting { IN_PROC_BROWSER_TEST_F(QUnitBrowserTestRunner, Remoting_Webapp_Js_Unittest) { base::FilePath base_dir; ASSERT_TRUE(PathService::Get(base::DIR_EXE, &base_dir)); #if defined(OS_MACOSX) if (base::mac::AmIBundled()) { // If we are inside a mac bundle, navigate up to the output directory base_dir = base::mac::GetAppBundlePath(base_dir).DirName(); } #endif // !defined(OS_MACOSX) RunTest( base_dir.Append(FILE_PATH_LITERAL("remoting/unittests/unittests.html"))); } } // namespace remoting
// 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 "base/path_service.h" #include "chrome/test/remoting/qunit_browser_test_runner.h" #if defined(OS_MACOSX) #include "base/mac/foundation_util.h" #endif // !defined(OS_MACOSX) namespace remoting { // Flakily times out on Win7 Tests (dbg): https://crbug.com/504204. #if defined(OS_WIN) && !defined(NDEBUG) #define MAYBE_Remoting_Webapp_Js_Unittest DISABLE_Remoting_Webapp_Js_Unittest #else #define MAYBE_Remoting_Webapp_Js_Unittest Remoting_Webapp_Js_Unittest #endif IN_PROC_BROWSER_TEST_F(QUnitBrowserTestRunner, MAYBE_Remoting_Webapp_Js_Unittest) { base::FilePath base_dir; ASSERT_TRUE(PathService::Get(base::DIR_EXE, &base_dir)); #if defined(OS_MACOSX) if (base::mac::AmIBundled()) { // If we are inside a mac bundle, navigate up to the output directory base_dir = base::mac::GetAppBundlePath(base_dir).DirName(); } #endif // !defined(OS_MACOSX) RunTest( base_dir.Append(FILE_PATH_LITERAL("remoting/unittests/unittests.html"))); } } // namespace remoting
Add an example of Kiss FFT in C++.
#include "kiss_fft.h" #include <complex> #include <iostream> #include <vector> using namespace std; int main() { const int nfft = 256; kiss_fft_cfg fwd = kiss_fft_alloc(nfft, 0, NULL, NULL); kiss_fft_cfg inv = kiss_fft_alloc(nfft, 1, NULL, NULL); vector<std::complex<float>> x(nfft, 0.0); vector<std::complex<float>> fx(nfft, 0.0); x[0] = 1; x[1] = std::complex<float>(0, 3); kiss_fft(fwd, (kiss_fft_cpx *)&x[0], (kiss_fft_cpx *)&fx[0]); for (int k = 0; k < nfft; ++k) { fx[k] = fx[k] * conj(fx[k]); fx[k] *= 1. / nfft; } kiss_fft(inv, (kiss_fft_cpx *)&fx[0], (kiss_fft_cpx *)&x[0]); cout << "the circular correlation of [1, 3i, 0 0 ....] with itself = "; cout << x[0] << "," << x[1] << "," << x[2] << "," << x[3] << " ... " << endl; kiss_fft_free(fwd); kiss_fft_free(inv); return 0; }
Add test for gpu assertions
#include "Halide.h" using namespace Halide; bool errored = false; void my_error(void *, const char *msg) { printf("Expected error: %s\n", msg); errored = true; } void my_print(void *, const char *msg) { // Empty to neuter debug message spew } int main(int argc, char **argv) { Target t = get_jit_target_from_environment(); if (!t.has_feature(Target::CUDA)) { printf("Not running test because cuda not enabled\n"); return 0; } // Turn on debugging so that the pipeline completes and error // checking is done before realize returns. Otherwise errors are // discovered too late to call a custom error handler. t.set_feature(Target::Debug); Func f; Var c, x; f(c, x) = x + c + 3; f.bound(c, 0, 3).unroll(c); Func g; g(c, x) = f(c, x) * 8; g.gpu_tile(x, 8); f.compute_at(g, Var::gpu_blocks()).gpu_threads(x); g.set_error_handler(&my_error); g.set_custom_print(&my_print); // Should succeed g.realize(3, 100, t); if (errored) { printf("There was not supposed to be an error\n"); return -1; } // Should trap g.realize(4, 100, t); if (!errored) { printf("There was supposed to be an error\n"); return -1; } printf("Success!\n"); return 0; }
Implement Boundary traversal of tree.
#include <stdio.h> typedef struct _NODE { int data; _NODE* left; _NODE* right; } NODE; NODE* newNode(int data) { NODE* node = new NODE(); node->data = data; node->left = nullptr; node->right = nullptr; return node; } void printBoundaryLeft(NODE* root) { if (root) { if (root->left) { printf("%d ", root->data); printBoundaryLeft(root->left); } else if (root->right) { printf("%d ", root->data); printBoundaryLeft(root->right); } } } void printLeaves(NODE* root) { if (root) { printLeaves(root->left); if (root->left == nullptr && root->right == nullptr) { printf("%d ", root->data); } printLeaves(root->right); } } void printBoundaryRight(NODE* root) { if (root) { if (root->right) { printBoundaryRight(root->right); printf("%d ", root->data); } else if (root->left) { printBoundaryRight(root->left); printf("%d ", root->data); } } } void printBoundary(NODE* root) { if (root) { printf("%d ", root->data); printBoundaryLeft(root->left); printLeaves(root->left); printLeaves(root->right); printBoundaryRight(root->right); } } int main(int argc, char const* argv[]) { NODE* root = newNode(20); root->left = newNode(8); root->left->left = newNode(4); root->left->right = newNode(12); root->left->right->left = newNode(10); root->left->right->right = newNode(14); root->right = newNode(22); root->right->right = newNode(25); printBoundary(root); return 0; }
Add library (Range Minimum Query)
// Verified: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_2_A struct RMQ { int size; ll default_value; vector<ll> tree; RMQ (int n, ll def) { default_value = def; size = 1; while(size < n)size *= 2; tree = vector<ll>(size * 2 - 1, default_value); } void update(int x, ll y){ int i = size + x - 1; tree[i] = y; while(i > 0){ i = (i - 1) / 2; tree[i] = min(tree[2 * i + 1], tree[2 * i + 2]); } } // min [x, y) int find_min(int x, int y){ return find_min(x, y, 0, 0, size); } int find_min(int x, int y, int k, int l, int r){ if(r <= x || y<=l) return default_value; if(x <= l && r<=y) return tree[k]; return min(find_min(x, y ,k * 2 + 1, l, (l + r) / 2), find_min(x, y, k * 2 + 2, (l + r) / 2, r)); } };
Use prefix ``++`` for objects
#include <string> #include "configuration.hh" int from_visual(const std::string& cont, int x) { if(cont.size() == 0) return 0; int count = 0, til = 0; int numTab = 0; for(unsigned int i = 0; i < cont.length(); i++) { unsigned int len; if(cont[i] == '\t') { len = TAB_SIZE - 1 - til; til = 0; numTab++; } else { len = 1; til++; til %= TAB_SIZE; } count += len; if(count > x - numTab) return i; } return -1; } int to_visual(const std::string& cont, int x) { int til = 0, xx = -1; for(std::string::const_iterator i = cont.begin(); i <= cont.begin() + x; i++) { if(*i == '\t') { xx += TAB_SIZE - til; til = 0; } else { til++; til %= TAB_SIZE; xx++; } } return xx; }
#include <string> #include "configuration.hh" int from_visual(const std::string& cont, int x) { if(cont.size() == 0) return 0; int count = 0, til = 0; int numTab = 0; for(unsigned int i = 0; i < cont.length(); i++) { unsigned int len; if(cont[i] == '\t') { len = TAB_SIZE - 1 - til; til = 0; numTab++; } else { len = 1; til++; til %= TAB_SIZE; } count += len; if(count > x - numTab) return i; } return -1; } int to_visual(const std::string& cont, int x) { int til = 0, xx = -1; for(std::string::const_iterator i = cont.begin(); i <= cont.begin() + x; ++i) { if(*i == '\t') { xx += TAB_SIZE - til; til = 0; } else { til++; til %= TAB_SIZE; xx++; } } return xx; }
Add solution of prob 4
#include <stdio.h> #include <stdlib.h> /* rand(), srand() */ #include <time.h> /* time() */ #include <math.h> /* abs() */ int main(void) { srand(time(NULL)); int N, T; printf("Enter N= "); scanf("%d", &N); printf("Enter T= "); scanf("%d", &T); int step = 0; for(int count = 0; count < T; ++count) { int s, x = 0, y = 0; for(s = 0; abs(x) < N || abs(y) < N; ++s) { switch(rand() % 4) { case 0: ++x; break; case 1: ++y; break; case 2: --x; break; case 3: --y; break; } } step += s; } step /= T; printf("Result: %d\n", step); return 0; }
Print max right element in array.
#include <stdio.h> void PrintNextGreatest(int arr[], int size) { int temp[size]; int max = -1; temp[size - 1] = max; for (int count = size - 2; count >= 0; count--) { if (arr[count] > max) { max = arr[count]; } temp[count] = max; } printf("Original array \n"); for (int i = 0; i < size; i++) { printf("%d ", arr[i]); } printf("Right Next Greater array \n"); for (int i = 0; i < size; i++) { printf("%d ", temp[i]); } } int main(int argc, char const *argv[]) { int arr[] = {16, 17, 4, 3, 5, 2}; int size = sizeof(arr) / sizeof(arr[0]); PrintNextGreatest(arr, size); return 0; }
Insert Delete GetRandom O(1) - Duplicates allowed
class RandomizedCollection { public: map<int,vector<int>> index; vector<int> nums; /** Initialize your data structure here. */ RandomizedCollection() { } /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */ bool insert(int val) { nums.push_back(val); if (index[val].size()>0){ index[val].push_back(nums.size()-1); return false; }else{ index[val].push_back(nums.size()-1); return true; } } /** Removes a value from the collection. Returns true if the collection contained the specified element. */ bool remove(int val) { if(index[val].size()==0) return false; int x=index[val].back(); if(x==nums.size()-1){ index[val].pop_back(); nums.pop_back(); return true; } int y=nums[nums.size()-1]; index[val].pop_back(); swap(nums[x],nums[nums.size()-1]); nums.pop_back(); index[y].pop_back(); index[y].push_back(x); sort(index[y].begin(),index[y].end()); return true; } /** Get a random element from the collection. */ int getRandom() { int n=nums.size(); int x=rand()%n; return nums[x]; } }; /** * Your RandomizedCollection object will be instantiated and called as such: * RandomizedCollection obj = new RandomizedCollection(); * bool param_1 = obj.insert(val); * bool param_2 = obj.remove(val); * int param_3 = obj.getRandom(); */
Add Chapter 21, exercise 5
// Chapter 21, Exercise 5: redesign and reimplement find() and count() to take // iterators to first and last elements (no end()), compare results to the // standard versions - can't return iterator to end() if not found #include "../lib_files/std_lib_facilities.h" //------------------------------------------------------------------------------ // return iterator to first occurrence of val in [first,last]; if element is not // found, return iterator to first - user has to check if first contains the // value or not template<class In, class T> In my_find(In first, In last, const T& val) { In p = first; while (p != last) { if (*p == val) return p; ++p; } // check last element if (*p == val) return p; return first; // did not find val, user has to check if *first == val } //------------------------------------------------------------------------------ // return number of occurrences of val in [first,last] template<class In, class T> int my_count(In first, In last, const T& val) { int count = 0; while (first != last) { if (*first==val) ++count; ++first; } if (*first==val) ++count; return count; } //------------------------------------------------------------------------------ int main() try { vector<int> vi; for (int i = 0; i<10; ++i) vi.push_back(randint(10)); typedef vector<int>::iterator vi_it; cout << "vi:\n"; for (vi_it it = vi.begin(); it<vi.end(); ++it) cout << *it << '\n'; cout << "Enter int to search for and count (-1 to quit): "; int n; while (cin>>n) { if (n==-1) break; vi_it it = my_find(vi.begin(),vi.end()-1,n); int count = my_count(vi.begin(),vi.end()-1,n); if (it==vi.begin() && *it!=n) cout << n << " is not in vi. Next int: "; else cout << n << " is at index " << it-vi.begin() << " (occurs " << count << " time" << (count==1 ? "" : "s") << "). Next int: "; } } catch (Range_error& re) { cerr << "bad index: " << re.index << "\n"; } catch (exception& e) { cerr << "exception: " << e.what() << endl; } catch (...) { cerr << "exception\n"; } //------------------------------------------------------------------------------
Add missing test for warning added in r310803.
// RUN: %clang_cc1 %s -verify -fsyntax-only -Wc++2a-compat -std=c++17 #define concept constexpr bool template<typename T> concept x = 0; #undef concept int concept = 0; // expected-warning {{'concept' is a keyword in C++2a}} int requires = 0; // expected-warning {{'requires' is a keyword in C++2a}}
Trim a Binary Search Tree
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* trimBST(TreeNode* root, int L, int R) { if(!root) return NULL; if(root->val<L) return trimBST(root->right,L,R); if(root->val>R) return trimBST(root->left,L,R); root->left=trimBST(root->left,L,R); root->right=trimBST(root->right,L,R); return root; } };
Add a test to verify the x86 intrinsic headers compile cleanly with no warnings or errors.
// Make sure the intrinsic headers compile cleanly with no warnings or errors. // RUN: %clang_cc1 -triple x86_64-unknown-unknown -Wsystem-headers \ // RUN: -fsyntax-only -x c++ -Wno-ignored-attributes -verify %s // RUN: %clang_cc1 -triple x86_64-unknown-unknown -Wsystem-headers \ // RUN: -fsyntax-only -x c++ -Wno-ignored-attributes -target-feature +f16c \ // RUN: -verify %s // expected-no-diagnostics // Dont' include mm_malloc.h. It's system specific. #define __MM_MALLOC_H #include <x86intrin.h>
Add the solution to "Student Scheduling".
#include <iostream> #include <algorithm> using namespace std; typedef struct node { int time; int due; }task_node; bool cmp(task_node a, task_node b) { return a.due < b.due; } bool is_possible(task_node *a, int n) { sort(a, a + n, cmp); int sum = 0; for (int i = 0; i < n; i++) { if (a[i].time > a[i].due - sum) { return false; } sum += a[i].time; } return true; } int main() { int N; cin >> N; while (N--) { int X; cin >> X; task_node *a = new task_node[X]; for (int i = 0; i < X; i++) { cin >> a[i].time >> a[i].due; } if (is_possible(a, X)) cout << "possible" << endl; else cout << "impossible" << endl; delete [] a; } return 0; }
Add body skeleton for cache simulation program
#include <stdio.h> #include <time.h> #include <stdlib.h> #include <deque> #define MEM_SIZE (1<<20) #define CACHE_SIZE (1<<8) #define DATA_SIZE (1<<8) using namespace std; int main() { // Variables used int dir, cmd, op; unsigned char dat, wait; // Plant the seed srand(time(0)); // Infinit Loop while(true){ // Each command is 32 bits, // 19...0 bits for dir, // 27...20 bits for data // 28 bit indicates operation type 1:read 0:write cmd = rand(); dir = cmd & 0xFFFFF; dat = (cmd & 0xF00000)>>20; op = (cmd>>28)&1; printf("op=%c on dir(0x%x) data:%d\n","wr"[op],dir,dat); wait = getchar(); } return 0; }
Test case for my last fix.
// RUN: %clang_cc1 -verify -fsyntax-only %s template<typename T> struct Node { int lhs; void splay( ) { Node<T> n[1]; (void)n->lhs; } }; void f() { Node<int> n; return n.splay(); }
Add arm_id_baesd_node without callback function
#include"ros/ros.h" #include"arm_msgs/ArmAnglesDegree.h" #include"servo_msgs/IdBased.h" #include<vector> void armMsgCb(const arm_msgs::ArmAnglesDegree::ConstPtr& msg); ros::Publisher pub; int main(int argc, char* argv[]) { ros::init(argc, argv, "arm_id_based_node"); ros::NodeHandle pnh("~"); std::vector<int> id_vec; pnh.getParam("id", id_vec); if (id_vec.empty()) { ROS_ERROR("I need id parameter: id is int vector"); return 1; } ros::NodeHandle nh; ros::Subscriber sub = nh.subscribe("arm_roll", 5, armMsgCb); pub = nh.advertise<servo_msgs::IdBased>("cmd_krs", 10); ros::spin(); return 0; } void armMsgCb(const arm_msgs::ArmAnglesDegree::ConstPtr& msg) { }
Add a test for PR40977
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // UNSUPPORTED: libcpp-has-no-threads // This test ensures that std::memory_order has the same size under all // standard versions to make sure we're not breaking the ABI. This is // relevant because std::memory_order is a scoped enumeration in C++20, // but an unscoped enumeration pre-C++20. // // See PR40977 for details. #include <atomic> #include <type_traits> enum cpp17_memory_order { cpp17_memory_order_relaxed, cpp17_memory_order_consume, cpp17_memory_order_acquire, cpp17_memory_order_release, cpp17_memory_order_acq_rel, cpp17_memory_order_seq_cst }; static_assert((std::is_same<std::underlying_type<cpp17_memory_order>::type, std::underlying_type<std::memory_order>::type>::value), "std::memory_order should have the same underlying type as a corresponding " "unscoped enumeration would. Otherwise, our ABI changes from C++17 to C++20."); int main(int, char**) { return 0; }
Add the solution to "Preceding Palindrome".
#include <iostream> #include <sstream> #include <string> #include <cstdlib> using namespace std; int reverse(int x) { int r = 0; while (x > 0) { r = r * 10 + x % 10; x /= 10; } return r; } bool is_palindrome(int x) { if (reverse(x) == x) { return true; } return false; } int main() { int T; cin >> T; while (T--) { int x; cin >> x; while (!is_palindrome(--x)); cout << x << endl; } return 0; }
Add a test file missed from r199782.
// RUN: %clang_cc1 -verify %s -pedantic-errors // RUN: %clang_cc1 -verify %s -pedantic-errors -DINLINE // RUN: %clang_cc1 -verify %s -pedantic-errors -DSTATIC // RUN: %clang_cc1 -verify %s -pedantic-errors -std=c++11 -DCONSTEXPR // RUN: %clang_cc1 -verify %s -std=c++11 -DDELETED #if INLINE inline // expected-error {{'main' is not allowed to be declared inline}} #elif STATIC static // expected-error {{'main' is not allowed to be declared static}} #elif CONSTEXPR constexpr // expected-error {{'main' is not allowed to be declared constexpr}} #endif int main(int argc, char **argv) #if DELETED = delete; // expected-error {{'main' is not allowed to be deleted}} #else { int (*pmain)(int, char**) = &main; // expected-error {{ISO C++ does not allow 'main' to be used by a program}} if (argc) main(0, 0); // expected-error {{ISO C++ does not allow 'main' to be used by a program}} } #endif
Add a test application for the get_pointer methods. This should really be in a unittest framework...
#include <OpenSG/OSGBaseInitFunctions.h> #include <OpenSG/OSGNode.h> #include <OpenSG/OSGNodeCore.h> #include <OpenSG/OSGRefPtr.h> int main (int argc, char **argv) { OSG::osgInit(argc, argv); // Test getting pointers OSG::NodePtr node_ptr = OSG::Node::create(); OSG::Node* node_cptr = get_pointer(node_ptr); OSG::NodeRefPtr node_rptr(OSG::Node::create()); node_cptr = get_pointer(node_rptr); }
Add one more type unit test
// Test that we can jump from a type unit in one dwo file into a type unit in a // different dwo file. // REQUIRES: lld // RUN: %clang %s -target x86_64-pc-linux -fno-standalone-debug -g \ // RUN: -fdebug-types-section -gsplit-dwarf -c -o %t1.o -DONE // RUN: %clang %s -target x86_64-pc-linux -fno-standalone-debug -g \ // RUN: -fdebug-types-section -gsplit-dwarf -c -o %t2.o -DTWO // RUN: llvm-dwarfdump %t1.dwo -debug-types | FileCheck --check-prefix=ONEUNIT %s // RUN: llvm-dwarfdump %t2.dwo -debug-types | FileCheck --check-prefix=ONEUNIT %s // RUN: ld.lld %t1.o %t2.o -o %t // RUN: %lldb %t -o "target var a b **b.a" -b | FileCheck %s // ONEUNIT-COUNT-1: DW_TAG_type_unit // CHECK: (const A) a = (a = 42) // CHECK: (const B) b = { // CHECK-NEXT: a = 0x{{.*}} // CHECK-NEXT: } // CHECK: (const A) **b.a = (a = 42) struct A; extern const A *a_ptr; #ifdef ONE struct A { int a = 42; }; constexpr A a{}; const A *a_ptr = &a; #else struct B { const A **a; }; extern constexpr B b{&a_ptr}; #endif
Add Solution for 415 Add Strings
// 415. Add Strings /** * Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2. * * Note: * * 1. The length of both num1 and num2 is < 5100. * 2. Both num1 and num2 contains only digits 0-9. * 3. Both num1 and num2 does not contain any leading zero. * 4. You must not use any built-in BigInteger library or convert the inputs to integer directly. * * Tags: Math * * Similar Problems: (M) Add Two Numbers, (M) Multiply Strings * * Author: Kuang Qin */ #include <iostream> #include <string> #include <algorithm> using namespace std; class Solution { public: string addStrings(string num1, string num2) { string res(""); int carry = 0, i = num1.size() - 1, j = num2.size() - 1; while (i >= 0 || j >= 0 || carry == 1) { if (i >= 0) carry += num1[i--] - '0'; if (j >= 0) carry += num2[j--] - '0'; res += carry % 10 + '0'; carry /= 10; } reverse(res.begin(), res.end()); return res; } }; int main() { string num1 = "13", num2 = "9"; Solution sol; string res = sol.addStrings(num1, num2); cout << res << endl; cin.get(); return 0; }
Add the solution to "Counting Sort 1".
#include <iostream> #include <cstring> using namespace std; const int maxn = 100; int main() { int n; cin >> n; int *c = new int[maxn]; memset(c, 0, sizeof(c)); while (n--) { int x; cin >> x; c[x]++; } for (int i = 0; i < maxn; i++) { cout << c[i] << " "; } delete [] c; return 0; }
Add the aggregate test file.
#include "test/test_main.h" int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); // what ever initialization you need here // invode the test return RUN_ALL_TESTS(); }
Test jumps which bypass variables declaration
// RUN: %clangxx_asan -O0 -fsanitize-address-use-after-scope %s -o %t && %run %t // Function jumps over variable initialization making lifetime analysis // ambiguous. Asan should ignore such variable and program must not fail. #include <stdlib.h> int *ptr; void f1(int cond) { if (cond) goto label; int tmp; label: ptr = &tmp; *ptr = 5; } void f2(int cond) { switch (cond) { case 1: { ++cond; int tmp; ptr = &tmp; exit(0); case 2: ptr = &tmp; *ptr = 5; exit(0); } } } void f3(int cond) { { int tmp; goto l2; l1: ptr = &tmp; *ptr = 5; exit(0); } l2: goto l1; } void use(int *x) { static int c = 10; if (--c == 0) exit(0); (*x)++; } void f4() { { int x; l2: use(&x); goto l1; } l1: goto l2; } int main() { f1(1); f2(1); f3(1); f4(); return 0; }
Add Chapter 21, Try This 4
// Chapter 21, Try This 4: get Dow Jones map example to work #include "../lib_files/std_lib_facilities.h" #include<map> #include<numeric> //------------------------------------------------------------------------------ double weighted_value(const pair<string,double>& a, const pair<string,double>& b) { return a.second * b.second; } //------------------------------------------------------------------------------ int main() try { map<string,double> dow_price; // Dow Jones Industrial index (symbol price); // for up-to-date quotes see www.djindexes.com dow_price["MMM"] = 160.60; dow_price["AXP"] = 90.44; dow_price["T"] = 32.67; dow_price["BA"] = 125.06; dow_price["CAT"] = 89.75; dow_price["CVX"] = 106.02; map<string,double> dow_weight; // Dow (symbol, weight) dow_weight.insert(make_pair("MMM",5.94)); dow_weight.insert(make_pair("AXP",3.35)); dow_weight.insert(make_pair("T",1.21)); dow_weight.insert(make_pair("BA",4.63)); dow_weight.insert(make_pair("CAT",3.32)); dow_weight.insert(make_pair("CVX",3.92)); map<string,string> dow_name; // Dow (symbol, name) dow_name["MMM"] = "3M Co."; dow_name["AXP"] = "American Express"; dow_name["T"] = "AT&T"; dow_name["BA"] = "Boeing"; dow_name["CAT"] = "Caterpillar"; dow_name["CVX"] = "Chevron"; typedef map<string,double>::const_iterator Dow_iterator; // write price for each company in the Dow index: for (Dow_iterator p = dow_price.begin(); p!=dow_price.end(); ++p) { const string& symbol = p->first; // the "ticker" symbol cout << symbol << '\t' << p->second << '\t' << dow_name[symbol] << '\n'; } double dji_index = inner_product(dow_price.begin(),dow_price.end(), // all companies dow_weight.begin(), // their weights 0.0, // initial value plus<double>(), // add (as usual) weighted_value); // and multiply cout << "DJI index is " << dji_index << "\n"; } catch (Range_error& re) { cerr << "bad index: " << re.index << "\n"; } catch (exception& e) { cerr << "exception: " << e.what() << endl; } catch (...) { cerr << "exception\n"; } //------------------------------------------------------------------------------
Add missing pgmspace test file
/* test_pgmspace.cpp - pgmspace tests Copyright © 2016 Ivan Grokhotkov Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. */ #include <catch.hpp> #include <string.h> #include <pgmspace.h> TEST_CASE("strstr_P works as strstr", "[core][pgmspace]") { auto t = [](const char* h, const char* n) { char* strstr_P_result = strstr_P(h, n); char* strstr_result = strstr(h, n); REQUIRE(strstr_P_result == strstr_result); }; // Test case data is from avr-libc, original copyright (c) 2007 Dmitry Xmelkov // See avr-libc/tests/simulate/pmstring/strstr_P.c t ("", ""); t("12345", ""); t("ababac", "abac"); t("", "a"); t("b", "a"); t("a", "a"); t("abcbef", "a"); t(".a", "a"); t(".a.", "a"); t("ABCDEFGH", "H"); t("", "12"); t("13", "12"); t("32", "12"); t("12", "12"); t("123", "12"); t("012", "12"); t("01200", "12"); t("a_ab_abc_abcd_abcde", "abcdef"); t("a_ab_abc_abcd_abcde_abcdef", "abcdef"); t("aababcabcdabcde", "abcdef"); t("aababcabcdabcdeabcdef", "abcdef"); t("abaabaaabaaaab", "aaaaab"); t("abaabaaabaaaabaaaaab", "aaaaab"); t("_foo_foo", "foo"); t("A", "a"); }