Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Format CValidationState properly in all cases
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <util/validation.h> #include <consensus/validation.h> #include <tinyformat.h> /** Convert ValidationState to a human-readable message for logging */ std::string FormatStateMessage(const ValidationState &state) { return strprintf("%s%s", state.GetRejectReason(), state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage()); } const std::string strMessageMagic = "Peercoin Signed Message:\n";
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <util/validation.h> #include <consensus/validation.h> #include <tinyformat.h> /** Convert ValidationState to a human-readable message for logging */ std::string FormatStateMessage(const ValidationState &state) { if (state.IsValid()) { return "Valid"; } return strprintf("%s%s", state.GetRejectReason(), state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage()); } const std::string strMessageMagic = "Peercoin Signed Message:\n";
Move cassert include to OS X specific code
#include <glbinding/GetProcAddress.h> #include <cassert> #ifdef WIN32 #include <string> #include <windows.h> #elif __APPLE__ #include <string> #include <dlfcn.h> #else #include <GL/glx.h> #endif namespace gl { ProcAddress GetProcAddress(const char * name) { #ifdef WIN32 typedef void (__stdcall * PROCADDRESS)(); PROCADDRESS procAddress = reinterpret_cast<PROCADDRESS>(wglGetProcAddress(name)); if (procAddress == nullptr) { static HMODULE module = LoadLibrary(L"OPENGL32.DLL"); procAddress = reinterpret_cast<PROCADDRESS>(::GetProcAddress(module, name)); } #elif __APPLE__ typedef void * PROCADDRESS; void * library = dlopen("/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL", RTLD_LAZY); assert(library != nullptr); void * symbol = dlsym(library, name); PROCADDRESS procAddress = reinterpret_cast<PROCADDRESS>(symbol); #else typedef void (* PROCADDRESS)(); PROCADDRESS procAddress = reinterpret_cast<PROCADDRESS>(glXGetProcAddress(reinterpret_cast<const unsigned char*>(name))); #endif return reinterpret_cast<ProcAddress>(procAddress); } } // namespace gl
#include <glbinding/GetProcAddress.h> #ifdef WIN32 #include <string> #include <windows.h> #elif __APPLE__ #include <cassert> #include <string> #include <dlfcn.h> #else #include <GL/glx.h> #endif namespace gl { ProcAddress GetProcAddress(const char * name) { #ifdef WIN32 typedef void (__stdcall * PROCADDRESS)(); PROCADDRESS procAddress = reinterpret_cast<PROCADDRESS>(wglGetProcAddress(name)); if (procAddress == nullptr) { static HMODULE module = LoadLibrary(L"OPENGL32.DLL"); procAddress = reinterpret_cast<PROCADDRESS>(::GetProcAddress(module, name)); } #elif __APPLE__ typedef void * PROCADDRESS; void * library = dlopen("/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL", RTLD_LAZY); assert(library != nullptr); void * symbol = dlsym(library, name); PROCADDRESS procAddress = reinterpret_cast<PROCADDRESS>(symbol); #else typedef void (* PROCADDRESS)(); PROCADDRESS procAddress = reinterpret_cast<PROCADDRESS>(glXGetProcAddress(reinterpret_cast<const unsigned char*>(name))); #endif return reinterpret_cast<ProcAddress>(procAddress); } } // namespace gl
Update subscribe topic for add pub topic
#include<ros/ros.h> #include<ics3/ics> #include<servo_msgs/IdBased.h> ics::ICS3* driver {nullptr}; void move(const servo_msgs::IdBased::ConstPtr& msg) { auto degree = ics::Angle::newDegree(msg->angle); auto nowpos = driver->move(msg->id, degree); // TODO: publish now pos } int main(int argc, char** argv) { ros::init(argc, argv, "servo_krs_node"); ros::NodeHandle n {}; ros::NodeHandle pn {"~"}; std::string path {"/dev/ttyUSB0"}; pn.param<std::string>("path", path, path); try { ics::ICS3 ics {path.c_str()}; driver = &ics; } catch (std::runtime_error e) { ROS_INFO("Error: Cannot make ICS3 instance [%s]", e.what()); ROS_INFO("I tried open [%s]", path.c_str()); return -1; } ros::Subscriber sub = n.subscribe("krs", 100, move); ros::spin(); return 0; }
#include<ros/ros.h> #include<ics3/ics> #include<servo_msgs/IdBased.h> ics::ICS3* driver {nullptr}; void move(const servo_msgs::IdBased::ConstPtr& msg) { auto degree = ics::Angle::newDegree(msg->angle); auto nowpos = driver->move(msg->id, degree); // TODO: publish now pos } int main(int argc, char** argv) { ros::init(argc, argv, "servo_krs_node"); ros::NodeHandle n {}; ros::NodeHandle pn {"~"}; std::string path {"/dev/ttyUSB0"}; pn.param<std::string>("path", path, path); try { ics::ICS3 ics {path.c_str()}; driver = &ics; } catch (std::runtime_error e) { ROS_INFO("Error: Cannot make ICS3 instance [%s]", e.what()); ROS_INFO("I tried open [%s]", path.c_str()); return -1; } ros::Subscriber sub = n.subscribe("cmd_krs", 100, move); ros::spin(); return 0; }
Remove unused `using namespace std`
#include <google/protobuf/compiler/command_line_interface.h> #include <google/protobuf/compiler/cpp/cpp_generator.h> #include <google/protobuf/compiler/perlxs/perlxs_generator.h> #include <iostream> #include <string> using namespace std; int main(int argc, char* argv[]) { google::protobuf::compiler::CommandLineInterface cli; // Proto2 C++ (for convenience, so the user doesn't need to call // protoc separately) google::protobuf::compiler::cpp::CppGenerator cpp_generator; cli.RegisterGenerator("--cpp_out", &cpp_generator, "Generate C++ header and source."); // Proto2 Perl/XS google::protobuf::compiler::perlxs::PerlXSGenerator perlxs_generator; cli.RegisterGenerator("--out", &perlxs_generator, "Generate Perl/XS source files."); cli.SetVersionInfo(perlxs_generator.GetVersionInfo()); // process Perl/XS command line options first, and filter them out // of the argument list. we really need to be able to register // options with the CLI instead of doing this stupid hack here. int j = 1; for (int i = 1; i < argc; i++) { if (perlxs_generator.ProcessOption(argv[i]) == false) { argv[j++] = argv[i]; } } return cli.Run(j, argv); }
#include <google/protobuf/compiler/command_line_interface.h> #include <google/protobuf/compiler/cpp/cpp_generator.h> #include <google/protobuf/compiler/perlxs/perlxs_generator.h> #include <iostream> #include <string> int main(int argc, char* argv[]) { google::protobuf::compiler::CommandLineInterface cli; // Proto2 C++ (for convenience, so the user doesn't need to call // protoc separately) google::protobuf::compiler::cpp::CppGenerator cpp_generator; cli.RegisterGenerator("--cpp_out", &cpp_generator, "Generate C++ header and source."); // Proto2 Perl/XS google::protobuf::compiler::perlxs::PerlXSGenerator perlxs_generator; cli.RegisterGenerator("--out", &perlxs_generator, "Generate Perl/XS source files."); cli.SetVersionInfo(perlxs_generator.GetVersionInfo()); // process Perl/XS command line options first, and filter them out // of the argument list. we really need to be able to register // options with the CLI instead of doing this stupid hack here. int j = 1; for (int i = 1; i < argc; i++) { if (perlxs_generator.ProcessOption(argv[i]) == false) { argv[j++] = argv[i]; } } return cli.Run(j, argv); }
Update c++ steganography solution to use cin
#ifndef MAIN_CPP #define MAIN_CPP #include <iostream> #include <bitset> #include <string> #include <fstream> int main() { std::ifstream myfile; std::string message,value,translate; enum States{W,Z,O,I}; States state = W; myfile.open("input1.txt"); while(!myfile.eof()) { std::getline(myfile,value,' '); value = value.substr(2,1); switch(state) { case W: { if(value == "0") { state = Z; message += value; } break; } case Z: { if(value == "1") { state = O; message +=value; } else { state = W; message = ""; } break; } case O: { if(value == "1" || value == "0") { message += value; state = I; } else { state = W; value = ""; } break; } case I: { if(!(value == "1" || value == "0")) { state = W; } else { message += value; if(message.length() == 8) { std::bitset<8> bs(message); translate += char(bs.to_ulong()); message = ""; } } break; } } } std::cout << translate; }; #endif
#ifndef MAIN_CPP #define MAIN_CPP #include <iostream> #include <bitset> #include <string> int main() { std::string message,value,translate; enum States{W,Z,O,I}; States state = W; while(std::getline(std::cin,value,' ')) { value = value.substr(2,1); switch(state) { case W: { if(value == "0") { state = Z; message += value; } break; } case Z: { if(value == "1") { state = O; message +=value; } else { state = W; message = ""; } break; } case O: { if(value == "1" || value == "0") { message += value; state = I; } else { state = W; value = ""; } break; } case I: { if(!(value == "1" || value == "0")) { state = W; } else { message += value; if(message.length() == 8) { std::bitset<8> bs(message); translate += char(bs.to_ulong()); message = ""; } } break; } } } std::cout << translate; }; #endif
Disable ExtensionApiTest.Popup. It's been timing out for the last 750+ runs.
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" // Flaky, http://crbug.com/46601. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_Popup) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("popup/popup_main")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, PopupFromInfobar) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("popup/popup_from_infobar")) << message_; }
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" // Times out. See http://crbug.com/46601. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Popup) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("popup/popup_main")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, PopupFromInfobar) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("popup/popup_from_infobar")) << message_; }
Set default lifetime to lt 0
#include "particle.h" Particle::Particle(const Vector4D &p, const Vector4D &v) : position(p), velocity(v), lifetime(0) { }
#include "particle.h" Particle::Particle(const Vector4D &p, const Vector4D &v) : position(p), velocity(v), lifetime(-1) { }
Use texture size as sprite frame size if not given
#include "gamelib/core/res/SpriteResource.hpp" #include "gamelib/core/res/ResourceManager.hpp" #include "gamelib/utils/json.hpp" namespace gamelib { void registerSpriteLoader(ResourceManager& resmgr) { resmgr.registerFileType("spr", spriteLoader); } BaseResourceHandle spriteLoader(const std::string& fname, ResourceManager* resmgr) { Json::Value node; if (!loadJsonFromFile(fname, node)) return nullptr; if (!node.isMember("texture")) { LOG_ERROR("No texture specified for sprite: ", fname); return nullptr; } auto sprite = SpriteResource::create(); sprite->tex = resmgr->get(node["texture"].asString()).as<TextureResource>(); math::Vec2f tmp; if (loadFromJson(node["framepos"], tmp)) sprite->rect.pos = tmp; if (loadFromJson(node["framesize"], tmp)) sprite->rect.size = tmp; if (loadFromJson(node["origin"], tmp)) sprite->origin = tmp.asPoint(); sprite->ani.length = node.get("length", 1).asInt(); sprite->ani.speed = node.get("speed", 0).asFloat(); sprite->ani.setIndex(node.get("offset", 0).asInt()); return sprite.as<BaseResource>(); } }
#include "gamelib/core/res/SpriteResource.hpp" #include "gamelib/core/res/ResourceManager.hpp" #include "gamelib/utils/json.hpp" #include "gamelib/utils/conversions.hpp" namespace gamelib { void registerSpriteLoader(ResourceManager& resmgr) { resmgr.registerFileType("spr", spriteLoader); } BaseResourceHandle spriteLoader(const std::string& fname, ResourceManager* resmgr) { Json::Value node; if (!loadJsonFromFile(fname, node)) return nullptr; if (!node.isMember("texture")) { LOG_ERROR("No texture specified for sprite: ", fname); return nullptr; } auto sprite = SpriteResource::create(); sprite->tex = resmgr->get(node["texture"].asString()).as<TextureResource>(); math::Vec2f pos, size = convert(sprite->tex->getSize()); loadFromJson(node["framepos"], pos); loadFromJson(node["framesize"], size); sprite->rect.pos = pos; sprite->rect.size = size; loadFromJson(node["origin"], sprite->origin); sprite->ani.length = node.get("length", 1).asInt(); sprite->ani.speed = node.get("speed", 0).asFloat(); sprite->ani.setIndex(node.get("offset", 0).asInt()); return sprite.as<BaseResource>(); } }
Remove extra functions from codec classes
#include "h264manager.h" H264Manager::H264Manager() { encodingParameters = "-c:v libx264 -preset ultrafast -f matroska"; } void H264Manager::start(QProcess &process, QString file) { QString command = "ffmpeg -re -i \"" + file + "\" -c:v libx264 -preset ultrafast -an -f matroska udp://localhost:" + ENCODED_VIDEO_PORT + " -c:v libx264 -preset ultrafast -an -f matroska udp://localhost:" + VIDEO_PROBE_PORT; process.start(command.toUtf8().constData()); }
#include "h264manager.h" H264Manager::H264Manager() { encodingParameters = "-c:v libx264 -preset ultrafast -f matroska"; }
Use parens to silence clang warnings
#include <ncurses.h> #include "../../../src/contents.hh" #include "../../../src/key_aliases.hh" #include "../../vick-move/src/move.hh" void enter_insert_mode(contents& contents, boost::optional<int>) { char ch; while(ch = getch() != _escape) { contents.cont[contents.y].insert(contents.x, 1, ch); mvf(contents); } } void enter_replace_insert_mode(contents& contents, boost::optional<int>) { char ch; while(ch = getch() != _escape) { if(contents.x >= contents.cont[contents.y].size()) { contents.cont[contents.y].push_back(ch); } else { contents.cont[contents.y][contents.x] = ch; } } }
#include <ncurses.h> #include "../../../src/contents.hh" #include "../../../src/key_aliases.hh" #include "../../vick-move/src/move.hh" void enter_insert_mode(contents& contents, boost::optional<int>) { char ch; while((ch = getch()) != _escape) { contents.cont[contents.y].insert(contents.x, 1, ch); mvf(contents); } } void enter_replace_insert_mode(contents& contents, boost::optional<int>) { char ch; while((ch = getch()) != _escape) { if(contents.x >= contents.cont[contents.y].size()) { contents.cont[contents.y].push_back(ch); } else { contents.cont[contents.y][contents.x] = ch; } } }
Work around gcc variadic arguments warning
#include "gtest/gtest.h" #include "hemi/launch.h" HEMI_MEM_DEVICE int result; HEMI_MEM_DEVICE int rGDim; HEMI_MEM_DEVICE int rBDim; template <typename... Arguments> struct k { HEMI_DEV_CALLABLE_MEMBER void operator()(Arguments... args) { result = sizeof...(args); rGDim = 1;//gridDim.x; rBDim = 1;//blockDim.x; } }; TEST(PortableLaunchTest, KernelFunction_AutoConfig) { k<int> kernel; hemi::launch(kernel, 1); }
#include "gtest/gtest.h" #include "hemi/launch.h" HEMI_MEM_DEVICE int result; HEMI_MEM_DEVICE int rGDim; HEMI_MEM_DEVICE int rBDim; template <typename T, typename... Arguments> HEMI_DEV_CALLABLE T first(T f, Arguments...) { return f; } template <typename... Arguments> struct k { HEMI_DEV_CALLABLE_MEMBER void operator()(Arguments... args) { result = first(args...); //sizeof...(args); rGDim = 1;//gridDim.x; rBDim = 1;//blockDim.x; } }; TEST(PortableLaunchTest, KernelFunction_AutoConfig) { k<int> kernel; hemi::launch(kernel, 1); }
Add another solution for the problem
class Solution { public: // Backtracking vector<vector<int>> subsets(vector<int>& nums) { vector<vector<int>> res; vector<int> sub; subsets(nums, sub, res, 0); return res; } void subsets(vector<int>& nums, vector<int>& sub, vector<vector<int>>& subs, int start) { subs.push_back(sub); for (int i = start; i < nums.size(); i++) { sub.push_back(nums[i]); subsets(nums, sub, subs, i + 1); sub.pop_back(); } } // Iterative vector<vector<int>> subsets(vector<int>& nums) { vector<vector<int>> res; vector<int> sub; res.push_back(sub); for (int i = 0; i < nums.size(); i++) { int size = res.size(); for (int j = 0; j < size; j++) { res.push_back(res[j]); res.back().push_back(nums[i]); } } return res; } };
class Solution { public: // Backtracking vector<vector<int>> subsets(vector<int>& nums) { vector<vector<int>> res; vector<int> sub; subsets(nums, sub, res, 0); return res; } void subsets(vector<int>& nums, vector<int>& sub, vector<vector<int>>& subs, int start) { subs.push_back(sub); for (int i = start; i < nums.size(); i++) { sub.push_back(nums[i]); subsets(nums, sub, subs, i + 1); sub.pop_back(); } } // Iterative vector<vector<int>> subsets(vector<int>& nums) { vector<vector<int>> res; vector<int> sub; res.push_back(sub); for (int i = 0; i < nums.size(); i++) { int size = res.size(); for (int j = 0; j < size; j++) { res.push_back(res[j]); res.back().push_back(nums[i]); } } return res; } // Bit manipulation vector<vector<int>> subsets(vector<int>& nums) { int n = nums.size(); int resSize = (int)pow(2, n); vector<vector<int>> res(resSize, vector<int>()); for (int i = 0; i < n; i++) { for (int j = 0; j < resSize; j++) { if ((j >> i) & 1) { res[j].push_back(nums[i]); } } } return res; } };
Fix Elevator Subsystem limit swtich
#include "ElevatorSubsystem.h" #include "../RobotMap.h" ElevatorSubsystem::ElevatorSubsystem() : Subsystem("ElevatorSubsystem"), pullMotorRight(PULL_MOTOR_RIGHT),pullMotorLeft(PULL_MOTOR_LEFT), underSwitch(UNDER_LIMIT),upSwitch(UP_LIMIT) { } void ElevatorSubsystem::InitDefaultCommand() { // Set the default command for a subsystem here. //SetDefaultCommand(new MySpecialCommand()); } // Put methods for controlling this subsystem // here. Call these from Commands. void ElevatorSubsystem::DriveElevator(float pullSpeed){ pullMotorLeft.Set(pullSpeed); pullMotorRight.Set(pullSpeed); }
#include "ElevatorSubsystem.h" #include "../RobotMap.h" ElevatorSubsystem::ElevatorSubsystem() : Subsystem("ElevatorSubsystem"), pullMotorRight(PULL_MOTOR_RIGHT),pullMotorLeft(PULL_MOTOR_LEFT), underSwitch(UNDER_LIMIT),upSwitch(UP_LIMIT) { } void ElevatorSubsystem::InitDefaultCommand() { // Set the default command for a subsystem here. //SetDefaultCommand(new MySpecialCommand()); } // Put methods for controlling this subsystem // here. Call these from Commands. void ElevatorSubsystem::DriveElevator(float pullSpeed){ //if underSwitch is pushed and pullspeed is plus, elevator doesn't move //if upSwitch is pushed and pullspeed is minus, elevator doesn't move if(!(underSwitch.Get() && pullSpeed > 0) && !(upSwitch.Get() && pullSpeed < 0)){ pullMotorLeft.Set(pullSpeed); pullMotorRight.Set(pullSpeed); } }
Remove implicit malloc() from interruption signal handler to prevent a deadlock of the whole client.
/* * Copyright (c) 2011 by Michael Berlin, Zuse Institute Berlin * * Licensed under the BSD License, see LICENSE file for details. * */ #include "libxtreemfs/callback/execute_sync_request.h" using namespace xtreemfs::rpc; using namespace xtreemfs::util; namespace xtreemfs { boost::thread_specific_ptr<int> intr_pointer; void InterruptSyncRequest(int signal) { if (Logging::log->loggingActive(LEVEL_DEBUG)) { Logging::log->getLog(LEVEL_DEBUG) << "INTERRUPT triggered, setting TLS pointer" << std::endl; } intr_pointer.reset(new int(0)); } } // namespace xtreemfs
/* * Copyright (c) 2011 by Michael Berlin, Zuse Institute Berlin * * Licensed under the BSD License, see LICENSE file for details. * */ #include "libxtreemfs/callback/execute_sync_request.h" using namespace xtreemfs::rpc; using namespace xtreemfs::util; namespace xtreemfs { /** The TLS pointer is set to != NULL if the current operation shall be * interrupted. */ boost::thread_specific_ptr<int> intr_pointer(NULL); /** Calling malloc() inside a signal handler is a really bad idea as there may * occur a dead lock on the lock of the heap: that happens if a malloc is in * progress, which already obtained a lock on the heap, and now a signal * handler is called (and executed in the same thread) and also tries to * execute malloc. * * For this reason the TLS is filled with the address of a static integer * instead of a new-ly created integer. */ int dummy_integer = 1; void InterruptSyncRequest(int signal) { if (Logging::log->loggingActive(LEVEL_DEBUG)) { Logging::log->getLog(LEVEL_DEBUG) << "INTERRUPT triggered, setting TLS pointer" << std::endl; } intr_pointer.reset(&dummy_integer); } } // namespace xtreemfs
Use -ffreestanding with clang_cc1 to make the test picks the clang builtin include.
// RUN: %clang -fsyntax-only -verify %s // RUN: %clang -fsyntax-only -verify -fshort-wchar %s #include <limits.h> const bool swchar = (wchar_t)-1 > (wchar_t)0; #ifdef __WCHAR_UNSIGNED__ int signed_test[!swchar]; #else int signed_test[swchar]; #endif int max_test[WCHAR_MAX == (swchar ? -(WCHAR_MIN+1) : (wchar_t)-1)]; int min_test[WCHAR_MIN == (swchar ? 0 : -WCHAR_MAX-1)];
// RUN: %clang_cc1 -ffreestanding -fsyntax-only -verify %s // RUN: %clang_cc1 -ffreestanding -fsyntax-only -verify -fshort-wchar %s #include <limits.h> const bool swchar = (wchar_t)-1 > (wchar_t)0; #ifdef __WCHAR_UNSIGNED__ int signed_test[!swchar]; #else int signed_test[swchar]; #endif int max_test[WCHAR_MAX == (swchar ? -(WCHAR_MIN+1) : (wchar_t)-1)]; int min_test[WCHAR_MIN == (swchar ? 0 : -WCHAR_MAX-1)];
Fix one test on OSX.
// Test that LargeAllocator unpoisons memory before releasing it to the OS. // RUN: %clangxx_asan %s -o %t // The memory is released only when the deallocated chunk leaves the quarantine, // otherwise the mmap(p, ...) call overwrites the malloc header. // RUN: ASAN_OPTIONS=quarantine_size=1 %t #include <assert.h> #include <malloc.h> #include <string.h> #include <sys/mman.h> int main() { const int kPageSize = 4096; void *p = memalign(kPageSize, 1024 * 1024); free(p); char *q = (char *)mmap(p, kPageSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON | MAP_FIXED, 0, 0); assert(q == p); memset(q, 42, kPageSize); munmap(q, kPageSize); return 0; }
// Test that LargeAllocator unpoisons memory before releasing it to the OS. // RUN: %clangxx_asan %s -o %t // The memory is released only when the deallocated chunk leaves the quarantine, // otherwise the mmap(p, ...) call overwrites the malloc header. // RUN: ASAN_OPTIONS=quarantine_size=1 %t #include <assert.h> #include <string.h> #include <sys/mman.h> #include <stdlib.h> #ifdef __ANDROID__ #include <malloc.h> void *my_memalign(size_t boundary, size_t size) { return memalign(boundary, size); } #else void *my_memalign(size_t boundary, size_t size) { void *p; posix_memalign(&p, boundary, size); return p; } #endif int main() { const int kPageSize = 4096; void *p = my_memalign(kPageSize, 1024 * 1024); free(p); char *q = (char *)mmap(p, kPageSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON | MAP_FIXED, 0, 0); assert(q == p); memset(q, 42, kPageSize); munmap(q, kPageSize); return 0; }
Remove extraneous IVW_CORE_API in explicit template instantiation
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2013-2017 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <inviwo/core/datastructures/spatialdata.h> namespace inviwo { template class IVW_CORE_API SpatialEntity<2>; template class IVW_CORE_API SpatialEntity<3>; } // namespace
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2013-2017 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <inviwo/core/datastructures/spatialdata.h> namespace inviwo { template class SpatialEntity<2>; template class SpatialEntity<3>; } // namespace
Build fix for unix (return type csSting incomplete). Hope it's correct...
/* Copyright (C) 2002 by Eric Sunshine <sunshine@sunshineco.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "csutil/sysfunc.h" #include <unistd.h> #include <sys/types.h> #include <pwd.h> csString csGetUsername() { csString username; struct passwd const* r = getpwuid(getuid()); if (r != 0) username = r->pw_name; username.Trim(); return username; }
/* Copyright (C) 2002 by Eric Sunshine <sunshine@sunshineco.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "csutil/sysfunc.h" #include <unistd.h> #include <sys/types.h> #include <pwd.h> #include "csutil/csstring.h" csString csGetUsername() { csString username; struct passwd const* r = getpwuid(getuid()); if (r != 0) username = r->pw_name; username.Trim(); return username; }
Upgrade Blink to milliseconds-based last modified filetimes, part 2.
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/child/file_info_util.h" #include "base/logging.h" #include "third_party/WebKit/public/platform/WebFileInfo.h" namespace content { void FileInfoToWebFileInfo(const base::File::Info& file_info, blink::WebFileInfo* web_file_info) { DCHECK(web_file_info); // WebKit now expects NaN as uninitialized/null Date. if (file_info.last_modified.is_null()) web_file_info->modificationTime = std::numeric_limits<double>::quiet_NaN(); else web_file_info->modificationTime = file_info.last_modified.ToDoubleT(); web_file_info->length = file_info.size; if (file_info.is_directory) web_file_info->type = blink::WebFileInfo::TypeDirectory; else web_file_info->type = blink::WebFileInfo::TypeFile; } static_assert(std::numeric_limits<double>::has_quiet_NaN, "should have quiet NaN"); } // namespace content
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/child/file_info_util.h" #include "base/logging.h" #include "third_party/WebKit/public/platform/WebFileInfo.h" namespace content { void FileInfoToWebFileInfo(const base::File::Info& file_info, blink::WebFileInfo* web_file_info) { DCHECK(web_file_info); // WebKit now expects NaN as uninitialized/null Date. if (file_info.last_modified.is_null()) { web_file_info->modificationTime = std::numeric_limits<double>::quiet_NaN(); web_file_info->modificationTimeMS = std::numeric_limits<double>::quiet_NaN(); } else { web_file_info->modificationTime = file_info.last_modified.ToDoubleT(); web_file_info->modificationTimeMS = file_info.last_modified.ToJsTime(); } web_file_info->length = file_info.size; if (file_info.is_directory) web_file_info->type = blink::WebFileInfo::TypeDirectory; else web_file_info->type = blink::WebFileInfo::TypeFile; } static_assert(std::numeric_limits<double>::has_quiet_NaN, "should have quiet NaN"); } // namespace content
Fix overflow bug in edge detector
#include "Halide.h" namespace { class EdgeDetect : public Halide::Generator<EdgeDetect> { public: ImageParam input{ UInt(8), 2, "input" }; Func build() { Var x, y; Func clamped = Halide::BoundaryConditions::repeat_edge(input); // Gradients in x and y. Func gx("gx"); Func gy("gy"); gx(x, y) = (clamped(x + 1, y) - clamped(x - 1, y)) / 2; gy(x, y) = (clamped(x, y + 1) - clamped(x, y - 1)) / 2; Func result("result"); result(x, y) = gx(x, y) * gx(x, y) + gy(x, y) * gy(x, y) + 128; // CPU schedule: // Parallelize over scan lines, 4 scanlines per task. // Independently, vectorize in x. result .parallel(y, 4) .vectorize(x, natural_vector_size(UInt(8))); return result; } }; Halide::RegisterGenerator<EdgeDetect> register_edge_detect{ "edge_detect" }; } // namespace
#include "Halide.h" namespace { class EdgeDetect : public Halide::Generator<EdgeDetect> { public: ImageParam input{ UInt(8), 2, "input" }; Func build() { Var x, y; Func clamped = Halide::BoundaryConditions::repeat_edge(input); // Gradients in x and y. Func gx("gx"); Func gy("gy"); gx(x, y) = cast<uint16_t>(clamped(x + 1, y)) - clamped(x - 1, y); gy(x, y) = cast<uint16_t>(clamped(x, y + 1)) - clamped(x, y - 1); Func result("result"); result(x, y) = cast<uint8_t>(min(255, gx(x, y) * gx(x, y) + gy(x, y) * gy(x, y))); // CPU schedule: // Parallelize over scan lines, 4 scanlines per task. // Independently, vectorize in x. result .parallel(y, 4) .vectorize(x, natural_vector_size(UInt(8))); return result; } }; Halide::RegisterGenerator<EdgeDetect> register_edge_detect{ "edge_detect" }; } // namespace
Add checker for illegal json string
#include "SubDocPropValueRenderer.h" #include <rapidjson/document.h> #include <glog/logging.h> namespace sf1r { void SubDocPropValueRenderer::renderSubDocPropValue( const std::string& propName, const std::string& origText, izenelib::driver::Value& resourceValue) { if (origText.empty()) return; rapidjson::Document doc; doc.Parse<0>(origText.c_str()); const rapidjson::Value& subDocs = doc; assert(subDocs.IsArray()); for (rapidjson::Value::ConstValueIterator vit = subDocs.Begin(); vit != subDocs.End(); vit++) { izenelib::driver::Value& subDoc = resourceValue(); for (rapidjson::Value::ConstMemberIterator mit = vit->MemberBegin(); mit != vit->MemberEnd(); mit++) { subDoc[mit->name.GetString()]=mit->value.GetString(); } } } }
#include "SubDocPropValueRenderer.h" #include <rapidjson/document.h> #include <glog/logging.h> namespace sf1r { void SubDocPropValueRenderer::renderSubDocPropValue( const std::string& propName, const std::string& origText, izenelib::driver::Value& resourceValue) { if (origText.empty()) return; rapidjson::Document doc; if (doc.Parse<0>(origText.c_str()).HasParseError()); { return; } const rapidjson::Value& subDocs = doc; assert(subDocs.IsArray()); for (rapidjson::Value::ConstValueIterator vit = subDocs.Begin(); vit != subDocs.End(); vit++) { izenelib::driver::Value& subDoc = resourceValue(); for (rapidjson::Value::ConstMemberIterator mit = vit->MemberBegin(); mit != vit->MemberEnd(); mit++) { subDoc[mit->name.GetString()]=mit->value.GetString(); } } } }
Add unit test for new wrapper call.
#include <fstream> #include <iostream> #include "person.pb.h" //#include "../pb2json.h" #include <pb2json.h> using namespace std; int main(int argc,char *argv[]) { ifstream fin("dump",ios::binary); fin.seekg(0,ios_base::end); size_t len = fin.tellg(); fin.seekg(0,ios_base::beg); char *buf = new char [len]; fin.read(buf,len); Message *p = new Person(); char *json = pb2json(p,buf,len); cout<<json<<endl; free(json); delete p; return 0; }
#include <fstream> #include <iostream> #include "person.pb.h" //#include "../pb2json.h" #include <pb2json.h> using namespace std; int main(int argc,char *argv[]) { // Test 1: read binary PB from a file and convert it to JSON ifstream fin("dump",ios::binary); fin.seekg(0,ios_base::end); size_t len = fin.tellg(); fin.seekg(0,ios_base::beg); char *buf = new char [len]; fin.read(buf,len); Message *p = new Person(); char *json = pb2json(p,buf,len); cout<<json<<endl; free(json); delete p; // Test 2: convert PB to JSON directly Person p2; char *json2 = pb2json(p2); cout<<json2<<endl; free(json2); return 0; }
Fix input test on Mac for ControlModifier
#include <QtTest/QtTest> #include <gui/input.h> class TestInput: public QObject { Q_OBJECT private slots: void specialKeys(); private: NeovimQt::InputConv input; }; void TestInput::specialKeys() { foreach(int k, input.specialKeys.keys()) { QCOMPARE(input.convertKey("", k, Qt::NoModifier), QString("<%1>").arg(input.specialKeys.value(k))); QCOMPARE(input.convertKey("", k, Qt::ControlModifier), #ifdef Q_OS_MAC // On Mac Control is actually the Cmd key, which we // don't support yet QString("<%1>").arg(input.specialKeys.value(k))); #else QString("<C-%1>").arg(input.specialKeys.value(k))); #endif QCOMPARE(input.convertKey("", k, Qt::AltModifier), QString("<A-%1>").arg(input.specialKeys.value(k))); QCOMPARE(input.convertKey("", k, Qt::MetaModifier), #ifdef Q_OS_MAC // On Mac Meta is actually the Control key QString("<C-%1>").arg(input.specialKeys.value(k))); #else // Meta is not handled right now QString("<%1>").arg(input.specialKeys.value(k))); #endif } } QTEST_MAIN(TestInput) #include "tst_input.moc"
#include <QtTest/QtTest> #include <gui/input.h> class TestInput: public QObject { Q_OBJECT private slots: void specialKeys(); private: NeovimQt::InputConv input; }; void TestInput::specialKeys() { foreach(int k, input.specialKeys.keys()) { QCOMPARE(input.convertKey("", k, Qt::NoModifier), QString("<%1>").arg(input.specialKeys.value(k))); QCOMPARE(input.convertKey("", k, Qt::ControlModifier), #ifdef Q_OS_MAC // On Mac Control is actually the Cmd key, which we // don't support yet QString("<D-%1>").arg(input.specialKeys.value(k))); #else QString("<C-%1>").arg(input.specialKeys.value(k))); #endif QCOMPARE(input.convertKey("", k, Qt::AltModifier), QString("<A-%1>").arg(input.specialKeys.value(k))); QCOMPARE(input.convertKey("", k, Qt::MetaModifier), #ifdef Q_OS_MAC // On Mac Meta is actually the Control key QString("<C-%1>").arg(input.specialKeys.value(k))); #else // Meta is not handled right now QString("<%1>").arg(input.specialKeys.value(k))); #endif } } QTEST_MAIN(TestInput) #include "tst_input.moc"
Tweak expected error message, although we still fail this test
// RUN: clang-cc -fsyntax-only -verify %s // XFAIL: * class C { public: C(int a, int b); }; C::C(int a, // expected-note {{previous definition}} int b) // expected-note {{previous definition}} try { int c; } catch (int a) { // expected-error {{redefinition of 'a'}} int b; // expected-error {{redefinition of 'b'}} ++c; // expected-error {{use of undeclared identifion 'c'}} }
// RUN: clang-cc -fsyntax-only -verify %s // XFAIL: * class C { public: C(int a, int b); }; C::C(int a, // expected-note {{previous definition}} int b) // expected-note {{previous definition}} try { int c; } catch (int a) { // expected-error {{redefinition of 'a'}} int b; // expected-error {{redefinition of 'b'}} ++c; // expected-error {{use of undeclared identifier 'c'}} }
Remove FIXME and hardcoded triple from this test (PR18251)
// RUN: %clang_cc1 -triple %itanium_abi_triple -emit-llvm %s -o - // FIXME: Don't assert for non-Win32 triples (PR18251). // RUN: %clang_cc1 -triple i686-pc-win32 -fno-rtti -emit-llvm %s -o - struct A { virtual void Method() = 0; }; struct B : public A { virtual void Method() { } }; typedef void (A::*fn_type_a)(void); typedef void (B::*fn_type_b)(void); int main(int argc, char **argv) { fn_type_a f = reinterpret_cast<fn_type_a>(&B::Method); fn_type_b g = reinterpret_cast<fn_type_b>(f); B b; (b.*g)(); return 0; }
// RUN: %clang_cc1 -triple %itanium_abi_triple -emit-llvm %s -o - // RUN: %clang_cc1 -triple %ms_abi_triple -fno-rtti -emit-llvm %s -o - struct A { virtual void Method() = 0; }; struct B : public A { virtual void Method() { } }; typedef void (A::*fn_type_a)(void); typedef void (B::*fn_type_b)(void); int main(int argc, char **argv) { fn_type_a f = reinterpret_cast<fn_type_a>(&B::Method); fn_type_b g = reinterpret_cast<fn_type_b>(f); B b; (b.*g)(); return 0; }
Strengthen hash function for (un)tagged metric name lookups.
#include <monsoon/history/collect_history.h> namespace monsoon { collect_history::~collect_history() noexcept {} std::size_t collect_history::metrics_hash::operator()( const std::tuple<group_name, metric_name>& t) const noexcept { return std::hash<group_name>()(std::get<0>(t)); } std::size_t collect_history::metrics_hash::operator()( const std::tuple<simple_group, metric_name>& t) const noexcept { return std::hash<simple_group>()(std::get<0>(t)); } } /* namespace monsoon */
#include <monsoon/history/collect_history.h> namespace monsoon { collect_history::~collect_history() noexcept {} std::size_t collect_history::metrics_hash::operator()( const std::tuple<group_name, metric_name>& t) const noexcept { return std::hash<group_name>()(std::get<0>(t)) ^ std::hash<metric_name>()(std::get<1>(t)); } std::size_t collect_history::metrics_hash::operator()( const std::tuple<simple_group, metric_name>& t) const noexcept { return std::hash<simple_group>()(std::get<0>(t)) ^ std::hash<metric_name>()(std::get<1>(t)); } } /* namespace monsoon */
Fix max array opt version
// Compile with -O3 -march=native to see autovectorization typedef double * __attribute__((aligned(64))) aligned_double; void maxArray(aligned_double __restrict x, aligned_double __restrict y) { for (int i = 0; i < 65536; i++) { x[i] = ((y[i] > x[i]) ? y[i] : x[i]); } }
// Compile with -O3 -march=native to see autovectorization typedef double *__attribute__((aligned(64))) aligned_double; void maxArray(aligned_double __restrict x, aligned_double __restrict y) { for (int i = 0; i < 65536; i++) { x[i] = ((y[i] > x[i]) ? y[i] : x[i]); } }
Hide download size if file is already downloaded.
#include <QFile> #include "ArchiveModel.hh" #include "ArchiveListItemWidget.hh" #include "ui_ArchiveListItemWidget.h" #include "HumanReadableSize.hh" ArchiveListItemWidget::ArchiveListItemWidget(QWidget *parent) : QWidget(parent), d_ui(QSharedPointer<Ui::ArchiveListItemWidget>(new Ui::ArchiveListItemWidget())) { d_ui->setupUi(this); } ArchiveListItemWidget::~ArchiveListItemWidget() { // declared here to generate QSharedPointer destructor where Ui::ArchiveListItemWidget is known. } void ArchiveListItemWidget::setArchiveEntry(ArchiveEntry const &entry) { d_ui->nameLabel->setText(entry.name); d_ui->descriptionLabel->setText(entry.description); d_ui->sizeLabel->setText(humanReadableSize(entry.size)); d_ui->downloadedLabel->setVisible(entry.existsLocally()); }
#include <QFile> #include "ArchiveModel.hh" #include "ArchiveListItemWidget.hh" #include "ui_ArchiveListItemWidget.h" #include "HumanReadableSize.hh" ArchiveListItemWidget::ArchiveListItemWidget(QWidget *parent) : QWidget(parent), d_ui(QSharedPointer<Ui::ArchiveListItemWidget>(new Ui::ArchiveListItemWidget())) { d_ui->setupUi(this); } ArchiveListItemWidget::~ArchiveListItemWidget() { // declared here to generate QSharedPointer destructor where Ui::ArchiveListItemWidget is known. } void ArchiveListItemWidget::setArchiveEntry(ArchiveEntry const &entry) { d_ui->nameLabel->setText(entry.name); d_ui->descriptionLabel->setText(entry.description); d_ui->sizeLabel->setText(humanReadableSize(entry.size)); d_ui->sizeLabel->setVisible(!entry.existsLocally()); d_ui->downloadedLabel->setVisible(entry.existsLocally()); }
Disable ExtensionApiTest.Infobars on Mac, as it is flaky.
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" #if defined(TOOLKIT_VIEWS) || defined(OS_MACOSX) #define MAYBE_Infobars Infobars #else // Need to finish port to Linux. See http://crbug.com/39916 for details. #define MAYBE_Infobars DISABLED_Infobars #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) { // TODO(finnur): Remove once infobars are no longer experimental (bug 39511). CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("infobars")) << message_; }
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" #if defined(TOOLKIT_VIEWS) #define MAYBE_Infobars Infobars #else // Need to finish port to Linux. See http://crbug.com/39916 for details. // Also disabled on mac. See http://crbug.com/60990. #define MAYBE_Infobars DISABLED_Infobars #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) { // TODO(finnur): Remove once infobars are no longer experimental (bug 39511). CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("infobars")) << message_; }
Allow the sim to run full speed
#include <sdf/sdf.hh> #include "gazebo/gazebo.hh" #include "gazebo/common/Plugin.hh" #include "gazebo/msgs/msgs.hh" #include "gazebo/physics/physics.hh" #include "gazebo/transport/transport.hh" #include <iostream> using namespace std; namespace gazebo { class SetupWorld : public WorldPlugin { public: void Load(physics::WorldPtr _parent, sdf::ElementPtr _sdf) { cout << "Setting up world..." << flush; // Create a new transport node transport::NodePtr node(new transport::Node()); // Initialize the node with the world name node->Init(_parent->GetName()); // Create a publisher on the ~/physics topic transport::PublisherPtr physicsPub = node->Advertise<msgs::Physics>("~/physics"); msgs::Physics physicsMsg; physicsMsg.set_type(msgs::Physics::ODE); // Set the step time physicsMsg.set_max_step_size(0.001); // Set the real time update rate physicsMsg.set_real_time_update_rate(1000.0); // Change gravity //msgs::Set(physicsMsg.mutable_gravity(), math::Vector3(0.01, 0, 0.1)); physicsPub->Publish(physicsMsg); cout << " done." << endl; } }; // Register this plugin with the simulator GZ_REGISTER_WORLD_PLUGIN(SetupWorld) }
#include <sdf/sdf.hh> #include "gazebo/gazebo.hh" #include "gazebo/common/Plugin.hh" #include "gazebo/msgs/msgs.hh" #include "gazebo/physics/physics.hh" #include "gazebo/transport/transport.hh" #include <iostream> using namespace std; namespace gazebo { class SetupWorld : public WorldPlugin { public: void Load(physics::WorldPtr _parent, sdf::ElementPtr _sdf) { cout << "Setting up world..." << flush; // Create a new transport node transport::NodePtr node(new transport::Node()); // Initialize the node with the world name node->Init(_parent->GetName()); // Create a publisher on the ~/physics topic transport::PublisherPtr physicsPub = node->Advertise<msgs::Physics>("~/physics"); msgs::Physics physicsMsg; physicsMsg.set_type(msgs::Physics::ODE); // Set the step time physicsMsg.set_max_step_size(0.001); // Set the real time update rate physicsMsg.set_real_time_update_rate(0); // Change gravity //msgs::Set(physicsMsg.mutable_gravity(), math::Vector3(0.01, 0, 0.1)); physicsPub->Publish(physicsMsg); cout << " done." << endl; } }; // Register this plugin with the simulator GZ_REGISTER_WORLD_PLUGIN(SetupWorld) }
Fix FS refactor build issue
/* * Copyright 2016 - 2018 gtalent2@gmail.com * * 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 <ox/fs/filesystem.hpp> #include <ox/std/std.hpp> #include "../media.hpp" namespace nostalgia { namespace core { uint8_t *loadRom(const char*) { return nullptr; } } }
/* * Copyright 2016 - 2018 gtalent2@gmail.com * * 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 <ox/fs/fs.hpp> #include <ox/std/std.hpp> #include "../media.hpp" namespace nostalgia { namespace core { uint8_t *loadRom(const char*) { return nullptr; } } }
Use the member functions begin and end.
// Petter Strandmark 2013. #include <map> #include <stdexcept> #include <vector> #include <spii/term_factory.h> using namespace std; namespace spii { class TermFactory::Implementation { public: map<string, TermCreator> creators; }; TermFactory::TermFactory() : impl(new TermFactory::Implementation) { } Term* TermFactory::create(const std::string& term_name, std::istream& in) const { auto creator = impl->creators.find(fix_name(term_name)); if (creator == impl->creators.end()) { std::string msg = "TermFactory::create: Unknown Term "; msg += term_name; throw runtime_error(msg.c_str()); } return creator->second(in); } void TermFactory::teach_term(const std::string& term_name, const TermCreator& creator) { impl->creators[fix_name(term_name)] = creator; } std::string TermFactory::fix_name(const std::string& org_name) { std::string name = org_name; std::replace(std::begin(name), std::end(name), ' ', '-'); return name; } }
// Petter Strandmark 2013. #include <map> #include <stdexcept> #include <vector> #include <spii/term_factory.h> using namespace std; namespace spii { class TermFactory::Implementation { public: map<string, TermCreator> creators; }; TermFactory::TermFactory() : impl(new TermFactory::Implementation) { } Term* TermFactory::create(const std::string& term_name, std::istream& in) const { auto creator = impl->creators.find(fix_name(term_name)); if (creator == impl->creators.end()) { std::string msg = "TermFactory::create: Unknown Term "; msg += term_name; throw runtime_error(msg.c_str()); } return creator->second(in); } void TermFactory::teach_term(const std::string& term_name, const TermCreator& creator) { impl->creators[fix_name(term_name)] = creator; } std::string TermFactory::fix_name(const std::string& org_name) { std::string name = org_name; std::replace(name.begin(), name.end(), ' ', '-'); return name; } }
Revert 64157 - Marking ExtensionApiTest.Infobars as FAILS until 10.5 issue is resolved. Reverting in order to create a proper CL for it. BUG=60990
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" #if defined(TOOLKIT_VIEWS) #define MAYBE_Infobars Infobars #elif defined(OS_MACOSX) // Temporarily marking as FAILS. See http://crbug.com/60990 for details. #define MAYBE_Infobars FAILS_Infobars #else // Need to finish port to Linux. See http://crbug.com/39916 for details. #define MAYBE_Infobars DISABLED_Infobars #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) { // TODO(finnur): Remove once infobars are no longer experimental (bug 39511). CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("infobars")) << message_; }
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" #if defined(TOOLKIT_VIEWS) || defined(OS_MACOSX) #define MAYBE_Infobars Infobars #else // Need to finish port to Linux. See http://crbug.com/39916 for details. #define MAYBE_Infobars DISABLED_Infobars #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) { // TODO(finnur): Remove once infobars are no longer experimental (bug 39511). CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("infobars")) << message_; }
Mark ExtensionApiTest.Storage as flaky. BUG=42943 TEST=none TBR=rafaelw
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Storage) { ASSERT_TRUE(RunExtensionTest("storage")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Cookies) { ASSERT_TRUE(RunExtensionTest("cookies")) << message_; }
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #if defined(OS_LINUX) // See http://crbug.com/42943. #define MAYBE_Storage FLAKY_Storage #else #define MAYBE_Storage Storage #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Storage) { ASSERT_TRUE(RunExtensionTest("storage")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Cookies) { ASSERT_TRUE(RunExtensionTest("cookies")) << message_; }
Fix an issue found by purify with my previous submission.
// 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 "config.h" #include "webkit/glue/resource_loader_bridge.h" #include "net/http/http_response_headers.h" namespace webkit_glue { ResourceLoaderBridge::ResponseInfo::ResponseInfo() { content_length = -1; #if defined(OS_WIN) response_data_file = base::kInvalidPlatformFileValue; #elif defined(OS_POSIX) response_data_file.fd = base::kInvalidPlatformFileValue; response_data_file.auto_close = false; #endif } ResourceLoaderBridge::ResponseInfo::~ResponseInfo() { } ResourceLoaderBridge::SyncLoadResponse::SyncLoadResponse() { } ResourceLoaderBridge::SyncLoadResponse::~SyncLoadResponse() { } ResourceLoaderBridge::ResourceLoaderBridge() { } ResourceLoaderBridge::~ResourceLoaderBridge() { } } // namespace webkit_glue
// 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 "config.h" #include "webkit/glue/resource_loader_bridge.h" #include "webkit/glue/webappcachecontext.h" #include "net/http/http_response_headers.h" namespace webkit_glue { ResourceLoaderBridge::ResponseInfo::ResponseInfo() { content_length = -1; app_cache_id = WebAppCacheContext::kNoAppCacheId; #if defined(OS_WIN) response_data_file = base::kInvalidPlatformFileValue; #elif defined(OS_POSIX) response_data_file.fd = base::kInvalidPlatformFileValue; response_data_file.auto_close = false; #endif } ResourceLoaderBridge::ResponseInfo::~ResponseInfo() { } ResourceLoaderBridge::SyncLoadResponse::SyncLoadResponse() { } ResourceLoaderBridge::SyncLoadResponse::~SyncLoadResponse() { } ResourceLoaderBridge::ResourceLoaderBridge() { } ResourceLoaderBridge::~ResourceLoaderBridge() { } } // namespace webkit_glue
Fix compiler error on OSX PPC: fix definition to match header.
#include "cvd/utility.h" namespace CVD { void differences(const float* a, const float* b, float* diff, unsigned int size) { differences<float, float>(a, b, diff, size); } void add_multiple_of_sum(const float* a, const float* b, const float& c, float* out, unsigned int count) { add_multiple_of_sum<float, float>(a, b, c, out, count); } void assign_multiple(const float* a, const float& c, float* out, unsigned int count) { assign_multiple<float, float, float>(a, c, out, count); } double inner_product(const float* a, const float* b, unsigned int count) { return inner_product<float>(a, b, count); } double sum_squared_differences(const float* a, const float* b, size_t count) { return SumSquaredDifferences<double, float,float>::sum_squared_differences(a,b,count); } void square(const float* in, float* out, size_t count) { square<float, float>(in, out, count); } void subtract_square(const float* in, float* out, size_t count) { subtract_square<float, float>(in, out, count); } }
#include "cvd/utility.h" namespace CVD { void differences(const float* a, const float* b, float* diff, unsigned int size) { differences<float, float>(a, b, diff, size); } void add_multiple_of_sum(const float* a, const float* b, const float& c, float* out, size_t count) { add_multiple_of_sum<float, float>(a, b, c, out, count); } void assign_multiple(const float* a, const float& c, float* out, unsigned int count) { assign_multiple<float, float, float>(a, c, out, count); } double inner_product(const float* a, const float* b, unsigned int count) { return inner_product<float>(a, b, count); } double sum_squared_differences(const float* a, const float* b, size_t count) { return SumSquaredDifferences<double, float,float>::sum_squared_differences(a,b,count); } void square(const float* in, float* out, size_t count) { square<float, float>(in, out, count); } void subtract_square(const float* in, float* out, size_t count) { subtract_square<float, float>(in, out, count); } }
Mark lines as NOLINT for clang-tidy
// Copyright (c) 2016-2017 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #include <clocale> #include <cstdio> #include "test.hpp" namespace tao { namespace TAOCPP_PEGTL_NAMESPACE { struct file_content : seq< TAOCPP_PEGTL_STRING( "dummy content" ), eol, discard > { }; struct file_grammar : seq< rep_min_max< 11, 11, file_content >, eof > { }; void unit_test() { const char* const filename = "src/test/pegtl/file_data.txt"; #if defined( _MSC_VER ) std::FILE* stream; ::fopen_s( &stream, filename, "rb" ); #else std::FILE* stream = std::fopen( filename, "rb" ); #endif TAOCPP_PEGTL_TEST_ASSERT( stream != nullptr ); TAOCPP_PEGTL_TEST_ASSERT( parse< file_grammar >( cstream_input<>( stream, 16, filename ) ) ); std::fclose( stream ); } } // namespace TAOCPP_PEGTL_NAMESPACE } // namespace tao #include "main.hpp"
// Copyright (c) 2016-2017 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #include <clocale> #include <cstdio> #include "test.hpp" namespace tao { namespace TAOCPP_PEGTL_NAMESPACE { struct file_content : seq< TAOCPP_PEGTL_STRING( "dummy content" ), eol, discard > { }; struct file_grammar : seq< rep_min_max< 11, 11, file_content >, eof > { }; void unit_test() { const char* const filename = "src/test/pegtl/file_data.txt"; #if defined( _MSC_VER ) std::FILE* stream; ::fopen_s( &stream, filename, "rb" ); // NOLINT #else std::FILE* stream = std::fopen( filename, "rb" ); // NOLINT #endif TAOCPP_PEGTL_TEST_ASSERT( stream != nullptr ); TAOCPP_PEGTL_TEST_ASSERT( parse< file_grammar >( cstream_input<>( stream, 16, filename ) ) ); std::fclose( stream ); } } // namespace TAOCPP_PEGTL_NAMESPACE } // namespace tao #include "main.hpp"
Refactor FormatStateMessage() to better match Core
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <util/validation.h> #include <consensus/validation.h> #include <tinyformat.h> /** Convert ValidationState to a human-readable message for logging */ std::string FormatStateMessage(const ValidationState &state) { return strprintf( "%s%s (code %i)", state.GetRejectReason(), state.GetDebugMessage().empty() ? "" : ", " + state.GetDebugMessage(), state.GetRejectCode()); } const std::string strMessageMagic = "Bitcoin Signed Message:\n";
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <util/validation.h> #include <consensus/validation.h> #include <tinyformat.h> std::string FormatStateMessage(const ValidationState &state) { if (state.IsValid()) { return "Valid"; } const std::string debug_message = state.GetDebugMessage(); if (!debug_message.empty()) { return strprintf("%s, %s (code %i)", state.GetRejectReason(), debug_message, state.GetRejectCode()); } return strprintf("%s (code %i)", state.GetRejectReason(), state.GetRejectCode()); } const std::string strMessageMagic = "Bitcoin Signed Message:\n";
Update function example for foo::i(ii), instead of foo::i:ii
#include <iostream> #include <qimessaging/signature.hpp> //sample foo function to take the signature from int foo(int a, int b) { return a + b + 42; } int main() { //wrapper arround signature, to create the signature of a function with it's name std::string signature; signature = qi::makeFunctionSignature("foo", &foo); std::cout << "function signature should be : foo::i:ii" << std::endl; std::cout << "function signature : " << signature << std::endl; std::cout << "Pretty printed function signature : " << qi::signatureToString(signature) << std::endl; return 0; }
#include <iostream> #include <qimessaging/signature.hpp> //sample foo function to take the signature from int foo(int a, int b) { return a + b + 42; } int main() { //wrapper arround signature, to create the signature of a function with it's name std::string signature; signature = qi::makeFunctionSignature("foo", &foo); std::cout << "function signature should be : foo::i(ii)" << std::endl; std::cout << "function signature : " << signature << std::endl; std::cout << "Pretty printed function signature : " << qi::signatureToString(signature) << std::endl; return 0; }
Fix test to specify an Itanium triple.
// RUN: %clang_cc1 -emit-llvm -x c++ -std=c++11 -verify %s -DN=1 // RUN: %clang_cc1 -emit-llvm -x c++ -std=c++11 -verify %s -DN=2 // RUN: %clang_cc1 -emit-llvm -x c++ -std=c++11 -verify %s -DN=3 struct A { int a; }; #if N == 1 // ChooseExpr template<class T> void test(int (&)[sizeof(__builtin_choose_expr(true, 1, 1), T())]) {} // expected-error {{cannot yet mangle}} template void test<int>(int (&)[sizeof(int)]); #elif N == 2 // CompoundLiteralExpr template<class T> void test(int (&)[sizeof((A){}, T())]) {} // expected-error {{cannot yet mangle}} template void test<int>(int (&)[sizeof(A)]); #elif N == 3 // DesignatedInitExpr template<class T> void test(int (&)[sizeof(A{.a = 10}, T())]) {} // expected-error {{cannot yet mangle}} template void test<int>(int (&)[sizeof(A)]); // FIXME: There are several more cases we can't yet mangle. #else #error unknown N #endif
// RUN: %clang_cc1 -emit-llvm -x c++ -std=c++11 -triple %itanium_abi_triple -verify %s -DN=1 // RUN: %clang_cc1 -emit-llvm -x c++ -std=c++11 -triple %itanium_abi_triple -verify %s -DN=2 // RUN: %clang_cc1 -emit-llvm -x c++ -std=c++11 -triple %itanium_abi_triple -verify %s -DN=3 struct A { int a; }; #if N == 1 // ChooseExpr template<class T> void test(int (&)[sizeof(__builtin_choose_expr(true, 1, 1), T())]) {} // expected-error {{cannot yet mangle}} template void test<int>(int (&)[sizeof(int)]); #elif N == 2 // CompoundLiteralExpr template<class T> void test(int (&)[sizeof((A){}, T())]) {} // expected-error {{cannot yet mangle}} template void test<int>(int (&)[sizeof(A)]); #elif N == 3 // DesignatedInitExpr template<class T> void test(int (&)[sizeof(A{.a = 10}, T())]) {} // expected-error {{cannot yet mangle}} template void test<int>(int (&)[sizeof(A)]); // FIXME: There are several more cases we can't yet mangle. #else #error unknown N #endif
Make the device check for the presence of the NotificationClient In case it's not present, raise the event of change of default
#include "stdafx.h" #include "AudioDeviceWrapper.h" #include "DefSoundException.h" using namespace System; bool AudioEndPointControllerWrapper::AudioDeviceWrapper::Equals(Object ^ o) { if (o == (Object^)nullptr) return false; if(o->GetType() != this->GetType()) { return false; } AudioDeviceWrapper^ that = static_cast<AudioDeviceWrapper^>(o); return that->Id == Id; } int AudioEndPointControllerWrapper::AudioDeviceWrapper::GetHashCode() { return this->Id->GetHashCode(); } void AudioEndPointControllerWrapper::AudioDeviceWrapper::SetAsDefault(Role role) { try { _audioDevice->SetDefault(static_cast<::ERole>(role)); } catch (DefSound::CNotActiveError error) { throw gcnew DefSoundNotActiveException(error); } catch(DefSound::CError error) { throw gcnew DefSoundException(error); } } bool AudioEndPointControllerWrapper::AudioDeviceWrapper::IsDefault(Role role) { try { return _audioDevice->IsDefault(static_cast<::ERole>(role)); } catch (DefSound::CNotActiveError error) { throw gcnew DefSoundNotActiveException(error); } catch (DefSound::CError error) { throw gcnew DefSoundException(error); } }
#include "stdafx.h" #include "AudioDeviceWrapper.h" #include "Audio.EndPoint.Controller.Wrapper.h" #include "DefSoundException.h" using namespace System; namespace AudioEndPointControllerWrapper { bool AudioDeviceWrapper::Equals(Object ^ o) { if (o == (Object^)nullptr) return false; if (o->GetType() != this->GetType()) { return false; } AudioDeviceWrapper^ that = static_cast<AudioDeviceWrapper^>(o); return that->Id == Id; } int AudioDeviceWrapper::GetHashCode() { return this->Id->GetHashCode(); } void AudioDeviceWrapper::SetAsDefault(Role role) { try { _audioDevice->SetDefault(static_cast<::ERole>(role)); if (!AudioController::IsNotificationAvailable()) { AudioController::RaiseDefault(gcnew DeviceDefaultChangedEvent(this, role)); } } catch (DefSound::CNotActiveError error) { throw gcnew DefSoundNotActiveException(error); } catch (DefSound::CError error) { throw gcnew DefSoundException(error); } } bool AudioDeviceWrapper::IsDefault(Role role) { try { return _audioDevice->IsDefault(static_cast<::ERole>(role)); } catch (DefSound::CNotActiveError error) { throw gcnew DefSoundNotActiveException(error); } catch (DefSound::CError error) { throw gcnew DefSoundException(error); } } }
Clarify lpBuffer layout in GetUserName unit test
#include <string> #include <vector> #include <unistd.h> #include <gtest/gtest.h> #include <scxcorelib/scxstrencodingconv.h> #include "getusername.h" using std::string; using std::vector; using SCXCoreLib::Utf16leToUtf8; TEST(GetUserName,simple) { // allocate a WCHAR_T buffer to receive username DWORD lpnSize = 64; WCHAR_T lpBuffer[lpnSize]; BOOL result = GetUserName(lpBuffer, &lpnSize); // GetUserName returns 1 on success ASSERT_EQ(1, result); // get expected username string username = string(getlogin()); // GetUserName sets lpnSize to length of username including null ASSERT_EQ(username.size()+1, lpnSize); // copy UTF-16 bytes from lpBuffer to vector for conversion vector<unsigned char> input(reinterpret_cast<unsigned char *>(&lpBuffer[0]), reinterpret_cast<unsigned char *>(&lpBuffer[lpnSize-1])); // convert to UTF-8 for assertion string output; Utf16leToUtf8(input, output); EXPECT_EQ(username, output); }
#include <string> #include <vector> #include <unistd.h> #include <gtest/gtest.h> #include <scxcorelib/scxstrencodingconv.h> #include "getusername.h" using std::string; using std::vector; using SCXCoreLib::Utf16leToUtf8; TEST(GetUserName,simple) { // allocate a WCHAR_T buffer to receive username DWORD lpnSize = 64; WCHAR_T lpBuffer[lpnSize]; BOOL result = GetUserName(lpBuffer, &lpnSize); // GetUserName returns 1 on success ASSERT_EQ(1, result); // get expected username string username = string(getlogin()); // GetUserName sets lpnSize to length of username including null ASSERT_EQ(username.size()+1, lpnSize); // copy UTF-16 bytes (excluding null) from lpBuffer to vector for conversion unsigned char *begin = reinterpret_cast<unsigned char *>(&lpBuffer[0]); // -1 to skip null; *2 because UTF-16 encodes two bytes per character unsigned char *end = begin + (lpnSize-1)*2; vector<unsigned char> input(begin, end); // convert to UTF-8 for assertion string output; Utf16leToUtf8(input, output); EXPECT_EQ(username, output); }
Make sample push receiver actually compile
#include <iostream> #include <string> #include "ace/INET_Addr.h" #include "ace/SOCK_Connector.h" #include "ace/SOCK_Stream.h" #include "ace/SOCK_Acceptor.h" #include "ace/Acceptor.h" #include "ace/Reactor.h" #include "AndroidServiceHandler.h" using namespace std; int main(int argc, char **argv) { cout << "Creating acceptor..." << endl; //TODO: make interface and port number specifiable on the command line ACE_INET_Addr serverAddress(32869, "0.0.0.0"); cout << "Listening on port " << serverAddress.get_port_number() << " on interface " << serverAddress.get_host_addr() << endl; //Creates and opens the socket acceptor; registers with the singleton ACE_Reactor //for accept events ACE_Acceptor<AndroidServiceHandler, ACE_SOCK_Acceptor> acceptor(serverAddress); //Get the process-wide ACE_Reactor (the one the acceptor should have registered with) ACE_Reactor *reactor = ACE_Reactor::instance(); cout << "Starting event loop..." << endl << flush; reactor->run_reactor_event_loop(); }
#include <iostream> #include <string> #include "ace/Reactor.h" #include "GatewayConnector/GatewayConnector.h" using namespace std; int main(int argc, char **argv) { cout << "Creating gateway connector..." << endl << flush; GatewayConnector *gatewayConnector = new GatewayConnector(NULL); //Get the process-wide ACE_Reactor (the one the acceptor should have registered with) ACE_Reactor *reactor = ACE_Reactor::instance(); cout << "Starting event loop..." << endl << flush; reactor->run_reactor_event_loop(); }
Fix missing parts of query. Still does not compile
// tagged_sqlite.cpp : Defines the entry point for the application. // #include "tagged_sqlite.h" using namespace std; int main() { using db = define_database< class mydb, define_table<class customers, define_column<class id, std::int64_t>, define_column<class name, std::string>>, define_table<class orders, define_column<class id, std::int64_t>, define_column<class item, std::string>, define_column<class customerid, std::int64_t>, define_column<class price, double>>>; auto query = query_builder<db>() .select(column<customisers. id>, column<customers, customerid>, column<orders, id>.as<class orderid>()) .from(table<customers>, table<orders>) .join() .where(column <) cout << to_statement(ss) << endl; auto e = column<class Test> == constant(5) || column<class A> * constant(5) <= parameter<class P1, std::int64_t>(); cout << expression_to_string(e) << std::endl; cout << "\n" << simple_type_name::long_name< detail::column_type<db, item>::value_type> << "\n"; return 0; }
// tagged_sqlite.cpp : Defines the entry point for the application. // #include "tagged_sqlite.h" using namespace std; int main() { using db = define_database< define_table<class customers, // define_column<class id, std::int64_t>, define_column<class name, std::string>>, define_table<class orders, // define_column<class id, std::int64_t>, define_column<class item, std::string>, define_column<class customerid, std::int64_t>, define_column<class price, double>>>; auto query = query_builder<db>() .select(column<customers, id>, column<orders, customerid>, column<name>, column<orders, id>.as<class orderid>(), column<price>) .from(table<customers>, table<orders>) .join(column<orderid> == column<customerid>) .where(column<price> > parameter<class price_parameter, double>) .build(); for (auto& row : execute_query(query, parameter<price_parameter>(100.0))) { std::cout << row.get<customers, id>(); std::cout << row.get<name>(); } cout << to_statement(ss) << endl; auto e = column<class Test> == constant(5) || column<class A> * constant(5) <= parameter<class P1, std::int64_t>(); cout << expression_to_string(e) << std::endl; cout << "\n" << simple_type_name::long_name< detail::column_type<db, item>::value_type> << "\n"; return 0; }
Update bug reference link in ExtensionApiTest.Toolstrip
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" // Disabled, http://crbug.com/30151. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Toolstrip) { ASSERT_TRUE(RunExtensionTest("toolstrip")) << message_; }
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" // Disabled, http://crbug.com/30151 (Linux and ChromeOS), // http://crbug.com/35034 (others). IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Toolstrip) { ASSERT_TRUE(RunExtensionTest("toolstrip")) << message_; }
Fix bug: paths have a leading slash.
#include "http_server/parse_path.hpp" #include <boost/lexical_cast.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/algorithm/string/classification.hpp> namespace http { namespace server3 { bool parse_path(const std::string &path, int &z, int &x, int &y) { std::vector<std::string> splits; boost::algorithm::split(splits, path, boost::algorithm::is_any_of("/.")); if (splits.size() != 4) { return false; } if (splits[3] != "pbf") { return false; } try { z = boost::lexical_cast<int>(splits[0]); x = boost::lexical_cast<int>(splits[1]); y = boost::lexical_cast<int>(splits[2]); return true; } catch (...) { return false; } } } }
#include "http_server/parse_path.hpp" #include <boost/lexical_cast.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/algorithm/string/classification.hpp> namespace http { namespace server3 { bool parse_path(const std::string &path, int &z, int &x, int &y) { std::vector<std::string> splits; boost::algorithm::split(splits, path, boost::algorithm::is_any_of("/.")); // we're expecting a leading /, then 3 numbers separated by /, // then ".pbf" at the end. if (splits.size() != 5) { return false; } if (splits[0] != "") { return false; } if (splits[4] != "pbf") { return false; } try { z = boost::lexical_cast<int>(splits[1]); x = boost::lexical_cast<int>(splits[2]); y = boost::lexical_cast<int>(splits[3]); return true; } catch (...) { return false; } } } }
Add missing license in LUA unittest
#include <iostream> #include "pinocchio/multibody/model.hpp" #include "pinocchio/multibody/parser/lua.hpp" #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE UrdfTest #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE ( ParsingLuaFile ) BOOST_AUTO_TEST_CASE ( buildModel ) { std::string filename = PINOCCHIO_SOURCE_DIR"/models/simple_model.lua"; #ifndef NDEBUG std::cout << "Parse filename \"" << filename << "\"" << std::endl; #endif se3::Model model = se3::lua::buildModel(filename, true, true); } BOOST_AUTO_TEST_SUITE_END()
// // Copyright (c) 2015 CNRS // // This file is part of Pinocchio // Pinocchio is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // Pinocchio 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // Pinocchio If not, see // <http://www.gnu.org/licenses/>. #include <iostream> #include "pinocchio/multibody/model.hpp" #include "pinocchio/multibody/parser/lua.hpp" #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE LuaTest #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE ( ParsingLuaFile ) BOOST_AUTO_TEST_CASE ( buildModel ) { std::string filename = PINOCCHIO_SOURCE_DIR"/models/simple_model.lua"; #ifndef NDEBUG std::cout << "Parse filename \"" << filename << "\"" << std::endl; #endif se3::Model model = se3::lua::buildModel(filename, true, true); } BOOST_AUTO_TEST_SUITE_END()
Disable error dialog on Windows
#define CATCH_CONFIG_MAIN #include <catch.hpp> /* * Catch main file for faster compilation. This file is the only one defining the * main function. */
#define CATCH_CONFIG_RUNNER #include "catch.hpp" // On Windows, disable the "Application error" dialog box, because it // requires an human intervention, and there is no one on Appveyor. // // On UNIX, does nothing void silent_crash_handlers(); int main(int argc, char* argv[]) { silent_crash_handlers(); return Catch::Session().run(argc, argv); } #if (defined(WIN32) || defined(WIN64)) #include <windows.h> void silent_crash_handlers() { SetErrorMode(GetErrorMode() | SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX); } #else void silent_crash_handlers() {} #endif
Fix invalid write in RenderViewHostObserver.
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/renderer_host/render_view_host_observer.h" #include "content/browser/renderer_host/render_view_host.h" RenderViewHostObserver::RenderViewHostObserver(RenderViewHost* render_view_host) : render_view_host_(render_view_host), routing_id_(render_view_host->routing_id()) { render_view_host_->AddObserver(this); } RenderViewHostObserver::~RenderViewHostObserver() { if (render_view_host_) render_view_host_->RemoveObserver(this); } void RenderViewHostObserver::RenderViewHostDestroyed() { delete this; } bool RenderViewHostObserver::OnMessageReceived(const IPC::Message& message) { return false; } bool RenderViewHostObserver::Send(IPC::Message* message) { if (!render_view_host_) { delete message; return false; } return render_view_host_->Send(message); } void RenderViewHostObserver::RenderViewHostDestruction() { render_view_host_->RemoveObserver(this); RenderViewHostDestroyed(); render_view_host_ = NULL; }
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/renderer_host/render_view_host_observer.h" #include "content/browser/renderer_host/render_view_host.h" RenderViewHostObserver::RenderViewHostObserver(RenderViewHost* render_view_host) : render_view_host_(render_view_host), routing_id_(render_view_host->routing_id()) { render_view_host_->AddObserver(this); } RenderViewHostObserver::~RenderViewHostObserver() { if (render_view_host_) render_view_host_->RemoveObserver(this); } void RenderViewHostObserver::RenderViewHostDestroyed() { delete this; } bool RenderViewHostObserver::OnMessageReceived(const IPC::Message& message) { return false; } bool RenderViewHostObserver::Send(IPC::Message* message) { if (!render_view_host_) { delete message; return false; } return render_view_host_->Send(message); } void RenderViewHostObserver::RenderViewHostDestruction() { render_view_host_->RemoveObserver(this); render_view_host_ = NULL; RenderViewHostDestroyed(); }
Drop all GIT_* variables in tests
#define CATCH_CONFIG_RUNNER #include "Catch/catch.hpp" #include <memory> #include "decoration.hpp" #include "printing.hpp" #include "TestUtils.hpp" int main(int argc, const char *argv[]) { PrintingSettings::set(std::make_shared<TestSettings>()); decor::disableDecorations(); // Remove destination directory if it exists to account for crashes. TempDirCopy tempDirCopy("tests/test-repo/_git", "tests/test-repo/.git", true); return Catch::Session().run(argc, argv); }
#define CATCH_CONFIG_RUNNER #include "Catch/catch.hpp" #include <boost/algorithm/string/predicate.hpp> #include <cstdlib> #include <cstring> #include <memory> #include "decoration.hpp" #include "printing.hpp" #include "TestUtils.hpp" int main(int argc, const char *argv[]) { // Drop all `GIT_*` environment variables as they might interfere with // running some tests. extern char **environ; for (char **e = environ; *e != NULL; ++e) { if (boost::starts_with(*e, "GIT_")) { unsetenv(std::string(*e, std::strchr(*e, '=')).c_str()); } } PrintingSettings::set(std::make_shared<TestSettings>()); decor::disableDecorations(); // Remove destination directory if it exists to account for crashes. TempDirCopy tempDirCopy("tests/test-repo/_git", "tests/test-repo/.git", true); return Catch::Session().run(argc, argv); }
Make some small changes on the code without changing its semantics
#include "../src/Sphere.h" #include "../src/Plane.h" void World::build() { vp.set_hres(200); vp.set_vres(200); vp.set_pixel_size(1.0); tracerPtr = new MultipleObjects(this); backgroundColor = RGBColor(0.0f, 0.0f, 0.0f); Sphere* sphere_ptr = new Sphere; sphere_ptr->setCenter(glm::vec3(0.0f, -25.0f, 0.0f)); sphere_ptr->setRadius(80); sphere_ptr->setColor(1, 0, 0); addObject(sphere_ptr); sphere_ptr = new Sphere(glm::vec3(0.0f, 30.0f, 0.0f), 60.0f); sphere_ptr->setColor(1, 1, 0); addObject(sphere_ptr); Plane* plane_ptr = new Plane(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 1.0f)); plane_ptr->setColor(0.0, 0.3, 0.0); addObject(plane_ptr); }
#include "../src/Sphere.h" #include "../src/Plane.h" #include <iostream> using namespace std; void World::build() { vp.set_hres(200); vp.set_vres(200); vp.set_pixel_size(1.0); tracerPtr = new MultipleObjects(this); backgroundColor = RGBColor(0.0f, 0.0f, 0.0f); Sphere* sphere_ptr = new Sphere; sphere_ptr->setCenter(glm::vec3(0.0f, -25.0f, 0.0f)); sphere_ptr->setRadius(80); sphere_ptr->setColor(1, 0, 0); addObject(sphere_ptr); sphere_ptr = new Sphere; sphere_ptr->setCenter(glm::vec3(0.0f, 30.0f, 0.0f)); sphere_ptr->setRadius(60); sphere_ptr->setColor(1, 1, 0); addObject(sphere_ptr); Plane* plane_ptr = new Plane(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 1.0f)); plane_ptr->setColor(0.0, 0.3, 0.0); addObject(plane_ptr); }
Update bug reference link in ExtensionApiTest.Toolstrip
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" // Disabled, http://crbug.com/30151. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Toolstrip) { ASSERT_TRUE(RunExtensionTest("toolstrip")) << message_; }
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" // Disabled, http://crbug.com/30151 (Linux and ChromeOS), // http://crbug.com/35034 (others). IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Toolstrip) { ASSERT_TRUE(RunExtensionTest("toolstrip")) << message_; }
Add option -f (file name only)
#include "qmimedatabase.h" #include <QtCore/QCoreApplication> #include <QtCore/QFile> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); if (argc <= 1) { printf( "No filename specified\n" ); return 1; } QString option; int fnPos = 1; if (argc > 2) { option = QString::fromLatin1(argv[1]); ++fnPos; } const QString fileName = QFile::decodeName(argv[fnPos]); //int accuracy; QMimeDatabase db; QMimeType mime; if (fileName == QLatin1String("-")) { QFile qstdin; qstdin.open(stdin, QIODevice::ReadOnly); const QByteArray data = qstdin.readAll(); //mime = QMimeType::findByContent(data, &accuracy); mime = db.findByData(data); } else if (option == "-c") { QFile file(fileName); if (file.open(QIODevice::ReadOnly)) { mime = db.findByData(file.read(32000)); } } else { //mime = QMimeType::findByPath(fileName, 0, args->isSet("f"), &accuracy); mime = db.findByFile(fileName); } if ( mime.isValid() /*&& !mime.isDefault()*/ ) { printf("%s\n", mime.name().toLatin1().constData()); //printf("(accuracy %d)\n", accuracy); } else { return 1; // error } return 0; }
#include "qmimedatabase.h" #include <QtCore/QCoreApplication> #include <QtCore/QFile> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); if (argc <= 1) { printf( "No filename specified\n" ); return 1; } QString option; int fnPos = 1; if (argc > 2) { option = QString::fromLatin1(argv[1]); ++fnPos; } const QString fileName = QFile::decodeName(argv[fnPos]); //int accuracy; QMimeDatabase db; QMimeType mime; if (fileName == QLatin1String("-")) { QFile qstdin; qstdin.open(stdin, QIODevice::ReadOnly); const QByteArray data = qstdin.readAll(); //mime = QMimeType::findByContent(data, &accuracy); mime = db.findByData(data); } else if (option == "-c") { QFile file(fileName); if (file.open(QIODevice::ReadOnly)) { mime = db.findByData(file.read(32000)); } } else if (option == "-f") { mime = db.findByName(fileName); } else { mime = db.findByFile(fileName); } if ( mime.isValid() /*&& !mime.isDefault()*/ ) { printf("%s\n", mime.name().toLatin1().constData()); //printf("(accuracy %d)\n", accuracy); } else { return 1; // error } return 0; }
Fix a couple of bugs in linear_congruential_engine::seed. Regression test added.
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // <random> // template <class UIntType, UIntType a, UIntType c, UIntType m> // class linear_congruential_engine; // template<class Sseq> void seed(Sseq& q); #include <random> #include <cassert> int main() { { unsigned a[] = {3, 5, 7}; std::seed_seq sseq(a, a+3); std::linear_congruential_engine<unsigned, 5, 7, 11> e1; std::linear_congruential_engine<unsigned, 5, 7, 11> e2(4); assert(e1 != e2); e1.seed(sseq); assert(e1 == e2); } }
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // <random> // template <class UIntType, UIntType a, UIntType c, UIntType m> // class linear_congruential_engine; // template<class Sseq> void seed(Sseq& q); #include <random> #include <cassert> int main() { { unsigned a[] = {3, 5, 7}; std::seed_seq sseq(a, a+3); std::linear_congruential_engine<unsigned, 5, 7, 11> e1; std::linear_congruential_engine<unsigned, 5, 7, 11> e2(4); assert(e1 != e2); e1.seed(sseq); assert(e1 == e2); } { unsigned a[] = {3, 5, 7, 9, 11}; std::seed_seq sseq(a, a+5); typedef std::linear_congruential_engine<unsigned long long, 1, 1, 0x200000001ULL> E; E e1(4309005589); E e2(sseq); assert(e1 == e2); } }
Make initializer list compatible with older GCC
#include "types.h" #include <cassert> namespace nadam { MessageInfo::MessageInfo(std::string name, uint32_t size, bool isVariableSize) : name{name}, size{size}, isVariableSize{isVariableSize}, hash{constructHash(name, size, isVariableSize)} { assert(name.length()); } util::sha1::hash MessageInfo::constructHash(const std::string& name, uint32_t size, bool isVariableSize) { util::sha1::Digest sha; sha.put(name.data(), static_cast<uint32_t>(name.size())); sha.put(isVariableSize); for (size_t i = 0; i < sizeof(size); ++i) { size_t byteNumber = sizeof(size) - 1 - i; sha.put(size >> 8 * byteNumber & 0xff); } return sha.finish(); } } // namespace nadam
#include "types.h" #include <cassert> namespace nadam { MessageInfo::MessageInfo(std::string name, uint32_t size, bool isVariableSize) : name(name), size(size), isVariableSize(isVariableSize), hash(constructHash(name, size, isVariableSize)) { assert(name.length()); } util::sha1::hash MessageInfo::constructHash(const std::string& name, uint32_t size, bool isVariableSize) { util::sha1::Digest sha; sha.put(name.data(), static_cast<uint32_t>(name.size())); sha.put(isVariableSize); for (size_t i = 0; i < sizeof(size); ++i) { size_t byteNumber = sizeof(size) - 1 - i; sha.put(size >> 8 * byteNumber & 0xff); } return sha.finish(); } } // namespace nadam
Fix in Remote command name parsing
#include <iostream> #include "Shell.h" #include "RemoteCommand.h" namespace RhIO { RemoteCommand::RemoteCommand(std::string fullName_, std::string desc_) : fullName(fullName_), desc(desc_), origin(""), name("") { auto found = fullName.find_last_of("/"); if (found > 0) { origin = fullName.substr(0, found); name = fullName.substr(found+1); } else { name = fullName; } } std::string RemoteCommand::getName() { return name; } std::string RemoteCommand::getDesc() { return desc; } std::string RemoteCommand::getOrigin() { return origin; } void RemoteCommand::process(std::vector<std::string> args) { auto response = shell->getClient()->call(fullName, args); std::cout << response; if (response.size() && response[response.size()-1]!='\n') { std::cout << std::endl; } } }
#include <iostream> #include "Shell.h" #include "RemoteCommand.h" namespace RhIO { RemoteCommand::RemoteCommand(std::string fullName_, std::string desc_) : fullName(fullName_), desc(desc_), origin(""), name("") { auto found = fullName.find_last_of("/"); if (found != std::string::npos) { origin = fullName.substr(0, found); name = fullName.substr(found+1); } else { name = fullName; } } std::string RemoteCommand::getName() { return name; } std::string RemoteCommand::getDesc() { return desc; } std::string RemoteCommand::getOrigin() { return origin; } void RemoteCommand::process(std::vector<std::string> args) { auto response = shell->getClient()->call(fullName, args); std::cout << response; if (response.size() && response[response.size()-1]!='\n') { std::cout << std::endl; } } }
Print a queue-specific debug message when dropping CAN messages.
#include "listener.h" #include "log.h" #include "buffers.h" void conditionalEnqueue(QUEUE_TYPE(uint8_t)* queue, uint8_t* message, int messageSize) { if(queue_available(queue) < messageSize + 2) { debug("Dropped incoming CAN message -- send queue (at %p) full\r\n", queue); return; } for(int i = 0; i < messageSize; i++) { QUEUE_PUSH(uint8_t, queue, (uint8_t)message[i]); } QUEUE_PUSH(uint8_t, queue, (uint8_t)'\r'); QUEUE_PUSH(uint8_t, queue, (uint8_t)'\n'); } void sendMessage(Listener* listener, uint8_t* message, int messageSize) { conditionalEnqueue(&listener->usb->sendQueue, message, messageSize); conditionalEnqueue(&listener->serial->sendQueue, message, messageSize); } void processListenerQueues(Listener* listener) { // Must always process USB, because this function usually runs the MCU's USB // task that handles SETUP and enumeration. processInputQueue(listener->usb); processInputQueue(listener->serial); }
#include "listener.h" #include "log.h" #include "buffers.h" bool conditionalEnqueue(QUEUE_TYPE(uint8_t)* queue, uint8_t* message, int messageSize) { if(queue_available(queue) < messageSize + 2) { return false; } for(int i = 0; i < messageSize; i++) { QUEUE_PUSH(uint8_t, queue, (uint8_t)message[i]); } QUEUE_PUSH(uint8_t, queue, (uint8_t)'\r'); QUEUE_PUSH(uint8_t, queue, (uint8_t)'\n'); return true; } void sendMessage(Listener* listener, uint8_t* message, int messageSize) { if(!conditionalEnqueue(&listener->usb->sendQueue, message, messageSize)) { debug("USB send queue full, dropping CAN message: %s\r\n", message); } if(!conditionalEnqueue(&listener->serial->sendQueue, message, messageSize)) { debug("UART send queue full, dropping CAN message: %s\r\n", message); } } void processListenerQueues(Listener* listener) { // Must always process USB, because this function usually runs the MCU's USB // task that handles SETUP and enumeration. processInputQueue(listener->usb); processInputQueue(listener->serial); }
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; }
Disable Vulkan native MSAA by default for now.
/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2016 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include "xenia/gpu/vulkan/vulkan_gpu_flags.h" DEFINE_bool(vulkan_renderdoc_capture_all, false, "Capture everything with RenderDoc."); DEFINE_bool(vulkan_native_msaa, true, "Use native MSAA"); DEFINE_bool(vulkan_dump_disasm, false, "Dump shader disassembly. NVIDIA only supported.");
/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2016 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include "xenia/gpu/vulkan/vulkan_gpu_flags.h" DEFINE_bool(vulkan_renderdoc_capture_all, false, "Capture everything with RenderDoc."); DEFINE_bool(vulkan_native_msaa, false, "Use native MSAA"); DEFINE_bool(vulkan_dump_disasm, false, "Dump shader disassembly. NVIDIA only supported.");
Make sure Travis detects failing test
#include <gtest/gtest.h> TEST(MathTest, TwoPlusTwoEqualsFour) { EXPECT_EQ(2 + 2, 4); } int main(int argc, char **argv) { ::testing::InitGoogleTest( &argc, argv ); return RUN_ALL_TESTS(); }
#include <gtest/gtest.h> TEST(MathTest, TwoPlusTwoEqualsFour) { EXPECT_EQ(2 + 2, 5); } int main(int argc, char **argv) { ::testing::InitGoogleTest( &argc, argv ); return RUN_ALL_TESTS(); }
Use more useful ancestor constructor
#include "Sprite.h" Sprite::Sprite() : Node() { // Image m_sprite_path = ""; } Sprite::Sprite(std::string p_sprite_path) : Sprite() { m_sprite_path = p_sprite_path; } Sprite::~Sprite() {} std::string Sprite::getSpritePath() { return m_sprite_path; }
#include "Sprite.h" Sprite::Sprite() : Node() { // Image m_sprite_path = ""; } Sprite::Sprite(std::string p_sprite_path) : Node() { // Image m_sprite_path = p_sprite_path; } Sprite::~Sprite() {} std::string Sprite::getSpritePath() { return m_sprite_path; }
Comment out a very annoying NOTIMPLEMENTED().
// 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/renderer/renderer_logging.h" #include "base/logging.h" #include "googleurl/src/gurl.h" namespace renderer_logging { // Sets the URL that is logged if the renderer crashes. Use GURL() to clear // the URL. void SetActiveRendererURL(const GURL& url) { // TODO(port): Once breakpad is integrated we can turn this on. NOTIMPLEMENTED(); } } // namespace renderer_logging
// 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/renderer/renderer_logging.h" #include "base/logging.h" #include "googleurl/src/gurl.h" namespace renderer_logging { // Sets the URL that is logged if the renderer crashes. Use GURL() to clear // the URL. void SetActiveRendererURL(const GURL& url) { // crbug.com/9646 } } // namespace renderer_logging
Make snippet run successfully again: the snippet for 'eval' was taking m=m.transpose() as an example of code that needs an explicit call to eval(), but that doesn't work anymore now that we have the clever assert detecting aliasing issues.
Matrix2f M = Matrix2f::Random(); Matrix2f m; m = M; cout << "Here is the matrix m:" << endl << m << endl; cout << "Now we want to replace m by its own transpose." << endl; cout << "If we do m = m.transpose(), then m becomes:" << endl; m = m.transpose() * 1; cout << m << endl << "which is wrong!" << endl; cout << "Now let us instead do m = m.transpose().eval(). Then m becomes" << endl; m = M; m = m.transpose().eval(); cout << m << endl << "which is right." << endl;
Matrix2f M = Matrix2f::Random(); Matrix2f m; m = M; cout << "Here is the matrix m:" << endl << m << endl; cout << "Now we want to copy a column into a row." << endl; cout << "If we do m.col(1) = m.row(0), then m becomes:" << endl; m.col(1) = m.row(0); cout << m << endl << "which is wrong!" << endl; cout << "Now let us instead do m.col(1) = m.row(0).eval(). Then m becomes" << endl; m = M; m.col(1) = m.row(0).eval(); cout << m << endl << "which is right." << endl;
Disable database connection for now.
#include <iostream> #include <sqlpp11/postgresql/postgresql.h> #include <sqlpp11/postgresql/insert.h> //#include <sqlpp11/sqlpp11.h> #include "Sample.h" int Returning(int argc, char **argv) { // Configuration auto config = std::make_shared<sqlpp::postgresql::connection_config>(); // DB connection sqlpp::postgresql::connection db(config); // Model test::TabBar t_bar; auto ins_news = insert_into(t_bar) .set(t_bar.gamma = true, t_bar.beta = "test") .returning(t_bar.beta); return 0; }
#include <iostream> #include <sqlpp11/postgresql/postgresql.h> #include <sqlpp11/postgresql/insert.h> //#include <sqlpp11/sqlpp11.h> #include "Sample.h" int Returning(int argc, char **argv) { // Configuration //auto config = std::make_shared<sqlpp::postgresql::connection_config>(); // DB connection //sqlpp::postgresql::connection db(config); // Model test::TabBar t_bar; auto ins_news = insert_into(t_bar) .set(t_bar.gamma = true, t_bar.beta = "test") .returning(t_bar.beta); return 0; }
Fix an initialization order issue in the copy ctor to avoid the warning
#include "perceptioninfoprivate.h" #include "btperceptioninfoscriptable.h" using namespace GluonEngine; PerceptionInfoPrivate::PerceptionInfoPrivate(QObject * parent) : QSharedData() { info = new btPerceptionInfoScriptable(parent); QScriptValue extensionObject = engine.globalObject(); script = 0; } PerceptionInfoPrivate::PerceptionInfoPrivate(const PerceptionInfoPrivate& other) : QSharedData() , info(other.info) , updateFunc(other.updateFunc) , drawFunc(other.drawFunc) , getAdjustedValueFunc(other.getAdjustedValueFunc) , script(other.script) { QScriptValue extensionObject = engine.globalObject(); } PerceptionInfoPrivate::~PerceptionInfoPrivate() { }
#include "perceptioninfoprivate.h" #include "btperceptioninfoscriptable.h" using namespace GluonEngine; PerceptionInfoPrivate::PerceptionInfoPrivate(QObject * parent) : QSharedData() { info = new btPerceptionInfoScriptable(parent); QScriptValue extensionObject = engine.globalObject(); script = 0; } PerceptionInfoPrivate::PerceptionInfoPrivate(const PerceptionInfoPrivate& other) : QSharedData() , info(other.info) , drawFunc(other.drawFunc) , updateFunc(other.updateFunc) , getAdjustedValueFunc(other.getAdjustedValueFunc) , script(other.script) { QScriptValue extensionObject = engine.globalObject(); } PerceptionInfoPrivate::~PerceptionInfoPrivate() { }
Add orientation update in SimpleGameWorld::Update.
#include "simplegameworld.h" void SimpleGameWorld::addEntity(shared_ptr< gamefw::Entity > entity) { m_entity_list.push_back(entity); } void SimpleGameWorld::update() { foreach(shared_ptr<gamefw::Entity> entity, m_entity_list) { entity->m_position.x += entity->m_velocity_local.x * glm::cos(glm::radians(entity->m_orientation.x)) + -entity->m_velocity_local.z * glm::sin(glm::radians(entity->m_orientation.x)); entity->m_position.z += entity->m_velocity_local.x * glm::sin(glm::radians(entity->m_orientation.x)) + entity->m_velocity_local.z * glm::cos(glm::radians(entity->m_orientation.x)); entity->m_position.y += entity->m_velocity_local.y; } }
#include "simplegameworld.h" void SimpleGameWorld::addEntity(shared_ptr< gamefw::Entity > entity) { m_entity_list.push_back(entity); } void SimpleGameWorld::update() { foreach(shared_ptr<gamefw::Entity> entity, m_entity_list) { entity->m_position.x += entity->m_velocity_local.x * glm::cos(glm::radians(entity->m_orientation.x)) + -entity->m_velocity_local.z * glm::sin(glm::radians(entity->m_orientation.x)); entity->m_position.z += entity->m_velocity_local.x * glm::sin(glm::radians(entity->m_orientation.x)) + entity->m_velocity_local.z * glm::cos(glm::radians(entity->m_orientation.x)); entity->m_position.y += entity->m_velocity_local.y; entity->m_orientation += entity->m_angular_velocity; } }
Fix reading from archived file in example
#include "util/file_piece.hh" #include "util/file.hh" #include "util/scoped.hh" #include "util/string_piece.hh" #include "util/tokenize_piece.hh" #include "util/murmur_hash.hh" #include "util/probing_hash_table.hh" #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fstream> #include <iostream> #include <boost/scoped_array.hpp> #include <boost/functional/hash.hpp> int main() { std::fstream backing("../source.uniq.rand.gz", std::ios::in); util::FilePiece test(backing, NULL, 1); //An example of how not to read a file (try/catch), will change later, but for now, hacking while(true){ try { StringPiece line = test.ReadLine(); std::cout << line << std::endl; } catch (util::EndOfFileException e){ std::cout << "End of file" << std::endl; break; } } return 0; }
#include "util/file_piece.hh" #include "util/file.hh" #include "util/scoped.hh" #include "util/string_piece.hh" #include "util/tokenize_piece.hh" #include "util/murmur_hash.hh" #include "util/probing_hash_table.hh" #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fstream> #include <iostream> #include <boost/scoped_array.hpp> #include <boost/functional/hash.hpp> int main() { //std::fstream backing("../source.uniq.rand.gz", std::ios::in); util::FilePiece test("../source.uniq.rand.gz", NULL, 1); //An example of how not to read a file (try/catch), will change later, but for now, hacking while(true){ try { StringPiece line = test.ReadLine(); std::cout << line << std::endl; } catch (util::EndOfFileException e){ std::cout << "End of file" << std::endl; break; } } return 0; }
Add LIBTFTPU macro qualifier to the definition of the TpuCompilationCacheMetrics.
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/tpu/kernels/tpu_compilation_cache_metrics.h" namespace tensorflow { namespace tpu { /* static */ void TpuCompilationCacheMetrics::IncrementCacheLookupCount( bool is_cache_hit, absl::string_view session_name) { // A placeholder for tracking metrics. } /* static */ void TpuCompilationCacheMetrics::SetCacheEntryCount(int64 count) { // A placeholder for tracking metrics. } } // namespace tpu } // namespace tensorflow
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/tpu/kernels/tpu_compilation_cache_metrics.h" namespace tensorflow { namespace tpu { // TODO(henrytan): remove this once `TpuCompilationCache` migration to OSS is // completed. #if defined(LIBTFTPU) /* static */ void TpuCompilationCacheMetrics::IncrementCacheLookupCount( bool is_cache_hit, absl::string_view session_name) { // A placeholder for tracking metrics. } /* static */ void TpuCompilationCacheMetrics::SetCacheEntryCount(int64 count) { // A placeholder for tracking metrics. } #endif // LIBTFTPU } // namespace tpu } // namespace tensorflow
Add a REQUIRES: darwin line for a mac test.
// Clang on MacOS can find libc++ living beside the installed compiler. // This test makes sure our libTooling-based tools emulate this properly with // fixed compilation database. // // RUN: rm -rf %t // RUN: mkdir %t // // Install the mock libc++ (simulates the libc++ directory structure). // RUN: cp -r %S/Inputs/mock-libcxx %t/ // // RUN: cp $(which clang-check) %t/mock-libcxx/bin/ // RUN: cp "%s" "%t/test.cpp" // RUN: %t/mock-libcxx/bin/clang-check -p "%t" "%t/test.cpp" -- -stdlib=libc++ -target x86_64-apple-darwin #include <mock_vector> vector v;
// Clang on MacOS can find libc++ living beside the installed compiler. // This test makes sure our libTooling-based tools emulate this properly with // fixed compilation database. // // RUN: rm -rf %t // RUN: mkdir %t // // Install the mock libc++ (simulates the libc++ directory structure). // RUN: cp -r %S/Inputs/mock-libcxx %t/ // // RUN: cp $(which clang-check) %t/mock-libcxx/bin/ // RUN: cp "%s" "%t/test.cpp" // RUN: %t/mock-libcxx/bin/clang-check -p "%t" "%t/test.cpp" -- -stdlib=libc++ -target x86_64-apple-darwin // REQUIRES: system-darwin #include <mock_vector> vector v;
Use STB Image instead of SDL Image
#include "texture.hpp" #include <string> #include <SDL_image.h> const std::string Texture::filename(const std::string &name) { return "/textures/" + name; } Texture::Texture(const Adapter &adapter, const std::string &name) { SDL_Surface *surface = IMG_Load(adapter.filename<Texture>(name).c_str()); glGenTextures(1, &_id); glBindTexture(GL_TEXTURE_2D, _id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, surface->w, surface->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, surface->pixels); SDL_FreeSurface(surface); } void Texture::use() const { glBindTexture(GL_TEXTURE_2D, _id); }
#include "texture.hpp" #include <string> #define STB_IMAGE_IMPLEMENTATION #define STBI_ASSERT(x) #define STBI_ONLY_PNG #include <stb_image.h> const std::string Texture::filename(const std::string &name) { return "/textures/" + name; } Texture::Texture(const Adapter &adapter, const std::string &name) { GLsizei width, height, comp; GLvoid *data = stbi_load(adapter.filename<Texture>(name).c_str(), &width, &height, &comp, 0); glGenTextures(1, &_id); glBindTexture(GL_TEXTURE_2D, _id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); stbi_image_free(data); } void Texture::use() const { glBindTexture(GL_TEXTURE_2D, _id); }
Define variables `are_points_defined`, `point1`, `point2`.
#include "line.hpp" // Include standard headers #include <cmath> // NAN, std::isnan, std::pow #include <string> // std::string #include <vector> // std::vector namespace geometry { // constructor. // can be used for creating n-dimensional lines. Line::Line(std::vector<float> point1, std::vector<float> point2) { if (point1 == point2) { this->is_valid = false; // two identical points do not define a line. this->general_form_coefficients.push_back(NAN); this->general_form_constant = NAN; } else { this->is_valid = true; // two distinct points define a line. } } // constructor. // can be used for creating n-dimensional lines. Line::Line(std::vector<float> general_form_coefficients, float general_form_constant) { this->general_form_coefficients = general_form_coefficients; this->general_form_constant = general_form_constant; } std::string Line::get_general_form_equation() { // TODO: implement this function! std::string line_equation; return line_equation; } }
#include "line.hpp" // Include standard headers #include <cmath> // NAN, std::isnan, std::pow #include <string> // std::string #include <vector> // std::vector namespace geometry { // constructor. // can be used for creating n-dimensional lines. Line::Line(std::vector<float> point1, std::vector<float> point2) { if (point1 == point2) { this->is_valid = false; // two identical points do not define a line. this->general_form_coefficients.push_back(NAN); this->general_form_constant = NAN; } else { this->is_valid = true; // two distinct points define a line. this->are_points_defined = true; this->point1 = point1; this->point2 = point2; } } // constructor. // can be used for creating n-dimensional lines. Line::Line(std::vector<float> general_form_coefficients, float general_form_constant) { this->general_form_coefficients = general_form_coefficients; this->general_form_constant = general_form_constant; } std::string Line::get_general_form_equation() { // TODO: implement this function! std::string line_equation; return line_equation; } }
Set StdHandle initialization with with call_once
#include <MinConsole.hpp> #include <Windows.h> namespace MinConsole { void* GetOutputHandle() { static void* Handle = nullptr; if( Handle == nullptr ) { Handle = GetStdHandle(STD_OUTPUT_HANDLE); } return Handle; } void SetTextColor(Color NewColor) { SetConsoleTextAttribute( GetOutputHandle(), static_cast<std::underlying_type_t<MinConsole::Color>>(NewColor) ); } std::size_t GetWidth() { CONSOLE_SCREEN_BUFFER_INFO ConsoleInfo; if( GetConsoleScreenBufferInfo( GetOutputHandle(), &ConsoleInfo) ) { return static_cast<size_t>(ConsoleInfo.dwSize.X); } return 0; } }
#include <MinConsole.hpp> #include <Windows.h> #include <mutex> namespace MinConsole { void* GetOutputHandle() { static void* Handle = nullptr; std::once_flag HandleCached; std::call_once(HandleCached, [=]() { Handle = GetStdHandle(STD_OUTPUT_HANDLE); }); return Handle; } void SetTextColor(Color NewColor) { SetConsoleTextAttribute( GetOutputHandle(), static_cast<std::underlying_type_t<MinConsole::Color>>(NewColor) ); } std::size_t GetWidth() { CONSOLE_SCREEN_BUFFER_INFO ConsoleInfo; if( GetConsoleScreenBufferInfo( GetOutputHandle(), &ConsoleInfo) ) { return static_cast<size_t>(ConsoleInfo.dwSize.X); } return 0; } }
Revert 191028 "[Sync] Disable unrecoverable error uploading."
// 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/sync/glue/chrome_report_unrecoverable_error.h" #include "base/rand_util.h" #include "build/build_config.h" #if defined(OS_WIN) #include <windows.h> #endif #include "chrome/common/chrome_constants.h" namespace browser_sync { static const double kErrorUploadRatio = 0.0; void ChromeReportUnrecoverableError() { // TODO(lipalani): Add this for other platforms as well. #if defined(OS_WIN) // We only want to upload |kErrorUploadRatio| ratio of errors. if (kErrorUploadRatio <= 0.0) return; // We are not allowed to upload errors. double random_number = base::RandDouble(); if (random_number > kErrorUploadRatio) return; // Get the breakpad pointer from chrome.exe typedef void (__cdecl *DumpProcessFunction)(); DumpProcessFunction DumpProcess = reinterpret_cast<DumpProcessFunction>( ::GetProcAddress(::GetModuleHandle( chrome::kBrowserProcessExecutableName), "DumpProcessWithoutCrash")); if (DumpProcess) DumpProcess(); #endif // OS_WIN } } // namespace browser_sync
// 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/sync/glue/chrome_report_unrecoverable_error.h" #include "base/rand_util.h" #include "build/build_config.h" #if defined(OS_WIN) #include <windows.h> #endif #include "chrome/common/chrome_constants.h" namespace browser_sync { static const double kErrorUploadRatio = 0.15; void ChromeReportUnrecoverableError() { // TODO(lipalani): Add this for other platforms as well. #if defined(OS_WIN) // We only want to upload |kErrorUploadRatio| ratio of errors. if (kErrorUploadRatio <= 0.0) return; // We are not allowed to upload errors. double random_number = base::RandDouble(); if (random_number > kErrorUploadRatio) return; // Get the breakpad pointer from chrome.exe typedef void (__cdecl *DumpProcessFunction)(); DumpProcessFunction DumpProcess = reinterpret_cast<DumpProcessFunction>( ::GetProcAddress(::GetModuleHandle( chrome::kBrowserProcessExecutableName), "DumpProcessWithoutCrash")); if (DumpProcess) DumpProcess(); #endif // OS_WIN } } // namespace browser_sync
Enable Kannada, Farsi and Telugu on CrOS
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #if defined(OS_CHROMEOS) #include "base/basictypes.h" #include "base/string_util.h" #endif namespace l10n_util { // Return true blindly for now. bool IsLocaleSupportedByOS(const std::string& locale) { #if !defined(OS_CHROMEOS) return true; #else // We don't have translations yet for am, fa and sw. // We don't have fonts for te and kn, yet. // TODO(jungshik): Once the above issues are resolved, change this back // to return true. static const char* kUnsupportedLocales[] = {"am", "fa", "kn", "sw", "te"}; for (size_t i = 0; i < arraysize(kUnsupportedLocales); ++i) { if (LowerCaseEqualsASCII(locale, kUnsupportedLocales[i])) return false; } return true; #endif } } // namespace l10n_util
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #if defined(OS_CHROMEOS) #include "base/basictypes.h" #include "base/string_util.h" #endif namespace l10n_util { // Return true blindly for now. bool IsLocaleSupportedByOS(const std::string& locale) { #if !defined(OS_CHROMEOS) return true; #else // We don't have translations yet for am, and sw. // TODO(jungshik): Once the above issues are resolved, change this back // to return true. static const char* kUnsupportedLocales[] = {"am", "sw"}; for (size_t i = 0; i < arraysize(kUnsupportedLocales); ++i) { if (LowerCaseEqualsASCII(locale, kUnsupportedLocales[i])) return false; } return true; #endif } } // namespace l10n_util
Print exception details on decode failure
#include "OptionsManager.h" #include <fstream> #include <boost/filesystem.hpp> #include <spotify/json.hpp> #include "codecs/OptionsCodec.h" OptionsManager::OptionsManager(std::string optionsFilename) { loadOptions(optionsFilename); } void OptionsManager::loadOptions(std::string optionsFilename) { std::ifstream ifs(optionsFilename); if (!ifs.good()) { throw std::runtime_error("Could not open options file"); } std::string str{std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>()}; mOptions = spotify::json::decode<Options>(str.c_str()); mOptions.filename = optionsFilename; createOutputDirectory(optionsFilename); } void OptionsManager::createOutputDirectory(std::string optionsFilename) { // TODO(hryniuk): move it elsewhere auto outputDirectory = mOptions.outputDirectory; boost::filesystem::path p(optionsFilename); p.remove_filename(); p.append(outputDirectory); boost::filesystem::create_directories(p); auto relativeOutputDirectory = p.string(); mOptions.relativeOutputDirectory = relativeOutputDirectory; } const Options& OptionsManager::getOptions() const { return mOptions; }
#include "OptionsManager.h" #include <fstream> #include <iostream> #include <boost/filesystem.hpp> #include <spotify/json.hpp> #include "codecs/OptionsCodec.h" OptionsManager::OptionsManager(std::string optionsFilename) { loadOptions(optionsFilename); } void OptionsManager::loadOptions(std::string optionsFilename) { std::ifstream ifs(optionsFilename); if (!ifs.good()) { throw std::runtime_error("Could not open options file"); } std::string str{std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>()}; try { mOptions = spotify::json::decode<Options>(str.c_str()); } catch (spotify::json::decode_exception e) { std::cout << "spotify::json::decode_exception encountered at " << e.offset() << ": " << e.what(); throw; } mOptions.filename = optionsFilename; createOutputDirectory(optionsFilename); } void OptionsManager::createOutputDirectory(std::string optionsFilename) { // TODO(hryniuk): move it elsewhere auto outputDirectory = mOptions.outputDirectory; boost::filesystem::path p(optionsFilename); p.remove_filename(); p.append(outputDirectory); boost::filesystem::create_directories(p); auto relativeOutputDirectory = p.string(); mOptions.relativeOutputDirectory = relativeOutputDirectory; } const Options& OptionsManager::getOptions() const { return mOptions; }
Disable test with debug runtime
// Test that verifies TSan runtime doesn't contain compiler-emitted // memcpy/memmove calls. It builds the binary with TSan and passes it to // check_memcpy.sh script. // RUN: %clangxx_tsan -O1 %s -o %t // RUN: llvm-objdump -d %t | FileCheck %s int main() { return 0; } // CHECK-NOT: callq {{.*<(__interceptor_)?mem(cpy|set)>}} // tail calls: // CHECK-NOT: jmpq {{.*<(__interceptor_)?mem(cpy|set)>}}
// Test that verifies TSan runtime doesn't contain compiler-emitted // memcpy/memmove calls. It builds the binary with TSan and passes it to // check_memcpy.sh script. // RUN: %clangxx_tsan -O1 %s -o %t // RUN: llvm-objdump -d %t | FileCheck %s // REQUIRES: compiler-rt-optimized int main() { return 0; } // CHECK-NOT: callq {{.*<(__interceptor_)?mem(cpy|set)>}} // tail calls: // CHECK-NOT: jmpq {{.*<(__interceptor_)?mem(cpy|set)>}}
Add cstdlib so that the code compiles on OSX
#include "JSON.h" #include <string> namespace ouroboros { JSON::JSON() :mpArr(nullptr) {} JSON::JSON(const std::string& aJSON) :mpArr(parse_json2(aJSON.c_str(), aJSON.length())) {} JSON::~JSON() { free(mpArr); } bool JSON::exists(const std::string& aPath) const { if (mpArr) { const json_token * ptr = find_json_token(mpArr, aPath.c_str()); if (ptr) { return true; } } return false; } std::string JSON::get(const std::string& aPath) const { if (mpArr) { const json_token * ptr = find_json_token(mpArr, aPath.c_str()); if (ptr) { return std::string(ptr->ptr, ptr->len); } } return std::string(); } bool JSON::empty() const { return (!mpArr); } }
#include "JSON.h" #include <string> #include <cstdlib> namespace ouroboros { JSON::JSON() :mpArr(nullptr) {} JSON::JSON(const std::string& aJSON) :mpArr(parse_json2(aJSON.c_str(), aJSON.length())) {} JSON::~JSON() { free(mpArr); } bool JSON::exists(const std::string& aPath) const { if (mpArr) { const json_token * ptr = find_json_token(mpArr, aPath.c_str()); if (ptr) { return true; } } return false; } std::string JSON::get(const std::string& aPath) const { if (mpArr) { const json_token * ptr = find_json_token(mpArr, aPath.c_str()); if (ptr) { return std::string(ptr->ptr, ptr->len); } } return std::string(); } bool JSON::empty() const { return (!mpArr); } }
Add "each" alias that's new in RSpec 3
#include <string> #include <ccspec/core/hooks.h> #include <ccspec/core/example_group.h> namespace ccspec { namespace core { void before(std::string entity, Hook hook) { ExampleGroup* parent_group = groups_being_defined.top(); if (entity == "each") parent_group->addBeforeEachHook(hook); else throw "no such before hook type"; } } // namespace core } // namespace ccspec
#include <string> #include <ccspec/core/hooks.h> #include <ccspec/core/example_group.h> namespace ccspec { namespace core { void before(std::string entity, Hook hook) { ExampleGroup* parent_group = groups_being_defined.top(); if (entity == "each" || entity == "example") parent_group->addBeforeEachHook(hook); else throw "no such before hook type"; } } // namespace core } // namespace ccspec
Add --start and --stop commands to manage the server.
#include <client/client.h> #include <server/server.h> #include <err.h> #include <stdlib.h> #include <string.h> #include <unistd.h> int main(int argc, char **argv) { int separator; char** compile_argv; separator = 0; for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "--") == 0) { separator = i; break; } } compile_argv = argv + separator; compile_argv[0] = separator >= 2 ? argv[separator - 1] : (char*) "clang"; /* Start the server and send the compile command. */ if (!clc::server::is_running()) clc::server::start(); /* Run the compiler and print error message if execvp returns. */ execvp(compile_argv[0], compile_argv); err(EXIT_FAILURE, "%s", compile_argv[0]); }
#include <client/client.h> #include <server/server.h> #include <err.h> #include <stdlib.h> #include <string.h> #include <unistd.h> int main(int argc, char **argv) { int separator; char** compile_argv; separator = 0; for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "--") == 0) { separator = i; break; } else if (strcmp(argv[i], "--start") == 0) { clc::server::start(); return EXIT_SUCCESS; } else if (strcmp(argv[i], "--stop") == 0) { clc::server::stop(); return EXIT_SUCCESS; } } compile_argv = argv + separator; compile_argv[0] = separator >= 2 ? argv[separator - 1] : (char*) "clang"; /* Start the server and send the compile command. */ if (!clc::server::is_running()) clc::server::start(); /* Run the compiler and print error message if execvp returns. */ execvp(compile_argv[0], compile_argv); err(EXIT_FAILURE, "%s", compile_argv[0]); }
Fix test failure on GCC 4.9
//===----------------------------------------------------------------------===// // // 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 // <utility> // template <class T1, class T2> struct pair // constexpr pair(); #include <utility> #include <type_traits> #include "archetypes.hpp" int main() { using NonThrowingDefault = NonThrowingTypes::DefaultOnly; using ThrowingDefault = NonTrivialTypes::DefaultOnly; static_assert(!std::is_nothrow_default_constructible<std::pair<ThrowingDefault, ThrowingDefault>>::value, ""); static_assert(!std::is_nothrow_default_constructible<std::pair<NonThrowingDefault, ThrowingDefault>>::value, ""); static_assert(!std::is_nothrow_default_constructible<std::pair<ThrowingDefault, NonThrowingDefault>>::value, ""); static_assert( std::is_nothrow_default_constructible<std::pair<NonThrowingDefault, NonThrowingDefault>>::value, ""); }
//===----------------------------------------------------------------------===// // // 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 // <utility> // template <class T1, class T2> struct pair // constexpr pair(); #include <utility> #include <type_traits> struct ThrowingDefault { ThrowingDefault() { } }; struct NonThrowingDefault { NonThrowingDefault() noexcept { } }; int main() { static_assert(!std::is_nothrow_default_constructible<std::pair<ThrowingDefault, ThrowingDefault>>::value, ""); static_assert(!std::is_nothrow_default_constructible<std::pair<NonThrowingDefault, ThrowingDefault>>::value, ""); static_assert(!std::is_nothrow_default_constructible<std::pair<ThrowingDefault, NonThrowingDefault>>::value, ""); static_assert( std::is_nothrow_default_constructible<std::pair<NonThrowingDefault, NonThrowingDefault>>::value, ""); }
Add test case from PR6952, which now works (thanks to Gabor).
// RUN: %clang_cc1 -fsyntax-only -verify %s template<typename T> struct X1 { friend void f6(int) { } // expected-error{{redefinition of}} \ // expected-note{{previous definition}} }; X1<int> x1a; X1<float> x1b; // expected-note {{in instantiation of}}
// RUN: %clang_cc1 -fsyntax-only -verify %s template<typename T> struct X1 { friend void f6(int) { } // expected-error{{redefinition of}} \ // expected-note{{previous definition}} }; X1<int> x1a; X1<float> x1b; // expected-note {{in instantiation of}} template<typename T> struct X2 { operator int(); friend void f(int x) { } // expected-error{{redefinition}} \ // expected-note{{previous definition}} }; int array0[sizeof(X2<int>)]; int array1[sizeof(X2<float>)]; // expected-note{{instantiation of}} void g() { X2<int> xi; f(xi); X2<float> xf; f(xf); }
Fix the copy constructors to call the base constructor
#include <iostream> using namespace std; class Greeting { protected: string s; public: Greeting(){ s = "Hello, "; } virtual ~Greeting() { } virtual void printGreeting() = 0; }; class GitHubGreeting : public Greeting { public: GitHubGreeting() { s += "GitHub!"; printGreeting(); } GitHubGreeting(GitHubGreeting & h) { } GitHubGreeting(GitHubGreeting * h) { } virtual ~GitHubGreeting() { } void operator=(GitHubGreeting & h) { } void printGreeting() { cout << s << endl; } }; int main() { GitHubGreeting h; return 0; }
#include <iostream> using namespace std; class Greeting { protected: string s; public: Greeting(){ s = "Hello, "; } virtual ~Greeting() { } virtual void printGreeting() = 0; }; class GitHubGreeting : public Greeting { public: GitHubGreeting() { s += "GitHub!"; printGreeting(); } GitHubGreeting(GitHubGreeting & h) { GitHubGreeting(); } GitHubGreeting(GitHubGreeting * h) { GitHubGreeting(); } virtual ~GitHubGreeting() { } void operator=(GitHubGreeting & h) { } void printGreeting() { cout << s << endl; } }; int main() { GitHubGreeting h; return 0; }
Write initial browser window file from IO thread.
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/legacy_window_manager/initial_browser_window_observer.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/logging.h" #include "chrome/common/chrome_notification_types.h" #include "content/public/browser/notification_service.h" namespace { // Taken from the --initial_chrome_window_mapped_file flag in the chromeos-wm // command line: http://goo.gl/uLwIL const char kInitialWindowFile[] = "/var/run/state/windowmanager/initial-chrome-window-mapped"; } // namespace namespace chromeos { InitialBrowserWindowObserver::InitialBrowserWindowObserver() { registrar_.Add(this, chrome::NOTIFICATION_BROWSER_WINDOW_READY, content::NotificationService::AllSources()); } void InitialBrowserWindowObserver::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { registrar_.RemoveAll(); file_util::WriteFile(FilePath(kInitialWindowFile), "", 0); } } // namespace chromeos
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/legacy_window_manager/initial_browser_window_observer.h" #include "base/bind.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/logging.h" #include "chrome/common/chrome_notification_types.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_service.h" namespace { // Taken from the --initial_chrome_window_mapped_file flag in the chromeos-wm // command line: http://goo.gl/uLwIL const char kInitialWindowFile[] = "/var/run/state/windowmanager/initial-chrome-window-mapped"; void WriteInitialWindowFile() { if (file_util::WriteFile(FilePath(kInitialWindowFile), "", 0) == -1) LOG(ERROR) << "Failed to touch " << kInitialWindowFile; } } // namespace namespace chromeos { InitialBrowserWindowObserver::InitialBrowserWindowObserver() { registrar_.Add(this, chrome::NOTIFICATION_BROWSER_WINDOW_READY, content::NotificationService::AllSources()); } void InitialBrowserWindowObserver::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { registrar_.RemoveAll(); content::BrowserThread::PostTask( content::BrowserThread::IO, FROM_HERE, base::Bind(&WriteInitialWindowFile)); } } // namespace chromeos
Fix a typo in a test case for ParamPolicy2.
#include "gtest/gtest.h" #include "Models/GaussianModel.hpp" #include "test_utils/test_utils.hpp" #include <fstream> namespace { using namespace BOOM; using std::endl; using std::cout; class ParamPolicy2Test : public ::testing::Test { protected: ParamPolicy2Test() { GlobalRng::rng.seed(8675309); } }; TEST_F(ParamPolicy2Test, ParamVectorTest) { GaussianModel model1(1.2, 3.7); EXPECT_EQ(2, model1.parameter_vector().size()); model1.disable_parameter_1(); model1.set_mu(0.1); EXPECT_DOUBLE_EQ(0.1, model1.mu()); EXPECT_DOUBLE_EQ(2.7, model1.sigma()); EXPECT_EQ(1, model1.parameter_vector().size()); } } // namespace
#include "gtest/gtest.h" #include "Models/GaussianModel.hpp" #include "test_utils/test_utils.hpp" #include <fstream> namespace { using namespace BOOM; using std::endl; using std::cout; class ParamPolicy2Test : public ::testing::Test { protected: ParamPolicy2Test() { GlobalRng::rng.seed(8675309); } }; TEST_F(ParamPolicy2Test, ParamVectorTest) { GaussianModel model1(1.2, 3.7); EXPECT_EQ(2, model1.parameter_vector().size()); // Fix the mean at its current value. model1.disable_parameter_1(); model1.set_mu(0.1); EXPECT_DOUBLE_EQ(0.1, model1.mu()); EXPECT_DOUBLE_EQ(3.7, model1.sigma()); EXPECT_EQ(1, model1.parameter_vector().size()); Vector params = model1.vectorize_params(); EXPECT_EQ(1, params.size()); EXPECT_DOUBLE_EQ(square(3.7), params[0]); } } // namespace
Remove pragma once from cpp file
#pragma once #include <glkernel/Kernel.h> #include <glm/vec2.hpp> #include <glkernel/Kernel.h> #include <glkernel/uniform_noise.h> #include <glkernel/normal_noise.h> #include <glkernel/square_points.hpp> namespace glkernel { void test() { { auto noise = glkernel::Kernel<float>(); } { auto noise = glkernel::Kernel<double>(); } { auto noise = glkernel::Kernel<glm::vec2>(); } { auto noise = glkernel::Kernel<glm::dvec2>(); } { auto noise = glkernel::Kernel<glm::vec3>(); } { auto noise = glkernel::Kernel<glm::dvec3>(); } { auto noise = glkernel::Kernel<glm::vec4>(); } { auto noise = glkernel::Kernel<glm::dvec4>(); } } } // namespace glkernel
#include <glkernel/Kernel.h> #include <glm/vec2.hpp> #include <glkernel/Kernel.h> #include <glkernel/uniform_noise.h> #include <glkernel/normal_noise.h> #include <glkernel/square_points.hpp> namespace glkernel { void test() { { auto noise = glkernel::Kernel<float>(); } { auto noise = glkernel::Kernel<double>(); } { auto noise = glkernel::Kernel<glm::vec2>(); } { auto noise = glkernel::Kernel<glm::dvec2>(); } { auto noise = glkernel::Kernel<glm::vec3>(); } { auto noise = glkernel::Kernel<glm::dvec3>(); } { auto noise = glkernel::Kernel<glm::vec4>(); } { auto noise = glkernel::Kernel<glm::dvec4>(); } } } // namespace glkernel
Revert "Fixed incorrect autowiring test."
#include "stdafx.h" #include "AutowiringTest.h" #include "Autowired.h" #include "TestFixtures/SimpleObject.h" #include "TestFixtures/SimpleReceiver.h" TEST_F(AutowiringTest, VerifyAutowiredFast) { // Add an object: m_create->Inject<SimpleObject>(); // Verify that AutowiredFast can find this object AutowiredFast<SimpleObject> sobj; ASSERT_TRUE(sobj.IsAutowired()) << "Failed to autowire an object which was just injected into a context"; } TEST_F(AutowiringTest, VerifyAutowiredFastNontrivial) { // This will cause a cache entry to be inserted into the CoreContext's memoization system. // If there is any improper or incorrect invalidation in that system, then the null entry // will create problems when we attempt to perform an AutowiredFast later on. AutowiredFast<CallableInterface>(); // Now we add the object AutoRequired<SimpleReceiver>(); // Verify that AutowiredFast can find this object from its interface Autowired<CallableInterface> ci; ASSERT_TRUE(ci.IsAutowired()) << "Failed to autowire an interface advertised by a newly-inserted object"; }
#include "stdafx.h" #include "AutowiringTest.h" #include "Autowired.h" #include "TestFixtures/SimpleObject.h" #include "TestFixtures/SimpleReceiver.h" TEST_F(AutowiringTest, VerifyAutowiredFast) { // Add an object: m_create->Inject<SimpleObject>(); // Verify that AutowiredFast can find this object AutowiredFast<SimpleObject> sobj; ASSERT_TRUE(sobj.IsAutowired()) << "Failed to autowire an object which was just injected into a context"; } TEST_F(AutowiringTest, VerifyAutowiredFastNontrivial) { // This will cause a cache entry to be inserted into the CoreContext's memoization system. // If there is any improper or incorrect invalidation in that system, then the null entry // will create problems when we attempt to perform an AutowiredFast later on. AutowiredFast<CallableInterface>(); // Now we add the object AutoRequired<SimpleReceiver>(); // Verify that AutowiredFast can find this object from its interface AutowiredFast<CallableInterface> ci; ASSERT_TRUE(ci.IsAutowired()) << "Failed to autowire an interface advertised by a newly-inserted object"; }
Disable DCHECK'ing that all NetworkChangeNotifiers are removed. BUG=34391
// 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 "net/base/network_change_notifier_helper.h" #include <algorithm> #include "base/logging.h" namespace net { namespace internal { NetworkChangeNotifierHelper::NetworkChangeNotifierHelper() : is_notifying_observers_(false) {} NetworkChangeNotifierHelper::~NetworkChangeNotifierHelper() { DCHECK(observers_.empty()); } void NetworkChangeNotifierHelper::AddObserver(Observer* observer) { DCHECK(!is_notifying_observers_); observers_.push_back(observer); } void NetworkChangeNotifierHelper::RemoveObserver(Observer* observer) { DCHECK(!is_notifying_observers_); observers_.erase(std::remove(observers_.begin(), observers_.end(), observer)); } void NetworkChangeNotifierHelper::OnIPAddressChanged() { DCHECK(!is_notifying_observers_); is_notifying_observers_ = true; for (std::vector<Observer*>::iterator it = observers_.begin(); it != observers_.end(); ++it) { (*it)->OnIPAddressChanged(); } is_notifying_observers_ = false; } } // namespace internal } // namespace net
// 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 "net/base/network_change_notifier_helper.h" #include <algorithm> #include "base/logging.h" namespace net { namespace internal { NetworkChangeNotifierHelper::NetworkChangeNotifierHelper() : is_notifying_observers_(false) {} NetworkChangeNotifierHelper::~NetworkChangeNotifierHelper() { // TODO(willchan): Re-enable this DCHECK after fixing http://crbug.com/34391 // since we're leaking URLRequestContextGetters that cause this DCHECK to // fire. // DCHECK(observers_.empty()); } void NetworkChangeNotifierHelper::AddObserver(Observer* observer) { DCHECK(!is_notifying_observers_); observers_.push_back(observer); } void NetworkChangeNotifierHelper::RemoveObserver(Observer* observer) { DCHECK(!is_notifying_observers_); observers_.erase(std::remove(observers_.begin(), observers_.end(), observer)); } void NetworkChangeNotifierHelper::OnIPAddressChanged() { DCHECK(!is_notifying_observers_); is_notifying_observers_ = true; for (std::vector<Observer*>::iterator it = observers_.begin(); it != observers_.end(); ++it) { (*it)->OnIPAddressChanged(); } is_notifying_observers_ = false; } } // namespace internal } // namespace net
Revert "Fixing a bug with rectangular window that would prevent it from being 0 at the end points"
/* * Rectangular Window Function Unit for Jamoma DSP * Copyright © 2009 by Trond Lossius * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "TTRectangularWindow.h" #define thisTTClass RectangularWindow #define thisTTClassName "rectangular" #define thisTTClassTags "audio, processor, function, window" TT_AUDIO_CONSTRUCTOR { setProcessMethod(processAudio); setCalculateMethod(calculateValue); } RectangularWindow::~RectangularWindow() { ; } TTErr RectangularWindow::calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data) { if ((x>0) && (x<1.0)) y = 1.0; else y = 0.0; return kTTErrNone; } TTErr RectangularWindow::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs) { TT_WRAP_CALCULATE_METHOD(calculateValue); }
/* * Rectangular Window Function Unit for Jamoma DSP * Copyright © 2009 by Trond Lossius * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "TTRectangularWindow.h" #define thisTTClass RectangularWindow #define thisTTClassName "rectangular" #define thisTTClassTags "audio, processor, function, window" TT_AUDIO_CONSTRUCTOR { setProcessMethod(processAudio); setCalculateMethod(calculateValue); } RectangularWindow::~RectangularWindow() { ; } TTErr RectangularWindow::calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data) { y = 1.0; return kTTErrNone; } TTErr RectangularWindow::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs) { TT_WRAP_CALCULATE_METHOD(calculateValue); }
Use vc_ functions to get display size
// Copyright (C) 2017 Elviss Strazdins // This file is part of the Ouzel engine. #include <bcm_host.h> #include "WindowResourceRasp.hpp" #include "utils/Log.hpp" namespace ouzel { WindowResourceRasp::WindowResourceRasp() { bcm_host_init(); } WindowResourceRasp::~WindowResourceRasp() { bcm_host_deinit(); } bool WindowResourceRasp::init(const Size2& newSize, bool newResizable, bool newFullscreen, bool newExclusiveFullscreen, const std::string& newTitle, bool newHighDpi, bool depth) { if (!WindowResource::init(newSize, newResizable, newFullscreen, newExclusiveFullscreen, newTitle, newHighDpi, depth)) { return false; } uint32_t screenWidth; uint32_t screenHeight; int32_t success = graphics_get_display_size(0, &screenWidth, &screenHeight); if (success < 0) { Log(Log::Level::ERR) << "Failed to get display size"; return false; } size.width = static_cast<float>(screenWidth); size.height = static_cast<float>(screenHeight); resolution = size; return true; } }
// Copyright (C) 2017 Elviss Strazdins // This file is part of the Ouzel engine. #include <bcm_host.h> #include "WindowResourceRasp.hpp" #include "utils/Log.hpp" namespace ouzel { WindowResourceRasp::WindowResourceRasp() { bcm_host_init(); } WindowResourceRasp::~WindowResourceRasp() { bcm_host_deinit(); } bool WindowResourceRasp::init(const Size2& newSize, bool newResizable, bool newFullscreen, bool newExclusiveFullscreen, const std::string& newTitle, bool newHighDpi, bool depth) { if (!WindowResource::init(newSize, newResizable, newFullscreen, newExclusiveFullscreen, newTitle, newHighDpi, depth)) { return false; } DISPMANX_DISPLAY_HANDLE_T display = vc_dispmanx_display_open(0); if (!display) { Log(Log::Level::ERR) << "Failed to open display"; return false; } DISPMANX_MODEINFO_T modeInfo; int32_t success = vc_dispmanx_display_get_info(display, &modeInfo); if (success < 0) { Log(Log::Level::ERR) << "Failed to get display size"; vc_dispmanx_display_close(display); return false; } size.width = static_cast<float>(modeInfo.width); size.height = static_cast<float>(modeInfo.height); resolution = size; vc_dispmanx_display_close(display); return true; } }
Add std::move to all local value
#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 { result.angle = driver->move(msg->id, ics::Angle::newDegree(msg->angle)); result.id = msg->id; pub.publish(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 { const auto& now_pos = driver->move(msg->id, ics::Angle::newDegree(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; }
Revert "Make sure failed tests actually fail."
#include "square.h" #include <gtest/gtest.h> TEST(TestSuite, squareTwo) { const double ret = square(2); ASSERT_EQ(5, ret); } TEST(TestSuite, squareFour) { const double ret = square(4.1); ASSERT_EQ(16.81, ret); } // Run all the tests that were declared with TEST() int main(int argc, char **argv){ testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
#include "square.h" #include <gtest/gtest.h> TEST(TestSuite, squareTwo) { const double ret = square(2); ASSERT_EQ(4, ret); } TEST(TestSuite, squareFour) { const double ret = square(4.1); ASSERT_EQ(16.81, ret); } // Run all the tests that were declared with TEST() int main(int argc, char **argv){ testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
Test for now starts an application.
#include "../test.h" #include <QUrl> #include "../../src/input/scxml_importer.h" TEST(Test_ScxmlImporter, foo) { ScxmlImporter importer(QUrl::fromLocalFile("../config/simple_state.xml")); }
#include "../test.h" #include <QUrl> #include <QStateMachine> #include <QGuiApplication> #include <QWindow> #include <QKeyEvent> #include <thread> #include <chrono> #include "../../src/input/scxml_importer.h" TEST(Test_ScxmlImporter, foo) { int zero = 0; QGuiApplication application(zero, static_cast<char **>(nullptr)); QWindow window; ScxmlImporter importer(QUrl::fromLocalFile("../config/simple_state.xml"), &window); auto stateMachine = importer.getStateMachine(); std::cout << "running:" << stateMachine->isRunning() << std::endl; stateMachine->start(); window.show(); std::cout << "running:" << stateMachine->isRunning() << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(500)); std::cout << "error:" << stateMachine->errorString().toStdString() << std::endl; std::cout << "running:" << stateMachine->isRunning() << std::endl; stateMachine->postEvent( new QKeyEvent(QEvent::KeyPress, Qt::Key_A, Qt::NoModifier)); application.exec(); }
Fix function signature in ATenOp for at::Half Set function
/** * Copyright (c) 2016-present, Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "aten_op.h" namespace caffe2 { REGISTER_CPU_OPERATOR(ATen, ATenOp<CPUContext>); template<> at::Backend ATenOp<CPUContext>::backend() const { return at::kCPU; } OPERATOR_SCHEMA(ATen); CAFFE_KNOWN_TYPE(at::Half); namespace math { template<> void Set<at::Half,CPUContext>(TIndex N, at::Half h, at::Half* v, CPUContext * c) { Set(0, h.x, (uint16_t*) v, c); } } }
/** * Copyright (c) 2016-present, Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "aten_op.h" namespace caffe2 { REGISTER_CPU_OPERATOR(ATen, ATenOp<CPUContext>); template<> at::Backend ATenOp<CPUContext>::backend() const { return at::kCPU; } OPERATOR_SCHEMA(ATen); CAFFE_KNOWN_TYPE(at::Half); namespace math { template<> void Set<at::Half,CPUContext>(const size_t N, const at::Half h, at::Half* v, CPUContext * c) { Set(0, h.x, (uint16_t*) v, c); } } }
Add suport for mimetypefinder -c file (find by file contents)
#include "qmimedatabase.h" #include <QtCore/QCoreApplication> #include <QtCore/QFile> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); if (argc <= 1) { printf( "No filename specified\n" ); return 1; } const QString fileName = QFile::decodeName(argv[1]); //int accuracy; QMimeDatabase db; QMimeType mime; if (fileName == QLatin1String("-")) { QFile qstdin; qstdin.open(stdin, QIODevice::ReadOnly); const QByteArray data = qstdin.readAll(); //mime = QMimeType::findByContent(data, &accuracy); mime = db.findByData(data); //} else if (args->isSet("c")) { //mime = QMimeType::findByFileContent(fileName, &accuracy); } else { //mime = QMimeType::findByPath(fileName, 0, args->isSet("f"), &accuracy); mime = db.findByFile(fileName); } if ( mime.isValid() /*&& !mime.isDefault()*/ ) { printf("%s\n", mime.name().toLatin1().constData()); //printf("(accuracy %d)\n", accuracy); } else { return 1; // error } return 0; }
#include "qmimedatabase.h" #include <QtCore/QCoreApplication> #include <QtCore/QFile> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); if (argc <= 1) { printf( "No filename specified\n" ); return 1; } QString option; int fnPos = 1; if (argc > 2) { option = QString::fromLatin1(argv[1]); ++fnPos; } const QString fileName = QFile::decodeName(argv[fnPos]); //int accuracy; QMimeDatabase db; QMimeType mime; if (fileName == QLatin1String("-")) { QFile qstdin; qstdin.open(stdin, QIODevice::ReadOnly); const QByteArray data = qstdin.readAll(); //mime = QMimeType::findByContent(data, &accuracy); mime = db.findByData(data); } else if (option == "-c") { QFile file(fileName); if (file.open(QIODevice::ReadOnly)) { mime = db.findByData(file.read(32000)); } } else { //mime = QMimeType::findByPath(fileName, 0, args->isSet("f"), &accuracy); mime = db.findByFile(fileName); } if ( mime.isValid() /*&& !mime.isDefault()*/ ) { printf("%s\n", mime.name().toLatin1().constData()); //printf("(accuracy %d)\n", accuracy); } else { return 1; // error } return 0; }
Change to /dev/urandom, as /dev/random was just haning/very slow
#include <iostream> #include <vector> #include <iomanip> #include <cmath> #include <random> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <stdlib.h> #include <stdio.h> using namespace std; // Implementation of the One-Time Pad key generation int main(int argc, char* argv[]) { if(argc < 2) { cout << "Usage: " << argv[0] << " len (key lenght in bytes)" << endl; return -1; } int len = atoi(argv[1]); if(len < 1) { cout << "Error in key size specification, must be > 1" << endl; return -1; } // Open random device: std::random_device rd2("/dev/random"); std::uniform_int_distribution<> dis(0,255); for(unsigned int i = 0; i < len; ++i) { std::cout << hex << setw(2) << setfill('0') << dis(rd2); } std::cout << dec << endl; return 0; }
#include <iostream> #include <vector> #include <iomanip> #include <cmath> #include <random> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <stdlib.h> #include <stdio.h> using namespace std; // Implementation of the One-Time Pad key generation int main(int argc, char* argv[]) { if(argc < 2) { cout << "Usage: " << argv[0] << " len (key lenght in bytes)" << endl; return -1; } int len = atoi(argv[1]); if(len < 1) { cout << "Error in key size specification, must be > 1" << endl; return -1; } // Open random device: std::random_device rd("/dev/urandom"); std::uniform_int_distribution<> dis(0,255); for(unsigned int i = 0; i < len; ++i) { std::cout << hex << setw(2) << setfill('0') << dis(rd); } std::cout << dec << endl; return 0; }
Reduce instruction count of totient
#include "common.th" _start: prologue c <- 67 call(totient) illegal // Computes the number of values less than C that are relatively prime to C. // Stores the result in B. totient: b <- 0 d <- c loop: k <- d == a jnzrel(k, done) pushall(b,c,d) call(gcd) k <- b <> 1 k <- k + 1 popall(b,c,d) b <- b + k d <- d - 1 goto(loop) done: ret
#include "common.th" _start: prologue c <- 67 call(totient) illegal // Computes the number of values less than C that are relatively prime to C. // Stores the result in B. totient: b <- 0 d <- c loop: k <- d == a jnzrel(k, done) pushall(b,c,d) call(gcd) k <- b <> 1 popall(b,c,d) b <- b + k + 1 d <- d - 1 goto(loop) done: ret
Mark test as unsupported in C++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: c++98, c++03 // REQUIRES: diagnose-if-support // <unordered_set> // Test that we generate a reasonable diagnostic when the specified hash is // not enabled. #include <unordered_set> #include <utility> using VT = std::pair<int, int>; using Set = std::unordered_set<VT>; int main() { Set s; // expected-error@__hash_table:* {{the specified hash functor does not meet the requirements for an enabled hash}} // FIXME: It would be great to suppress the below diagnostic all together. // but for now it's sufficient that it appears last. However there is // currently no way to test the order diagnostics are issued. // expected-error@memory:* {{call to implicitly-deleted default constructor of 'std::__1::hash<std::__1::pair<int, int> >'}} }
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // REQUIRES: diagnose-if-support // UNSUPPORTED: c++98, c++03 // Libc++ only provides a defined primary template for std::hash in C++14 and // newer. // UNSUPPORTED: c++11 // <unordered_set> // Test that we generate a reasonable diagnostic when the specified hash is // not enabled. #include <unordered_set> #include <utility> using VT = std::pair<int, int>; using Set = std::unordered_set<VT>; int main() { Set s; // expected-error@__hash_table:* {{the specified hash functor does not meet the requirements for an enabled hash}} // FIXME: It would be great to suppress the below diagnostic all together. // but for now it's sufficient that it appears last. However there is // currently no way to test the order diagnostics are issued. // expected-error@memory:* {{call to implicitly-deleted default constructor of 'std::__1::hash<std::__1::pair<int, int> >'}} }
Clean up Problem 30 solution
#include "SubstringWithConcatenationOfAllWords.hpp" #include <unordered_map> using namespace std; vector<int> SubstringWithConcatenationOfAllWords::findSubstring(string s, vector<string>& words) { vector<int> ret; size_t seglen = words[0].size(); size_t nsegs = words.size(); if (nsegs == 0 || s.size() == 0 || seglen == 0 || seglen * nsegs > s.size()) return ret; unordered_map<string, int> records; for (auto w : words) records[w]++; int p = 0; while (p + seglen * nsegs - 1 < s.size()) { unordered_map<string, int> local = records; int i; for (i = 0; i < nsegs; i++) { string seg = s.substr(p + i * seglen, seglen); if (local.find(seg) == local.end() || local[seg] == 0) break; else local[seg]--; } if (i == nsegs) ret.push_back(p); p++; } return ret; }
#include "SubstringWithConcatenationOfAllWords.hpp" #include <unordered_map> using namespace std; vector<int> SubstringWithConcatenationOfAllWords::findSubstring(string s, vector<string>& words) { vector<int> ret; size_t strlen = s.size(); size_t numw = words.size(); if (strlen == 0 || numw == 0) return ret; size_t wlen = words[0].size(); size_t substrlen = numw * wlen; if (wlen == 0 || substrlen > strlen) return ret; unordered_map<string, int> records; for (auto w : words) records[w]++; for (int p = 0; p + substrlen - 1 < strlen; p++) { unordered_map<string, int> local = records; int q; for (q = 0; q < numw; q++) { string seg = s.substr(p + q * wlen, wlen); if (local.find(seg) == local.end() || local[seg] == 0) break; else local[seg]--; } if (q == numw) ret.push_back(p); } return ret; }
Reorder quadrotor motors per convention.
#include <motor/multirotor_quad_x_motor_mapper.hpp> #include <array> MultirotorQuadXMotorMapper::MultirotorQuadXMotorMapper() { } void MultirotorQuadXMotorMapper::init() { PWMMotorMapper::init(); } void MultirotorQuadXMotorMapper::run(actuator_setpoint_t& input) { // Calculate output shifts std::array<float, 4> output_shifts = { 1.0f * input.pitch_sp + 1.0f * input.roll_sp + 1.0f * input.yaw_sp, // front left -1.0f * input.pitch_sp + 1.0f * input.roll_sp - 1.0f * input.yaw_sp, // front right -1.0f * input.pitch_sp - 1.0f * input.roll_sp + 1.0f * input.yaw_sp, // back right 1.0f * input.pitch_sp - 1.0f * input.roll_sp - 1.0f * input.yaw_sp // back left }; // Add throttle to shifts to get absolute output value std::array<float, 4> outputs = { 0 }; for(int i = 0; i < 4; i++) { outputs[i] = input.throttle_sp + output_shifts[i]; } setMotorSpeeds(outputs); }
#include <motor/multirotor_quad_x_motor_mapper.hpp> #include <array> MultirotorQuadXMotorMapper::MultirotorQuadXMotorMapper() { } void MultirotorQuadXMotorMapper::init() { PWMMotorMapper::init(); } void MultirotorQuadXMotorMapper::run(actuator_setpoint_t& input) { // Calculate output shifts // TODO(yoos): comment on motor indexing convention starting from positive // X in counterclockwise order. std::array<float, 4> output_shifts = { 1.0f * input.roll_sp - 1.0f * input.pitch_sp + 1.0f * input.yaw_sp, // front left 1.0f * input.roll_sp + 1.0f * input.pitch_sp - 1.0f * input.yaw_sp, // back left - 1.0f * input.roll_sp + 1.0f * input.pitch_sp + 1.0f * input.yaw_sp, // back right - 1.0f * input.roll_sp - 1.0f * input.pitch_sp - 1.0f * input.yaw_sp // front right }; // Add throttle to shifts to get absolute output value std::array<float, 4> outputs = { 0 }; for(int i = 0; i < 4; i++) { outputs[i] = input.throttle_sp + output_shifts[i]; } setMotorSpeeds(outputs); }
Fix default code directory for non-root user.
#include <puppet/compiler/settings.hpp> #include <boost/filesystem.hpp> #include <unistd.h> using namespace std; namespace fs = boost::filesystem; namespace sys = boost::system; namespace puppet { namespace compiler { string settings::default_code_directory() { auto home = getenv("HOME"); // For root or if the directory exists, use the global code directory sys::error_code ec; if (!home || geteuid() == 0 || fs::is_directory("/etc/puppetlabs/code", ec)) { return "/etc/puppetlabs/code"; } // Otherwise, use the local directory return (fs::path(home) / ".puppetlabs" / "etc" / "code").string(); } vector<string> settings::default_environment_directories() { vector<string> directories = { "$codedir/environments", }; return directories; } vector<string> settings::default_module_directories() { vector<string> directories = { "$codedir/modules", "/opt/puppetlabs/puppet/modules", }; return directories; } }} // namespace puppet::compiler
#include <puppet/compiler/settings.hpp> #include <boost/filesystem.hpp> #include <unistd.h> using namespace std; namespace fs = boost::filesystem; namespace sys = boost::system; namespace puppet { namespace compiler { string settings::default_code_directory() { auto home = getenv("HOME"); // For root or users without a HOME directory, use the global location if (!home || geteuid() == 0) { return "/etc/puppetlabs/code"; } // Otherwise, use the local directory return (fs::path(home) / ".puppetlabs" / "etc" / "code").string(); } vector<string> settings::default_environment_directories() { vector<string> directories = { "$codedir/environments", }; return directories; } vector<string> settings::default_module_directories() { vector<string> directories = { "$codedir/modules", "/opt/puppetlabs/puppet/modules", }; return directories; } }} // namespace puppet::compiler