Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Disable ExtensionApiTest.JavaScriptURLPermissions, it flakily hits an assertion.
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "net/base/mock_host_resolver.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, JavaScriptURLPermissions) { host_resolver()->AddRule("a.com", "127.0.0.1"); host_resolver()->AddRule("b.com", "127.0.0.1"); ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("tabs/javascript_url_permissions")) << message_; }
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "net/base/mock_host_resolver.h" // Disabled, http://crbug.com/63589. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_JavaScriptURLPermissions) { host_resolver()->AddRule("a.com", "127.0.0.1"); host_resolver()->AddRule("b.com", "127.0.0.1"); ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("tabs/javascript_url_permissions")) << message_; }
Print $ in for loop
#inlcude <iostream> using namespace std; int main(){ return 0; }
#include <iostream> #include <string> using namespace std; int main(int argc,char **argv){ string command; cout << argv[1]; //While loop that repeats $ and cin command while(command != "exit"){ cout << "$"; cin >> command; } return 0; }
Fix no newline at end of file
// This file is only compiled if the cmake option BP_USE_ADDITIONAL_SOURCEFILE is set to ON #ifndef HAS_ADDITIONAL_SOURCEFILE #error If this file is compiled, the target must have HAS_ADDITIONAL_SOURCEFILE defined #endif
// This file is only compiled if the cmake option BP_USE_ADDITIONAL_SOURCEFILE is set to ON #ifndef HAS_ADDITIONAL_SOURCEFILE #error If this file is compiled, the target must have HAS_ADDITIONAL_SOURCEFILE defined #endif
Print a qDebug saying what player is actually running
#include "testingplayer.h" #ifdef XINE_PLAYER #include "xineplayer.h" #endif #include "qtsingleapplication.h" #include <QDebug> #include <QtDBus> int main(int argc, char** argv) { QtSingleApplication app(argc, argv); app.setApplicationName("mediahelper"); app.setOrganizationName("Nokia"); app.setOrganizationDomain("nokia.com"); if (app.isRunning()) { qWarning() << app.applicationName() << "is already running, aborting"; return false; } bool dbusRegistration = QDBusConnection::sessionBus().registerService(QMH_HELPER_DBUS_SERVICENAME); if (!dbusRegistration) { qDebug() << "Can't seem to register dbus service:" << QDBusConnection::sessionBus().lastError().message(); app.exit(-1); } AbstractMediaPlayer *player = 0; #ifdef XINE_PLAYER #warning using xine backend player = new XinePlayer(&app); #else #warning using qDebug testing backend player = new TestingPlayer(&app); #endif dbusRegistration = QDBusConnection::sessionBus().registerObject("/", player, QDBusConnection::ExportScriptableSlots|QDBusConnection::ExportScriptableSignals); if (!dbusRegistration) { qDebug() << "Can't seem to register dbus object:" << QDBusConnection::sessionBus().lastError().message(); app.exit(-1); } return app.exec(); }
#include "testingplayer.h" #ifdef XINE_PLAYER #include "xineplayer.h" #endif #include "qtsingleapplication.h" #include <QDebug> #include <QtDBus> int main(int argc, char** argv) { QtSingleApplication app(argc, argv); app.setApplicationName("mediahelper"); app.setOrganizationName("Nokia"); app.setOrganizationDomain("nokia.com"); if (app.isRunning()) { qWarning() << app.applicationName() << "is already running, aborting"; return false; } bool dbusRegistration = QDBusConnection::sessionBus().registerService(QMH_HELPER_DBUS_SERVICENAME); if (!dbusRegistration) { qDebug() << "Can't seem to register dbus service:" << QDBusConnection::sessionBus().lastError().message(); app.exit(-1); } AbstractMediaPlayer *player = 0; #ifdef XINE_PLAYER #warning using xine backend qDebug() << "Xine player started"; player = new XinePlayer(&app); #else #warning using qDebug testing backend qDebug() << "qDebug player started"; player = new TestingPlayer(&app); #endif dbusRegistration = QDBusConnection::sessionBus().registerObject("/", player, QDBusConnection::ExportScriptableSlots|QDBusConnection::ExportScriptableSignals); if (!dbusRegistration) { qDebug() << "Can't seem to register dbus object:" << QDBusConnection::sessionBus().lastError().message(); app.exit(-1); } return app.exec(); }
Implement GC for expenses and earnings
//======================================================================= // Copyright (c) 2013-2014 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include <fstream> #include <sstream> #include "gc.hpp" #include "accounts.hpp" #include "expenses.hpp" #include "earnings.hpp" using namespace budget; namespace { } //end of anonymous namespace void budget::gc_module::load(){ load_accounts(); load_expenses(); load_earnings(); } void budget::gc_module::unload(){ save_expenses(); save_earnings(); save_accounts(); } void budget::gc_module::handle(const std::vector<std::string>& args){ if(args.size() > 1){ std::cout << "Too many parameters" << std::endl; } else { std::cout << "Make all IDs contiguous..." << std::endl; std::cout << "...done" << std::endl; } }
//======================================================================= // Copyright (c) 2013-2014 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include <fstream> #include <sstream> #include "gc.hpp" #include "accounts.hpp" #include "expenses.hpp" #include "earnings.hpp" using namespace budget; namespace { template<typename Values> std::size_t gc(Values& values){ std::sort(values.begin(), values.end(), [](const typename Values::value_type& a, const typename Values::value_type& b){ return a.id < b.id; }); std::size_t next_id = 0; for(auto& expense : values){ expense.id = ++next_id; } return ++next_id; } void gc_expenses(){ auto next_id = gc(all_expenses()); set_expenses_next_id(next_id); set_expenses_changed(); } void gc_earnings(){ auto next_id = gc(all_earnings()); set_earnings_next_id(next_id); set_earnings_changed(); } } //end of anonymous namespace void budget::gc_module::load(){ load_accounts(); load_expenses(); load_earnings(); } void budget::gc_module::unload(){ save_expenses(); save_earnings(); save_accounts(); } void budget::gc_module::handle(const std::vector<std::string>& args){ if(args.size() > 1){ std::cout << "Too many parameters" << std::endl; } else { std::cout << "Make all IDs contiguous..." << std::endl; gc_expenses(); gc_earnings(); std::cout << "...done" << std::endl; } }
Add LEQUAL depth function to context init
#include "Context.h" #include <GL/glew.h> #include "Utilities.h" namespace ion { namespace GL { void Context::Init() { CheckedGLCall(glEnable(GL_DEPTH_TEST)); } void Context::Clear(std::initializer_list<EBuffer> Buffers) { static u32 const BufferLookup[3] = { GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT }; int BitMask = 0; for (auto Buffer : Buffers) BitMask |= BufferLookup[(int) Buffer]; CheckedGLCall(glClear(BitMask)); } } }
#include "Context.h" #include <GL/glew.h> #include "Utilities.h" namespace ion { namespace GL { void Context::Init() { CheckedGLCall(glEnable(GL_DEPTH_TEST)); CheckedGLCall(glDepthFunc(GL_LEQUAL)); } void Context::Clear(std::initializer_list<EBuffer> Buffers) { static u32 const BufferLookup[3] = { GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT }; int BitMask = 0; for (auto Buffer : Buffers) BitMask |= BufferLookup[(int) Buffer]; CheckedGLCall(glClear(BitMask)); } } }
Use of the command btk::Logger::SetVerbose instead of setting the stream buffer of std::cerr to null when the symbol TDD_SILENT_CERR is defined.
#include "_TDDConfigure.h" // BTK error messages are not displayed #define TDD_SILENT_CERR int main() { #if defined(TDD_SILENT_CERR) std::streambuf* standardErrorOutput = std::cerr.rdbuf(0); #endif int err = CxxTest::ErrorPrinter().run(); #if defined(TDD_SILENT_CERR) std::cerr.rdbuf(standardErrorOutput); #endif return err; }; #include <cxxtest/Root.cpp>
#include "_TDDConfigure.h" #include <btkLogger.h> // BTK error messages are not displayed #define TDD_SILENT_CERR int main() { #if defined(TDD_SILENT_CERR) btk::Logger::SetVerboseMode(btk::Logger::Quiet); #endif return CxxTest::ErrorPrinter().run();; }; #include <cxxtest/Root.cpp>
Add virtual to nested template example
template<typename First, typename Second> class Pair { private: First first; Second second; public: template<typename Third> class Inner { Third third; }; }; int main(int argc, char *argv[]) { Pair<int,double> pp1; Pair<int,int> pp2; Pair<int,double>::Inner<char> p; Pair<int,double>::Inner<long> p2; Pair<int,int>::Inner<char> p3; Pair<int,int>::Inner<double> p4; Pair<double,double>::Inner<char> p5; return 0; }
template<typename First, typename Second> class Pair { private: First first; Second second; public: virtual ~Pair() {} template<typename Third> class Inner { Third third; }; }; int main(int argc, char *argv[]) { Pair<int,double> pp1; Pair<int,int> pp2; Pair<int,double>::Inner<char> p; Pair<int,double>::Inner<long> p2; Pair<int,int>::Inner<char> p3; Pair<int,int>::Inner<double> p4; Pair<double,double>::Inner<char> p5; 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_; }
Add correct preprocessor check for Windows.
#include "GLPlatform.hpp" #include <stdexcept> namespace CPM_GL_PLATFORM_NS { void glPlatformInit() { #ifdef GL_PLATFORM_USING_WIN GLenum err = glewInit(); if (GLEW_OK != err) { throw std::runtime_error("GLEW failed to initialize."); } #endif } } // namespace CPM_GL_PLATFORM_NS
#include "GLPlatform.hpp" #include <stdexcept> namespace CPM_GL_PLATFORM_NS { void glPlatformInit() { #ifdef WIN32 GLenum err = glewInit(); if (GLEW_OK != err) { throw std::runtime_error("GLEW failed to initialize."); } #endif } } // namespace CPM_GL_PLATFORM_NS
Clear display before each text display
#include <iostream> #include <string> #include "../lcd/MiniLcdPCD8544.h" using namespace std; /** * Test the WiringPiLcdDisplay implementation */ int main() { unique_ptr<MiniLcdPCD8544> lcd(MiniLcdPCD8544::getLcdDisplayInstance()); lcd->init(); lcd->displayText("Text to display:", 0, 0); cout << "Enter text to display: "; int count = 0; for (std::string line; std::getline(std::cin, line);) { count ++; int col = 0; int row = count % 3 + 1; if(count % 2) col = 2; lcd->displayText(line.c_str(), col, row); cout << "Enter text to display: "; } lcd->clear(); }
#include <iostream> #include <string> #include "../lcd/MiniLcdPCD8544.h" using namespace std; /** * Test the WiringPiLcdDisplay implementation */ int main() { unique_ptr<MiniLcdPCD8544> lcd(MiniLcdPCD8544::getLcdDisplayInstance()); lcd->init(); lcd->displayText("Text to display:", 0, 0); cout << "Enter text to display: "; int count = 0; for (std::string line; std::getline(std::cin, line);) { count ++; int col = 0; int row = count % 3 + 1; if(count % 2) col = 2; lcd->clear(); lcd->displayText(line.c_str(), col, row); cout << "Enter text to display: "; } lcd->clear(); }
Convert to use of axonalArbor syntax.
/* * RandomConn.cpp * * Created on: Apr 27, 2009 * Author: rasmussn */ #include "RandomConn.hpp" #include <assert.h> #include <string.h> namespace PV { RandomConn::RandomConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post, int channel) { this->connId = hc->numberOfConnections(); this->name = strdup(name); this->parent = hc; this->numBundles = 1; initialize(NULL, pre, post, channel); hc->addConnection(this); } int RandomConn::initializeWeights(const char * filename) { assert(filename == NULL); return initializeRandomWeights(0); } }
/* * RandomConn.cpp * * Created on: Apr 27, 2009 * Author: rasmussn */ #include "RandomConn.hpp" #include <assert.h> #include <string.h> namespace PV { RandomConn::RandomConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post, int channel) { this->connId = hc->numberOfConnections(); this->name = strdup(name); this->parent = hc; this->numAxonalArborLists = 1; initialize(NULL, pre, post, channel); hc->addConnection(this); } int RandomConn::initializeWeights(const char * filename) { assert(filename == NULL); return initializeRandomWeights(0); } }
Update pin definitions for 16x2 lcd
#include "display.h" #include "sensor.h" #include <LiquidCrystal.h> // Arduino LCD library #include <Arduino.h> // enables use of byte pics // pin definition for LCD #define LCD_CS 10 #define LCD_DC 9 #define LCD_RST 8 namespace LCD { TFT TFTscreen = TFT(LCD_CS, LCD_DC, LCD_RST); void setup() { // initialize the display TFTscreen.begin(); // clear the screen with a black background TFTscreen.background(0, 0, 0); // set the font color to white TFTscreen.stroke(255, 255, 255); } void clearScreen() { // clear the screen to show refreshed data TFTscreen.background(0, 0, 0); } void displayTemp(int tempInt) { char tempChar[6]; snprintf(tempChar, sizeof tempChar, "%d", tempInt); // print temp text TFTscreen.text(tempChar, 0, 20); } }
#include "display.h" #include "sensor.h" #include <LiquidCrystal.h> // Arduino LCD library #include <Arduino.h> // enables use of byte pics #define DISPLAY_RS 14 #define DISPLAY_E 15 #define DISPLAY_D4 5 #define DISPLAY_D5 4 #define DISPLAY_D6 3 #define DISPLAY_D7 2 namespace LCD { TFT TFTscreen = TFT(LCD_CS, LCD_DC, LCD_RST); void setup() { // initialize the display TFTscreen.begin(); // clear the screen with a black background TFTscreen.background(0, 0, 0); // set the font color to white TFTscreen.stroke(255, 255, 255); } void clearScreen() { // clear the screen to show refreshed data TFTscreen.background(0, 0, 0); } void displayTemp(int tempInt) { char tempChar[6]; snprintf(tempChar, sizeof tempChar, "%d", tempInt); // print temp text TFTscreen.text(tempChar, 0, 20); } }
Create example memory read test
#include <gtest/gtest.h> #include <system.h> #include "mock_memorymodule.h" class SystemTest : public testing::Test { protected: System sys; StrictMockMemoryModule mem; }; //Dumy test TEST_F(SystemTest, TestMemoryAddressTranslation) { unsigned char dummy_buffer[10]; sys.installMemory(mem, 10, 10); int iret = sys.readMemory(10, 5, dummy_buffer); }
#include <gtest/gtest.h> #include <errors.h> #include <system.h> #include "mock_memorymodule.h" class SystemTest : public testing::Test { protected: System sys; StrictMockMemoryModule mem; }; //Dumy test TEST_F(SystemTest, TestMemoryAddressTranslation) { unsigned char dummy_buffer[10]; int iret; iret = sys.installMemory(mem, 10, 10); ASSERT_EQ(iret, ERR_SUCCESS) << "Module installion failed"; iret = sys.readMemory(10, 5, dummy_buffer); ASSERT_EQ(iret, ERR_SUCCESS) << "Memory read failed"; }
Fix tests after cache tweaks
#define BOOST_TEST_MODULE Bitcoin Test Suite #include <boost/test/unit_test.hpp> #include "db.h" #include "txdb.h" #include "main.h" #include "wallet.h" CWallet* pwalletMain; CClientUIInterface uiInterface; extern bool fPrintToConsole; extern void noui_connect(); struct TestingSetup { CCoinsViewDB *pcoinsdbview; TestingSetup() { fPrintToDebugger = true; // don't want to write to debug.log file noui_connect(); bitdb.MakeMock(); pblocktree = new CBlockTreeDB(true); pcoinsdbview = new CCoinsViewDB(true); pcoinsTip = new CCoinsViewCache(*pcoinsdbview); LoadBlockIndex(); bool fFirstRun; pwalletMain = new CWallet("wallet.dat"); pwalletMain->LoadWallet(fFirstRun); RegisterWallet(pwalletMain); } ~TestingSetup() { delete pwalletMain; pwalletMain = NULL; delete pcoinsTip; delete pcoinsdbview; delete pblocktree; bitdb.Flush(true); } }; BOOST_GLOBAL_FIXTURE(TestingSetup); void Shutdown(void* parg) { exit(0); } void StartShutdown() { exit(0); }
#define BOOST_TEST_MODULE Bitcoin Test Suite #include <boost/test/unit_test.hpp> #include "db.h" #include "txdb.h" #include "main.h" #include "wallet.h" CWallet* pwalletMain; CClientUIInterface uiInterface; extern bool fPrintToConsole; extern void noui_connect(); struct TestingSetup { CCoinsViewDB *pcoinsdbview; TestingSetup() { fPrintToDebugger = true; // don't want to write to debug.log file noui_connect(); bitdb.MakeMock(); pblocktree = new CBlockTreeDB(1 << 20, true); pcoinsdbview = new CCoinsViewDB(1 << 23, true); pcoinsTip = new CCoinsViewCache(*pcoinsdbview); LoadBlockIndex(); bool fFirstRun; pwalletMain = new CWallet("wallet.dat"); pwalletMain->LoadWallet(fFirstRun); RegisterWallet(pwalletMain); } ~TestingSetup() { delete pwalletMain; pwalletMain = NULL; delete pcoinsTip; delete pcoinsdbview; delete pblocktree; bitdb.Flush(true); } }; BOOST_GLOBAL_FIXTURE(TestingSetup); void Shutdown(void* parg) { exit(0); } void StartShutdown() { exit(0); }
Add code that hangs until the IP address changes
// observable-ip-address.cpp : Defines the entry point for the console application. // #include "stdafx.h" int _tmain(int argc, _TCHAR* argv[]) { return 0; }
// observable-ip-address.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <winsock2.h> #include <iphlpapi.h> #include <stdio.h> #include <windows.h> #pragma comment(lib, "iphlpapi.lib") #pragma comment(lib, "ws2_32.lib") int _tmain(int argc, _TCHAR* argv[]) { OVERLAPPED overlap; DWORD ret; HANDLE hand = NULL; overlap.hEvent = WSACreateEvent(); ret = NotifyAddrChange(&hand, &overlap); if (ret != NO_ERROR) { if (WSAGetLastError() != WSA_IO_PENDING) { printf("NotifyAddrChange error...%d\n", WSAGetLastError()); return 1; } } if (WaitForSingleObject(overlap.hEvent, INFINITE) == WAIT_OBJECT_0) printf("IP Address table changed..\n"); return 0; }
Remove erroneous DCHECK from KeyEventTracker
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/protocol/key_event_tracker.h" #include "base/logging.h" #include "remoting/proto/event.pb.h" namespace remoting { namespace protocol { KeyEventTracker::KeyEventTracker(InputStub* input_stub) : input_stub_(input_stub) { } KeyEventTracker::~KeyEventTracker() { DCHECK(pressed_keys_.empty()); } void KeyEventTracker::InjectKeyEvent(const KeyEvent& event) { DCHECK(event.has_pressed()); DCHECK(event.has_keycode()); if (event.pressed()) { pressed_keys_.insert(event.keycode()); } else { pressed_keys_.erase(event.keycode()); } input_stub_->InjectKeyEvent(event); } void KeyEventTracker::InjectMouseEvent(const MouseEvent& event) { input_stub_->InjectMouseEvent(event); } void KeyEventTracker::ReleaseAllKeys() { std::set<int>::iterator i; for (i = pressed_keys_.begin(); i != pressed_keys_.end(); ++i) { KeyEvent event; event.set_keycode(*i); event.set_pressed(false); input_stub_->InjectKeyEvent(event); } pressed_keys_.clear(); } } // namespace protocol } // namespace remoting
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/protocol/key_event_tracker.h" #include "base/logging.h" #include "remoting/proto/event.pb.h" namespace remoting { namespace protocol { KeyEventTracker::KeyEventTracker(InputStub* input_stub) : input_stub_(input_stub) { } KeyEventTracker::~KeyEventTracker() { } void KeyEventTracker::InjectKeyEvent(const KeyEvent& event) { DCHECK(event.has_pressed()); DCHECK(event.has_keycode()); if (event.pressed()) { pressed_keys_.insert(event.keycode()); } else { pressed_keys_.erase(event.keycode()); } input_stub_->InjectKeyEvent(event); } void KeyEventTracker::InjectMouseEvent(const MouseEvent& event) { input_stub_->InjectMouseEvent(event); } void KeyEventTracker::ReleaseAllKeys() { std::set<int>::iterator i; for (i = pressed_keys_.begin(); i != pressed_keys_.end(); ++i) { KeyEvent event; event.set_keycode(*i); event.set_pressed(false); input_stub_->InjectKeyEvent(event); } pressed_keys_.clear(); } } // namespace protocol } // namespace remoting
Debug / release macros check added (required for normal assert functioning on non-Windows systems)
#include "advanced_assert.h" std::function<void (const char*)> AdvancedAssert::_loggingFunc; void AdvancedAssert::setLoggingFunc(const std::function<void (const char*)>& func) { _loggingFunc = func; }
#include "advanced_assert.h" #if defined _DEBUG == (defined NDEBUG || NDEBUG == 1) #error "Either _DEBUG or NDEBUG=1 must be defined" #endif std::function<void (const char*)> AdvancedAssert::_loggingFunc; void AdvancedAssert::setLoggingFunc(const std::function<void (const char*)>& func) { _loggingFunc = func; }
Put the using namespace std in the cpp files
#include <iostream> #include "../src/tisys.hpp" int main(int argc, char** argv){ cout << "Example" <<endl; Filesystem fs; if ( argc == 1 ) fs.info("."); else fs.info( argv[1] ); cout << fs; return 0; }
#include <iostream> #include "../src/tisys.hpp" using namespace std; int main(int argc, char** argv){ cout << "Example" <<endl; Filesystem fs; if ( argc == 1 ) fs.info("."); else fs.info( argv[1] ); cout << fs; return 0; }
Remove dependency on importing std into global namespace.
#include <cstdlib> #include <stdio.h> #include <string.h> #include <set> #include <string> #include <assert.h> using namespace std; set<string> done; void dump_header(string header) { if (done.find(header) != done.end()) return; done.insert(header); FILE *f = fopen(header.c_str(), "r"); if (f == NULL) { fprintf(stderr, "Could not open header %s.\n", header.c_str()); exit(1); } char line[1024]; while (fgets(line, 1024, f)) { if (strncmp(line, "#include \"", 10) == 0) { char *sub_header = line + 10; for (int i = 0; i < 1014; i++) { if (sub_header[i] == '"') sub_header[i] = 0; } size_t slash_pos = header.rfind('/'); std::string path; if (slash_pos != std::string::npos) path = header.substr(0, slash_pos + 1); dump_header(path + sub_header); } else { fputs(line, stdout); } } fclose(f); } int main(int argc, char **headers) { for (int i = 1; i < argc; i++) { dump_header(headers[i]); } return 0; }
#include <cstdlib> #include <stdio.h> #include <string.h> #include <set> #include <string> #include <assert.h> std::set<std::string> done; void dump_header(std::string header) { if (done.find(header) != done.end()) return; done.insert(header); FILE *f = fopen(header.c_str(), "r"); if (f == NULL) { fprintf(stderr, "Could not open header %s.\n", header.c_str()); exit(1); } char line[1024]; while (fgets(line, 1024, f)) { if (strncmp(line, "#include \"", 10) == 0) { char *sub_header = line + 10; for (int i = 0; i < 1014; i++) { if (sub_header[i] == '"') sub_header[i] = 0; } size_t slash_pos = header.rfind('/'); std::string path; if (slash_pos != std::string::npos) path = header.substr(0, slash_pos + 1); dump_header(path + sub_header); } else { fputs(line, stdout); } } fclose(f); } int main(int argc, char **headers) { for (int i = 1; i < argc; i++) { dump_header(headers[i]); } return 0; }
Create context using DEFAULT instead of CPU for OpenCL backend
#include <ctx.hpp> #include <cl.hpp> #include <vector> namespace opencl { using std::vector; using cl::Platform; using cl::Device; void ctxCB(const char *errinfo, const void *private_info, size_t cb, void *user_data) { printf("Context Error: %s\n", errinfo); fflush(stdout); } const cl::Context& getCtx(unsigned char idx) { static std::vector<cl::Platform> platforms(0); static std::vector<cl::Context> contexts(0); if(contexts.empty()) { Platform::get(&platforms); for(auto platform : platforms) { vector<cl_context_properties> prop = {CL_CONTEXT_PLATFORM, (cl_context_properties)platform(), 0}; contexts.emplace_back(CL_DEVICE_TYPE_CPU, &prop.front(), ctxCB); } } return contexts[idx]; } cl::CommandQueue& getQueue(unsigned char idx) { static std::vector<cl::CommandQueue> queues; if(queues.empty()) { queues.emplace_back(getCtx(0)); } return queues[idx]; } }
#include <ctx.hpp> #include <cl.hpp> #include <vector> namespace opencl { using std::vector; using cl::Platform; using cl::Device; void ctxCB(const char *errinfo, const void *private_info, size_t cb, void *user_data) { printf("Context Error: %s\n", errinfo); fflush(stdout); } const cl::Context& getCtx(unsigned char idx) { static std::vector<cl::Platform> platforms(0); static std::vector<cl::Context> contexts(0); if(contexts.empty()) { Platform::get(&platforms); for(auto platform : platforms) { vector<cl_context_properties> prop = {CL_CONTEXT_PLATFORM, (cl_context_properties)platform(), 0}; contexts.emplace_back(CL_DEVICE_TYPE_DEFAULT, &prop.front(), ctxCB); } } return contexts[idx]; } cl::CommandQueue& getQueue(unsigned char idx) { static std::vector<cl::CommandQueue> queues; if(queues.empty()) { queues.emplace_back(getCtx(0)); } return queues[idx]; } }
Return 0 instead of NULL for a non-pointer type. Eliminates a warning in GCC.
#include "SkTypeface.h" // ===== Begin Chrome-specific definitions ===== uint32_t SkTypeface::UniqueID(const SkTypeface* face) { return NULL; } void SkTypeface::serialize(SkWStream* stream) const { } SkTypeface* SkTypeface::Deserialize(SkStream* stream) { return NULL; } // ===== End Chrome-specific definitions =====
#include "SkTypeface.h" // ===== Begin Chrome-specific definitions ===== uint32_t SkTypeface::UniqueID(const SkTypeface* face) { return 0; } void SkTypeface::serialize(SkWStream* stream) const { } SkTypeface* SkTypeface::Deserialize(SkStream* stream) { return NULL; } // ===== End Chrome-specific definitions =====
Add test code for Sphere intersection.
#include "gtest/gtest.h" #include "../include/rainy.h" using namespace rainy; TEST(SphereTest, InstanceTest) { Sphere sp(1.0, Vector3(0.0, 0.0, 0.0), Color(), Color(0.75, 0.75, 0.75), REFLECTION_DIFFUSE); EXPECT_EQ(0.0, sp.center().x()); EXPECT_EQ(0.0, sp.center().y()); EXPECT_EQ(0.0, sp.center().z()); HitPoint hitpoint; sp.intersect(Ray(Vector3(10.0, 0.0, 0.0), Vector3(-1.0, 0.0, 0.0)), hitpoint); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
#include "gtest/gtest.h" #include "../include/rainy.h" using namespace rainy; TEST(SphereTest, InstanceTest) { Sphere sp(2.0, Vector3(0.0, 0.0, 0.0), Color(), Color(0.75, 0.75, 0.75), REFLECTION_DIFFUSE); EXPECT_EQ(0.0, sp.center().x()); EXPECT_EQ(0.0, sp.center().y()); EXPECT_EQ(0.0, sp.center().z()); EXPECT_EQ(0.0, sp.emission().x()); EXPECT_EQ(0.0, sp.emission().y()); EXPECT_EQ(0.0, sp.emission().z()); EXPECT_EQ(0.75, sp.color().x()); EXPECT_EQ(0.75, sp.color().y()); EXPECT_EQ(0.75, sp.color().z()); EXPECT_EQ(REFLECTION_DIFFUSE, sp.reftype()); HitPoint hitpoint; EXPECT_TRUE(sp.intersect(Ray(Vector3(10.0, 0.0, 0.0), Vector3(-1.0, 0.0, 0.0)), hitpoint)); EXPECT_EQ(2.0, hitpoint.position().x()); EXPECT_EQ(0.0, hitpoint.position().y()); EXPECT_EQ(0.0, hitpoint.position().z()); EXPECT_EQ(1.0, hitpoint.normal().x()); EXPECT_EQ(0.0, hitpoint.normal().y()); EXPECT_EQ(0.0, hitpoint.normal().z()); EXPECT_FALSE(sp.intersect(Ray(Vector3(10.0, 0.0, 0.0), Vector3(0.0, 1.0, 0.0)), hitpoint)); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
Fix leak of PlatformHandleDispatchers in Mojo IPC
// Copyright (c) 2015 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 "ipc/mojo/ipc_mojo_handle_attachment.h" #include "ipc/ipc_message_attachment_set.h" #include "third_party/mojo/src/mojo/edk/embedder/embedder.h" namespace IPC { namespace internal { MojoHandleAttachment::MojoHandleAttachment(mojo::ScopedHandle handle) : handle_(handle.Pass()) { } MojoHandleAttachment::~MojoHandleAttachment() { } MessageAttachment::Type MojoHandleAttachment::GetType() const { return TYPE_MOJO_HANDLE; } #if defined(OS_POSIX) base::PlatformFile MojoHandleAttachment::TakePlatformFile() { mojo::embedder::ScopedPlatformHandle platform_handle; MojoResult unwrap_result = mojo::embedder::PassWrappedPlatformHandle( handle_.release().value(), &platform_handle); if (unwrap_result != MOJO_RESULT_OK) { LOG(ERROR) << "Pipe failed to covert handles. Closing: " << unwrap_result; return -1; } return platform_handle.release().fd; } #endif // OS_POSIX mojo::ScopedHandle MojoHandleAttachment::TakeHandle() { return handle_.Pass(); } } // namespace internal } // namespace IPC
// Copyright (c) 2015 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 "ipc/mojo/ipc_mojo_handle_attachment.h" #include "ipc/ipc_message_attachment_set.h" #include "third_party/mojo/src/mojo/edk/embedder/embedder.h" namespace IPC { namespace internal { MojoHandleAttachment::MojoHandleAttachment(mojo::ScopedHandle handle) : handle_(handle.Pass()) { } MojoHandleAttachment::~MojoHandleAttachment() { } MessageAttachment::Type MojoHandleAttachment::GetType() const { return TYPE_MOJO_HANDLE; } #if defined(OS_POSIX) base::PlatformFile MojoHandleAttachment::TakePlatformFile() { mojo::embedder::ScopedPlatformHandle platform_handle; MojoResult unwrap_result = mojo::embedder::PassWrappedPlatformHandle( handle_.get().value(), &platform_handle); handle_.reset(); if (unwrap_result != MOJO_RESULT_OK) { LOG(ERROR) << "Pipe failed to covert handles. Closing: " << unwrap_result; return -1; } return platform_handle.release().fd; } #endif // OS_POSIX mojo::ScopedHandle MojoHandleAttachment::TakeHandle() { return handle_.Pass(); } } // namespace internal } // namespace IPC
Add python binding to ContextError
#include "xchainer/python/error.h" #include "xchainer/error.h" #include "xchainer/python/common.h" namespace xchainer { namespace py = pybind11; // standard convention void InitXchainerError(pybind11::module& m) { py::register_exception<XchainerError>(m, "XchainerError"); py::register_exception<BackendError>(m, "BackendError"); py::register_exception<DeviceError>(m, "DeviceError"); py::register_exception<DtypeError>(m, "DtypeError"); py::register_exception<DimensionError>(m, "DimensionError"); } } // namespace xchainer
#include "xchainer/python/error.h" #include "xchainer/error.h" #include "xchainer/python/common.h" namespace xchainer { namespace py = pybind11; // standard convention void InitXchainerError(pybind11::module& m) { py::register_exception<XchainerError>(m, "XchainerError"); py::register_exception<ContextError>(m, "ContextError"); py::register_exception<BackendError>(m, "BackendError"); py::register_exception<DeviceError>(m, "DeviceError"); py::register_exception<DtypeError>(m, "DtypeError"); py::register_exception<DimensionError>(m, "DimensionError"); } } // namespace xchainer
Load deferred import libraries when building the snapshot
// Copyright 2015 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 "sky/tools/sky_snapshot/vm.h" #include "base/logging.h" #include "sky/tools/sky_snapshot/loader.h" #include "sky/tools/sky_snapshot/logging.h" extern "C" { extern void* kDartVmIsolateSnapshotBuffer; extern void* kDartIsolateSnapshotBuffer; } static const char* kDartArgs[] = { "--enable_mirrors=false", }; void InitDartVM() { CHECK(Dart_SetVMFlags(arraysize(kDartArgs), kDartArgs)); CHECK( Dart_Initialize(reinterpret_cast<uint8_t*>(&kDartVmIsolateSnapshotBuffer), nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr) == nullptr); } Dart_Isolate CreateDartIsolate() { CHECK(kDartIsolateSnapshotBuffer); char* error = nullptr; Dart_Isolate isolate = Dart_CreateIsolate( "dart:snapshot", "main", reinterpret_cast<uint8_t*>(&kDartIsolateSnapshotBuffer), nullptr, nullptr, &error); CHECK(isolate) << error; CHECK(!LogIfError(Dart_SetLibraryTagHandler(HandleLibraryTag))); Dart_ExitIsolate(); return isolate; }
// Copyright 2015 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 "sky/tools/sky_snapshot/vm.h" #include "base/logging.h" #include "sky/tools/sky_snapshot/loader.h" #include "sky/tools/sky_snapshot/logging.h" extern "C" { extern void* kDartVmIsolateSnapshotBuffer; extern void* kDartIsolateSnapshotBuffer; } static const char* kDartArgs[] = { "--enable_mirrors=false", "--load_deferred_eagerly=true", }; void InitDartVM() { CHECK(Dart_SetVMFlags(arraysize(kDartArgs), kDartArgs)); CHECK( Dart_Initialize(reinterpret_cast<uint8_t*>(&kDartVmIsolateSnapshotBuffer), nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr) == nullptr); } Dart_Isolate CreateDartIsolate() { CHECK(kDartIsolateSnapshotBuffer); char* error = nullptr; Dart_Isolate isolate = Dart_CreateIsolate( "dart:snapshot", "main", reinterpret_cast<uint8_t*>(&kDartIsolateSnapshotBuffer), nullptr, nullptr, &error); CHECK(isolate) << error; CHECK(!LogIfError(Dart_SetLibraryTagHandler(HandleLibraryTag))); Dart_ExitIsolate(); return isolate; }
Use the stack size provided by configure.
#include <kernel/kernconf.hh> USDK_API kernconf_type kernconf = { // Default is large enough until we enable a mechanism to dynamically // reallocate task space on demand. /* .default_stack_size = */ 128 * 1024, /* .minimum_stack_size = */ 4 * 1024 };
#include <kernel/config.h> #include <kernel/kernconf.hh> USDK_API kernconf_type kernconf = { // Default is large enough until we enable a mechanism to dynamically // reallocate task space on demand. /* .default_stack_size = */ URBI_KERNEL_STACK_SIZE * 1024, /* .minimum_stack_size = */ 4 * 1024 };
Fix warn_once to effectively warn once
// cfiles, an analysis frontend for the Chemfiles library // Copyright (C) Guillaume Fraux and contributors -- BSD license #include <iostream> #include <set> #include "warnings.hpp" void warn(std::string message) { std::cerr << "[cfiles] " << message << std::endl; } void warn_once(std::string message) { static std::set<std::string> already_seen; auto seen = already_seen.insert(message).second; if (!seen) { warn(message); } }
// cfiles, an analysis frontend for the Chemfiles library // Copyright (C) Guillaume Fraux and contributors -- BSD license #include <iostream> #include <set> #include "warnings.hpp" void warn(std::string message) { std::cerr << "[cfiles] " << message << std::endl; } void warn_once(std::string message) { static std::set<std::string> ALREADY_SEEN; auto not_seen = ALREADY_SEEN.insert(message).second; if (not_seen) { warn(message); } }
Sort ray-intersected boxes by distance
#include "planning/simulation/interactable_geometry.hh" namespace jcc { namespace simulation { std::vector<RayIntersection> InteractableGeometry::all_intersections( const geometry::Ray& ray) { std::vector<RayIntersection> intersections; for (const auto& bbox : aabb_) { const auto intersection = bbox.second.bbox.intersect(ray); if (intersection.intersected) { intersections.push_back( {bbox.first, intersection.distance, ray(intersection.distance)}); } } return intersections; } std::vector<BoundingBoxIntersection> InteractableGeometry::all_intersections( const InteractableGeometry::BBox3& bbox) { return {}; } } // namespace simulation } // namespace jcc
#include "planning/simulation/interactable_geometry.hh" #include <algorithm> namespace jcc { namespace simulation { std::vector<RayIntersection> InteractableGeometry::all_intersections( const geometry::Ray& ray) { std::vector<RayIntersection> intersections; for (const auto& bbox : aabb_) { const auto intersection = bbox.second.bbox.intersect(ray); if (intersection.intersected) { intersections.push_back( {bbox.first, intersection.distance, ray(intersection.distance)}); } } std::sort(intersections.begin(), intersections.end(), [](const RayIntersection& a, const RayIntersection& b) -> bool { return a.distance < b.distance; }); return intersections; } std::vector<BoundingBoxIntersection> InteractableGeometry::all_intersections( const InteractableGeometry::BBox3& other) { std::vector<BoundingBoxIntersection> intersections; for (const auto& bbox : aabb_) { const auto intersection = bbox.second.bbox.intersect(other); if (intersection.contained) { intersections.push_back({bbox.first, intersection.contained}); } } return intersections; } } // namespace simulation } // namespace jcc
Mark the recent variant test as UNSUPPORTED for C++ before 17
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <array> // template <size_t I, class T> struct variant_alternative; // undefined // template <size_t I, class T> struct variant_alternative<I, const T>; // template <size_t I, class T> struct variant_alternative<I, volatile T>; // template <size_t I, class T> struct variant_alternative<I, const volatile T>; // template <size_t I, class T> // using variant_alternative_t = typename variant_alternative<I, T>::type; // // template <size_t I, class... Types> // struct variant_alternative<I, variant<Types...>>; #include <variant> #include <cassert> int main() { { typedef std::variant<int, double> T; std::variant_alternative<2, T>::type foo; // expected-note {{requested here}} // expected-error@variant:* {{static_assert failed "Index out of bounds in std::variant_alternative<>"}} } }
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // <variant> // UNSUPPORTED: c++98, c++03, c++11, c++14 // template <size_t I, class T> struct variant_alternative; // undefined // template <size_t I, class T> struct variant_alternative<I, const T>; // template <size_t I, class T> struct variant_alternative<I, volatile T>; // template <size_t I, class T> struct variant_alternative<I, const volatile T>; // template <size_t I, class T> // using variant_alternative_t = typename variant_alternative<I, T>::type; // // template <size_t I, class... Types> // struct variant_alternative<I, variant<Types...>>; #include <variant> #include <cassert> int main() { { typedef std::variant<int, double> T; std::variant_alternative<2, T>::type foo; // expected-note {{requested here}} // expected-error@variant:* {{static_assert failed "Index out of bounds in std::variant_alternative<>"}} } }
Revert text-to-speech-test from using exact memory manager
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/external/gtest.h> #include <aws/core/Aws.h> #include <aws/testing/platform/PlatformTesting.h> #include <aws/testing/MemoryTesting.h> int main(int argc, char** argv) { Aws::SDKOptions options; options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Trace; AWS_BEGIN_MEMORY_TEST_EX(options, 1024, 128); Aws::Testing::InitPlatformTest(options); Aws::InitAPI(options); ::testing::InitGoogleTest(&argc, argv); int exitCode = RUN_ALL_TESTS(); Aws::ShutdownAPI(options); AWS_END_MEMORY_TEST_EX; Aws::Testing::ShutdownPlatformTest(options); return exitCode; }
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/external/gtest.h> #include <aws/core/Aws.h> #include <aws/testing/platform/PlatformTesting.h> //#include <aws/testing/MemoryTesting.h> int main(int argc, char** argv) { Aws::SDKOptions options; options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Trace; //AWS_BEGIN_MEMORY_TEST_EX(options, 1024, 128); Aws::Testing::InitPlatformTest(options); Aws::InitAPI(options); ::testing::InitGoogleTest(&argc, argv); int exitCode = RUN_ALL_TESTS(); Aws::ShutdownAPI(options); ///AWS_END_MEMORY_TEST_EX; Aws::Testing::ShutdownPlatformTest(options); return exitCode; }
Make sure Point is made of right-sized coord's.
// Copyright (c) 2022 Ultimaker B.V. // CuraEngine is released under the terms of the AGPLv3 or higher. #include "utils/IntPoint.h" #include <gtest/gtest.h> // NOLINTBEGIN(*-magic-numbers) namespace cura { TEST(IntPointTest, TestRotationMatrix) { PointMatrix rot2d(90); Point3Matrix rot_homogeneous(rot2d); Point a(20, 10); Point b(30, 20); Point translated = Point3Matrix::translate(-a).apply(b); Point rotated = rot_homogeneous.apply(translated); Point rotated_in_place = Point3Matrix::translate(a).apply(rotated); Point3Matrix all_in_one = Point3Matrix::translate(a).compose(rot_homogeneous).compose(Point3Matrix::translate(-a)); Point rotated_in_place_2 = all_in_one.apply(b); ASSERT_EQ(rotated_in_place, rotated_in_place_2) << "Matrix composition with translate and rotate failed."; } } // namespace cura // NOLINTEND(*-magic-numbers)
// Copyright (c) 2022 Ultimaker B.V. // CuraEngine is released under the terms of the AGPLv3 or higher. #include "utils/IntPoint.h" #include <gtest/gtest.h> // NOLINTBEGIN(*-magic-numbers) namespace cura { TEST(IntPointTest, TestRotationMatrix) { PointMatrix rot2d(90); Point3Matrix rot_homogeneous(rot2d); Point a(20, 10); Point b(30, 20); Point translated = Point3Matrix::translate(-a).apply(b); Point rotated = rot_homogeneous.apply(translated); Point rotated_in_place = Point3Matrix::translate(a).apply(rotated); Point3Matrix all_in_one = Point3Matrix::translate(a).compose(rot_homogeneous).compose(Point3Matrix::translate(-a)); Point rotated_in_place_2 = all_in_one.apply(b); ASSERT_EQ(rotated_in_place, rotated_in_place_2) << "Matrix composition with translate and rotate failed."; } TEST(IntPointTest, TestSize) { ASSERT_EQ(sizeof(Point::X), sizeof(coord_t)); ASSERT_LE(sizeof(coord_t), sizeof(int64_t)); } } // namespace cura // NOLINTEND(*-magic-numbers)
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
Fix bug when checking log level.
#include "logger.h" namespace lightstep { //------------------------------------------------------------------------------ // LogDefault //------------------------------------------------------------------------------ static void LogDefault(LogLevel log_level, opentracing::string_view message) noexcept try { std::ostringstream oss; switch (log_level) { case LogLevel::debug: oss << "Debug: "; break; case LogLevel::info: oss << "Info: "; break; case LogLevel::warn: oss << "Warn: "; break; case LogLevel::error: oss << "Error: "; break; case LogLevel::off: /* This should never be reached. */ return; } oss << message << '\n'; std::cerr << oss.str(); } catch (const std::exception& /*e*/) { // Ignore errors. } //------------------------------------------------------------------------------ // Constructor //------------------------------------------------------------------------------ Logger::Logger() : logger_sink_{LogDefault} {} Logger::Logger( std::function<void(LogLevel, opentracing::string_view)>&& logger_sink) { if (logger_sink) { logger_sink_ = std::move(logger_sink); } else { logger_sink_ = LogDefault; } } //------------------------------------------------------------------------------ // Log //------------------------------------------------------------------------------ void Logger::Log(LogLevel level, opentracing::string_view message) noexcept try { if (static_cast<int>(level) <= static_cast<int>(level_)) { logger_sink_(level, message); } } catch (const std::exception& /*e*/) { // Ignore exceptions. } } // namespace lightstep
#include "logger.h" namespace lightstep { //------------------------------------------------------------------------------ // LogDefault //------------------------------------------------------------------------------ static void LogDefault(LogLevel log_level, opentracing::string_view message) noexcept try { std::ostringstream oss; switch (log_level) { case LogLevel::debug: oss << "Debug: "; break; case LogLevel::info: oss << "Info: "; break; case LogLevel::warn: oss << "Warn: "; break; case LogLevel::error: oss << "Error: "; break; case LogLevel::off: /* This should never be reached. */ return; } oss << message << '\n'; std::cerr << oss.str(); } catch (const std::exception& /*e*/) { // Ignore errors. } //------------------------------------------------------------------------------ // Constructor //------------------------------------------------------------------------------ Logger::Logger() : logger_sink_{LogDefault} {} Logger::Logger( std::function<void(LogLevel, opentracing::string_view)>&& logger_sink) { if (logger_sink) { logger_sink_ = std::move(logger_sink); } else { logger_sink_ = LogDefault; } } //------------------------------------------------------------------------------ // Log //------------------------------------------------------------------------------ void Logger::Log(LogLevel level, opentracing::string_view message) noexcept try { if (static_cast<int>(level) >= static_cast<int>(level_)) { logger_sink_(level, message); } } catch (const std::exception& /*e*/) { // Ignore exceptions. } } // namespace lightstep
Enable this test for PPC64.
// RUN: %clangxx_msan -O0 %s -c -o %t // RUN: %clangxx_msan -O3 %s -c -o %t // Regression test for MemorySanitizer instrumentation of a select instruction // with vector arguments. #if defined(__x86_64__) #include <emmintrin.h> __m128d select(bool b, __m128d c, __m128d d) { return b ? c : d; } #elif defined (__mips64) typedef double __w64d __attribute__ ((vector_size(16))); __w64d select(bool b, __w64d c, __w64d d) { return b ? c : d; } #endif
// RUN: %clangxx_msan -O0 %s -c -o %t // RUN: %clangxx_msan -O3 %s -c -o %t // Regression test for MemorySanitizer instrumentation of a select instruction // with vector arguments. #if defined(__x86_64__) #include <emmintrin.h> __m128d select(bool b, __m128d c, __m128d d) { return b ? c : d; } #elif defined (__mips64) || defined (__powerpc64__) typedef double __w64d __attribute__ ((vector_size(16))); __w64d select(bool b, __w64d c, __w64d d) { return b ? c : d; } #endif
Make sure entities UID space don't clash between server & client.
#include "entity.h" using namespace sf; Entity::Entity(EntityShape shape0, Engine *engine0) { shape = shape0; position.x = 0; position.y = 0; isKilledFlag = false; engine = engine0; UID = ++globalUID; } Entity::~Entity() { engine = NULL; } Uint32 Entity::globalUID = 0; Uint32 Entity::getUID(void) const {return UID;} void Entity::setUID(Uint32 uid) {UID = uid;} void Entity::useUpperUID(void) { globalUID |= 0x80000000; }
#include "entity.h" using namespace sf; Entity::Entity(EntityShape shape0, Engine *engine0) { shape = shape0; position.x = 0; position.y = 0; isKilledFlag = false; engine = engine0; if (globalUID & 0x80000000) { globalUID = (globalUID+1) | 0x80000000; } else { globalUID = (globalUID+1) & (~0x80000000); } UID = globalUID; } Entity::~Entity() { engine = NULL; } Uint32 Entity::globalUID = 0; Uint32 Entity::getUID(void) const {return UID;} void Entity::setUID(Uint32 uid) {UID = uid;} void Entity::useUpperUID(void) { globalUID |= 0x80000000; }
Revert "Guard inclusion of boost/python.hpp"
// a wrapper to load netgen-dll into python #include <iostream> #ifdef NG_PYTHON #include <boost/python.hpp> #endif #ifdef WIN32 #define DLL_HEADER __declspec(dllimport) #else #define DLL_HEADER #endif void DLL_HEADER ExportNetgenMeshing(); void DLL_HEADER ExportMeshVis(); void DLL_HEADER ExportCSG(); void DLL_HEADER ExportCSGVis(); void DLL_HEADER ExportGeom2d(); #ifdef NG_PYTHON BOOST_PYTHON_MODULE(libngpy) { ExportCSG(); ExportCSGVis(); ExportNetgenMeshing(); ExportMeshVis(); ExportGeom2d(); } #endif
// a wrapper to load netgen-dll into python #include <iostream> #include <boost/python.hpp> #ifdef WIN32 #define DLL_HEADER __declspec(dllimport) #else #define DLL_HEADER #endif void DLL_HEADER ExportNetgenMeshing(); void DLL_HEADER ExportMeshVis(); void DLL_HEADER ExportCSG(); void DLL_HEADER ExportCSGVis(); void DLL_HEADER ExportGeom2d(); BOOST_PYTHON_MODULE(libngpy) { ExportCSG(); ExportCSGVis(); ExportNetgenMeshing(); ExportMeshVis(); ExportGeom2d(); }
Remove trailing whitespace from example source code
#include <QtWidgets/QApplication> #include "mainwindow.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }
#include <QtWidgets/QApplication> #include "mainwindow.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }
Put test in Annwvyn namespace
#include "engineBootstrap.hpp" #include <catch/catch.hpp> TEST_CASE("Test glTF Loading") { auto GameEngine = Annwvyn::bootstrapTestEngine("GlTF Test"); auto object = Annwvyn::AnnGetGameObjectManager()->createGameObject("Avocado.glb"); object->setPosition(0, 1.6, 9); REQUIRE(object != nullptr); GameEngine->initPlayerRoomscalePhysics(); Annwvyn::AnnGetEventManager()->useDefaultEventListener(); const auto counter = 60*5; auto frame = 0; while(frame < counter && !GameEngine->checkNeedToQuit()) { object->setOrientation(Annwvyn::AnnQuaternion(Annwvyn::AnnDegree(frame * 5), Annwvyn::AnnVect3::UNIT_Y)); frame++; GameEngine->refresh(); } }
#include "engineBootstrap.hpp" #include <catch/catch.hpp> namespace Annwvyn { TEST_CASE("Test glTF Loading") { auto GameEngine = Annwvyn::bootstrapTestEngine("GlTF Test"); auto object = Annwvyn::AnnGetGameObjectManager()->createGameObject("Avocado.glb"); object->setPosition(0, 1.6, 9); object->setScale(3, 3, 3); REQUIRE(object != nullptr); GameEngine->initPlayerRoomscalePhysics(); Annwvyn::AnnGetEventManager()->useDefaultEventListener(); const auto counter = 60 * 5; auto frame = 0; while(frame < counter && !GameEngine->checkNeedToQuit()) { object->setOrientation(Annwvyn::AnnQuaternion(Annwvyn::AnnDegree(frame * 5), Annwvyn::AnnVect3::UNIT_Y)); frame++; GameEngine->refresh(); } } }
Fix clone of props for legacy interop component
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "LegacyViewManagerInteropViewProps.h" namespace facebook { namespace react { LegacyViewManagerInteropViewProps::LegacyViewManagerInteropViewProps( const LegacyViewManagerInteropViewProps &sourceProps, const RawProps &rawProps) : ViewProps(sourceProps, rawProps), otherProps((folly::dynamic)rawProps) {} } // namespace react } // namespace facebook
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "LegacyViewManagerInteropViewProps.h" namespace facebook { namespace react { static folly::dynamic recursiveMerge( folly::dynamic const &lhs, folly::dynamic const &rhs) { auto copy = lhs; copy.merge_patch(rhs); return copy; } LegacyViewManagerInteropViewProps::LegacyViewManagerInteropViewProps( const LegacyViewManagerInteropViewProps &sourceProps, const RawProps &rawProps) : ViewProps(sourceProps, rawProps), otherProps( recursiveMerge(sourceProps.otherProps, (folly::dynamic)rawProps)) {} } // namespace react } // namespace facebook
Make sure to parse gtest_* flags before other flags when running tests.
// Copyright 2012, Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Author: tomasz.kaftal@gmail.com (Tomasz Kaftal) // // This file contains a custom googletest main method to launch tests. // It launches the Supersonic initialisation routine. #include <iostream> #include "supersonic/base/infrastructure/init.h" #include "gtest/gtest.h" GTEST_API_ int main(int argc, char** argv) { std::cout << "Running main() from supersonic_test_main.cc\n"; supersonic::SupersonicInit(&argc, &argv); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
// Copyright 2012, Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Author: tomasz.kaftal@gmail.com (Tomasz Kaftal) // // This file contains a custom googletest main method to launch tests. // It launches the Supersonic initialisation routine. #include <iostream> #include "supersonic/base/infrastructure/init.h" #include "gtest/gtest.h" GTEST_API_ int main(int argc, char** argv) { std::cout << "Running main() from supersonic_test_main.cc\n"; // Make sure to parse gtest_* flags before parsing other flags. testing::InitGoogleTest(&argc, argv); supersonic::SupersonicInit(&argc, &argv); return RUN_ALL_TESTS(); }
Work around Clang bug introduced in r324062
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // <fstream> // template <class charT, class traits = char_traits<charT> > // class basic_fstream // The char type of the stream and the char_type of the traits have to match #include <fstream> int main() { std::basic_fstream<char, std::char_traits<wchar_t> > f; // expected-error-re@ios:* {{static_assert failed{{.*}} "traits_type::char_type must be the same type as CharT"}} // expected-error-re@streambuf:* {{static_assert failed{{.*}} "traits_type::char_type must be the same type as CharT"}} }
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // <fstream> // template <class charT, class traits = char_traits<charT> > // class basic_fstream // The char type of the stream and the char_type of the traits have to match #include <fstream> int main() { std::basic_fstream<char, std::char_traits<wchar_t> > f; // expected-error-re@ios:* {{static_assert failed{{.*}} "traits_type::char_type must be the same type as CharT"}} // expected-error-re@streambuf:* {{static_assert failed{{.*}} "traits_type::char_type must be the same type as CharT"}} // FIXME: As of commit r324062 Clang incorrectly generates a diagnostic about mismatching // exception specifications for types which are already invalid for one reason or another. // For now we tolerate this diagnostic. // expected-error@ostream:* 0-1 {{exception specification of overriding function is more lax than base version}} }
Change display of int exception
#include "main.hpp" int main() { DEV::KeepConsoleOpen keepConsoleOpen; keepConsoleOpen.setKeyRequirement(DEV::KeepConsoleOpen::Escape); try { Game game; game.run(); } catch (int e) { DEV::printLine("Exception caught:\n\"" + pl::stringFrom(e) + "\""); return EXIT_FAILURE; } catch (char* e) { DEV::printLine("Exception caught:\n\"" + std::string(e) + "\""); return EXIT_FAILURE; } catch (...) { DEV::printLine("Unknown exception caught!"); return EXIT_FAILURE; } keepConsoleOpen.allowToClose(); return EXIT_SUCCESS; }
#include "main.hpp" int main() { DEV::KeepConsoleOpen keepConsoleOpen; keepConsoleOpen.setKeyRequirement(DEV::KeepConsoleOpen::Escape); try { Game game; game.run(); } catch (int e) { DEV::printLine("Exception caught: " + pl::stringFrom(e)); return EXIT_FAILURE; } catch (char* e) { DEV::printLine("Exception caught:\n\"" + std::string(e) + "\""); return EXIT_FAILURE; } catch (...) { DEV::printLine("Unknown exception caught!"); return EXIT_FAILURE; } keepConsoleOpen.allowToClose(); return EXIT_SUCCESS; }
Fix mistake of using size instead of capacity.
#include "misc_util.h" namespace dlib { void string_fmt_time(std::string& ret) { time_t now = time(NULL); struct tm *t = localtime(&now); while(!strftime((char *)ret.data(), ret.capacity(), "%Y:%m:%d %H:%M", t)) ret.reserve(ret.size() << 1); } }
#include "misc_util.h" namespace dlib { void string_fmt_time(std::string& ret) { time_t now = time(NULL); struct tm *t = localtime(&now); while(!strftime((char *)ret.data(), ret.capacity(), "%Y:%m:%d %H:%M", t)) ret.reserve(ret.capacity() ? ret.capacity() << 1: 16); } }
Initialize the fields of the sigaction structure.
/* -*- mode:linux -*- */ /** * \file timeout.cc * * * * \author Ethan Burns * \date 2008-12-16 */ #include <iostream> #include <signal.h> #include <stdlib.h> #include <unistd.h> using namespace std; void alarm_action(int sig) { cout << "No Solution" << endl << "cost: infinity" << endl << "length: infinity" << endl << "wall_time: infinity" << endl << "CPU_time: infinity" << endl << "generated: infinity" << endl << "expanded: infinity" << endl; exit(EXIT_SUCCESS); } void timeout(unsigned int sec) { struct sigaction sa; sa.sa_handler = alarm_action; sigaction(SIGALRM, &sa, NULL); alarm(sec); }
/* -*- mode:linux -*- */ /** * \file timeout.cc * * * * \author Ethan Burns * \date 2008-12-16 */ #include <iostream> #include <signal.h> #include <stdlib.h> #include <unistd.h> using namespace std; void alarm_action(int sig) { cout << "No Solution" << endl << "cost: infinity" << endl << "length: infinity" << endl << "wall_time: infinity" << endl << "CPU_time: infinity" << endl << "generated: infinity" << endl << "expanded: infinity" << endl; exit(EXIT_SUCCESS); } void timeout(unsigned int sec) { struct sigaction sa; sa.sa_flags = 0; sa.sa_sigaction = NULL; sa.sa_restorer = NULL; sa.sa_handler = alarm_action; sigfillset(&sa.sa_mask); sigaction(SIGALRM, &sa, NULL); alarm(sec); }
Add github link, make code narrower.
#include <QPushButton> #include <QHBoxLayout> #include <QApplication> int main(int argc, char *argv[]) { QApplication a{argc, argv}; QWidget w; QHBoxLayout layout{&w}; QPushButton button1{"Default"}; button1.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum); layout.addWidget(&button1); QPushButton button2{"Styled"}; button2.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); button2.setStyleSheet( "* { border: 2px solid #8f8f91; border-radius: 12px; background-color: #d02020; }" "*:pressed { background-color: #f6f7fa; }"); layout.addWidget(&button2); auto pal = w.palette(); pal.setBrush(QPalette::Background, Qt::darkBlue); w.setPalette(pal); w.show(); return a.exec(); }
// https://github.com/KubaO/stackoverflown/tree/master/questions/styledbutton-20642553 #include <QPushButton> #include <QHBoxLayout> #include <QApplication> int main(int argc, char *argv[]) { QApplication a{argc, argv}; QWidget w; QHBoxLayout layout{&w}; QPushButton button1{"Default"}; button1.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum); layout.addWidget(&button1); QPushButton button2{"Styled"}; button2.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); button2.setStyleSheet( "* { border: 2px solid #8f8f91; border-radius: 12px; background-color: #d02020; }" "*:pressed { background-color: #f6f7fa; }"); layout.addWidget(&button2); auto pal = w.palette(); pal.setBrush(QPalette::Background, Qt::darkBlue); w.setPalette(pal); w.show(); return a.exec(); }
Read file and finish tutorial
// Copyright 2015 Matt Heard // http://mattheard.net // matt@mattheard.net // @mattheard #include <iostream> #include <string> int main(int argc, char **argv) { const int expectedNumArgs = 2; if (argc != expectedNumArgs) { using std::string; const string cmdName = "DisplayImage"; const string argsDesc = " <Image_Path>"; std::cout << "Usage: " << cmdName << argsDesc << 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> int main(int argc, char **argv) { using std::string; const int expectedNumArgs = 2; if (argc != expectedNumArgs) { const string cmdName = "DisplayImage"; 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; } // The tutorial calls `namedWindow` and `imshow` to display the input image // in a GUI window, but as I'm currently running these tutorials on a // headless Raspberry Pi, I will not do that. Where future tutorials show // modified images, I will write them to files instead with `imwrite`, and // view them on a browser across my local network. return 0; }
Remove the free of behaviors to the plans
/* * Behavior.cpp * * Created on: Mar 25, 2014 * Author: user */ #include "Behavior.h" Behavior::Behavior(Robot* robot) { // TODO Auto-generated constructor stub _robot = robot; } Behavior* Behavior::addNextBehavior(Behavior* behavior) { this->_nextBehaviors.push_back(behavior); } Behavior* Behavior::getNextBehavior() { for (vector<Behavior*>::const_iterator iter = _nextBehaviors.begin(); iter != _nextBehaviors.end(); iter++) { Behavior* currentBehavior = *iter; if (currentBehavior->startCondition()) { return currentBehavior; } } return NULL; } Behavior::~Behavior() { for (vector<Behavior*>::const_iterator iter = _nextBehaviors.begin(); iter != _nextBehaviors.end(); iter++) { Behavior* currentBehavior = *iter; delete currentBehavior; } }
/* * Behavior.cpp * * Created on: Mar 25, 2014 * Author: user */ #include "Behavior.h" Behavior::Behavior(Robot* robot) { _robot = robot; } Behavior* Behavior::addNextBehavior(Behavior* behavior) { this->_nextBehaviors.push_back(behavior); } Behavior* Behavior::getNextBehavior() { for (vector<Behavior*>::const_iterator iter = _nextBehaviors.begin(); iter != _nextBehaviors.end(); iter++) { Behavior* currentBehavior = *iter; if (currentBehavior->startCondition()) { return currentBehavior; } } return NULL; } Behavior::~Behavior() { }
Replace use of share<0>() with share()
#include <agency/execution_policy.hpp> #include <vector> int sum(const std::vector<int>& data) { using namespace agency; return bulk_invoke(con(data.size()), [&](concurrent_agent& self, std::vector<int>& scratch) -> single_result<int> { auto i = self.index(); auto n = scratch.size(); while(n > 1) { if(i < n/2) { scratch[i] += scratch[n - i - 1]; } // wait for every agent in the group to reach this point self.wait(); // cut the number of active agents in half n -= n/2; } // the first agent returns the result if(i == 0) { return scratch[0]; } // all other agents return an ignored value return std::ignore; }, share<0>(data) ); } int main() { size_t n = 10; std::vector<int> data(n, 1); auto result = sum(data); std::cout << "sum is " << result << std::endl; assert(result == n); std::cout << "OK" << std::endl; return 0; }
#include <agency/execution_policy.hpp> #include <vector> int sum(const std::vector<int>& data) { using namespace agency; return bulk_invoke(con(data.size()), [&](concurrent_agent& self, std::vector<int>& scratch) -> single_result<int> { auto i = self.index(); auto n = scratch.size(); while(n > 1) { if(i < n/2) { scratch[i] += scratch[n - i - 1]; } // wait for every agent in the group to reach this point self.wait(); // cut the number of active agents in half n -= n/2; } // the first agent returns the result if(i == 0) { return scratch[0]; } // all other agents return an ignored value return std::ignore; }, share(data) ); } int main() { size_t n = 10; std::vector<int> data(n, 1); auto result = sum(data); std::cout << "sum is " << result << std::endl; assert(result == n); std::cout << "OK" << std::endl; return 0; }
Change system font to Noto Sans.
/* * Copyright (C) 2015 - Florent Revest <revestflo@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This 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 "controls_plugin.h" #include <QFontDatabase> #include <QGuiApplication> #include <QtQml> #include "application_p.h" #include "flatmesh.h" #include "icon.h" ControlsPlugin::ControlsPlugin(QObject *parent) : QQmlExtensionPlugin(parent) { } void ControlsPlugin::registerTypes(const char *uri) { Q_ASSERT(uri == QLatin1String("org.asteroid.controls")); QGuiApplication::setFont(QFont("Open Sans")); qmlRegisterType<Application_p>(uri, 1, 0, "Application_p"); qmlRegisterType<FlatMesh>(uri, 1, 0, "FlatMesh"); qmlRegisterType<Icon>(uri, 1, 0, "Icon"); }
/* * Copyright (C) 2015 - Florent Revest <revestflo@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This 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 "controls_plugin.h" #include <QFontDatabase> #include <QGuiApplication> #include <QtQml> #include "application_p.h" #include "flatmesh.h" #include "icon.h" ControlsPlugin::ControlsPlugin(QObject *parent) : QQmlExtensionPlugin(parent) { } void ControlsPlugin::registerTypes(const char *uri) { Q_ASSERT(uri == QLatin1String("org.asteroid.controls")); QGuiApplication::setFont(QFont("Noto Sans")); qmlRegisterType<Application_p>(uri, 1, 0, "Application_p"); qmlRegisterType<FlatMesh>(uri, 1, 0, "FlatMesh"); qmlRegisterType<Icon>(uri, 1, 0, "Icon"); }
Add a triple to this test so it passes for targets where alignof(double) really should be equal to alignof(float).
// RUN: %clang_cc1 -std=c++11 -verify %s alignas(double) void f(); // expected-error {{'alignas' attribute only applies to variables, data members and tag types}} alignas(double) unsigned char c[sizeof(double)]; // expected-note {{previous}} extern unsigned char c[sizeof(double)]; alignas(float) extern unsigned char c[sizeof(double)]; // expected-error {{different alignment}}
// RUN: %clang_cc1 -std=c++11 -verify %s -triple x86_64-linux-gnu alignas(double) void f(); // expected-error {{'alignas' attribute only applies to variables, data members and tag types}} alignas(double) unsigned char c[sizeof(double)]; // expected-note {{previous}} extern unsigned char c[sizeof(double)]; alignas(float) extern unsigned char c[sizeof(double)]; // expected-error {{different alignment}}
Update to Kate's First Prototype
#include <iostream> //Thomas' Prototypes //Hannah's Prototypes int atomic_distance (int x, int y, int z); //Kate's Prototype: defines atomic distance as combination of x, y, z coordinates int (main) { using nedit file... create new input "hannah's test changes" }
#include <iostream> //Thomas' Prototypes //Hannah's Prototypes int atomic_distance (int atom_dist_x, int atom_dist_y, int atom_dist_z); //Kate's Prototype: defines atomic distance as combination of x, y, z coordinates int (main) { using nedit file... create new input "hannah's test changes" }
Return true if the event was handled.
// // C++ Implementation: mailvieweventfilter // // Description: // // // Author: Aron Boström <aron dot bostrom at gmail dot com>, (C) 2006 // // Copyright: See COPYING file that comes with this distribution // // #include <QtDebug> #include <QResizeEvent> #include <QWidget> #include "mailvieweventfilter.h" MailViewEventFilter::MailViewEventFilter(QWidget *textedit, QWidget *viewport, QObject *parent) : QObject(parent), m_viewport(viewport), m_textedit(textedit) { } MailViewEventFilter::~MailViewEventFilter() { } bool MailViewEventFilter::eventFilter(QObject *obj, QEvent *event) { if (event->type() == QEvent::Resize) { QResizeEvent *resizeEvent = static_cast<QResizeEvent *>(event); m_viewport->resize(resizeEvent->size()); m_textedit->resize(resizeEvent->size()); qDebug() << "TEST"; } return QObject::eventFilter(obj, event); } #include "mailvieweventfilter.moc"
// // C++ Implementation: mailvieweventfilter // // Description: // // // Author: Aron Boström <aron dot bostrom at gmail dot com>, (C) 2006 // // Copyright: See COPYING file that comes with this distribution // // #include <QtDebug> #include <QResizeEvent> #include <QWidget> #include "mailvieweventfilter.h" MailViewEventFilter::MailViewEventFilter(QWidget *textedit, QWidget *viewport, QObject *parent) : QObject(parent), m_viewport(viewport), m_textedit(textedit) { } MailViewEventFilter::~MailViewEventFilter() { } bool MailViewEventFilter::eventFilter(QObject *obj, QEvent *event) { if (event->type() == QEvent::Resize) { QResizeEvent *resizeEvent = static_cast<QResizeEvent *>(event); m_viewport->resize(resizeEvent->size()); m_textedit->resize(resizeEvent->size()); qDebug() << "TEST"; return true; } return QObject::eventFilter(obj, event); } #include "mailvieweventfilter.moc"
Stop propagating shadow in blacklisted functions.
// RUN: %clangxx_msan -m64 -O0 %s -o %t && %run %t >%t.out 2>&1 // RUN: %clangxx_msan -m64 -O1 %s -o %t && not %run %t >%t.out 2>&1 // RUN: FileCheck %s < %t.out // RUN: %clangxx_msan -m64 -O2 %s -o %t && not %run %t >%t.out 2>&1 // RUN: FileCheck %s < %t.out // RUN: %clangxx_msan -m64 -O3 %s -o %t && not %run %t >%t.out 2>&1 // RUN: FileCheck %s < %t.out // Test that (no_sanitize_memory) functions propagate shadow. // Note that at -O0 there is no report, because 'x' in 'f' is spilled to the // stack, and then loaded back as a fully initialiazed value (due to // no_sanitize_memory attribute). #include <stdlib.h> #include <stdio.h> __attribute__((noinline)) __attribute__((no_sanitize_memory)) int f(int x) { return x; } int main(void) { int x; int * volatile p = &x; int y = f(*p); // CHECK: WARNING: MemorySanitizer: use-of-uninitialized-value // CHECK: {{#0 0x.* in main .*no_sanitize_memory_prop.cc:}}[[@LINE+1]] if (y) exit(0); return 0; }
// RUN: %clangxx_msan -m64 -O0 %s -o %t && %run %t >%t.out 2>&1 // RUN: %clangxx_msan -m64 -O1 %s -o %t && %run %t >%t.out 2>&1 // RUN: %clangxx_msan -m64 -O2 %s -o %t && %run %t >%t.out 2>&1 // RUN: %clangxx_msan -m64 -O3 %s -o %t && %run %t >%t.out 2>&1 // Test that (no_sanitize_memory) functions DO NOT propagate shadow. #include <stdlib.h> #include <stdio.h> __attribute__((noinline)) __attribute__((no_sanitize_memory)) int f(int x) { return x; } int main(void) { int x; int * volatile p = &x; int y = f(*p); if (y) exit(0); return 0; }
Use Language::LanguageIsCPlusPlus instead of doing the same switch over language
//===-- CPlusPlusLanguage.cpp --------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "CPlusPlusLanguage.h" #include "lldb/Core/ConstString.h" #include "lldb/Core/PluginManager.h" using namespace lldb; using namespace lldb_private; void CPlusPlusLanguage::Initialize() { PluginManager::RegisterPlugin (GetPluginNameStatic(), "C++ Language", CreateInstance); } void CPlusPlusLanguage::Terminate() { PluginManager::UnregisterPlugin (CreateInstance); } lldb_private::ConstString CPlusPlusLanguage::GetPluginNameStatic() { static ConstString g_name("cplusplus"); return g_name; } //------------------------------------------------------------------ // PluginInterface protocol //------------------------------------------------------------------ lldb_private::ConstString CPlusPlusLanguage::GetPluginName() { return GetPluginNameStatic(); } uint32_t CPlusPlusLanguage::GetPluginVersion() { return 1; } //------------------------------------------------------------------ // Static Functions //------------------------------------------------------------------ Language * CPlusPlusLanguage::CreateInstance (lldb::LanguageType language) { switch (language) { case lldb::eLanguageTypeC_plus_plus: case lldb::eLanguageTypeC_plus_plus_03: case lldb::eLanguageTypeC_plus_plus_11: case lldb::eLanguageTypeC_plus_plus_14: return new CPlusPlusLanguage(); default: return nullptr; } }
//===-- CPlusPlusLanguage.cpp --------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "CPlusPlusLanguage.h" #include "lldb/Core/ConstString.h" #include "lldb/Core/PluginManager.h" using namespace lldb; using namespace lldb_private; void CPlusPlusLanguage::Initialize() { PluginManager::RegisterPlugin (GetPluginNameStatic(), "C++ Language", CreateInstance); } void CPlusPlusLanguage::Terminate() { PluginManager::UnregisterPlugin (CreateInstance); } lldb_private::ConstString CPlusPlusLanguage::GetPluginNameStatic() { static ConstString g_name("cplusplus"); return g_name; } //------------------------------------------------------------------ // PluginInterface protocol //------------------------------------------------------------------ lldb_private::ConstString CPlusPlusLanguage::GetPluginName() { return GetPluginNameStatic(); } uint32_t CPlusPlusLanguage::GetPluginVersion() { return 1; } //------------------------------------------------------------------ // Static Functions //------------------------------------------------------------------ Language * CPlusPlusLanguage::CreateInstance (lldb::LanguageType language) { if (Language::LanguageIsCPlusPlus(language)) return new CPlusPlusLanguage(); return nullptr; }
Fix wrong parameters order in client test
#include "environment.h" #include <webdriverxx/client.h> #include <gtest/gtest.h> namespace test { using namespace webdriverxx; class TestClient : public ::testing::Test { protected: static void SetUpTestCase() { client = new Client(GetWebDriverUrl()); } static void TearDownTestCase() { delete client; client = 0; } static Client* client; }; Client* TestClient::client = 0; TEST_F(TestClient, GetsStatus) { picojson::object status = client->GetStatus(); ASSERT_TRUE(status["build"].is<picojson::object>()); ASSERT_TRUE(status["os"].is<picojson::object>()); } TEST_F(TestClient, GetsSessions) { client->GetSessions(); } TEST_F(TestClient, CreatesSession) { Parameters params = GetParameters(); client->CreateSession(params.required, params.desired); } } // namespace test
#include "environment.h" #include <webdriverxx/client.h> #include <gtest/gtest.h> namespace test { using namespace webdriverxx; class TestClient : public ::testing::Test { protected: static void SetUpTestCase() { client = new Client(GetWebDriverUrl()); } static void TearDownTestCase() { delete client; client = 0; } static Client* client; }; Client* TestClient::client = 0; TEST_F(TestClient, GetsStatus) { picojson::object status = client->GetStatus(); ASSERT_TRUE(status["build"].is<picojson::object>()); ASSERT_TRUE(status["os"].is<picojson::object>()); } TEST_F(TestClient, GetsSessions) { client->GetSessions(); } TEST_F(TestClient, CreatesSession) { Parameters params = GetParameters(); client->CreateSession(params.desired, params.required); } } // namespace test
Fix buildbreak for missing error code from cstdlib
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2013 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <libcouchbase/debug.h> /** * This is just an example program intended to show you how to use * the debug functionalities of libcouchbase */ static void dumpHttpCommand(void) { lcb_http_cmd_t http_cmd("/foo/bar", 8, NULL, 0, LCB_HTTP_METHOD_POST, 1, "applicaiton/json"); std::cout << http_cmd << std::endl; } int main(void) { dumpHttpCommand(); exit(EXIT_SUCCESS); }
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2013 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <libcouchbase/debug.h> #include <cstdlib> using namespace std; /** * This is just an example program intended to show you how to use * the debug functionalities of libcouchbase */ static void dumpHttpCommand(void) { lcb_http_cmd_t http_cmd("/foo/bar", 8, NULL, 0, LCB_HTTP_METHOD_POST, 1, "applicaiton/json"); cout << http_cmd << endl; } int main(void) { dumpHttpCommand(); exit(EXIT_SUCCESS); }
Fix empty string being added to string vector.
#include "string_split.h" namespace psz { std::vector<std::string> SplitString(const std::string& str, const std::string& sep) { std::vector<std::string> results; size_t prev = 0; size_t pos = str.find(sep); while (pos != std::string::npos) { results.push_back(str.substr(prev, pos - prev)); prev = pos + 1; pos = str.find(sep, prev); } results.push_back(str.substr(prev, str.length() - prev)); return results; } std::vector<unsigned int> SplitStringAndParse(const std::string& str, const std::string& sep, int shift) { std::vector<unsigned int> result; for (const auto& val : SplitString(str, sep)) { if (val.empty()) { continue; } unsigned int val_u = std::stoul(val); // CHECK_LE(-shift, val_u); result.push_back(val_u + shift); } return result; } } // namespace psz
#include "string_split.h" namespace psz { std::vector<std::string> SplitString(const std::string& str, const std::string& sep) { std::vector<std::string> results; size_t prev = 0; size_t pos = str.find(sep); while (pos != std::string::npos) { // TODO optimize! auto s = str.substr(prev, pos - prev); if (!s.empty()) { results.push_back(s); } prev = pos + 1; pos = str.find(sep, prev); } results.push_back(str.substr(prev, str.length() - prev)); return results; } std::vector<unsigned int> SplitStringAndParse(const std::string& str, const std::string& sep, int shift) { std::vector<unsigned int> result; for (const auto& val : SplitString(str, sep)) { if (val.empty()) { continue; } unsigned int val_u = std::stoul(val); // CHECK_LE(-shift, val_u); result.push_back(val_u + shift); } return result; } } // namespace psz
Fix the case of windows.h for consistency
// Copyright (C) 2015 Elviss Strazdins // This file is part of the Ouzel engine. #include <Windows.h> #include "Application.h" int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { ouzel::Application* application = new ouzel::Application(); //TODO: create main window //TODO: attach Renderer's view to this window //TODO: run main loop return 0; }
// Copyright (C) 2015 Elviss Strazdins // This file is part of the Ouzel engine. #include <windows.h> #include "Application.h" int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { ouzel::Application* application = new ouzel::Application(); //TODO: create main window //TODO: attach Renderer's view to this window //TODO: run main loop return 0; }
Make clang tools ignore -fcolor-diagnostics and -fdiagnostics-color retrieved from the compilation database.
//===--- ArgumentsAdjusters.cpp - Command line arguments adjuster ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains definitions of classes which implement ArgumentsAdjuster // interface. // //===----------------------------------------------------------------------===// #include "clang/Tooling/ArgumentsAdjusters.h" namespace clang { namespace tooling { void ArgumentsAdjuster::anchor() { } /// Add -fsyntax-only option to the commnand line arguments. CommandLineArguments ClangSyntaxOnlyAdjuster::Adjust(const CommandLineArguments &Args) { CommandLineArguments AdjustedArgs = Args; // FIXME: Remove options that generate output. AdjustedArgs.push_back("-fsyntax-only"); return AdjustedArgs; } } // end namespace tooling } // end namespace clang
//===--- ArgumentsAdjusters.cpp - Command line arguments adjuster ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains definitions of classes which implement ArgumentsAdjuster // interface. // //===----------------------------------------------------------------------===// #include "clang/Tooling/ArgumentsAdjusters.h" #include "clang/Basic/LLVM.h" #include "llvm/ADT/StringRef.h" namespace clang { namespace tooling { void ArgumentsAdjuster::anchor() { } /// Add -fsyntax-only option to the commnand line arguments. CommandLineArguments ClangSyntaxOnlyAdjuster::Adjust(const CommandLineArguments &Args) { CommandLineArguments AdjustedArgs; for (size_t i = 0, e = Args.size(); i != e; ++i) { StringRef Arg = Args[i]; // FIXME: Remove options that generate output. if (!Arg.startswith("-fcolor-diagnostics") && !Arg.startswith("-fdiagnostics-color")) AdjustedArgs.push_back(Args[i]); } AdjustedArgs.push_back("-fsyntax-only"); return AdjustedArgs; } } // end namespace tooling } // end namespace clang
Test for saving a selected region to a file
#include "ui/region_picker.hpp" int main() { EasyGIF::UI::RegionPicker picker(false); picker.Activate(); while(picker.IsRunning()) { picker.UpdateEvents(); picker.ProcessInput(); picker.Draw(); } return 0; }
#include "img/image_frame.hpp" #include "img/image_grabber.hpp" #include "img/image_saver.hpp" #include "ui/region_picker.hpp" #include <unistd.h> int main() { EasyGIF::UI::RegionPicker picker(false); EasyGIF::ImageFrame frame; EasyGIF::ImageGrabber grabber; EasyGIF::ImageSaver saver; picker.Activate(); while(picker.IsRunning()) { picker.UpdateEvents(); if(picker.IsConfirmed()) { ::EasyGIF::Utility::Rectangle rect = picker.GetRect(); picker.Shutdown(); sleep(5); // let X close the window frame = grabber.Grab(rect); saver.LoadData(frame); saver.Save("./test_picker.png"); } else { picker.ProcessInput(); picker.Draw(); } } return 0; }
Add static_assert to check evaluated value
#include <cassert> #include <iostream> #include "ColorFinder.hpp" int main() { constexpr ColorFinder::Color c{0x82, 0x12, 0x18}; constexpr auto name = getClosestColorName(c); std::cout << name << std::endl; return 0; }
#include <cassert> #include <iostream> #include "ColorFinder.hpp" int main() { constexpr ColorFinder::Color c{0x82, 0x12, 0x18}; constexpr auto name = getClosestColorName(c); static_assert(name == "Falu Red", "Something went wrong"); std::cout << name << std::endl; return 0; }
Add --wast option to evm2wasm CLI
#include <string> #include <iostream> #include <fstream> #include <streambuf> #include <evm2wasm.h> using namespace std; int main(int argc, char **argv) { if (argc < 2) { cerr << "Usage: " << argv[0] << " <EVM file>" << endl; return 1; } ifstream input(argv[1]); if (!input.is_open()) { cerr << "File not found: " << argv[1] << endl; return 1; } string str( (std::istreambuf_iterator<char>(input)), std::istreambuf_iterator<char>() ); cout << evm2wasm::evm2wasm(str) << endl; return 0; }
#include <string> #include <iostream> #include <fstream> #include <streambuf> #include <evm2wasm.h> using namespace std; int main(int argc, char **argv) { if (argc < 2) { cerr << "Usage: " << argv[0] << " <EVM file> [--wast]" << endl; return 1; } bool wast = false; if (argc == 3) { wast = (string(argv[2]) == "--wast"); if (!wast) { cerr << "Usage: " << argv[0] << " <EVM file> [--wast]" << endl; return 1; } } ifstream input(argv[1]); if (!input.is_open()) { cerr << "File not found: " << argv[1] << endl; return 1; } string str( (std::istreambuf_iterator<char>(input)), std::istreambuf_iterator<char>() ); if (wast) { cout << evm2wasm::evm2wast(str) << endl; } else { cout << evm2wasm::evm2wasm(str) << endl; } return 0; }
Add const to constant value
#include "Genes/Freedom_To_Move_Gene.h" #include <string> #include "Genes/Gene.h" #include "Game/Board.h" #include "Game/Color.h" double Freedom_To_Move_Gene::score_board(const Board& board, Piece_Color perspective, size_t) const noexcept { static auto initial_score = double(Board().legal_moves().size()); if(perspective == board.whose_turn()) { return board.legal_moves().size()/initial_score; } else { return board.previous_moves_count()/initial_score; } } std::string Freedom_To_Move_Gene::name() const noexcept { return "Freedom to Move Gene"; }
#include "Genes/Freedom_To_Move_Gene.h" #include <string> #include "Genes/Gene.h" #include "Game/Board.h" #include "Game/Color.h" double Freedom_To_Move_Gene::score_board(const Board& board, Piece_Color perspective, size_t) const noexcept { static const auto initial_score = double(Board().legal_moves().size()); if(perspective == board.whose_turn()) { return board.legal_moves().size()/initial_score; } else { return board.previous_moves_count()/initial_score; } } std::string Freedom_To_Move_Gene::name() const noexcept { return "Freedom to Move Gene"; }
Fix to unicode cmd line argument handling
#include "mainwindow.h" #include <QApplication> #include <QDialog> #include <QGridLayout> #include <QLayout> #include <QDebug> #include "application.h" int main(int argc, char *argv[]) { QCoreApplication::setOrganizationName("JASP"); QCoreApplication::setOrganizationDomain("jasp-stats.org"); QCoreApplication::setApplicationName("JASP"); Application a(argc, argv); MainWindow w; w.show(); if (argc > 1) w.open(QString(argv[1])); return a.exec(); }
#include "mainwindow.h" #include <QApplication> #include <QDialog> #include <QGridLayout> #include <QLayout> #include <QDebug> #include "application.h" int main(int argc, char *argv[]) { QCoreApplication::setOrganizationName("JASP"); QCoreApplication::setOrganizationDomain("jasp-stats.org"); QCoreApplication::setApplicationName("JASP"); Application a(argc, argv); MainWindow w; w.show(); QStringList args = QApplication::arguments(); if (args.length() > 1) w.open(args.at(1)); return a.exec(); }
Fix to work with different definitions of cass_uint64_t
/* Copyright (c) 2014 DataStax 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 "logger.hpp" namespace cass { void default_log_callback(cass_uint64_t time_ms, CassLogLevel severity, CassString message, void* data) { // TODO(mpenick): Format time fprintf(stderr, "%llu [%s]: %.*s\n", time_ms, cass_log_level_string(severity), static_cast<int>(message.length), message.data); } }
/* Copyright (c) 2014 DataStax 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 "logger.hpp" namespace cass { void default_log_callback(cass_uint64_t time_ms, CassLogLevel severity, CassString message, void* data) { fprintf(stderr, "%u.%03u [%s]: %.*s\n", (unsigned int)(time_ms/1000), (unsigned int)(time_ms % 1000), cass_log_level_string(severity), static_cast<int>(message.length), message.data); } }
Simplify bestMatch code as lower_bound = upper_bound when no exact match found
#include "PrimaryTreeIndex.h" void PrimaryTreeIndex::buildIndex(Table & table, int column) { int rowno = 0; for(auto &currentRow : table) { index.emplace(currentRow[column], rowno++); } } int PrimaryTreeIndex::size() const { return index.size(); } int PrimaryTreeIndex::exactMatch(const std::string& key) const { auto it = index.find(key); return it == index.end() ? -1 : it->second; } int PrimaryTreeIndex::bestMatch(const std::string& key) const { auto bounds = index.equal_range(key); auto lower_bound = bounds.first; auto upper_bound = bounds.second; if(lower_bound != index.end() && lower_bound->first == key) { return lower_bound->second; } else { std::map<std::string,int>::const_reverse_iterator rbegin(upper_bound); std::map<std::string,int>::const_reverse_iterator rend(index.begin()); for(auto it = rbegin; it!=rend; it++) { auto idx = key.find(it->first); if(idx != std::string::npos) { return it->second; } } } return -1; }
#include "PrimaryTreeIndex.h" void PrimaryTreeIndex::buildIndex(Table & table, int column) { int rowno = 0; for(auto &currentRow : table) { index.emplace(currentRow[column], rowno++); } } int PrimaryTreeIndex::size() const { return index.size(); } int PrimaryTreeIndex::exactMatch(const std::string& key) const { auto it = index.find(key); return it == index.end() ? -1 : it->second; } int PrimaryTreeIndex::bestMatch(const std::string& key) const { auto lower_bound = index.lower_bound(key); if(lower_bound != index.end() && lower_bound->first == key) { return lower_bound->second; } else { std::map<std::string,int>::const_reverse_iterator rbegin(lower_bound); std::map<std::string,int>::const_reverse_iterator rend(index.begin()); for(auto it = rbegin; it!=rend; it++) { auto idx = key.find(it->first); if(idx != std::string::npos) { return it->second; } } } return -1; }
Fix crash when emitting unhandled error on native EventEmitter
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/common/api/event_emitter_caller.h" #include "atom/common/api/locker.h" #include "atom/common/node_includes.h" namespace mate { namespace internal { v8::Local<v8::Value> CallMethodWithArgs(v8::Isolate* isolate, v8::Local<v8::Object> obj, const char* method, ValueVector* args) { // Perform microtask checkpoint after running JavaScript. v8::MicrotasksScope script_scope(isolate, v8::MicrotasksScope::kRunMicrotasks); // Use node::MakeCallback to call the callback, and it will also run pending // tasks in Node.js. return node::MakeCallback(isolate, obj, method, args->size(), &args->front(), {0, 0}).ToLocalChecked(); } } // namespace internal } // namespace mate
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/common/api/event_emitter_caller.h" #include "atom/common/api/locker.h" #include "atom/common/node_includes.h" namespace mate { namespace internal { v8::Local<v8::Value> CallMethodWithArgs(v8::Isolate* isolate, v8::Local<v8::Object> obj, const char* method, ValueVector* args) { // Perform microtask checkpoint after running JavaScript. v8::MicrotasksScope script_scope(isolate, v8::MicrotasksScope::kRunMicrotasks); // Use node::MakeCallback to call the callback, and it will also run pending // tasks in Node.js. v8::MaybeLocal<v8::Value> ret = node::MakeCallback(isolate, obj, method, args->size(), &args->front(), {0, 0}); if (ret.IsEmpty()) { return v8::Boolean::New(isolate, false); } return ret.ToLocalChecked(); } } // namespace internal } // namespace mate
Fix up r331244 - the emitted definition is weak_odr linkage. Should get the build bots to healthy again without a full revert. As the functionality added has nothing to do with linkage this seems unlikely to represent a deep or interesting bug in the patch.
// RUN: %clang_cc1 -std=c++17 -emit-llvm -fchar8_t -triple x86_64-linux %s -o - | FileCheck %s // CHECK: define void @_Z1fDu( void f(char8_t c) {} // CHECK: define void @_Z1gIiEvDTplplcvT__ELA4_KDuELDu114EE template<typename T> void g(decltype(T() + u8"foo" + u8'r')) {} template void g<int>(const char8_t*);
// RUN: %clang_cc1 -std=c++17 -emit-llvm -fchar8_t -triple x86_64-linux %s -o - | FileCheck %s // CHECK: define void @_Z1fDu( void f(char8_t c) {} // CHECK: define weak_odr void @_Z1gIiEvDTplplcvT__ELA4_KDuELDu114EE template<typename T> void g(decltype(T() + u8"foo" + u8'r')) {} template void g<int>(const char8_t*);
Read in the page names into a vector and hash
#include <stdio.h> int main(int argc, char* argv[]) { printf("One\n"); printf("Two\n"); printf("Three\n"); printf("Four\n"); return 0; }
#include <stdio.h> #include <iostream> #include <fstream> #include <vector> #include <unordered_map> int main(int argc, char* argv[]) { if (argc != 5) { std::cerr << "Path Finder only accepts 4 arguments\n"; exit(1); } // Load in all page titles into a vector std::cout << "\033[92m==>\033[0m Reading in page titles as a vector & map\n"; std::vector<std::string> pages; std::unordered_map<std::string, int> page_ids; { std::ifstream page_titles_file(argv[1]); std::string page_name; // We won't be using the first index of the vector for anything since // the page_id indexes start at 1 instead of 0. This should help to // prevent any errors during devlopment pages.push_back(""); // Read the page name into the vector and into the hash-map int index = 1; while (std::getline(page_titles_file, page_name)) { pages.push_back(page_name); page_ids[page_name] = index++; } std::cout << "\033[94m -> \033[0mRead in " << index - 1 << " page titles\n"; } return 0; }
Change the player status based on it's own energy
#include <memory> #include "Vec2i.h" #include "IMapElement.h" #include "CActor.h" #include "CWizard.h" namespace WizardOfGalicia { CWizard::CWizard() : CActor() { emission = 20; view = '^'; team = Team::HEROES; hp = 5; attack = 4; defence = 1; magicEnergy = 20; } void CWizard::update(std::shared_ptr<CMap> map) { if ( abs( magicEnergy ) > 0.0f ) { magicEnergy += ( magicEnergy / abs( magicEnergy ) ); } emission = abs( magicEnergy ); } void CWizard::turnLeft() { CActor::turnLeft(); updateView(); } void CWizard::turnRight() { CActor::turnRight(); updateView(); } void CWizard::updateView() { switch (direction) { case Direction::N: view = '^'; break; case Direction::W: view = '<'; break; case Direction::E: view = '>'; break; case Direction::S: view = 'V'; break; } } }
#include <memory> #include "Vec2i.h" #include "IMapElement.h" #include "CActor.h" #include "CWizard.h" namespace WizardOfGalicia { CWizard::CWizard() : CActor() { emission = 20; view = '^'; team = Team::HEROES; hp = 5; attack = 4; defence = 1; magicEnergy = 20; } void CWizard::update(std::shared_ptr<CMap> map) { if ( abs( magicEnergy ) > 0.0f ) { magicEnergy += ( magicEnergy / abs( magicEnergy ) ); } emission = abs( magicEnergy ); attack = 4 + abs( magicEnergy ); defence = 2 + abs( magicEnergy ); } void CWizard::turnLeft() { CActor::turnLeft(); updateView(); } void CWizard::turnRight() { CActor::turnRight(); updateView(); } void CWizard::updateView() { switch (direction) { case Direction::N: view = '^'; break; case Direction::W: view = '<'; break; case Direction::E: view = '>'; break; case Direction::S: view = 'V'; break; } } }
Revert 112083 - Try a different library for Crc32.
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "courgette/crc.h" #ifdef OS_CHROMEOS # include "zlib.h" #else extern "C" { # include "third_party/lzma_sdk/7zCrc.h" } #endif #include "base/basictypes.h" namespace courgette { uint32 CalculateCrc(const uint8* buffer, size_t size) { uint32 crc; #ifdef OS_CHROMEOS // Calculate Crc by calling CRC method in zlib crc = crc32(0, buffer, size); #else // Calculate Crc by calling CRC method in LZMA SDK CrcGenerateTable(); crc = CrcCalc(buffer, size); #endif return ~crc; } } // namespace
// 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. // Calculate Crc by calling CRC method in LZMA SDK #include "courgette/crc.h" extern "C" { #include "third_party/lzma_sdk/7zCrc.h" } namespace courgette { uint32 CalculateCrc(const uint8* buffer, size_t size) { CrcGenerateTable(); uint32 crc = 0xffffffffL; crc = ~CrcCalc(buffer, size); return crc; } } // namespace
Remove explicit WIN32 references from Console app.
#include "KAI/Console/Console.h" #include <iostream> #ifdef WIN32 #define WIN32_LEAN_AND_MEAN #include <Windows.h> #endif using namespace std; USING_NAMESPACE_KAI //static Color _color; int main(int argc, char **argv) { KAI_UNUSED_2(argc, argv); cout << "pyro v0.1" << endl; Console console; console.SetLanguage(Language::Pi); Process::trace = 0; console.GetExecutor()->SetTraceLevel(0); return console.Run(); }
#include <KAI/Console/Console.h> #include <iostream> using namespace std; USING_NAMESPACE_KAI int main(int argc, char **argv) { KAI_UNUSED_2(argc, argv); cout << "KAI v0.1" << endl; Console console; console.SetLanguage(Language::Pi); // the higher the number, the greater the verbosity of debug output Process::trace = 0; console.GetExecutor()->SetTraceLevel(0); // start the REPL return console.Run(); }
Make the test less sensitive to DWARF emission implementation details.
// REQUIRES: x86-64-registered-target // RUN: %clang_cc1 -triple x86_64-apple-darwin10 -g -fno-limit-debug-info -S %s -o %t // RUN: FileCheck %s < %t // FIXME: This testcase shouldn't rely on assembly emission. //CHECK: Lpubtypes_begin1: //CHECK: .asciz "G" //CHECK-NEXT: .long 0 //CHECK-NEXT: Lpubtypes_end1: class G { public: void foo(); }; void G::foo() { }
// REQUIRES: x86-64-registered-target // RUN: %clang_cc1 -triple x86_64-apple-darwin10 -g -fno-limit-debug-info -S %s -o %t // RUN: FileCheck %s < %t // FIXME: This testcase shouldn't rely on assembly emission. //CHECK: Lpubtypes_begin[[SECNUM:[0-9]:]] //CHECK: .asciz "G" //CHECK-NEXT: .long 0 //CHECK-NEXT: Lpubtypes_end[[SECNUM]] class G { public: void foo(); }; void G::foo() { }
Use find() instead of walking strings 'by hand' in IsValidHostName
/* * Copyright (C) 2004-2009 See the AUTHORS file for details. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. */ #include "Server.h" CServer::CServer(const CString& sName, unsigned short uPort, const CString& sPass, bool bSSL) { m_sName = sName; m_uPort = (uPort) ? uPort : 6667; m_sPass = sPass; m_bSSL = bSSL; } CServer::~CServer() {} bool CServer::IsValidHostName(const CString& sHostName) { const char* p = sHostName.c_str(); if (sHostName.empty()) { return false; } while (*p) { if (*p++ == ' ') { return false; } } return true; } const CString& CServer::GetName() const { return m_sName; } unsigned short CServer::GetPort() const { return m_uPort; } const CString& CServer::GetPass() const { return m_sPass; } bool CServer::IsSSL() const { return m_bSSL; } CString CServer::GetString() const { return m_sName + " " + CString(m_bSSL ? "+" : "") + CString(m_uPort) + CString(m_sPass.empty() ? "" : " " + m_sPass); }
/* * Copyright (C) 2004-2009 See the AUTHORS file for details. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. */ #include "Server.h" CServer::CServer(const CString& sName, unsigned short uPort, const CString& sPass, bool bSSL) { m_sName = sName; m_uPort = (uPort) ? uPort : 6667; m_sPass = sPass; m_bSSL = bSSL; } CServer::~CServer() {} bool CServer::IsValidHostName(const CString& sHostName) { if (sHostName.empty()) { return false; } if (sHostName.find(' ') != CString::npos) { return false; } return true; } const CString& CServer::GetName() const { return m_sName; } unsigned short CServer::GetPort() const { return m_uPort; } const CString& CServer::GetPass() const { return m_sPass; } bool CServer::IsSSL() const { return m_bSSL; } CString CServer::GetString() const { return m_sName + " " + CString(m_bSSL ? "+" : "") + CString(m_uPort) + CString(m_sPass.empty() ? "" : " " + m_sPass); }
Fix the draw X FLTK C++ example
// Copyright (c) 2016, Herman Bergwerf. All rights reserved. // Use of this source code is governed by a MIT-style license // that can be found in the LICENSE file. // Based on: http://seriss.com/people/erco/fltk/#FltkX #include <FL/Fl.H> #include <FL/fl_draw.H> #include <FL/Fl_Box.H> #include <FL/Fl_Double_Window.H> /// Widget that draws two diagonal lines class XWidget : public Fl_Box { public: /// Constuctor XWidget(int x, int y, int w, int h) : Fl_Box(x, y, w, h, 0) {} /// Draws the lines /*void draw() { fl_color(FL_BLACK); int x1 = x(), y1 = y(); int x2 = x() + w() - 1, y2 = y() + h() - 1; fl_line(x1, y1, x2, y2); fl_line(x1, y2, x2, y1); }*/ }; int main() { Fl_Double_Window *win = new Fl_Double_Window(200, 200, "X"); XWidget *x = new XWidget(0, 0, win -> w(), win -> h()); x -> box(FL_UP_BOX); win -> resizable(x); win -> show(); return Fl::run(); }
// Copyright (c) 2016, Herman Bergwerf. All rights reserved. // Use of this source code is governed by a MIT-style license // that can be found in the LICENSE file. // Based on: http://seriss.com/people/erco/fltk/#FltkX #include <FL/Fl.H> #include <FL/fl_draw.H> #include <FL/Fl_Box.H> #include <FL/Fl_Double_Window.H> /// Widget that draws two diagonal lines class XWidget : public Fl_Widget { public: /// Constuctor XWidget(int x, int y, int w, int h) : Fl_Widget(x, y, w, h, 0) {} /// Draws the lines void draw() { fl_color(FL_BLACK); int x1 = x(), y1 = y(); int x2 = x() + w() - 1, y2 = y() + h() - 1; fl_line(x1, y1, x2, y2); fl_line(x1, y2, x2, y1); } }; int main() { Fl_Double_Window *win = new Fl_Double_Window(200, 200, "X"); XWidget *x = new XWidget(0, 0, win -> w(), win -> h()); win -> resizable(x); win -> show(); return Fl::run(); }
Fix TestAttachResume test so it doesn't hang on Linux with ptrace lockdown.
#include <stdio.h> #include <fcntl.h> #include <chrono> #include <thread> void *start(void *data) { int i; size_t idx = (size_t)data; for (i=0; i<30; i++) { if ( idx == 0 ) std::this_thread::sleep_for(std::chrono::microseconds(1)); std::this_thread::sleep_for(std::chrono::seconds(1)); } return 0; } int main(int argc, char const *argv[]) { static const size_t nthreads = 16; std::thread threads[nthreads]; size_t i; for (i=0; i<nthreads; i++) threads[i] = std::move(std::thread(start, (void*)i)); for (i=0; i<nthreads; i++) threads[i].join(); }
#include <stdio.h> #include <fcntl.h> #include <chrono> #include <thread> #if defined(__linux__) #include <sys/prctl.h> #endif void *start(void *data) { int i; size_t idx = (size_t)data; for (i=0; i<30; i++) { if ( idx == 0 ) std::this_thread::sleep_for(std::chrono::microseconds(1)); std::this_thread::sleep_for(std::chrono::seconds(1)); } return 0; } int main(int argc, char const *argv[]) { #if defined(__linux__) // Immediately enable any ptracer so that we can allow the stub attach // operation to succeed. Some Linux kernels are locked down so that // only an ancestor process can be a ptracer of a process. This disables that // restriction. Without it, attach-related stub tests will fail. #if defined(PR_SET_PTRACER) && defined(PR_SET_PTRACER_ANY) // For now we execute on best effort basis. If this fails for // some reason, so be it. const int prctl_result = prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0); static_cast<void> (prctl_result); #endif #endif static const size_t nthreads = 16; std::thread threads[nthreads]; size_t i; for (i=0; i<nthreads; i++) threads[i] = std::move(std::thread(start, (void*)i)); for (i=0; i<nthreads; i++) threads[i].join(); }
Use strtoll like strtoimax on Interix.
#include <inttypes.h> #include <stdlib.h> #include <config/config_type_int.h> ConfigTypeInt config_type_int; bool ConfigTypeInt::set(ConfigValue *cv, const std::string& vstr) { if (ints_.find(cv) != ints_.end()) return (false); const char *str = vstr.c_str(); char *endp; intmax_t imax; imax = strtoimax(str, &endp, 0); if (*endp != '\0') return (false); ints_[cv] = imax; return (true); }
#if !defined(__OPENNT) #include <inttypes.h> #endif #include <stdlib.h> #include <config/config_type_int.h> ConfigTypeInt config_type_int; bool ConfigTypeInt::set(ConfigValue *cv, const std::string& vstr) { if (ints_.find(cv) != ints_.end()) return (false); const char *str = vstr.c_str(); char *endp; intmax_t imax; #if !defined(__OPENNT) imax = strtoimax(str, &endp, 0); #else imax = strtoll(str, &endp, 0); #endif if (*endp != '\0') return (false); ints_[cv] = imax; return (true); }
Return jit::VM only if ETH_JIT macro is on
/* This file is part of cpp-ethereum. cpp-ethereum 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. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ #include "VMFace.h" #include "VM.h" #include <libevmjit/VM.h> using namespace dev; using namespace dev::eth; std::unique_ptr<VMFace> VMFace::create(VMFace::Kind _kind, u256 _gas) { std::unique_ptr<VMFace> vm(_kind == Kind::JIT ? static_cast<VMFace*>(new jit::VM) : new VM); vm->reset(_gas); return vm; }
/* This file is part of cpp-ethereum. cpp-ethereum 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. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ #include "VMFace.h" #include "VM.h" #include <libevmjit/VM.h> using namespace dev; using namespace dev::eth; std::unique_ptr<VMFace> VMFace::create(VMFace::Kind _kind, u256 _gas) { std::unique_ptr<VMFace> vm; #if ETH_JIT vm.reset(_kind == Kind::JIT ? static_cast<VMFace*>(new jit::VM) : new VM); #else vm.reset(new VM); #endif vm->reset(_gas); return vm; }
Fix compiler warning in smoketest
/* * Copyright (C) 2016 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "Game.h" #include "Shell.h" #if (defined(_MSC_VER) && _MSC_VER < 1900 /*vs2015*/) || \ defined MINGW_HAS_SECURE_API #include <basetsd.h> #define snprintf sprintf_s #endif void Game::print_stats() { // Output frame count and measured elapsed time auto now = std::chrono::system_clock::now(); auto elapsed = now - start_time; auto elapsed_millis = std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).count(); char msg[256]; snprintf(msg, 255, "frames:%d, elapsedms:%ld", frame_count, elapsed_millis); shell_->log(Shell::LogPriority::LOG_INFO, msg); } void Game::quit() { print_stats(); shell_->quit(); }
/* * Copyright (C) 2016 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <sstream> #include "Game.h" #include "Shell.h" void Game::print_stats() { // Output frame count and measured elapsed time auto now = std::chrono::system_clock::now(); auto elapsed = now - start_time; auto elapsed_millis = std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).count(); std::stringstream ss; ss << "frames:" << frame_count << ", elapsedms:" << elapsed_millis; shell_->log(Shell::LogPriority::LOG_INFO, ss.str().c_str()); } void Game::quit() { print_stats(); shell_->quit(); }
Use C++ includes when appropriate.
#include "daemon.h" #include <err.h> #include <iostream> #include <string.h> #include <unistd.h> int main(int argc, char **argv) { int separator = 0; char** compile_argv; for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "--") == 0) { separator = i; break; } } compile_argv = argv + separator; compile_argv[0] = separator >= 2 ? argv[separator - 1] : strdup("clang"); if (clc::daemon::start()) { /* Send compile message to server. */ } /* Run the compiler and print error message if execvp returns. */ execvp(compile_argv[0], compile_argv); err(EXIT_FAILURE, "%s", compile_argv[0]); }
#include "daemon.h" #include <cstring> #include <err.h> #include <iostream> #include <unistd.h> int main(int argc, char **argv) { int separator = 0; char** compile_argv; for (int i = 1; i < argc; ++i) { if (std::strcmp(argv[i], "--") == 0) { separator = i; break; } } compile_argv = argv + separator; compile_argv[0] = separator >= 2 ? argv[separator - 1] : (char*) "clang"; if (clc::daemon::start()) { /* Send compile message to server. */ } /* Run the compiler and print error message if execvp returns. */ execvp(compile_argv[0], compile_argv); err(EXIT_FAILURE, "%s", compile_argv[0]); }
Make script download and print a web page.
#include <cstdio> #include <string> #include <vector> using std::vector; using std::string; int main(int argc, char *argv[]) { vector<string> args(argv + 1, argv + argc); for (const auto &arg : args) { printf("%s\n", arg.c_str()); } return 0; }
#include <cstdio> #include <string> #include <vector> #include <curl/curl.h> using std::vector; using std::string; struct LinkTestData { string in_source_url; string in_href_url; string out_source_page; }; size_t WriteData(void *buffer, size_t size, size_t nmemb, void *userp) { LinkTestData *link_test_data = (LinkTestData *)userp; char *body = (char *)buffer; link_test_data->out_source_page.append(body, body + nmemb); return size * nmemb; } int main(int argc, char *argv[]) { string root(argv[1]); printf("%s\n", root.c_str()); curl_global_init(CURL_GLOBAL_ALL); CURL *handle = curl_easy_init(); LinkTestData link = {}; curl_easy_setopt(handle, CURLOPT_URL, root.c_str()); curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, WriteData); curl_easy_setopt(handle, CURLOPT_WRITEDATA, &link); CURLcode success = curl_easy_perform(handle); printf("%s\n", link.out_source_page.c_str()); curl_easy_cleanup(handle); curl_global_cleanup(); return 0; }
Fix incorrect use of IOBuf::reserve
/* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <thpp/Storage.h> namespace thpp { namespace detail { IOBufAllocator::IOBufAllocator(folly::IOBuf&& iob) : iob_(std::move(iob)) { DCHECK(!iob_.isChained()); } void* IOBufAllocator::malloc(long size) { CHECK(false) << "IOBufAllocator::malloc should never be called"; } void* IOBufAllocator::realloc(void* ptr, long size) { CHECK_EQ(ptr, iob_.writableData()); if (size > iob_.capacity()) { iob_.unshareOne(); iob_.reserve(0, size - iob_.capacity()); } if (size < iob_.length()) { iob_.trimEnd(iob_.length() - size); } else { iob_.append(size - iob_.length()); } return iob_.writableData(); } void IOBufAllocator::free(void* ptr) { CHECK_EQ(ptr, iob_.writableData()); delete this; } } // namespace detail } // namespaces
/* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <thpp/Storage.h> namespace thpp { namespace detail { IOBufAllocator::IOBufAllocator(folly::IOBuf&& iob) : iob_(std::move(iob)) { DCHECK(!iob_.isChained()); } void* IOBufAllocator::malloc(long size) { CHECK(false) << "IOBufAllocator::malloc should never be called"; } void* IOBufAllocator::realloc(void* ptr, long size) { CHECK_EQ(ptr, iob_.writableData()); if (size <= iob_.length()) { iob_.trimEnd(iob_.length() - size); } else { auto extra = size - iob_.length(); if (extra > iob_.tailroom()) { iob_.unshareOne(); iob_.reserve(0, extra); } iob_.append(extra); } return iob_.writableData(); } void IOBufAllocator::free(void* ptr) { CHECK_EQ(ptr, iob_.writableData()); delete this; } } // namespace detail } // namespaces
Enable reading from stdin if the configuration filename is '-'.
#include "readfile.h" #include <stdexcept> #include <sstream> #include <cstdio> #include <cerrno> #include <cstring> using namespace std; /* read_file: read the entire contents of a file into a C++ string. */ string read_file(const string& filename) { // Open the file int errno_; FILE* fd; if (NULL == (fd = fopen(filename.c_str(), "r"))) { errno_ = errno; throw runtime_error(string("fopen: ") + strerror(errno_)); } // Read the data onto a string char *buf = new char[BUFSIZ]; string data; while (!feof(fd)) { size_t sz = fread(buf, 1, BUFSIZ, fd); if (ferror(fd)) { errno_ = errno; break; } data.append(buf, sz); } delete[] buf; // Check for errors / close file ostringstream errmsg; bool error = false; if (ferror(fd)) { error = true; errmsg << "fread: " << strerror(errno_); } if (fclose(fd)) { error = true; errno_ = errno; if (error) errmsg << "; "; errmsg << "fclose: " << strerror(errno_); } if (error) throw runtime_error(errmsg.str()); // Return data return data; }
#include "readfile.h" #include <stdexcept> #include <sstream> #include <cstdio> #include <cerrno> #include <cstring> using namespace std; /* read_file: read the entire contents of a file into a C++ string. */ string read_file(const string& filename) { // Open the file int errno_; FILE* fd; if (filename == "-") { fd = stdin; } else if (NULL == (fd = fopen(filename.c_str(), "r"))) { errno_ = errno; throw runtime_error(string("fopen: ") + strerror(errno_)); } // Read the data onto a string char *buf = new char[BUFSIZ]; string data; while (!feof(fd)) { size_t sz = fread(buf, 1, BUFSIZ, fd); if (ferror(fd)) { errno_ = errno; break; } data.append(buf, sz); } delete[] buf; // Check for errors / close file ostringstream errmsg; bool error = false; if (ferror(fd)) { error = true; errmsg << "fread: " << strerror(errno_); } if (filename != "-" && fclose(fd)) { error = true; errno_ = errno; if (error) errmsg << "; "; errmsg << "fclose: " << strerror(errno_); } if (error) throw runtime_error(errmsg.str()); // Return data return data; }
Fix wrong assigned key digital ids
#include <core.h> #include "thermostat.h" #include "keyboard.h" #define BUTTONS 4 uint8_t keyPins[BUTTONS] = {KEY_MODE_PIN, KEY_UP_PIN, KEY_DOWN_PIN, KEY_SETUP_PIN}; uint32_t lastKeyChangeMillis[BUTTONS] = {0, 0, 0, 0}; using namespace core; idType keyIds[BUTTONS]; idType idKeyMode, idKeyUp, idKeyDown, idKeySetup; void setupKeyboard() { for (int i = 0; i < BUTTONS; i++) { pinMode(keyPins[i], INPUT); keyIds[i] = store::defineDigital(); } idKeyMode = keyPins[0]; idKeyUp = keyPins[1]; idKeyDown = keyPins[2]; idKeySetup = keyPins[3]; } void checkKeys() { for (int i = 0; i < BUTTONS; i++) { uint8_t state = digitalRead(keyPins[i]); if (state == store::digitals[keyIds[i]]) { continue; } uint32_t now = millis(); if (now - lastKeyChangeMillis[i] < 300) { continue; } lastKeyChangeMillis[i] = now; store::setDigital(keyIds[i], state); Serial.print("Key "); Serial.print(i); Serial.println(state == HIGH ? " down" : " up"); } }
#include <core.h> #include "thermostat.h" #include "keyboard.h" #define BUTTONS 4 uint8_t keyPins[BUTTONS] = {KEY_MODE_PIN, KEY_UP_PIN, KEY_DOWN_PIN, KEY_SETUP_PIN}; uint32_t lastKeyChangeMillis[BUTTONS] = {0, 0, 0, 0}; using namespace core; idType keyIds[BUTTONS]; idType idKeyMode, idKeyUp, idKeyDown, idKeySetup; void setupKeyboard() { for (int i = 0; i < BUTTONS; i++) { pinMode(keyPins[i], INPUT); keyIds[i] = store::defineDigital(); } idKeyMode = keyIds[0]; idKeyUp = keyIds[1]; idKeyDown = keyIds[2]; idKeySetup = keyIds[3]; } void checkKeys() { for (int i = 0; i < BUTTONS; i++) { uint8_t state = digitalRead(keyPins[i]); if (state == store::digitals[keyIds[i]]) { continue; } uint32_t now = millis(); if (now - lastKeyChangeMillis[i] < 300) { continue; } lastKeyChangeMillis[i] = now; store::setDigital(keyIds[i], state); Serial.print("Key "); Serial.print(i); Serial.println(state == HIGH ? " down" : " up"); } }
Mark iostreams test as XFAIL on older macOSes
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include <iostream> #include <cassert> #include "test_macros.h" // Test to make sure that the streams only get initialized once // Taken from https://bugs.llvm.org/show_bug.cgi?id=43300 int main(int, char**) { std::cout << "Hello!"; std::ios_base::fmtflags stock_flags = std::cout.flags(); std::cout << std::boolalpha << true; std::ios_base::fmtflags ba_flags = std::cout.flags(); assert(stock_flags != ba_flags); std::ios_base::Init init_streams; std::ios_base::fmtflags after_init = std::cout.flags(); assert(after_init == ba_flags); return 0; }
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include <iostream> #include <cassert> #include "test_macros.h" // Test to make sure that the streams only get initialized once // Taken from https://bugs.llvm.org/show_bug.cgi?id=43300 // The dylibs shipped on macOS so far do not contain the fix for PR43300, so // this test fails. // XFAIL: with_system_cxx_lib=macosx10.15 // XFAIL: with_system_cxx_lib=macosx10.14 // XFAIL: with_system_cxx_lib=macosx10.13 // XFAIL: with_system_cxx_lib=macosx10.12 // XFAIL: with_system_cxx_lib=macosx10.11 // XFAIL: with_system_cxx_lib=macosx10.10 // XFAIL: with_system_cxx_lib=macosx10.9 // XFAIL: with_system_cxx_lib=macosx10.8 // XFAIL: with_system_cxx_lib=macosx10.7 int main(int, char**) { std::cout << "Hello!"; std::ios_base::fmtflags stock_flags = std::cout.flags(); std::cout << std::boolalpha << true; std::ios_base::fmtflags ba_flags = std::cout.flags(); assert(stock_flags != ba_flags); std::ios_base::Init init_streams; std::ios_base::fmtflags after_init = std::cout.flags(); assert(after_init == ba_flags); return 0; }
Set the user agent string correctly on Windows
#include "common/application_info.h" namespace brightray { std::string GetApplicationName() { return std::string(); } std::string GetApplicationVersion() { return std::string(); } }
#include "common/application_info.h" #include "base/file_version_info.h" #include "base/memory/scoped_ptr.h" #include "base/utf_string_conversions.h" namespace brightray { std::string GetApplicationName() { auto info = make_scoped_ptr(FileVersionInfo::CreateFileVersionInfoForModule(GetModuleHandle(nullptr))); return UTF16ToUTF8(info->product_name()); } std::string GetApplicationVersion() { auto info = make_scoped_ptr(FileVersionInfo::CreateFileVersionInfoForModule(GetModuleHandle(nullptr))); return UTF16ToUTF8(info->file_version()); } }
Fix auth struct linker problem
/* This file is part of fus. * * fus is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * fus is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with fus. If not, see <http://www.gnu.org/licenses/>. */ // Include all protocol headers here #include "auth.h" #include "common.h" // Protocol utilities will help with compile-time verifications #include "utils.h" // Reinclude all of the protocol inlines to define objects #include "protocol_objects_begin.inl" #include "auth.h" #include "common.inl" #include "protocol_objects_end.inl"
/* This file is part of fus. * * fus is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * fus is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with fus. If not, see <http://www.gnu.org/licenses/>. */ // Include all protocol headers here #include "auth.h" #include "common.h" // Protocol utilities will help with compile-time verifications #include "utils.h" // Reinclude all of the protocol inlines to define objects #include "protocol_objects_begin.inl" #include "auth.inl" #include "common.inl" #include "protocol_objects_end.inl"
ADD gets graphicscomponent and sets values
#include "LevelState.h" LevelState::LevelState() { } LevelState::~LevelState() { } int LevelState::ShutDown() { int result = 1; return result; } int LevelState::Initialize(GameStateHandler * gsh, ComponentHandler* cHandler) { int result = 0; result = GameState::InitializeBase(gsh, cHandler); //Read from file //Get Components //Set Component values //Give Components to entities this->m_player1.Initialize(); return result; } int LevelState::Update(float dt, InputHandler * inputHandler) { int result = 0; this->m_player1.Update(dt, inputHandler); return result; }
#include "LevelState.h" LevelState::LevelState() { } LevelState::~LevelState() { } int LevelState::ShutDown() { int result = 1; return result; } int LevelState::Initialize(GameStateHandler * gsh, ComponentHandler* cHandler) { int result = 0; result = GameState::InitializeBase(gsh, cHandler); //Read from file //Get Components GraphicsComponent* tempComp = this->m_cHandler->GetGraphicsComponent(); //Set Component values tempComp->active = 1; tempComp->modelID = 1337; tempComp->worldMatrix = DirectX::XMMatrixIdentity(); //Give Components to entities this->m_player1.Initialize(); return result; } int LevelState::Update(float dt, InputHandler * inputHandler) { int result = 0; this->m_player1.Update(dt, inputHandler); return result; }
Add check for “txt” extension.
// Includes #include "App/Factories/TextFileNFDelegate.h" #include "App/Nodes/TextFileNode.h" #include "App/Logger.h" // STD. #include <fstream> TextFileNFDelegate::TextFileNFDelegate() { } TextFileNFDelegate::~TextFileNFDelegate() { } std::string TextFileNFDelegate::nodeType() const { return "TextFile"; } std::vector<std::string> TextFileNFDelegate::requiredParameters() { std::vector<std::string> result; result.push_back("fileName"); return result; } bool TextFileNFDelegate::isValidParameter(const std::string &parameter, const std::string &value) const { if (parameter == "fileName") { std::ifstream file(value.c_str()); if (file.is_open()) { file.close(); return true; } else { file.close(); Logger::instance().logError("File with given file name cannot be opened."); return false; } } else { return false; } } Node *TextFileNFDelegate::createNode(const std::string &id, const std::map<std::string, std::string> &parameters) { return new TextFileNode(id, parameters.at("fileName")); }
// Includes #include "App/Factories/TextFileNFDelegate.h" #include "App/Nodes/TextFileNode.h" #include "App/Logger.h" // STD. #include <fstream> TextFileNFDelegate::TextFileNFDelegate() { } TextFileNFDelegate::~TextFileNFDelegate() { } std::string TextFileNFDelegate::nodeType() const { return "TextFile"; } std::vector<std::string> TextFileNFDelegate::requiredParameters() { std::vector<std::string> result; result.push_back("fileName"); return result; } bool TextFileNFDelegate::isValidParameter(const std::string &parameter, const std::string &value) const { if (parameter == "fileName") { std::string extension = value.substr(value.size()-4); if (extension != ".txt") { Logger::instance().logError("Invalid parameter: incorrect extension, should be '.txt'."); return false; } std::ifstream file(value.c_str()); if (file.is_open()) { file.close(); return true; } else { file.close(); Logger::instance().logError("Invalid parameter: file with given file name cannot be opened."); return false; } } else { Logger::instance().logError("Invalid parameter: parameter not supported for text file node."); return false; } } Node *TextFileNFDelegate::createNode(const std::string &id, const std::map<std::string, std::string> &parameters) { return new TextFileNode(id, parameters.at("fileName")); }
Fix passing of server to subsystem.
/* * SchemeAdHoc.c * * Scheme adhoc callback into opencog * * Copyright (c) 2008 Linas Vepstas <linas@linas.org> */ #ifdef HAVE_GUILE #include <libguile.h> #include <opencog/server/CogServer.h> #include <opencog/nlp/wsd/WordSenseProcessor.h> #include "SchemeSmob.h" using namespace opencog; /* ============================================================== */ /** * Dispatcher to invoke various miscellaneous C++ riff-raff from * scheme code. */ SCM SchemeSmob::ss_ad_hoc(SCM command) { std::string cmdname = decode_string (command, "cog-ad-hoc"); if (0 == cmdname.compare("do-wsd")) { WordSenseProcessor wsp; wsp.use_threads(false); wsp.run_no_delay(CogServer::createInstance()); // XXX What an ugly interface. Alas. return SCM_BOOL_T; } return SCM_BOOL_F; } #endif /* ===================== END OF FILE ============================ */
/* * SchemeAdHoc.c * * Scheme adhoc callback into opencog * * Copyright (c) 2008 Linas Vepstas <linas@linas.org> */ #ifdef HAVE_GUILE #include <libguile.h> #include <opencog/server/CogServer.h> #include <opencog/nlp/wsd/WordSenseProcessor.h> #include "SchemeSmob.h" using namespace opencog; /* ============================================================== */ /** * Dispatcher to invoke various miscellaneous C++ riff-raff from * scheme code. */ SCM SchemeSmob::ss_ad_hoc(SCM command) { std::string cmdname = decode_string (command, "cog-ad-hoc"); if (0 == cmdname.compare("do-wsd")) { WordSenseProcessor wsp; wsp.use_threads(false); wsp.run_no_delay(static_cast<CogServer *>(&server())); // XXX What an ugly interface. Alas. return SCM_BOOL_T; } return SCM_BOOL_F; } #endif /* ===================== END OF FILE ============================ */
Call ShouldQuit function to determine when to exit the REPL.
#include <iostream> #include "cons.h" #include "error.h" #include "eval.h" #include "init.h" #include "reader.h" namespace { class Repl { std::istream& in_; std::ostream& out_; std::string prompt_ = "mclisp> "; mclisp::Reader reader_; public: explicit Repl(std::istream& in=std::cin, std::ostream& out=std::cout): in_(in), out_(out), reader_(in_) {}; int loop(); }; int Repl::loop() { std::ostringstream oss; while (true) { out_ << prompt_; oss.str(""); oss.clear(); try { mclisp::ConsCell *exp = reader_.Read(); oss << *exp; if (EQ(exp, EOF) || oss.str() == "QUIT" || oss.str() == "(QUIT)") // TODO implement real (quit) function. break; mclisp::ConsCell *value = Eval(exp); out_ << *value << std::endl; } catch (mclisp::Error& e) { out_ << e.what() << std::endl; } } return 0; } } //end namespace int main() { // InitLisp must be called before the Reader object is initialized (which // happens in the Repl constructor). mclisp::InitLisp(); Repl repl; return repl.loop(); }
#include <iostream> #include "cons.h" #include "error.h" #include "eval.h" #include "init.h" #include "reader.h" namespace { bool ShouldQuit(mclisp::ConsCell *exp) { std::ostringstream oss; oss << *exp; return EQ(exp, EOF) || oss.str() == "QUIT" || oss.str() == "(QUIT)"; } class Repl { std::istream& in_; std::ostream& out_; std::string prompt_ = "mclisp> "; mclisp::Reader reader_; public: explicit Repl(std::istream& in=std::cin, std::ostream& out=std::cout): in_(in), out_(out), reader_(in_) {}; int loop(); }; int Repl::loop() { while (true) { out_ << prompt_; try { mclisp::ConsCell *exp = reader_.Read(); if (ShouldQuit(exp)) break; mclisp::ConsCell *value = Eval(exp); out_ << *value << std::endl; } catch (mclisp::Error& e) { out_ << e.what() << std::endl; } } return 0; } } //end namespace int main() { // InitLisp must be called before the Reader object is initialized (which // happens in the Repl constructor). mclisp::InitLisp(); Repl repl; return repl.loop(); }
Delete when ref-count goes to 1, not 2\!
#include "mbed.h" #include "MicroBit.h" void RefCounted::init() { // Initialize to one reference (lowest bit set to 1) refCount = 3; } static inline bool isReadOnlyInline(RefCounted *t) { uint32_t refCount = t->refCount; if (refCount == 0xffff) return true; // object in flash // Do some sanity checking while we're here if (refCount == 1) uBit.panic(MICROBIT_USE_AFTER_FREE); // object should have been deleted if ((refCount & 1) == 0) uBit.panic(MICROBIT_REF_COUNT_CORRUPTION); // refCount doesn't look right // Not read only return false; } bool RefCounted::isReadOnly() { return isReadOnlyInline(this); } void RefCounted::incr() { if (!isReadOnlyInline(this)) refCount += 2; } void RefCounted::decr() { if (isReadOnlyInline(this)) return; refCount -= 2; if (refCount == 2) { free(this); } }
#include "mbed.h" #include "MicroBit.h" void RefCounted::init() { // Initialize to one reference (lowest bit set to 1) refCount = 3; } static inline bool isReadOnlyInline(RefCounted *t) { uint32_t refCount = t->refCount; if (refCount == 0xffff) return true; // object in flash // Do some sanity checking while we're here if (refCount == 1) uBit.panic(MICROBIT_USE_AFTER_FREE); // object should have been deleted if ((refCount & 1) == 0) uBit.panic(MICROBIT_REF_COUNT_CORRUPTION); // refCount doesn't look right // Not read only return false; } bool RefCounted::isReadOnly() { return isReadOnlyInline(this); } void RefCounted::incr() { if (!isReadOnlyInline(this)) refCount += 2; } void RefCounted::decr() { if (isReadOnlyInline(this)) return; refCount -= 2; if (refCount == 1) { free(this); } }
Change resolution to 16:9 aspect ratio
#include <SFML/Graphics.hpp> int main(int argc, char const *argv[]) { sf::RenderWindow window(sf::VideoMode(800, 600), "Lord of the Orb", sf::Style::Titlebar | sf::Style::Close); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) { window.close(); } } window.clear(sf::Color::Black); window.display(); } return 0; }
#include <SFML/Graphics.hpp> int main(int argc, char const *argv[]) { sf::RenderWindow window(sf::VideoMode(1280, 720), "Lord of the Orb", sf::Style::Close); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) { window.close(); } } window.clear(sf::Color::Black); window.display(); } return 0; }
Use nan to wrap V8 functions.
#include <node.h> #include <node_internals.h> using namespace v8; #include "runas.h" namespace { Handle<Value> Runas(const Arguments& args) { HandleScope scope; if (!args[0]->IsString() || !args[1]->IsArray() || !args[2]->IsObject()) return node::ThrowError("Bad argument"); std::string command(*String::Utf8Value(args[0])); std::vector<std::string> c_args; Handle<Array> v_args = Handle<Array>::Cast(args[1]); uint32_t length = v_args->Length(); c_args.reserve(length); for (uint32_t i = 0; i < length; ++i) { std::string arg(*String::Utf8Value(v_args->Get(i))); c_args.push_back(arg); } Handle<Object> v_options = args[2]->ToObject(); int options = runas::OPTION_NONE; if (v_options->Get(String::New("hide"))->BooleanValue()) options |= runas::OPTION_HIDE; int code; if (!runas::Runas(command, c_args, options, &code)) return node::ThrowError("Failed to call runas"); return scope.Close(Integer::New(code)); } void Init(Handle<Object> exports) { NODE_SET_METHOD(exports, "runas", Runas); } } // namespace NODE_MODULE(runas, Init)
#include "nan.h" using namespace v8; #include "runas.h" namespace { NAN_METHOD(Runas) { NanScope(); if (!args[0]->IsString() || !args[1]->IsArray() || !args[2]->IsObject()) return NanThrowTypeError("Bad argument"); std::string command(*String::Utf8Value(args[0])); std::vector<std::string> c_args; Handle<Array> v_args = Handle<Array>::Cast(args[1]); uint32_t length = v_args->Length(); c_args.reserve(length); for (uint32_t i = 0; i < length; ++i) { std::string arg(*String::Utf8Value(v_args->Get(i))); c_args.push_back(arg); } Handle<Object> v_options = args[2]->ToObject(); int options = runas::OPTION_NONE; if (v_options->Get(String::New("hide"))->BooleanValue()) options |= runas::OPTION_HIDE; int code; if (!runas::Runas(command, c_args, options, &code)) return NanThrowError("Failed to call runas"); NanReturnValue(Integer::New(code)); } void Init(Handle<Object> exports) { NODE_SET_METHOD(exports, "runas", Runas); } } // namespace NODE_MODULE(runas, Init)
Fix the scope of noDominance()
#include "MOLPUpdateComputation.hpp" MOLPUpdateComputation::MOLPUpdateComputation(MOLP a, MOLP b) : molpA(a), molpB(b) { } bool noDominance() { return (molpA.empty() || molpB.empty() || molpA.isInA1AreaOf(molpB) || molpB.isInA1AreaOf(molpA)); } void MOLPUpdateComputation::initIterators() { endA = molpA.edges().end(); endB = molpB.edges().end(); iterA = molpA.edges().begin(); iterB = molpB.edges().begin(); while (iterA->isInA1AreaOf(*iterB) && iterA != endA) ++iterA; while (iterB->isInA1AreaOf(*iterA) && iterB != endB) ++iterB; } DominanceStatus MOLPUpdateComputation::computeUpdate() { if (noDominance()) return DominanceStatus::NO_DOM; initIterators(); }
#include "MOLPUpdateComputation.hpp" MOLPUpdateComputation::MOLPUpdateComputation(MOLP a, MOLP b) : molpA(a), molpB(b) { } bool MOLPUpdateComputation::noDominance() { return (molpA.empty() || molpB.empty() || molpA.isInA1AreaOf(molpB) || molpB.isInA1AreaOf(molpA)); } void MOLPUpdateComputation::initIterators() { endA = molpA.edges().end(); endB = molpB.edges().end(); iterA = molpA.edges().begin(); iterB = molpB.edges().begin(); while (iterA->isInA1AreaOf(*iterB) && iterA != endA) ++iterA; while (iterB->isInA1AreaOf(*iterA) && iterB != endB) ++iterB; } DominanceStatus MOLPUpdateComputation::computeUpdate() { if (noDominance()) return DominanceStatus::NO_DOM; initIterators(); }
Add a basic memory grow test
#include <Ab/Config.hpp> #include <Ab/Memory.hpp> #include <Ab/Test/BasicTest.hpp> #include <gtest/gtest.h> namespace Ab { namespace Test { class TestMemory : public BasicTest {}; TEST_F(TestMemory, initAndKill) { Memory m; ASSERT_EQ(m.init(Memory::defaultConfig()), MemoryError::SUCCESS); m.kill(); } } // namespace Test } // namespace Ab
#include <Ab/Config.hpp> #include <Ab/Memory.hpp> #include <Ab/Test/BasicTest.hpp> #include <gtest/gtest.h> namespace Ab { namespace Test { class TestMemory : public BasicTest {}; TEST_F(TestMemory, initAndKill) { Memory m; ASSERT_EQ(m.init(Memory::defaultConfig()), MemoryError::SUCCESS); m.kill(); } TEST_F(TestMemory, grow) { Memory m; m.init(Memory::defaultConfig()); for (std::size_t i = 0; i < 3; i++) { EXPECT_EQ(m.grow(), MemoryError::SUCCESS); } m.kill(); } } // namespace Test } // namespace Ab
Fix a shadowed data member.
/** * \file heuristic.cc * * * * \author Ethan Burns * \date 2008-10-13 */ #include "util/fixed_point.h" #include "heuristic.h" Heuristic::Heuristic(const SearchDomain *d) : domain(d), weight(fp_one) {} Heuristic::~Heuristic() {} void Heuristic::set_weight(float weight) { weight = fp_one * weight; } fp_type Heuristic::get_weight(void) const { return weight; }
/** * \file heuristic.cc * * * * \author Ethan Burns * \date 2008-10-13 */ #include "util/fixed_point.h" #include "heuristic.h" Heuristic::Heuristic(const SearchDomain *d) : domain(d), weight(fp_one) {} Heuristic::~Heuristic() {} void Heuristic::set_weight(float wt) { weight = fp_one * wt; } fp_type Heuristic::get_weight(void) const { return weight; }
Update unit tests for 0.0.11.0-dev
#include "omnicore/version.h" #include "config/bitcoin-config.h" #include <string> #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(omnicore_version_tests) BOOST_AUTO_TEST_CASE(version_comparison) { BOOST_CHECK(OMNICORE_VERSION > 900300); // Master Core v0.0.9.3 } /** * The following tests are very unhandy, because any version bump * breaks the tests. * * TODO: might be removed completely. */ BOOST_AUTO_TEST_CASE(version_string) { BOOST_CHECK_EQUAL(OmniCoreVersion(), "0.0.10-rel"); } BOOST_AUTO_TEST_CASE(version_number) { BOOST_CHECK_EQUAL(OMNICORE_VERSION, 1000000); } BOOST_AUTO_TEST_CASE(config_package_version) { // the package version is used in the file names: BOOST_CHECK_EQUAL(PACKAGE_VERSION, "0.0.10.0-rel"); } BOOST_AUTO_TEST_SUITE_END()
#include "omnicore/version.h" #include "config/bitcoin-config.h" #include <string> #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(omnicore_version_tests) BOOST_AUTO_TEST_CASE(version_comparison) { BOOST_CHECK(OMNICORE_VERSION > 1000000); // Omni Core v0.0.10.0 } /** * The following tests are very unhandy, because any version bump * breaks the tests. * * TODO: might be removed completely. */ BOOST_AUTO_TEST_CASE(version_string) { BOOST_CHECK_EQUAL(OmniCoreVersion(), "0.0.11-dev"); } BOOST_AUTO_TEST_CASE(version_number) { BOOST_CHECK_EQUAL(OMNICORE_VERSION, 1100000); } BOOST_AUTO_TEST_CASE(config_package_version) { // the package version is used in the file names: BOOST_CHECK_EQUAL(PACKAGE_VERSION, "0.0.11.0-dev"); } BOOST_AUTO_TEST_SUITE_END()
Support pointers to "None" as used in the wanproxy.conf.
#include <string> #include <config/config.h> #include <config/config_type_pointer.h> #include <config/config_value.h> ConfigTypePointer config_type_pointer; bool ConfigTypePointer::set(ConfigValue *cv, const std::string& vstr) { if (pointers_.find(cv) != pointers_.end()) return (false); Config *config = cv->config_; ConfigObject *co = config->lookup(vstr); if (co == NULL) return (false); pointers_[cv] = co; return (true); }
#include <string> #include <config/config.h> #include <config/config_type_pointer.h> #include <config/config_value.h> ConfigTypePointer config_type_pointer; bool ConfigTypePointer::set(ConfigValue *cv, const std::string& vstr) { if (pointers_.find(cv) != pointers_.end()) return (false); /* XXX Have a magic None that is easily-detected? */ if (vstr == "None") { pointers_[cv] = NULL; return (true); } Config *config = cv->config_; ConfigObject *co = config->lookup(vstr); if (co == NULL) return (false); pointers_[cv] = co; return (true); }