Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add alias and dependence tests
#include <cstdio> int f() { int x, y[1024][1024]; scanf("%d", &x); // hidden store scanf("%d", &y[0][0]); // hidden store x += y[0][0]; // store 0, load 0, load 1 (WAR load 1 - store 0) return x; // load 2 (RAW: store 0) } int g() { int x, y[1024][1024]; scanf("%d", &x); // hidden store scanf("%d", &y[0][0]); // hidden store x += y[0][0]; // store 1, load 3, load 4 (WAR load 4 - store 1) // *** interference: *** (RAW: store 0 - load 4) // *** interference: *** (WAW: store 0 - store 1) // *** interference: *** (WAR: load 2 - store 1) return x; // load 5 (RAW: store 1) } int main() { printf("%d\n", f() + g()); return 0; }
#include <cstdio> int f() { int x, y[1024][1024]; scanf("%d", &x); // hidden store scanf("%d", &y[0][0]); // hidden store x += y[0][0]; // store 0, load 0, load 1 (WAR load 1 - store 0) return x; // load 2 (RAW: store 0) } int g() { int x, y[1024][1024]; scanf("%d", &x); // hidden store scanf("%d", &y[0][0]); // hidden store x += y[0][0]; // store 1, load 3, load 4 (WAR load 4 - store 1) // *** interference: *** (RAW: store 0 - load 4) // *** interference: *** (WAW: store 0 - store 1) // *** interference: *** (WAR: load 2 - store 1) return x; // load 5 (RAW: store 1) } int main() { printf("%d\n", f() + g()); return 0; }
Add another simple test of C++ rmc
#include <rmc++.h> void mp_send(rmc<int> *flag, rmc<int> *data) { VEDGE(wdata, wflag); L(wdata, *data = 42); L(wflag, *flag = 1); } int mp_recv(rmc<int> *flag, int *data) { XEDGE(rflag, rdata); while (L(rflag, *flag) == 0) continue; return L(rdata, *data); } int cas(rmc<int> *p) { int i = 0; return p->compare_exchange_strong(i, 1); } int xadd_int(rmc<int> *p) { return p->fetch_add(10); } int *xadd_ptr(rmc<int *> *p) { return p->fetch_add(10); }
#include <rmc++.h> void mp_send(rmc<int> *flag, rmc<int> *data) { VEDGE(wdata, wflag); L(wdata, *data = 42); L(wflag, *flag = 1); } int mp_recv(rmc<int> *flag, int *data) { XEDGE(rflag, rdata); while (L(rflag, *flag) == 0) continue; return L(rdata, *data); } int cas(rmc<int> *p) { int i = 0; return p->compare_exchange_strong(i, 1); } int xadd_int(rmc<int> *p) { return p->fetch_add(10); } int *xadd_ptr(rmc<int *> *p) { return p->fetch_add(10); } // Make sure it works with longs also... (long overlaps with // fetch_add on pointers so this depends on doing something to // avoid the overlap) long xadd_long(rmc<long> *p) { return p->fetch_add(10); }
Add Command 2 Commad Group
#include "AutonomousCommandGroup.h" #include "MoveElevator.h" #include "Move2Container.h" #include "AdjustAngle.h" #include "BringBurden.h" #include "PivotCommand.h" #include "../RobotMap.h" AutonomousCommandGroup::AutonomousCommandGroup() { //AddSequential(new PivotCommand(-90)); AddSequential(new MoveElevator(3.0,true)); AddSequential(new Move2Container()); AddSequential(new AdjustAngle()); AddSequential(new BringBurden()); }
#include "AutonomousCommandGroup.h" #include "MoveElevator.h" #include "Move2Container.h" #include "AdjustAngle.h" #include "BringBurden.h" #include "PivotCommand.h" #include "../RobotMap.h" AutonomousCommandGroup::AutonomousCommandGroup() { AddSequential(new MoveElevator(3.0,true)); AddSequential(new Move2Container()); AddSequential(new AdjustAngle()); AddSequential(new BringBurden()); AddSequential(new PivotCommand(-90)); AddSequential(new MoveElevator(3.0,false)); }
Update for webkit header moves
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE-CHROMIUM file. #include "common/content_client.h" #include "common/application_info.h" #include "base/stringprintf.h" #include "base/string_util.h" #include "ui/base/resource/resource_bundle.h" #include "webkit/user_agent/user_agent_util.h" namespace brightray { ContentClient::ContentClient() { } ContentClient::~ContentClient() { } std::string ContentClient::GetProduct() const { auto name = GetApplicationName(); RemoveChars(name, kWhitespaceASCII, &name); return base::StringPrintf("%s/%s", name.c_str(), GetApplicationVersion().c_str()); } std::string ContentClient::GetUserAgent() const { return webkit_glue::BuildUserAgentFromProduct(GetProduct()); } base::StringPiece ContentClient::GetDataResource(int resource_id, ui::ScaleFactor scale_factor) const { return ui::ResourceBundle::GetSharedInstance().GetRawDataResourceForScale(resource_id, scale_factor); } gfx::Image& ContentClient::GetNativeImageNamed(int resource_id) const { return ui::ResourceBundle::GetSharedInstance().GetNativeImageNamed(resource_id); } }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE-CHROMIUM file. #include "common/content_client.h" #include "common/application_info.h" #include "base/stringprintf.h" #include "base/string_util.h" #include "ui/base/resource/resource_bundle.h" #include "webkit/common/user_agent/user_agent_util.h" namespace brightray { ContentClient::ContentClient() { } ContentClient::~ContentClient() { } std::string ContentClient::GetProduct() const { auto name = GetApplicationName(); RemoveChars(name, kWhitespaceASCII, &name); return base::StringPrintf("%s/%s", name.c_str(), GetApplicationVersion().c_str()); } std::string ContentClient::GetUserAgent() const { return webkit_glue::BuildUserAgentFromProduct(GetProduct()); } base::StringPiece ContentClient::GetDataResource(int resource_id, ui::ScaleFactor scale_factor) const { return ui::ResourceBundle::GetSharedInstance().GetRawDataResourceForScale(resource_id, scale_factor); } gfx::Image& ContentClient::GetNativeImageNamed(int resource_id) const { return ui::ResourceBundle::GetSharedInstance().GetNativeImageNamed(resource_id); } }
Use include instead of import
#import <node.h> #import "nan.h" #import "scrollbar-style-observer.h" using namespace v8; void ScrollbarStyleObserver::Init(Handle<Object> target) { NanScope(); Local<FunctionTemplate> newTemplate = FunctionTemplate::New(ScrollbarStyleObserver::New); newTemplate->SetClassName(NanSymbol("ScrollbarStyleObserver")); newTemplate->InstanceTemplate()->SetInternalFieldCount(1); Local<ObjectTemplate> proto = newTemplate->PrototypeTemplate(); NODE_SET_METHOD(proto, "getPreferredScrollbarStyle", ScrollbarStyleObserver::GetPreferredScrollbarStyle); target->Set(NanSymbol("ScrollbarStyleObserver"), newTemplate->GetFunction()); } NODE_MODULE(scrollbar_style_observer, ScrollbarStyleObserver::Init) NAN_METHOD(ScrollbarStyleObserver::New) { NanScope(); Local<Function> callbackHandle = args[0].As<Function>(); NanCallback *callback = new NanCallback(callbackHandle); ScrollbarStyleObserver *observer = new ScrollbarStyleObserver(callback); observer->Wrap(args.This()); NanReturnUndefined(); } ScrollbarStyleObserver::ScrollbarStyleObserver(NanCallback *callback) : callback(callback) { } ScrollbarStyleObserver::~ScrollbarStyleObserver() { delete callback; }; void ScrollbarStyleObserver::HandleScrollbarStyleChanged() { } NAN_METHOD(ScrollbarStyleObserver::GetPreferredScrollbarStyle) { NanScope(); NanReturnValue(String::New("legacy")); }
#include <node.h> #include "nan.h" #include "scrollbar-style-observer.h" using namespace v8; void ScrollbarStyleObserver::Init(Handle<Object> target) { NanScope(); Local<FunctionTemplate> newTemplate = FunctionTemplate::New(ScrollbarStyleObserver::New); newTemplate->SetClassName(NanSymbol("ScrollbarStyleObserver")); newTemplate->InstanceTemplate()->SetInternalFieldCount(1); Local<ObjectTemplate> proto = newTemplate->PrototypeTemplate(); NODE_SET_METHOD(proto, "getPreferredScrollbarStyle", ScrollbarStyleObserver::GetPreferredScrollbarStyle); target->Set(NanSymbol("ScrollbarStyleObserver"), newTemplate->GetFunction()); } NODE_MODULE(scrollbar_style_observer, ScrollbarStyleObserver::Init) NAN_METHOD(ScrollbarStyleObserver::New) { NanScope(); Local<Function> callbackHandle = args[0].As<Function>(); NanCallback *callback = new NanCallback(callbackHandle); ScrollbarStyleObserver *observer = new ScrollbarStyleObserver(callback); observer->Wrap(args.This()); NanReturnUndefined(); } ScrollbarStyleObserver::ScrollbarStyleObserver(NanCallback *callback) : callback(callback) { } ScrollbarStyleObserver::~ScrollbarStyleObserver() { delete callback; }; void ScrollbarStyleObserver::HandleScrollbarStyleChanged() { } NAN_METHOD(ScrollbarStyleObserver::GetPreferredScrollbarStyle) { NanScope(); NanReturnValue(String::New("legacy")); }
Add chpl_error() and chpl_internal_error(), indicating they halt execution.
/** * Coverity Scan model * * Manage false positives by giving coverity some hints. * * Updates to this file must be manually submitted by an admin to: * * https://scan.coverity.com/projects/1222 * */ // When tag is 1 or 2, let coverity know that execution is halting. Those // tags correspond to INT_FATAL and USR_FATAL respectively. // // INT_FATAL, et al, work by calling setupError and then // handleError. setupError simply sets some static globals, then handleError // looks at those to decide how to error. For example, when INT_FATAL calls // handleError it will abort execution because exit_immediately is true. // // Here we're fibbing to coverity by telling it that setupError results in // abort (as opposed to handleError), but the effect should be the same. void setupError(const char *filename, int lineno, int tag) { if (tag == 1 || tag == 2) { __coverity_panic__(); } }
/** * Coverity Scan model * * Manage false positives by giving coverity some hints. * * Updates to this file must be manually submitted by an admin to: * * https://scan.coverity.com/projects/1222 * */ // When tag is 1 or 2, let coverity know that execution is halting. Those // tags correspond to INT_FATAL and USR_FATAL respectively. // // INT_FATAL, et al, work by calling setupError and then // handleError. setupError simply sets some static globals, then handleError // looks at those to decide how to error. For example, when INT_FATAL calls // handleError it will abort execution because exit_immediately is true. // // Here we're fibbing to coverity by telling it that setupError results in // abort (as opposed to handleError), but the effect should be the same. void setupError(const char *filename, int lineno, int tag) { if (tag == 1 || tag == 2) { __coverity_panic__(); } } //============================== // runtime // // chpl_error() ends execution void chpl_error(const char* message, int32_t lineno, c_string filename) { __coverity_panic__(); } // chpl_internal_error() ends execution void chpl_internal_error(const char* message) { __coverity_panic__(); }
Add 'MAX' to ControllerMaxLen enum set.
// Copyright 2014-present Bill Fisher. All rights reserved. #include "ofp/yaml/yllvm.h" #include "ofp/yaml/ycontrollermaxlen.h" using namespace ofp; using ofp::yaml::EnumConverterSparse; #define OFP_NAME(s) \ { OFPCML_##s, #s } OFP_BEGIN_IGNORE_GLOBAL_CONSTRUCTOR static std::pair<OFPControllerMaxLen, llvm::StringRef> sControllerMaxLen[] = { OFP_NAME(NO_BUFFER), }; EnumConverterSparse<OFPControllerMaxLen> llvm::yaml::ScalarTraits<ofp::ControllerMaxLen>::converter{ sControllerMaxLen}; OFP_END_IGNORE_GLOBAL_CONSTRUCTOR
// Copyright 2014-present Bill Fisher. All rights reserved. #include "ofp/yaml/yllvm.h" #include "ofp/yaml/ycontrollermaxlen.h" using namespace ofp; using ofp::yaml::EnumConverterSparse; #define OFP_NAME(s) \ { OFPCML_##s, #s } OFP_BEGIN_IGNORE_GLOBAL_CONSTRUCTOR static std::pair<OFPControllerMaxLen, llvm::StringRef> sControllerMaxLen[] = { OFP_NAME(MAX), OFP_NAME(NO_BUFFER), }; EnumConverterSparse<OFPControllerMaxLen> llvm::yaml::ScalarTraits<ofp::ControllerMaxLen>::converter{ sControllerMaxLen}; OFP_END_IGNORE_GLOBAL_CONSTRUCTOR
Fix missing sanitizer platform include
//=-- lsan_linux.cc -------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is a part of LeakSanitizer. Linux-specific code. // //===----------------------------------------------------------------------===// #if SANITIZER_LINUX #include "lsan_allocator.h" namespace __lsan { static THREADLOCAL AllocatorCache allocator_cache; AllocatorCache *GetAllocatorCache() { return &allocator_cache; } } // namespace __lsan #endif // SANITIZER_LINUX
//=-- lsan_linux.cc -------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is a part of LeakSanitizer. Linux-specific code. // //===----------------------------------------------------------------------===// #include "sanitizer_common/sanitizer_platform.h" #if SANITIZER_LINUX #include "lsan_allocator.h" namespace __lsan { static THREADLOCAL AllocatorCache allocator_cache; AllocatorCache *GetAllocatorCache() { return &allocator_cache; } } // namespace __lsan #endif // SANITIZER_LINUX
Remove output of scope without a resource from logging functions.
#include <puppet/compiler/evaluation/functions/alert.hpp> #include <puppet/compiler/evaluation/functions/call_context.hpp> #include <puppet/compiler/evaluation/scope.hpp> #include <puppet/logging/logger.hpp> using namespace std; using namespace puppet::runtime; namespace puppet { namespace compiler { namespace evaluation { namespace functions { values::value log(logging::logger& logger, scope const& current, logging::level level, values::array const& arguments) { // Format the message based on the arguments ostringstream ss; arguments.join(ss, " "); auto message = ss.str(); // Log the message if (logger.would_log(level)) { logger.log(level, (boost::format("%1%: %2%") % current % message).str()); } return message; } descriptor alert::create_descriptor() { functions::descriptor descriptor{ "alert" }; descriptor.add("Callable", [](call_context& context) { auto& evaluation_context = context.context(); return log(evaluation_context.node().logger(), *evaluation_context.calling_scope(), logging::level::alert, context.arguments()); }); return descriptor; } }}}} // namespace puppet::compiler::evaluation::functions
#include <puppet/compiler/evaluation/functions/alert.hpp> #include <puppet/compiler/evaluation/functions/call_context.hpp> #include <puppet/compiler/evaluation/scope.hpp> #include <puppet/logging/logger.hpp> using namespace std; using namespace puppet::runtime; namespace puppet { namespace compiler { namespace evaluation { namespace functions { values::value log(logging::logger& logger, scope const& current, logging::level level, values::array const& arguments) { // Format the message based on the arguments ostringstream ss; arguments.join(ss, " "); auto message = ss.str(); // Log the message if (logger.would_log(level)) { if (!current.resource()) { logger.log(level, message); } else { logger.log(level, (boost::format("%1%: %2%") % current % message).str()); } } return message; } descriptor alert::create_descriptor() { functions::descriptor descriptor{ "alert" }; descriptor.add("Callable", [](call_context& context) { auto& evaluation_context = context.context(); return log(evaluation_context.node().logger(), *evaluation_context.calling_scope(), logging::level::alert, context.arguments()); }); return descriptor; } }}}} // namespace puppet::compiler::evaluation::functions
Fix test failure on Windowns.
// Test header and library paths when Clang is used with Android standalone // toolchain. // // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \ // RUN: -target arm-linux-androideabi \ // RUN: -B%S/Inputs/basic_android_tree \ // RUN: --sysroot=%S/Inputs/basic_android_tree/sysroot \ // RUN: | FileCheck %s // CHECK: clang" "-cc1" // CHECK: "-internal-isystem" "{{.*}}/arm-linux-androideabi/include/c++/4.4.3" // CHECK: "-internal-isystem" "{{.*}}/arm-linux-androideabi/include/c++/4.4.3/arm-linux-androideabi" // CHECK: "-internal-externc-isystem" "{{.*}}/sysroot/include" // CHECK: "-internal-externc-isystem" "{{.*}}/sysroot/usr/include" // CHECK: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]" // CHECK: "-L{{.*}}/lib/gcc/arm-linux-androideabi/4.4.3" // CHECK: "-L{{.*}}/lib/gcc/arm-linux-androideabi/4.4.3/../../../../arm-linux-androideabi/lib" // CHECK: "-L{{.*}}/sysroot/usr/lib"
// Test header and library paths when Clang is used with Android standalone // toolchain. // // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \ // RUN: -target arm-linux-androideabi \ // RUN: -B%S/Inputs/basic_android_tree \ // RUN: --sysroot=%S/Inputs/basic_android_tree/sysroot \ // RUN: | FileCheck %s // CHECK: {{.*}}clang{{(.exe)?}}" "-cc1" // CHECK: "-internal-isystem" "{{.*}}/arm-linux-androideabi/include/c++/4.4.3" // CHECK: "-internal-isystem" "{{.*}}/arm-linux-androideabi/include/c++/4.4.3/arm-linux-androideabi" // CHECK: "-internal-externc-isystem" "{{.*}}/sysroot/include" // CHECK: "-internal-externc-isystem" "{{.*}}/sysroot/usr/include" // CHECK: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]" // CHECK: "-L{{.*}}/lib/gcc/arm-linux-androideabi/4.4.3" // CHECK: "-L{{.*}}/lib/gcc/arm-linux-androideabi/4.4.3/../../../../arm-linux-androideabi/lib" // CHECK: "-L{{.*}}/sysroot/usr/lib"
Disable DefaultPluginUITest::DefaultPluginLoadTest on windows as it crashes.
// 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/basictypes.h" #include "base/file_path.h" #include "build/build_config.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" class DefaultPluginUITest : public UITest { public: DefaultPluginUITest() { dom_automation_enabled_ = true; } }; TEST_F(DefaultPluginUITest, DefaultPluginLoadTest) { // Open page with default plugin. FilePath test_file(test_data_directory_); test_file = test_file.AppendASCII("default_plugin.html"); NavigateToURL(net::FilePathToFileURL(test_file)); // Check that the default plugin was loaded. It executes a bit of javascript // in the HTML file which replaces the innerHTML of div |result| with "DONE". scoped_refptr<TabProxy> tab(GetActiveTab()); std::wstring out; ASSERT_TRUE(tab->ExecuteAndExtractString(L"", L"domAutomationController.send(" L"document.getElementById('result').innerHTML)", &out)); ASSERT_EQ(L"DONE", out); }
// 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/basictypes.h" #include "base/file_path.h" #include "build/build_config.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" class DefaultPluginUITest : public UITest { public: DefaultPluginUITest() { dom_automation_enabled_ = true; } }; #if defined(OS_WIN) #define MAYBE_DefaultPluginLoadTest DISABLED_DefaultPluginLoadTest #else #define MAYBE_DefaultPluginLoadTest DefaultPluginLoadTest #endif TEST_F(DefaultPluginUITest, MAYBE_DefaultPluginLoadTest) { // Open page with default plugin. FilePath test_file(test_data_directory_); test_file = test_file.AppendASCII("default_plugin.html"); NavigateToURL(net::FilePathToFileURL(test_file)); // Check that the default plugin was loaded. It executes a bit of javascript // in the HTML file which replaces the innerHTML of div |result| with "DONE". scoped_refptr<TabProxy> tab(GetActiveTab()); std::wstring out; ASSERT_TRUE(tab->ExecuteAndExtractString(L"", L"domAutomationController.send(" L"document.getElementById('result').innerHTML)", &out)); ASSERT_EQ(L"DONE", out); }
Make front-end debug info namespace test frontend-only & more specific without overconstraining it
// RUN: %clang -g -S -fverbose-asm %s -o - | FileCheck %s // CHECK: TAG_namespace namespace A { enum numbers { ZERO, ONE }; } using namespace A; numbers n;
// RUN: %clang -g -S -emit-llvm %s -o - | FileCheck %s namespace A { int i; } // CHECK: [[FILE:![0-9]*]] = {{.*}} ; [ DW_TAG_file_type ] [{{.*}}/test/CodeGenCXX/debug-info-namespace.cpp] // CHECK: [[VAR:![0-9]*]] = {{.*}}, metadata [[NS:![0-9]*]], metadata !"i", {{.*}} ; [ DW_TAG_variable ] [i] // CHECK: [[NS]] = {{.*}}, metadata [[FILE]], {{.*}} ; [ DW_TAG_namespace ] [A] [line 3]
Fix for PR2881: fix a small leak exposed by valgrind, using a ManagedStatic.
//===-- PluginLoader.cpp - Implement -load command line option ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the -load <plugin> command line option handler. // //===----------------------------------------------------------------------===// #define DONT_GET_PLUGIN_LOADER_OPTION #include "llvm/Support/PluginLoader.h" #include "llvm/Support/Streams.h" #include "llvm/System/DynamicLibrary.h" #include <ostream> #include <vector> using namespace llvm; static std::vector<std::string> *Plugins; void PluginLoader::operator=(const std::string &Filename) { if (!Plugins) Plugins = new std::vector<std::string>(); std::string Error; if (sys::DynamicLibrary::LoadLibraryPermanently(Filename.c_str(), &Error)) { cerr << "Error opening '" << Filename << "': " << Error << "\n -load request ignored.\n"; } else { Plugins->push_back(Filename); } } unsigned PluginLoader::getNumPlugins() { return Plugins ? Plugins->size() : 0; } std::string &PluginLoader::getPlugin(unsigned num) { assert(Plugins && num < Plugins->size() && "Asking for an out of bounds plugin"); return (*Plugins)[num]; }
//===-- PluginLoader.cpp - Implement -load command line option ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the -load <plugin> command line option handler. // //===----------------------------------------------------------------------===// #define DONT_GET_PLUGIN_LOADER_OPTION #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/PluginLoader.h" #include "llvm/Support/Streams.h" #include "llvm/System/DynamicLibrary.h" #include <ostream> #include <vector> using namespace llvm; static ManagedStatic<std::vector<std::string> > Plugins; void PluginLoader::operator=(const std::string &Filename) { std::string Error; if (sys::DynamicLibrary::LoadLibraryPermanently(Filename.c_str(), &Error)) { cerr << "Error opening '" << Filename << "': " << Error << "\n -load request ignored.\n"; } else { Plugins->push_back(Filename); } } unsigned PluginLoader::getNumPlugins() { return Plugins.isConstructed() ? Plugins->size() : 0; } std::string &PluginLoader::getPlugin(unsigned num) { assert(Plugins.isConstructed() && num < Plugins->size() && "Asking for an out of bounds plugin"); return (*Plugins)[num]; }
Use document font in BracketedWindow.
#include "BracketedSentenceWidget.hh" #include <QDebug> #include <QPainter> #include <QTextEdit> #include <QSettings> BracketedSentenceWidget::BracketedSentenceWidget(QWidget *parent) : QTextEdit(parent), d_stylesheet(":/stylesheets/bracketed-sentence.xsl"), d_transformer(d_stylesheet) { QFontMetrics m(font()); int ruleHeight = m.lineSpacing(); setFixedHeight(2 * ruleHeight + (2 * document()->documentMargin())); setReadOnly(true); } void BracketedSentenceWidget::setParse(QString const &parse) { d_parse = parse; updateText(); } void BracketedSentenceWidget::updateText() { if (!d_parse.isEmpty()) { QString sentence = transformXML(d_parse); setText(sentence.trimmed()); } } QString BracketedSentenceWidget::transformXML(QString const &xml) const { QHash<QString, QString> params; return d_transformer.transform(xml, params); }
#include "BracketedSentenceWidget.hh" #include <QDebug> #include <QPainter> #include <QTextEdit> #include <QSettings> BracketedSentenceWidget::BracketedSentenceWidget(QWidget *parent) : QTextEdit(parent), d_stylesheet(":/stylesheets/bracketed-sentence.xsl"), d_transformer(d_stylesheet) { QFontMetrics m(document()->defaultFont()); int ruleHeight = m.lineSpacing(); setFixedHeight(2 * ruleHeight + (2 * document()->documentMargin())); setReadOnly(true); } void BracketedSentenceWidget::setParse(QString const &parse) { d_parse = parse; updateText(); } void BracketedSentenceWidget::updateText() { if (!d_parse.isEmpty()) { QString sentence = transformXML(d_parse); setText(sentence.trimmed()); } } QString BracketedSentenceWidget::transformXML(QString const &xml) const { QHash<QString, QString> params; return d_transformer.transform(xml, params); }
Use correct bound for static work allocation.
#include <boost/mpi.hpp> #include <iostream> #include <string> #include <set> #include <boost/serialization/string.hpp> #include "InstrumentFactories.h" #include "Stochastic.h" #include "Ising.h" #include "Measurement.h" namespace mpi = boost::mpi; int main(int argc, char* argv[]) { mpi::environment env(argc, argv); mpi::communicator world; char hostname[256]; int requester; const int dimension = 50; const int iterations = 1000; gethostname(hostname,255); std::clog << "Hello world from host " << hostname << std::endl; ReservoirFactory *rFactory = new DefaultArgsReservoirFactory<StochasticReservoir>; SystemFactory *sFactory = new BinomialSystemFactory; Experiment::range work; Experiment experiment; experiment.iterations = iterations; experiment.dimension = dimension; experiment.sfactory=sFactory; experiment.rfactory=rFactory; for (int k=world.rank(); k<iterations; k+=world.size()) { MeasurementResult result = experiment.performIteration(k); printf("%s\n",outputString(result).c_str()); } std::clog<<"Node "<<world.rank()<<" finished.\n"; return 0; }
#include <boost/mpi.hpp> #include <iostream> #include <string> #include <set> #include <boost/serialization/string.hpp> #include "InstrumentFactories.h" #include "Stochastic.h" #include "Ising.h" #include "Measurement.h" namespace mpi = boost::mpi; int main(int argc, char* argv[]) { mpi::environment env(argc, argv); mpi::communicator world; char hostname[256]; int requester; const int dimension = 50; const int iterations = 1000; gethostname(hostname,255); std::clog << "Hello world from host " << hostname << std::endl; ReservoirFactory *rFactory = new DefaultArgsReservoirFactory<StochasticReservoir>; SystemFactory *sFactory = new BinomialSystemFactory; Experiment::range work; Experiment experiment; experiment.iterations = iterations; experiment.dimension = dimension; experiment.sfactory=sFactory; experiment.rfactory=rFactory; for (int k=world.rank(); k<dimension*dimension; k+=world.size()) { MeasurementResult result = experiment.performIteration(k); printf("%s\n",outputString(result).c_str()); } std::clog<<"Node "<<world.rank()<<" finished.\n"; return 0; }
Fix compilation against recent libigt2
#include "tree.hh" #include "tree-entry.hh" namespace mimosa { namespace git { Tree::Tree(git_repository * repo, const git_oid * id) : tree_(nullptr) { if (id) git_tree_lookup(&tree_, repo, id); } Tree::Tree(git_repository * repo, const git_oid * id, const std::string & directory) : tree_(nullptr) { if (directory.empty()) { git_tree_lookup(&tree_, repo, id); return; } Tree root(repo, id); TreeEntry entry; if (git_tree_entry_bypath(entry.ref(), root, directory.c_str())) return; if (git_tree_entry_type(entry) != GIT_OBJ_TREE) return; git_tree_lookup(&tree_, repo, git_tree_entry_id(entry)); } Tree::~Tree() { git_tree_free(tree_); } } }
#include "tree.hh" #include "tree-entry.hh" namespace mimosa { namespace git { Tree::Tree(git_repository * repo, const git_oid * id) : tree_(nullptr) { if (id) git_tree_lookup(&tree_, repo, id); } Tree::Tree(git_repository * repo, const git_oid * id, const std::string & directory) : tree_(nullptr) { if (directory.empty()) { git_tree_lookup(&tree_, repo, id); return; } Tree root(repo, id); TreeEntry entry; if (git_tree_entry_bypath(entry.ref(), root, directory.c_str())) return; if (git_tree_entry_type(entry) != GIT_OBJECT_TREE) return; git_tree_lookup(&tree_, repo, git_tree_entry_id(entry)); } Tree::~Tree() { git_tree_free(tree_); } } }
Fix timer manager update loop
#include "stdafx.h" #include <dukat/timermanager.h> namespace dukat { Timer* TimerManager::create_timer(float interval, std::function<void(void)> callback, bool recurring) { auto timer = std::make_unique<Timer>(++last_id, interval, callback, recurring); auto res = timer.get(); timers.push_back(std::move(timer)); return res; } void TimerManager::cancel_timer(Timer* timer) { auto it = std::find_if(timers.begin(), timers.end(), [timer](const std::unique_ptr<Timer>& ptr) { return ptr.get() == timer; }); if (it != timers.end()) { timers.erase(it); } } void TimerManager::update(float delta) { for (auto it = timers.begin(); it != timers.end(); ) { (*it)->remaining -= delta; // check if timer has expired if ((*it)->remaining <= 0.0f) { if ((*it)->callback) { (*it)->callback(); } if ((*it)->recurring) { (*it)->remaining = (*it)->interval; } else { it = timers.erase(it); continue; } } ++it; } } }
#include "stdafx.h" #include <dukat/timermanager.h> namespace dukat { Timer* TimerManager::create_timer(float interval, std::function<void(void)> callback, bool recurring) { auto timer = std::make_unique<Timer>(++last_id, interval, callback, recurring); auto res = timer.get(); timers.push_back(std::move(timer)); return res; } void TimerManager::cancel_timer(Timer* timer) { auto it = std::find_if(timers.begin(), timers.end(), [timer](const std::unique_ptr<Timer>& ptr) { return ptr.get() == timer; }); if (it != timers.end()) { timers.erase(it); } } void TimerManager::update(float delta) { const auto max_id = last_id; for (auto it = timers.begin(); it != timers.end(); ) { // only process timers up to current max during this frame if ((*it)->id > max_id) break; (*it)->remaining -= delta; // check if timer has expired if ((*it)->remaining <= 0.0f) { if ((*it)->callback) { (*it)->callback(); } if ((*it)->recurring) { (*it)->remaining = (*it)->interval; } else { it = timers.erase(it); continue; } } ++it; } } }
Update the Python interface with the new names
/* * Chemharp, an efficient IO library for chemistry file formats * Copyright (C) 2015 Guillaume Fraux * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ */ #include "chemharp-python.hpp" void register_trajectory() { /* Trajectory class *******************************************************/ py::class_<Trajectory, boost::noncopyable>("Trajectory", py::init<string, py::optional<string, string>>()) .def("read_next_step", &Trajectory::read_next_step) .def("read_at_step", &Trajectory::read_at_step) .def("write_step", &Trajectory::write_step) .def("done", &Trajectory::done) .def("close", &Trajectory::close) .def("nsteps", &Trajectory::nsteps) .def("topology", static_cast<void (Trajectory::*)(const Topology&)>(&Trajectory::topology)) .def("topology", static_cast<void (Trajectory::*)(const string&)>(&Trajectory::topology)) ; }
/* * Chemharp, an efficient IO library for chemistry file formats * Copyright (C) 2015 Guillaume Fraux * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ */ #include "chemharp-python.hpp" void register_trajectory() { /* Trajectory class *******************************************************/ py::class_<Trajectory, boost::noncopyable>("Trajectory", py::init<string, py::optional<string, string>>()) .def("read", &Trajectory::read) .def("read_at", &Trajectory::read_at) .def("write", &Trajectory::write) .def("done", &Trajectory::done) .def("close", &Trajectory::close) .def("nsteps", &Trajectory::nsteps) .def("topology", static_cast<void (Trajectory::*)(const Topology&)>(&Trajectory::topology)) .def("topology", static_cast<void (Trajectory::*)(const string&)>(&Trajectory::topology)) ; }
Remove license header from example
/***************************************************************************** * * X testing environment - Google Test environment feat. dummy x server * * Copyright (C) 2011 Canonical Ltd. * * This program 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. * * 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 * General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include <xorg/gtest/test.h> using namespace xorg::testing; /** * @example xorg-gtest.cpp * * This is an example for using the fixture * xorg::testing::Test for your own tests. Please * make sure that you have the X.org dummy display * driver installed on your system and that you execute * the test with root privileges. */ TEST_F(Test, DummyXorgServerTest) { EXPECT_NE(0, DefaultRootWindow(Display())); }
#include <xorg/gtest/test.h> using namespace xorg::testing; /** * @example xorg-gtest.cpp * * This is an example for using the fixture * xorg::testing::Test for your own tests. Please * make sure that you have the X.org dummy display * driver installed on your system and that you execute * the test with root privileges. */ TEST_F(Test, DummyXorgServerTest) { EXPECT_NE(0, DefaultRootWindow(Display())); }
Add call to build lookup table
// Copyright 2015 Matt Heard // http://mattheard.net // matt@mattheard.net // @mattheard #include <opencv2/opencv.hpp> #include <iostream> #include <string> int main(int argc, char **argv) { using std::string; const int expectedNumArgs = 3; if (argc != expectedNumArgs) { const string cmdName = "ConvertToGrey"; const string argsDesc = " <Image_Path> <Reduce_By>"; std::cout << "Usage: " << cmdName << argsDesc << std::endl; return -1; } const string inputFilename = argv[1]; const cv::Mat srcImg = cv::imread(inputFilename); if (!srcImg.data) { const string err = "No image data"; std::cerr << err << std::cout; return -1; } const int divideWith = atoi(argv[2]); if (divideWith < 1) { std::cout << "Invalid number entered for dividing." << std::endl; return -1; } return 0; }
// Copyright 2015 Matt Heard // http://mattheard.net // matt@mattheard.net // @mattheard #include <opencv2/opencv.hpp> #include <iostream> #include <string> using cv::Mat; Mat buildLookUpTable(const int divideWith) { return Mat(); } int main(int argc, char **argv) { using std::string; const int expectedNumArgs = 3; if (argc != expectedNumArgs) { const string cmdName = "ConvertToGrey"; const string argsDesc = " <Image_Path> <Reduce_By>"; std::cout << "Usage: " << cmdName << argsDesc << std::endl; return -1; } const string inputFilename = argv[1]; const Mat srcImg = cv::imread(inputFilename); if (!srcImg.data) { const string err = "No image data"; std::cerr << err << std::cout; return -1; } const int divideWith = atoi(argv[2]); if (divideWith < 1) { std::cout << "Invalid number entered for dividing." << std::endl; return -1; } const Mat lookUpTable = buildLookUpTable(divideWith); return 0; }
Enable Sort for the XLA GPU backend.
/* Copyright 2017 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/compiler/tf2xla/tf2xla_util.h" #include "tensorflow/compiler/tf2xla/xla_op_registry.h" #include "tensorflow/core/framework/kernel_def.pb.h" namespace tensorflow { bool GpuOpFilter(KernelDef* kdef) { // TODO(b/26783907): The GPU backend currently does not implement sort. if (kdef->op() == "XlaSort" || kdef->op() == "TopKV2") { return false; } if (kdef->op() == "Const") { AddDtypeToKernalDefConstraint("dtype", DT_STRING, kdef); } if (kdef->op() == "Assert") { AddDtypeToKernalDefConstraint("T", DT_STRING, kdef); } return true; } REGISTER_XLA_BACKEND(DEVICE_GPU_XLA_JIT, kGpuAllTypes, GpuOpFilter); } // namespace tensorflow
/* Copyright 2017 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/compiler/tf2xla/tf2xla_util.h" #include "tensorflow/compiler/tf2xla/xla_op_registry.h" #include "tensorflow/core/framework/kernel_def.pb.h" namespace tensorflow { bool GpuOpFilter(KernelDef* kdef) { if (kdef->op() == "Const") { AddDtypeToKernalDefConstraint("dtype", DT_STRING, kdef); } if (kdef->op() == "Assert") { AddDtypeToKernalDefConstraint("T", DT_STRING, kdef); } return true; } REGISTER_XLA_BACKEND(DEVICE_GPU_XLA_JIT, kGpuAllTypes, GpuOpFilter); } // namespace tensorflow
Add range update to Fenwick
#include <bits/stdc++.h> using namespace std; struct Fenwick { vector<int> data; int len; Fenwick(int l) { len = l; data.assign(l + 1, 0); } void update(int at, int by) { while (at < len) { data[at] += by; at |= (at + 1); } } int query(int at) { int res = 0; while (at >= 0) { res += data[at]; at = (at & (at + 1)) - 1; } return res; } int queryRange(int l, int r) { return data[r] - data[l-1]; } }; int main() { }
#include <bits/stdc++.h> using namespace std; class Fenwick { private: vector<int> data; vector<int> dataMul; int len; bool range; void internalUpdate(int at, int mul, int add) { while (at < len) { dataMul[at] += mul; data[at] += add; at |= (at + 1); } } int queryStd(int at) { int res = 0; while (at >= 0) { res += data[at]; at = (at & (at + 1)) - 1; } return res; } int queryIfRange(int at) { int mul = 0; int add = 0; int start = at; while (at >= 0) { mul += dataMul[at]; add += data[at]; at = (at & (at + 1)) - 1; } return mul * start + add; } public: Fenwick(int len, bool range = false) { this->len = len; this->range = range; data.assign(len + 1, 0); if (range) dataMul.assign(len + 1, 0); } void update(int at, int by) { if (range) throw; while (at < len) { data[at] += by; at |= (at + 1); } } void updateRange(int left, int right, int by) { if (!range) throw; internalUpdate(left, by, -by * (left -1)); internalUpdate(right, -by, by * right); } int query(int at) { return range ? queryIfRange(at) : queryStd(at); } int queryRange(int l, int r) { return query(r) - query(l-1); } }; int main() { }
Add function to remove whitespace from input buffer.
/* Main Process for CLI tlisp */ /* Compile using g++ -std=c++11 -Wall main.cpp -o tlisp */ #include <iostream> #include <string> #include <iomanip> /* OSX / Linux Libraries */ // #include <readline.h> // #include <editline/history.h> using std::cin; using std::cout; using std::endl; using std::setw; using std::string; /* Globals... for now */ string input; int main(int argc, char** argv) { /* Very basic REPL */ cout << "tlisp Version 0.0.0.1" << endl; cout << "Press 'CTRL-c' to exit." << endl; while (true) { /* Prompt line */ cout << "tlisp >> "; getline(cin,input); if (input == "exit") { cout << "Have a nice day!"; break; } cout << "You entered: " << input << endl; } return 0; }
/* Main Process for CLI tlisp */ /* Compile using g++ -std=c++11 -Wall main.cpp -o tlisp */ #include <iostream> #include <iomanip> #include <string.h> /* OSX / Linux Libraries */ // #include <readline.h> // #include <editline/history.h> using std::cin; using std::cout; using std::endl; using std::setw; void remove_whitespace(char* str) { /* A small function to remove spaces and tabs from a C-string */ size_t idx = 0; // 'Copy to' string index size_t jdx = 0; // 'Copy from' string index while((*(str + idx) = *(str + jdx++)) != '\0') if (*(str + idx) != ' ' && *(str + idx) != '\t') // Remove spaces and tabs idx++; return; } int main(int argc, char** argv) { /* Very basic REPL */ const size_t MAX = 2048; char input_buffer[MAX]; cout << "tlisp Version 0.0.0.1" << endl; cout << "Press 'CTRL-c' to exit." << endl; while (true) { /* Prompt line */ cout << "tlisp >> "; cin.get(input_buffer, MAX).get(); /* REPL Exit check */ /* TODO: Currently if exit is anywhere in the buffer, the REPL will exit. It should only exit if the user enters 'exit' only. Need to fix this */ if (sizeof(strstr(input_buffer, "exit"))) { cout << endl << "Have a nice day!" << endl; break; } cout << "You entered: " << input_buffer << endl; cout << "Remove the whitespace!" << endl; remove_whitespace(input_buffer); cout << "This is better: " << input_buffer << endl; } return 0; }
Tidy code to follow guidelines
// // Copyright (c) 2018 The nanoFramework project contributors // Portions Copyright (c) Microsoft Corporation. All rights reserved. // See LICENSE file in the project root for full license information. // #include <ssl.h> #include "mbedtls.h" int ssl_write_internal( int sd, const char* data, size_t req_len) { mbedTLS_NFContext* context= (mbedTLS_NFContext*)SOCKET_DRIVER.GetSocketSslData(sd); mbedtls_ssl_context *ssl = context->ssl; int ret; // Loop until all data has been sent or error size_t req_offset = 0; do { ret = mbedtls_ssl_write( ssl, (const unsigned char *)(data + req_offset), req_len - req_offset); if (ret > 0) req_offset += static_cast<size_t>(ret); } while( req_offset < req_len && (ret > 0 || ret == MBEDTLS_ERR_SSL_WANT_WRITE || ret == MBEDTLS_ERR_SSL_WANT_READ) ); if (ret < 0) { //mbedtls_printf("mbedtls_ssl_write() returned -0x%04X\n", -ret); return 0; } return req_len; }
// // Copyright (c) 2018 The nanoFramework project contributors // Portions Copyright (c) Microsoft Corporation. All rights reserved. // See LICENSE file in the project root for full license information. // #include <ssl.h> #include "mbedtls.h" int ssl_write_internal( int sd, const char* data, size_t req_len) { mbedTLS_NFContext* context= (mbedTLS_NFContext*)SOCKET_DRIVER.GetSocketSslData(sd); mbedtls_ssl_context *ssl = context->ssl; int ret; // Loop until all data has been sent or error size_t req_offset = 0; do { ret = mbedtls_ssl_write( ssl, (const unsigned char *)(data + req_offset), req_len - req_offset); if (ret > 0) { req_offset += static_cast<size_t>(ret); } } while( req_offset < req_len && (ret > 0 || ret == MBEDTLS_ERR_SSL_WANT_WRITE || ret == MBEDTLS_ERR_SSL_WANT_READ) ); if (ret < 0) { //mbedtls_printf("mbedtls_ssl_write() returned -0x%04X\n", -ret); return 0; } return req_len; }
Add error message for missing socket.
#include "ofMain.h" #include "ofApp.h" #include <stdlib.h> int main(int argc, char* argv[]){ if (argc < 2) { exit(1); return 0; } else { ofSetupOpenGL(1024,768,OF_FULLSCREEN); ofRunApp(new ofApp(argv[1])); } }
#include "ofMain.h" #include "ofApp.h" #include <iostream> #include <stdlib.h> int main(int argc, char* argv[]){ if (argc < 2) { cerr << "Usage: interface <socket path>"; exit(1); return 0; } else { ofSetupOpenGL(1024,768,OF_FULLSCREEN); ofRunApp(new ofApp(argv[1])); } }
Upgrade to an Enhanced IIe if hard drives are present.
// // StaticAnalyser.cpp // Clock Signal // // Created by Thomas Harte on 14/04/2018. // Copyright 2018 Thomas Harte. All rights reserved. // #include "StaticAnalyser.hpp" #include "Target.hpp" Analyser::Static::TargetList Analyser::Static::AppleII::GetTargets(const Media &media, const std::string &, TargetPlatform::IntType) { auto target = std::make_unique<Target>(); target->media = media; if(!target->media.disks.empty()) target->disk_controller = Target::DiskController::SixteenSector; TargetList targets; targets.push_back(std::move(target)); return targets; }
// // StaticAnalyser.cpp // Clock Signal // // Created by Thomas Harte on 14/04/2018. // Copyright 2018 Thomas Harte. All rights reserved. // #include "StaticAnalyser.hpp" #include "Target.hpp" Analyser::Static::TargetList Analyser::Static::AppleII::GetTargets(const Media &media, const std::string &, TargetPlatform::IntType) { auto target = std::make_unique<Target>(); target->media = media; // If any disks are present, attach a Disk II. if(!target->media.disks.empty()) { target->disk_controller = Target::DiskController::SixteenSector; } // The emulated SCSI card requires a IIe, so upgrade to that if // any mass storage is present. if(!target->media.mass_storage_devices.empty()) { target->model = Target::Model::EnhancedIIe; } TargetList targets; targets.push_back(std::move(target)); return targets; }
Add the OpenGL state objects to the property manager
#include "precompiled.hpp" #include "ui/docks/OpenGLStateWidget.hpp" #include "gl/OpenGLPointers.hpp" namespace balls { OpenGLStateWidget::OpenGLStateWidget(OpenGLPointers& gl, QWidget* parent) : QWidget(parent), m_blendState(gl), m_clipOptions(gl), m_colorOptions(gl), m_depthOptions(gl), m_geometryOptions(gl), m_hints(gl), m_implementationInfo(gl), m_sampleOptions(gl), m_stencilOptions(gl) { ui.setupUi(this); } }
#include "precompiled.hpp" #include "ui/docks/OpenGLStateWidget.hpp" #include "gl/OpenGLPointers.hpp" namespace balls { OpenGLStateWidget::OpenGLStateWidget(OpenGLPointers& gl, QWidget* parent) : QWidget(parent), m_blendState(gl), m_clipOptions(gl), m_colorOptions(gl), m_depthOptions(gl), m_geometryOptions(gl), m_hints(gl), m_implementationInfo(gl), m_sampleOptions(gl), m_stencilOptions(gl) { ui.setupUi(this); ui.openGlProperties->addObject(&m_blendState); ui.openGlProperties->addObject(&m_clipOptions); ui.openGlProperties->addObject(&m_colorOptions); ui.openGlProperties->addObject(&m_depthOptions); ui.openGlProperties->addObject(&m_geometryOptions); ui.openGlProperties->addObject(&m_hints); ui.openGlProperties->addObject(&m_implementationInfo); ui.openGlProperties->addObject(&m_sampleOptions); ui.openGlProperties->addObject(&m_stencilOptions); } }
Fix typo spotted by Phil. Still doesn't fix the assertion.
/* Copyright (C) 2008 Paul Richards. This program 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. 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "stdafx.h" #include "DebugOutputCallbacks.h" namespace Proffy { DebugOutputCallbacks::~DebugOutputCallbacks() { } HRESULT __stdcall DebugOutputCallbacks::QueryInterface(REFIID interfaceId, PVOID* result) { *result = NULL; if (IsEqualIID(interfaceId, __uuidof(IUnknown)) || IsEqualIID(interfaceId, __uuidof(IDebugEventCallbacks))) { *result = this; AddRef(); return S_OK; } else { return E_NOINTERFACE; } } ULONG __stdcall DebugOutputCallbacks::AddRef(void) { return 1; } ULONG __stdcall DebugOutputCallbacks::Release(void) { return 1; } HRESULT __stdcall DebugOutputCallbacks::Output(ULONG /*mask*/, PCSTR text) { std::cout << text; return S_OK; } }
/* Copyright (C) 2008 Paul Richards. This program 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. 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "stdafx.h" #include "DebugOutputCallbacks.h" namespace Proffy { DebugOutputCallbacks::~DebugOutputCallbacks() { } HRESULT __stdcall DebugOutputCallbacks::QueryInterface(REFIID interfaceId, PVOID* result) { *result = NULL; if (IsEqualIID(interfaceId, __uuidof(IUnknown)) || IsEqualIID(interfaceId, __uuidof(IDebugOutputCallbacks))) { *result = this; AddRef(); return S_OK; } else { return E_NOINTERFACE; } } ULONG __stdcall DebugOutputCallbacks::AddRef(void) { return 1; } ULONG __stdcall DebugOutputCallbacks::Release(void) { return 1; } HRESULT __stdcall DebugOutputCallbacks::Output(ULONG /*mask*/, PCSTR text) { std::cout << text; return S_OK; } }
Fix unit test now that 'ld' is host specific
//===- lld/unittest/UniversalDriverTest.cpp -------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Universal driver tests that depend on the value of argv[0]. /// //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "lld/Driver/Driver.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; using namespace lld; TEST(UniversalDriver, flavor) { const char *args[] = { "ld" }; std::string diags; raw_string_ostream os(diags); UniversalDriver::link(array_lengthof(args), args, os); EXPECT_EQ(os.str().find("failed to determine driver flavor"), std::string::npos); EXPECT_NE(os.str().find("No input files"), std::string::npos); }
//===- lld/unittest/UniversalDriverTest.cpp -------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Universal driver tests that depend on the value of argv[0]. /// //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "lld/Driver/Driver.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; using namespace lld; TEST(UniversalDriver, flavor) { const char *args[] = { "gnu-ld" }; std::string diags; raw_string_ostream os(diags); UniversalDriver::link(array_lengthof(args), args, os); EXPECT_EQ(os.str().find("failed to determine driver flavor"), std::string::npos); EXPECT_NE(os.str().find("No input files"), std::string::npos); }
Remove a hard CHECK when allocating instance ID would fail.
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/api/guest_view/guest_view_internal_api.h" #include "chrome/browser/guest_view/guest_view_manager.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/extensions/api/guest_view_internal.h" #include "extensions/common/permissions/permissions_data.h" namespace extensions { GuestViewInternalAllocateInstanceIdFunction:: GuestViewInternalAllocateInstanceIdFunction() { } bool GuestViewInternalAllocateInstanceIdFunction::RunAsync() { EXTENSION_FUNCTION_VALIDATE(!args_->GetSize()); // Check if we have "webview" permission. CHECK(GetExtension()->permissions_data()->HasAPIPermission( APIPermission::kWebView)); int instanceId = GuestViewManager::FromBrowserContext(browser_context()) ->GetNextInstanceID(); SetResult(base::Value::CreateIntegerValue(instanceId)); SendResponse(true); return true; } } // namespace extensions
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/api/guest_view/guest_view_internal_api.h" #include "chrome/browser/guest_view/guest_view_manager.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/extensions/api/guest_view_internal.h" #include "extensions/common/permissions/permissions_data.h" namespace { const char* kWebViewPermissionRequiredError = "\"webview\" permission is required for allocating instance ID."; } // namespace namespace extensions { GuestViewInternalAllocateInstanceIdFunction:: GuestViewInternalAllocateInstanceIdFunction() { } bool GuestViewInternalAllocateInstanceIdFunction::RunAsync() { EXTENSION_FUNCTION_VALIDATE(!args_->GetSize()); if (!GetExtension()->permissions_data()->HasAPIPermission( APIPermission::kWebView)) { LOG(ERROR) << kWebViewPermissionRequiredError; error_ = kWebViewPermissionRequiredError; SendResponse(false); return false; } int instanceId = GuestViewManager::FromBrowserContext(browser_context()) ->GetNextInstanceID(); SetResult(base::Value::CreateIntegerValue(instanceId)); SendResponse(true); return true; } } // namespace extensions
Add some missing function initializers.
// Native C++ Libraries #include <iostream> #include <string> #include <sstream> #include <vector> // C++ Interpreter Libraries #include <Console.h> #include <Varible.h> #include <Include.h> using namespace std; int main() { RESTART: string input = ""; getline(cin, input); goto RESTART; }
// Native C++ Libraries #include <iostream> #include <string> #include <sstream> #include <vector> // C++ Interpreter Libraries #include <Console.h> #include <Varible.h> #include <Include.h> using namespace std; int main() { RESTART: string input = ""; ConsoleOutCheck(input); CheckForInt(input); CheckForIntAfterMath(input); CHECKFORIOSTREAM(input); getline(cin, input); goto RESTART; }
Correct error introduced by file rename.
#include "kronrodLaurieGautschi.h" #include "kronrodPiessensBurkardt.h" #include <iostream> #include <iomanip> using namespace Kronrod; using namespace Eigen; using namespace std; int main() { Array<double,Dynamic,2> ans; int n = 10; ans = multiPrecisionKronrod(n); cout << "Laurie/Gautschi:" << endl; cout << setprecision(15); cout << ans << endl; cout << endl << endl; cout << "PiessensBurkardt" << endl; Array<double, Dynamic, 1> xGK; Array<double, Dynamic, 1> wGK; Array<double, Dynamic, 1> wG; kronrod(n, xGK, wGK, wG); cout << xGK << endl << endl; cout << wGK << endl << endl; cout << wG << endl << endl; return 0; }
#include "kronrodLaurieGautschi.h" #include "kronrodPiessens.h" #include <iostream> #include <iomanip> using namespace Kronrod; using namespace Eigen; using namespace std; int main() { Array<double,Dynamic,2> ans; int n = 10; ans = multiPrecisionKronrod(n); cout << "Laurie/Gautschi:" << endl; cout << setprecision(15); cout << ans << endl; cout << endl << endl; cout << "Piessens" << endl; Array<double, Dynamic, 1> xGK; Array<double, Dynamic, 1> wGK; Array<double, Dynamic, 1> wG; kronrod(n, xGK, wGK, wG); cout << xGK << endl << endl; cout << wGK << endl << endl; cout << wG << endl << endl; return 0; }
Print maxrss before playing each video.
#include <stdio.h> #include "video.h" int main(int argc, char* argv[]) { if (argc < 3) { printf("missing filename\n"); exit(0); } gst_init (NULL,NULL); int k; sscanf(argv[2], "%d", &k); for (int q = 0; q < k; q++) { video testvideo(argv[1]); while (testvideo.getvisible()) { testvideo.update(); } } gst_deinit(); }
/* Copyright 2014, Adrien Destugues <pulkomandy@pulkomandy.tk> * Distributed under the terms of the MIT license */ #include <stdio.h> #include <sys/time.h> #include <sys/resource.h> #include "video.h" int main(int argc, char* argv[]) { if (argc < 3) { printf("missing filename\n"); exit(EXIT_FAILURE); } gst_init (NULL,NULL); struct rusage usage; int k; sscanf(argv[2], "%d", &k); for (int q = 0; q < k; q++) { getrusage(RUSAGE_CHILDREN, &usage); printf("Loop %d: maxrss=%d\n", q, usage.ru_maxrss); video testvideo(argv[1]); while (testvideo.getvisible()) { testvideo.update(); } } gst_deinit(); exit(EXIT_SUCCESS); }
Fix compilation error with clang.
#include "company.hpp" #include <ref/DescriptorsImpl.ipp> template class ref::ClassDescriptorImpl< example::Company >;
#include "company.hpp" #include <ref/DescriptorsImpl.ipp> template struct ref::ClassDescriptorImpl< example::Company >;
Fix tsan test for Darwin. NFCI.
// RUN: %clangxx_tsan -O1 -DTEST_ERROR=ERANGE %s -o %t && %run %t 2>&1 | FileCheck --check-prefixes=CHECK,CHECK-SYS %s // RUN: %clangxx_tsan -O1 -DTEST_ERROR=-1 %s -o %t && not %run %t 2>&1 | FileCheck --check-prefixes=CHECK,CHECK-USER %s #include <assert.h> #include <errno.h> #include <pthread.h> #include <stdio.h> #include <string.h> char buffer[1000]; void *Thread(void *p) { return strerror_r(TEST_ERROR, buffer, sizeof(buffer)); } int main() { pthread_t th[2]; pthread_create(&th[0], 0, Thread, 0); pthread_create(&th[1], 0, Thread, 0); pthread_join(th[0], 0); pthread_join(th[1], 0); fprintf(stderr, "DONE\n"); } // CHECK-USER: WARNING: ThreadSanitizer: data race // CHECK-SYS-NOT: WARNING: ThreadSanitizer: data race // CHECK: DONE
// RUN: %clangxx_tsan -O1 -DTEST_ERROR=ERANGE %s -o %t && %run %t 2>&1 | FileCheck --check-prefixes=CHECK,CHECK-SYS %s // RUN: %clangxx_tsan -O1 -DTEST_ERROR=-1 %s -o %t && not %run %t 2>&1 | FileCheck --check-prefixes=CHECK,CHECK-USER %s #include <assert.h> #include <errno.h> #include <pthread.h> #include <stdio.h> #include <string.h> char buffer[1000]; void *Thread(void *p) { (void)strerror_r(TEST_ERROR, buffer, sizeof(buffer)); return p; } int main() { pthread_t th[2]; pthread_create(&th[0], 0, Thread, 0); pthread_create(&th[1], 0, Thread, 0); pthread_join(th[0], 0); pthread_join(th[1], 0); fprintf(stderr, "DONE\n"); } // CHECK-USER: WARNING: ThreadSanitizer: data race // CHECK-SYS-NOT: WARNING: ThreadSanitizer: data race // CHECK: DONE
Fix up after r163846. Sorry!
// RUN: %clang_cc1 -fsyntax-only -verify -std=c++0x %s enum X : short { A, B }; extern decltype(+A) x; extern int x; enum Y : long { C, D }; extern decltype(+C) y; extern long y; // An enum with a fixed underlying type has an integral promotion to that type, // and to its promoted type. enum B : bool { false_, true_ }; template<bool> struct T {}; T<false_> f; T<true_> t; T<+true_> t; // expected-error {{conversion from 'int' to 'bool'}} enum B2 : bool { a = false, b = true, c = false_, d = true_, e = +false_ // expected-error {{conversion from 'int' to 'bool'}} \ // FIXME: expected-error {{enumerator value 2 is not representable}} };
// RUN: %clang_cc1 -fsyntax-only -verify -std=c++0x %s enum X : short { A, B }; extern decltype(+A) x; extern int x; enum Y : long { C, D }; extern decltype(+C) y; extern long y; // An enum with a fixed underlying type has an integral promotion to that type, // and to its promoted type. enum B : bool { false_, true_ }; template<bool> struct T {}; T<false_> f; T<true_> t; // FIXME: DR1407 will make this ill-formed for a different reason. T<+true_> q; // desired-error {{conversion from 'int' to 'bool'}} enum B2 : bool { a = false, b = true, c = false_, d = true_, // FIXME: DR1407 will make this ill-formed e = +false_ // desired-error {{conversion from 'int' to 'bool'}} };
Change style of the code and file name
#include "Game.h" int main(int argc, char** argv) { // A * token followed by another * token in this case is a pointer to a pointer. In this case, argv is a pointer to an array of char*. It is equivalent to (int argc, char* argv[]). Game::Start(); return 0; }
#include "Game.h" #include <SFML/Graphics.hpp> int main(int argc, char** argv) { // A * token followed by another * token in this case is a pointer to a pointer. In this case, argv is a pointer to an array of char*. It is equivalent to (int argc, char* argv[]). Game::Start(); return 0; }
Make lost GL context checking more robust, fixes thread race between layers and renderers
#include "GLResource.h" #include "renderers/utils/GLResourceManager.h" #include <thread> namespace carto { GLResource::~GLResource() { } bool GLResource::isValid() const { if (_manager.lock()) { return true; } return false; } GLResource::GLResource(const std::weak_ptr<GLResourceManager>& manager) : _manager(manager) { } }
#include "GLResource.h" #include "renderers/utils/GLResourceManager.h" #include <thread> namespace carto { GLResource::~GLResource() { } bool GLResource::isValid() const { if (auto manager = _manager.lock()) { return manager->getGLThreadId() != std::thread::id(); } return false; } GLResource::GLResource(const std::weak_ptr<GLResourceManager>& manager) : _manager(manager) { } }
Update folder include for SysTime.h.
#include <paparazzi/SysTime.h> #include <unistd.h> #include <iostream> void printCallBack (uint8_t a) { std::cout << "Call !" << std::endl ; } int main () { SysTime *systime = SysTime::getSysTime () ; tid_t mainID = systime->registerTimer (0.5, printCallBack); tid_t stopID = systime->registerTimer (10, 0) ; while (!systime->checkAndAckTimer(stopID)) { usleep(10) ; } return 0 ; }
#include "../src/SysTime.h" #include <unistd.h> #include <iostream> void printCallBack (uint8_t a) { std::cout << "Call !" << std::endl ; } int main () { SysTime *systime = SysTime::getSysTime () ; tid_t mainID = systime->registerTimer (0.5, printCallBack); tid_t stopID = systime->registerTimer (10, 0) ; while (!systime->checkAndAckTimer(stopID)) { usleep(10) ; } return 0 ; }
Use regex_match to be more flexible with checking type_name's result
#include <mettle.hpp> using namespace mettle; struct my_type {}; namespace my_namespace { struct another_type {}; } suite<> test_type_name("type_name()", [](auto &_) { _.test("primitives", []() { expect(type_name<int>(), equal_to("int")); expect(type_name<int &>(), equal_to("int &")); expect(type_name<int &&>(), equal_to("int &&")); expect(type_name<const int>(), equal_to("const int")); expect(type_name<volatile int>(), equal_to("volatile int")); expect(type_name<const volatile int>(), equal_to("const volatile int")); }); _.test("custom types", []() { expect(type_name<my_type>(), equal_to("my_type")); expect(type_name<my_namespace::another_type>(), equal_to("my_namespace::another_type")); }); });
#include <mettle.hpp> using namespace mettle; struct my_type {}; namespace my_namespace { struct another_type {}; } suite<> test_type_name("type_name()", [](auto &_) { _.test("primitives", []() { expect(type_name<int>(), equal_to("int")); expect(type_name<int &>(), regex_match("int\\s*&")); expect(type_name<int &&>(), regex_match("int\\s*&&")); expect(type_name<const int>(), equal_to("const int")); expect(type_name<volatile int>(), equal_to("volatile int")); expect(type_name<const volatile int>(), equal_to("const volatile int")); }); _.test("custom types", []() { expect(type_name<my_type>(), equal_to("my_type")); expect(type_name<my_namespace::another_type>(), equal_to("my_namespace::another_type")); }); });
Correct function prototype of stub function.
/* * The MIT License (MIT) * * Copyright (c) <2016> <Stephan Gatzka> * * 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 <stdbool.h> #include "authenticate.h" extern "C" { bool credentials_ok(const char *user, char *passwd) { (void)user; (void)passwd; return true; } }
/* * The MIT License (MIT) * * Copyright (c) <2016> <Stephan Gatzka> * * 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 <stdbool.h> #include "authenticate.h" extern "C" { const cJSON *credentials_ok(const char *user, char *passwd) { (void)user; (void)passwd; return NULL; } }
Add a lambda example from the working draft.
// RUN: %clang_cc1 -std=c++11 %s -verify class X0 { void explicit_capture() { int foo; (void)[foo, foo] () {}; // expected-error {{'foo' can appear only once}} (void)[this, this] () {}; // expected-error {{'this' can appear only once}} (void)[=, foo] () {}; // expected-error {{'&' must precede a capture when}} (void)[=, &foo] () {}; (void)[=, this] () {}; // expected-error {{'this' cannot appear}} (void)[&, foo] () {}; (void)[&, &foo] () {}; // expected-error {{'&' cannot precede a capture when}} (void)[&, this] () {}; } };
// RUN: %clang_cc1 -std=c++11 %s -verify class X0 { void explicit_capture() { int foo; (void)[foo, foo] () {}; // expected-error {{'foo' can appear only once}} (void)[this, this] () {}; // expected-error {{'this' can appear only once}} (void)[=, foo] () {}; // expected-error {{'&' must precede a capture when}} (void)[=, &foo] () {}; (void)[=, this] () {}; // expected-error {{'this' cannot appear}} (void)[&, foo] () {}; (void)[&, &foo] () {}; // expected-error {{'&' cannot precede a capture when}} (void)[&, this] () {}; } }; struct S2 { void f(int i); }; void S2::f(int i) { (void)[&, i]{ }; (void)[&, &i]{ }; // expected-error{{'&' cannot precede a capture when the capture default is '&'}} (void)[=, this]{ }; // expected-error{{'this' cannot appear in a capture list when the capture default is '='}} (void)[i, i]{ }; // expected-error{{'i' can appear only once in a capture list}} }
Add pause before exit on windows systems
#include <need-hug-lib/hpp/NeedHugGame.hpp> #include <need-hug-lib/hpp/ReturnCode/ReturnCodeConverter.hpp> #include <iostream> int main(int argc, char** argv) { using namespace NeedHug; ReturnCode returnCode = ReturnCode::Continue; while(returnCode == NeedHug::ReturnCode::Continue) { // When the code reaches here, nothing should be allocated any longer in order to avoid memoryleaks. NeedHugGame needHugGame; try { returnCode = needHugGame.Start(); } catch(...) { std::cout << "Game crashed unexpectedly" << std::endl; returnCode = ReturnCode::Unknown; } } std::cout << "The game returned the following stopCode '" << ReturnCodeConverter().Convert(returnCode).info << "'." << std::endl; int returnCodeValue = 1; if(returnCode == ReturnCode::Stop) { returnCodeValue = 0; } return returnCodeValue; }
#include <need-hug-lib/hpp/NeedHugGame.hpp> #include <need-hug-lib/hpp/ReturnCode/ReturnCodeConverter.hpp> #include <iostream> int main(int argc, char** argv) { using namespace NeedHug; ReturnCode returnCode = ReturnCode::Continue; while (returnCode == NeedHug::ReturnCode::Continue) { // When the code reaches here, nothing should be allocated any longer in order to avoid memoryleaks. NeedHugGame needHugGame; try { returnCode = needHugGame.Start(); } catch (...) { std::cout << "Game crashed unexpectedly" << std::endl; returnCode = ReturnCode::Unknown; } } std::cout << "The game returned the following stopCode '" << ReturnCodeConverter().Convert(returnCode).info << "'." << std::endl; int returnCodeValue = 1; if (returnCode == ReturnCode::Stop) { returnCodeValue = 0; } #ifdef _WIN32 std::getchar(); #endif return returnCodeValue; }
UPDATE json, add some message for details
#include <iostream> #include <iomanip> // for std::setw #include <nlohmann/json.hpp> using json = nlohmann::json; bool parse_and_dump(const char* text, json& result) { // parse and serialize JSON result = json::parse(text); //std::cout << std::setw(4) << j_complete << "\n\n"; return true; } int test_parse_string() { // a JSON text auto text = R"( { "Image": { "Width": 800, "Height": 600, "Title": "View from 15th Floor", "Thumbnail": { "Url": "http://www.example.com/image/481989943", "Height": 125, "Width": 100 }, "Animated" : false, "IDs": [116, 943, 234, 38793] } } )"; json myobj; if ( parse_and_dump(text, myobj) ) { std::cout << std::setw(4) << myobj << "\n\n"; return true; } return false; }
#include <iostream> #include <iomanip> // for std::setw #include <nlohmann/json.hpp> bool parse_and_dump(const char* text, nlohmann::json& result) { using json = nlohmann::json; // parse and serialize JSON result = json::parse(text); //std::cout << std::setw(4) << j_complete << "\n\n"; return true; } int test_parse_string() { using namespace std; using json = nlohmann::json; cout << __func__ << " uses a RAW string to initialize a json object\n"; // a JSON text auto text = R"( { "Image": { "Width": 800, "Height": 600, "Title": "View from 15th Floor", "Thumbnail": { "Url": "http://www.example.com/image/481989943", "Height": 125, "Width": 100 }, "Animated" : false, "IDs": [116, 943, 234, 38793] } } )"; json myobj; auto query = myobj.meta(); cout << "json.hpp version: " << query["version"]["string"] << endl; if ( parse_and_dump(text, myobj) ) { cout << std::setw(4) << myobj << "\n\n"; return true; } return false; }
Make the implicit cast of size_t to int explicit
// Copyright 2010 Google Inc. 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 <string.h> #include <time.h> #include <cstdlib> // A simple piece of data to be exported. extern int kExportedData[1024] = { 0 }; int function1() { return rand(); } int function2() { return strlen("hello"); } int function3() { return static_cast<int>(clock()) + function1(); }
// Copyright 2010 Google Inc. 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 <string.h> #include <time.h> #include <cstdlib> // A simple piece of data to be exported. extern int kExportedData[1024] = { 0 }; int function1() { return rand(); } int function2() { return static_cast<int>(strlen("hello")); } int function3() { return static_cast<int>(clock()) + function1(); }
Change the stub for file_util::EvictFileFromSystemCache
// Copyright (c) 2008 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/test_file_util.h" #include "base/logging.h" namespace file_util { bool EvictFileFromSystemCache(const FilePath& file) { // TODO(port): Implement. NOTIMPLEMENTED(); return false; } } // namespace file_util
// Copyright (c) 2008 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/test_file_util.h" #include "base/logging.h" namespace file_util { bool EvictFileFromSystemCache(const FilePath& file) { // There is no way that we can think of to dump something from the UBC. You // can add something so when you open it, it doesn't go in, but that won't // work here. return true; } } // namespace file_util
Add a comment about eye resolution parameters in case of operator HMD renderer
#include "stdafx.h" #include "OpenGLOperatorOculusRiftRenderer.h" namespace operator_view { namespace opengl { OperatorOculusRiftRenderer::OperatorOculusRiftRenderer(std::shared_ptr<IOperatorRenderer> operatorRendererToDecorate) : IOperatorOculusRiftRenderer(operatorRendererToDecorate) { } void OperatorOculusRiftRenderer::initialize(std::uint16_t eyeResolutionWidth, std::uint16_t eyeResolutionHeight) { Q_UNUSED(eyeResolutionWidth); Q_UNUSED(eyeResolutionHeight); } void OperatorOculusRiftRenderer::renderLeftEye() { } void OperatorOculusRiftRenderer::renderRightEye() { } } }
#include "stdafx.h" #include "OpenGLOperatorOculusRiftRenderer.h" namespace operator_view { namespace opengl { OperatorOculusRiftRenderer::OperatorOculusRiftRenderer(std::shared_ptr<IOperatorRenderer> operatorRendererToDecorate) : IOperatorOculusRiftRenderer(operatorRendererToDecorate) { } void OperatorOculusRiftRenderer::initialize(std::uint16_t eyeResolutionWidth, std::uint16_t eyeResolutionHeight) { // The HMD will override these values. // Therefore, they are not used here. // Q_UNUSED(eyeResolutionWidth); Q_UNUSED(eyeResolutionHeight); } void OperatorOculusRiftRenderer::renderLeftEye() { } void OperatorOculusRiftRenderer::renderRightEye() { } } }
Remove -fPIC from shared build test.
// RUN: %clangxx -shared -fPIC -o /dev/null -v -fxray-instrument %s 2>&1 | \ // RUN: FileCheck %s --check-prefix=SHARED // RUN: %clangxx -static -o /dev/null -v -fxray-instrument %s 2>&1 -DMAIN | \ // RUN: FileCheck %s --check-prefix=STATIC // // SHARED-NOT: {{clang_rt\.xray-}} // STATIC: {{clang_rt\.xray-}} // // REQUIRES: linux int foo() { return 42; } #ifdef MAIN int main() { return foo(); } #endif
// RUN: %clangxx -shared -o /dev/null -v -fxray-instrument %s 2>&1 | \ // RUN: FileCheck %s --check-prefix=SHARED // RUN: %clangxx -static -o /dev/null -v -fxray-instrument %s 2>&1 -DMAIN | \ // RUN: FileCheck %s --check-prefix=STATIC // // SHARED-NOT: {{clang_rt\.xray-}} // STATIC: {{clang_rt\.xray-}} // // REQUIRES: linux int foo() { return 42; } #ifdef MAIN int main() { return foo(); } #endif
Remove unnecessary uses of <iostream>.
//===- fpcmp.cpp - A fuzzy "cmp" that permits floating point noise --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // fpcmp is a tool that basically works like the 'cmp' tool, except that it can // tolerate errors due to floating point noise, with the -r and -a options. // //===----------------------------------------------------------------------===// #include "llvm/Support/CommandLine.h" #include "llvm/Support/FileUtilities.h" #include <iostream> using namespace llvm; namespace { cl::opt<std::string> File1(cl::Positional, cl::desc("<input file #1>"), cl::Required); cl::opt<std::string> File2(cl::Positional, cl::desc("<input file #2>"), cl::Required); cl::opt<double> RelTolerance("r", cl::desc("Relative error tolerated"), cl::init(0)); cl::opt<double> AbsTolerance("a", cl::desc("Absolute error tolerated"), cl::init(0)); } int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv); std::string ErrorMsg; int DF = DiffFilesWithTolerance(sys::PathWithStatus(File1), sys::PathWithStatus(File2), AbsTolerance, RelTolerance, &ErrorMsg); if (!ErrorMsg.empty()) std::cerr << argv[0] << ": " << ErrorMsg << "\n"; return DF; }
//===- fpcmp.cpp - A fuzzy "cmp" that permits floating point noise --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // fpcmp is a tool that basically works like the 'cmp' tool, except that it can // tolerate errors due to floating point noise, with the -r and -a options. // //===----------------------------------------------------------------------===// #include "llvm/Support/CommandLine.h" #include "llvm/Support/FileUtilities.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; namespace { cl::opt<std::string> File1(cl::Positional, cl::desc("<input file #1>"), cl::Required); cl::opt<std::string> File2(cl::Positional, cl::desc("<input file #2>"), cl::Required); cl::opt<double> RelTolerance("r", cl::desc("Relative error tolerated"), cl::init(0)); cl::opt<double> AbsTolerance("a", cl::desc("Absolute error tolerated"), cl::init(0)); } int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv); std::string ErrorMsg; int DF = DiffFilesWithTolerance(sys::PathWithStatus(File1), sys::PathWithStatus(File2), AbsTolerance, RelTolerance, &ErrorMsg); if (!ErrorMsg.empty()) errs() << argv[0] << ": " << ErrorMsg << "\n"; return DF; }
Change logging level to show >=INFO severity
#include "Logging.h" #include <SenseKit/sensekit_types.h> INITIALIZE_LOGGING namespace sensekit { void initialize_logging(const char* logFilePath) { const char TRUE_STRING[] = "true"; el::Loggers::addFlag(el::LoggingFlag::CreateLoggerAutomatically); el::Loggers::addFlag(el::LoggingFlag::ColoredTerminalOutput); el::Loggers::addFlag(el::LoggingFlag::HierarchicalLogging); el::Loggers::setLoggingLevel(el::Level::Info); el::Configurations defaultConf; defaultConf.setToDefault(); defaultConf.setGlobally(el::ConfigurationType::Enabled, TRUE_STRING); defaultConf.setGlobally(el::ConfigurationType::ToStandardOutput, TRUE_STRING); defaultConf.setGlobally(el::ConfigurationType::ToFile, TRUE_STRING); defaultConf.setGlobally(el::ConfigurationType::Filename, logFilePath); el::Loggers::setDefaultConfigurations(defaultConf, true); defaultConf.clear(); } }
#include "Logging.h" #include <SenseKit/sensekit_types.h> INITIALIZE_LOGGING namespace sensekit { void initialize_logging(const char* logFilePath) { const char TRUE_STRING[] = "true"; el::Loggers::addFlag(el::LoggingFlag::CreateLoggerAutomatically); el::Loggers::addFlag(el::LoggingFlag::ColoredTerminalOutput); el::Loggers::addFlag(el::LoggingFlag::HierarchicalLogging); el::Configurations defaultConf; defaultConf.setToDefault(); defaultConf.setGlobally(el::ConfigurationType::Enabled, TRUE_STRING); defaultConf.setGlobally(el::ConfigurationType::ToStandardOutput, TRUE_STRING); defaultConf.setGlobally(el::ConfigurationType::ToFile, TRUE_STRING); defaultConf.setGlobally(el::ConfigurationType::Filename, logFilePath); el::Loggers::setDefaultConfigurations(defaultConf, true); el::Loggers::setLoggingLevel(el::Level::Debug); defaultConf.clear(); } }
Fix strstr search (using std::search instead)
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "stdafx.h" #include "search_strstr.h" StrStrSearch::StrStrSearch() : pattern_(NULL), patternLen_(0) { } void StrStrSearch::PreProcess(const char *pattern, int patternLen, SearchOptions options, SearchCreateResult& result) { pattern_ = pattern; patternLen_ = patternLen; } void StrStrSearch::Search(SearchParams* searchParams) { const char* start = searchParams->TextStart; if (searchParams->MatchStart) { start = searchParams->MatchStart + searchParams->MatchLength; } searchParams->MatchStart = strstr(start, pattern_); if (searchParams->MatchStart != nullptr) { searchParams->MatchLength = patternLen_; } }
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "stdafx.h" #include "search_strstr.h" #include <algorithm> StrStrSearch::StrStrSearch() : pattern_(NULL), patternLen_(0) { } void StrStrSearch::PreProcess( const char *pattern, int patternLen, SearchOptions options, SearchCreateResult& result) { pattern_ = pattern; patternLen_ = patternLen; } void StrStrSearch::Search(SearchParams* searchParams) { const char* start = searchParams->TextStart; const char* last = searchParams->TextStart + searchParams->TextLength; if (searchParams->MatchStart) { start = searchParams->MatchStart + searchParams->MatchLength; } auto result = std::search(start, last, pattern_, pattern_ + patternLen_); if (result == last) { searchParams->MatchStart = nullptr; searchParams->MatchLength = 0; return; } searchParams->MatchStart = result; searchParams->MatchLength = patternLen_; }
Fix spelling error in comment.
//===- tools/lld/lld.cpp - Linker Driver Dispatcher -----------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// /// This is the entry point to the lld driver. This is a thin wrapper which /// dispatches to the given platform specific driver. /// //===----------------------------------------------------------------------===// #include "lld/Core/LLVM.h" #include "lld/Driver/Driver.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" using namespace lld; /// Universal linker main(). This linker eumulates the gnu, darwin, or /// windows linker based on the tool name or if the first argument is /// -flavor. int main(int argc, const char *argv[]) { // Standard set up, so program fails gracefully. llvm::sys::PrintStackTraceOnErrorSignal(); llvm::PrettyStackTraceProgram stackPrinter(argc, argv); llvm::llvm_shutdown_obj shutdown; return !UniversalDriver::link( llvm::MutableArrayRef<const char *>(argv, argc)); }
//===- tools/lld/lld.cpp - Linker Driver Dispatcher -----------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// /// This is the entry point to the lld driver. This is a thin wrapper which /// dispatches to the given platform specific driver. /// //===----------------------------------------------------------------------===// #include "lld/Core/LLVM.h" #include "lld/Driver/Driver.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" using namespace lld; /// Universal linker main(). This linker emulates the gnu, darwin, or /// windows linker based on the tool name or if the first argument is /// -flavor. int main(int argc, const char *argv[]) { // Standard set up, so program fails gracefully. llvm::sys::PrintStackTraceOnErrorSignal(); llvm::PrettyStackTraceProgram stackPrinter(argc, argv); llvm::llvm_shutdown_obj shutdown; return !UniversalDriver::link( llvm::MutableArrayRef<const char *>(argv, argc)); }
Increase the base font size for touch ui
// 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 "views/controls/menu/menu_config.h" #include "grit/app_resources.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/resource/resource_bundle.h" namespace views { // static MenuConfig* MenuConfig::Create() { MenuConfig* config = new MenuConfig(); ResourceBundle& rb = ResourceBundle::GetSharedInstance(); config->font = rb.GetFont(ResourceBundle::BaseFont); config->arrow_width = rb.GetBitmapNamed(IDR_MENU_ARROW)->width(); // Add 4 to force some padding between check and label. config->check_width = rb.GetBitmapNamed(IDR_MENU_CHECK)->width() + 4; config->check_height = rb.GetBitmapNamed(IDR_MENU_CHECK)->height(); return config; } } // namespace views
// 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 "views/controls/menu/menu_config.h" #include "grit/app_resources.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/resource/resource_bundle.h" namespace views { // static MenuConfig* MenuConfig::Create() { MenuConfig* config = new MenuConfig(); ResourceBundle& rb = ResourceBundle::GetSharedInstance(); #if defined(TOUCH_UI) config->font = rb.GetFont(ResourceBundle::LargeFont); #else config->font = rb.GetFont(ResourceBundle::BaseFont); #endif config->arrow_width = rb.GetBitmapNamed(IDR_MENU_ARROW)->width(); // Add 4 to force some padding between check and label. config->check_width = rb.GetBitmapNamed(IDR_MENU_CHECK)->width() + 4; config->check_height = rb.GetBitmapNamed(IDR_MENU_CHECK)->height(); return config; } } // namespace views
Make hermitianizer move the data to the left half of the imagef.
#include "herm_padded.h" #ifdef __FULL_HERM #define __(a) a #else #define __(a) #endif // Very simple. Only for even sizes. void herm_padded_inplace(complexd * data, int size, int pitch){ int pad = pitch - size // the same as (size-1)*(pitch+1) , dataend = size * pitch - pad - 1; ; complexd * pv0 = data , * pv1 = data + dataend; ; // An extra complexity due to a padding of the data for (int i = 0; i < size / 2; i++) { for (int j = 0; j < size; j++) { __(complexd tmp;) __(tmp = *pv0;) *pv0 += conj(*pv1); __(*pv1 += conj(tmp);) pv0++; pv1--; } pv0 += pad; pv1 -= pad; } }
#include "herm_padded.h" #ifndef MOVE_TO_TOP // Very simple. Only for even sizes. void herm_padded_inplace(complexd * data, int size, int pitch){ int pad = pitch - size // the same as (size-1)*(pitch+1) , dataend = size * pitch - pad - 1 , jmp = pad + size / 2 ; complexd * pv0 = data , * pv1 = data + dataend; ; // An extra complexity due to a padding of the data for (int i = 0; i < size; i++) { for (int j = 0; j < size / 2; j++) { *pv0 += conj(*pv1); pv0++; pv1--; } pv0 += jmp; pv1 -= jmp; } } #else // Very simple. Only for even sizes. void herm_padded_inplace(complexd * data, int size, int pitch){ int pad = pitch - size // the same as (size-1)*(pitch+1) , dataend = size * pitch - pad - 1; ; complexd * pv0 = data , * pv1 = data + dataend; ; // An extra complexity due to a padding of the data for (int i = 0; i < size / 2; i++) { for (int j = 0; j < size; j++) { *pv0 += conj(*pv1); pv0++; pv1--; } pv0 += pad; pv1 -= pad; } } #endif
Improve DP solution for Problem 32 Longest Valid Parentheses
#include "LongestValidParentheses.hpp" #include <stack> #include <vector> #include <algorithm> using namespace std; int LongestValidParentheses::longestValidParentheses(string s) { if (s.size() < 2) return 0; vector<int> dp(s.size(), 0); for (int i = 1; i < s.size(); i++) { if (s[i] == '(') dp[i] = 0; else { // s[i] = ')' int j = i - dp[i - 1]; if (j - 1 >= 0 && s[j - 1] == '(') dp[i] = (j - 2 >= 0) ? dp[i - 1] + dp[j - 2] + 2 : dp[i - 1] + 2; else dp[i] = 0; } } return *(max_element(dp.begin(), dp.end())); }
#include "LongestValidParentheses.hpp" #include <stack> #include <vector> #include <algorithm> using namespace std; int LongestValidParentheses::longestValidParentheses(string s) { if (s.size() < 2) return 0; vector<int> dp(s.size(), 0); int ret = 0; for (int i = 1; i < s.size(); i++) { if (s[i] == '(') continue; if (s[i - 1] == '(') { dp[i] = 2; if (i - 2 >= 0) dp[i] += dp[i - 2]; } else { int jump = dp[i - 1]; if (i - jump - 1 >= 0 && s[i - jump - 1] == '(') { dp[i] = jump + 2; if (i - jump - 2 >= 0) dp[i] += dp[i - jump - 2]; } } ret = (dp[i] > ret) ? dp[i] : ret; } return ret; }
Read the text file using QTextStream so that it is encoding-aware
#include "textfile.h" #include <QFile> TextFile::TextFile(QObject *parent) : QObject(parent), mValid(false) { } QString TextFile::text() const { return mText; } QString TextFile::source() const { return mSource; } void TextFile::setSource(const QString &file) { mValid = false; mSource = file; QFile f(file); if (!f.open(QIODevice::ReadOnly)) { return; } mText = f.readAll(); mValid = !mText.isEmpty(); emit sourceChanged(); emit textChanged(); emit validChanged(); }
#include "textfile.h" #include <QFile> #include <QTextStream> TextFile::TextFile(QObject *parent) : QObject(parent), mValid(false) { } QString TextFile::text() const { return mText; } QString TextFile::source() const { return mSource; } void TextFile::setSource(const QString &file) { mValid = false; mSource = file; QFile f(file); if (!f.open(QIODevice::ReadOnly)) { return; } QTextStream stream(&f); mText = stream.readAll(); mValid = !mText.isEmpty(); emit sourceChanged(); emit textChanged(); emit validChanged(); }
Add verbose flag to WerkVersion to show operating system name
/* * Copyright (c) 2015-2018 Agalmic Ventures LLC (www.agalmicventures.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include <iostream> #include "Werk/Version.hpp" int main(int, char **) { std::cout << werk::getVersion() << std::endl; return 0; }
/* * Copyright (c) 2015-2018 Agalmic Ventures LLC (www.agalmicventures.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include <iostream> #include "Werk/OS/OS.hpp" #include "Werk/Version.hpp" int main(int argc, char **argv) { std::cout << werk::getVersion(); if (argc > 1 && std::string(argv[1]) == "-v") { std::cout << " (" << werk::getOperatingSystemName() << ")"; } std::cout << std::endl; return 0; }
Return exit code based on test result
#include <iostream> #include <ccspec.h> using std::cout; using ccspec::core::formatters::DocumentationFormatter; using ccspec::core::ExampleGroup; using ccspec::core::Reporter; namespace spec { namespace matchers { extern ExampleGroup* eq_spec; } // namespace matchers } // namespace spec int main() { using namespace spec; DocumentationFormatter formatter(cout); Reporter reporter(&formatter); matchers::eq_spec->run(reporter); delete matchers::eq_spec; return 1; }
#include <iostream> #include <ccspec.h> using std::cout; using ccspec::core::formatters::DocumentationFormatter; using ccspec::core::ExampleGroup; using ccspec::core::Reporter; namespace spec { namespace matchers { extern ExampleGroup* eq_spec; } // namespace matchers } // namespace spec int main() { using namespace spec; DocumentationFormatter formatter(cout); Reporter reporter(&formatter); bool succeeded = matchers::eq_spec->run(reporter); delete matchers::eq_spec; return !succeeded; }
Remove basic test from linear memory test
#include <Ab/Config.hpp> #include <Ab/LinearMemory.hpp> #include <Ab/Test/BasicTest.hpp> #include <gtest/gtest.h> namespace Ab::Test { class LinearMemoryTest : public BasicTest {}; TEST_F(LinearMemoryTest, init_and_kill) { LinearMemory m; } TEST_F(LinearMemoryTest, grow_three_times) { LinearMemory m; for (std::size_t i = 0; i < 3; i++) { m.grow(); } } } // namespace Ab::Test
#include <Ab/Config.hpp> #include <Ab/LinearMemory.hpp> #include <gtest/gtest.h> namespace Ab::Test { TEST(LinearMemoryTest, init_and_kill) { LinearMemory m; } TEST(LinearMemoryTest, grow_three_times) { LinearMemory m; for (std::size_t i = 0; i < 3; i++) { m.grow(); } } } // namespace Ab::Test
Disable hmac_sha1 test when SSL is not enabled
/* * Copyright (C) 2009, 2010, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ #include <libport/base64.hh> #include <libport/hmac-sha1.hh> #include <libport/unit-test.hh> using libport::test_suite; #include <iostream> static void test() { std::string msg = "GET\n\n\nTue, 27 Mar 2007 19:36:42 +0000\n" "/johnsmith/photos/puppy.jpg"; std::string key = "uV3F3YluFJax1cknvbcGwgjvx4QpvB+leU8dUj2o"; BOOST_CHECK_EQUAL(libport::base64(libport::hmac_sha1(msg, key)), "xXjDGYUmKxnwqr5KXNPGldn5LbA="); } test_suite* init_test_suite() { test_suite* suite = BOOST_TEST_SUITE("libport::hmac_sha1 test suite"); suite->add(BOOST_TEST_CASE(test)); return suite; }
/* * Copyright (C) 2009, 2010, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ #include <libport/config.h> #include <libport/base64.hh> #include <libport/hmac-sha1.hh> #include <libport/unit-test.hh> using libport::test_suite; #include <iostream> static void test() { #ifdef LIBPORT_ENABLE_SSL std::string msg = "GET\n\n\nTue, 27 Mar 2007 19:36:42 +0000\n" "/johnsmith/photos/puppy.jpg"; std::string key = "uV3F3YluFJax1cknvbcGwgjvx4QpvB+leU8dUj2o"; BOOST_CHECK_EQUAL(libport::base64(libport::hmac_sha1(msg, key)), "xXjDGYUmKxnwqr5KXNPGldn5LbA="); #endif } test_suite* init_test_suite() { test_suite* suite = BOOST_TEST_SUITE("libport::hmac_sha1 test suite"); suite->add(BOOST_TEST_CASE(test)); return suite; }
Use _msize instead of malloc_usable_size on Windows
#include "memory_manager.hpp" #include <malloc.h> #include <new> void CustomMemoryManager::Start() { this->numberOfAllocations = 0; this->peakAllocatedBytes = 0; this->allocatedBytes = 0; this->totalAllocatedBytes = 0; } void CustomMemoryManager::Stop(Result *result) { result->num_allocs = this->numberOfAllocations; result->max_bytes_used = this->peakAllocatedBytes; result->total_allocated_bytes = this->totalAllocatedBytes; } void CustomMemoryManager::trackMemory(size_t size) { auto int_size = static_cast<int64_t>(size); this->numberOfAllocations += 1; this->allocatedBytes += int_size; this->totalAllocatedBytes += int_size; this->peakAllocatedBytes = std::max(this->peakAllocatedBytes, this->allocatedBytes); } void CustomMemoryManager::untrackMemory(size_t size) { auto int_size = static_cast<int64_t>(size); this->allocatedBytes -= int_size; } void CustomMemoryManager::untrackMemory(void *ptr) { untrackMemory(malloc_usable_size(ptr)); } CustomMemoryManager &getMemoryManager() { static CustomMemoryManager manager{}; return manager; }
#include "memory_manager.hpp" #include <malloc.h> #include <new> void CustomMemoryManager::Start() { this->numberOfAllocations = 0; this->peakAllocatedBytes = 0; this->allocatedBytes = 0; this->totalAllocatedBytes = 0; } void CustomMemoryManager::Stop(Result *result) { result->num_allocs = this->numberOfAllocations; result->max_bytes_used = this->peakAllocatedBytes; result->total_allocated_bytes = this->totalAllocatedBytes; } void CustomMemoryManager::trackMemory(size_t size) { auto int_size = static_cast<int64_t>(size); this->numberOfAllocations += 1; this->allocatedBytes += int_size; this->totalAllocatedBytes += int_size; this->peakAllocatedBytes = std::max(this->peakAllocatedBytes, this->allocatedBytes); } void CustomMemoryManager::untrackMemory(size_t size) { auto int_size = static_cast<int64_t>(size); this->allocatedBytes -= int_size; } void CustomMemoryManager::untrackMemory(void *ptr) { const auto blockSize = std::invoke([ptr] { #ifdef _WIN32 return _msize(ptr); #else return malloc_usable_size(ptr); #endif }); untrackMemory(blockSize); } CustomMemoryManager &getMemoryManager() { static CustomMemoryManager manager{}; return manager; }
Format CValidationState properly in all cases
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Bitcoin Core developers // Copyright (c) 2021 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "util/validation.h" #include "consensus/validation.h" #include "tinyformat.h" /** Convert CValidationState to a human-readable message for logging */ std::string FormatStateMessage(const CValidationState& state) { return strprintf("%s%s (code %i)", state.GetRejectReason(), state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage(), state.GetRejectCode()); } const std::string strMessageMagic = "DarkNet Signed Message:\n";
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Bitcoin Core developers // Copyright (c) 2021 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "util/validation.h" #include "consensus/validation.h" #include "tinyformat.h" /** Convert CValidationState to a human-readable message for logging */ std::string FormatStateMessage(const CValidationState& state) { if (state.IsValid()) { return "Valid"; } return strprintf("%s%s (code %i)", state.GetRejectReason(), state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage(), state.GetRejectCode()); } const std::string strMessageMagic = "DarkNet Signed Message:\n";
Fix ADC track and hold formula
#include "board.h" #include <aery32/all.h> using namespace aery; #define ADC_PINMASK_ALLCHAN (0xff << 21) int main(void) { int errno; uint16_t result; /* conversion result in bits */ double volt; /* conversion in volts */ init_board(); gpio_init_pin(LED, GPIO_OUTPUT); gpio_init_pins(porta, ADC_PINMASK_ALLCHAN, GPIO_FUNCTION_A); errno = adc_init( 7, /* prescal, adclk = pba_clk / (2 * (prescal+1)) */ true, /* hires, 10-bit (false would be 8-bit) */ 0, /* shtim, sample and hold time = (shtim + 1) / adclk */ 0 /* startup, startup time = (startup + 1) * 8 / adclk */ ); if (errno != -1) adc_enable(1 << 3); /* enables the channel 3 */ /* init done, turn the LED on */ gpio_set_pin_high(LED); for(;;) { adc_start_cnv(); while (adc_isbusy(1 << 3)); result = adc_read_cnv(3); volt = cnv2volt(result); } return 0; }
#include "board.h" #include <aery32/all.h> using namespace aery; #define ADC_PINMASK_ALLCHAN (0xff << 21) int main(void) { int errno; uint16_t result; /* conversion result in bits */ double volt; /* conversion in volts */ init_board(); gpio_init_pin(LED, GPIO_OUTPUT); gpio_init_pins(porta, ADC_PINMASK_ALLCHAN, GPIO_FUNCTION_A); errno = adc_init( 7, /* prescal, adclk = pba_clk / (2 * (prescal+1)) */ true, /* hires, 10-bit (false would be 8-bit) */ 0, /* shtim, sample and hold time = (shtim + 3) / adclk */ 0 /* startup, startup time = (startup + 1) * 8 / adclk */ ); if (errno != -1) adc_enable(1 << 3); /* enables the channel 3 */ /* init done, turn the LED on */ gpio_set_pin_high(LED); for(;;) { adc_start_cnv(); while (adc_isbusy(1 << 3)); result = adc_read_cnv(3); volt = cnv2volt(result); } return 0; }
Remove some unsed locks. InitModule is not called concurrently anymore.
// Copyright (c) 2012-2013, the scalloc Project Authors. All rights reserved. // Please see the AUTHORS file for details. Use of this source code is governed // by a BSD license that can be found in the LICENSE file. #include "distributed_queue.h" #include "common.h" #include "runtime_vars.h" #include "spinlock-inl.h" namespace { // Lock guarding initializing the DQ module. cache_aligned SpinLock g_init_lock(LINKER_INITIALIZED); // Lock guarding the state allocator. cache_aligned SpinLock g_state_lock(LINKER_INITIALIZED); // Flag inidicating whether the DQ module has been initialized. bool g_dq_module_init; } // namespace scalloc::PageHeapAllocator<Stack, 64> DistributedQueue::backend_allocator_; scalloc::PageHeapAllocator<DistributedQueue::State, 64> DistributedQueue::state_allocator_; __thread DistributedQueue::State* DistributedQueue::state_; void DistributedQueue::InitModule() { SpinLockHolder holder(&g_init_lock); CompilerBarrier(); if (!g_dq_module_init) { backend_allocator_.Init(RuntimeVars::SystemPageSize()); state_allocator_.Init(RuntimeVars::SystemPageSize()); g_dq_module_init = true; } } void DistributedQueue::Init(size_t p) { p_ = p; for (size_t i = 0; i < p_; i++) { backends_[i] = backend_allocator_.New(); backends_[i]->Init(); } } DistributedQueue::State* DistributedQueue::NewState() { return state_allocator_.New(); }
// Copyright (c) 2012-2013, the scalloc Project Authors. All rights reserved. // Please see the AUTHORS file for details. Use of this source code is governed // by a BSD license that can be found in the LICENSE file. #include "distributed_queue.h" #include "common.h" #include "runtime_vars.h" #include "spinlock-inl.h" scalloc::PageHeapAllocator<Stack, 64> DistributedQueue::backend_allocator_; scalloc::PageHeapAllocator<DistributedQueue::State, 64> DistributedQueue::state_allocator_; __thread DistributedQueue::State* DistributedQueue::state_; void DistributedQueue::InitModule() { backend_allocator_.Init(RuntimeVars::SystemPageSize()); state_allocator_.Init(RuntimeVars::SystemPageSize()); } void DistributedQueue::Init(size_t p) { p_ = p; for (size_t i = 0; i < p_; i++) { backends_[i] = backend_allocator_.New(); backends_[i]->Init(); } } DistributedQueue::State* DistributedQueue::NewState() { return state_allocator_.New(); }
Enable pre-connect via {mouse,gesture}-event triggers to limited users controlled by Finch.
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/net/prescient_networking_dispatcher.h" #include "chrome/common/render_messages.h" #include "content/public/renderer/render_thread.h" using WebKit::WebPrescientNetworking; PrescientNetworkingDispatcher::~PrescientNetworkingDispatcher() { } void PrescientNetworkingDispatcher::preconnect( const WebKit::WebURL& url, WebKit::WebPreconnectMotivation motivation) { // FIXME(kouhei) actual pre-connecting is currently disabled. // This should shortly be enabled via Finch field trials in upcoming patch. // content::RenderThread::Get()->Send(new ChromeViewHostMsg_Preconnect(url)); }
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/net/prescient_networking_dispatcher.h" #include "base/metrics/field_trial.h" #include "chrome/common/render_messages.h" #include "content/public/renderer/render_thread.h" using WebKit::WebPrescientNetworking; const char kMouseEventPreconnectFieldTrialName[] = "MouseEventPreconnect"; const char kMouseEventPreconnectFieldTrialMouseDownGroup[] = "MouseDown"; const char kMouseEventPreconnectFieldTrialMouseOverGroup[] = "MouseOver"; const char kMouseEventPreconnectFieldTrialTapUnconfirmedGroup[] = "TapUnconfirmed"; const char kMouseEventPreconnectFieldTrialTapDownGroup[] = "TapDown"; namespace { // Returns true if preconnect is enabled for given motivation. // The preconnect via {mouse,gesture} event is enabled for limited userbase // for Finch field trial. bool isPreconnectEnabledForMotivation( WebKit::WebPreconnectMotivation motivation) { std::string group = base::FieldTrialList::FindFullName(kMouseEventPreconnectFieldTrialName); switch (motivation) { case WebKit::WebPreconnectMotivationLinkMouseDown: return group == kMouseEventPreconnectFieldTrialMouseDownGroup; case WebKit::WebPreconnectMotivationLinkMouseOver: return group == kMouseEventPreconnectFieldTrialMouseOverGroup; case WebKit::WebPreconnectMotivationLinkTapUnconfirmed: return group == kMouseEventPreconnectFieldTrialTapUnconfirmedGroup; case WebKit::WebPreconnectMotivationLinkTapDown: return group == kMouseEventPreconnectFieldTrialTapDownGroup; default: return false; } } } // namespace PrescientNetworkingDispatcher::~PrescientNetworkingDispatcher() { } void PrescientNetworkingDispatcher::preconnect( const WebKit::WebURL& url, WebKit::WebPreconnectMotivation motivation) { if (isPreconnectEnabledForMotivation(motivation)) content::RenderThread::Get()->Send(new ChromeViewHostMsg_Preconnect(url)); }
Include stdlib, since it seems to be necessary,
#include "Manager.h" #include "Value.h" #include "api.h" Value * newValue(uint8_t valueType, uint64_t valueId) { Value * tmp = (Value *)malloc(sizeof(Value)); *tmp = (struct Value){0}; tmp->valueType = valueType; tmp->valueId = valueId; return tmp; } void freeValue(Value * value) { free(value); }
#include <stdlib.h> #include "Manager.h" #include "Value.h" #include "api.h" Value * newValue(uint8_t valueType, uint64_t valueId) { Value * tmp = (Value *)malloc(sizeof(Value)); *tmp = (struct Value){0}; tmp->valueType = valueType; tmp->valueId = valueId; return tmp; } void freeValue(Value * value) { free(value); }
Use std::scoped_lock only for C++17 and newer
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // On Windows Clang bugs out when both __declspec and __attribute__ are present, // the processing goes awry preventing the definition of the types. // XFAIL: LIBCXX-WINDOWS-FIXME // UNSUPPORTED: libcpp-has-no-threads // REQUIRES: thread-safety // <mutex> // MODULES_DEFINES: _LIBCPP_ENABLE_THREAD_SAFETY_ANNOTATIONS #define _LIBCPP_ENABLE_THREAD_SAFETY_ANNOTATIONS #include <mutex> std::mutex m; int foo __attribute__((guarded_by(m))); static void scoped() { std::scoped_lock<std::mutex> lock(m); foo++; } int main() { scoped(); std::lock_guard<std::mutex> lock(m); foo++; }
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // On Windows Clang bugs out when both __declspec and __attribute__ are present, // the processing goes awry preventing the definition of the types. // XFAIL: LIBCXX-WINDOWS-FIXME // UNSUPPORTED: libcpp-has-no-threads // REQUIRES: thread-safety // <mutex> // MODULES_DEFINES: _LIBCPP_ENABLE_THREAD_SAFETY_ANNOTATIONS #define _LIBCPP_ENABLE_THREAD_SAFETY_ANNOTATIONS #include <mutex> std::mutex m; int foo __attribute__((guarded_by(m))); static void scoped() { #if __cplusplus >= 201703L std::scoped_lock<std::mutex> lock(m); foo++; #endif } int main() { scoped(); std::lock_guard<std::mutex> lock(m); foo++; }
Add headers for not caching JSON views on the client
/* * Copyright 2010 MQWeb - Franky Braem * * Licensed under the EUPL, Version 1.1 or – as soon they * will be approved by the European Commission - subsequent * versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the * Licence. * You may obtain a copy of the Licence at: * * http://joinup.ec.europa.eu/software/page/eupl * * Unless required by applicable law or agreed to in * writing, software distributed under the Licence is * distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. * See the Licence for the specific language governing * permissions and limitations under the Licence. */ #include "MQ/Web/JSONView.h" namespace MQ { namespace Web { JSONView::JSONView() : View() { } JSONView::~JSONView() { } void JSONView::initializeResponse(Poco::Net::HTTPServerResponse& response) { response.setChunkedTransferEncoding(true); response.setContentType("application/json"); } bool JSONView::render(Poco::JSON::Object::Ptr data, std::ostream& os) { data->stringify(os); os.flush(); return true; } }} // Namespace MQ::Web
/* * Copyright 2010 MQWeb - Franky Braem * * Licensed under the EUPL, Version 1.1 or – as soon they * will be approved by the European Commission - subsequent * versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the * Licence. * You may obtain a copy of the Licence at: * * http://joinup.ec.europa.eu/software/page/eupl * * Unless required by applicable law or agreed to in * writing, software distributed under the Licence is * distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. * See the Licence for the specific language governing * permissions and limitations under the Licence. */ #include "MQ/Web/JSONView.h" namespace MQ { namespace Web { JSONView::JSONView() : View() { } JSONView::~JSONView() { } void JSONView::initializeResponse(Poco::Net::HTTPServerResponse& response) { response.setChunkedTransferEncoding(true); response.setContentType("application/json"); response.set("Cache-Controle", "no-cache,no-store,must-revalidate"); // HTTP 1.1 response.set("Pragma", "no-cache"); // HTTP 1.0 response.set("Expires", "0"); // Proxies } bool JSONView::render(Poco::JSON::Object::Ptr data, std::ostream& os) { data->stringify(os); os.flush(); return true; } }} // Namespace MQ::Web
Remove using namespace to silence linter
#include <iostream> #include "ccspec.h" using std::cout; using ccspec::core::formatters::DocumentationFormatter; using ccspec::core::ExampleGroup; using ccspec::core::Reporter; namespace spec { namespace matchers { extern ExampleGroup* eq_spec; } // namespace matchers } // namespace spec int main() { using namespace spec; DocumentationFormatter formatter(cout); Reporter reporter(&formatter); bool succeeded = matchers::eq_spec->run(reporter); delete matchers::eq_spec; return !succeeded; }
#include <iostream> #include "ccspec.h" using std::cout; using ccspec::core::formatters::DocumentationFormatter; using ccspec::core::ExampleGroup; using ccspec::core::Reporter; namespace spec { namespace matchers { extern ExampleGroup* eq_spec; } // namespace matchers } // namespace spec int main() { DocumentationFormatter formatter(cout); Reporter reporter(&formatter); bool succeeded = spec::matchers::eq_spec->run(reporter); delete spec::matchers::eq_spec; return !succeeded; }
Fix this test: llvm-gcc-4.2 optimizes almost everything away, resulting in zero matches, while llvm-gcc-4.1 manages to remove one pointless selector changing the number of matches.
// RUN: %llvmgxx %s -S -emit-llvm -O2 -o - | \ // RUN: ignore grep {eh\.selector.*One.*Two.*Three.*Four.*Five.*Six.*null} | \ // RUN: wc -l | grep {\[02\]} extern void X(void); struct One {}; struct Two {}; struct Three {}; struct Four {}; struct Five {}; struct Six {}; static void A(void) throw () { X(); } static void B(void) throw (Two) { try { A(); } catch (One) {} } static void C(void) throw (Six, Five) { try { B(); } catch (Three) {} catch (Four) {} } int main () { try { C(); } catch (...) {} }
// RUN: %llvmgxx %s -S -O2 -o - | \ // RUN: ignore grep {eh\.selector.*One.*Two.*Three.*Four.*Five.*Six.*null} | \ // RUN: wc -l | grep {\[01\]} extern void X(void); struct One {}; struct Two {}; struct Three {}; struct Four {}; struct Five {}; struct Six {}; static void A(void) throw () { X(); } static void B(void) throw (Two) { try { A(); } catch (One) {} } static void C(void) throw (Six, Five) { try { B(); } catch (Three) {} catch (Four) {} } int main () { try { C(); } catch (...) {} }
Add missing triple to CodeGen test.
// RUN: %clang_cc1 -std=c++1y -emit-llvm %s -o - | FileCheck %s // CHECK: @x = global {{.*}} zeroinitializer // CHECK: define {{.*}} @_Z1fv inline auto f() { int n = 0; // CHECK: load i32 // CHECK: store i32 // CHECK: ret return [=] () mutable { return ++n; }; } auto x = f(); template<typename T> auto *g(T t) { return t; } template<typename T> decltype(auto) h(T t) { return t; } // CHECK: define {{.*}} @_Z1zv void z() { // CHECK: call {{.*}} @_Z1gIPZ1fvEUlvE_EPDaT_( // CHECK: call {{.*}} @_Z1hIPZ1fvEUlvE_EDcT_( g(&x); h(&x); } auto i() { return [] {}; } // CHECK: define {{.*}} @_Z1jv auto j() { // CHECK: call {{.*}} @"_Z1hIZ1ivE3$_0EDcT_"() h(i()); }
// RUN: %clang_cc1 -std=c++1y -triple x86_64-linux-gnu -emit-llvm %s -o - | FileCheck %s // CHECK: @x = global {{.*}} zeroinitializer // CHECK: define {{.*}} @_Z1fv inline auto f() { int n = 0; // CHECK: load i32 // CHECK: store i32 // CHECK: ret return [=] () mutable { return ++n; }; } auto x = f(); template<typename T> auto *g(T t) { return t; } template<typename T> decltype(auto) h(T t) { return t; } // CHECK: define {{.*}} @_Z1zv void z() { // CHECK: call {{.*}} @_Z1gIPZ1fvEUlvE_EPDaT_( // CHECK: call {{.*}} @_Z1hIPZ1fvEUlvE_EDcT_( g(&x); h(&x); } auto i() { return [] {}; } // CHECK: define {{.*}} @_Z1jv auto j() { // CHECK: call {{.*}} @"_Z1hIZ1ivE3$_0EDcT_"() h(i()); }
Use std::abs to ease Jenkins warning
#include <gtest/gtest.h> #include <sm/timing/NsecTimeUtilities.hpp> TEST( NsetTimeTestSuite, testChronoConversion ) { std::chrono::system_clock::time_point tp1 = std::chrono::system_clock::now(); sm::timing::NsecTime ns1 = sm::timing::chronoToNsec( tp1 ); std::chrono::system_clock::time_point tp2 = sm::timing::nsecToChrono( ns1 ); ASSERT_TRUE(tp1 == tp2); } TEST( NsetTimeTestSuite, testSecConversion ) { sm::timing::NsecTime ns1 = sm::timing::nsecNow(); double s2 = sm::timing::nsecToSec(ns1); sm::timing::NsecTime ns2 = sm::timing::secToNsec(s2); ASSERT_LT(abs(ns1-ns2), 1000000); }
#include <cstdlib> #include <gtest/gtest.h> #include <sm/timing/NsecTimeUtilities.hpp> TEST( NsetTimeTestSuite, testChronoConversion ) { std::chrono::system_clock::time_point tp1 = std::chrono::system_clock::now(); sm::timing::NsecTime ns1 = sm::timing::chronoToNsec( tp1 ); std::chrono::system_clock::time_point tp2 = sm::timing::nsecToChrono( ns1 ); ASSERT_TRUE(tp1 == tp2); } TEST( NsetTimeTestSuite, testSecConversion ) { sm::timing::NsecTime ns1 = sm::timing::nsecNow(); double s2 = sm::timing::nsecToSec(ns1); sm::timing::NsecTime ns2 = sm::timing::secToNsec(s2); ASSERT_LT(std::abs(ns1-ns2), 1000000); }
Add Binary Search Tree in C++
#include <iostream> #include "binarysearchtree.h" int main() { BinarySearchTree<int> tree; tree.insert(0); tree.insert(4); tree.insert(3); tree.insert(2); tree.insert(1); if (tree.contains(1)) { std::cout << "Item found" << std::endl; } int max = tree.findMax(); int min = tree.findMin(); std::cout << "The maximum element: " << max << std::endl; std::cout << "The minimum element: " << min << std::endl; return 0; }
#include <iostream> #include "binarysearchtree.h" // test binary search tree int main() { BinarySearchTree<int> tree; tree.insert(0); tree.insert(4); tree.insert(3); tree.insert(2); tree.insert(1); if (tree.contains(1)) { std::cout << "Item found" << std::endl; } int max = tree.findMax(); int min = tree.findMin(); std::cout << "The maximum element: " << max << std::endl; std::cout << "The minimum element: " << min << std::endl; return 0; }
Update debug info test for schema change made to LLVM.
// RUN: %clang -g -S -emit-llvm %s -o - | FileCheck %s namespace A { #line 1 "foo.cpp" namespace B { int i; } } // CHECK: [[FILE:![0-9]*]] {{.*}}debug-info-namespace.cpp" // CHECK: [[VAR:![0-9]*]] = {{.*}}, metadata [[NS:![0-9]*]], metadata !"i", {{.*}} ; [ DW_TAG_variable ] [i] // CHECK: [[NS]] = {{.*}}, metadata [[FILE2:![0-9]*]], metadata [[CTXT:![0-9]*]], {{.*}} ; [ DW_TAG_namespace ] [B] [line 1] // CHECK: [[CTXT]] = {{.*}}, metadata [[FILE]], null, {{.*}} ; [ DW_TAG_namespace ] [A] [line 3] // CHECK: [[FILE2]]} ; [ DW_TAG_file_type ] [{{.*}}foo.cpp] // FIXME: It is confused on win32 to generate file entry when dosish filename is given. // REQUIRES: shell
// RUN: %clang -g -S -emit-llvm %s -o - | FileCheck %s namespace A { #line 1 "foo.cpp" namespace B { int i; } } // CHECK: [[FILE:![0-9]*]] {{.*}}debug-info-namespace.cpp" // CHECK: [[VAR:![0-9]*]] = {{.*}}, metadata [[NS:![0-9]*]], metadata !"i", {{.*}} ; [ DW_TAG_variable ] [i] // CHECK: [[NS]] = {{.*}}, metadata [[FILE2:![0-9]*]], null, metadata [[CTXT:![0-9]*]], {{.*}} ; [ DW_TAG_namespace ] [B] [line 1] // CHECK: [[CTXT]] = {{.*}}, metadata [[FILE]], null, null, {{.*}} ; [ DW_TAG_namespace ] [A] [line 3] // CHECK: {i32 {{[0-9]+}}, metadata [[FILE2]]{{.*}} ; [ DW_TAG_file_type ] [{{.*}}foo.cpp] // FIXME: It is confused on win32 to generate file entry when dosish filename is given. // REQUIRES: shell
Add placeholder value so listener node isn't null.
#include "Listener.hpp" using namespace Component; Listener::Listener(Entity* entity) : SuperComponent(entity) { } Json::Value Listener::Save() const { return Json::Value(); } void Listener::Load(const Json::Value& node) { }
#include "Listener.hpp" using namespace Component; Listener::Listener(Entity* entity) : SuperComponent(entity) { } Json::Value Listener::Save() const { Json::Value component; component["placeholderValue"] = ""; return component; } void Listener::Load(const Json::Value& node) { }
Allow passing either a directory name or a filename to the compiler.
#include <ostream> #include <boost/filesystem.hpp> #include <papyrus/parser/PapyrusParser.h> #include <papyrus/PapyrusScript.h> #include <pex/PexWriter.h> int main(int argc, char* argv[]) { if (argc != 2) { printf("Invoke like: caprica.exe myFile.psc"); } #ifdef NDEBUG try { #endif std::string file = argv[1]; auto parser = new caprica::papyrus::parser::PapyrusParser(file); auto a = parser->parseScript(); delete parser; auto ctx = new caprica::papyrus::PapyrusResolutionContext(); a->semantic(ctx); auto pex = a->buildPex(); delete ctx; delete a; std::ofstream strm(boost::filesystem::basename(file) + ".pex", std::ofstream::binary); caprica::pex::PexWriter wtr(strm); pex->write(wtr); delete pex; #ifdef NDEBUG } catch (std::runtime_error err) { printf("%s", err.what()); //getchar(); } #endif return 0; }
#include <ostream> #include <string> #include <boost/filesystem.hpp> #include <papyrus/parser/PapyrusParser.h> #include <papyrus/PapyrusScript.h> #include <pex/PexWriter.h> void compileScript(std::string filename) { auto parser = new caprica::papyrus::parser::PapyrusParser(filename); auto a = parser->parseScript(); delete parser; auto ctx = new caprica::papyrus::PapyrusResolutionContext(); a->semantic(ctx); auto pex = a->buildPex(); delete ctx; delete a; std::ofstream strm(boost::filesystem::basename(filename) + ".pex", std::ofstream::binary); caprica::pex::PexWriter wtr(strm); pex->write(wtr); delete pex; } int main(int argc, char* argv[]) { if (argc != 2) { printf("Invoke like: caprica.exe myFile.psc"); } #ifdef NDEBUG try { #endif std::string file = argv[1]; if (boost::filesystem::is_directory(file)) { boost::system::error_code ec; for (auto e : boost::filesystem::directory_iterator(file, ec)) { compileScript(e.path().string()); } } else { compileScript(file); } #ifdef NDEBUG } catch (std::runtime_error err) { printf("%s", err.what()); getchar(); } #endif return 0; }
Implement search result using regex_iterator.
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "stdafx.h" #include <regex> #include "search_regex.h" RegexSearch::RegexSearch() : pattern_(NULL), patternLen_(0), regex_(nullptr) { } RegexSearch::~RegexSearch() { delete regex_; } bool RegexSearch::PreProcess(const char *pattern, int patternLen, SearchOptions options) { auto flags = std::regex::ECMAScript; if ((options & kMatchCase) == 0) { flags = flags | std::regex::icase; } regex_ = new std::regex(pattern, patternLen, flags); pattern_ = pattern; patternLen_ = patternLen; return true; } void RegexSearch::Search(const char *text, int textLen, Callback matchFound) { #if 0 const char* first = text; const char* last = text + textLen; std::cmatch match; bool result = std::regex_search(first, last, match, *regex_, std::regex_constants::match_default); if (!result) { return SearchResult(); } auto position = match.position(); auto length = match.length(); // Special case of regex that match empty sequence (e.g. [a-z]*). // We assume this is a "no result" to avoid infinite loops. if (position == 0 && length == 0) { return SearchResult(); } return SearchResult(first + position, length); #endif }
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "stdafx.h" #include <regex> #include "search_regex.h" RegexSearch::RegexSearch() : pattern_(NULL), patternLen_(0), regex_(nullptr) { } RegexSearch::~RegexSearch() { delete regex_; } bool RegexSearch::PreProcess(const char *pattern, int patternLen, SearchOptions options) { auto flags = std::regex::ECMAScript; if ((options & kMatchCase) == 0) { flags = flags | std::regex::icase; } regex_ = new std::regex(pattern, patternLen, flags); pattern_ = pattern; patternLen_ = patternLen; return true; } void RegexSearch::Search(const char *text, int textLen, Callback matchFound) { std::cregex_iterator end; std::cregex_iterator it(text, text + textLen, *regex_); while (it != end) { if (!matchFound(text + (*it).position(), (*it).length())) break; ++it; } }
Improve constexpr tests for std::any
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03, c++11, c++14 // <any> // any() noexcept; #include <any> #include <type_traits> #include <cassert> #include "test_macros.h" #include "any_helpers.h" #include "count_new.hpp" #if TEST_HAS_BUILTIN_IDENTIFIER(__has_constant_initializer) // std::any must have a constexpr default constructor, but it's a non-literal // type so we can't create a constexpr variable. This tests that we actually // get 'constant initialization'. std::any a; static_assert(__has_constant_initializer(a), "any must be constant initializable"); #endif int main() { using std::any; { static_assert( std::is_nothrow_default_constructible<any>::value , "Must be default constructible" ); } { DisableAllocationGuard g; ((void)g); any const a; assertEmpty(a); } }
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03, c++11, c++14 // <any> // any() noexcept; #include <any> #include <type_traits> #include <cassert> #include "test_macros.h" #include "any_helpers.h" #include "count_new.hpp" int main() { using std::any; { static_assert( std::is_nothrow_default_constructible<any>::value , "Must be default constructible" ); } { struct TestConstexpr : public std::any { constexpr TestConstexpr() : std::any() {} }; #ifdef _LIBCPP_SAFE_STATIC _LIBCPP_SAFE_STATIC static std::any a; ((void)a); #endif } { DisableAllocationGuard g; ((void)g); any const a; assertEmpty(a); } }
Add call to conversion fn
// Copyright 2015 Matt Heard // http://mattheard.net // matt@mattheard.net // @mattheard #include <opencv2/opencv.hpp> #include <iostream> #include <string> int main(int argc, char **argv) { using std::string; const int expectedNumArgs = 2; if (argc != expectedNumArgs) { const string cmdName = "ConvertToGrey"; const string argsDesc = " <Image_Path>"; std::cout << "Usage: " << cmdName << argsDesc << std::endl; return -1; } const string filename = argv[1]; const cv::Mat img = cv::imread(filename); if (!img.data) { const string err = "No image data"; std::cerr << err << std::cout; return -1; } return 0; }
// Copyright 2015 Matt Heard // http://mattheard.net // matt@mattheard.net // @mattheard #include <opencv2/opencv.hpp> #include <iostream> #include <string> using cv::Mat; // TODO(mattheard): Implement me Mat convertToGrey(const Mat &src) { return Mat(); } int main(int argc, char **argv) { using std::string; const int expectedNumArgs = 2; if (argc != expectedNumArgs) { const string cmdName = "ConvertToGrey"; const string argsDesc = " <Image_Path>"; std::cout << "Usage: " << cmdName << argsDesc << std::endl; return -1; } const string filename = argv[1]; const Mat srcImg = cv::imread(filename); if (!srcImg.data) { const string err = "No image data"; std::cerr << err << std::cout; return -1; } const Mat greyImg = convertToGrey(srcImg); return 0; }
Disable the Bookmarks ExtensionAPITest becuase it is 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 "chrome/browser/extensions/extension_apitest.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Bookmarks) { // TODO(erikkay) no initial state for this test. ASSERT_TRUE(RunExtensionTest("bookmarks")) << message_; }
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" // TODO(brettw) bug 19866: this test is disabled because it is flaky. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Bookmarks) { // TODO(erikkay) no initial state for this test. ASSERT_TRUE(RunExtensionTest("bookmarks")) << message_; }
Use the newer v3 api for boost filesystem
#ifdef WIN32 #include "anh/plugin/platform/win32_library.h" #include <exception> #include <sstream> #include <Windows.h> #include <boost/filesystem.hpp> using namespace anh::plugin; using namespace boost::filesystem; using namespace platform; using namespace std; shared_ptr<Win32Library> Win32Library::Load(std::string library) { path library_path(library); HMODULE handle = ::LoadLibrary(library_path.native_file_string().c_str()); if (handle == NULL) { DWORD error_code = ::GetLastError(); stringstream ss; ss << "LoadLibrary(" << library << ") Failed. errorCode: " << error_code; throw runtime_error(ss.str()); } return shared_ptr<Win32Library>(new Win32Library(handle)); } Win32Library::Win32Library(HMODULE handle) : handle_(handle) , exit_func_(0) {} Win32Library::~Win32Library() { if (handle_) { ::FreeLibrary(handle_); } } void * Win32Library::GetSymbol(const string& symbol) { if (!handle_) { return nullptr; } return ::GetProcAddress(handle_, symbol.c_str()); } #endif // WIN32
#ifdef WIN32 #include "anh/plugin/platform/win32_library.h" #include <exception> #include <sstream> #include <Windows.h> #include <boost/filesystem.hpp> using namespace anh::plugin; using namespace boost::filesystem; using namespace platform; using namespace std; shared_ptr<Win32Library> Win32Library::Load(std::string library) { path library_path(library); HMODULE handle = ::LoadLibrary(library_path.string().c_str()); if (handle == NULL) { DWORD error_code = ::GetLastError(); stringstream ss; ss << "LoadLibrary(" << library << ") Failed. errorCode: " << error_code; throw runtime_error(ss.str()); } return shared_ptr<Win32Library>(new Win32Library(handle)); } Win32Library::Win32Library(HMODULE handle) : handle_(handle) , exit_func_(0) {} Win32Library::~Win32Library() { if (handle_) { ::FreeLibrary(handle_); } } void * Win32Library::GetSymbol(const string& symbol) { if (!handle_) { return nullptr; } return ::GetProcAddress(handle_, symbol.c_str()); } #endif // WIN32
Update plugin requirements for 1.2.0
// // kern_start.cpp // AppleALC // // Copyright © 2016-2017 vit9696. All rights reserved. // #include <Headers/plugin_start.hpp> #include <Headers/kern_api.hpp> #include "kern_alc.hpp" static AlcEnabler alc; static const char *bootargOff[] { "-alcoff", "-x" }; static const char *bootargDebug[] { "-alcdbg" }; static const char *bootargBeta[] { "-alcbeta" }; PluginConfiguration ADDPR(config) { xStringify(PRODUCT_NAME), parseModuleVersion(xStringify(MODULE_VERSION)), bootargOff, arrsize(bootargOff), bootargDebug, arrsize(bootargDebug), bootargBeta, arrsize(bootargBeta), KernelVersion::MountainLion, KernelVersion::HighSierra, []() { alc.init(); } };
// // kern_start.cpp // AppleALC // // Copyright © 2016-2017 vit9696. All rights reserved. // #include <Headers/plugin_start.hpp> #include <Headers/kern_api.hpp> #include "kern_alc.hpp" static AlcEnabler alc; static const char *bootargOff[] { "-alcoff" }; static const char *bootargDebug[] { "-alcdbg" }; static const char *bootargBeta[] { "-alcbeta" }; PluginConfiguration ADDPR(config) { xStringify(PRODUCT_NAME), parseModuleVersion(xStringify(MODULE_VERSION)), LiluAPI::AllowNormal | LiluAPI::AllowInstallerRecovery, bootargOff, arrsize(bootargOff), bootargDebug, arrsize(bootargDebug), bootargBeta, arrsize(bootargBeta), KernelVersion::MountainLion, KernelVersion::HighSierra, []() { alc.init(); } };
Change fill mode of transitions to backwards not both
// 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 "config.h" #include "core/animation/css/CSSTransitionData.h" #include "core/animation/Timing.h" namespace blink { CSSTransitionData::CSSTransitionData() { m_propertyList.append(initialProperty()); } CSSTransitionData::CSSTransitionData(const CSSTransitionData& other) : CSSTimingData(other) , m_propertyList(other.m_propertyList) { } bool CSSTransitionData::transitionsMatchForStyleRecalc(const CSSTransitionData& other) const { return m_propertyList == other.m_propertyList; } Timing CSSTransitionData::convertToTiming(size_t index) const { ASSERT(index < m_propertyList.size()); // Note that the backwards fill part is required for delay to work. Timing timing = CSSTimingData::convertToTiming(index); timing.fillMode = Timing::FillModeBoth; return timing; } } // namespace blink
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #include "core/animation/css/CSSTransitionData.h" #include "core/animation/Timing.h" namespace blink { CSSTransitionData::CSSTransitionData() { m_propertyList.append(initialProperty()); } CSSTransitionData::CSSTransitionData(const CSSTransitionData& other) : CSSTimingData(other) , m_propertyList(other.m_propertyList) { } bool CSSTransitionData::transitionsMatchForStyleRecalc(const CSSTransitionData& other) const { return m_propertyList == other.m_propertyList; } Timing CSSTransitionData::convertToTiming(size_t index) const { ASSERT(index < m_propertyList.size()); // Note that the backwards fill part is required for delay to work. Timing timing = CSSTimingData::convertToTiming(index); timing.fillMode = Timing::FillModeBackwards; return timing; } } // namespace blink
Update Application Info for JASP 0.7.5.1
// // Copyright (C) 2016 University of Amsterdam // // This program 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 2 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // #include "appinfo.h" const Version AppInfo::version = Version(0, 7, 5, 255); const std::string AppInfo::name = "JASP"; const std::string AppInfo::builddate = "Fri Feb 19 2016 12:55:58 GMT+0100 (CET)"; std::string AppInfo::getShortDesc() { return AppInfo::name + " " + AppInfo::version.asString(); }
// // Copyright (C) 2016 University of Amsterdam // // This program 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 2 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // #include "appinfo.h" const Version AppInfo::version = Version(0, 7, 5, 256); const std::string AppInfo::name = "JASP"; const std::string AppInfo::builddate = "Thu Feb 25 2016 11:50:50 GMT+0100 (CET)"; std::string AppInfo::getShortDesc() { return AppInfo::name + " " + AppInfo::version.asString(); }
Fix test failure in release mode.
// RUN: %clang_cc1 -emit-llvm -o - -O1 %s | FileCheck %s // Check that we generate TBAA for vtable pointer loads and stores. struct A { virtual int foo() const ; virtual ~A(); }; void CreateA() { new A; } void CallFoo(A *a) { a->foo(); } // CHECK: %vtable = load {{.*}} !tbaa !0 // CHECK: store {{.*}} !tbaa !0 // CHECK: !0 = metadata !{metadata !"vtable pointer", metadata !1} // CHECK: !1 = metadata !{metadata !"Simple C/C++ TBAA", null}
// RUN: %clang_cc1 -emit-llvm -o - -O1 %s | FileCheck %s // Check that we generate TBAA for vtable pointer loads and stores. struct A { virtual int foo() const ; virtual ~A(); }; void CreateA() { new A; } void CallFoo(A *a) { a->foo(); } // CHECK: %{{.*}} = load {{.*}} !tbaa !0 // CHECK: store {{.*}} !tbaa !0 // CHECK: !0 = metadata !{metadata !"vtable pointer", metadata !1} // CHECK: !1 = metadata !{metadata !"Simple C/C++ TBAA", null}
Fix a signedness warning on Darwin
// Copyright (c) 2009 - Decho Corp. #include "mordor/common/pch.h" #include "stream.h" #include <string.h> size_t Stream::write(const char *sz) { return write(sz, strlen(sz)); } size_t Stream::write(const void *b, size_t len) { Buffer buf; buf.copyIn(b, len); return write(buf, len); } std::string Stream::getDelimited(char delim, bool eofIsDelimiter) { ptrdiff_t offset = find(delim, ~0, !eofIsDelimiter); eofIsDelimiter = offset < 0; if (offset < 0) offset = -offset - 1; Buffer buf; size_t readResult = read(buf, offset + (eofIsDelimiter ? 0 : 1)); ASSERT(readResult == offset + (eofIsDelimiter ? 0 : 1)); // Don't copyOut the delimiter itself std::string result; result.resize(offset); buf.copyOut(const_cast<char*>(result.data()), offset); return result; }
// Copyright (c) 2009 - Decho Corp. #include "mordor/common/pch.h" #include "stream.h" #include <string.h> size_t Stream::write(const char *sz) { return write(sz, strlen(sz)); } size_t Stream::write(const void *b, size_t len) { Buffer buf; buf.copyIn(b, len); return write(buf, len); } std::string Stream::getDelimited(char delim, bool eofIsDelimiter) { ptrdiff_t offset = find(delim, ~0, !eofIsDelimiter); eofIsDelimiter = offset < 0; if (offset < 0) offset = -offset - 1; Buffer buf; size_t readResult = read(buf, offset + (eofIsDelimiter ? 0 : 1)); ASSERT((ptrdiff_t)readResult == offset + (eofIsDelimiter ? 0 : 1)); // Don't copyOut the delimiter itself std::string result; result.resize(offset); buf.copyOut(const_cast<char*>(result.data()), offset); return result; }
Add code section for Big Five usage.
#include <iostream> #include "Student.h" int main(int argc, char **argv){ Student c("Joe Schmoe", 12345); std::cout << c.getNumber() << ": " << c.getName() << std::endl; int num_grades = c.getNumGrades(); float * grades = c.getGrades(); for(int i=0; i<num_grades; i++){ std::cout << grades[i] << "\t"; } std::cout << std::endl; c.addGrade(100); c.addGrade(71); c.addGrade(93); c.addGrade(85); c.addGrade(76); c.addGrade(92); c.addGrade(100); c.addGrade(87); c.addGrade(85); c.addGrade(101); c.addGrade(91); c.addGrade(77); std::cout << c.getNumber() << ": " << c.getName() << std::endl; num_grades = c.getNumGrades(); grades = c.getGrades(); for(int i=0; i<num_grades; i++){ std::cout << grades[i] << "\t"; } }
#include <iostream> #include "Student.h" int main(int argc, char **argv){ Student c("Joe Schmoe", 12345); std::cout << c.getNumber() << ": " << c.getName() << std::endl; int num_grades = c.getNumGrades(); float * grades = c.getGrades(); for(int i=0; i<num_grades; i++){ std::cout << grades[i] << "\t"; } std::cout << std::endl; c.addGrade(100); c.addGrade(71); c.addGrade(93); c.addGrade(85); c.addGrade(76); c.addGrade(92); c.addGrade(100); c.addGrade(87); c.addGrade(85); c.addGrade(101); c.addGrade(91); c.addGrade(77); std::cout << c.getNumber() << ": " << c.getName() << std::endl; num_grades = c.getNumGrades(); grades = c.getGrades(); for(int i=0; i<num_grades; i++){ std::cout << grades[i] << "\t"; } // Now let's try out the Big Five! }
Fix compilation failure in unit tests on Windows.
//===-- GDBRemoteTestUtils.cpp ----------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "GDBRemoteTestUtils.h" namespace lldb_private { namespace process_gdb_remote { void GDBRemoteTest::SetUpTestCase() { #if defined(_MSC_VER) WSADATA data; ::WSAStartup(MAKEWORD(2, 2), &data); #endif } void GDBRemoteTest::TearDownTestCase() { #if defined(_MSC_VER) ::WSACleanup(); #endif } } // namespace process_gdb_remote } // namespace lldb_private
//===-- GDBRemoteTestUtils.cpp ----------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "GDBRemoteTestUtils.h" #if defined(_MSC_VER) #include "lldb/Host/windows/windows.h" #include <WinSock2.h> #endif namespace lldb_private { namespace process_gdb_remote { void GDBRemoteTest::SetUpTestCase() { #if defined(_MSC_VER) WSADATA data; ::WSAStartup(MAKEWORD(2, 2), &data); #endif } void GDBRemoteTest::TearDownTestCase() { #if defined(_MSC_VER) ::WSACleanup(); #endif } } // namespace process_gdb_remote } // namespace lldb_private
Initialize all the board properties
// // Created by Sam on 9/25/2017. // #include "../../../include/Game/Core/Board.h" #include "../../../include/Game/Core/Card.h" #include "../../../include/Game/Derived/Card/Creature.h" #include "../../../include/Game/Derived/Containers/CreatureZone.h" #include "../../../include/Game/Derived/Containers/Deck.h" #include "../../../include/Game/Derived/Containers/Graveyard.h" void Board::playCard(std::shared_ptr<Card> card) { if (auto creature = std::dynamic_pointer_cast<Creature>(card)) { creatures->cards.push_back(creature); } } Board::Board() = default; Board::~Board() = default;
// // Created by Sam on 9/25/2017. // #include "../../../include/Game/Core/Board.h" #include "../../../include/Game/Core/Card.h" #include "../../../include/Game/Derived/Card/Creature.h" #include "../../../include/Game/Derived/Containers/CreatureZone.h" #include "../../../include/Game/Derived/Containers/Deck.h" #include "../../../include/Game/Derived/Containers/Graveyard.h" void Board::playCard(std::shared_ptr<Card> card) { if (auto creature = std::dynamic_pointer_cast<Creature>(card)) { creatures->cards.push_back(creature); } } Board::Board() : creatures(std::make_shared<CreatureZone>()), deck(std::make_shared<Deck>()), graveyard(std::make_shared<Graveyard>()) { } Board::~Board() = default;
Set correctly a format on page capture.
#include "frame.hpp" namespace ph { Frame::Frame(QWebFrame *frame, QObject *parent): QObject(parent) { p_frame = frame; } Frame::~Frame() {} QByteArray Frame::toHtml() { return p_frame->toHtml().toUtf8(); } QByteArray Frame::captureImage(const char *format, int quality) { p_frame->page()->setViewportSize(p_frame->contentsSize()); QImage image(p_frame->page()->viewportSize(), QImage::Format_ARGB32_Premultiplied); image.fill(Qt::transparent); QBuffer buffer; buffer.open(QIODevice::ReadWrite); QPainter painter(&image); painter.setRenderHint(QPainter::Antialiasing, true); painter.setRenderHint(QPainter::TextAntialiasing, true); painter.setRenderHint(QPainter::SmoothPixmapTransform, true); p_frame->render(&painter); painter.end(); image.save(&buffer, "PNG"); return buffer.buffer(); } QByteArray Frame::evaluateJavaScript(const QString &js) { QVariant result = p_frame->evaluateJavaScript(js); return result.toString().toUtf8(); } QWebElement Frame::findFirstElement(const QString &selector) { return p_frame->findFirstElement(selector); } }
#include "frame.hpp" namespace ph { Frame::Frame(QWebFrame *frame, QObject *parent): QObject(parent) { p_frame = frame; } Frame::~Frame() {} QByteArray Frame::toHtml() { return p_frame->toHtml().toUtf8(); } QByteArray Frame::captureImage(const char *format, int quality) { p_frame->page()->setViewportSize(p_frame->contentsSize()); QImage image(p_frame->page()->viewportSize(), QImage::Format_ARGB32_Premultiplied); image.fill(Qt::transparent); QBuffer buffer; buffer.open(QIODevice::ReadWrite); QPainter painter(&image); painter.setRenderHint(QPainter::Antialiasing, true); painter.setRenderHint(QPainter::TextAntialiasing, true); painter.setRenderHint(QPainter::SmoothPixmapTransform, true); p_frame->render(&painter); painter.end(); image.save(&buffer, format, quality); return buffer.buffer(); } QByteArray Frame::evaluateJavaScript(const QString &js) { QVariant result = p_frame->evaluateJavaScript(js); return result.toString().toUtf8(); } QWebElement Frame::findFirstElement(const QString &selector) { return p_frame->findFirstElement(selector); } }
Make it a absolute path
/* * FileHelper.cpp * * Created on: 08.06.2016 * Author: hartung */ #include <boost/filesystem.hpp> #include "util/FileHelper.hpp" namespace Util { std::string FileHelper::find(const std::string & path, const std::string & fileName, const bool & recursive) { namespace fs = boost::filesystem; std::string res; fs::path bpath(path); if (fs::is_directory(bpath)) { for (fs::directory_iterator it = fs::directory_iterator(bpath); it != fs::directory_iterator(); ++it) { if (fs::is_directory(*it)) { if (recursive) { res = find(bpath.string(), fileName, recursive); } } else if (fs::is_regular(*it) && it->path().filename() == fileName) { res = it->path().string(); } if (!res.empty()) break; } } return res; } } std::string Util::FileHelper::absoluteFilePath(const std::string& fileName) { std::string res(""); namespace fs = boost::filesystem; fs::path bpath(fileName); if(fs::is_regular(bpath)) res = bpath.string(); return res; }
/* * FileHelper.cpp * * Created on: 08.06.2016 * Author: hartung */ #include <boost/filesystem.hpp> #include "util/FileHelper.hpp" namespace Util { std::string FileHelper::find(const std::string & path, const std::string & fileName, const bool & recursive) { namespace fs = boost::filesystem; std::string res; fs::path bpath(path); if (fs::is_directory(bpath)) { for (fs::directory_iterator it = fs::directory_iterator(bpath); it != fs::directory_iterator(); ++it) { if (fs::is_directory(*it)) { if (recursive) { res = find(bpath.string(), fileName, recursive); } } else if (fs::is_regular(*it) && it->path().filename() == fileName) { res = it->path().string(); } if (!res.empty()) break; } } return res; } } std::string Util::FileHelper::absoluteFilePath(const std::string& fileName) { std::string res(""); namespace fs = boost::filesystem; fs::path bpath(fileName); if(fs::is_regular(bpath)) res = fs::absolute(bpath).string(); return res; }
Return false when failing to open a file
#include "VM.hpp" #include <fstream> #include <iterator> #include "IoDevice.hpp" namespace model { VM::VM( IoDevice& ioDevice ) : m_ioDevice{ ioDevice } , m_cpu{ m_mmu, m_ioDevice, m_rng } { } bool VM::loadRom( const std::string& fileName ) { std::ifstream in{ fileName, std::ios::binary }; if ( in.is_open() ) { const std::vector<chip8::byte_t> data{ std::istream_iterator<chip8::byte_t>{ in }, std::istream_iterator<chip8::byte_t>{} }; in.close(); m_mmu.load( data, chip8::init_rom_load_address ); } return true; // TODO this is always returnign true... } void VM::cycle() { m_cpu.cycle(); } } // namespace model
#include "VM.hpp" #include <fstream> #include <iterator> #include "IoDevice.hpp" namespace model { VM::VM( IoDevice& ioDevice ) : m_ioDevice{ ioDevice } , m_cpu{ m_mmu, m_ioDevice, m_rng } { } bool VM::loadRom( const std::string& fileName ) { std::ifstream in{ fileName, std::ios::binary }; if ( in.is_open() ) { const std::vector<chip8::byte_t> data{ std::istream_iterator<chip8::byte_t>{ in }, std::istream_iterator<chip8::byte_t>{} }; in.close(); m_mmu.load( data, chip8::init_rom_load_address ); return true; } return false; } void VM::cycle() { m_cpu.cycle(); } } // namespace model
Update this test yet again, this time based on a nice consecutive pair of lines provided with the filecheck output from the previous run. I'll probably give up after this and get someone with a Windows build to help me out.
// 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 {{.*}} in malloc // CHECK: #1 {{.*FIXME}} // CHECK: #2 {{.* main .*}}intercept_strdup.cc:[[@LINE-15]] 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 {{.*}} in __asan_wrap_strdup // CHECK: #1 {{.*}} in main {{.*}}intercept_strdup.cc:[[@LINE-15]] free(ptr); }
Return non-zero status on error
// Copyright 2015 Nikita Chudinov #include <iostream> #include "argument_parser.h" #include "daemon.h" #include "ipc.h" int main(int argc, char *argv[]) { ArgumentParser arguments(argc, argv); switch (arguments.GetMode()) { case ArgumentParser::START: Daemon::Start(); break; case ArgumentParser::KILL: Daemon::Kill(); break; case ArgumentParser::STORE: case ArgumentParser::CHECK: { IpcConnection socket("\0INTEGRITY"); IpcClient *client = socket.MakeClient(); client->SendCommand(arguments.GetMode()); client->SendString(arguments.GetPathListFile()); break; } case ArgumentParser::UNKNOWN: case ArgumentParser::HELP: default: arguments.PrintHelpMessage(); break; } return 0; }
// Copyright 2015 Nikita Chudinov #include <iostream> #include "argument_parser.h" #include "daemon.h" #include "ipc.h" int main(int argc, char *argv[]) { ArgumentParser arguments(argc, argv); int status = 0; switch (arguments.GetMode()) { case ArgumentParser::START: Daemon::Start(); break; case ArgumentParser::KILL: Daemon::Kill(); break; case ArgumentParser::STORE: case ArgumentParser::CHECK: { IpcConnection socket("\0INTEGRITY"); IpcClient *client = socket.MakeClient(); client->SendCommand(arguments.GetMode()); client->SendString(arguments.GetPathListFile()); break; } case ArgumentParser::UNKNOWN: status = 1; case ArgumentParser::HELP: default: arguments.PrintHelpMessage(); break; } return status; }
Optimize sphere sampling code using trig identity
#include "./Sphere.hpp" #include "./misc.hpp" #include <algorithm> #include <cmath> namespace yks { Optional<float> intersect(const vec3& origin, float radius, const Ray& r) { const vec3 o = r.origin - origin; const vec3 v = r.direction; float t1, t2; const int solutions = solve_quadratic(dot(v, v), 2*dot(o, v), dot(o, o) - radius*radius, t1, t2); if (solutions == 0) { return Optional<float>(); } else if (solutions == 1) { return make_optional<float>(t1); } else { return make_optional<float>(std::min(t1, t2)); } } vec3 uniform_point_on_sphere(float a, float b) { const float y = 2.0f * a - 1.0f; const float latitude = std::asin(y); const float longitude = b * two_pi; const float cos_latitude = std::cos(latitude); return mvec3(cos_latitude * cos(longitude), y, cos_latitude * sin(longitude)); } }
#include "./Sphere.hpp" #include "./misc.hpp" #include <algorithm> #include <cmath> namespace yks { Optional<float> intersect(const vec3& origin, float radius, const Ray& r) { const vec3 o = r.origin - origin; const vec3 v = r.direction; float t1, t2; const int solutions = solve_quadratic(dot(v, v), 2*dot(o, v), dot(o, o) - radius*radius, t1, t2); if (solutions == 0) { return Optional<float>(); } else if (solutions == 1) { return make_optional<float>(t1); } else { return make_optional<float>(std::min(t1, t2)); } } vec3 uniform_point_on_sphere(float a, float b) { const float y = 2.0f * a - 1.0f; const float longitude = b * two_pi; const float cos_latitude = std::sqrt(1.0f - sqr(y)); return mvec3(cos_latitude * std::cos(longitude), y, cos_latitude * std::sin(longitude)); } }
Fix state switching in main menu.
#include "main_menu_state.hpp" #include "game_state.hpp" namespace Quoridor { MainMenuState::MainMenuState() { } MainMenuState::~MainMenuState() { } void MainMenuState::handle_events(StateManager *stm, std::shared_ptr<UI::UIImpl> ui) { UI::Event ev; if (ui->poll_event(&ev)) { switch (ev) { case UI::kEnter: { std::shared_ptr<Quoridor::IState> game_state(new Quoridor::GameState()); stm->change_state(std::shared_ptr<Quoridor::IState>(game_state)); } break; case UI::kEsc: stm->stop(); break; default: break; } } } void MainMenuState::update() { } void MainMenuState::draw(std::shared_ptr<UI::UIImpl> /* ui */) { } void MainMenuState::change_state() { } } /* namespace Quoridor */
#include "main_menu_state.hpp" #include "start_game_state.hpp" namespace Quoridor { MainMenuState::MainMenuState() { } MainMenuState::~MainMenuState() { } void MainMenuState::handle_events(StateManager *stm, std::shared_ptr<UI::UIImpl> ui) { UI::Event ev; if (ui->poll_event(&ev)) { switch (ev) { case UI::kEnter: { std::shared_ptr<IState> start_game_state(new StartGameState(ui)); stm->change_state(std::shared_ptr<IState>(start_game_state)); } break; case UI::kEsc: stm->stop(); break; default: break; } } } void MainMenuState::update() { } void MainMenuState::draw(std::shared_ptr<UI::UIImpl> /* ui */) { } void MainMenuState::change_state() { } } /* namespace Quoridor */
Mark [[nodiscard]] tests unsupported on GCC prior to 7.0
// -*- C++ -*- //===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03 // Test that entities declared [[nodiscard]] as at extension by libc++, are // only actually declared such when _LIBCPP_ENABLE_NODISCARD is specified. // All entities to which libc++ applies [[nodiscard]] as an extension should // be tested here and in nodiscard_extensions.pass.cpp. They should also // be listed in `UsingLibcxx.rst` in the documentation for the extension. // MODULES_DEFINES: _LIBCPP_ENABLE_NODISCARD #define _LIBCPP_ENABLE_NODISCARD #include <memory> #include "test_macros.h" int main() { { // expected-error-re@+1 {{ignoring return value of function declared with {{'nodiscard'|warn_unused_result}} attribute}} std::get_temporary_buffer<int>(1); } }
// -*- C++ -*- //===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03 // GCC versions prior to 7.0 don't provide the required [[nodiscard]] attribute. // UNSUPPORTED: gcc-4, gcc-5, gcc-6 // Test that entities declared [[nodiscard]] as at extension by libc++, are // only actually declared such when _LIBCPP_ENABLE_NODISCARD is specified. // All entities to which libc++ applies [[nodiscard]] as an extension should // be tested here and in nodiscard_extensions.pass.cpp. They should also // be listed in `UsingLibcxx.rst` in the documentation for the extension. // MODULES_DEFINES: _LIBCPP_ENABLE_NODISCARD #define _LIBCPP_ENABLE_NODISCARD #include <memory> #include "test_macros.h" int main() { { // expected-error-re@+1 {{ignoring return value of function declared with {{'nodiscard'|warn_unused_result}} attribute}} std::get_temporary_buffer<int>(1); } }
Set stack slot to null before calling destructor
#include "runtime_internal.h" #define INLINE inline __attribute__((weak)) __attribute__((always_inline)) __attribute__((used)) extern "C" { INLINE void call_destructor(void *user_context, void (*fn)(void *user_context, void *object), void **object) { // Call the function if (*object) { fn(user_context, *object); } *object = NULL; } }
#include "runtime_internal.h" #define INLINE inline __attribute__((weak)) __attribute__((always_inline)) __attribute__((used)) extern "C" { INLINE void call_destructor(void *user_context, void (*fn)(void *user_context, void *object), void **object) { void *o = *object; *object = NULL; // Call the function if (o) { fn(user_context, o); } } }
Work around the cache->settings->cache deadlock
#include <vw/Core/System.h> #include <vw/Core/Cache.h> #include <vw/Core/Log.h> #include <vw/Core/Settings.h> #include <vw/Core/Stopwatch.h> namespace { vw::RunOnce core_once = VW_RUNONCE_INIT; vw::Cache* cache_ptr = 0; vw::Settings* settings_ptr = 0; vw::Log* log_ptr = 0; vw::StopwatchSet* stopwatch_ptr = 0; void init_core() { settings_ptr = new vw::Settings(); log_ptr = new vw::Log(); cache_ptr = new vw::Cache(settings_ptr->system_cache_size()); stopwatch_ptr = new vw::StopwatchSet(); } } namespace vw { Cache& vw_system_cache() { core_once.run(init_core); return *cache_ptr; } Log& vw_log() { core_once.run(init_core); return *log_ptr; } Settings& vw_settings() { core_once.run(init_core); return *settings_ptr; } StopwatchSet& vw_stopwatch_set() { core_once.run(init_core); return *stopwatch_ptr; } }
#include <vw/Core/System.h> #include <vw/Core/Cache.h> #include <vw/Core/Log.h> #include <vw/Core/Settings.h> #include <vw/Core/Stopwatch.h> #define FUNC(Name, Type, Code) \ namespace { \ vw::RunOnce Name ## _once = VW_RUNONCE_INIT; \ Type* Name ## _ptr = 0; \ void init_ ## Name() { \ Name ## _ptr = new Type Code; \ } \ } \ Type& vw::vw_ ## Name() { \ Name ## _once.run(init_ ## Name); \ return *Name ## _ptr; \ } FUNC( settings, vw::Settings, ()); FUNC( log, vw::Log, ()); FUNC( system_cache, vw::Cache, (vw::vw_settings().system_cache_size())); FUNC(stopwatch_set, vw::StopwatchSet, ());
Fix a unittest that was leaking a HANDLE due to base::Process refactoring.
// Copyright (c) 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/app/chrome_watcher_command_line_win.h" #include <windows.h> #include "base/command_line.h" #include "base/files/file_path.h" #include "base/process/process.h" #include "base/win/scoped_handle.h" #include "testing/gtest/include/gtest/gtest.h" TEST(ChromeWatcherCommandLineTest, BasicTest) { base::Process current = base::Process::Open(base::GetCurrentProcId()); ASSERT_TRUE(current.IsValid()); HANDLE event = ::CreateEvent(nullptr, FALSE, FALSE, nullptr); base::CommandLine cmd_line = GenerateChromeWatcherCommandLine( base::FilePath(L"example.exe"), current.Handle(), event); base::win::ScopedHandle current_result; base::win::ScopedHandle event_result; ASSERT_TRUE(InterpretChromeWatcherCommandLine(cmd_line, &current_result, &event_result)); ASSERT_EQ(current.Handle(), current_result.Get()); ASSERT_EQ(event, event_result.Get()); }
// Copyright (c) 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/app/chrome_watcher_command_line_win.h" #include <windows.h> #include "base/command_line.h" #include "base/files/file_path.h" #include "base/process/process_handle.h" #include "base/win/scoped_handle.h" #include "testing/gtest/include/gtest/gtest.h" TEST(ChromeWatcherCommandLineTest, BasicTest) { // Ownership of these handles is passed to the ScopedHandles below via // InterpretChromeWatcherCommandLine(). base::ProcessHandle current = ::OpenProcess(PROCESS_QUERY_INFORMATION | SYNCHRONIZE, TRUE, // Inheritable ::GetCurrentProcessId()); ASSERT_NE(nullptr, current); HANDLE event = ::CreateEvent(nullptr, FALSE, FALSE, nullptr); ASSERT_NE(nullptr, event); base::CommandLine cmd_line = GenerateChromeWatcherCommandLine( base::FilePath(L"example.exe"), current, event); base::win::ScopedHandle current_result; base::win::ScopedHandle event_result; ASSERT_TRUE(InterpretChromeWatcherCommandLine(cmd_line, &current_result, &event_result)); ASSERT_EQ(current, current_result.Get()); ASSERT_EQ(event, event_result.Get()); }