Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Save Prefs can run when disabled
#include "SavePreferences.h" SavePreferences::SavePreferences() { } // Called just before this Command runs the first time void SavePreferences::Initialize() { Preferences::GetInstance()->Save(); } // Called repeatedly when this Command is scheduled to run void SavePreferences::Execute() { } // Make this return true when this Command no longer needs to run execute() bool SavePreferences::IsFinished() { return true; } // Called once after isFinished returns true void SavePreferences::End() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run void SavePreferences::Interrupted() { End(); }
#include "SavePreferences.h" SavePreferences::SavePreferences() { this->SetRunWhenDisabled(true); } // Called just before this Command runs the first time void SavePreferences::Initialize() { Preferences::GetInstance()->Save(); } // Called repeatedly when this Command is scheduled to run void SavePreferences::Execute() { } // Make this return true when this Command no longer needs to run execute() bool SavePreferences::IsFinished() { return true; } // Called once after isFinished returns true void SavePreferences::End() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run void SavePreferences::Interrupted() { End(); }
Check to see if there's an image before drawing starts.
#include "SVGImage.h" #define NANOSVG_IMPLEMENTATION #include <nanosvg.h> #include <nanovg.h> // XXX This is bad, but easy. #define NANOVG_GL_IMPLEMENTATION #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #include <GLES2/gl2platform.h> #include <nanovg_gl.h> #include <nanovg.c> SVGImage::SVGImage() : _nanoSvgImage(nullptr) { } SVGImage::SVGImage(const boost::filesystem::path &path) : SVGImage() { open(path); } SVGImage::~SVGImage() { if (_nanoSvgImage) { ::nsvgDelete(_nanoSvgImage); } _nanoSvgImage = nullptr; } bool SVGImage::open(const boost::filesystem::path &path) { _nanoSvgImage = ::nsvgParseFromFile(path.string().c_str(), "", 72.f); return (_nanoSvgImage->width > 0.0f && _nanoSvgImage->height > 0.0 && _nanoSvgImage->shapes); } void SVGImage::draw() { }
#include "SVGImage.h" #define NANOSVG_IMPLEMENTATION #include <nanosvg.h> #include <nanovg.h> // XXX This is bad, but easy. #define NANOVG_GL_IMPLEMENTATION #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #include <GLES2/gl2platform.h> #include <nanovg_gl.h> #include <nanovg.c> SVGImage::SVGImage() : _nanoSvgImage(nullptr) { } SVGImage::SVGImage(const boost::filesystem::path &path) : SVGImage() { open(path); } SVGImage::~SVGImage() { if (_nanoSvgImage) { ::nsvgDelete(_nanoSvgImage); } _nanoSvgImage = nullptr; } bool SVGImage::open(const boost::filesystem::path &path) { _nanoSvgImage = ::nsvgParseFromFile(path.string().c_str(), "", 72.f); return (_nanoSvgImage->width > 0.0f && _nanoSvgImage->height > 0.0 && _nanoSvgImage->shapes); } void SVGImage::draw() { if (!_nanoSvgImage) return; }
Fix for compile problems under IRIX.
//C++ header - Open Scene Graph Simulation - Copyright (C) 1998-2002 Robert Osfield // Distributed under the terms of the GNU General Public License (GPL) // as published by the Free Software Foundation. // // All software using osgSim must be GPL'd or excempted via the // purchase of the Open Scene Graph Professional License (OSGPL) // for further information contact robert@openscenegraph.com. #include <osgSim/BlinkSequence> #include <stdlib.h> using namespace osgSim; BlinkSequence::BlinkSequence(): Referenced(), _pulsePeriod(0.0), _phaseShift(0.0), _pulseData(), _sequenceGroup(0) {} BlinkSequence::BlinkSequence(const BlinkSequence& bs): Referenced(), _pulsePeriod(bs._pulsePeriod), _phaseShift(bs._phaseShift), _pulseData(bs._pulseData), _sequenceGroup(bs._sequenceGroup) {} BlinkSequence::SequenceGroup::SequenceGroup(): Referenced() { // set a random base time between 0 and 1000.0 _baseTime = ((double)rand()/(double)RAND_MAX)*1000.0; } BlinkSequence::SequenceGroup::SequenceGroup(double baseTime): Referenced(), _baseTime(baseTime) {}
//C++ header - Open Scene Graph Simulation - Copyright (C) 1998-2002 Robert Osfield // Distributed under the terms of the GNU General Public License (GPL) // as published by the Free Software Foundation. // // All software using osgSim must be GPL'd or excempted via the // purchase of the Open Scene Graph Professional License (OSGPL) // for further information contact robert@openscenegraph.com. #include <osgSim/BlinkSequence> #include <stdlib.h> using namespace osgSim; BlinkSequence::BlinkSequence(): _pulsePeriod(0.0), _phaseShift(0.0), _pulseData(), _sequenceGroup(0) { } BlinkSequence::BlinkSequence(const BlinkSequence& bs): _pulsePeriod(bs._pulsePeriod), _phaseShift(bs._phaseShift), _pulseData(bs._pulseData), _sequenceGroup(bs._sequenceGroup) { } BlinkSequence::SequenceGroup::SequenceGroup() { // set a random base time between 0 and 1000.0 _baseTime = ((double)rand()/(double)RAND_MAX)*1000.0; } BlinkSequence::SequenceGroup::SequenceGroup(double baseTime): _baseTime(baseTime) { }
Fix inheriting constructor test for std::function.
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // <functional> // See https://llvm.org/bugs/show_bug.cgi?id=20002 #include <functional> #include <type_traits> using Fn = std::function<void()>; struct S : Fn { using function::function; }; int main() { S f1( Fn{} ); S f2(std::allocator_arg, std::allocator<void>{}, Fn{}); }
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03 // <functional> // See https://llvm.org/bugs/show_bug.cgi?id=20002 #include <functional> #include <type_traits> using Fn = std::function<void()>; struct S : public std::function<void()> { using function::function; }; int main() { S s( [](){} ); S f1( s ); S f2(std::allocator_arg, std::allocator<int>{}, s); }
Increase version for the VS support
#include "MainWindow.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); QApplication::setApplicationName("ofProjectGenerator"); QApplication::setApplicationVersion("0.5.1"); QApplication::setOrganizationName("Furkanzmc"); MainWindow w; w.show(); return a.exec(); }
#include "MainWindow.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); QApplication::setApplicationName("ofProjectGenerator"); QApplication::setApplicationVersion("0.5.2"); QApplication::setOrganizationName("Furkanzmc"); MainWindow w; w.show(); return a.exec(); }
Add unittests for RemoveWindowsStyleAccelerators() function.
// 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 "ui/gfx/linux_util.h" #include "base/basictypes.h" #include "testing/gtest/include/gtest/gtest.h" namespace gfx { TEST(LinuxUtilTest, ConvertAcceleratorsFromWindowsStyle) { static const struct { const char* input; const char* output; } cases[] = { { "", "" }, { "nothing", "nothing" }, { "foo &bar", "foo _bar" }, { "foo &&bar", "foo &bar" }, { "foo &&&bar", "foo &_bar" }, { "&foo &&bar", "_foo &bar" }, { "&foo &bar", "_foo _bar" }, }; for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) { std::string result = ConvertAcceleratorsFromWindowsStyle(cases[i].input); EXPECT_EQ(cases[i].output, result); } } } // namespace gfx
// 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 "ui/gfx/linux_util.h" #include "base/basictypes.h" #include "testing/gtest/include/gtest/gtest.h" namespace gfx { TEST(LinuxUtilTest, ConvertAcceleratorsFromWindowsStyle) { static const struct { const char* input; const char* output; } cases[] = { { "", "" }, { "nothing", "nothing" }, { "foo &bar", "foo _bar" }, { "foo &&bar", "foo &bar" }, { "foo &&&bar", "foo &_bar" }, { "&foo &&bar", "_foo &bar" }, { "&foo &bar", "_foo _bar" }, }; for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) { std::string result = ConvertAcceleratorsFromWindowsStyle(cases[i].input); EXPECT_EQ(cases[i].output, result); } } TEST(LinuxUtilTest, RemoveWindowsStyleAccelerators) { static const struct { const char* input; const char* output; } cases[] = { { "", "" }, { "nothing", "nothing" }, { "foo &bar", "foo bar" }, { "foo &&bar", "foo &bar" }, { "foo &&&bar", "foo &bar" }, { "&foo &&bar", "foo &bar" }, { "&foo &bar", "foo bar" }, }; for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) { std::string result = RemoveWindowsStyleAccelerators(cases[i].input); EXPECT_EQ(cases[i].output, result); } } } // namespace gfx
Remove the usage of non-portable std::map::at() from VariantMap
#include "variantmap.h" namespace MolCore { // === VariantMap ========================================================== // /// \class VariantMap /// \brief The VariantMap class provides a map between string keys /// and variant values. // --- Construction and Destruction ---------------------------------------- // /// Creates a new variant map object. VariantMap::VariantMap() { } /// Destroys the variant map. VariantMap::~VariantMap() { } // --- Properties ---------------------------------------------------------- // /// Returns the size of the variant map. size_t VariantMap::size() const { return m_map.size(); } /// Returns \c true if the variant map is empty (i.e. size() == /// \c 0). bool VariantMap::isEmpty() const { return m_map.empty(); } // --- Values -------------------------------------------------------------- // /// Sets the value of \p name to \p value. void VariantMap::setValue(const std::string &name, const Variant &value) { m_map[name] = value; } /// Returns the value for \p name. Variant VariantMap::value(const std::string &name) const { return m_map.at(name); } } // end MolCore namespace
#include "variantmap.h" namespace MolCore { // === VariantMap ========================================================== // /// \class VariantMap /// \brief The VariantMap class provides a map between string keys /// and variant values. // --- Construction and Destruction ---------------------------------------- // /// Creates a new variant map object. VariantMap::VariantMap() { } /// Destroys the variant map. VariantMap::~VariantMap() { } // --- Properties ---------------------------------------------------------- // /// Returns the size of the variant map. size_t VariantMap::size() const { return m_map.size(); } /// Returns \c true if the variant map is empty (i.e. size() == /// \c 0). bool VariantMap::isEmpty() const { return m_map.empty(); } // --- Values -------------------------------------------------------------- // /// Sets the value of \p name to \p value. void VariantMap::setValue(const std::string &name, const Variant &value) { m_map[name] = value; } /// Returns the value for \p name. If \p name is not found a null /// variant is returned. Variant VariantMap::value(const std::string &name) const { std::map<std::string, Variant>::const_iterator iter = m_map.find(name); if(iter == m_map.end()) return Variant(); return iter->second; } } // end MolCore namespace
Fix constructor usage (copy constructor deleted)
#include <iostream> #include <array> #include <asio/steady_timer.hpp> #include <asio.hpp> #include <thread> #include "node/raft_node.h" using namespace std; std::vector<raft_node_endpoint_t> peers{ {1ul, "localhost", 12345, 13001}, {2ul, "localhost", 12346, 13002}, {3ul, "localhost", 12347, 13003} }; int main(int argc, char* argv[]) { try { // Start raft_nodes std::vector<std::thread> workers; for (auto &peer : peers) { workers.push_back(std::thread([&peer]() { auto node = raft_node(peer.uuid, std::make_shared<raft::config>(peers)); node.run(); })); } // Wait for raft_nodes to finish std::for_each(workers.begin(), workers.end(), [](std::thread &t){ t.join(); }); } catch(std::exception& e) { std::cerr << "Error" << std::endl; std::cerr << e.what() << std::endl; } return 0; }
#include <iostream> #include <array> #include <asio/steady_timer.hpp> #include <asio.hpp> #include <thread> #include "node/raft_node.h" using namespace std; std::vector<raft_node_endpoint_t> peers{ {1ul, "localhost", 12345, 13001}, {2ul, "localhost", 12346, 13002}, {3ul, "localhost", 12347, 13003} }; int main(int argc, char* argv[]) { try { // Start raft_nodes std::vector<std::thread> workers; for (auto &peer : peers) { workers.push_back(std::thread([&peer]() { raft_node node(peer.uuid, std::make_shared<raft::config>(peers)); node.run(); })); } // Wait for raft_nodes to finish std::for_each(workers.begin(), workers.end(), [](std::thread &t){ t.join(); }); } catch(std::exception& e) { std::cerr << "Error" << std::endl; std::cerr << e.what() << std::endl; } return 0; }
Remove linter concerns which no longer trigger
/// \file main.cpp #include "HelloTriangleApplication.hpp" #define DOCTEST_CONFIG_IMPLEMENT #include "doctest.h" #include <cstdlib> #include <ostream> #include <stdexcept> int main(int argc, char* argv[]) // NOLINT(bugprone-exception-escape) { ////////////////////////////// Testing Stuff //// doctest::Context context; // context.setOption("no-breaks", true); // context.setOption("no-run", true); // context.applyCommandLine(argc, argv); // auto test_results = context.run(); // if (context.shouldExit()) return test_results; // ///////////////////////////////////////////////// HelloTriangleApplication app; try { app.run(); } catch (const std::exception& e) { std::cerr << e.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS + test_results; } // vim:set et ts=2 sw=0 sts=0:
/// \file main.cpp #include "HelloTriangleApplication.hpp" #define DOCTEST_CONFIG_IMPLEMENT #include "doctest.h" #include <cstdlib> #include <ostream> #include <stdexcept> int main(int argc, char* argv[]) { /////////////////////////////////////////////////////////////// Testing Stuff doctest::Context context; context.setOption("no-breaks", true); context.setOption("no-run", true); context.applyCommandLine(argc, argv); auto test_results = context.run(); if (context.shouldExit()) return test_results; ///////////////////////////////////////////////////////////////////////////// HelloTriangleApplication app; try { app.run(); } catch (const std::exception& e) { std::cerr << e.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS + test_results; } // vim:set et ts=2 sw=0 sts=0:
Fix compile error when building content_unittests for android.
// 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 "content/browser/renderer_host/render_widget_host_view.h" #include "base/logging.h" // static void RenderWidgetHostView::GetDefaultScreenInfo( WebKit::WebScreenInfo* results) { NOTIMPLEMENTED(); } //////////////////////////////////////////////////////////////////////////////// // RenderWidgetHostView, public: // static RenderWidgetHostView* RenderWidgetHostView::CreateViewForWidget( RenderWidgetHost* widget) { NOTIMPLEMENTED(); return NULL; }
// 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 "content/browser/renderer_host/render_widget_host_view.h" #include "base/logging.h" // static void RenderWidgetHostViewBase::GetDefaultScreenInfo( WebKit::WebScreenInfo* results) { NOTIMPLEMENTED(); } //////////////////////////////////////////////////////////////////////////////// // RenderWidgetHostView, public: // static RenderWidgetHostView* RenderWidgetHostView::CreateViewForWidget( RenderWidgetHost* widget) { NOTIMPLEMENTED(); return NULL; }
Convert string back to wstring
#include "stdafx.h" #include "ScriptLoader.h" #include <boost\filesystem.hpp> #include <sstream> namespace fs = boost::filesystem; using namespace fs; ScriptLoader::ScriptLoader(JsContextRef* context) { this->context = *context; } ScriptLoader::~ScriptLoader() { } void ScriptLoader::LoadScripts() { path js(L"js"); if (is_directory(js)) { for (directory_entry& entry : directory_iterator(js)) { path file = entry.path(); if (is_regular_file(file) && file.has_extension() && file.extension() == ".js") { fs::ifstream fileStream(file); ostringstream stringStream; stringStream << fileStream.rdbuf(); fileStream.close(); string script = stringStream.str(); LoadScript(script); } } } else { create_directory(js); } } void ScriptLoader::LoadScript(string script) { }
#include "stdafx.h" #include "ScriptLoader.h" #include <boost\filesystem.hpp> #include <sstream> namespace fs = boost::filesystem; using namespace fs; ScriptLoader::ScriptLoader(JsContextRef* context) { this->context = *context; } ScriptLoader::~ScriptLoader() { } void ScriptLoader::LoadScripts() { path js(L"js"); if (is_directory(js)) { for (directory_entry& entry : directory_iterator(js)) { path file = entry.path(); if (is_regular_file(file) && file.has_extension() && file.extension() == ".js") { fs::wifstream fileStream(file); wostringstream stringStream; stringStream << fileStream.rdbuf();; fileStream.close(); wstring script = stringStream.str(); LoadScript(script); } } } else { create_directory(js); } } void ScriptLoader::LoadScript(wstring script) { }
Enable flow control in Greentea
#include "greentea-client/greentea_serial.h" SingletonPtr<GreenteaSerial> greentea_serial; GreenteaSerial::GreenteaSerial() : mbed::RawSerial(USBTX, USBRX, MBED_CONF_PLATFORM_STDIO_BAUD_RATE) {};
#include "greentea-client/greentea_serial.h" /** * Macros for setting console flow control. */ #define CONSOLE_FLOWCONTROL_RTS 1 #define CONSOLE_FLOWCONTROL_CTS 2 #define CONSOLE_FLOWCONTROL_RTSCTS 3 #define mbed_console_concat_(x) CONSOLE_FLOWCONTROL_##x #define mbed_console_concat(x) mbed_console_concat_(x) #define CONSOLE_FLOWCONTROL mbed_console_concat(MBED_CONF_TARGET_CONSOLE_UART_FLOW_CONTROL) SingletonPtr<GreenteaSerial> greentea_serial; GreenteaSerial::GreenteaSerial() : mbed::RawSerial(USBTX, USBRX, MBED_CONF_PLATFORM_STDIO_BAUD_RATE) { #if CONSOLE_FLOWCONTROL == CONSOLE_FLOWCONTROL_RTS set_flow_control(SerialBase::RTS, STDIO_UART_RTS, NC); #elif CONSOLE_FLOWCONTROL == CONSOLE_FLOWCONTROL_CTS set_flow_control(SerialBase::CTS, NC, STDIO_UART_CTS); #elif CONSOLE_FLOWCONTROL == CONSOLE_FLOWCONTROL_RTSCTS set_flow_control(SerialBase::RTSCTS, STDIO_UART_RTS, STDIO_UART_CTS); #endif }
Fix dangling reference in test
//===----------------------- cxa_bad_cast.pass.cpp ------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03 #include <cxxabi.h> #include <cassert> #include <stdlib.h> #include <exception> #include <typeinfo> class Base { virtual void foo() {}; }; class Derived : public Base {}; Derived &test_bad_cast(Base b) { return dynamic_cast<Derived&>(b); } Base gB; void my_terminate() { exit(0); } int main () { // swap-out the terminate handler void (*default_handler)() = std::get_terminate(); std::set_terminate(my_terminate); #ifndef LIBCXXABI_HAS_NO_EXCEPTIONS try { #endif Derived &d = test_bad_cast(gB); assert(false); ((void)d); #ifndef LIBCXXABI_HAS_NO_EXCEPTIONS } catch (std::bad_cast) { // success return 0; } catch (...) { assert(false); } #endif // failure, restore the default terminate handler and fire std::set_terminate(default_handler); std::terminate(); }
//===----------------------- cxa_bad_cast.pass.cpp ------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03 #include <cxxabi.h> #include <cassert> #include <stdlib.h> #include <exception> #include <typeinfo> class Base { virtual void foo() {}; }; class Derived : public Base {}; Derived &test_bad_cast(Base& b) { return dynamic_cast<Derived&>(b); } Base gB; void my_terminate() { exit(0); } int main () { // swap-out the terminate handler void (*default_handler)() = std::get_terminate(); std::set_terminate(my_terminate); #ifndef LIBCXXABI_HAS_NO_EXCEPTIONS try { #endif Derived &d = test_bad_cast(gB); assert(false); ((void)d); #ifndef LIBCXXABI_HAS_NO_EXCEPTIONS } catch (std::bad_cast) { // success return 0; } catch (...) { assert(false); } #endif // failure, restore the default terminate handler and fire std::set_terminate(default_handler); std::terminate(); }
Modify json cache implementation to match null/empty array behavior
#include "CacheJsonToArticleConverter.h" #include <json/json.h> #include "WalkerException.h" #include "Article.h" ArticleCollection& CacheJsonToArticleConverter::convertToArticle(std::string json, ArticleCollection& articleCache) { Json::Reader reader; Json::Value document; bool success = reader.parse(json, document, false); if(!success) { throw WalkerException("Error parsing JSON"); } // get all "main" articles first for(auto &titleElement : document.getMemberNames()) { std::string title = titleElement; Article *a = articleCache.get(title); if(a == nullptr) { a = new Article(title); articleCache.add(a); } for(auto linkedArticle : document.get(title, Json::Value::nullSingleton()) .get("forward_links", Json::Value::nullSingleton())) { std::string linkedTitle = linkedArticle.asString(); Article *la = articleCache.get(linkedTitle); if(la == nullptr) { la = new Article(linkedTitle); articleCache.add(la); } a->addLink(la); } } return articleCache; /* a->setAnalyzed(true); ? */ }
#include "CacheJsonToArticleConverter.h" #include <json/json.h> #include "WalkerException.h" #include "Article.h" ArticleCollection& CacheJsonToArticleConverter::convertToArticle(std::string json, ArticleCollection& articleCache) { Json::Reader reader; Json::Value document; bool success = reader.parse(json, document, false); if(!success) { throw WalkerException("Error parsing JSON"); } // get all "main" articles first for(auto &titleElement : document.getMemberNames()) { std::string title = titleElement; Article *a = articleCache.get(title); if(a == nullptr) { a = new Article(title); articleCache.add(a); } auto links = document .get(title, Json::Value::nullSingleton()) .get("forward_links", Json::Value::nullSingleton()); if(links.isNull()) { /* don't need to set article analyzed to false, * since that's the default */ continue; } a->setAnalyzed(true); for(auto linkedArticle : links) { std::string linkedTitle = linkedArticle.asString(); Article *la = articleCache.get(linkedTitle); if(la == nullptr) { la = new Article(linkedTitle); articleCache.add(la); } a->addLink(la); } } return articleCache; /* a->setAnalyzed(true); ? */ }
Remove obsolete oglp code include.
/* * Copyright (c) 2015 Daniel Kirchner * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #include "glutil.h" #include <oglp/oglp.cxx> namespace glutil { void Init (oglp::GetProcAddressCallback getprocaddress) { oglp::Init (getprocaddress); } } /* namespace glutil */
/* * Copyright (c) 2015 Daniel Kirchner * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #include "glutil.h" namespace glutil { void Init (oglp::GetProcAddressCallback getprocaddress) { oglp::Init (getprocaddress); } } /* namespace glutil */
Add Error handling to textureholder
#include "TextureHolder.hpp" TextureHolder::TextureHolder() { } void TextureHolder::load(Textures id, const std::string &fileName) { std::unique_ptr<sf::Texture> texture(new sf::Texture); texture->loadFromFile(fileName); m_textureMap.insert(std::make_pair(id, std::move(texture))); } sf::Texture& TextureHolder::get(Textures id) { auto found = m_textureMap.find(id); return *found->second; } const sf::Texture& TextureHolder::get(Textures id) const { auto found = m_textureMap.find(id); return *found->second; }
#include "TextureHolder.hpp" TextureHolder::TextureHolder() { } void TextureHolder::load(Textures id, const std::string &fileName) { std::unique_ptr<sf::Texture> texture(new sf::Texture); if (!texture->loadFromFile(fileName)) { throw std::runtime_error("TextureHolder::load - Failed to load " + fileName); } auto inserted = m_textureMap.insert(std::make_pair(id, std::move(texture))); // Stop execute in debug mode when there was an error by inserting the resource(e.g try to add the same id twice) // Trying to load the same resource twice with the same id is a logical error so the progtam should stop immediately in debug mode assert(inserted.second); } sf::Texture& TextureHolder::get(Textures id) { auto found = m_textureMap.find(id); // Stop programm in debug mode, when trying to get a resource which is not loaded assert(found != m_textureMap.end()); return *found->second; } const sf::Texture& TextureHolder::get(Textures id) const { auto found = m_textureMap.find(id); return *found->second; }
Fix missing call to Pipe::init
/// // // LibSourcey // Copyright (c) 2005, Sourcey <https://sourcey.com> // // SPDX-License-Identifier: LGPL-2.1+ // /// @addtogroup base /// @{ #include "scy/pipe.h" using std::endl; namespace scy { Pipe::Pipe(uv::Loop* loop) : Stream(loop, new uv_pipe_t) { } Pipe::~Pipe() { } void Pipe::init(bool ipc) { uv_pipe_init(loop(), ptr<uv_pipe_t>(), ipc ? 1 : 0); //Stream::readStart(); } bool Pipe::readStart() { return Stream::readStart(); } // //bool Pipe::readStop() //{ // return Stream::readStop(); //} } // namespace scy /// @\}
/// // // LibSourcey // Copyright (c) 2005, Sourcey <https://sourcey.com> // // SPDX-License-Identifier: LGPL-2.1+ // /// @addtogroup base /// @{ #include "scy/pipe.h" using std::endl; namespace scy { Pipe::Pipe(uv::Loop* loop) : Stream(loop, new uv_pipe_t) { } Pipe::~Pipe() { } void Pipe::init(bool ipc) { uv_pipe_init(loop(), ptr<uv_pipe_t>(), ipc ? 1 : 0); Stream::init(); } bool Pipe::readStart() { return Stream::readStart(); } // bool Pipe::readStop() // { // return Stream::readStop(); // } } // namespace scy /// @\}
Use designated interface of the color gradient preparation tool in the color gradient preparation stage
#include <gloperate/stages/ColorGradientPreparationStage.h> #include <gloperate/base/ColorGradientList.h> #include <gloperate/tools/ColorGradientPreparation.h> namespace gloperate { ColorGradientPreparationStage::ColorGradientPreparationStage() { addInput("gradients", gradients); addInput("pixmapSize", pixmapSize); addOutput("names", names); addOutput("pixmaps", pixmaps); } ColorGradientPreparationStage::~ColorGradientPreparationStage() { } void ColorGradientPreparationStage::process() { ColorGradientPreparation preparation(gradients.data(), pixmapSize.data()); names.data() = preparation.names(); pixmaps.data() = preparation.pixmaps(); invalidateOutputs(); } } // namespace gloperate
#include <gloperate/stages/ColorGradientPreparationStage.h> #include <gloperate/base/ColorGradientList.h> #include <gloperate/tools/ColorGradientPreparation.h> namespace gloperate { ColorGradientPreparationStage::ColorGradientPreparationStage() { addInput("gradients", gradients); addInput("pixmapSize", pixmapSize); addOutput("names", names); addOutput("pixmaps", pixmaps); } ColorGradientPreparationStage::~ColorGradientPreparationStage() { } void ColorGradientPreparationStage::process() { ColorGradientPreparation preparation(gradients.data(), pixmapSize.data()); preparation.fillNames(names.data()); preparation.fillPixmaps(pixmaps.data()); invalidateOutputs(); } } // namespace gloperate
Disable zeroconf in factory reset mode
#include "network_config.hpp" #include <fstream> #include <string> namespace phosphor { namespace network { namespace bmc { void writeDHCPDefault(const std::string& filename, const std::string& interface) { std::ofstream filestream; filestream.open(filename); filestream << "[Match]\nName=" << interface << "\n[Network]\nDHCP=true\nLinkLocalAddressing=yes\n" "[DHCP]\nClientIdentifier=mac\n"; filestream.close(); } } }//namespace network }//namespace phosphor
#include "network_config.hpp" #include <fstream> #include <string> namespace phosphor { namespace network { namespace bmc { void writeDHCPDefault(const std::string& filename, const std::string& interface) { std::ofstream filestream; filestream.open(filename); filestream << "[Match]\nName=" << interface << "\n[Network]\nDHCP=true\n" "[DHCP]\nClientIdentifier=mac\n"; filestream.close(); } } }//namespace network }//namespace phosphor
Fix namespace. It is <gx:duration>.
// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2013 Mayank Madan <maddiemadan@gmail.com> // #include "KmlDurationTagHandler.h" #include "MarbleDebug.h" #include "KmlElementDictionary.h" #include "MarbleGlobal.h" #include "GeoDataFlyTo.h" #include "GeoParser.h" namespace Marble { namespace kml { KML_DEFINE_TAG_HANDLER( duration ) GeoNode *KmldurationTagHandler::parse(GeoParser & parser) const { Q_ASSERT ( parser.isStartElement() && parser.isValidElement( kmlTag_duration ) ); GeoStackItem parentItem = parser.parentElement(); qreal const duration = parser.readElementText().trimmed().toDouble(); if ( parentItem.is<GeoDataFlyTo>() ){ parentItem.nodeAs<GeoDataFlyTo>()->setDuration( duration ); } return 0; } } }
// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2013 Mayank Madan <maddiemadan@gmail.com> // #include "KmlDurationTagHandler.h" #include "MarbleDebug.h" #include "KmlElementDictionary.h" #include "MarbleGlobal.h" #include "GeoDataFlyTo.h" #include "GeoParser.h" namespace Marble { namespace kml { KML_DEFINE_TAG_HANDLER_GX22( duration ) GeoNode *KmldurationTagHandler::parse(GeoParser & parser) const { Q_ASSERT ( parser.isStartElement() && parser.isValidElement( kmlTag_duration ) ); GeoStackItem parentItem = parser.parentElement(); qreal const duration = parser.readElementText().trimmed().toDouble(); if ( parentItem.is<GeoDataFlyTo>() ){ parentItem.nodeAs<GeoDataFlyTo>()->setDuration( duration ); } return 0; } } }
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 =====
Set the transparent region appropriately
#include <qpiekey.h> #include <QSizePolicy> #include <QPainter> #include <QPaintEvent> QPieKey::QPieKey(QWidget *parent) : QWidget(parent) { bitmap = new QBitmap(40,40); QPainter painter(bitmap); bitmap->clear(); painter.drawEllipse(0, 0, 40, 40); setFixedSize(40, 40); setMask(*bitmap); } QPieKey::~QPieKey() { } void QPieKey::paintEvent(QPaintEvent *event) { QPainter painter(this); painter.setBrush(QColor(128, 128, 128)); painter.drawRect(event->rect()); }
#include <qpiekey.h> #include <QSizePolicy> #include <QPainter> #include <QPaintEvent> #define SIZE 60 QPieKey::QPieKey(QWidget *parent) : QWidget(parent) { bitmap = new QBitmap(SIZE*2,SIZE*2); QPainter painter(bitmap); setFixedSize(SIZE*2, SIZE*2); bitmap->clear(); painter.setBrush(Qt::color1); painter.drawEllipse(1, 1, SIZE*2-2, SIZE*2-2); painter.setBrush(Qt::color0); painter.drawEllipse(SIZE/2, SIZE/2, SIZE, SIZE); setMask(*bitmap); hide(); } QPieKey::~QPieKey() { } void QPieKey::paintEvent(QPaintEvent *event) { QPainter painter(this); painter.setBrush(QColor(128, 128, 128)); painter.drawRect(event->rect()); }
Remove exception handler - this was not needed
#include <iostream> #include <gtest/gtest.h> int main(int argc, char* argv[]) try { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } catch (...) { std::cout << "Exception during testing. Exiting...\n"; return 1; }
#include <iostream> #include <gtest/gtest.h> int main(int argc, char* argv[]) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
Set the host file system model's root path to "myComputer" so the host browser will show all drives.
#include "models/bucket.h" #include "views/session_view.h" SessionView::SessionView(Session* session, QWidget* parent) : QWidget(parent), m_session(session) { m_hostFileSystem = new QFileSystemModel(this); m_hostFileSystem->setRootPath(QDir::rootPath()); m_hostBrowser = new QTreeView; m_hostBrowser->setModel(m_hostFileSystem); m_hostBrowser->setRootIndex(m_hostFileSystem->index(QDir::rootPath())); // Remove the focus rectangle around the tree view on OSX. m_hostBrowser->setAttribute(Qt::WA_MacShowFocusRect, 0); m_remoteBrowser = new QTreeView; // Remove the focus rectangle around the tree view on OSX. m_remoteBrowser->setAttribute(Qt::WA_MacShowFocusRect, 0); m_splitter = new QSplitter; m_splitter->addWidget(m_hostBrowser); m_splitter->addWidget(m_remoteBrowser); m_topLayout = new QVBoxLayout(this); m_topLayout->addWidget(m_splitter); setLayout(m_topLayout); m_client = new Client(m_session->GetHost(), m_session->GetPort(), m_session->GetAccessId(), m_session->GetSecretKey()); ds3_get_service_response* response = m_client->GetService(); Bucket* bucket = new Bucket(response); m_remoteBrowser->setModel(bucket); } SessionView::~SessionView() { delete m_client; }
#include "models/bucket.h" #include "views/session_view.h" SessionView::SessionView(Session* session, QWidget* parent) : QWidget(parent), m_session(session) { m_hostFileSystem = new QFileSystemModel(this); QString rootPath = m_hostFileSystem->myComputer().toString(); m_hostFileSystem->setRootPath(rootPath); m_hostBrowser = new QTreeView; m_hostBrowser->setModel(m_hostFileSystem); // Remove the focus rectangle around the tree view on OSX. m_hostBrowser->setAttribute(Qt::WA_MacShowFocusRect, 0); m_remoteBrowser = new QTreeView; // Remove the focus rectangle around the tree view on OSX. m_remoteBrowser->setAttribute(Qt::WA_MacShowFocusRect, 0); m_splitter = new QSplitter; m_splitter->addWidget(m_hostBrowser); m_splitter->addWidget(m_remoteBrowser); m_topLayout = new QVBoxLayout(this); m_topLayout->addWidget(m_splitter); setLayout(m_topLayout); m_client = new Client(m_session->GetHost(), m_session->GetPort(), m_session->GetAccessId(), m_session->GetSecretKey()); ds3_get_service_response* response = m_client->GetService(); Bucket* bucket = new Bucket(response); m_remoteBrowser->setModel(bucket); } SessionView::~SessionView() { delete m_client; }
Handle count being zero in transport latch.
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "transport_latch.h" #include <vespa/vespalib/util/stringfmt.h> using vespalib::make_string; using storage::spi::Result; namespace proton { TransportLatch::TransportLatch(uint32_t cnt) : _latch(cnt), _lock(), _result() {} TransportLatch::~TransportLatch() = default; void TransportLatch::send(ResultUP result, bool documentWasFound) { { std::lock_guard<std::mutex> guard(_lock); if (!_result) { _result = std::move(result); } else if (result->hasError()) { _result.reset(new Result(mergeErrorResults(*_result, *result))); } else if (documentWasFound) { _result = std::move(result); } } _latch.countDown(); } Result TransportLatch::mergeErrorResults(const Result &lhs, const Result &rhs) { Result::ErrorType error = (lhs.getErrorCode() > rhs.getErrorCode() ? lhs : rhs).getErrorCode(); return Result(error, make_string("%s, %s", lhs.getErrorMessage().c_str(), rhs.getErrorMessage().c_str())); } } // proton
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "transport_latch.h" #include <vespa/vespalib/util/stringfmt.h> using vespalib::make_string; using storage::spi::Result; namespace proton { TransportLatch::TransportLatch(uint32_t cnt) : _latch(cnt), _lock(), _result() { if (cnt == 0u) { _result = std::make_unique<Result>(); } } TransportLatch::~TransportLatch() = default; void TransportLatch::send(ResultUP result, bool documentWasFound) { { std::lock_guard<std::mutex> guard(_lock); if (!_result) { _result = std::move(result); } else if (result->hasError()) { _result.reset(new Result(mergeErrorResults(*_result, *result))); } else if (documentWasFound) { _result = std::move(result); } } _latch.countDown(); } Result TransportLatch::mergeErrorResults(const Result &lhs, const Result &rhs) { Result::ErrorType error = (lhs.getErrorCode() > rhs.getErrorCode() ? lhs : rhs).getErrorCode(); return Result(error, make_string("%s, %s", lhs.getErrorMessage().c_str(), rhs.getErrorMessage().c_str())); } } // proton
Add code to find text "this turn" and set flag
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <Rosetta/Cards/Cards.hpp> #include <Rosetta/Enchants/Effects.hpp> #include <Rosetta/Enchants/Enchants.hpp> #include <regex> namespace RosettaStone { Enchant Enchants::GetEnchantFromText(const std::string& cardID) { std::vector<Effect> effects; static std::regex attackHealthRegex("\\+([[:digit:]]+)/\\+([[:digit:]]+)"); static std::regex attackRegex("\\+([[:digit:]]+) Attack"); const std::string text = Cards::FindCardByID(cardID).text; std::smatch values; if (std::regex_search(text, values, attackHealthRegex)) { effects.emplace_back(Effects::AttackN(std::stoi(values[1].str()))); effects.emplace_back(Effects::HealthN(std::stoi(values[2].str()))); } else if (std::regex_search(text, values, attackRegex)) { effects.emplace_back(Effects::AttackN(std::stoi(values[1].str()))); } return Enchant(effects); } } // namespace RosettaStone
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <Rosetta/Cards/Cards.hpp> #include <Rosetta/Enchants/Effects.hpp> #include <Rosetta/Enchants/Enchants.hpp> #include <regex> namespace RosettaStone { Enchant Enchants::GetEnchantFromText(const std::string& cardID) { std::vector<Effect> effects; bool isOneTurn = false; static std::regex attackHealthRegex("\\+([[:digit:]]+)/\\+([[:digit:]]+)"); static std::regex attackRegex("\\+([[:digit:]]+) Attack"); const std::string text = Cards::FindCardByID(cardID).text; std::smatch values; if (std::regex_search(text, values, attackHealthRegex)) { effects.emplace_back(Effects::AttackN(std::stoi(values[1].str()))); effects.emplace_back(Effects::HealthN(std::stoi(values[2].str()))); } else if (std::regex_search(text, values, attackRegex)) { effects.emplace_back(Effects::AttackN(std::stoi(values[1].str()))); } if (text.find("this turn") != std::string::npos) { isOneTurn = true; } return Enchant(effects, isOneTurn); } } // namespace RosettaStone
Update AnalogOut pinname in the test
#include "test_env.h" #if defined(TARGET_K64F) AnalogIn in(A0); AnalogOut out(A5); #elif defined(TARGET_KL25Z) AnalogIn in(PTC2); AnalogOut out(PTE30); #elif defined(TARGET_KL05Z) AnalogIn in(PTB11); // D9 AnalogOut out(PTB1); // D1 #elif defined(TARGET_KL46Z) AnalogIn in(PTB0); AnalogOut out(PTE30); #else AnalogIn in(p17); AnalogOut out(p18); #endif #define ERROR_TOLLERANCE 0.05 int main() { bool check = true; for (float out_value=0.0; out_value<1.1; out_value+=0.1) { out.write(out_value); wait(0.1); float in_value = in.read(); float diff = fabs(out_value - in_value); if (diff > ERROR_TOLLERANCE) { check = false; printf("ERROR (out:%.4f) - (in:%.4f) = (%.4f)"NL, out_value, in_value, diff); } else { printf("OK (out:%.4f) - (in:%.4f) = (%.4f)"NL, out_value, in_value, diff); } } notify_completion(check); }
#include "test_env.h" #if defined(TARGET_K64F) AnalogIn in(A0); AnalogOut out(DAC0_OUT); #elif defined(TARGET_KL25Z) AnalogIn in(PTC2); AnalogOut out(PTE30); #elif defined(TARGET_KL05Z) AnalogIn in(PTB11); // D9 AnalogOut out(PTB1); // D1 #elif defined(TARGET_KL46Z) AnalogIn in(PTB0); AnalogOut out(PTE30); #else AnalogIn in(p17); AnalogOut out(p18); #endif #define ERROR_TOLLERANCE 0.05 int main() { bool check = true; for (float out_value=0.0; out_value<1.1; out_value+=0.1) { out.write(out_value); wait(0.1); float in_value = in.read(); float diff = fabs(out_value - in_value); if (diff > ERROR_TOLLERANCE) { check = false; printf("ERROR (out:%.4f) - (in:%.4f) = (%.4f)"NL, out_value, in_value, diff); } else { printf("OK (out:%.4f) - (in:%.4f) = (%.4f)"NL, out_value, in_value, diff); } } notify_completion(check); }
Fix compilation error caused by tgmath.h.
#include <tgmath.h> typedef struct { float f; int i; } my_untagged_struct; double multiply(my_untagged_struct *s) { return s->f * s->i; } double multiply(my_untagged_struct *s, int x) { return multiply(s) * x; } int main(int argc, char **argv) { my_untagged_struct s = { .f = (float)argc, .i = argc, }; // lldb testsuite break return !(multiply(&s, argc) == pow(argc, 3)); }
#include <cmath> typedef struct { float f; int i; } my_untagged_struct; double multiply(my_untagged_struct *s) { return s->f * s->i; } double multiply(my_untagged_struct *s, int x) { return multiply(s) * x; } int main(int argc, char **argv) { my_untagged_struct s = { .f = (float)argc, .i = argc, }; // lldb testsuite break return !(multiply(&s, argc) == pow(argc, 3)); }
Mark local transform dirty when camera zoom changes
// Copyright (C) 2015 Elviss Strazdins // This file is part of the Ouzel engine. #include "Camera.h" namespace ouzel { Camera::Camera() { } Camera::~Camera() { } void Camera::setZoom(float zoom) { _zoom = zoom; if (_zoom < 0.1f) { _zoom = 0.1f; } _transformDirty = _inverseTransformDirty = true; } void Camera::calculateLocalTransform() const { Matrix4 translation; translation.translate(-_position.x, -_position.y, 0.0f); Matrix4 rotation; rotation.rotate(Vector3(0.0f, 0.0f, -1.0f), -_rotation); Matrix4 scale; scale.scale(_zoom); _localTransform = scale * rotation * translation; _localTransformDirty = false; } void Camera::calculateTransform() const { if (_localTransformDirty) { calculateLocalTransform(); } _transform = _parentTransform * _localTransform; _transformDirty = false; for (NodePtr child : _children) { child->updateTransform(_transform); } } }
// Copyright (C) 2015 Elviss Strazdins // This file is part of the Ouzel engine. #include "Camera.h" namespace ouzel { Camera::Camera() { } Camera::~Camera() { } void Camera::setZoom(float zoom) { _zoom = zoom; if (_zoom < 0.1f) { _zoom = 0.1f; } _localTransformDirty = _transformDirty = _inverseTransformDirty = true; } void Camera::calculateLocalTransform() const { Matrix4 translation; translation.translate(-_position.x, -_position.y, 0.0f); Matrix4 rotation; rotation.rotate(Vector3(0.0f, 0.0f, -1.0f), -_rotation); Matrix4 scale; scale.scale(_zoom); _localTransform = scale * rotation * translation; _localTransformDirty = false; } void Camera::calculateTransform() const { if (_localTransformDirty) { calculateLocalTransform(); } _transform = _parentTransform * _localTransform; _transformDirty = false; for (NodePtr child : _children) { child->updateTransform(_transform); } } }
Update log message; skin -> language
#include "LanguageTranslator.h" #include "Logger.h" #include "StringUtils.h" LanguageTranslator::LanguageTranslator(std::wstring langFileName) { CLOG(L"Loading skin XML: %s", langFileName.c_str()); std::string u8FileName = StringUtils::Narrow(langFileName); tinyxml2::XMLError result = _xml.LoadFile(u8FileName.c_str()); if (result != tinyxml2::XMLError::XML_SUCCESS) { if (result == tinyxml2::XMLError::XML_ERROR_FILE_NOT_FOUND) { //Error::ErrorMessageDie(SKINERR_INVALID_SKIN); } throw std::logic_error("Failed to read XML file!"); } _root = _xml.GetDocument()->FirstChildElement("translation"); if (_root == NULL) { throw std::runtime_error("Could not find root XML element"); } } std::wstring LanguageTranslator::Translate(std::wstring str) { return str; }
#include "LanguageTranslator.h" #include "Logger.h" #include "StringUtils.h" LanguageTranslator::LanguageTranslator() { } LanguageTranslator::LanguageTranslator(std::wstring langFileName) { CLOG(L"Loading language XML: %s", langFileName.c_str()); std::string u8FileName = StringUtils::Narrow(langFileName); tinyxml2::XMLError result = _xml.LoadFile(u8FileName.c_str()); if (result != tinyxml2::XMLError::XML_SUCCESS) { if (result == tinyxml2::XMLError::XML_ERROR_FILE_NOT_FOUND) { //Error::ErrorMessageDie(SKINERR_INVALID_SKIN); } throw std::logic_error("Failed to read XML file!"); } _root = _xml.GetDocument()->FirstChildElement("translation"); if (_root == NULL) { throw std::runtime_error("Could not find root XML element"); } } std::wstring LanguageTranslator::Translate(std::wstring str) { return str; }
Fix a last-minute typo and make the test not emit temporaries.
// RUN: clang-cc %s template <typename T> struct Num { T value_; public: Num(T value) : value_(value) {} T get() const { return value_; } template <typename U> struct Rep { U count_; Rep(U count) : count_(count) {} friend Num operator*(const Num &a, const Rep &n) { Num x = 0; for (U count = n.count_; count; --count) x += a; return x; } }; friend Num operator+(const Num &a, const Num &b) { return a.value_ + b.value_; } Num& operator+=(const Num& b) { value_ += b.value_; return *this; } }; int calc1() { Num<int> left = -1; Num<int> right = 1; Num<int> result = left + right; return result.get(); } int calc2() { Num<int> x = 3; Num<int>::Rep<char> n = (cast) 10; Num<int> result = x * n; return result.get(); }
// RUN: clang-cc -emit-llvm-only %s template <typename T> struct Num { T value_; public: Num(T value) : value_(value) {} T get() const { return value_; } template <typename U> struct Rep { U count_; Rep(U count) : count_(count) {} friend Num operator*(const Num &a, const Rep &n) { Num x = 0; for (U count = n.count_; count; --count) x += a; return x; } }; friend Num operator+(const Num &a, const Num &b) { return a.value_ + b.value_; } Num& operator+=(const Num& b) { value_ += b.value_; return *this; } }; int calc1() { Num<int> left = -1; Num<int> right = 1; Num<int> result = left + right; return result.get(); } int calc2() { Num<int> x = 3; Num<int>::Rep<char> n = (char) 10; Num<int> result = x * n; return result.get(); }
Implement querying CPU time from /proc/stat on Linux for systemInfo.cpu API
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/api/system_info_cpu/cpu_info_provider.h" namespace extensions { bool CpuInfoProvider::QueryCpuTimePerProcessor(std::vector<CpuTime>* times) { // TODO(hongbo): Query the cpu time from /proc/stat. return false; } } // namespace extensions
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/api/system_info_cpu/cpu_info_provider.h" #include <cstdio> #include <iostream> #include "base/file_util.h" #include "base/format_macros.h" namespace extensions { namespace { const char kProcStat[] = "/proc/stat"; } // namespace bool CpuInfoProvider::QueryCpuTimePerProcessor(std::vector<CpuTime>* times) { DCHECK(times); std::string contents; if (!file_util::ReadFileToString(FilePath(kProcStat), &contents)) return false; std::istringstream iss(contents); uint64 user = 0, nice = 0, sys = 0, idle = 0; std::string line; // Skip the first line because it is just an aggregated number of // all cpuN lines. std::getline(iss, line); std::vector<CpuTime> results; while (std::getline(iss, line)) { if (line.compare(0, 3, "cpu") != 0) continue; sscanf(line.c_str(), "%*s %"PRIu64" %"PRIu64" %"PRIu64" %"PRIu64, &user, &nice, &sys, &idle); CpuTime time; time.kernel = sys; time.user = user + nice; time.idle = idle; results.push_back(time); } times->swap(results); return true; } } // namespace extensions
Make c++11 example more realistic
#include <iostream> #include <thread> void call_from_thread() { std::cout << "Hello, World" << std::endl; } int main() { //Launch a thread std::thread t[5]; for(int i = 0; i < 5; i++){ t[i] = std::thread(call_from_thread); } for(int i = 0; i < 5; i++){ t[i].join(); } return 0; }
#include <thread> #include <iostream> #include <vector> void hello(){ std::cout << "Hello, world" << std::endl; } int main(){ std::vector<std::thread> threads; for(int i = 0; i < 5; ++i){ threads.push_back(std::thread(hello)); } for(auto& thread : threads){ thread.join(); } return 0; }
Fix undefined behavior in memcpy
// Copyright 2021 The Pigweed Authors // // 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 // // https://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 "pw_transfer/internal/chunk_data_buffer.h" #include <cstring> #include "pw_assert/assert.h" namespace pw::transfer::internal { void ChunkDataBuffer::Write(ConstByteSpan data, bool last_chunk) { PW_DASSERT(data.size() <= buffer_.size()); std::memcpy(buffer_.data(), data.data(), data.size()); size_ = data.size(); last_chunk_ = last_chunk; } } // namespace pw::transfer::internal
// Copyright 2021 The Pigweed Authors // // 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 // // https://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 "pw_transfer/internal/chunk_data_buffer.h" #include <algorithm> #include <cstring> #include "pw_assert/assert.h" namespace pw::transfer::internal { void ChunkDataBuffer::Write(ConstByteSpan data, bool last_chunk) { PW_DASSERT(data.size() <= buffer_.size()); std::copy(data.begin(), data.end(), buffer_.begin()); size_ = data.size(); last_chunk_ = last_chunk; } } // namespace pw::transfer::internal
Fix unit crc8 unit test
#include <gtest/gtest.h> #include <teraranger_hub/teraranger_one.h> class HubParserTest : public ::testing::Test{ protected: uint8_t input_buffer[BUFFER_SIZE] = {0x54,0x48,0x08,0xa7,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x0b};//expected result is one 2.22 meter measurement }; TEST_F(HubParserTest, crc8Test){ int16_t crc = teraranger_hub::crc8(input_buffer, 18); EXPECT_EQ(crc, input_buffer[18]); } TEST_F(HubParserTest, parsingTest){ float result = teraranger_hub::two_chars_to_float(input_buffer[2],input_buffer[3]); ASSERT_FLOAT_EQ(result, 2215); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
#include <gtest/gtest.h> #include <teraranger_hub/teraranger_one.h> #include <teraranger_hub/helper_lib.h> class HubParserTest : public ::testing::Test{ protected: uint8_t input_buffer[BUFFER_SIZE] = {0x54,0x48,0x08,0xa7,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x0b};//expected result is one 2.22 meter measurement }; TEST_F(HubParserTest, crc8Test){ int16_t crc = teraranger_hub::HelperLib::crc8(input_buffer, 18); EXPECT_EQ(crc, input_buffer[18]); } TEST_F(HubParserTest, parsingTest){ float result = teraranger_hub::two_chars_to_float(input_buffer[2],input_buffer[3]); ASSERT_FLOAT_EQ(result, 2215); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
Fix warning in open location code library
#include "codearea.h" #include <algorithm> namespace openlocationcode { const double kLatitudeMaxDegrees = 90; const double kLongitudeMaxDegrees = 180; CodeArea::CodeArea(double latitude_lo, double longitude_lo, double latitude_hi, double longitude_hi, size_t code_length) { latitude_lo_ = latitude_lo; longitude_lo_ = longitude_lo; latitude_hi_ = latitude_hi; longitude_hi_ = longitude_hi; code_length_ = code_length; } double CodeArea::GetLatitudeLo() const{ return latitude_lo_; } double CodeArea::GetLongitudeLo() const { return longitude_lo_; } double CodeArea::GetLatitudeHi() const { return latitude_hi_; } double CodeArea::GetLongitudeHi() const { return longitude_hi_; } size_t CodeArea::GetCodeLength() const { return code_length_; } LatLng CodeArea::GetCenter() const { double latitude_center = std::min(latitude_lo_ + (latitude_hi_ - latitude_lo_) / 2, kLatitudeMaxDegrees); double longitude_center = std::min(longitude_lo_ + (longitude_hi_ - longitude_lo_) / 2, kLongitudeMaxDegrees); LatLng center = {latitude: latitude_center, longitude: longitude_center}; return center; } } // namespace openlocationcode
#include "codearea.h" #include <algorithm> namespace openlocationcode { const double kLatitudeMaxDegrees = 90; const double kLongitudeMaxDegrees = 180; CodeArea::CodeArea(double latitude_lo, double longitude_lo, double latitude_hi, double longitude_hi, size_t code_length) { latitude_lo_ = latitude_lo; longitude_lo_ = longitude_lo; latitude_hi_ = latitude_hi; longitude_hi_ = longitude_hi; code_length_ = code_length; } double CodeArea::GetLatitudeLo() const{ return latitude_lo_; } double CodeArea::GetLongitudeLo() const { return longitude_lo_; } double CodeArea::GetLatitudeHi() const { return latitude_hi_; } double CodeArea::GetLongitudeHi() const { return longitude_hi_; } size_t CodeArea::GetCodeLength() const { return code_length_; } LatLng CodeArea::GetCenter() const { double latitude_center = std::min(latitude_lo_ + (latitude_hi_ - latitude_lo_) / 2, kLatitudeMaxDegrees); double longitude_center = std::min(longitude_lo_ + (longitude_hi_ - longitude_lo_) / 2, kLongitudeMaxDegrees); LatLng center{latitude_center, longitude_center}; return center; } } // namespace openlocationcode
Add test for setting coordinates
#include <gmi_mesh.h> #include <gmi_null.h> #include <apfMDS.h> #include <apfMesh2.h> #include <apfConvert.h> #include <apf.h> #include <PCU.h> int main(int argc, char** argv) { assert(argc==3); MPI_Init(&argc,&argv); PCU_Comm_Init(); PCU_Protect(); gmi_register_mesh(); gmi_register_null(); int* conn; int nelem; int etype; apf::Mesh2* m = apf::loadMdsMesh(argv[1],argv[2]); int dim = m->getDimension(); destruct(m, conn, nelem, etype); m->destroyNative(); apf::destroyMesh(m); gmi_model* model = gmi_load(".null"); m = apf::makeEmptyMdsMesh(model, dim, false); apf::GlobalToVert outMap; apf::construct(m, conn, nelem, etype, outMap); outMap.clear(); delete [] conn; apf::alignMdsRemotes(m); apf::deriveMdsModel(m); m->verify(); m->destroyNative(); apf::destroyMesh(m); PCU_Comm_Free(); MPI_Finalize(); }
#include <gmi_mesh.h> #include <gmi_null.h> #include <apfMDS.h> #include <apfMesh2.h> #include <apfConvert.h> #include <apf.h> #include <PCU.h> int main(int argc, char** argv) { assert(argc==3); MPI_Init(&argc,&argv); PCU_Comm_Init(); PCU_Protect(); gmi_register_mesh(); gmi_register_null(); int* conn; double* coords; int nelem; int etype; int nverts; apf::Mesh2* m = apf::loadMdsMesh(argv[1],argv[2]); int dim = m->getDimension(); extractCoords(m, coords, nverts); destruct(m, conn, nelem, etype); m->destroyNative(); apf::destroyMesh(m); gmi_model* model = gmi_load(".null"); m = apf::makeEmptyMdsMesh(model, dim, false); apf::GlobalToVert outMap; apf::construct(m, conn, nelem, etype, outMap); delete [] conn; apf::alignMdsRemotes(m); apf::deriveMdsModel(m); apf::setCoords(m, coords, nverts, outMap); delete [] coords; outMap.clear(); m->verify(); //apf::writeVtkFiles("after", m); m->destroyNative(); apf::destroyMesh(m); PCU_Comm_Free(); MPI_Finalize(); }
Change the stub for file_util::EvictFileFromSystemCache
// Copyright (c) 2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/test_file_util.h" #include "base/logging.h" namespace file_util { bool EvictFileFromSystemCache(const FilePath& file) { // TODO(port): Implement. NOTIMPLEMENTED(); return false; } } // namespace file_util
// Copyright (c) 2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/test_file_util.h" #include "base/logging.h" namespace file_util { bool EvictFileFromSystemCache(const FilePath& file) { // There is no way that we can think of to dump something from the UBC. You // can add something so when you open it, it doesn't go in, but that won't // work here. return true; } } // namespace file_util
Test the COM Port assignments in the AWG class
#include <gtest/gtest.h> #include "../src/awg.hpp" #include "../src/pulseTrain.hpp" class AWGConstructors : public ::testing::Test { protected: }; class AWGAcessors : public ::testing::Test { protected: }; int main(int argc, char * argv[] ) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
#include <gtest/gtest.h> #include "../src/awg.hpp" #include "../src/pulseTrain.hpp" TEST(AwgClass, ComPort) { awg testAwg; EXPECT_EQ(std::string("COM1"),testAwg.comPort()); testAwg.comPort(2); EXPECT_EQ(std::string("COM2"),testAwg.comPort()); testAwg.comPort("com1"); EXPECT_EQ(std::string("com1"),testAwg.comPort()); } int main(int argc, char * argv[] ) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
Fix return value in create()
#include <unordered_map> #include <mutex> #include "../os.h" #include "test_lib.h" #include "../../../intercom-cpp/src/cominterop.h" #include "../../../intercom-cpp/src/activator.h" using intercom::Activator; void InitializeRuntime() { } void UninitializeRuntime() { } intercom::HRESULT CreateInstance( intercom::REFCLSID clsid, intercom::REFIID iid, void** pout ) { Activator activate( test_lib::Descriptor::NAME, clsid ); activate.create( iid, pout ); return S_OK; }
#include <unordered_map> #include <mutex> #include "../os.h" #include "test_lib.h" #include "../../../intercom-cpp/src/cominterop.h" #include "../../../intercom-cpp/src/activator.h" using intercom::Activator; void InitializeRuntime() { } void UninitializeRuntime() { } intercom::HRESULT CreateInstance( intercom::REFCLSID clsid, intercom::REFIID iid, void** pout ) { Activator activate( test_lib::Descriptor::NAME, clsid ); return activate.create( iid, pout ); }
Print newline in usage in rewrite
//------------------------------------------------------------------------------ // rewriter.cpp // Simple tool that parses an input file and writes it back out; used // for verifying the round-trip nature of the parse tree. // // File is under the MIT license; see LICENSE for details //------------------------------------------------------------------------------ #include <cstdio> #if defined(_WIN32) # include <fcntl.h> # include <io.h> #endif #include <filesystem> #include "slang/syntax/SyntaxPrinter.h" #include "slang/syntax/SyntaxTree.h" using namespace slang; int main(int argc, char** argv) try { if (argc != 2) { fprintf(stderr, "usage: rewriter file"); return 1; } // Make sure we reproduce newlines correctly on Windows: #if defined(_WIN32) _setmode(_fileno(stdout), _O_BINARY); #endif if (!std::filesystem::exists(argv[1])) { fprintf(stderr, "File does not exist: %s\n", argv[1]); return 1; } if (!std::filesystem::is_regular_file(argv[1])) { fprintf(stderr, "%s is not a file\n", argv[1]); return 1; } auto tree = SyntaxTree::fromFile(argv[1]); printf("%s", SyntaxPrinter::printFile(*tree).c_str()); return 0; } catch (const std::exception& e) { printf("internal compiler error (exception): %s\n", e.what()); return 2; }
//------------------------------------------------------------------------------ // rewriter.cpp // Simple tool that parses an input file and writes it back out; used // for verifying the round-trip nature of the parse tree. // // File is under the MIT license; see LICENSE for details //------------------------------------------------------------------------------ #include <cstdio> #if defined(_WIN32) # include <fcntl.h> # include <io.h> #endif #include <filesystem> #include "slang/syntax/SyntaxPrinter.h" #include "slang/syntax/SyntaxTree.h" using namespace slang; int main(int argc, char** argv) try { if (argc != 2) { fprintf(stderr, "usage: rewriter file\n"); return 1; } // Make sure we reproduce newlines correctly on Windows: #if defined(_WIN32) _setmode(_fileno(stdout), _O_BINARY); #endif if (!std::filesystem::exists(argv[1])) { fprintf(stderr, "File does not exist: %s\n", argv[1]); return 1; } if (!std::filesystem::is_regular_file(argv[1])) { fprintf(stderr, "%s is not a file\n", argv[1]); return 1; } auto tree = SyntaxTree::fromFile(argv[1]); printf("%s", SyntaxPrinter::printFile(*tree).c_str()); return 0; } catch (const std::exception& e) { printf("internal compiler error (exception): %s\n", e.what()); return 2; }
Use the new actions plugins
/* <one line to give the program's name and a brief idea of what it does.> Copyright (C) 2013 David Edmundson <D.Edmundson@lboro.ac.uk> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "person-plugin-manager.h" #include <QAction> #include "abstract-person-plugin.h" PersonPluginManager::PersonPluginManager(QObject* parent): QObject(parent) { } PersonPluginManager::~PersonPluginManager() { qDeleteAll(m_plugins); } QList<QAction*> PersonPluginManager::actionsForPerson(PersonData* person, QObject* parent) { QList<QAction*> actions; Q_FOREACH(AbstractPersonPlugin *plugin, m_plugins) { actions << plugin->actionsForPerson(person, parent); } return actions; }
/* <one line to give the program's name and a brief idea of what it does.> Copyright (C) 2013 David Edmundson <D.Edmundson@lboro.ac.uk> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "person-plugin-manager.h" #include <QAction> #include "abstract-person-plugin.h" #include "plugins/im-plugin.h" #include "plugins/email-plugin.h" PersonPluginManager::PersonPluginManager(QObject* parent): QObject(parent) { m_plugins << new IMPlugin(this); m_plugins << new EmailPlugin(this); } PersonPluginManager::~PersonPluginManager() { qDeleteAll(m_plugins); } QList<QAction*> PersonPluginManager::actionsForPerson(PersonData* person, QObject* parent) { QList<QAction*> actions; Q_FOREACH(AbstractPersonPlugin *plugin, m_plugins) { actions << plugin->actionsForPerson(person, parent); } return actions; }
Make protocol regexes case insensitive
#include "MessageBuilder.hpp" #include "common/LinkParser.hpp" #include "singletons/Emotes.hpp" #include "singletons/Resources.hpp" #include "singletons/Theme.hpp" #include <QDateTime> namespace chatterino { MessageBuilder::MessageBuilder() : message(new Message) { } MessagePtr MessageBuilder::getMessage() { return this->message; } void MessageBuilder::append(MessageElement *element) { this->message->addElement(element); } void MessageBuilder::appendTimestamp() { this->appendTimestamp(QTime::currentTime()); } void MessageBuilder::setHighlight(bool value) { if (value) { this->message->flags |= Message::Highlighted; } else { this->message->flags &= ~Message::Highlighted; } } void MessageBuilder::appendTimestamp(const QTime &time) { this->append(new TimestampElement(time)); } QString MessageBuilder::matchLink(const QString &string) { LinkParser linkParser(string); static QRegularExpression httpRegex("\\bhttps?://"); static QRegularExpression ftpRegex("\\bftps?://"); if (!linkParser.hasMatch()) { return QString(); } QString captured = linkParser.getCaptured(); if (!captured.contains(httpRegex)) { if (!captured.contains(ftpRegex)) { captured.insert(0, "http://"); } } return captured; } } // namespace chatterino
#include "MessageBuilder.hpp" #include "common/LinkParser.hpp" #include "singletons/Emotes.hpp" #include "singletons/Resources.hpp" #include "singletons/Theme.hpp" #include <QDateTime> namespace chatterino { MessageBuilder::MessageBuilder() : message(new Message) { } MessagePtr MessageBuilder::getMessage() { return this->message; } void MessageBuilder::append(MessageElement *element) { this->message->addElement(element); } void MessageBuilder::appendTimestamp() { this->appendTimestamp(QTime::currentTime()); } void MessageBuilder::setHighlight(bool value) { if (value) { this->message->flags |= Message::Highlighted; } else { this->message->flags &= ~Message::Highlighted; } } void MessageBuilder::appendTimestamp(const QTime &time) { this->append(new TimestampElement(time)); } QString MessageBuilder::matchLink(const QString &string) { LinkParser linkParser(string); static QRegularExpression httpRegex("\\bhttps?://", QRegularExpression::CaseInsensitiveOption); static QRegularExpression ftpRegex("\\bftps?://", QRegularExpression::CaseInsensitiveOption); if (!linkParser.hasMatch()) { return QString(); } QString captured = linkParser.getCaptured(); if (!captured.contains(httpRegex)) { if (!captured.contains(ftpRegex)) { captured.insert(0, "http://"); } } return captured; } } // namespace chatterino
Fix order of animation update
#include "stdafx.h" #include <dukat/animationmanager.h> namespace dukat { Animation* AnimationManager::add(std::unique_ptr<Animation> animation) { auto anim = animation.get(); animations.push_back(std::move(animation)); if (!anim->is_running()) { anim->start(); } return anim; } void AnimationManager::cancel(Animation* animation) { auto it = std::find_if(animations.begin(), animations.end(), [animation](const std::unique_ptr<Animation>& anim) { return animation == anim.get(); }); if (it != animations.end()) (*it)->stop(); // don't erase here - update will take care of that } void AnimationManager::update(float delta) { for (auto it = animations.begin(); it != animations.end(); ) { (*it)->step(delta); if ((*it)->is_done()) { it = animations.erase(it); } else { ++it; } } } }
#include "stdafx.h" #include <dukat/animationmanager.h> namespace dukat { Animation* AnimationManager::add(std::unique_ptr<Animation> animation) { auto anim = animation.get(); animations.push_back(std::move(animation)); if (!anim->is_running()) { anim->start(); } return anim; } void AnimationManager::cancel(Animation* animation) { auto it = std::find_if(animations.begin(), animations.end(), [animation](const std::unique_ptr<Animation>& anim) { return animation == anim.get(); }); if (it != animations.end()) (*it)->stop(); // don't erase here - update will take care of that } void AnimationManager::update(float delta) { for (auto it = animations.begin(); it != animations.end(); ) { if ((*it)->is_done()) { it = animations.erase(it); } else { (*it)->step(delta); ++it; } } } }
Make button turn off after time ends
#include "game.h" #include "button.h" #include "screen.h" #include "led.h" #include "timer.h" #include "const.h" #include "logger.h" #include "helper.h" #include "controller.h" namespace game { namespace { const unsigned long GAME_TIME = 3000; unsigned long endTime; unsigned int buttonsPressed = 0; void countDown() { screen::display("3"); helper::waitTime(1000); screen::display("2"); helper::waitTime(1000); screen::display("1"); helper::waitTime(1000); } void runMain() { while (millis() < endTime) { //Generate random button int buttonNumber = random(0, constants::NUMBER_OF_LEDS - 1); //Turn on led and wait for button press led::turnOn(buttonNumber); while(not button::isPressed(buttonNumber)){ controller::run(); } led::turnOff(buttonNumber); //Increment counter buttonsPressed ++; } } } unsigned long getRemainingTime() { unsigned long remainingTime = endTime - millis(); if (remainingTime > 0) { return remainingTime; } return 0; } void start() { countDown(); endTime = GAME_TIME + millis(); timer::start(); runMain(); timer::stop(); screen::display(String(buttonsPressed) + " buttons pressed"); } }
#include "game.h" #include "button.h" #include "screen.h" #include "led.h" #include "timer.h" #include "const.h" #include "logger.h" #include "helper.h" #include "controller.h" namespace game { namespace { const unsigned long GAME_TIME = 3000; unsigned long endTime; unsigned int buttonsPressed = 0; void countDown() { screen::display("3"); helper::waitTime(1000); screen::display("2"); helper::waitTime(1000); screen::display("1"); helper::waitTime(1000); } void runMain() { while (millis() < endTime) { //Generate random button int buttonNumber = random(0, constants::NUMBER_OF_LEDS - 1); //Turn on led and wait for button press led::turnOn(buttonNumber); while(not button::isPressed(buttonNumber) and millis() < endTime){ controller::run(); } if (millis() < endTime){ buttonsPressed ++; //Increment counter } led::turnOff(buttonNumber); } } } unsigned long getRemainingTime() { unsigned long remainingTime = endTime - millis(); if (remainingTime > 0) { return remainingTime; } return 0; } void start() { countDown(); endTime = GAME_TIME + millis(); timer::start(); runMain(); timer::stop(); screen::display(String(buttonsPressed) + " buttons pressed"); } }
Check setup return value to stop the FSM if false
#include "YarpStateDirector.hpp" const int rd::YarpStateDirector::DEFAULT_RATE_MS = 100; rd::YarpStateDirector::YarpStateDirector(rd::State *state) : StateDirector(state), RateThread(DEFAULT_RATE_MS) { } bool rd::YarpStateDirector::Start() { RD_DEBUG("Starting StateDirector for id %s\n", state->getStateId().c_str()); active = true; state->setup(); return yarp::os::RateThread::start(); } bool rd::YarpStateDirector::Stop() { RD_DEBUG("Stopping StateDirector for id %s\n", state->getStateId().c_str()); active = false; yarp::os::RateThread::askToStop(); yarp::os::RateThread::stop(); state->cleanup(); return true; } void rd::YarpStateDirector::run() { //RD_DEBUG("Entering loop in StateDirector with id %s\n", state->getStateId().c_str()); if ( !state->loop() ) { RD_ERROR("Error in loop. Stopping this state...\n"); this->Stop(); } int condition = state->evaluateConditions(); if (nextStates.find(condition) != nextStates.end()) { this->Stop(); nextStates.find(condition)->second->Start(); } }
#include "YarpStateDirector.hpp" const int rd::YarpStateDirector::DEFAULT_RATE_MS = 100; rd::YarpStateDirector::YarpStateDirector(rd::State *state) : StateDirector(state), RateThread(DEFAULT_RATE_MS) { } bool rd::YarpStateDirector::Start() { RD_DEBUG("Starting StateDirector for id %s\n", state->getStateId().c_str()); active = true; if (!state->setup()) { RD_ERROR("Error in state setup for id %s\n", state->getStateId.c_str()); return false; } return yarp::os::RateThread::start(); } bool rd::YarpStateDirector::Stop() { RD_DEBUG("Stopping StateDirector for id %s\n", state->getStateId().c_str()); active = false; yarp::os::RateThread::askToStop(); yarp::os::RateThread::stop(); state->cleanup(); return true; } void rd::YarpStateDirector::run() { //RD_DEBUG("Entering loop in StateDirector with id %s\n", state->getStateId().c_str()); if ( !state->loop() ) { RD_ERROR("Error in loop. Stopping this state...\n"); this->Stop(); } int condition = state->evaluateConditions(); if (nextStates.find(condition) != nextStates.end()) { this->Stop(); nextStates.find(condition)->second->Start(); } }
Fix a typo in a comment.
#include <cstddef> #include <string> // Emulates the standard std::string literal ("..."s) from C++14. Since 's' is // reserved by the standard, we have to use '_s' instead of 's'. std::string operator "" _s(const char *str, std::size_t length) { return std::string(str, length); } int main() { std::string s1 = "abc\x00xyz"; // s1 contains "abc" std::string s2 = "abc\x00xyz"_s; // s1 contains "abc\x00xyz" }
#include <cstddef> #include <string> // Emulates the standard std::string literal ("..."s) from C++14. Since 's' is // reserved by the standard, we have to use '_s' instead of 's'. std::string operator "" _s(const char *str, std::size_t length) { return std::string(str, length); } int main() { std::string s1 = "abc\x00xyz"; // s1 contains "abc" std::string s2 = "abc\x00xyz"_s; // s2 contains "abc\x00xyz" }
Disable WebKitThreadTest.ExposedInChromeThread, due to subsequent assert.
// 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/in_process_webkit/webkit_thread.h" #include "testing/gtest/include/gtest/gtest.h" TEST(WebKitThreadTest, ExposedInChromeThread) { int* null = NULL; // Help the template system out. EXPECT_FALSE(ChromeThread::DeleteSoon(ChromeThread::WEBKIT, FROM_HERE, null)); { WebKitThread thread; EXPECT_FALSE(ChromeThread::DeleteSoon(ChromeThread::WEBKIT, FROM_HERE, null)); thread.Initialize(); EXPECT_TRUE(ChromeThread::DeleteSoon(ChromeThread::WEBKIT, FROM_HERE, null)); } EXPECT_FALSE(ChromeThread::DeleteSoon(ChromeThread::WEBKIT, FROM_HERE, null)); }
// 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/in_process_webkit/webkit_thread.h" #include "testing/gtest/include/gtest/gtest.h" TEST(WebKitThreadTest, DISABLED_ExposedInChromeThread) { int* null = NULL; // Help the template system out. EXPECT_FALSE(ChromeThread::DeleteSoon(ChromeThread::WEBKIT, FROM_HERE, null)); { WebKitThread thread; EXPECT_FALSE(ChromeThread::DeleteSoon(ChromeThread::WEBKIT, FROM_HERE, null)); thread.Initialize(); EXPECT_TRUE(ChromeThread::DeleteSoon(ChromeThread::WEBKIT, FROM_HERE, null)); } EXPECT_FALSE(ChromeThread::DeleteSoon(ChromeThread::WEBKIT, FROM_HERE, null)); }
Fix runtime error on Windows
#include <stdlib.h> #include <cppfs/system.h> namespace cppfs { namespace system { std::string homeDir() { return std::string(getenv("HOME")); } std::string configDir(const std::string & application) { #if defined(SYSTEM_WINDOWS) return std::string(getenv("APPDATA")) + "\\" + application; #elif defined(SYSTEM_DARWIN) return std::string(getenv("HOME")) + "/Library/Preferences/" + application; #else return std::string(getenv("HOME")) + "/.config/" + application; #endif } } // namespace system } // namespace cppfs
#include <stdlib.h> #include <cppfs/system.h> namespace cppfs { namespace system { std::string homeDir() { #if defined(SYSTEM_WINDOWS) return std::string(getenv("HOMEPATH")); #else return std::string(getenv("HOME")); #endif } std::string configDir(const std::string & application) { #if defined(SYSTEM_WINDOWS) return std::string(getenv("APPDATA")) + "\\" + application; #elif defined(SYSTEM_DARWIN) return std::string(getenv("HOME")) + "/Library/Preferences/" + application; #else return std::string(getenv("HOME")) + "/.config/" + application; #endif } } // namespace system } // namespace cppfs
Add tests for the clear() and dequeue() methods.
#include "Queue.h" #include "gtest/gtest.h" /* The Queue data structure * Public interface: * enqueue() * dequeue() * size() * clear() * begin() * end() : one pass the last item * empty() */ class QueueTest : public testing::Test { protected: // SetUp() & TearDown() are virtual functions from testting::Test, // so we just signify that we override them here virtual void SetUp() { q1_.enqueue(1); q1_.enqueue(2); q2_.enqueue(1); q2_.enqueue(3); } virtual void TearDown() { } // setup fixtures Queue<int> q0_; Queue<int> q1_; Queue<int> q2_; }; // Use TEST_F to test with fixtures. TEST_F(QueueTest, DefaultConstructor) { EXPECT_EQ(0u, q0_.size()); } TEST_F(QueueTest, Enqueue){ EXPECT_EQ(2u, q1_.size()); EXPECT_EQ(2u, q2_.size()); q2_.enqueue(100); EXPECT_EQ(3u, q2_.size()); }
#include "Queue.h" #include "gtest/gtest.h" /* The Queue data structure * Public interface: * enqueue() * dequeue() * size() * clear() * begin() * end() : one pass the last item * empty() */ class QueueTest : public testing::Test { protected: // SetUp() & TearDown() are virtual functions from testting::Test, // so we just signify that we override them here virtual void SetUp() { q1_.enqueue(1); q1_.enqueue(2); q2_.enqueue(1); q2_.enqueue(3); } virtual void TearDown() { } // setup fixtures Queue<int> q0_; Queue<int> q1_; Queue<int> q2_; }; // Use TEST_F to test with fixtures. TEST_F(QueueTest, DefaultConstructor) { EXPECT_EQ(0u, q0_.size()); } TEST_F(QueueTest, enqueue){ EXPECT_EQ(2u, q1_.size()); EXPECT_EQ(2u, q2_.size()); q2_.enqueue(100); EXPECT_EQ(3u, q2_.size()); } TEST_F(QueueTest, clear) { q2_.clear(); EXPECT_TRUE(q2_.empty()); } TEST_F(QueueTest, dequeue) { int* pop_item = q1_.dequeue(); EXPECT_EQ(*pop_item, 1); EXPECT_EQ(q1_.size(), 1); delete pop_item; pop_item = q1_.dequeue(); EXPECT_EQ(*pop_item, 2); EXPECT_TRUE(q1_.empty()); // q1_ should be empty now. check it: delete pop_item; pop_item = q1_.dequeue(); EXPECT_EQ(nullptr, pop_item); }
Use ``nullptr`` instead of ``0`` or ``NULL``
#include "configuration.hh" namespace vick { char QUIT_KEY = 0; int TAB_SIZE = 1; void (*PUSH_BACK_CHANGE)(contents&, std::shared_ptr<change>) = 0; std::string DELIMINATORS = ""; bool use_colors() {return true;} void init_conf() {} void add_listeners() {} void add_commands( std::map<std::string, std::function<boost::optional<std::shared_ptr<change> >( contents&, boost::optional<int>)> >&) {} }
#include "configuration.hh" namespace vick { char QUIT_KEY = 0; int TAB_SIZE = 1; void (*PUSH_BACK_CHANGE)(contents&, std::shared_ptr<change>) = nullptr; std::string DELIMINATORS = ""; bool use_colors() {return true;} void init_conf() {} void add_listeners() {} void add_commands( std::map<std::string, std::function<boost::optional<std::shared_ptr<change> >( contents&, boost::optional<int>)> >&) {} }
Fix build failure of minikin_perftest
/* * Copyright (C) 2016 The Android Open Source Project * * 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 <cutils/log.h> #include <stdio.h> #include <sys/stat.h> #include <string> #include <vector> std::vector<uint8_t> readWholeFile(const std::string& filePath) { FILE* fp = fopen(filePath.c_str(), "r"); LOG_ALWAYS_FATAL_IF(fp == nullptr); struct stat st; LOG_ALWAYS_FATAL_IF(fstat(fileno(fp), &st) != 0); std::vector<uint8_t> result(st.st_size); LOG_ALWAYS_FATAL_IF(fread(result.data(), 1, st.st_size, fp) != st.st_size); fclose(fp); return result; }
/* * Copyright (C) 2016 The Android Open Source Project * * 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 <cutils/log.h> #include <stdio.h> #include <sys/stat.h> #include <string> #include <vector> std::vector<uint8_t> readWholeFile(const std::string& filePath) { FILE* fp = fopen(filePath.c_str(), "r"); LOG_ALWAYS_FATAL_IF(fp == nullptr); struct stat st; LOG_ALWAYS_FATAL_IF(fstat(fileno(fp), &st) != 0); std::vector<uint8_t> result(st.st_size); LOG_ALWAYS_FATAL_IF(fread(result.data(), 1, st.st_size, fp) != static_cast<size_t>(st.st_size)); fclose(fp); return result; }
Add a few missing newlines at eof.
// // Copyright (c) 2012-2013 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // ShaderExecutable9.cpp: Implements a D3D9-specific class to contain shader // executable implementation details. #include "libANGLE/renderer/d3d/d3d9/ShaderExecutable9.h" #include "common/debug.h" namespace rx { ShaderExecutable9::ShaderExecutable9(const void *function, size_t length, IDirect3DPixelShader9 *executable) : ShaderExecutableD3D(function, length) { mPixelExecutable = executable; mVertexExecutable = NULL; } ShaderExecutable9::ShaderExecutable9(const void *function, size_t length, IDirect3DVertexShader9 *executable) : ShaderExecutableD3D(function, length) { mVertexExecutable = executable; mPixelExecutable = NULL; } ShaderExecutable9::~ShaderExecutable9() { SafeRelease(mVertexExecutable); SafeRelease(mPixelExecutable); } IDirect3DVertexShader9 *ShaderExecutable9::getVertexShader() const { return mVertexExecutable; } IDirect3DPixelShader9 *ShaderExecutable9::getPixelShader() const { return mPixelExecutable; } }
// // Copyright (c) 2012-2013 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // ShaderExecutable9.cpp: Implements a D3D9-specific class to contain shader // executable implementation details. #include "libANGLE/renderer/d3d/d3d9/ShaderExecutable9.h" #include "common/debug.h" namespace rx { ShaderExecutable9::ShaderExecutable9(const void *function, size_t length, IDirect3DPixelShader9 *executable) : ShaderExecutableD3D(function, length) { mPixelExecutable = executable; mVertexExecutable = NULL; } ShaderExecutable9::ShaderExecutable9(const void *function, size_t length, IDirect3DVertexShader9 *executable) : ShaderExecutableD3D(function, length) { mVertexExecutable = executable; mPixelExecutable = NULL; } ShaderExecutable9::~ShaderExecutable9() { SafeRelease(mVertexExecutable); SafeRelease(mPixelExecutable); } IDirect3DVertexShader9 *ShaderExecutable9::getVertexShader() const { return mVertexExecutable; } IDirect3DPixelShader9 *ShaderExecutable9::getPixelShader() const { return mPixelExecutable; } }
Put newlines after more debug messages.
#include "buffers.h" #include "strutil.h" #include "log.h" void processQueue(ByteQueue* queue, bool (*callback)(uint8_t*)) { uint8_t snapshot[QUEUE_MAX_LENGTH(uint8_t)]; queue_snapshot(queue, snapshot); if(callback == NULL) { debug("Callback is NULL (%p) -- unable to handle queue at %p\r\n", callback, queue); return; } if(callback(snapshot)) { queue_init(queue); } else if(queue_full(queue)) { debug("Incoming write is too long"); queue_init(queue); } else if(strnchr((char*)snapshot, queue_length(queue), '\0') != NULL) { debug("Incoming buffered write corrupted -- clearing buffer"); queue_init(queue); } }
#include "buffers.h" #include "strutil.h" #include "log.h" void processQueue(ByteQueue* queue, bool (*callback)(uint8_t*)) { uint8_t snapshot[QUEUE_MAX_LENGTH(uint8_t)]; queue_snapshot(queue, snapshot); if(callback == NULL) { debug("Callback is NULL (%p) -- unable to handle queue at %p\r\n", callback, queue); return; } if(callback(snapshot)) { queue_init(queue); } else if(queue_full(queue)) { debug("Incoming write is too long\r\n"); queue_init(queue); } else if(strnchr((char*)snapshot, queue_length(queue), '\0') != NULL) { debug("Incoming buffered write corrupted -- clearing buffer\r\n"); queue_init(queue); } }
Set sphere function's objective value method to be const (missed this one)
#include <optimisationProblem/benchmark/sphereFunction.hpp> #include <cmath> using std::sqrt; using std::pow; #include <armadillo> using arma::norm; namespace hop { SphereFunction::SphereFunction(const unsigned int &numberOfDimensions) : BenchmarkProblem(numberOfDimensions) { } double SphereFunction::getObjectiveValueImplementation(const Col<double> &parameter) { return pow(norm(getRandomParameterTranslation(parameter)), 2); } }
#include <optimisationProblem/benchmark/sphereFunction.hpp> #include <cmath> using std::sqrt; using std::pow; #include <armadillo> using arma::norm; namespace hop { SphereFunction::SphereFunction(const unsigned int &numberOfDimensions) : BenchmarkProblem(numberOfDimensions) { } double SphereFunction::getObjectiveValueImplementation(const Col<double> &parameter) const { return pow(norm(getRandomParameterTranslation(parameter)), 2); } }
Add constants for unit test
#include "stdafx.h" #include "CppUnitTest.h" #include "datastore.h" using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; using DataStore = You::DataStore::DataStore; namespace YouDataStoreTests { TEST_CLASS(DataStoreApiTest) { public: DataStore sut; TEST_METHOD(DataStore_Post_Basic_Test) { bool result = sut.post(0, DataStore::STask()); Assert::IsTrue(result); } TEST_METHOD(DataStore_Post_DuplicateId_Test) { sut.post(0, DataStore::STask()); bool result = sut.post(0, DataStore::STask()); Assert::IsFalse(result); } TEST_METHOD(DataStore_Put_Basic_Test) { sut.post(0, DataStore::STask()); bool result = sut.put(0, DataStore::STask()); Assert::IsTrue(result); } }; } // namespace YouDataStoreTests
#include "stdafx.h" #include "CppUnitTest.h" #include "datastore.h" using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; using DataStore = You::DataStore::DataStore; namespace YouDataStoreTests { const std::wstring TASK_ID = L"id"; const std::wstring DESCRIPTION = L"desc"; const std::wstring DEADLINE = L"deadl"; const std::wstring PRIORITY = L"pri"; const std::wstring DEPENDENCIES = L"depend"; const DataStore::STask stask = { { TASK_ID, L"0" }, { DESCRIPTION, L"bla bla" }, { DEADLINE, L"xxxxxx" }, { PRIORITY, L"urgent" }, { DEPENDENCIES, L"12345" } }; TEST_CLASS(DataStoreApiTest) { public: DataStore sut; TEST_METHOD(DataStore_Post_Basic_Test) { bool result = sut.post(0, DataStore::STask()); Assert::IsTrue(result); } TEST_METHOD(DataStore_Post_DuplicateId_Test) { sut.post(0, DataStore::STask()); bool result = sut.post(0, DataStore::STask()); Assert::IsFalse(result); } TEST_METHOD(DataStore_Put_Basic_Test) { sut.post(0, DataStore::STask()); bool result = sut.put(0, DataStore::STask()); Assert::IsTrue(result); } }; } // namespace YouDataStoreTests
Remove --check-prefix=CHECK as it's useless
// RUN: %clangxx_asan -O0 %s -Fe%t 2>&1 // 'cat' is used below to work around FileCheck buffering bug which makes this // test flaky. FIXME: file an issue. // RUN: not %run %t 2>&1 | cat | FileCheck %s --check-prefix=CHECK #include <windows.h> DWORD WINAPI thread_proc(void *context) { int subscript = -1; volatile char stack_buffer[42]; stack_buffer[subscript] = 42; // CHECK: AddressSanitizer: stack-buffer-overflow on address [[ADDR:0x[0-9a-f]+]] // CHECK: WRITE of size 1 at [[ADDR]] thread T1 // CHECK: {{#0 .* thread_proc .*thread_stack_array_left_oob.cc}}:[[@LINE-3]] // CHECK: Address [[ADDR]] is located in stack of thread T1 at offset {{.*}} in frame // CHECK: thread_proc return 0; } int main(void) { HANDLE thr = CreateThread(NULL, 0, thread_proc, NULL, 0, NULL); // CHECK: Thread T1 created by T0 here: // CHECK: {{#[01] .* main .*thread_stack_array_left_oob.cc}}:[[@LINE-2]] WaitForSingleObject(thr, INFINITE); return 0; }
// RUN: %clangxx_asan -O0 %s -Fe%t 2>&1 // 'cat' is used below to work around FileCheck buffering bug which makes this // test flaky. FIXME: file an issue. // RUN: not %run %t 2>&1 | cat | FileCheck %s #include <windows.h> DWORD WINAPI thread_proc(void *context) { int subscript = -1; volatile char stack_buffer[42]; stack_buffer[subscript] = 42; // CHECK: AddressSanitizer: stack-buffer-overflow on address [[ADDR:0x[0-9a-f]+]] // CHECK: WRITE of size 1 at [[ADDR]] thread T1 // CHECK: {{#0 .* thread_proc .*thread_stack_array_left_oob.cc}}:[[@LINE-3]] // CHECK: Address [[ADDR]] is located in stack of thread T1 at offset {{.*}} in frame // CHECK: thread_proc return 0; } int main(void) { HANDLE thr = CreateThread(NULL, 0, thread_proc, NULL, 0, NULL); // CHECK: Thread T1 created by T0 here: // CHECK: {{#[01] .* main .*thread_stack_array_left_oob.cc}}:[[@LINE-2]] WaitForSingleObject(thr, INFINITE); return 0; }
Support for overloads on free functions.
{{{header}}} {{#includes}} #include <{{{.}}}> {{/includes}} {{{precontent}}} #include <boost/python.hpp> #include <cmath> /* postinclude */ void {{function.mangled_name}}() { ::boost::python::object parent_object(::boost::python::scope(){{! }}{{#function.scope}}{{#name}}.attr("{{name}}"){{/name}}{{/function.scope}}); ::boost::python::scope parent_scope(parent_object); boost::python::def("{{function.name}}", {{! }}static_cast<{{{function.type}}}>(&{{{function.qualified_name}}}){{! }}{{#function.params?}}, ({{#function.params}}::boost::python::arg("{{name}}"){{^last}}, {{/last}}{{/function.params}}){{/function.params?}}) ;} {{{postcontent}}} {{{footer}}}
{{{header}}} {{#includes}} #include <{{{.}}}> {{/includes}} {{{precontent}}} #include <boost/python.hpp> #include <cmath> /* postinclude */ void {{function.mangled_name}}() { ::boost::python::object parent_object(::boost::python::scope(){{! }}{{#function.scope}}{{#name}}.attr("{{name}}"){{/name}}{{/function.scope}}); ::boost::python::scope parent_scope(parent_object); {{#function.overloads}}{{! }}::boost::python::def("{{name}}", []({{#params}}{{{type}}} {{name}}{{^last}}, {{/last}}{{/params}}) -> {{{return_type}}} { {{! }}return {{{qualified_name}}}({{#params}}{{name}}{{^last}}, {{/last}}{{/params}}); }{{! }}{{#return_value_policy}}, ::boost::python::return_value_policy<{{{.}}} >(){{/return_value_policy}}{{! }}{{#params?}}, ({{#params}}::boost::python::arg("{{name}}"){{^last}}, {{/last}}{{/params}}){{/params?}}); {{/function.overloads}} } {{{postcontent}}} {{{footer}}}
Insert an assert to catch a bad VarInit variable type.
#include "removeNamedParameters.h" #include "expr.h" #include "stmt.h" void RemoveNamedParameters::postProcessExpr(Expr* expr) { if (NamedExpr* named_expr = dynamic_cast<NamedExpr*>(expr)) { named_expr->replace(named_expr->actual->copy()); } if (VarInitExpr* var_init = dynamic_cast<VarInitExpr*>(expr)) { if (dynamic_cast<ArrayType*>(var_init->symbol->type) || dynamic_cast<DomainType*>(var_init->symbol->type)) { // No Default Initialization for Arrays/Domains var_init->parentStmt->replace(new NoOpStmt()); } else { if (var_init->symbol->type->defaultVal) { var_init->replace(var_init->symbol->type->defaultVal->copy()); } else { var_init->replace(new FnCall(new Variable(var_init->symbol->type->defaultConstructor), NULL)); } } } }
#include "removeNamedParameters.h" #include "expr.h" #include "stmt.h" void RemoveNamedParameters::postProcessExpr(Expr* expr) { if (NamedExpr* named_expr = dynamic_cast<NamedExpr*>(expr)) { named_expr->replace(named_expr->actual->copy()); } if (VarInitExpr* var_init = dynamic_cast<VarInitExpr*>(expr)) { if (dynamic_cast<ArrayType*>(var_init->symbol->type) || dynamic_cast<DomainType*>(var_init->symbol->type)) { // No Default Initialization for Arrays/Domains var_init->parentStmt->replace(new NoOpStmt()); } else { if (var_init->symbol->type->defaultVal) { var_init->replace(var_init->symbol->type->defaultVal->copy()); } else { assert(var_init->symbol->type->defaultConstructor); var_init->replace(new FnCall(new Variable(var_init->symbol->type->defaultConstructor), NULL)); } } } }
Change if/else to ternary if
#include "details.hpp" #include "json/json.h" dota2::DetailsRequest &dota2::DetailsRequest::id(MatchID id) { query.insert({"match_id", std::to_string(id)}); return *this; } dota2::Details::Details(const Json::Value &json) { const auto& result = json["result"]; matchID = result["match_id"].asInt(); startTime = timePoint(result["start_time"].asInt64()); firstBloodTime = timePoint(result["first_blood_time"].asInt64()); if(result["radiant_win"].asBool()) { winningTeam = Team::RADIANT; } else { winningTeam = Team::DIRE; } } dota2::MatchID dota2::Details::getMatchID() const { return matchID; } dota2::Team dota2::Details::getWinningTeam() const { return winningTeam; } dota2::Details::timePoint dota2::Details::getStartTime() const { return startTime; } dota2::Details::timePoint dota2::Details::getFirstBloodTime() const { return firstBloodTime; }
#include "details.hpp" #include "json/json.h" dota2::DetailsRequest &dota2::DetailsRequest::id(MatchID id) { query.insert({"match_id", std::to_string(id)}); return *this; } dota2::Details::Details(const Json::Value &json) { const auto& result = json["result"]; matchID = result["match_id"].asInt(); startTime = timePoint(result["start_time"].asInt64()); firstBloodTime = timePoint(result["first_blood_time"].asInt64()); winningTeam = result["radiant_win"].asBool() ? Team::RADIANT : Team::DIRE; } dota2::MatchID dota2::Details::getMatchID() const { return matchID; } dota2::Team dota2::Details::getWinningTeam() const { return winningTeam; } dota2::Details::timePoint dota2::Details::getStartTime() const { return startTime; } dota2::Details::timePoint dota2::Details::getFirstBloodTime() const { return firstBloodTime; }
Use rectangle-point collision in button.
#include "Button.hpp" #include <Engine/Geometry/Rectangle.hpp> #include <Engine/Util/Input.hpp> using namespace GUI; Button::Button(Widget* parent) : Widget(parent) { mouseHover = false; hasClickedCallback = false; size = glm::vec2(64.f, 64.f); } Button::~Button() { } void Button::Update() { double xpos = Input()->CursorX(); double ypos = Input()->CursorY(); mouseHover = xpos >= GetPosition().x && xpos < GetPosition().x + size.x && ypos >= GetPosition().y && ypos < GetPosition().y + size.y; if (mouseHover && Input()->MousePressed(GLFW_MOUSE_BUTTON_LEFT) && hasClickedCallback) { clickedCallback(); } } glm::vec2 Button::GetSize() const { return size; } void Button::SetSize(const glm::vec2& size) { this->size = size; } void Button::SetClickedCallback(std::function<void()> callback) { clickedCallback = callback; hasClickedCallback = true; } bool Button::GetMouseHover() const { return mouseHover; }
#include "Button.hpp" #include <Engine/Geometry/Rectangle.hpp> #include <Engine/Util/Input.hpp> #include <Engine/Physics/Rectangle.hpp> using namespace GUI; Button::Button(Widget* parent) : Widget(parent) { mouseHover = false; hasClickedCallback = false; size = glm::vec2(64.f, 64.f); } Button::~Button() { } void Button::Update() { glm::vec2 mousePosition(Input()->CursorX(), Input()->CursorY()); Physics::Rectangle rect(GetPosition(), size); mouseHover = rect.Collide(mousePosition); if (mouseHover && Input()->MousePressed(GLFW_MOUSE_BUTTON_LEFT) && hasClickedCallback) { clickedCallback(); } } glm::vec2 Button::GetSize() const { return size; } void Button::SetSize(const glm::vec2& size) { this->size = size; } void Button::SetClickedCallback(std::function<void()> callback) { clickedCallback = callback; hasClickedCallback = true; } bool Button::GetMouseHover() const { return mouseHover; }
Test commit for testing EXPERIMENTAL code trigger.
#include "StorageDeleteFileChunkJob.h" #include "System/Stopwatch.h" #include "System/FileSystem.h" #include "StorageFileChunk.h" StorageDeleteFileChunkJob::StorageDeleteFileChunkJob(StorageFileChunk* chunk_) { chunk = chunk_; } void StorageDeleteFileChunkJob::Execute() { Stopwatch sw; Buffer filename; Log_Debug("Deleting file chunk %U from disk, starting", chunk->GetChunkID()); sw.Start(); filename.Write(chunk->GetFilename()); delete chunk; FS_Delete(filename.GetBuffer()); sw.Stop(); Log_Debug("Deleted, elapsed: %U", (uint64_t) sw.Elapsed()); } void StorageDeleteFileChunkJob::OnComplete() { delete this; }
#include "StorageDeleteFileChunkJob.h" #include "System/Stopwatch.h" #include "System/FileSystem.h" #include "StorageFileChunk.h" StorageDeleteFileChunkJob::StorageDeleteFileChunkJob(StorageFileChunk* chunk_) { chunk = chunk_; } void StorageDeleteFileChunkJob::Execute() { Stopwatch sw; Buffer filename; Log_Debug("Deleting file chunk %U from disk, starting", chunk->GetChunkID()); sw.Start(); filename.Write(chunk->GetFilename()); delete chunk; // EXPERIMENTAL: remove from production! //FS_Delete(filename.GetBuffer()); sw.Stop(); Log_Debug("Deleted, elapsed: %U", (uint64_t) sw.Elapsed()); } void StorageDeleteFileChunkJob::OnComplete() { delete this; }
Fix formatting in 'who' command
#include <miniMAT/ast/WhoStmt.hpp> #include <iostream> namespace miniMAT { namespace ast { std::string WhoStmt::GetClassName() const { return "WhoStmt"; } void WhoStmt::VisitDisplay(const std::string& prefix) const { using namespace miniMAT::visit::display; Show(prefix, *this); } Matrix WhoStmt::VisitEvaluate(std::shared_ptr<std::map<std::string, Matrix>> vars) { if (vars->size() != 0) { std::cout << std::endl; for (auto var : *vars) std::cout << var.first << std::endl; std::cout << std::endl; } return Matrix::Zero(0,0); } void WhoStmt::VisitCheck(std::shared_ptr<std::map<std::string, Matrix>> vars, std::shared_ptr<reporter::ErrorReporter> reporter) const { } } }
#include <miniMAT/ast/WhoStmt.hpp> #include <iostream> namespace miniMAT { namespace ast { std::string WhoStmt::GetClassName() const { return "WhoStmt"; } void WhoStmt::VisitDisplay(const std::string& prefix) const { using namespace miniMAT::visit::display; Show(prefix, *this); } Matrix WhoStmt::VisitEvaluate(std::shared_ptr<std::map<std::string, Matrix>> vars) { if (vars->size() != 0) { std::cout << std::endl << "Your variables are:" << std::endl << std::endl; for (auto var : *vars) std::cout << var.first << " "; std::cout << std::endl << std::endl; } return Matrix::Zero(0,0); } void WhoStmt::VisitCheck(std::shared_ptr<std::map<std::string, Matrix>> vars, std::shared_ptr<reporter::ErrorReporter> reporter) const { } } }
Remove dead code in FtpNetworkLayer
// Copyright (c) 2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/ftp/ftp_network_layer.h" #include "net/ftp/ftp_network_session.h" #include "net/ftp/ftp_network_transaction.h" #include "net/socket/client_socket_factory.h" namespace net { FtpNetworkLayer::FtpNetworkLayer(HostResolver* host_resolver) : session_(new FtpNetworkSession(host_resolver)), suspended_(false) { } FtpNetworkLayer::~FtpNetworkLayer() { } // static FtpTransactionFactory* FtpNetworkLayer::CreateFactory( HostResolver* host_resolver) { return new FtpNetworkLayer(host_resolver); } FtpTransaction* FtpNetworkLayer::CreateTransaction() { if (suspended_) return NULL; return new FtpNetworkTransaction(session_->host_resolver(), ClientSocketFactory::GetDefaultFactory()); } void FtpNetworkLayer::Suspend(bool suspend) { suspended_ = suspend; /* TODO(darin): We'll need this code once we have a connection manager. if (suspend) session_->connection_manager()->CloseIdleSockets(); */ } } // namespace net
// Copyright (c) 2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/ftp/ftp_network_layer.h" #include "net/ftp/ftp_network_session.h" #include "net/ftp/ftp_network_transaction.h" #include "net/socket/client_socket_factory.h" namespace net { FtpNetworkLayer::FtpNetworkLayer(HostResolver* host_resolver) : session_(new FtpNetworkSession(host_resolver)), suspended_(false) { } FtpNetworkLayer::~FtpNetworkLayer() { } // static FtpTransactionFactory* FtpNetworkLayer::CreateFactory( HostResolver* host_resolver) { return new FtpNetworkLayer(host_resolver); } FtpTransaction* FtpNetworkLayer::CreateTransaction() { if (suspended_) return NULL; return new FtpNetworkTransaction(session_->host_resolver(), ClientSocketFactory::GetDefaultFactory()); } void FtpNetworkLayer::Suspend(bool suspend) { suspended_ = suspend; } } // namespace net
Fix test with wrong function call
#include <catch.hpp> #include "WordDecoder.hpp" namespace { using namespace Core8; TEST_CASE("Decode X from pattern vXvv", "[decoder]") { REQUIRE(WordDecoder::readX(0x0F00) == 0XF); REQUIRE(WordDecoder::readX(0xF0FF) == 0X0); } TEST_CASE("Decode Y from pattern vvYv", "[decoder]") { REQUIRE(WordDecoder::readY(0x00F0) == 0XF); REQUIRE(WordDecoder::readY(0xFF0F) == 0X0); } TEST_CASE("Decode N from pattern vvvN", "[decoder]") { REQUIRE(WordDecoder::readN(0x000F) == 0XF); REQUIRE(WordDecoder::readN(0xFFF0) == 0X0); } TEST_CASE("Decode NN from pattern vvNN", "[decoder]") { REQUIRE(WordDecoder::readNN(0x00FF) == 0XFF); REQUIRE(WordDecoder::readNN(0xFF11) == 0X11); } TEST_CASE("Decode NNN from pattern vNNN", "[decoder]") { REQUIRE(WordDecoder::readNN(0x0FFF) == 0XFFF); REQUIRE(WordDecoder::readNN(0xF111) == 0X111); } } // unnamed namespace
#include <catch.hpp> #include "WordDecoder.hpp" namespace { using namespace Core8; TEST_CASE("Decode X from pattern vXvv", "[decoder]") { REQUIRE(WordDecoder::readX(0x0F00) == 0XF); REQUIRE(WordDecoder::readX(0xF0FF) == 0X0); } TEST_CASE("Decode Y from pattern vvYv", "[decoder]") { REQUIRE(WordDecoder::readY(0x00F0) == 0XF); REQUIRE(WordDecoder::readY(0xFF0F) == 0X0); } TEST_CASE("Decode N from pattern vvvN", "[decoder]") { REQUIRE(WordDecoder::readN(0x000F) == 0XF); REQUIRE(WordDecoder::readN(0xFFF0) == 0X0); } TEST_CASE("Decode NN from pattern vvNN", "[decoder]") { REQUIRE(WordDecoder::readNN(0x00FF) == 0XFF); REQUIRE(WordDecoder::readNN(0xFF11) == 0X11); } TEST_CASE("Decode NNN from pattern vNNN", "[decoder]") { REQUIRE(WordDecoder::readNNN(0x0FFF) == 0XFFF); REQUIRE(WordDecoder::readNNN(0xF111) == 0X111); } } // unnamed namespace
Fix build failure due to missing newline Patch by tropikhajma, thanks! CCBUG: 291907
// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2011 Daniel Marth <danielmarth@gmx.at> // #include "RelatedActivities.h" namespace Marble { namespace Declarative { RelatedActivities::RelatedActivities() { } RelatedActivities::RelatedActivities( const QMap<QString, QVariant>& relatedActivities ) : m_relatedActivities( relatedActivities ) { } QStringList RelatedActivities::get( const QString& name ) const { return m_relatedActivities[name].toStringList(); } void RelatedActivities::setRelatedActivities( const QMap<QString, QVariant>& relatedActivities ) { m_relatedActivities = relatedActivities; } QMap<QString, QVariant> RelatedActivities::relatedActivities() const { return m_relatedActivities; } } } #include "RelatedActivities.moc"
// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2011 Daniel Marth <danielmarth@gmx.at> // #include "RelatedActivities.h" namespace Marble { namespace Declarative { RelatedActivities::RelatedActivities() { } RelatedActivities::RelatedActivities( const QMap<QString, QVariant>& relatedActivities ) : m_relatedActivities( relatedActivities ) { } QStringList RelatedActivities::get( const QString& name ) const { return m_relatedActivities[name].toStringList(); } void RelatedActivities::setRelatedActivities( const QMap<QString, QVariant>& relatedActivities ) { m_relatedActivities = relatedActivities; } QMap<QString, QVariant> RelatedActivities::relatedActivities() const { return m_relatedActivities; } } } #include "RelatedActivities.moc"
Declare zero graphs also to be relevant (may yield non-trivial cyclic weight relations).
#include "../kontsevich_graph_series.hpp" #include <string> using namespace std; int main(int argc, char* argv[]) { if (argc != 2) { cout << "Usage: " << argv[0] << " [order]\n"; return 1; } size_t order = stoi(argv[1]); set<KontsevichGraph> relevants = KontsevichGraph::graphs(order, 2, true, true, [](KontsevichGraph g) -> bool { return g.positive_differential_order() && g.is_prime() && !g.is_zero(); }); size_t counter = 0; for (KontsevichGraph const& g : relevants) cout << g.encoding() << " w_" << order << "_" << (++counter) << "\n"; }
#include "../kontsevich_graph_series.hpp" #include <string> using namespace std; int main(int argc, char* argv[]) { if (argc != 2) { cout << "Usage: " << argv[0] << " [order]\n"; return 1; } size_t order = stoi(argv[1]); set<KontsevichGraph> relevants = KontsevichGraph::graphs(order, 2, true, true, [](KontsevichGraph g) -> bool { return g.positive_differential_order() && g.is_prime(); }); size_t counter = 0; for (KontsevichGraph const& g : relevants) { cout << g.encoding() << " "; if (g.is_zero()) cout << "0\n"; else cout << "w_" << order << "_" << (++counter) << "\n"; } }
Use const references in a few more places
#include "compiler/build_tables/item_set_closure.h" #include <algorithm> #include <set> #include "tree_sitter/compiler.h" #include "compiler/build_tables/follow_sets.h" #include "compiler/build_tables/item.h" #include "compiler/prepared_grammar.h" namespace tree_sitter { using std::set; using rules::Symbol; namespace build_tables { static bool contains(const ParseItemSet *items, const ParseItem &item) { if (items->empty()) return false; return (std::find(items->begin(), items->end(), item) != items->end()); } static void add_item(ParseItemSet *item_set, const ParseItem &item, const PreparedGrammar &grammar) { if (!contains(item_set, item)) { item_set->insert(item); for (auto &pair : follow_sets(item, grammar)) { Symbol non_terminal = pair.first; set<Symbol> terminals = pair.second; for (auto &terminal : terminals) { ParseItem next_item(non_terminal, grammar.rule(non_terminal), 0, terminal); add_item(item_set, next_item, grammar); } } } } const ParseItemSet item_set_closure(const ParseItemSet &item_set, const PreparedGrammar &grammar) { ParseItemSet result; for (ParseItem item : item_set) add_item(&result, item, grammar); return result; } } }
#include "compiler/build_tables/item_set_closure.h" #include <algorithm> #include <set> #include "tree_sitter/compiler.h" #include "compiler/build_tables/follow_sets.h" #include "compiler/build_tables/item.h" #include "compiler/prepared_grammar.h" namespace tree_sitter { using std::set; using rules::Symbol; namespace build_tables { static bool contains(const ParseItemSet *items, const ParseItem &item) { if (items->empty()) return false; return (std::find(items->begin(), items->end(), item) != items->end()); } static void add_item(ParseItemSet *item_set, const ParseItem &item, const PreparedGrammar &grammar) { if (!contains(item_set, item)) { item_set->insert(item); for (const auto &pair : follow_sets(item, grammar)) { const Symbol &non_terminal = pair.first; const set<Symbol> &terminals = pair.second; for (const auto &terminal : terminals) { ParseItem next_item(non_terminal, grammar.rule(non_terminal), 0, terminal); add_item(item_set, next_item, grammar); } } } } const ParseItemSet item_set_closure(const ParseItemSet &item_set, const PreparedGrammar &grammar) { ParseItemSet result; for (const ParseItem &item : item_set) add_item(&result, item, grammar); return result; } } }
Mark this test as XFAIL with older compilers, since they hit PR18097
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // UNSUPPORTED: libcpp-has-no-threads // UNSUPPORTED: c++98, c++03 // <atomic> // constexpr atomic<T>::atomic(T value) #include <atomic> #include <type_traits> #include <cassert> struct UserType { int i; UserType() noexcept {} constexpr explicit UserType(int d) noexcept : i(d) {} friend bool operator==(const UserType& x, const UserType& y) { return x.i == y.i; } }; template <class Tp> void test() { typedef std::atomic<Tp> Atomic; static_assert(std::is_literal_type<Atomic>::value, ""); constexpr Tp t(42); { constexpr Atomic a(t); assert(a == t); } { constexpr Atomic a{t}; assert(a == t); } { constexpr Atomic a = ATOMIC_VAR_INIT(t); assert(a == t); } } int main() { test<int>(); test<UserType>(); }
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // UNSUPPORTED: libcpp-has-no-threads // UNSUPPORTED: c++98, c++03 // NOTE: atomic<> of a TriviallyCopyable class is wrongly rejected by older // clang versions. It was fixed right before the llvm 3.5 release. See PR18097. // XFAIL: apple-clang-6.0, clang-3.4, clang-3.3 // <atomic> // constexpr atomic<T>::atomic(T value) #include <atomic> #include <type_traits> #include <cassert> struct UserType { int i; UserType() noexcept {} constexpr explicit UserType(int d) noexcept : i(d) {} friend bool operator==(const UserType& x, const UserType& y) { return x.i == y.i; } }; template <class Tp> void test() { typedef std::atomic<Tp> Atomic; static_assert(std::is_literal_type<Atomic>::value, ""); constexpr Tp t(42); { constexpr Atomic a(t); assert(a == t); } { constexpr Atomic a{t}; assert(a == t); } { constexpr Atomic a = ATOMIC_VAR_INIT(t); assert(a == t); } } int main() { test<int>(); test<UserType>(); }
Use "ignore" rather than grep tricks.
// RUN: %llvmgxx %s -S -emit-llvm -O2 -o - | grep -c {handle\\|_Unwind_Resume} | grep {\[14\]} struct One { }; struct Two { }; void handle_unexpected () { try { throw; } catch (One &) { throw Two (); } }
// RUN: %llvmgxx %s -S -emit-llvm -O2 -o - | ignore grep _Unwind_Resume | \ // RUN: wc -l | grep {\[03\]} struct One { }; struct Two { }; void handle_unexpected () { try { throw; } catch (One &) { throw Two (); } }
Implement dbus stub for async API.
/****************************************************************************** * Copyright (C) 2011 Frank Osterfeld <frank.osterfeld@gmail.com> * * * * 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. For licensing and distribution * * details, check the accompanying file 'COPYING'. * *****************************************************************************/ #include "keychain_p.h" #include <QSettings> using namespace QKeychain; QKeychain::Error Keychain::Private::readEntryImpl( QByteArray* pw, const QString& key, QString* err ) { Q_UNUSED( key ) Q_ASSERT( pw ); Q_ASSERT( err ); return NotImplemented; } QKeychain::Error Keychain::Private::writeEntryImpl( const QString& key, const QByteArray& data_, QString* err ) { Q_ASSERT( err ); return NotImplemented; } QKeychain::Error Keychain::Private::deleteEntryImpl( const QString& key, QString* err ) { Q_ASSERT( err ); err->clear(); return NotImplemented; } QKeychain::Error Keychain::Private::entryExistsImpl( bool* exists, const QString& key, QString* err ) { Q_ASSERT( exists ); Q_ASSERT( err ); err->clear(); *exists = false; return NotImplemented; }
/****************************************************************************** * Copyright (C) 2011 Frank Osterfeld <frank.osterfeld@gmail.com> * * * * 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. For licensing and distribution * * details, check the accompanying file 'COPYING'. * *****************************************************************************/ #include "keychain_p.h" #include <QSettings> using namespace QKeychain; void ReadPasswordJob::Private::doStart() { q->emitFinishedWithError( NotImplemented, QString() ); } void WritePasswordJob::Private::doStart() { q->emitFinishedWithError( NotImplemented, QString() ); }
Remove a check from strerror_r test.
// RUN: %clangxx_asan -O0 %s -o %t && %t // Regression test for PR17138. #include <assert.h> #include <string.h> int main() { char buf[1024]; char *res = (char *)strerror_r(300, buf, sizeof(buf)); assert(res != 0); return 0; }
// RUN: %clangxx_asan -O0 %s -o %t && %t // Regression test for PR17138. #include <assert.h> #include <string.h> #include <stdio.h> int main() { char buf[1024]; char *res = (char *)strerror_r(300, buf, sizeof(buf)); printf("%p\n", res); return 0; }
Make it easier to debug by exposing a temporary
//===- MRegisterInfo.cpp - Target Register Information Implementation -----===// // // This file implements the MRegisterInfo interface. // //===----------------------------------------------------------------------===// #include "llvm/Target/MRegisterInfo.h" MRegisterInfo::MRegisterInfo(const MRegisterDesc *D, unsigned NR, regclass_iterator RCB, regclass_iterator RCE, int CFSO, int CFDO) : Desc(D), NumRegs(NR), RegClassBegin(RCB), RegClassEnd(RCE) { assert(NumRegs < FirstVirtualRegister && "Target has too many physical registers!"); PhysRegClasses = new const TargetRegisterClass*[NumRegs]; for (unsigned i = 0; i != NumRegs; ++i) PhysRegClasses[i] = 0; // Fill in the PhysRegClasses map for (MRegisterInfo::regclass_iterator I = regclass_begin(), E = regclass_end(); I != E; ++I) for (unsigned i=0; i < (*I)->getNumRegs(); ++i) { assert(PhysRegClasses[(*I)->getRegister(i)] == 0 && "Register in more than one class?"); PhysRegClasses[(*I)->getRegister(i)] = *I; } CallFrameSetupOpcode = CFSO; CallFrameDestroyOpcode = CFDO; } MRegisterInfo::~MRegisterInfo() { delete[] PhysRegClasses; }
//===- MRegisterInfo.cpp - Target Register Information Implementation -----===// // // This file implements the MRegisterInfo interface. // //===----------------------------------------------------------------------===// #include "llvm/Target/MRegisterInfo.h" MRegisterInfo::MRegisterInfo(const MRegisterDesc *D, unsigned NR, regclass_iterator RCB, regclass_iterator RCE, int CFSO, int CFDO) : Desc(D), NumRegs(NR), RegClassBegin(RCB), RegClassEnd(RCE) { assert(NumRegs < FirstVirtualRegister && "Target has too many physical registers!"); PhysRegClasses = new const TargetRegisterClass*[NumRegs]; for (unsigned i = 0; i != NumRegs; ++i) PhysRegClasses[i] = 0; // Fill in the PhysRegClasses map for (MRegisterInfo::regclass_iterator I = regclass_begin(), E = regclass_end(); I != E; ++I) for (unsigned i = 0, e = (*I)->getNumRegs(); i != e; ++i) { unsigned Reg = (*I)->getRegister(i); assert(PhysRegClasses[Reg] == 0 && "Register in more than one class?"); PhysRegClasses[Reg] = *I; } CallFrameSetupOpcode = CFSO; CallFrameDestroyOpcode = CFDO; } MRegisterInfo::~MRegisterInfo() { delete[] PhysRegClasses; }
Change Android file reading to RAII.
#include "FileSystem.h" #include "android/AndroidServices.h" #include <stdexcept> #include <fstream> #include <sstream> #include <android/log.h> namespace yarrar { namespace filesystem { void readFile(const std::string& relativePath, std::string& toBuffer) { auto assetManager = yarrar::android::getAssetManager(); AAsset* file = AAssetManager_open(assetManager, relativePath.c_str(), AASSET_MODE_BUFFER); if(!file) { throw std::runtime_error(std::string("failed to open file: ") + relativePath); } size_t len = AAsset_getLength(file); toBuffer.clear(); toBuffer.resize(len); int ret = AAsset_read(file, &toBuffer.front(), len); if(ret <= 0) { throw std::runtime_error(std::string("failed to open file: ") + relativePath); } AAsset_close(file); } } }
#include "FileSystem.h" #include "android/AndroidServices.h" #include <stdexcept> #include <fstream> #include <sstream> namespace { class AndroidFile { public: AndroidFile(const std::string& path): m_path(path), m_file(nullptr) { m_file = AAssetManager_open(yarrar::android::getAssetManager(), m_path.c_str(), AASSET_MODE_BUFFER); if(!m_file) { throw std::runtime_error(std::string("failed to open file: ") + m_path); } } ~AndroidFile() { AAsset_close(m_file); } void read(std::string& toBuffer) { if(!m_file) { throw std::runtime_error(std::string("file not opened: ") + m_path); } size_t len = AAsset_getLength(m_file); toBuffer.clear(); toBuffer.resize(len); int ret = AAsset_read(m_file, &toBuffer.front(), len); if(ret <= 0) { throw std::runtime_error(std::string("read error in file: ") + m_path); } } private: std::string m_path; AAsset* m_file; }; } namespace yarrar { namespace filesystem { void readFile(const std::string& relativePath, std::string& toBuffer) { yarrar::android::log(std::string("Opening file: ") + relativePath); AndroidFile f(relativePath); f.read(toBuffer); } } }
Change message type to None
#include "pch.h" #include "MidiNrpnParameterValueChangeMessage.h" using namespace PeteBrown::Devices::Midi; MidiNrpnParameterValueChangeMessage::MidiNrpnParameterValueChangeMessage() { _rawData = ref new Windows::Storage::Streams::Buffer(TOTAL_BYTES_IN_MESSAGE); _rawData->Length = TOTAL_BYTES_IN_MESSAGE; _rawBytes = MidiMessageHelper::GetRawDataBytesFromBuffer(_rawData); // _type = Windows::Devices::Midi::MidiMessageType::None; _type = Windows::Devices::Midi::MidiMessageType::ControlChange; BuildBaseMessages(); } // //unsigned short MidiNrpnParameterValueChangeMessage::ParameterNumber::get() //{ // //} // //void MidiNrpnParameterValueChangeMessage::ParameterNumber::set(unsigned short value) //{ // // TODO: Set msb and lsb as well as backing store //} // // // //unsigned short MidiNrpnParameterValueChangeMessage::Value::get() //{ // //} // //void MidiNrpnParameterValueChangeMessage::Value::set(unsigned short value) //{ // // TODO: Set msb and lsb as well as backing store //}
#include "pch.h" #include "MidiNrpnParameterValueChangeMessage.h" using namespace PeteBrown::Devices::Midi; MidiNrpnParameterValueChangeMessage::MidiNrpnParameterValueChangeMessage() { _rawData = ref new Windows::Storage::Streams::Buffer(TOTAL_BYTES_IN_MESSAGE); _rawData->Length = TOTAL_BYTES_IN_MESSAGE; _rawBytes = MidiMessageHelper::GetRawDataBytesFromBuffer(_rawData); _type = Windows::Devices::Midi::MidiMessageType::None; // _type = Windows::Devices::Midi::MidiMessageType::ControlChange; BuildBaseMessages(); } // //unsigned short MidiNrpnParameterValueChangeMessage::ParameterNumber::get() //{ // //} // //void MidiNrpnParameterValueChangeMessage::ParameterNumber::set(unsigned short value) //{ // // TODO: Set msb and lsb as well as backing store //} // // // //unsigned short MidiNrpnParameterValueChangeMessage::Value::get() //{ // //} // //void MidiNrpnParameterValueChangeMessage::Value::set(unsigned short value) //{ // // TODO: Set msb and lsb as well as backing store //}
Increase number of robot names that can be generated.
#include "robot_name.h" #include <sstream> #include <stdexcept> using namespace std; namespace robot_name { namespace { string next_prefix(string prefix) { string next{prefix}; const string letters{"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"}; if (prefix[1] == letters.back()) { if (prefix[0] == letters.back()) { throw range_error("prefix combinations exhausted"); } next[1] = letters[0]; next[0] = letters[letters.find(next[0]) + 1]; } else { next[1] = letters[letters.find(next[1]) + 1]; } return next; } string generate_name() { static string prefix = "AA"; static int unit_number = 100; ostringstream buff; if (unit_number > 999) { prefix = next_prefix(prefix); unit_number = 100; } buff << prefix << unit_number++; return buff.str(); } } robot::robot() : name_(generate_name()) { } void robot::reset() { name_ = generate_name(); } }
#include "robot_name.h" #include <iomanip> #include <sstream> #include <stdexcept> using namespace std; namespace robot_name { namespace { string next_prefix(string prefix) { string next{prefix}; const string letters{"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"}; if (prefix[1] == letters.back()) { if (prefix[0] == letters.back()) { throw range_error("prefix combinations exhausted"); } next[1] = letters[0]; next[0] = letters[letters.find(next[0]) + 1]; } else { next[1] = letters[letters.find(next[1]) + 1]; } return next; } string generate_name() { static string prefix = "AA"; static int unit_number = 0; ostringstream buff; if (unit_number > 999) { prefix = next_prefix(prefix); unit_number = 0; } buff << prefix << setw(3) << setfill('0') << unit_number++; return buff.str(); } } robot::robot() : name_(generate_name()) { } void robot::reset() { name_ = generate_name(); } }
Fix ffmpeg detection with -D OPENCV_WARNINGS_ARE_ERRORS=ON option.
#define __STDC_CONSTANT_MACROS #include <stdlib.h> extern "C" { #include <libavformat/avformat.h> #include <libavcodec/avcodec.h> #include <libswscale/swscale.h> } #define CALC_FFMPEG_VERSION(a,b,c) ( a<<16 | b<<8 | c ) static void test() { AVFormatContext* c = 0; AVCodec* avcodec = 0; AVFrame* frame = 0; #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0) int err = avformat_open_input(&c, "", NULL, NULL); #else int err = av_open_input_file(&c, "", NULL, 0, NULL); #endif } int main() { test(); return 0; }
#define __STDC_CONSTANT_MACROS #include <stdlib.h> extern "C" { #include <libavformat/avformat.h> #include <libavcodec/avcodec.h> #include <libswscale/swscale.h> } #define CALC_FFMPEG_VERSION(a,b,c) ( a<<16 | b<<8 | c ) static void test() { AVFormatContext* c = 0; AVCodec* avcodec = 0; AVFrame* frame = 0; (void)avcodec; (void)frame; #if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0) int err = avformat_open_input(&c, "", NULL, NULL); #else int err = av_open_input_file(&c, "", NULL, 0, NULL); #endif (void)err; } int main() { test(); return 0; }
Add the statement to expression in the FOR loop
#include <iostream> #include <string> using std::string; using std::cout; using std::endl; int main() { string str("a simple string"); // while decltype(str.size()) i = 0; while (i < str.size()) str[i++] = 'X'; cout << str << endl; // for for (i = 0; i<str.size(); ++i) str[i] = 'Y'; cout << str << endl; // I like range for. return 0; }
#include <iostream> #include <string> using std::string; using std::cout; using std::endl; int main() { string str("a simple string"); // while decltype(str.size()) i = 0; while (i < str.size()) str[i++] = 'X'; cout << str << endl; // for for (i = 0; i < str.size(); str[i++] = 'Y'); cout << str << endl; // I like range for. return 0; }
Use getTexture method to access image tex
// // shaderImageMask.cpp // shaderExample // // Created by Alex Olivier on 6/6/14. // // This example shows how to pass multiple textures // to a shader. It uses one texture as a mask. // Based on openFrameworks shader tutorials #include "shaderImageMask.h" shaderImageMask::shaderImageMask(string iFilename1, string iFilename2){ // Create 2 image objects image1 = new ofxImageObject(iFilename1); image2 = new ofxImageObject(iFilename2); addChild(image1); addChild(image2); } // Destroy objects shaderImageMask::~shaderImageMask(){ removeChild(image1); removeChild(image2); delete image1; delete image2; } void shaderImageMask::idle(float iTime){ } // Override default method to set shader parameters // Pass 2 textures to our shaders void shaderImageMask::setShaderParams(){ // Pass one texture in as "tex0" // Pass second texture in as "mask" shader->setUniformTexture("tex0", *image1->tex, 1); shader->setUniformTexture("mask", *image2->tex, 2); }
// // shaderImageMask.cpp // shaderExample // // Created by Alex Olivier on 6/6/14. // // This example shows how to pass multiple textures // to a shader. It uses one texture as a mask. // Based on openFrameworks shader tutorials #include "shaderImageMask.h" shaderImageMask::shaderImageMask(string iFilename1, string iFilename2){ // Create 2 image objects image1 = new ofxImageObject(iFilename1); image2 = new ofxImageObject(iFilename2); addChild(image1); addChild(image2); } // Destroy objects shaderImageMask::~shaderImageMask(){ removeChild(image1); removeChild(image2); delete image1; delete image2; } void shaderImageMask::idle(float iTime){ } // Override default method to set shader parameters // Pass 2 textures to our shaders void shaderImageMask::setShaderParams(){ // Pass one texture in as "tex0" // Pass second texture in as "mask" shader->setUniformTexture("tex0", *image1->getTexture(), 1); shader->setUniformTexture("mask", *image2->getTexture(), 2); }
Set window size to 600x600.
#include <thread> #include <renderer.hpp> #include <fensterchen.hpp> int main(int argc, char* argv[]) { unsigned const width = 800; unsigned const height = 600; std::string const filename = "./checkerboard.ppm"; Renderer app(width, height, filename); std::thread thr([&app]() { app.render(); }); Window win(glm::ivec2(width,height)); while (!win.shouldClose()) { if (win.isKeyPressed(GLFW_KEY_ESCAPE)) { win.stop(); } glDrawPixels( width, height, GL_RGB, GL_FLOAT , app.colorbuffer().data()); win.update(); } thr.join(); return 0; }
#include <thread> #include <renderer.hpp> #include <fensterchen.hpp> int main(int argc, char* argv[]) { unsigned const width = 600; unsigned const height = 600; std::string const filename = "./checkerboard.ppm"; Renderer app(width, height, filename); std::thread thr([&app]() { app.render(); }); Window win(glm::ivec2(width,height)); while (!win.shouldClose()) { if (win.isKeyPressed(GLFW_KEY_ESCAPE)) { win.stop(); } glDrawPixels( width, height, GL_RGB, GL_FLOAT , app.colorbuffer().data()); win.update(); } thr.join(); return 0; }
Fix include header statement of test
// ThermoFun includes #include <Thermofun/ThermoFun.hpp> using namespace ThermoFun; int main() { Database db("aq17.json"); }
// ThermoFun includes #include <ThermoFun/ThermoFun.hpp> using namespace ThermoFun; int main() { Database db("aq17.json"); }
Improve ability to make small jumps
/* Copyright 2014 Dietrich Epp. This file is part of Oubliette. Oubliette is licensed under the terms of the 2-clause BSD license. For more information, see LICENSE.txt. */ #include "stats.hpp" namespace game { const walking_stats stats::player = { 600.0f, // Walking 1200.0f, 120.0f, 300.0f, 150.0f, 3, // Jumping 25, 200.0f, 250.0f, true }; }
/* Copyright 2014 Dietrich Epp. This file is part of Oubliette. Oubliette is licensed under the terms of the 2-clause BSD license. For more information, see LICENSE.txt. */ #include "stats.hpp" namespace game { const walking_stats stats::player = { 600.0f, // Walking 1200.0f, 120.0f, 300.0f, 150.0f, 3, // Jumping 25, 400.0f, 180.0f, true }; }
Fix a test that never compiled under -fmodules
//===-- main.cpp ------------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include <stdio.h> class Point { public: int x; int y; Point(int a, int b): x(a), y(b) {} }; class Data { public: int id; Point point; Data(int i): id(i), point(0, 0) {} }; int main(int argc, char const *argv[]) { Data *data[1000]; Data **ptr = data; for (int i = 0; i < 1000; ++i) { ptr[i] = new Data(i); ptr[i]->point.x = i; ptr[i]->point.y = i+1; } printf("Finished populating data.\n"); for (int i = 0; i < 1000; ++i) { bool dump = argc > 1; // Set breakpoint here. // Evaluate a couple of expressions (2*1000 = 2000 exprs): // expr ptr[i]->point.x // expr ptr[i]->point.y if (dump) { printf("data[%d] = %d (%d, %d)\n", i, ptr[i]->id, ptr[i]->point.x, ptr[i]->point.y); } } return 0; }
//===-- main.cpp ------------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// class Point { public: int x; int y; Point(int a, int b): x(a), y(b) {} }; class Data { public: int id; Point point; Data(int i): id(i), point(0, 0) {} }; int main(int argc, char const *argv[]) { Data *data[1000]; Data **ptr = data; for (int i = 0; i < 1000; ++i) { ptr[i] = new Data(i); ptr[i]->point.x = i; ptr[i]->point.y = i+1; } for (int i = 0; i < 1000; ++i) { bool dump = argc > 1; // Set breakpoint here. // Evaluate a couple of expressions (2*1000 = 2000 exprs): // expr ptr[i]->point.x // expr ptr[i]->point.y } return 0; }
Add simple FPS display to example.
#include <iostream> #include "../../rltk/rltk.hpp" #include <sstream> bool tick(double duration_ms) { auto res = rltk::get_screen_size_px(); std::stringstream ss; ss << "Frame duration: " << duration_ms << " ms. Resolution: " << res.first << "x" << res.second; rltk::cls_root(); rltk::print_to_root(1, 1, ss.str()); return false; } int main() { rltk::init(tick); rltk::run(); }
#include <iostream> #include "../../rltk/rltk.hpp" #include <sstream> bool tick(double duration_ms) { auto res = rltk::get_screen_size_px(); std::stringstream ss; ss << "Frame duration: " << duration_ms << " ms (" << (1000.0/duration_ms) << " FPS). Resolution: " << res.first << "x" << res.second; rltk::cls_root(); rltk::print_to_root(1, 1, ss.str()); return false; } int main() { rltk::init(tick); rltk::run(); }
Use iterator var for character as `c` instead of confusing `x` (using `contents.x` as well)
#include <boost/optional.hpp> #include "move.hh" #include "../../../src/contents.hh" namespace vick { namespace move { boost::optional< std::shared_ptr<change> > mvsot(contents& contents, boost::optional<int>) { contents.waiting_for_desired = false; contents.x = 0; for(auto x : contents.cont[contents.y]) { if(x == ' ' || x == '\t') contents.x++; else break; } return boost::none; } } }
#include <boost/optional.hpp> #include "move.hh" #include "../../../src/contents.hh" namespace vick { namespace move { boost::optional< std::shared_ptr<change> > mvsot(contents& contents, boost::optional<int>) { contents.waiting_for_desired = false; contents.x = 0; for(auto c : contents.cont[contents.y]) { if(c == ' ' || c == '\t') contents.x++; else break; } return boost::none; } } }
Use nan to wrap around V8 functions.
#include "nslog.h" #include <node.h> using namespace v8; namespace { Handle<Value> Log(const Arguments& args) { String::Utf8Value utf8_string(Local<String>::Cast(args[0])); nslog::Log(*utf8_string); return Undefined(); } void Init(Handle<Object> exports) { NODE_SET_METHOD(exports, "log", Log); } } // namespace NODE_MODULE(nslog, Init)
#include "nslog.h" #include "nan.h" using namespace v8; namespace { NAN_METHOD(Log) { NanScope(); String::Utf8Value utf8_string(Local<String>::Cast(args[0])); nslog::Log(*utf8_string); NanReturnUndefined(); } void Init(Handle<Object> exports) { NODE_SET_METHOD(exports, "log", Log); } } // namespace NODE_MODULE(nslog, Init)
Fix logging highlighting, visibility, and newlines
#include "logger.h" Logger g_logger; //------------------------------------------------------------------------------ LogViewer::LogViewer(QWidget* parent) : QPlainTextEdit(parent) { } void LogViewer::connectLogger(Logger* logger) { connect(logger, SIGNAL(logMessage(int, QString)), this, SLOT(appendLogMessage(int, QString)), Qt::QueuedConnection); } void LogViewer::appendLogMessage(int logLevel, QString msg) { switch (logLevel) { case Logger::Warning: appendHtml("<b>WARNING</b>: " + msg); break; case Logger::Error: appendHtml("<b>ERROR</b>: " + msg); break; case Logger::Info: appendPlainText(msg); break; } ensureCursorVisible(); } //------------------------------------------------------------------------------ std::ostream& operator<<(std::ostream& out, const QByteArray& s) { out.write(s.constData(), s.size()); return out; } std::ostream& operator<<(std::ostream& out, const QString& s) { out << s.toUtf8(); return out; }
#include "logger.h" Logger g_logger; //------------------------------------------------------------------------------ LogViewer::LogViewer(QWidget* parent) : QPlainTextEdit(parent) { } void LogViewer::connectLogger(Logger* logger) { connect(logger, SIGNAL(logMessage(int, QString)), this, SLOT(appendLogMessage(int, QString)), Qt::QueuedConnection); } void LogViewer::appendLogMessage(int logLevel, QString msg) { moveCursor(QTextCursor::End); switch (logLevel) { case Logger::Warning: appendHtml("<b>WARNING</b>: "); insertPlainText(msg); break; case Logger::Error: appendHtml("<b>ERROR</b>: "); insertPlainText(msg); break; case Logger::Info: appendPlainText(msg); break; } ensureCursorVisible(); } //------------------------------------------------------------------------------ std::ostream& operator<<(std::ostream& out, const QByteArray& s) { out.write(s.constData(), s.size()); return out; } std::ostream& operator<<(std::ostream& out, const QString& s) { out << s.toUtf8(); return out; }
Revert "Revert "Vehicle ammo prefix VAMMOTYPE_ to VEQUIPMENTAMMOTYPE_""
#include "game/state/rules/city/vammotype.h" #include "game/state/gamestate.h" namespace OpenApoc { const UString &VAmmoType::getPrefix() { static UString prefix = "VAMMOTYPE_"; return prefix; } const UString &VAmmoType::getTypeName() { static UString name = "VAmmoType"; return name; } sp<VAmmoType> VAmmoType::get(const GameState &state, const UString &id) { auto it = state.vehicle_ammo.find(id); if (it == state.vehicle_ammo.end()) { LogError("No vammo type matching ID \"%s\"", id); return nullptr; } return it->second; } }
#include "game/state/rules/city/vammotype.h" #include "game/state/gamestate.h" namespace OpenApoc { const UString &VAmmoType::getPrefix() { static UString prefix = "VEQUIPMENTAMMOTYPE_"; return prefix; } const UString &VAmmoType::getTypeName() { static UString name = "VAmmoType"; return name; } sp<VAmmoType> VAmmoType::get(const GameState &state, const UString &id) { auto it = state.vehicle_ammo.find(id); if (it == state.vehicle_ammo.end()) { LogError("No vammo type matching ID \"%s\"", id); return nullptr; } return it->second; } }
Update with convert unit to radian
#include<ros/ros.h> #include<servo_msgs/IdBased.h> #include<ics3/ics> ics::ICS3* driver {nullptr}; ros::Publisher pub; void move(const servo_msgs::IdBased::ConstPtr& msg) { servo_msgs::IdBased result; try { auto&& now_pos = driver->move(msg->id, ics::Angle::newDegree(msg->angle)); result.angle = std::move(now_pos); // now_pos is universal reference, but now use after code it. use move result.id = msg->id; pub.publish(std::move(result)); } catch (std::runtime_error e) { ROS_INFO("Communicate error: %s", e.what()); } } int main(int argc, char** argv) { ros::init(argc, argv, "servo_krs_node"); ros::NodeHandle pn {"~"}; std::string path {"/dev/ttyUSB0"}; pn.param<std::string>("path", path, path); ROS_INFO("Open servo motor path: %s", path.c_str()); ics::ICS3 ics {std::move(path)}; driver = &ics; ros::NodeHandle n {}; ros::Subscriber sub {n.subscribe("cmd_krs", 100, move)}; pub = n.advertise<servo_msgs::IdBased>("pose_krs", 10); ros::spin(); return 0; }
#include<ros/ros.h> #include<servo_msgs/IdBased.h> #include<ics3/ics> ics::ICS3* driver {nullptr}; ros::Publisher pub; void move(const servo_msgs::IdBased::ConstPtr& msg) { servo_msgs::IdBased result; try { auto now_pos = driver->move(msg->id, ics::Angle::newRadian(msg->angle)); result.angle = std::move(now_pos); result.id = msg->id; pub.publish(std::move(result)); } catch (std::runtime_error e) { ROS_INFO("Communicate error: %s", e.what()); } } int main(int argc, char** argv) { ros::init(argc, argv, "servo_krs_node"); ros::NodeHandle pn {"~"}; std::string path {"/dev/ttyUSB0"}; pn.param<std::string>("path", path, path); ROS_INFO("Open servo motor path: %s", path.c_str()); ics::ICS3 ics {std::move(path)}; driver = &ics; ros::NodeHandle n {}; ros::Subscriber sub {n.subscribe("cmd_krs", 100, move)}; pub = n.advertise<servo_msgs::IdBased>("pose_krs", 10); ros::spin(); return 0; }
Set float precision to 2 in FloatInfo
#include "nodes/ui/float_info.h" #include "elements/ui/float_info.h" #include <QTableWidget> #include <QGraphicsSimpleTextItem> namespace nodes::ui { FloatInfo::FloatInfo() { QFont font{}; font.setPixelSize(32); auto widget = new QGraphicsSimpleTextItem("0.0"); widget->setFont(font); QPointF widgetPosition{}; widgetPosition.rx() = -(widget->boundingRect().width() / 2.0); widgetPosition.ry() = -(widget->boundingRect().height() / 2.0); widget->setPos(widgetPosition); setCentralWidget(widget); m_info = widget; } void FloatInfo::refreshCentralWidget() { if (!m_element || !m_element->inputs()[0].value) return; float const value{ std::get<float>(*m_element->inputs()[0].value) }; m_info->setText(QString::number(value, 'f', 6)); } void FloatInfo::showProperties() { showCommonProperties(); showInputsProperties(); showOutputsProperties(); } } // namespace nodes::ui
#include "nodes/ui/float_info.h" #include "elements/ui/float_info.h" #include <QTableWidget> #include <QGraphicsSimpleTextItem> namespace nodes::ui { FloatInfo::FloatInfo() { QFont font{}; font.setPixelSize(32); auto widget = new QGraphicsSimpleTextItem("0.0"); widget->setFont(font); QPointF widgetPosition{}; widgetPosition.rx() = -(widget->boundingRect().width() / 2.0); widgetPosition.ry() = -(widget->boundingRect().height() / 2.0); widget->setPos(widgetPosition); setCentralWidget(widget); m_info = widget; } void FloatInfo::refreshCentralWidget() { if (!m_element || !m_element->inputs()[0].value) return; float const value{ std::get<float>(*m_element->inputs()[0].value) }; m_info->setText(QString::number(value, 'f', 2)); } void FloatInfo::showProperties() { showCommonProperties(); showInputsProperties(); showOutputsProperties(); } } // namespace nodes::ui
Fix window geometry on launch when window is still hidden
/* Copyright (c) 2013-2014 Jeffrey Pfau * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "GBAApp.h" #include "GameController.h" #include <QFileOpenEvent> extern "C" { #include "platform/commandline.h" } using namespace QGBA; GBAApp::GBAApp(int& argc, char* argv[]) : QApplication(argc, argv) , m_window(&m_configController) { #ifdef BUILD_SDL SDL_Init(SDL_INIT_NOPARACHUTE); #endif QApplication::setApplicationName(PROJECT_NAME); QApplication::setApplicationVersion(PROJECT_VERSION); GBAArguments args = {}; if (m_configController.parseArguments(&args, argc, argv)) { m_window.argumentsPassed(&args); } else { m_window.loadConfig(); } freeArguments(&args); m_window.show(); } bool GBAApp::event(QEvent* event) { if (event->type() == QEvent::FileOpen) { m_window.controller()->loadGame(static_cast<QFileOpenEvent*>(event)->file()); return true; } return QApplication::event(event); }
/* Copyright (c) 2013-2014 Jeffrey Pfau * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "GBAApp.h" #include "GameController.h" #include <QFileOpenEvent> extern "C" { #include "platform/commandline.h" } using namespace QGBA; GBAApp::GBAApp(int& argc, char* argv[]) : QApplication(argc, argv) , m_window(&m_configController) { #ifdef BUILD_SDL SDL_Init(SDL_INIT_NOPARACHUTE); #endif QApplication::setApplicationName(PROJECT_NAME); QApplication::setApplicationVersion(PROJECT_VERSION); m_window.show(); GBAArguments args = {}; if (m_configController.parseArguments(&args, argc, argv)) { m_window.argumentsPassed(&args); } else { m_window.loadConfig(); } freeArguments(&args); } bool GBAApp::event(QEvent* event) { if (event->type() == QEvent::FileOpen) { m_window.controller()->loadGame(static_cast<QFileOpenEvent*>(event)->file()); return true; } return QApplication::event(event); }
Fix PR23041. Use lock_shared() as opposed to lock() in shared_lock test.
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // UNSUPPORTED: libcpp-has-no-threads // <shared_mutex> // template <class Mutex> class shared_lock; // shared_lock(mutex_type& m, adopt_lock_t); #include <shared_mutex> #include <cassert> int main() { #if _LIBCPP_STD_VER > 11 std::shared_timed_mutex m; m.lock(); std::shared_lock<std::shared_timed_mutex> lk(m, std::adopt_lock); assert(lk.mutex() == &m); assert(lk.owns_lock() == true); #endif // _LIBCPP_STD_VER > 11 }
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // UNSUPPORTED: libcpp-has-no-threads // <shared_mutex> // template <class Mutex> class shared_lock; // shared_lock(mutex_type& m, adopt_lock_t); #include <shared_mutex> #include <cassert> int main() { #if _LIBCPP_STD_VER > 11 std::shared_timed_mutex m; m.lock_shared(); std::shared_lock<std::shared_timed_mutex> lk(m, std::adopt_lock); assert(lk.mutex() == &m); assert(lk.owns_lock() == true); #endif // _LIBCPP_STD_VER > 11 }
Send alias and rport parameters to proxy.
#include "sipnondialogclient.h" #include <QDebug> SIPNonDialogClient::SIPNonDialogClient(SIPTransactionUser *tu): SIPClientTransaction (tu) {} void SIPNonDialogClient::set_remoteURI(SIP_URI& uri) { remoteUri_ = uri; } void SIPNonDialogClient::getRequestMessageInfo(RequestType type, std::shared_ptr<SIPMessageInfo>& outMessage) { SIPClientTransaction::getRequestMessageInfo(type, outMessage); if (type == SIP_REGISTER) { outMessage->expires = 600; // TODO: Implement resending } } bool SIPNonDialogClient::processResponse(SIPResponse& response, std::shared_ptr<SIPDialogState> state) { // TODO Q_UNUSED(response); Q_UNUSED(state); if (getOngoingRequest() == SIP_REGISTER) { qDebug() << "Got a response for REGISTER! TODO: Processing not implemented!"; } return false; } void SIPNonDialogClient::startTransaction(RequestType type) { SIPClientTransaction::startTransaction(type); } void SIPNonDialogClient::registerToServer() { startTransaction(SIP_REGISTER); emit sendNondialogRequest(remoteUri_, SIP_REGISTER); }
#include "sipnondialogclient.h" #include <QDebug> SIPNonDialogClient::SIPNonDialogClient(SIPTransactionUser *tu): SIPClientTransaction (tu) {} void SIPNonDialogClient::set_remoteURI(SIP_URI& uri) { remoteUri_ = uri; } void SIPNonDialogClient::getRequestMessageInfo(RequestType type, std::shared_ptr<SIPMessageInfo>& outMessage) { SIPClientTransaction::getRequestMessageInfo(type, outMessage); if (type == SIP_REGISTER) { outMessage->expires = 600; // TODO: Implement resending if (!outMessage->vias.empty()) { outMessage->vias.back().alias = true; outMessage->vias.back().rport = true; } } } bool SIPNonDialogClient::processResponse(SIPResponse& response, std::shared_ptr<SIPDialogState> state) { // TODO Q_UNUSED(response); Q_UNUSED(state); if (getOngoingRequest() == SIP_REGISTER) { qDebug() << "Got a response for REGISTER! TODO: Processing not implemented!"; } return false; } void SIPNonDialogClient::startTransaction(RequestType type) { SIPClientTransaction::startTransaction(type); } void SIPNonDialogClient::registerToServer() { startTransaction(SIP_REGISTER); emit sendNondialogRequest(remoteUri_, SIP_REGISTER); }
Rename unit test: WebViewTest.GetContentAsPlainText -> WebViewTest.ActiveState.
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "testing/gtest/include/gtest/gtest.h" #include "third_party/WebKit/WebKit/chromium/public/WebView.h" #include "webkit/tools/test_shell/test_shell_test.h" using WebKit::WebView; class WebViewTest : public TestShellTest { }; TEST_F(WebViewTest, GetContentAsPlainText) { WebView* view = test_shell_->webView(); ASSERT_TRUE(view != 0); view->setIsActive(true); EXPECT_TRUE(view->isActive()); view->setIsActive(false); EXPECT_FALSE(view->isActive()); view->setIsActive(true); EXPECT_TRUE(view->isActive()); } // TODO(viettrungluu): add more tests
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "testing/gtest/include/gtest/gtest.h" #include "third_party/WebKit/WebKit/chromium/public/WebView.h" #include "webkit/tools/test_shell/test_shell_test.h" using WebKit::WebView; class WebViewTest : public TestShellTest { }; TEST_F(WebViewTest, ActiveState) { WebView* view = test_shell_->webView(); ASSERT_TRUE(view != 0); view->setIsActive(true); EXPECT_TRUE(view->isActive()); view->setIsActive(false); EXPECT_FALSE(view->isActive()); view->setIsActive(true); EXPECT_TRUE(view->isActive()); } // TODO(viettrungluu): add more tests
Revert naming change - we're using camelCase everywhere else.
#include "bitfield.h" unsigned long getBitField(uint8_t* data, int start_bit, int num_bits) { unsigned long ret = 0; int start_byte = start_bit / 8; if (num_bits <= 8 ) { // Bit fields are positioned according to big-endian bit layout, but // inside the bit field, values are represented as little-endian. // Therefore, to get the bit field, we just need to convert to big-endian // bit ordering to find the field, and directly use the value we find in // the field. int bit_position = start_bit % 8; ret = data[start_byte]; int end_bit = bit_position + num_bits; ret = ret >> (8 - end_bit); } else { int end_byte = (start_bit + num_bits) / 8; // The lowest byte address contains the most significant bit. for (int i = start_byte; i <= end_byte; i++) { ret = ret << 8; ret = ret | data[i]; } //Calculates value to shift bitfield of interest to LSB ret = ret >> (8 - ((start_bit + num_bits) % 8)); } // Mask out any other bits besides those in the bitfield. unsigned long bitmask = (unsigned long)((0x1 << num_bits) - 1); return ret & bitmask; }
#include "bitfield.h" unsigned long getBitField(uint8_t* data, int startBit, int numBits) { unsigned long ret = 0; int startByte = startBit / 8; if (numBits <= 8 ) { // Bit fields are positioned according to big-endian bit layout, but // inside the bit field, values are represented as little-endian. // Therefore, to get the bit field, we just need to convert to big-endian // bit ordering to find the field, and directly use the value we find in // the field. int bitPosition = startBit % 8; ret = data[startByte]; int endBit = bitPosition + numBits; ret = ret >> (8 - endBit); } else { int endByte = (startBit + numBits) / 8; // The lowest byte address contains the most significant bit. for (int i = startByte; i <= endByte; i++) { ret = ret << 8; ret = ret | data[i]; } //Calculates value to shift bitfield of interest to LSB ret = ret >> (8 - ((startBit + numBits) % 8)); } // Mask out any other bits besides those in the bitfield. unsigned long bitmask = (unsigned long)((0x1 << numBits) - 1); return ret & bitmask; }
Correct argument name of constructor (effects -> _effects)
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <Rosetta/Enchants/Enchant.hpp> namespace RosettaStone { Enchant::Enchant(Effect& effect) { effects.emplace_back(effect); } Enchant::Enchant(std::vector<Effect>& effects) { effects = effects; } void Enchant::ActivateTo(Character* character) { for (auto& effect : effects) { effect.Apply(character); } } } // namespace RosettaStone
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <Rosetta/Enchants/Enchant.hpp> namespace RosettaStone { Enchant::Enchant(Effect& effect) { effects.emplace_back(effect); } Enchant::Enchant(std::vector<Effect>& _effects) { effects = _effects; } void Enchant::ActivateTo(Character* character) { for (auto& effect : effects) { effect.Apply(character); } } } // namespace RosettaStone
Use demo server as default and record performance.
/** * @file example.cpp * @author Marcus Edel * * Simple random agent. */ #include <iostream> #include "environment.hpp" using namespace gym; int main(int argc, char* argv[]) { const std::string environment = "CartPole-v0"; const std::string host = "127.0.0.1"; const std::string port = "4040"; double totalReward = 0; size_t totalSteps = 0; Environment env(host, port, environment); env.reset(); while (1) { env.step(env.action_space.sample()); env.render(); totalReward += env.reward; totalSteps += 1; if (env.done) { break; } } std::cout << "Total steps: " << totalSteps << " reward: " << totalReward << std::endl; return 0; }
/** * @file example.cpp * @author Marcus Edel * * Simple random agent. */ #include <iostream> #include "environment.hpp" using namespace gym; int main(int argc, char* argv[]) { const std::string environment = "SpaceInvaders-v0"; const std::string host = "kurg.org"; const std::string port = "4040"; double totalReward = 0; size_t totalSteps = 0; Environment env(host, port, environment); env.compression(9); env.monitor.start("./dummy/", true, true); env.reset(); env.render(); while (1) { arma::mat action = env.action_space.sample(); std::cout << "action: \n" << action << std::endl; env.step(action); totalReward += env.reward; totalSteps += 1; if (env.done) { break; } std::cout << "Current step: " << totalSteps << " current reward: " << totalReward << std::endl; } std::cout << "Total steps: " << totalSteps << " reward: " << totalReward << std::endl; return 0; }
Fix rdar-13338477 test-case for Linux. - Using __builtin_trap confuses the stack unwinder - __builtin_trap specific test will be added shortly
//===-- main.cpp ------------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// void bar(int const *foo) { __builtin_trap(); // Set break point at this line. } int main() { int foo[] = {1,2,3}; bar(foo); }
//===-- main.cpp ------------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// bool bar(int const *foo) { return foo != 0; // Set break point at this line. } int main() { int foo[] = {1,2,3}; return bar(foo); }
Fix a remove-cstr-calls test that fails checking of the produced code.
// RUN: grep -Ev "// *[A-Z-]+:" %s > %t.cpp // RUN: remove-cstr-calls . %t.cpp -- // RUN: FileCheck -input-file=%t.cpp %s // REQUIRES: shell namespace std { template<typename T> class allocator {}; template<typename T> class char_traits {}; template<typename C, typename T, typename A> struct basic_string { basic_string(); basic_string(const C *p, const A& a = A()); const C *c_str() const; }; typedef basic_string<char, std::char_traits<char>, std::allocator<char> > string; } namespace llvm { struct StringRef { StringRef(const char *p); }; } void f1(const std::string &s) { f1(s.c_str()); // CHECK: void f1 // CHECK-NEXT: f1(s) } void f2(const llvm::StringRef r) { std::string s; f2(s.c_str()); // CHECK: std::string s; // CHECK-NEXT: f2(s) } void f3(const llvm::StringRef &r) { std::string s; f3(s.c_str()); // CHECK: std::string s; // CHECK: f3(s) }
// RUN: grep -Ev "// *[A-Z-]+:" %s > %t.cpp // RUN: remove-cstr-calls . %t.cpp -- // RUN: FileCheck -input-file=%t.cpp %s // REQUIRES: shell namespace std { template<typename T> class allocator {}; template<typename T> class char_traits {}; template<typename C, typename T, typename A> struct basic_string { basic_string(); basic_string(const C *p, const A& a = A()); const C *c_str() const; }; typedef basic_string<char, std::char_traits<char>, std::allocator<char> > string; } namespace llvm { struct StringRef { StringRef(const char *p); StringRef(const std::string &); }; } void f1(const std::string &s) { f1(s.c_str()); // CHECK: void f1 // CHECK-NEXT: f1(s) } void f2(const llvm::StringRef r) { std::string s; f2(s.c_str()); // CHECK: std::string s; // CHECK-NEXT: f2(s) } void f3(const llvm::StringRef &r) { std::string s; f3(s.c_str()); // CHECK: std::string s; // CHECK: f3(s) }
Fix compilation of Tut00 after Physics change
#include <Nazara/Audio.hpp> #include <Nazara/Core.hpp> #include <Nazara/Graphics.hpp> #include <Nazara/Lua.hpp> #include <Nazara/Network.hpp> #include <Nazara/Noise.hpp> #include <Nazara/Physics.hpp> #include <Nazara/Renderer.hpp> #include <Nazara/Utility.hpp> #include <NDK/Application.hpp> #include <iostream> int main(int argc, char* argv[]) { // This "example" has only one purpose: Giving an empty project for you to test whatever you want // If you wish to have multiple test projects, you only have to copy/paste this directory and change the name in the build.lua Ndk::Application application(argc, argv); // Do what you want here return EXIT_SUCCESS; }
#include <Nazara/Audio.hpp> #include <Nazara/Core.hpp> #include <Nazara/Graphics.hpp> #include <Nazara/Lua.hpp> #include <Nazara/Network.hpp> #include <Nazara/Noise.hpp> #include <Nazara/Physics2D.hpp> #include <Nazara/Physics3D.hpp> #include <Nazara/Renderer.hpp> #include <Nazara/Utility.hpp> #include <NDK/Application.hpp> #include <iostream> int main(int argc, char* argv[]) { // This "example" has only one purpose: Giving an empty project for you to test whatever you want // If you wish to have multiple test projects, you only have to copy/paste this directory and change the name in the build.lua Ndk::Application application(argc, argv); // Do what you want here return EXIT_SUCCESS; }