Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Switch to string compare operator
#include "locale.hpp" #include <cstring> #include <clocale> #include <algorithm> #undef min #undef max namespace locale { std::vector<std::pair<std::string_view, std::string_view>> ListLocales() { std::vector<std::pair<std::string_view, std::string_view>> ret; ret.reserve(std::size_t(ELocale::MAXLocale)); for (ELocale l = ELocale(0); l < ELocale::MAXLocale; l = ELocale(int(l) + 1)) ret.emplace_back(GetName(l), GetFullName(l)); return ret; } ELocale LookupLocale(std::string_view name) { for (ELocale l = ELocale(0); l < ELocale::MAXLocale; l = ELocale(int(l) + 1)) if (!name.compare(GetName(l))) return l; return ELocale::Invalid; } ELocale SystemLocaleOrEnglish() { const char* sysLocale = std::setlocale(LC_ALL, nullptr); size_t sysLocaleLen = std::strlen(sysLocale); for (ELocale l = ELocale(0); l < ELocale::MAXLocale; l = ELocale(int(l) + 1)) { auto name = GetName(l); if (!name.compare(0, std::min(name.size(), sysLocaleLen), sysLocale)) return l; } return ELocale::en_US; } } // namespace locale
#include "locale.hpp" #include <cstring> #include <clocale> #include <algorithm> #undef min #undef max namespace locale { std::vector<std::pair<std::string_view, std::string_view>> ListLocales() { std::vector<std::pair<std::string_view, std::string_view>> ret; ret.reserve(std::size_t(ELocale::MAXLocale)); for (ELocale l = ELocale(0); l < ELocale::MAXLocale; l = ELocale(int(l) + 1)) ret.emplace_back(GetName(l), GetFullName(l)); return ret; } ELocale LookupLocale(std::string_view name) { for (ELocale l = ELocale(0); l < ELocale::MAXLocale; l = ELocale(int(l) + 1)) if (name == GetName(l)) return l; return ELocale::Invalid; } ELocale SystemLocaleOrEnglish() { const char* sysLocale = std::setlocale(LC_ALL, nullptr); size_t sysLocaleLen = std::strlen(sysLocale); for (ELocale l = ELocale(0); l < ELocale::MAXLocale; l = ELocale(int(l) + 1)) { auto name = GetName(l); if (!name.compare(0, std::min(name.size(), sysLocaleLen), sysLocale)) return l; } return ELocale::en_US; } } // namespace locale
Add MainHook to media unittests.
// 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 "base/test/test_suite.h" #include "media/base/media.h" class TestSuiteNoAtExit : public base::TestSuite { public: TestSuiteNoAtExit(int argc, char** argv) : TestSuite(argc, argv) {} virtual ~TestSuiteNoAtExit() {} protected: virtual void Initialize(); }; void TestSuiteNoAtExit::Initialize() { // Run TestSuite::Initialize first so that logging is initialized. base::TestSuite::Initialize(); // Run this here instead of main() to ensure an AtExitManager is already // present. media::InitializeMediaLibraryForTesting(); } int main(int argc, char** argv) { return TestSuiteNoAtExit(argc, argv).Run(); }
// 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 "base/test/main_hook.h" #include "base/test/test_suite.h" #include "media/base/media.h" class TestSuiteNoAtExit : public base::TestSuite { public: TestSuiteNoAtExit(int argc, char** argv) : TestSuite(argc, argv) {} virtual ~TestSuiteNoAtExit() {} protected: virtual void Initialize(); }; void TestSuiteNoAtExit::Initialize() { // Run TestSuite::Initialize first so that logging is initialized. base::TestSuite::Initialize(); // Run this here instead of main() to ensure an AtExitManager is already // present. media::InitializeMediaLibraryForTesting(); } int main(int argc, char** argv) { MainHook hook(main, argc, argv); return TestSuiteNoAtExit(argc, argv).Run(); }
Fix the test for printing the memory profile. This fuctionality is only available along side the leak checking, so use the REQUIRES for that.
// RUN: %clangxx_asan %s -o %t // RUN: %t 2>&1 | FileCheck %s #include <sanitizer/common_interface_defs.h> #include <stdio.h> char *sink[1000]; int main() { int idx = 0; for (int i = 0; i < 17; i++) sink[idx++] = new char[131]; for (int i = 0; i < 42; i++) sink[idx++] = new char[24]; __sanitizer_print_memory_profile(100); __sanitizer_print_memory_profile(50); } // CHECK: Live Heap Allocations: {{.*}}; showing top 100% // CHECK: 2227 byte(s) ({{.*}}%) in 17 allocation(s) // CHECK: 1008 byte(s) ({{.*}}%) in 42 allocation(s) // CHECK: Live Heap Allocations: {{.*}}; showing top 50% // CHECK: 2227 byte(s) ({{.*}}%) in 17 allocation(s) // CHECK-NOT: 1008 byte
// Printing memory profiling only works in the configuration where we can // detect leaks. // REQUIRES: leak-detection // // RUN: %clangxx_asan %s -o %t // RUN: %run %t 2>&1 | FileCheck %s #include <sanitizer/common_interface_defs.h> #include <stdio.h> char *sink[1000]; int main() { int idx = 0; for (int i = 0; i < 17; i++) sink[idx++] = new char[131]; for (int i = 0; i < 42; i++) sink[idx++] = new char[24]; __sanitizer_print_memory_profile(100); __sanitizer_print_memory_profile(50); } // CHECK: Live Heap Allocations: {{.*}}; showing top 100% // CHECK: 2227 byte(s) ({{.*}}%) in 17 allocation(s) // CHECK: 1008 byte(s) ({{.*}}%) in 42 allocation(s) // CHECK: Live Heap Allocations: {{.*}}; showing top 50% // CHECK: 2227 byte(s) ({{.*}}%) in 17 allocation(s) // CHECK-NOT: 1008 byte
Fix this test for gcc-4.2.
// RUN: %llvmgxx %s -S -emit-llvm -O2 -o - | ignore grep _Unwind_Resume | \ // RUN: wc -l | grep {\[02\]} struct One { }; struct Two { }; void handle_unexpected () { try { throw; } catch (One &) { throw Two (); } }
// RUN: %llvmgxx %s -S -emit-llvm -O2 -o - | ignore grep _Unwind_Resume | \ // RUN: wc -l | grep {\[23\]} struct One { }; struct Two { }; void handle_unexpected () { try { throw; } catch (One &) { throw Two (); } }
Fix (another) compilation bug on MSVC.
/* * The MIT License (MIT) * * Copyright (c) 2017 Nathan Osman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "transfersaction.h" QString TransfersAction::name() const { return "transfers"; } bool TransfersAction::ui() const { return true; } QString TransfersAction::title() const { return tr("View Transfers..."); } QVariant TransfersAction::invoke(const QVariantMap &) { mTransferWindow.show(); }
/* * The MIT License (MIT) * * Copyright (c) 2017 Nathan Osman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "transfersaction.h" QString TransfersAction::name() const { return "transfers"; } bool TransfersAction::ui() const { return true; } QString TransfersAction::title() const { return tr("View Transfers..."); } QVariant TransfersAction::invoke(const QVariantMap &) { mTransferWindow.show(); return true; }
Add missing include in FrequencyMao
#include "rapidcheck/detail/FrequencyMap.h" namespace rc { namespace detail { FrequencyMap::FrequencyMap(const std::vector<std::size_t> &frequencies) : m_sum(0) { m_table.reserve(frequencies.size()); for (auto x : frequencies) { m_sum += x; m_table.push_back(m_sum); } } std::size_t FrequencyMap::lookup(std::size_t x) const { return std::upper_bound(begin(m_table), end(m_table), x) - begin(m_table); } std::size_t FrequencyMap::sum() const { return m_sum; } } // namespace detail } // namespace rc
#include "rapidcheck/detail/FrequencyMap.h" #include <algorithm> namespace rc { namespace detail { FrequencyMap::FrequencyMap(const std::vector<std::size_t> &frequencies) : m_sum(0) { m_table.reserve(frequencies.size()); for (auto x : frequencies) { m_sum += x; m_table.push_back(m_sum); } } std::size_t FrequencyMap::lookup(std::size_t x) const { return std::upper_bound(begin(m_table), end(m_table), x) - begin(m_table); } std::size_t FrequencyMap::sum() const { return m_sum; } } // namespace detail } // namespace rc
Remove debug and unused headers
#include <fstream> #include <iostream> #include <utility> #include <map> #include <set> #include <queue> #include <bitset> #include <algorithm> using namespace std; int main() { ifstream fin("bcount.in"); ofstream fout("bcount.out"); int num_cows, num_queries; fin >> num_cows >> num_queries; vector<array<int, 3>> totals(num_cows + 1); for (int i = 0; i < num_cows; i++) { int cow; fin >> cow; totals[i + 1] = totals[i]; totals[i + 1][cow - 1]++; } for (int i = 0; i < num_queries; i++) { int a, b; fin >> a >> b; fout << (totals[b][0] - totals[a - 1][0]) << ' ' << (totals[b][1] - totals[a - 1][1]) << ' ' << (totals[b][2] - totals[a - 1][2]) << endl; } }
#include <fstream> #include <array> #include <vector> using namespace std; int main() { ifstream fin("bcount.in"); ofstream fout("bcount.out"); int num_cows, num_queries; fin >> num_cows >> num_queries; vector<array<int, 3>> totals(num_cows + 1); for (int i = 0; i < num_cows; i++) { int cow; fin >> cow; totals[i + 1] = totals[i]; totals[i + 1][cow - 1]++; } for (int i = 0; i < num_queries; i++) { int a, b; fin >> a >> b; fout << (totals[b][0] - totals[a - 1][0]) << ' ' << (totals[b][1] - totals[a - 1][1]) << ' ' << (totals[b][2] - totals[a - 1][2]) << endl; } }
Move an exception_ptr in exceptionStr
/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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 <folly/ExceptionString.h> namespace folly { /** * Debug string for an exception: include type and what(), if * defined. */ fbstring exceptionStr(const std::exception& e) { #if FOLLY_HAS_RTTI fbstring rv(demangle(typeid(e))); rv += ": "; #else fbstring rv("Exception (no RTTI available): "); #endif rv += e.what(); return rv; } fbstring exceptionStr(std::exception_ptr ep) { if (!kHasExceptions) { return "Exception (catch unavailable)"; } return catch_exception( [&]() -> fbstring { return catch_exception<std::exception const&>( [&]() -> fbstring { std::rethrow_exception(ep); }, [](auto&& e) { return exceptionStr(e); }); }, []() -> fbstring { return "<unknown exception>"; }); } } // namespace folly
/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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 <folly/ExceptionString.h> #include <utility> namespace folly { /** * Debug string for an exception: include type and what(), if * defined. */ fbstring exceptionStr(const std::exception& e) { #if FOLLY_HAS_RTTI fbstring rv(demangle(typeid(e))); rv += ": "; #else fbstring rv("Exception (no RTTI available): "); #endif rv += e.what(); return rv; } fbstring exceptionStr(std::exception_ptr ep) { if (!kHasExceptions) { return "Exception (catch unavailable)"; } return catch_exception( [&]() -> fbstring { return catch_exception<std::exception const&>( [&]() -> fbstring { std::rethrow_exception(std::move(ep)); }, [](auto&& e) { return exceptionStr(e); }); }, []() -> fbstring { return "<unknown exception>"; }); } } // namespace folly
Make sure we still reject static data members in anonymous unions in C++11.
// RUN: %clang_cc1 -verify -std=c++11 %s // Unlike in C++98, C++11 allows unions to have static data members. union U1 { static constexpr int k1 = 0; static const int k2 = k1; static int k3 = k2; // expected-error {{non-const static data member must be initialized out of line}} static constexpr double k4 = k2; static const double k5 = k4; // expected-warning {{GNU extension}} expected-note {{use 'constexpr'}} int n[k1 + 3]; }; constexpr int U1::k1; constexpr int U1::k2; int U1::k3; const double U1::k4; const double U1::k5; template<typename T> union U2 { static const int k1; static double k2; T t; }; template<typename T> constexpr int U2<T>::k1 = sizeof(U2<T>); template<typename T> double U2<T>::k2 = 5.3; static_assert(U2<int>::k1 == sizeof(int), ""); static_assert(U2<char>::k1 == sizeof(char), ""); union U3 { static const int k; U3() : k(0) {} // expected-error {{does not name a non-static data member}} };
// RUN: %clang_cc1 -verify -std=c++11 %s // Unlike in C++98, C++11 allows unions to have static data members. union U1 { static constexpr int k1 = 0; static const int k2 = k1; static int k3 = k2; // expected-error {{non-const static data member must be initialized out of line}} static constexpr double k4 = k2; static const double k5 = k4; // expected-warning {{GNU extension}} expected-note {{use 'constexpr'}} int n[k1 + 3]; }; constexpr int U1::k1; constexpr int U1::k2; int U1::k3; const double U1::k4; const double U1::k5; template<typename T> union U2 { static const int k1; static double k2; T t; }; template<typename T> constexpr int U2<T>::k1 = sizeof(U2<T>); template<typename T> double U2<T>::k2 = 5.3; static_assert(U2<int>::k1 == sizeof(int), ""); static_assert(U2<char>::k1 == sizeof(char), ""); union U3 { static const int k; U3() : k(0) {} // expected-error {{does not name a non-static data member}} }; struct S { union { static const int n; // expected-error {{static members cannot be declared in an anonymous union}} int a; int b; }; }; static union { static const int k; // expected-error {{static members cannot be declared in an anonymous union}} int n; };
Add constructor and destructor for StreamProcessor template
#include <nekit/deps/easylogging++.h> #include <nekit/stream_coder/detail/stream_coder_manager.h> #include <nekit/stream_coder/stream_processor.h> namespace nekit { namespace stream_coder { template <class T> ActionRequest StreamProcessor<T>::Negotiate() { return impl_->Negotiate(); } template <class T> BufferReserveSize StreamProcessor<T>::InputReserve() { return impl_->InputReserve(); } template <class T> ActionRequest StreamProcessor<T>::Input(utils::Buffer& buffer) { return impl_->Input(buffer); } template <class T> BufferReserveSize StreamProcessor<T>::OutputReserve() { return impl_->OutputReserve(); } template <class T> ActionRequest StreamProcessor<T>::Output(utils::Buffer& buffer) { return impl_->Output(buffer); } template <class T> utils::Error StreamProcessor<T>::GetLatestError() const { return impl_->GetLatestError(); } template <class T> bool StreamProcessor<T>::forwarding() const { return impl_->forwarding(); } template <class T> T* StreamProcessor<T>::implemention() { return impl_; } } // namespace stream_coder } // namespace nekit
#include <nekit/deps/easylogging++.h> #include <nekit/stream_coder/detail/stream_coder_manager.h> #include <nekit/stream_coder/stream_processor.h> namespace nekit { namespace stream_coder { template <class T> StreamProcessor<T>::StreamProcessor() { impl_ = new T(); } template <class T> StreamProcessor<T>::~StreamProcessor() { delete impl_; } template <class T> ActionRequest StreamProcessor<T>::Negotiate() { return impl_->Negotiate(); } template <class T> BufferReserveSize StreamProcessor<T>::InputReserve() { return impl_->InputReserve(); } template <class T> ActionRequest StreamProcessor<T>::Input(utils::Buffer& buffer) { return impl_->Input(buffer); } template <class T> BufferReserveSize StreamProcessor<T>::OutputReserve() { return impl_->OutputReserve(); } template <class T> ActionRequest StreamProcessor<T>::Output(utils::Buffer& buffer) { return impl_->Output(buffer); } template <class T> utils::Error StreamProcessor<T>::GetLatestError() const { return impl_->GetLatestError(); } template <class T> bool StreamProcessor<T>::forwarding() const { return impl_->forwarding(); } template <class T> T* StreamProcessor<T>::implemention() { return impl_; } } // namespace stream_coder } // namespace nekit
Call setlocale(LC_ALL, "") in a renderer process for subsequent calls to SysNativeMBToWide and WideToSysNativeMB (that use mbstowcs and wcstombs) to work correctly.
// 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_main_platform_delegate.h" #include "base/debug_util.h" // This is a no op class because we do not have a sandbox on linux. RendererMainPlatformDelegate::RendererMainPlatformDelegate( const MainFunctionParams& parameters) : parameters_(parameters) { } RendererMainPlatformDelegate::~RendererMainPlatformDelegate() { } void RendererMainPlatformDelegate::PlatformInitialize() { } void RendererMainPlatformDelegate::PlatformUninitialize() { } bool RendererMainPlatformDelegate::InitSandboxTests(bool no_sandbox) { // The sandbox is started in the zygote process: zygote_main_linux.cc // http://code.google.com/p/chromium/wiki/LinuxSUIDSandbox return true; } bool RendererMainPlatformDelegate::EnableSandbox() { // The sandbox is started in the zygote process: zygote_main_linux.cc // http://code.google.com/p/chromium/wiki/LinuxSUIDSandbox return true; } void RendererMainPlatformDelegate::RunSandboxTests() { // The sandbox is started in the zygote process: zygote_main_linux.cc // http://code.google.com/p/chromium/wiki/LinuxSUIDSandbox }
// 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_main_platform_delegate.h" #include "base/debug_util.h" // This is a no op class because we do not have a sandbox on linux. RendererMainPlatformDelegate::RendererMainPlatformDelegate( const MainFunctionParams& parameters) : parameters_(parameters) { } RendererMainPlatformDelegate::~RendererMainPlatformDelegate() { } void RendererMainPlatformDelegate::PlatformInitialize() { // To make wcstombs/mbstowcs work in a renderer. const char* locale = setlocale(LC_ALL, ""); LOG_IF(WARNING, locale == NULL) << "setlocale failed."; } void RendererMainPlatformDelegate::PlatformUninitialize() { } bool RendererMainPlatformDelegate::InitSandboxTests(bool no_sandbox) { // The sandbox is started in the zygote process: zygote_main_linux.cc // http://code.google.com/p/chromium/wiki/LinuxSUIDSandbox return true; } bool RendererMainPlatformDelegate::EnableSandbox() { // The sandbox is started in the zygote process: zygote_main_linux.cc // http://code.google.com/p/chromium/wiki/LinuxSUIDSandbox return true; } void RendererMainPlatformDelegate::RunSandboxTests() { // The sandbox is started in the zygote process: zygote_main_linux.cc // http://code.google.com/p/chromium/wiki/LinuxSUIDSandbox }
Reduce iterations in generic intersection alg
#include "surface.h" namespace batoid { #pragma omp declare target Surface::Surface() : _devPtr(nullptr) {} Surface::~Surface() {} bool Surface::timeToIntersect( double x, double y, double z, double vx, double vy, double vz, double& dt ) const { // The better the initial estimate of dt, the better this will perform double rPx = x+vx*dt; double rPy = y+vy*dt; double rPz = z+vz*dt; double sz = sag(rPx, rPy); // Always do exactly 10 iterations. GPUifies better this way. for (int iter=0; iter<10; iter++) { // repeatedly intersect plane tangent to surface at (rPx, rPy, sz) with ray double nx, ny, nz; normal(rPx, rPy, nx, ny, nz); dt = (rPx-x)*nx + (rPy-y)*ny + (sz-z)*nz; dt /= (nx*vx + ny*vy + nz*vz); rPx = x+vx*dt; rPy = y+vy*dt; rPz = z+vz*dt; sz = sag(rPx, rPy); } return (std::abs(sz-rPz) < 1e-12); } #pragma omp end declare target }
#include "surface.h" namespace batoid { #pragma omp declare target Surface::Surface() : _devPtr(nullptr) {} Surface::~Surface() {} bool Surface::timeToIntersect( double x, double y, double z, double vx, double vy, double vz, double& dt ) const { // The better the initial estimate of dt, the better this will perform double rPx = x+vx*dt; double rPy = y+vy*dt; double rPz = z+vz*dt; double sz = sag(rPx, rPy); // Always do exactly 5 iterations. GPUifies better this way. // Unit tests pass (as of 20/10/13) with just 3 iterations. for (int iter=0; iter<5; iter++) { // repeatedly intersect plane tangent to surface at (rPx, rPy, sz) with ray double nx, ny, nz; normal(rPx, rPy, nx, ny, nz); dt = (rPx-x)*nx + (rPy-y)*ny + (sz-z)*nz; dt /= (nx*vx + ny*vy + nz*vz); rPx = x+vx*dt; rPy = y+vy*dt; rPz = z+vz*dt; sz = sag(rPx, rPy); } return (std::abs(sz-rPz) < 1e-12); } #pragma omp end declare target }
Remove unconditional assert from addNativeTracingHooks. Do nothing instead.
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "JSITracing.h" namespace facebook { namespace jsi { void addNativeTracingHooks(Runtime &rt) { assert(false && "unimplemented"); } } // namespace jsi } // namespace facebook
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "JSITracing.h" namespace facebook { namespace jsi { void addNativeTracingHooks(Runtime &rt) { // Unimplemented } } // namespace jsi } // namespace facebook
Fix race condition in thread test.
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // UNSUPPORTED: libcpp-has-no-threads // <thread> // class thread // void detach(); #include <thread> #include <new> #include <cstdlib> #include <cassert> class G { int alive_; public: static int n_alive; static bool op_run; G() : alive_(1) {++n_alive;} G(const G& g) : alive_(g.alive_) {++n_alive;} ~G() {alive_ = 0; --n_alive;} void operator()() { assert(alive_ == 1); assert(n_alive >= 1); op_run = true; } }; int G::n_alive = 0; bool G::op_run = false; int main() { { std::thread t0((G())); assert(t0.joinable()); t0.detach(); assert(!t0.joinable()); std::this_thread::sleep_for(std::chrono::milliseconds(250)); assert(G::op_run); assert(G::n_alive == 0); } }
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // UNSUPPORTED: libcpp-has-no-threads // <thread> // class thread // void detach(); #include <thread> #include <atomic> #include <cassert> std::atomic_bool done = ATOMIC_VAR_INIT(false); class G { int alive_; bool done_; public: static int n_alive; static bool op_run; G() : alive_(1), done_(false) { ++n_alive; } G(const G& g) : alive_(g.alive_), done_(false) { ++n_alive; } ~G() { alive_ = 0; --n_alive; if (done_) done = true; } void operator()() { assert(alive_ == 1); assert(n_alive >= 1); op_run = true; done_ = true; } }; int G::n_alive = 0; bool G::op_run = false; int main() { { G g; std::thread t0(g); assert(t0.joinable()); t0.detach(); assert(!t0.joinable()); while (!done) {} assert(G::op_run); assert(G::n_alive == 1); } assert(G::n_alive == 0); }
Comment why the slots table is allocated on the heap.
#include <object/centralized-slots.hh> namespace object { CentralizedSlots::content_type* CentralizedSlots::content_ = new CentralizedSlots::content_type(); CentralizedSlots::loc_index_type& CentralizedSlots::loc_index_ = CentralizedSlots::content_->get<0>(); CentralizedSlots::obj_index_type& CentralizedSlots::obj_index_ = CentralizedSlots::content_->get<1>(); }
#include <object/centralized-slots.hh> namespace object { // Allocated dynamically to avoid static destruction order // fiasco. Some objects could indeed be destroyed after the hash // table is destroyed. CentralizedSlots::content_type* CentralizedSlots::content_ = new CentralizedSlots::content_type(); CentralizedSlots::loc_index_type& CentralizedSlots::loc_index_ = CentralizedSlots::content_->get<0>(); CentralizedSlots::obj_index_type& CentralizedSlots::obj_index_ = CentralizedSlots::content_->get<1>(); }
Destroy half-created ZOOM-C result-set on failure, thanks to Phil Dennis <phil@booksys.com>
// $Header: /home/cvsroot/yaz++/zoom/zrs.cpp,v 1.5 2003-07-02 10:25:13 adam Exp $ // Z39.50 Result Set class #include "zoom.h" namespace ZOOM { resultSet::resultSet(connection &c, const query &q) : owner(c) { ZOOM_connection yazc = c._getYazConnection(); rs = ZOOM_connection_search(yazc, q._getYazQuery()); int errcode; const char *errmsg; // unused: carries same info as `errcode' const char *addinfo; if ((errcode = ZOOM_connection_error(yazc, &errmsg, &addinfo)) != 0) { throw bib1Exception(errcode, addinfo); } } resultSet::~resultSet() { ZOOM_resultset_destroy(rs); } std::string resultSet::option(const std::string &key) const { return ZOOM_resultset_option_get(rs, key.c_str()); } bool resultSet::option(const std::string &key, const std::string &val) { ZOOM_resultset_option_set(rs, key.c_str(), val.c_str()); return true; } size_t resultSet::size() const { return ZOOM_resultset_size(rs); } }
// $Header: /home/cvsroot/yaz++/zoom/zrs.cpp,v 1.6 2003-09-22 13:04:52 mike Exp $ // Z39.50 Result Set class #include "zoom.h" namespace ZOOM { resultSet::resultSet(connection &c, const query &q) : owner(c) { ZOOM_connection yazc = c._getYazConnection(); rs = ZOOM_connection_search(yazc, q._getYazQuery()); int errcode; const char *errmsg; // unused: carries same info as `errcode' const char *addinfo; if ((errcode = ZOOM_connection_error(yazc, &errmsg, &addinfo)) != 0) { ZOOM_resultset_destroy(rs); throw bib1Exception(errcode, addinfo); } } resultSet::~resultSet() { ZOOM_resultset_destroy(rs); } std::string resultSet::option(const std::string &key) const { return ZOOM_resultset_option_get(rs, key.c_str()); } bool resultSet::option(const std::string &key, const std::string &val) { ZOOM_resultset_option_set(rs, key.c_str(), val.c_str()); return true; } size_t resultSet::size() const { return ZOOM_resultset_size(rs); } }
Remove superfluous setName(mName) from the c'tor.
// kmfoldernode.cpp #include "kmfolderdir.h" //----------------------------------------------------------------------------- KMFolderNode::KMFolderNode(KMFolderDir* aParent, const QString& aName) //: KMFolderNodeInherited(aParent) { mType = "node"; mName = aName; mParent = aParent; mDir = FALSE; setName(mName); } //----------------------------------------------------------------------------- KMFolderNode::~KMFolderNode() { } //----------------------------------------------------------------------------- const char* KMFolderNode::type(void) const { return mType; } //----------------------------------------------------------------------------- void KMFolderNode::setType(const char* aType) { mType = aType; } //----------------------------------------------------------------------------- bool KMFolderNode::isDir(void) const { return mDir; } //----------------------------------------------------------------------------- QString KMFolderNode::path() const { if (parent()) return parent()->path(); return 0; } //----------------------------------------------------------------------------- QString KMFolderNode::label(void) const { return name(); } //----------------------------------------------------------------------------- KMFolderDir* KMFolderNode::parent(void) const { return mParent; } //----------------------------------------------------------------------------- void KMFolderNode::setParent( KMFolderDir* aParent ) { mParent = aParent; } #include "kmfoldernode.moc"
// kmfoldernode.cpp #include "kmfolderdir.h" //----------------------------------------------------------------------------- KMFolderNode::KMFolderNode(KMFolderDir* aParent, const QString& aName) //: KMFolderNodeInherited(aParent) { mType = "node"; mName = aName; mParent = aParent; mDir = FALSE; } //----------------------------------------------------------------------------- KMFolderNode::~KMFolderNode() { } //----------------------------------------------------------------------------- const char* KMFolderNode::type(void) const { return mType; } //----------------------------------------------------------------------------- void KMFolderNode::setType(const char* aType) { mType = aType; } //----------------------------------------------------------------------------- bool KMFolderNode::isDir(void) const { return mDir; } //----------------------------------------------------------------------------- QString KMFolderNode::path() const { if (parent()) return parent()->path(); return 0; } //----------------------------------------------------------------------------- QString KMFolderNode::label(void) const { return name(); } //----------------------------------------------------------------------------- KMFolderDir* KMFolderNode::parent(void) const { return mParent; } //----------------------------------------------------------------------------- void KMFolderNode::setParent( KMFolderDir* aParent ) { mParent = aParent; } #include "kmfoldernode.moc"
Add solution for Day 2 part two
// Day2.cpp : Defines the entry point for the console application. // #include "stdafx.h" int main() { std::ifstream Input("Input.txt"); if (!Input.is_open()) { std::cout << "Error opening File!" << std::endl; return 0; } std::string Line; uint64_t WrappingPaper = 0; while (std::getline(Input, Line)) { std::stringstream LineStream(Line); uint32_t l; uint32_t h; uint32_t w; LineStream >> l; LineStream.get(); LineStream >> h; LineStream.get(); LineStream >> w; uint32_t Side1 = l * w; uint32_t Side2 = h * w; uint32_t Side3 = l * h; uint32_t SmallestSide = std::min({ Side1, Side2, Side3 }); WrappingPaper += SmallestSide + 2 * Side1 + 2 * Side2 + 2 * Side3; } Input.close(); std::cout << "Wrapping Paper: " << WrappingPaper << std::endl; system("pause"); return 0; }
// Day2.cpp : Defines the entry point for the console application. // #include "stdafx.h" int main() { std::ifstream Input("Input.txt"); if (!Input.is_open()) { std::cout << "Error opening File!" << std::endl; return 0; } std::string Line; uint64_t WrappingPaper = 0; uint64_t Ribbon = 0; while (std::getline(Input, Line)) { std::stringstream LineStream(Line); uint32_t l; uint32_t h; uint32_t w; LineStream >> l; LineStream.get(); LineStream >> h; LineStream.get(); LineStream >> w; uint32_t Side1 = l * w; uint32_t Side2 = h * w; uint32_t Side3 = l * h; uint32_t SmallestSide = std::min({ Side1, Side2, Side3 }); uint32_t LargestDimension = std::max({ l, w, h }); WrappingPaper += SmallestSide + 2 * Side1 + 2 * Side2 + 2 * Side3; Ribbon += l * w * h + 2 * l + 2 * w + 2 * h - 2 * LargestDimension; } Input.close(); std::cout << "Wrapping Paper: " << WrappingPaper << std::endl; std::cout << "Ribbon: " << Ribbon << std::endl; system("pause"); return 0; }
Enable GPIOA in board::lowLevelInitialization() for NUCLEO-F103RB
/** * \file * \brief board::lowLevelInitialization() implementation for NUCLEO-F103RB * * \author Copyright (C) 2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * 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 "distortos/board/lowLevelInitialization.hpp" namespace distortos { namespace board { /*---------------------------------------------------------------------------------------------------------------------+ | global functions +---------------------------------------------------------------------------------------------------------------------*/ void lowLevelInitialization() { } } // namespace board } // namespace distortos
/** * \file * \brief board::lowLevelInitialization() implementation for NUCLEO-F103RB * * \author Copyright (C) 2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * 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 "distortos/board/lowLevelInitialization.hpp" #include "distortos/chip/CMSIS-proxy.h" namespace distortos { namespace board { /*---------------------------------------------------------------------------------------------------------------------+ | global functions +---------------------------------------------------------------------------------------------------------------------*/ void lowLevelInitialization() { RCC->APB2ENR |= #ifdef CONFIG_BOARD_LEDS_ENABLE RCC_APB2ENR_IOPAEN | #endif // def CONFIG_BOARD_LEDS_ENABLE 0; } } // namespace board } // namespace distortos
Use test data with spaces
#include <sstream> #include <gtest/gtest.h> #include <errors.h> #include <iostreamsocket.h> #define TEST_CLASS IOStreamSocketTest #define INIT_DATA ("dat_data_tho") #define INIT_LEN (12) class TEST_CLASS : public testing::Test { protected: TEST_CLASS() : in(INIT_DATA), sock(in, out) { } std::stringstream in, out; IOStreamSocket sock; }; TEST_F(TEST_CLASS, TestRead) { int iret; char *buffer[INIT_LEN+1] = {0}; iret = sock.read(0, INIT_LEN, buffer); ASSERT_EQ(iret, ERR_SUCCESS) << "Read failed"; ASSERT_TRUE(!memcmp(buffer, INIT_DATA, INIT_LEN)) << "Read wrong data(" << buffer << ")"; } TEST_F(TEST_CLASS, TestWrite) { int iret; iret = sock.write(0, INIT_LEN, INIT_DATA); ASSERT_EQ(iret, ERR_SUCCESS) << "Read failed"; const char *actual = out.str().c_str(); ASSERT_TRUE(!memcmp(actual, INIT_DATA, INIT_LEN)) << "Wrote wrong data(" << actual << ")"; }
#include <sstream> #include <gtest/gtest.h> #include <errors.h> #include <iostreamsocket.h> #define TEST_CLASS IOStreamSocketTest #define INIT_DATA ("dat data tho") #define INIT_LEN (12) class TEST_CLASS : public testing::Test { protected: TEST_CLASS() : in(INIT_DATA), sock(in, out) { } std::stringstream in, out; IOStreamSocket sock; }; TEST_F(TEST_CLASS, TestRead) { int iret; char *buffer[INIT_LEN+1] = {0}; iret = sock.read(0, INIT_LEN, buffer); ASSERT_EQ(iret, ERR_SUCCESS) << "Read failed"; ASSERT_TRUE(!memcmp(buffer, INIT_DATA, INIT_LEN)) << "Read wrong data(" << buffer << ")"; } TEST_F(TEST_CLASS, TestWrite) { int iret; iret = sock.write(0, INIT_LEN, INIT_DATA); ASSERT_EQ(iret, ERR_SUCCESS) << "Read failed"; const char *actual = out.str().c_str(); ASSERT_TRUE(!memcmp(actual, INIT_DATA, INIT_LEN)) << "Wrote wrong data(" << actual << ")"; }
Set exit code on quitting.
// External Depdendencies #include "../../../lib/jnipp/jnipp.h" // Module Dependencies #include "../include/app.h" #include "../include/eventqueue.h" namespace native { namespace ui { // Static Variable Initialisations thread_local int EventQueue::_exitCode = 0; bool EventQueue::handleEvent(bool block) { throw NotImplementedException(); } void EventQueue::quitWithCode(int exitCode) { jni::Object* activity = (jni::Object*) App::getAppHandle(); activity->call<void>("finish"); } } }
// External Depdendencies #include "../../../lib/jnipp/jnipp.h" // Module Dependencies #include "../include/app.h" #include "../include/eventqueue.h" namespace native { namespace ui { // Static Variable Initialisations thread_local int EventQueue::_exitCode = 0; bool EventQueue::handleEvent(bool block) { throw NotImplementedException(); } void EventQueue::quitWithCode(int exitCode) { jni::Object* activity = (jni::Object*) App::getAppHandle(); _exitCode = exitCode; activity->call<void>("finish"); } } }
Enable bump with turbo by default
#include "gflags/gflags.h" DEFINE_string(race_id, "", ""); DEFINE_bool(continuous_integration, true, ""); DEFINE_double(safe_angle, 60.0, ""); DEFINE_int32(handicap, 0, ""); DEFINE_bool(check_if_safe_ahead, true, ""); DEFINE_int32(answer_time, 10, "Time limit for answer in ms"); DEFINE_bool(bump_with_turbo, false, "kamikazebumps"); DEFINE_bool(defend_turbo_bump, false, "Defend against people that have bump_with_turbo");
#include "gflags/gflags.h" DEFINE_string(race_id, "", ""); DEFINE_bool(continuous_integration, true, ""); DEFINE_double(safe_angle, 60.0, ""); DEFINE_int32(handicap, 0, ""); DEFINE_bool(check_if_safe_ahead, true, ""); DEFINE_int32(answer_time, 10, "Time limit for answer in ms"); DEFINE_bool(bump_with_turbo, true, "kamikazebumps"); DEFINE_bool(defend_turbo_bump, false, "Defend against people that have bump_with_turbo");
Change the stub for file_util::EvictFileFromSystemCache
// Copyright (c) 2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/test_file_util.h" #include "base/logging.h" namespace file_util { bool EvictFileFromSystemCache(const FilePath& file) { // TODO(port): Implement. NOTIMPLEMENTED(); return false; } } // namespace file_util
// Copyright (c) 2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/test_file_util.h" #include "base/logging.h" namespace file_util { bool EvictFileFromSystemCache(const FilePath& file) { // There is no way that we can think of to dump something from the UBC. You // can add something so when you open it, it doesn't go in, but that won't // work here. return true; } } // namespace file_util
Disable ExtensionApiTest.JavaScriptURLPermissions, it flakily hits an assertion.
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "net/base/mock_host_resolver.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, JavaScriptURLPermissions) { host_resolver()->AddRule("a.com", "127.0.0.1"); host_resolver()->AddRule("b.com", "127.0.0.1"); ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("tabs/javascript_url_permissions")) << message_; }
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "net/base/mock_host_resolver.h" // Disabled, http://crbug.com/63589. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_JavaScriptURLPermissions) { host_resolver()->AddRule("a.com", "127.0.0.1"); host_resolver()->AddRule("b.com", "127.0.0.1"); ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("tabs/javascript_url_permissions")) << message_; }
Fix resizing for arbitrary lookup tables
// // TableLookupOsc.cpp // Tonic // // Created by Nick Donaldson on 2/8/13. // #include "TableLookupOsc.h" namespace Tonic { namespace Tonic_{ TableLookupOsc_::TableLookupOsc_() : phase_(0.0) { modFrames_.resize(kSynthesisBlockSize, 1); lookupTable_ = SampleTable(kSynthesisBlockSize,1); } void TableLookupOsc_::reset(){ phase_ = 0.0f; } void TableLookupOsc_::setLookupTable(SampleTable table){ if (table.channels() != 1){ error("TableLookupOsc expects lookup table with 1 channel only"); return; } unsigned int nearestPo2; if (!isPowerOf2(table.size()-1, &nearestPo2)){ warning("TableLookUpOsc lookup tables must have a (power-of-two + 1) number of samples (example 2049 or 4097). Resizing to nearest power-of-two + 1"); // TODO: This will just lop off samples or add silence. Don't want to do that. table.resample(nearestPo2+1, 1); } lookupTable_ = table; } } // Namespace Tonic_ TableLookupOsc & TableLookupOsc::setLookupTable(SampleTable lookupTable){ gen()->setLookupTable(lookupTable); return *this; } } // Namespace Tonic
// // TableLookupOsc.cpp // Tonic // // Created by Nick Donaldson on 2/8/13. // #include "TableLookupOsc.h" namespace Tonic { namespace Tonic_{ TableLookupOsc_::TableLookupOsc_() : phase_(0.0) { modFrames_.resize(kSynthesisBlockSize, 1); lookupTable_ = SampleTable(kSynthesisBlockSize,1); } void TableLookupOsc_::reset(){ phase_ = 0.0f; } void TableLookupOsc_::setLookupTable(SampleTable table){ if (table.channels() != 1){ error("TableLookupOsc expects lookup table with 1 channel only"); return; } unsigned int nearestPo2; if (!isPowerOf2(table.size()-1, &nearestPo2)){ warning("TableLookUpOsc lookup tables must have a (power-of-two + 1) number of samples (example 2049 or 4097). Resizing to nearest power-of-two + 1"); table.resample(nearestPo2, 1); table.resize(nearestPo2+1, 1); table.dataPointer()[nearestPo2] = table.dataPointer()[0]; // copy first sample to last } lookupTable_ = table; } } // Namespace Tonic_ TableLookupOsc & TableLookupOsc::setLookupTable(SampleTable lookupTable){ gen()->setLookupTable(lookupTable); return *this; } } // Namespace Tonic
Remove names of unused variables
//Copyright (c) 2018 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include "MockSocket.h" namespace cura { MockSocket::MockSocket() { } void MockSocket::connect(const std::string& address, int port) { /* Do nothing. */ } void MockSocket::listen(const std::string& address, int port) { /* Do nothing. */ } void MockSocket::close() { /* Do nothing. */ } void MockSocket::reset() { /* Do nothing. */ } void MockSocket::sendMessage(Arcus::MessagePtr message) { sent_messages.push_back(message); } Arcus::MessagePtr MockSocket::takeNextMessage() { Arcus::MessagePtr result = received_messages.front(); received_messages.pop_front(); return result; } void MockSocket::pushMessageToReceivedQueue(Arcus::MessagePtr message) { received_messages.push_back(message); } Arcus::MessagePtr MockSocket::popMessageFromSendQueue() { Arcus::MessagePtr result = sent_messages.front(); sent_messages.pop_front(); return result; } } //namespace cura
//Copyright (c) 2018 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include "MockSocket.h" namespace cura { MockSocket::MockSocket() { } void MockSocket::connect(const std::string&, int) { /* Do nothing. */ } void MockSocket::listen(const std::string&, int) { /* Do nothing. */ } void MockSocket::close() { /* Do nothing. */ } void MockSocket::reset() { /* Do nothing. */ } void MockSocket::sendMessage(Arcus::MessagePtr message) { sent_messages.push_back(message); } Arcus::MessagePtr MockSocket::takeNextMessage() { Arcus::MessagePtr result = received_messages.front(); received_messages.pop_front(); return result; } void MockSocket::pushMessageToReceivedQueue(Arcus::MessagePtr message) { received_messages.push_back(message); } Arcus::MessagePtr MockSocket::popMessageFromSendQueue() { Arcus::MessagePtr result = sent_messages.front(); sent_messages.pop_front(); return result; } } //namespace cura
Fix invalid inline because get pointer
#include "ros/ros.h" #include "servo_msgs/KrsServoDegree.h" #include "krs_servo_driver.hpp" class KrsServoNode { public: KrsServoNode(); explicit KrsServoNode(ros::NodeHandle& nh); private: void krsServoDegreeCallback(const servo_msgs::KrsServoDegree::ConstPtr& msg); ros::Subscriber sub; KrsServoDriver krs; }; KrsServoNode::KrsServoNode() : krs() {} KrsServoNode::KrsServoNode(ros::NodeHandle& nh) : krs() { sub = nh.subscribe("cmd_krs", 16, &KrsServoNode::krsServoDegreeCallback, this); } inline void KrsServoNode::krsServoDegreeCallback(const servo_msgs::KrsServoDegree::ConstPtr& msg) { krs.sendAngle(msg->id, msg->angle); } int main(int argc, char** argv) { ros::init(argc, argv, "krs_servo_node"); ros::NodeHandle nh; KrsServoNode ksn(nh); ros::spin(); return 0; }
#include "ros/ros.h" #include "servo_msgs/KrsServoDegree.h" #include "krs_servo_driver.hpp" class KrsServoNode { public: KrsServoNode(); explicit KrsServoNode(ros::NodeHandle& nh); private: void krsServoDegreeCallback(const servo_msgs::KrsServoDegree::ConstPtr& msg); ros::Subscriber sub; KrsServoDriver krs; }; KrsServoNode::KrsServoNode() : krs() {} KrsServoNode::KrsServoNode(ros::NodeHandle& nh) : krs() { sub = nh.subscribe("cmd_krs", 16, &KrsServoNode::krsServoDegreeCallback, this); } void KrsServoNode::krsServoDegreeCallback(const servo_msgs::KrsServoDegree::ConstPtr& msg) { krs.sendAngle(msg->id, msg->angle); } int main(int argc, char** argv) { ros::init(argc, argv, "krs_servo_node"); ros::NodeHandle nh; KrsServoNode ksn(nh); ros::spin(); return 0; }
Remove erroneous DCHECK from KeyEventTracker
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/protocol/key_event_tracker.h" #include "base/logging.h" #include "remoting/proto/event.pb.h" namespace remoting { namespace protocol { KeyEventTracker::KeyEventTracker(InputStub* input_stub) : input_stub_(input_stub) { } KeyEventTracker::~KeyEventTracker() { DCHECK(pressed_keys_.empty()); } void KeyEventTracker::InjectKeyEvent(const KeyEvent& event) { DCHECK(event.has_pressed()); DCHECK(event.has_keycode()); if (event.pressed()) { pressed_keys_.insert(event.keycode()); } else { pressed_keys_.erase(event.keycode()); } input_stub_->InjectKeyEvent(event); } void KeyEventTracker::InjectMouseEvent(const MouseEvent& event) { input_stub_->InjectMouseEvent(event); } void KeyEventTracker::ReleaseAllKeys() { std::set<int>::iterator i; for (i = pressed_keys_.begin(); i != pressed_keys_.end(); ++i) { KeyEvent event; event.set_keycode(*i); event.set_pressed(false); input_stub_->InjectKeyEvent(event); } pressed_keys_.clear(); } } // namespace protocol } // namespace remoting
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/protocol/key_event_tracker.h" #include "base/logging.h" #include "remoting/proto/event.pb.h" namespace remoting { namespace protocol { KeyEventTracker::KeyEventTracker(InputStub* input_stub) : input_stub_(input_stub) { } KeyEventTracker::~KeyEventTracker() { } void KeyEventTracker::InjectKeyEvent(const KeyEvent& event) { DCHECK(event.has_pressed()); DCHECK(event.has_keycode()); if (event.pressed()) { pressed_keys_.insert(event.keycode()); } else { pressed_keys_.erase(event.keycode()); } input_stub_->InjectKeyEvent(event); } void KeyEventTracker::InjectMouseEvent(const MouseEvent& event) { input_stub_->InjectMouseEvent(event); } void KeyEventTracker::ReleaseAllKeys() { std::set<int>::iterator i; for (i = pressed_keys_.begin(); i != pressed_keys_.end(); ++i) { KeyEvent event; event.set_keycode(*i); event.set_pressed(false); input_stub_->InjectKeyEvent(event); } pressed_keys_.clear(); } } // namespace protocol } // namespace remoting
Validate the executor as part of the test
#include <agency/new_executor_traits.hpp> #include <cassert> #include <iostream> #include "test_executors.hpp" template<class Executor> void test() { using executor_type = Executor; { // returning void executor_type exec; int set_me_to_thirteen = 0; auto f = agency::new_executor_traits<executor_type>::async_execute(exec, [&] { set_me_to_thirteen = 13; }); f.wait(); assert(set_me_to_thirteen == 13); } { // returning int executor_type exec; auto f = agency::new_executor_traits<executor_type>::async_execute(exec, [] { return 13; }); assert(f.get() == 13); } } int main() { using namespace test_executors; test<empty_executor>(); test<single_agent_when_all_execute_and_select_executor>(); test<multi_agent_when_all_execute_and_select_executor>(); test<single_agent_then_execute_executor>(); test<multi_agent_execute_returning_user_defined_container_executor>(); test<multi_agent_execute_returning_default_container_executor>(); test<multi_agent_execute_returning_void_executor>(); std::cout << "OK" << std::endl; return 0; }
#include <agency/new_executor_traits.hpp> #include <cassert> #include <iostream> #include "test_executors.hpp" template<class Executor> void test() { using executor_type = Executor; { // returning void executor_type exec; int set_me_to_thirteen = 0; auto f = agency::new_executor_traits<executor_type>::async_execute(exec, [&] { set_me_to_thirteen = 13; }); f.wait(); assert(set_me_to_thirteen == 13); assert(exec.valid()); } { // returning int executor_type exec; auto f = agency::new_executor_traits<executor_type>::async_execute(exec, [] { return 13; }); assert(f.get() == 13); assert(exec.valid()); } } int main() { using namespace test_executors; test<empty_executor>(); test<single_agent_when_all_execute_and_select_executor>(); test<multi_agent_when_all_execute_and_select_executor>(); test<single_agent_then_execute_executor>(); test<multi_agent_execute_returning_user_defined_container_executor>(); test<multi_agent_execute_returning_default_container_executor>(); test<multi_agent_execute_returning_void_executor>(); std::cout << "OK" << std::endl; return 0; }
Remove the switches kSilentDumpOnDCHECK and kMemoryProfiling from NaCl and broker processes.
// 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 "base/basictypes.h" #include "base/command_line.h" #include "chrome/common/chrome_switches.h" namespace nacl { void CopyNaClCommandLineArguments(CommandLine* cmd_line) { const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess(); // Propagate the following switches to the NaCl loader command line (along // with any associated values) if present in the browser command line. // TODO(gregoryd): check which flags of those below can be supported. static const char* const kSwitchNames[] = { switches::kNoSandbox, switches::kTestNaClSandbox, switches::kDisableBreakpad, switches::kFullMemoryCrashReport, switches::kEnableLogging, switches::kDisableLogging, switches::kLoggingLevel, switches::kEnableDCHECK, switches::kSilentDumpOnDCHECK, switches::kMemoryProfiling, switches::kNoErrorDialogs, #if defined(OS_MACOSX) switches::kEnableSandboxLogging, #endif }; cmd_line->CopySwitchesFrom(browser_command_line, kSwitchNames, arraysize(kSwitchNames)); } } // namespace nacl
// 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 "base/basictypes.h" #include "base/command_line.h" #include "chrome/common/chrome_switches.h" namespace nacl { void CopyNaClCommandLineArguments(CommandLine* cmd_line) { const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess(); // Propagate the following switches to the NaCl loader command line (along // with any associated values) if present in the browser command line. // TODO(gregoryd): check which flags of those below can be supported. static const char* const kSwitchNames[] = { switches::kNoSandbox, switches::kTestNaClSandbox, switches::kDisableBreakpad, switches::kFullMemoryCrashReport, switches::kEnableLogging, switches::kDisableLogging, switches::kLoggingLevel, switches::kEnableDCHECK, switches::kNoErrorDialogs, #if defined(OS_MACOSX) switches::kEnableSandboxLogging, #endif }; cmd_line->CopySwitchesFrom(browser_command_line, kSwitchNames, arraysize(kSwitchNames)); } } // namespace nacl
Fix line numbers for code inlined from __nodebug__ functions.
// RUN: %clangxx_msan -m64 -O0 %s -o %t && %run %t // RUN: %clangxx_msan -DPOSITIVE -m64 -O0 %s -o %t && not %run %t 2>&1 | FileCheck %s #include <emmintrin.h> int to_int(double v) { __m128d t = _mm_set_sd(v); int x = _mm_cvtsd_si32(t); return x; // CHECK: WARNING: MemorySanitizer: use-of-uninitialized-value // CHECK: #{{.*}} in to_int{{.*}}vector_cvt.cc:[[@LINE-4]] } int main() { #ifdef POSITIVE double v; #else double v = 1.1; #endif double* volatile p = &v; int x = to_int(*p); return !x; }
// RUN: %clangxx_msan -m64 -O0 %s -o %t && %run %t // RUN: %clangxx_msan -DPOSITIVE -m64 -O0 %s -o %t && not %run %t 2>&1 | FileCheck %s #include <emmintrin.h> int to_int(double v) { __m128d t = _mm_set_sd(v); int x = _mm_cvtsd_si32(t); return x; // CHECK: WARNING: MemorySanitizer: use-of-uninitialized-value // CHECK: #{{.*}} in to_int{{.*}}vector_cvt.cc:[[@LINE-3]] } int main() { #ifdef POSITIVE double v; #else double v = 1.1; #endif double* volatile p = &v; int x = to_int(*p); return !x; }
Disable WindowOpenPanelTest.WindowOpenFocus on Windows debug builds.
// 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 "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" class WindowOpenPanelTest : public ExtensionApiTest { void SetUpCommandLine(base::CommandLine* command_line) override { ExtensionApiTest::SetUpCommandLine(command_line); command_line->AppendSwitch(switches::kEnablePanels); } }; // http://crbug.com/253417 for NDEBUG #if defined(OS_WIN) || (defined(OS_MACOSX) && defined(NDEBUG)) // Focus test fails if there is no window manager on Linux. IN_PROC_BROWSER_TEST_F(WindowOpenPanelTest, WindowOpenFocus) { ASSERT_TRUE(RunExtensionTest("window_open/focus")) << message_; } #endif
// 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 "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" class WindowOpenPanelTest : public ExtensionApiTest { void SetUpCommandLine(base::CommandLine* command_line) override { ExtensionApiTest::SetUpCommandLine(command_line); command_line->AppendSwitch(switches::kEnablePanels); } }; // http://crbug.com/253417 for NDEBUG #if (defined(OS_WIN) || defined(OS_MACOSX)) && defined(NDEBUG) // Focus test fails if there is no window manager on Linux. IN_PROC_BROWSER_TEST_F(WindowOpenPanelTest, WindowOpenFocus) { ASSERT_TRUE(RunExtensionTest("window_open/focus")) << message_; } #endif
Support high-dpi screens in Windows
#include "mainwindow.h" #include <QApplication> QString _defaultPathAudio = ""; QString _defaultPathProjects = ""; QString _defaultPathOutput = ""; int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }
#include "mainwindow.h" #include <QApplication> QString _defaultPathAudio = ""; QString _defaultPathProjects = ""; QString _defaultPathOutput = ""; int main(int argc, char *argv[]) { QApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::Round); QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }
Increase portability of xalloc test
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // <ios> // class ios_base // static int xalloc(); #include <ios> #include <cassert> int main(int, char**) { assert(std::ios_base::xalloc() == 0); assert(std::ios_base::xalloc() == 1); assert(std::ios_base::xalloc() == 2); assert(std::ios_base::xalloc() == 3); assert(std::ios_base::xalloc() == 4); return 0; }
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // <ios> // class ios_base // static int xalloc(); #include <ios> #include <cassert> int main(int, char**) { int index = std::ios_base::xalloc(); for (int i = 0; i < 10000; ++i) assert(std::ios_base::xalloc() == ++index); return 0; }
Disable test in C++<11 mode due to use of alignas.
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // <memory> // template <class T> // pair<T*, ptrdiff_t> // get_temporary_buffer(ptrdiff_t n); // // template <class T> // void // return_temporary_buffer(T* p); #include <memory> #include <cassert> struct alignas(32) A { int field; }; int main() { std::pair<A*, std::ptrdiff_t> ip = std::get_temporary_buffer<A>(5); assert(!(ip.first == nullptr) ^ (ip.second == 0)); assert(reinterpret_cast<uintptr_t>(ip.first) % alignof(A) == 0); std::return_temporary_buffer(ip.first); }
//===----------------------------------------------------------------------===// // // 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 // <memory> // template <class T> // pair<T*, ptrdiff_t> // get_temporary_buffer(ptrdiff_t n); // // template <class T> // void // return_temporary_buffer(T* p); #include <memory> #include <cassert> struct alignas(32) A { int field; }; int main() { std::pair<A*, std::ptrdiff_t> ip = std::get_temporary_buffer<A>(5); assert(!(ip.first == nullptr) ^ (ip.second == 0)); assert(reinterpret_cast<uintptr_t>(ip.first) % alignof(A) == 0); std::return_temporary_buffer(ip.first); }
Add comparison to "real" value.
/** @file.cc * π approximation */ #include <iostream> #include <random> /** Approximate π in a number of runs. * @param N the number of runs * @param rng the random number generator used * @return an approximation of π */ double ApproximatePi(const size_t N, std::mt19937 &rng) { static std::uniform_real_distribution<double> dist(0.0, 1.0); size_t i, n = 0; double x, y; for (i = 0; i < N; i++) { x = dist(rng); y = dist(rng); if (x * x + y * y <= 1) { ++n; } } return 4.0 * n / N; } /** Main. */ int main(int argc, char *argv[]) { std::random_device rd; std::mt19937 rng(rd()); std::cout << "π = " << ApproximatePi(10000000, rng) << std::endl; }
/** @file.cc * π approximation */ #include <cmath> #include <iomanip> #include <iostream> #include <random> /** Approximate π in a number of runs. * @param N the number of runs * @param rng the random number generator used * @return an approximation of π */ double ApproximatePi(const size_t N, std::mt19937 &rng) { static std::uniform_real_distribution<double> dist(0.0, 1.0); size_t i, n = 0; double x, y; for (i = 0; i < N; i++) { x = dist(rng); y = dist(rng); if (x * x + y * y <= 1) { ++n; } } return 4.0 * n / N; } /** Main. */ int main(int argc, char *argv[]) { std::random_device rd; std::mt19937 rng(rd()); double pi = ApproximatePi(10000000, rng); std::cout << std::setprecision(20) << " π = " << pi << std::endl << "π - π = " << pi - M_PI << std::endl; }
Set logging level based on build
/** * Tower Defence Pro #005 * (C) 2010 - Samuel Andersson, Björn Ekberg */ #ifdef _WIN32 #define _CRTDBG_MAP_ALLOC #include <cstdlib> #include <crtdbg.h> #endif #include <Core/Game.h> #include <Core/GameEngine.h> #include <ctime> #include <memory> #include <Utils/Log.h> int main(int argc, char *argv[]) { /** Seed srand() */ time_t t; time(&t); srand((unsigned int) t); Log::reportingLevel() = logDEBUG; FILE* logFd; fopen_s(&logFd, "output.log", "w"); Output2FILE::stream() = logFd; int ret = 0; Game* game = new Game(); { GameSettings settings; settings.WindowWidth = WWIDTH; settings.WindowHeight = WHEIGHT; settings.WindowTitle = "Tower Defence Pro " + std::string(VERSION) + " © 2010 - 2016 A15 Entertainment"; GameEngine engine(settings); ret = engine.run(game); } delete game; #ifdef _WIN32 _CrtDumpMemoryLeaks(); #endif return ret; }
/** * Tower Defence Pro #005 * (C) 2010 - Samuel Andersson, Björn Ekberg */ #if defined(_WIN32) && (_DEBUG) #define _CRTDBG_MAP_ALLOC #include <cstdlib> #include <crtdbg.h> #endif #include <Core/Game.h> #include <Core/GameEngine.h> #include <ctime> #include <memory> #include <Utils/Log.h> int main(int argc, char *argv[]) { /** Seed srand() */ time_t t; time(&t); srand((unsigned int) t); #ifdef _DEBUG Log::reportingLevel() = logDEBUG; #else Log::reportingLevel() = logWARNING; #endif FILE* logFd; fopen_s(&logFd, "log.txt", "w"); Output2FILE::stream() = logFd; int ret = 0; Game* game = new Game(); { GameSettings settings; settings.WindowWidth = WWIDTH; settings.WindowHeight = WHEIGHT; settings.WindowTitle = "Tower Defence Pro " + std::string(VERSION) + " © 2010 - 2016 A15 Entertainment"; GameEngine engine(settings); ret = engine.run(game); } delete game; #if defined(_WIN32) && defined (_DEBUG) _CrtDumpMemoryLeaks(); #endif return ret; }
Throw runtime_error if Test::SetUp fails to open connection to server
/***************************************************************************** * * utouch-frame - Touch Frame Library * * Copyright (C) 2011 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "xorg/gtest/test.h" #include <X11/Xlib.h> struct xorg::testing::Test::Private { ::Display* display; }; xorg::testing::Test::Test() : d_(new Private) { d_->display = NULL; } void xorg::testing::Test::SetUp() { d_->display = XOpenDisplay(NULL); ASSERT_TRUE(d_->display != NULL) << "Failed to open connection to display"; } void xorg::testing::Test::TearDown() { XCloseDisplay(d_->display); d_->display = NULL; } ::Display* xorg::testing::Test::Display() const { return d_->display; }
/***************************************************************************** * * utouch-frame - Touch Frame Library * * Copyright (C) 2011 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "xorg/gtest/test.h" #include <stdexcept> #include <X11/Xlib.h> struct xorg::testing::Test::Private { ::Display* display; }; xorg::testing::Test::Test() : d_(new Private) { d_->display = NULL; } void xorg::testing::Test::SetUp() { d_->display = XOpenDisplay(NULL); if (!d_->display) throw std::runtime_error("Failed to open connection to display"); } void xorg::testing::Test::TearDown() { XCloseDisplay(d_->display); d_->display = NULL; } ::Display* xorg::testing::Test::Display() const { return d_->display; }
Revert "[asan] Disable test on powerpc64be"
// RUN: %clangxx_asan -fno-rtti -DBUILD_SO1 -fPIC -shared %s -o %dynamiclib1 // RUN: %clangxx_asan -fno-rtti -DBUILD_SO2 -fPIC -shared %s -o %dynamiclib2 // RUN: %clangxx_asan -fno-rtti %s %ld_flags_rpath_exe1 %ld_flags_rpath_exe2 -o %t // RUN: %env_asan_opts=fast_unwind_on_malloc=0:detect_odr_violation=2 not %run %t 2>&1 | FileCheck %s // FIXME: Somehow does not detect ODR on powerpc64be // XFAIL: powerpc64 struct XYZ { virtual void foo(); }; #if defined(BUILD_SO1) void XYZ::foo() {} #elif defined(BUILD_SO2) void XYZ::foo() {} #else int main() {} #endif // CHECK: AddressSanitizer: odr-violation // CHECK-NEXT: 'vtable for XYZ' // CHECK-NEXT: 'vtable for XYZ'
// RUN: %clangxx_asan -fno-rtti -DBUILD_SO1 -fPIC -shared %s -o %dynamiclib1 // RUN: %clangxx_asan -fno-rtti -DBUILD_SO2 -fPIC -shared %s -o %dynamiclib2 // RUN: %clangxx_asan -fno-rtti %s %ld_flags_rpath_exe1 %ld_flags_rpath_exe2 -o %t // RUN: %env_asan_opts=fast_unwind_on_malloc=0:detect_odr_violation=2 not %run %t 2>&1 | FileCheck %s struct XYZ { virtual void foo(); }; #if defined(BUILD_SO1) void XYZ::foo() {} #elif defined(BUILD_SO2) void XYZ::foo() {} #else int main() {} #endif // CHECK: AddressSanitizer: odr-violation // CHECK-NEXT: 'vtable for XYZ' // CHECK-NEXT: 'vtable for XYZ'
Enable image input from console
#include <iostream> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include "edges.hpp" #include "sharpen.hpp" int main() { cv::Mat image(cv::imread("swiss.jpg")); cv::Mat edges; //std::cout << image.channels() << std::endl; findEdges(image, edges); cv::imshow("nyc.jpg", image); cv::imshow("Edges of nyc.jpg", edges); cv::waitKey(0); return 0; }
#include <iostream> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include "edges.hpp" #include "sharpen.hpp" int main(int argc, char* argv[]) { if(argc < 2) { std::cerr << "Please enter the name of the image file in which to find edges." << std::endl; return 0; } std::string imageFile(argv[1]); cv::Mat image(cv::imread(imageFile)); if(image.rows == 0 || image.cols == 0) { std::cerr << "Please enter a valid image file." << std::endl; return 0; } cv::Mat edges; // blank image findEdges(image, edges); // show before & after cv::imshow(imageFile, image); cv::imshow("Edges of " + imageFile, edges); // convert & save image to file edges.convertTo(edges, CV_8UC1, 255.0); cv::imwrite("edges." + imageFile, edges); // wait cv::waitKey(0); return 0; }
Change the baudrate according to the CmdMessenger Receive example
#include <iostream> #include "CmdMessenger.h" using namespace std; enum { ksetled }; int main(int argc, char *argv[]) { if(argc == 2){ char op; cmd::CmdMessenger arduino(argv[1], 9600); cmd::Cmd led(ksetled); cmd::Timeout timeout = cmd::Timeout::simpleTimeout(1000); arduino.setTimeout(timeout); while(true) { cout << "'1' turns on, '0' turns off, 'q' quits: "; cin >> op; cout << endl; switch(op) { case '1': led << true << CmdEnd(); arduino.send(led); cout << led.getNumArgs() << endl; led.clear(); break; case '0': led << false << CmdEnd(); arduino.send(led); led.clear(); break; case 'q': break; } if(op == 'q') break; cout << "feeding in serial data\n"; arduino.feedInSerialData(); } } else { cout << "Usage: led 'port_name'\n"; } return 0; }
#include <iostream> #include "CmdMessenger.h" using namespace std; enum { ksetled }; int main(int argc, char *argv[]) { if(argc == 2){ char op; cmd::CmdMessenger arduino(argv[1], 115200); cmd::Cmd led(ksetled); cmd::Timeout timeout = cmd::Timeout::simpleTimeout(1000); arduino.setTimeout(timeout); while(true) { cout << "'1' turns on, '0' turns off, 'q' quits: "; cin >> op; cout << endl; switch(op) { case '1': led << true << CmdEnd(); arduino.send(led); cout << led.getNumArgs() << endl; led.clear(); break; case '0': led << false << CmdEnd(); arduino.send(led); led.clear(); break; case 'q': break; } if(op == 'q') break; cout << "feeding in serial data\n"; arduino.feedInSerialData(); } } else { cout << "Usage: led 'port_name'\n"; } return 0; }
Initialize target_message_loop_ in the constructor.
// 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/icon_loader.h" #include "base/message_loop.h" #include "base/mime_util.h" #include "base/thread.h" #include "chrome/browser/browser_process.h" #include "third_party/skia/include/core/SkBitmap.h" IconLoader::IconLoader(const IconGroupID& group, IconSize size, Delegate* delegate) : group_(group), icon_size_(size), bitmap_(NULL), delegate_(delegate) { } IconLoader::~IconLoader() { delete bitmap_; } void IconLoader::Start() { target_message_loop_ = MessageLoop::current(); #if defined(OS_LINUX) // This call must happen on the UI thread before we can start loading icons. mime_util::DetectGtkTheme(); #endif g_browser_process->file_thread()->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(this, &IconLoader::ReadIcon)); } void IconLoader::NotifyDelegate() { if (delegate_->OnBitmapLoaded(this, bitmap_)) bitmap_ = NULL; }
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/icon_loader.h" #include "base/message_loop.h" #include "base/mime_util.h" #include "base/thread.h" #include "chrome/browser/browser_process.h" #include "third_party/skia/include/core/SkBitmap.h" IconLoader::IconLoader(const IconGroupID& group, IconSize size, Delegate* delegate) : target_message_loop_(NULL), group_(group), icon_size_(size), bitmap_(NULL), delegate_(delegate) { } IconLoader::~IconLoader() { delete bitmap_; } void IconLoader::Start() { target_message_loop_ = MessageLoop::current(); #if defined(OS_LINUX) // This call must happen on the UI thread before we can start loading icons. mime_util::DetectGtkTheme(); #endif g_browser_process->file_thread()->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(this, &IconLoader::ReadIcon)); } void IconLoader::NotifyDelegate() { if (delegate_->OnBitmapLoaded(this, bitmap_)) bitmap_ = NULL; }
Update the sensord config test
#include <sensormanagerinterface.h> #include <datatypes/magneticfield.h> int main() { SensorManagerInterface* m_remoteSensorManager; m_remoteSensorManager = &SensorManagerInterface::instance(); return 0; }
#include <sensormanagerinterface.h> #include <datatypes/magneticfield.h> #include <abstractsensor.h> #include <abstractsensor_i.h> int main() { SensorManagerInterface* m_remoteSensorManager; m_remoteSensorManager = &SensorManagerInterface::instance(); QList<DataRange> (AbstractSensorChannelInterface::*func)() = &AbstractSensorChannelInterface::getAvailableIntervals; return 0; }
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(); }
Update SHA1_IA32 to use compress_n
/************************************************* * SHA-160 (IA-32) Source File * * (C) 1999-2007 Jack Lloyd * *************************************************/ #include <botan/sha1_ia32.h> #include <botan/loadstor.h> namespace Botan { namespace { extern "C" void botan_sha160_ia32_compress(u32bit[5], const byte[64], u32bit[81]); } /************************************************* * SHA-160 Compression Function * *************************************************/ void SHA_160_IA32::hash(const byte input[]) { botan_sha160_ia32_compress(digest, input, W); } }
/************************************************* * SHA-160 (IA-32) Source File * * (C) 1999-2007 Jack Lloyd * *************************************************/ #include <botan/sha1_ia32.h> #include <botan/loadstor.h> namespace Botan { namespace { extern "C" void botan_sha160_ia32_compress(u32bit[5], const byte[64], u32bit[81]); } /************************************************* * SHA-160 Compression Function * *************************************************/ void SHA_160_IA32::compress_n(const byte input[], u32bit blocks) { for(u32bit i = 0; i != blocks; ++i) { botan_sha160_ia32_compress(digest, input, W); input += HASH_BLOCK_SIZE; } } }
Convert sandbox NOTIMPLEMENTED()s into a bug.
// 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_main_platform_delegate.h" #include "base/debug_util.h" // This is a no op class because we do not have a sandbox on linux. RendererMainPlatformDelegate::RendererMainPlatformDelegate( const MainFunctionParams& parameters) : parameters_(parameters) { } RendererMainPlatformDelegate::~RendererMainPlatformDelegate() { } void RendererMainPlatformDelegate::PlatformInitialize() { } void RendererMainPlatformDelegate::PlatformUninitialize() { } bool RendererMainPlatformDelegate::InitSandboxTests(bool no_sandbox) { NOTIMPLEMENTED(); return true; } bool RendererMainPlatformDelegate::EnableSandbox() { NOTIMPLEMENTED(); return true; } void RendererMainPlatformDelegate::RunSandboxTests() { 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_main_platform_delegate.h" #include "base/debug_util.h" // This is a no op class because we do not have a sandbox on linux. RendererMainPlatformDelegate::RendererMainPlatformDelegate( const MainFunctionParams& parameters) : parameters_(parameters) { } RendererMainPlatformDelegate::~RendererMainPlatformDelegate() { } void RendererMainPlatformDelegate::PlatformInitialize() { } void RendererMainPlatformDelegate::PlatformUninitialize() { } bool RendererMainPlatformDelegate::InitSandboxTests(bool no_sandbox) { // We have no sandbox. // http://code.google.com/p/chromium/issues/detail?id=8081 return true; } bool RendererMainPlatformDelegate::EnableSandbox() { // We have no sandbox. // http://code.google.com/p/chromium/issues/detail?id=8081 return true; } void RendererMainPlatformDelegate::RunSandboxTests() { // We have no sandbox. // http://code.google.com/p/chromium/issues/detail?id=8081 }
Make the storing variable's name generic.
// RUN: %clang_cc1 -emit-llvm -o - -triple x86_64-apple-darwin %s | FileCheck %s // <rdar://problem/11043589> struct Length { Length(double v) { m_floatValue = static_cast<float>(v); } bool operator==(const Length& o) const { return getFloatValue() == o.getFloatValue(); } bool operator!=(const Length& o) const { return !(*this == o); } private: float getFloatValue() const { return m_floatValue; } float m_floatValue; }; struct Foo { static Length inchLength(double inch); static bool getPageSizeFromName(const Length &A) { static const Length legalWidth = inchLength(8.5); if (A != legalWidth) return true; return false; } }; // CHECK: @_ZZN3Foo19getPageSizeFromNameERK6LengthE10legalWidth = linkonce_odr global %struct.Length zeroinitializer, align 4 // CHECK: store float %call, float* getelementptr inbounds (%struct.Length* @_ZZN3Foo19getPageSizeFromNameERK6LengthE10legalWidth, i32 0, i32 0), align 1 bool bar(Length &b) { Foo f; return f.getPageSizeFromName(b); }
// RUN: %clang_cc1 -emit-llvm -o - -triple x86_64-apple-darwin %s | FileCheck %s // <rdar://problem/11043589> struct Length { Length(double v) { m_floatValue = static_cast<float>(v); } bool operator==(const Length& o) const { return getFloatValue() == o.getFloatValue(); } bool operator!=(const Length& o) const { return !(*this == o); } private: float getFloatValue() const { return m_floatValue; } float m_floatValue; }; struct Foo { static Length inchLength(double inch); static bool getPageSizeFromName(const Length &A) { static const Length legalWidth = inchLength(8.5); if (A != legalWidth) return true; return false; } }; // CHECK: @_ZZN3Foo19getPageSizeFromNameERK6LengthE10legalWidth = linkonce_odr global %struct.Length zeroinitializer, align 4 // CHECK: store float %{{.*}}, float* getelementptr inbounds (%struct.Length* @_ZZN3Foo19getPageSizeFromNameERK6LengthE10legalWidth, i32 0, i32 0), align 1 bool bar(Length &b) { Foo f; return f.getPageSizeFromName(b); }
Print JSON in tree format.
#include "vast/sink/json.h" #include "vast/util/json.h" namespace vast { namespace sink { json::json(path p) : stream_{std::move(p)} { } bool json::process(event const& e) { auto j = to<util::json>(e); if (! j) return false; auto str = to_string(*j); str += '\n'; return stream_.write(str.begin(), str.end()); } std::string json::describe() const { return "json-sink"; } } // namespace sink } // namespace vast
#include "vast/sink/json.h" #include "vast/util/json.h" namespace vast { namespace sink { json::json(path p) : stream_{std::move(p)} { } bool json::process(event const& e) { auto j = to<util::json>(e); if (! j) return false; auto str = to_string(*j, true); str += '\n'; return stream_.write(str.begin(), str.end()); } std::string json::describe() const { return "json-sink"; } } // namespace sink } // namespace vast
Use a true random number generator in the priority protobuf test
#include <gtest/gtest.h> #include <chrono> #include <iostream> #include <random> #include <string> #include <thread> #include "priority.pb.h" #include "prioritybuffer.h" #define NUM_ITEMS 1000 unsigned long long get_priority(const PriorityMessage& message) { return message.priority(); } TEST(PriorityProtobufTests, RandomPriorityTest) { PriorityBuffer<PriorityMessage> buffer{get_priority}; std::default_random_engine generator; std::uniform_int_distribution<unsigned long long> distribution(0, 100LL); for (int i = 0; i < NUM_ITEMS; ++i) { PriorityMessage message; auto priority = distribution(generator); message.set_priority(priority); EXPECT_EQ(priority, message.priority()); message.CheckInitialized(); buffer.Push(message); } unsigned long long priority = 100LL; for (int i = 0; i < NUM_ITEMS; ++i) { auto message = buffer.Pop(); message.CheckInitialized(); EXPECT_GE(priority, message.priority()); priority = message.priority(); } } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); GOOGLE_PROTOBUF_VERIFY_VERSION; return RUN_ALL_TESTS(); }
#include <gtest/gtest.h> #include <chrono> #include <iostream> #include <random> #include <string> #include <thread> #include "priority.pb.h" #include "prioritybuffer.h" #define NUM_ITEMS 1000 unsigned long long get_priority(const PriorityMessage& message) { return message.priority(); } TEST(PriorityProtobufTests, RandomPriorityTest) { PriorityBuffer<PriorityMessage> buffer{get_priority}; std::random_device generator; std::uniform_int_distribution<unsigned long long> distribution(0, 100LL); for (int i = 0; i < NUM_ITEMS; ++i) { PriorityMessage message; auto priority = distribution(generator); message.set_priority(priority); EXPECT_EQ(priority, message.priority()); message.CheckInitialized(); buffer.Push(message); } unsigned long long priority = 100LL; for (int i = 0; i < NUM_ITEMS; ++i) { auto message = buffer.Pop(); message.CheckInitialized(); EXPECT_GE(priority, message.priority()); priority = message.priority(); } } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); GOOGLE_PROTOBUF_VERIFY_VERSION; return RUN_ALL_TESTS(); }
Write newline after serialized XML.
// This file is part of MicroRestD <http://github.com/ufal/microrestd/>. // // Copyright 2015 Institute of Formal and Applied Linguistics, Faculty of // Mathematics and Physics, Charles University in Prague, Czech Republic. // // 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 <cstdio> #include "microrestd.h" using namespace ufal::microrestd; int main(void) { xml_builder xml; xml.element("nazdar"); xml.indent().text("text-<nazdar"); xml.indent().element("test").attribute("test", "value"); xml.indent().text("text->test"); xml.indent().close(); xml.indent().text("text-&nazdar"); xml.indent().element("pokus").attribute("attr", nullptr).close(); xml.indent().close(); auto data = xml.current(); printf("%*s", int(data.len), data.str); return 0; }
// This file is part of MicroRestD <http://github.com/ufal/microrestd/>. // // Copyright 2015 Institute of Formal and Applied Linguistics, Faculty of // Mathematics and Physics, Charles University in Prague, Czech Republic. // // 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 <cstdio> #include "microrestd.h" using namespace ufal::microrestd; int main(void) { xml_builder xml; xml.element("nazdar"); xml.indent().text("text-<nazdar"); xml.indent().element("test").attribute("test", "value"); xml.indent().text("text->test"); xml.indent().close(); xml.indent().text("text-&nazdar"); xml.indent().element("pokus").attribute("attr", nullptr).close(); xml.indent().close(); auto data = xml.current(); printf("%*s\n", int(data.len), data.str); return 0; }
Return 404's when expected dashboard file missing
#include "dashboardcontroller.h" #include "serialization/result.h" #include "infrastructure/contentservice.h" #include <fstream> ApiMock::DashboardController::DashboardController(ContentService* content) : _content(content) {} ApiMock::ResponseData ApiMock::DashboardController::get(RequestData request) { auto content = _content->getContent("www/app/index.html"); RawResult c(content.content, content.mimeType); return createResponse(HTTP_OK, &c); }
#include "dashboardcontroller.h" #include "serialization/result.h" #include "infrastructure/contentservice.h" #include <fstream> #include <infrastructure/exceptions.h> ApiMock::DashboardController::DashboardController(ContentService* content) : _content(content) {} ApiMock::ResponseData ApiMock::DashboardController::get(RequestData request) { try { auto content = _content->getContent("www/app/index.html"); RawResult c(content.content, content.mimeType); return createResponse(HTTP_OK, &c); } catch (FileNotFoundException e) { return createResponse(HTTP_NOT_FOUND); } }
Fix getting application name config string on non-windows systems.
// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "PlatformNix.h" #include "Framework.h" #if !defined(_WINDOWS) namespace Foundation { std::string PlatformNix::GetApplicationDataDirectory() { char *ppath = NULL; ppath = getenv("HOME"); if (ppath == NULL) throw Core::Exception("Failed to get HOME environment variable."); std::string path(ppath); return path + "/." + framework_->GetDefaultConfig().GetString(Framework::ConfigurationGroup(), "application_name"); } std::wstring PlatformNix::GetApplicationDataDirectoryW() { // Unicode not supported on Unix-based platforms std::string path = GetApplicationDataDirectory(); return (Core::ToWString(path)); } std::string PlatformNix::GetUserDocumentsDirectory() { return GetApplicationDataDirectory(); } std::wstring PlatformNix::GetUserDocumentsDirectoryW() { return GetApplicationDataDirectoryW(); } } #endif
// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "PlatformNix.h" #include "Framework.h" #if !defined(_WINDOWS) namespace Foundation { std::string PlatformNix::GetApplicationDataDirectory() { char *ppath = NULL; ppath = getenv("HOME"); if (ppath == NULL) throw Core::Exception("Failed to get HOME environment variable."); std::string path(ppath); return path + "/." + framework_->GetDefaultConfig().GetSetting<std::string>(Framework::ConfigurationGroup(), "application_name"); } std::wstring PlatformNix::GetApplicationDataDirectoryW() { // Unicode not supported on Unix-based platforms std::string path = GetApplicationDataDirectory(); return (Core::ToWString(path)); } std::string PlatformNix::GetUserDocumentsDirectory() { return GetApplicationDataDirectory(); } std::wstring PlatformNix::GetUserDocumentsDirectoryW() { return GetApplicationDataDirectoryW(); } } #endif
Exclude the NLP Tests class also.
/// Project-level integration tests #include "stdafx.h" #include <CppUnitTest.h> using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; namespace You { namespace NLP { namespace Tests { TEST_CLASS(NlpTests) { public: }; } // namespace Tests } // namespace NLP } // namespace You
/// Project-level integration tests #include "stdafx.h" #include <CppUnitTest.h> using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; namespace You { namespace NLP { namespace UnitTests { TEST_CLASS(NlpTests) { public: }; } // namespace UnitTests } // namespace NLP } // namespace You
Fix MPLY-9622 - Re-running search using Search button after selecting a result will not show all rooms as highlighted Buddy:Jordan.Brown
// Copyright eeGeo Ltd (2012-2015), All Rights Reserved #include "SearchMenuPerformedSearchMessageHandler.h" namespace ExampleApp { namespace SearchMenu { namespace SdkModel { SearchMenuPerformedSearchMessageHandler::SearchMenuPerformedSearchMessageHandler(Search::SdkModel::ISearchQueryPerformer& searchQueryPerformer, ExampleAppMessaging::TMessageBus& messageBus, Metrics::IMetricsService& metricsService) : m_searchQueryPerformer(searchQueryPerformer) , m_messageBus(messageBus) , m_metricsService(metricsService) , m_handlePerformedSearchMessageBinding(this, &SearchMenuPerformedSearchMessageHandler::OnPerformedSearchMessage) { m_messageBus.SubscribeNative(m_handlePerformedSearchMessageBinding); } SearchMenuPerformedSearchMessageHandler::~SearchMenuPerformedSearchMessageHandler() { m_messageBus.UnsubscribeNative(m_handlePerformedSearchMessageBinding); } void SearchMenuPerformedSearchMessageHandler::OnPerformedSearchMessage(const SearchMenuPerformedSearchMessage& message) { m_metricsService.SetEvent("Search", "Search string", message.SearchQuery().c_str()); m_searchQueryPerformer.PerformSearchQuery(message.SearchQuery(), message.IsTag(), message.IsInterior()); } } } }
// Copyright eeGeo Ltd (2012-2015), All Rights Reserved #include "SearchMenuPerformedSearchMessageHandler.h" namespace ExampleApp { namespace SearchMenu { namespace SdkModel { SearchMenuPerformedSearchMessageHandler::SearchMenuPerformedSearchMessageHandler(Search::SdkModel::ISearchQueryPerformer& searchQueryPerformer, ExampleAppMessaging::TMessageBus& messageBus, Metrics::IMetricsService& metricsService) : m_searchQueryPerformer(searchQueryPerformer) , m_messageBus(messageBus) , m_metricsService(metricsService) , m_handlePerformedSearchMessageBinding(this, &SearchMenuPerformedSearchMessageHandler::OnPerformedSearchMessage) { m_messageBus.SubscribeNative(m_handlePerformedSearchMessageBinding); } SearchMenuPerformedSearchMessageHandler::~SearchMenuPerformedSearchMessageHandler() { m_messageBus.UnsubscribeNative(m_handlePerformedSearchMessageBinding); } void SearchMenuPerformedSearchMessageHandler::OnPerformedSearchMessage(const SearchMenuPerformedSearchMessage& message) { m_searchQueryPerformer.RemoveSearchQueryResults(); m_metricsService.SetEvent("Search", "Search string", message.SearchQuery().c_str()); m_searchQueryPerformer.PerformSearchQuery(message.SearchQuery(), message.IsTag(), message.IsInterior()); } } } }
Add more proper pure BinarySearch algorithm removing linear search
/* * Just playing around with binary and linear search. No idea. */ #include <iostream> using namespace std; int foo[10] = { 2, 16, 40, 77, 88, 99, 105, 120, 150 }; int n, result = 0; int length = 10; int sillySearch(int element) { //Figure out array length and make first split length = length / 2; result = foo[length]; if (result < element) { while (length<10) { result = foo[(length)]; length++; if (result == element) { return result; } } } else { while (length>0) { result = foo[(length)]; length--; if (result == element) { return result; } } } return -1; } int main(int argc, char argv[]) { //first sort the array ascenging order int tell = sillySearch(40); cout << tell; cout << "Hello\n"; }
/* * Implementing binary search */ #include <iostream> using namespace std; //get rid of fixed array int foo[10] = { 2, 16, 40, 77, 88, 99, 105, 120, 150 }; int sillySearch(int element) { int minIndex = 0; int maxIndex = 10 - 1; //array.length here plz int curElement, curIndex; while (minIndex < maxIndex) { curIndex = (minIndex + maxIndex) / 2 | 0; curElement = foo[curIndex]; //curElement = foo[(minIndex + maxIndex) / 2 | 0]; if (curElement < element) { minIndex = curIndex + 1; } else if (curElement > element) { maxIndex = curIndex + 1; } else { return curIndex; } } return -1; } int main(int argc, char argv[]) { //first sort the array ascenging order int tell = sillySearch(40); cout << tell; cout << "Hello World Once Again!\n"; }
Add fuzzing coverage for JSONRPCTransactionError(...) and RPCErrorFromTransactionError(...)
// Copyright (c) 2020 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 <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <util/error.h> #include <cstdint> #include <vector> // The fuzzing kitchen sink: Fuzzing harness for functions that need to be // fuzzed but a.) don't belong in any existing fuzzing harness file, and // b.) are not important enough to warrant their own fuzzing harness file. void test_one_input(const std::vector<uint8_t>& buffer) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const TransactionError transaction_error = fuzzed_data_provider.PickValueInArray<TransactionError>({TransactionError::OK, TransactionError::MISSING_INPUTS, TransactionError::ALREADY_IN_CHAIN, TransactionError::P2P_DISABLED, TransactionError::MEMPOOL_REJECTED, TransactionError::MEMPOOL_ERROR, TransactionError::INVALID_PSBT, TransactionError::PSBT_MISMATCH, TransactionError::SIGHASH_MISMATCH, TransactionError::MAX_FEE_EXCEEDED}); (void)TransactionErrorString(transaction_error); }
// Copyright (c) 2020 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 <rpc/util.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <util/error.h> #include <cstdint> #include <vector> // The fuzzing kitchen sink: Fuzzing harness for functions that need to be // fuzzed but a.) don't belong in any existing fuzzing harness file, and // b.) are not important enough to warrant their own fuzzing harness file. void test_one_input(const std::vector<uint8_t>& buffer) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const TransactionError transaction_error = fuzzed_data_provider.PickValueInArray<TransactionError>({TransactionError::OK, TransactionError::MISSING_INPUTS, TransactionError::ALREADY_IN_CHAIN, TransactionError::P2P_DISABLED, TransactionError::MEMPOOL_REJECTED, TransactionError::MEMPOOL_ERROR, TransactionError::INVALID_PSBT, TransactionError::PSBT_MISMATCH, TransactionError::SIGHASH_MISMATCH, TransactionError::MAX_FEE_EXCEEDED}); (void)JSONRPCTransactionError(transaction_error); (void)RPCErrorFromTransactionError(transaction_error); (void)TransactionErrorString(transaction_error); }
Fix out of bounds exception when printing crash states.
#include "PermuteTestResult.h" namespace fs_testing { using std::ostream; using std::string; using std::to_string; ostream& PermuteTestResult::PrintCrashState(ostream& os) const { for (unsigned int i = 0; i < crash_state.size() - 1; ++i) { os << to_string(crash_state.at(i)) << ", "; } os << to_string(crash_state.back()); return os; } } // namespace fs_testing
#include "PermuteTestResult.h" namespace fs_testing { using std::ostream; using std::string; using std::to_string; ostream& PermuteTestResult::PrintCrashState(ostream& os) const { if (crash_state.size() == 0) { return os; } for (unsigned int i = 0; i < crash_state.size() - 1; ++i) { os << to_string(crash_state.at(i)) << ", "; } os << to_string(crash_state.back()); return os; } } // namespace fs_testing
Fix non-const literal string warning with g++ 4.3.
#include <string> #include <libport/pthread.h> #include <libport/unit-test.hh> using libport::test_suite; std::string truth("vim is future"); void* thread1(void* data) { std::string del((char *) data); size_t pos = truth.find(del); truth.erase(pos, pos + del.size()); return 0; } void* thread2(void* data) { pthread_join(*(pthread_t *)data, 0); truth.insert(0, "emacs"); return (void*)0xdeadbeef; } void test_pthread() { pthread_t my_thread[2]; char* vim = "vim"; void* ret; BOOST_CHECK(!pthread_create(my_thread, 0, &thread1, vim)); BOOST_CHECK(!pthread_create(my_thread + 1, 0, &thread2, my_thread)); pthread_join(my_thread[1], &ret); BOOST_CHECK_EQUAL(ret, (void*)0xdeadbeef); BOOST_CHECK_EQUAL(truth, "emacs is future"); } test_suite* init_test_suite() { test_suite* suite = BOOST_TEST_SUITE("libport::semaphore"); suite->add(BOOST_TEST_CASE(test_pthread)); return suite; }
#include <string> #include <libport/pthread.h> #include <libport/unit-test.hh> using libport::test_suite; std::string truth("vim is future"); void* thread1(void* data) { std::string del((char *) data); size_t pos = truth.find(del); truth.erase(pos, pos + del.size()); return 0; } void* thread2(void* data) { pthread_join(*(pthread_t *)data, 0); truth.insert(0, "emacs"); return (void*)0xdeadbeef; } void test_pthread() { pthread_t my_thread[2]; const char* vim = "vim"; void* ret; BOOST_CHECK(!pthread_create(my_thread, 0, &thread1, (char*)vim)); BOOST_CHECK(!pthread_create(my_thread + 1, 0, &thread2, my_thread)); pthread_join(my_thread[1], &ret); BOOST_CHECK_EQUAL(ret, (void*)0xdeadbeef); BOOST_CHECK_EQUAL(truth, "emacs is future"); } test_suite* init_test_suite() { test_suite* suite = BOOST_TEST_SUITE("libport::semaphore"); suite->add(BOOST_TEST_CASE(test_pthread)); return suite; }
Add test case for <rdar://problem/7880658>.
// RUN: %clang_cc1 -fsyntax-only -verify %s -Wmissing-noreturn void f() __attribute__((noreturn)); template<typename T> void g(T) { // expected-warning {{function could be attribute 'noreturn'}} f(); } template void g<int>(int); // expected-note {{in instantiation of function template specialization 'g<int>' requested here}} template<typename T> struct A { void g() { // expected-warning {{function could be attribute 'noreturn'}} f(); } }; template struct A<int>; // expected-note {{in instantiation of member function 'A<int>::g' requested here}} struct B { template<typename T> void g(T) { // expected-warning {{function could be attribute 'noreturn'}} f(); } }; template void B::g<int>(int); // expected-note {{in instantiation of function template specialization 'B::g<int>' requested here}} // We don't want a warning here. struct X { virtual void g() { f(); } }; namespace test1 { bool condition(); // We don't want a warning here. void foo() { while (condition()) {} } }
// RUN: %clang_cc1 -fsyntax-only -verify %s -Wmissing-noreturn void f() __attribute__((noreturn)); template<typename T> void g(T) { // expected-warning {{function could be attribute 'noreturn'}} f(); } template void g<int>(int); // expected-note {{in instantiation of function template specialization 'g<int>' requested here}} template<typename T> struct A { void g() { // expected-warning {{function could be attribute 'noreturn'}} f(); } }; template struct A<int>; // expected-note {{in instantiation of member function 'A<int>::g' requested here}} struct B { template<typename T> void g(T) { // expected-warning {{function could be attribute 'noreturn'}} f(); } }; template void B::g<int>(int); // expected-note {{in instantiation of function template specialization 'B::g<int>' requested here}} // We don't want a warning here. struct X { virtual void g() { f(); } }; namespace test1 { bool condition(); // We don't want a warning here. void foo() { while (condition()) {} } } // <rdar://problem/7880658> - This test case previously had a false "missing return" // warning. struct R7880658 { R7880658 &operator++(); bool operator==(const R7880658 &) const; bool operator!=(const R7880658 &) const; }; void f_R7880658(R7880658 f, R7880658 l) { // no-warning for (; f != l; ++f) { } }
Add ifdef to compile on mac
#include "Logger.h" #include <Effekseer.h> #include <filesystem> #include <spdlog/sinks/basic_file_sink.h> #include <spdlog/spdlog.h> namespace Effekseer::Tool { void Logger::SetFileLogger(const char16_t* path) { spdlog::flush_on(spdlog::level::trace); spdlog::set_level(spdlog::level::trace); spdlog::trace("Begin Native::SetFileLogger"); #if defined(_WIN32) auto wpath = std::filesystem::path(reinterpret_cast<const wchar_t*>(path)); auto fileLogger = spdlog::basic_logger_mt("logger", wpath.generic_string().c_str()); #else char cpath[512]; Effekseer::ConvertUtf16ToUtf8(cpath, 512, path); auto fileLogger = spdlog::basic_logger_mt("logger", cpath); #endif spdlog::set_default_logger(fileLogger); #if defined(_WIN32) spdlog::trace("Native::SetFileLogger : {}", wpath.generic_string().c_str()); #else spdlog::trace("Native::SetFileLogger : {}", cpath); #endif spdlog::trace("End Native::SetFileLogger"); } } // namespace Effekseer::Tool
#include "Logger.h" #include <Effekseer.h> #if defined(_WIN32) #include <filesystem> #endif #include <spdlog/sinks/basic_file_sink.h> #include <spdlog/spdlog.h> namespace Effekseer::Tool { void Logger::SetFileLogger(const char16_t* path) { spdlog::flush_on(spdlog::level::trace); spdlog::set_level(spdlog::level::trace); spdlog::trace("Begin Native::SetFileLogger"); #if defined(_WIN32) auto wpath = std::filesystem::path(reinterpret_cast<const wchar_t*>(path)); auto fileLogger = spdlog::basic_logger_mt("logger", wpath.generic_string().c_str()); #else char cpath[512]; Effekseer::ConvertUtf16ToUtf8(cpath, 512, path); auto fileLogger = spdlog::basic_logger_mt("logger", cpath); #endif spdlog::set_default_logger(fileLogger); #if defined(_WIN32) spdlog::trace("Native::SetFileLogger : {}", wpath.generic_string().c_str()); #else spdlog::trace("Native::SetFileLogger : {}", cpath); #endif spdlog::trace("End Native::SetFileLogger"); } } // namespace Effekseer::Tool
Replace void with int to make this a valid C++ file.
// RUN: %clang_cc1 -ast-print -o - %s | FileCheck %s extern "C" void f(void); // CHECK: extern "C" void f() extern "C" void v; // CHECK: extern "C" void v
// RUN: %clang_cc1 -ast-print -o - %s | FileCheck %s extern "C" int f(void); // CHECK: extern "C" int f() extern "C" int v; // CHECK: extern "C" int v
Simplify the TestQTCore main function
// Copyright (c) 2021 The Orbit 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 <gtest/gtest.h> #include <QCoreApplication> #include <cstdio> #include <optional> namespace { // QCoreApplication objects needs to be on the stack or in static storage. Putting this variable // into the QCoreApplicationStarter class leads to a crash during destruction. I'm not sure what is // going on. std::optional<QCoreApplication> app; // QCoreApplicationStarter is a gtest event listener which takes care of delayed construction of the // QCoreApplication object. class QCoreApplicationStarter : public testing::EmptyTestEventListener { public: explicit QCoreApplicationStarter(int argc, char** argv) : argc_{argc}, argv_{argv} {} private: void OnTestStart(const ::testing::TestInfo& /*test_info*/) override { if (!app.has_value()) app.emplace(argc_, argv_); } int argc_; char** argv_; }; } // namespace int main(int argc, char* argv[]) { printf("Running main() from %s\n", __FILE__); ::testing::InitGoogleTest(&argc, argv); ::testing::TestEventListeners& listeners = ::testing::UnitTest::GetInstance()->listeners(); listeners.Append(new QCoreApplicationStarter{argc, argv}); // NOLINT int result = RUN_ALL_TESTS(); app = std::nullopt; return result; }
// Copyright (c) 2021 The Orbit 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 <gtest/gtest.h> #include <QCoreApplication> #include <cstdio> int main(int argc, char* argv[]) { printf("Running main() from %s\n", __FILE__); ::testing::InitGoogleTest(&argc, argv); QCoreApplication app{argc, argv}; int result = RUN_ALL_TESTS(); return result; }
Revert "use direct access to tensor when possible"
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "tensor_attribute_executor.h" #include <vespa/searchlib/tensor/i_tensor_attribute.h> #include <vespa/searchlib/tensor/direct_tensor_attribute.h> namespace search { namespace features { TensorAttributeExecutor:: TensorAttributeExecutor(const search::tensor::ITensorAttribute *attribute) : _attribute(attribute), _emptyTensor(attribute->getEmptyTensor()), _tensor() { } void TensorAttributeExecutor::execute(uint32_t docId) { using DTA = search::tensor::DirectTensorAttribute; if (auto direct = dynamic_cast<const DTA *>(_attribute)) { outputs().set_object(0, direct->get_tensor_ref(docId)); return; } _tensor = _attribute->getTensor(docId); if (_tensor) { outputs().set_object(0, *_tensor); } else { outputs().set_object(0, *_emptyTensor); } } } // namespace features } // namespace search
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "tensor_attribute_executor.h" #include <vespa/searchlib/tensor/i_tensor_attribute.h> namespace search { namespace features { TensorAttributeExecutor:: TensorAttributeExecutor(const search::tensor::ITensorAttribute *attribute) : _attribute(attribute), _emptyTensor(attribute->getEmptyTensor()), _tensor() { } void TensorAttributeExecutor::execute(uint32_t docId) { _tensor = _attribute->getTensor(docId); if (_tensor) { outputs().set_object(0, *_tensor); } else { outputs().set_object(0, *_emptyTensor); } } } // namespace features } // namespace search
Fix *nix build, don't actually need these definitions
#define CATCH_CONFIG_MAIN #include <catch.hpp> #include <ionConfig.h> #ifdef ION_CONFIG_WINDOWS class DebugOutBuffer : public std::stringbuf { public: virtual int sync() { OutputDebugString(str().c_str()); str(""); return 0; } }; namespace Catch { std::ostream buffer(new DebugOutBuffer()); std::ostream & cout() { return buffer; } std::ostream & cerr() { return buffer; } } #else namespace Catch { std::ostream & cout() { return std::cout; } std::ostream & cerr() { return std::cerr; } } #endif
#define CATCH_CONFIG_MAIN #include <catch.hpp> #include <ionConfig.h> #ifdef ION_CONFIG_WINDOWS class DebugOutBuffer : public std::stringbuf { public: virtual int sync() { OutputDebugString(str().c_str()); str(""); return 0; } }; namespace Catch { std::ostream buffer(new DebugOutBuffer()); std::ostream & cout() { return buffer; } std::ostream & cerr() { return buffer; } } #endif
Add a test for uniqueptr having either NULL and nullptr
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // <memory> // unique_ptr // Test unique_ptr(pointer, deleter) ctor // unique_ptr(pointer, deleter()) only requires MoveConstructible deleter #include <memory> #include <cassert> #include "../../deleter.h" struct A { static int count; A() {++count;} A(const A&) {++count;} ~A() {--count;} }; int A::count = 0; int main() { { A* p = new A[3]; assert(A::count == 3); std::unique_ptr<A[], Deleter<A[]> > s(p, Deleter<A[]>()); assert(s.get() == p); assert(s.get_deleter().state() == 0); } assert(A::count == 0); }
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // <memory> // unique_ptr // Test unique_ptr(pointer, deleter) ctor // unique_ptr(pointer, deleter()) only requires MoveConstructible deleter #include <memory> #include <cassert> #include "../../deleter.h" struct A { static int count; A() {++count;} A(const A&) {++count;} ~A() {--count;} }; int A::count = 0; int main() { { A* p = new A[3]; assert(A::count == 3); std::unique_ptr<A[], Deleter<A[]> > s(p, Deleter<A[]>()); assert(s.get() == p); assert(s.get_deleter().state() == 0); } assert(A::count == 0); { // LWG#2520 says that nullptr is a valid input as well as null std::unique_ptr<A[], Deleter<A[]> > s1(NULL, Deleter<A[]>()); std::unique_ptr<A[], Deleter<A[]> > s2(nullptr, Deleter<A[]>()); } assert(A::count == 0); }
Make initial Pipeline instance a shared_ptr
// Copyright 2011 Branan Purvine-Riley and Adam Johnson // // 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 "pipeline/Pipeline.hpp" struct DemoConsole : public Pipeline::KbdCallback { virtual ~DemoConsole() {} void operator()(Keysym, uint32_t) {} }; int main(int argc, char **argv) { Pipeline p; p.pushKbdCallback(new DemoConsole); auto fsaa_level_iter = p.fsaaLevels().rbegin(); p.setFsaa(*fsaa_level_iter); // set the highest possible FSAA level for(;;) { p.beginFrame(); p.render(); p.endFrame(); if(!p.platformEventLoop()) break; } }
// Copyright 2011 Branan Purvine-Riley and Adam Johnson // // 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 "pipeline/Pipeline.hpp" struct DemoConsole : public Pipeline::KbdCallback { virtual ~DemoConsole() {} void operator()(Keysym, uint32_t) {} }; int main(int argc, char **argv) { std::shared_ptr<Pipeline> p = std::shared_ptr<Pipeline>(new Pipeline); p->pushKbdCallback(new DemoConsole); auto fsaa_level_iter = p->fsaaLevels().rbegin(); p->setFsaa(*fsaa_level_iter); // set the highest possible FSAA level for(;;) { p->beginFrame(); p->render(); p->endFrame(); if(!p->platformEventLoop()) break; } }
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); }
Add cloned theme to theme list
#include "SettingsWindow.hpp" #include <imgui.h> #include "../ImGui/Theme.hpp" using namespace GUI; SettingsWindow::SettingsWindow() { themes.push_back("Default"); } void SettingsWindow::Show() { if (ImGui::Begin("Settings", &visible)) { // Show drop down list to select theme. if (dropDownItems != nullptr) delete[] dropDownItems; dropDownItems = new const char*[themes.size()]; for (std::size_t i=0; i < themes.size(); ++i) { dropDownItems[i] = themes[i].c_str(); } ImGui::Combo("Theme", &theme, dropDownItems, themes.size()); // Clone current theme to create a new theme. if (ImGui::Button("Clone")) { ImGui::OpenPopup("Theme Name"); themeName[0] = '\0'; } if (ImGui::BeginPopupModal("Theme Name", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { ImGui::InputText("Name", themeName, 128); if (ImGui::Button("Create")) { ImGui::SaveTheme(""); ImGui::CloseCurrentPopup(); } ImGui::SameLine(); if (ImGui::Button("Cancel")) ImGui::CloseCurrentPopup(); ImGui::EndPopup(); } ImGui::ShowStyleEditor(); } ImGui::End(); } bool SettingsWindow::IsVisible() const { return visible; } void SettingsWindow::SetVisible(bool visible) { this->visible = visible; }
#include "SettingsWindow.hpp" #include <imgui.h> #include "../ImGui/Theme.hpp" using namespace GUI; SettingsWindow::SettingsWindow() { themes.push_back("Default"); } void SettingsWindow::Show() { if (ImGui::Begin("Settings", &visible)) { // Show drop down list to select theme. if (dropDownItems != nullptr) delete[] dropDownItems; dropDownItems = new const char*[themes.size()]; for (std::size_t i=0; i < themes.size(); ++i) { dropDownItems[i] = themes[i].c_str(); } ImGui::Combo("Theme", &theme, dropDownItems, themes.size()); // Clone current theme to create a new theme. if (ImGui::Button("Clone")) { ImGui::OpenPopup("Theme Name"); themeName[0] = '\0'; } if (ImGui::BeginPopupModal("Theme Name", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { ImGui::InputText("Name", themeName, 128); if (ImGui::Button("Create")) { ImGui::SaveTheme(themeName); themes.push_back(themeName); ImGui::CloseCurrentPopup(); } ImGui::SameLine(); if (ImGui::Button("Cancel")) ImGui::CloseCurrentPopup(); ImGui::EndPopup(); } ImGui::ShowStyleEditor(); } ImGui::End(); } bool SettingsWindow::IsVisible() const { return visible; } void SettingsWindow::SetVisible(bool visible) { this->visible = visible; }
Fix loading unset material component
#include "Material.hpp" #include "../Manager/Managers.hpp" #include "../Manager/ResourceManager.hpp" #include "../Texture/TextureAsset.hpp" #include "../Hymn.hpp" using namespace Component; Material::Material(Entity* entity) : SuperComponent(entity) { diffuse = Hymn().defaultDiffuse; normal = Hymn().defaultNormal; specular = Hymn().defaultSpecular; glow = Hymn().defaultGlow; } Json::Value Material::Save() const { Json::Value component; if (diffuse != nullptr) component["diffuse"] = diffuse->name; if (normal != nullptr) component["normal"] = normal->name; if (specular != nullptr) component["specular"] = specular->name; if (glow != nullptr) component["glow"] = glow->name; return component; } void Material::Load(const Json::Value& node) { LoadTexture(diffuse, node.get("diffuse", "").asString()); LoadTexture(normal, node.get("normal", "").asString()); LoadTexture(specular, node.get("specular", "").asString()); LoadTexture(glow, node.get("glow", "").asString()); } void Material::LoadTexture(TextureAsset*& texture, const std::string& name) { texture = Managers().resourceManager->CreateTextureAsset(name); }
#include "Material.hpp" #include "../Manager/Managers.hpp" #include "../Manager/ResourceManager.hpp" #include "../Texture/TextureAsset.hpp" #include "../Hymn.hpp" using namespace Component; Material::Material(Entity* entity) : SuperComponent(entity) { diffuse = Hymn().defaultDiffuse; normal = Hymn().defaultNormal; specular = Hymn().defaultSpecular; glow = Hymn().defaultGlow; } Json::Value Material::Save() const { Json::Value component; if (diffuse != nullptr) component["diffuse"] = diffuse->name; if (normal != nullptr) component["normal"] = normal->name; if (specular != nullptr) component["specular"] = specular->name; if (glow != nullptr) component["glow"] = glow->name; return component; } void Material::Load(const Json::Value& node) { LoadTexture(diffuse, node.get("diffuse", "").asString()); LoadTexture(normal, node.get("normal", "").asString()); LoadTexture(specular, node.get("specular", "").asString()); LoadTexture(glow, node.get("glow", "").asString()); } void Material::LoadTexture(TextureAsset*& texture, const std::string& name) { if (!name.empty()) texture = Managers().resourceManager->CreateTextureAsset(name); }
Fix the linux build by adding a string.h include.
// 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 "ppapi/cpp/directory_entry.h" #include "ppapi/cpp/module.h" namespace pp { DirectoryEntry::DirectoryEntry() { memset(&data_, 0, sizeof(data_)); } DirectoryEntry::DirectoryEntry(const DirectoryEntry& other) { data_.file_ref = other.data_.file_ref; data_.file_type = other.data_.file_type; if (data_.file_ref) Module::Get()->core().AddRefResource(data_.file_ref); } DirectoryEntry::~DirectoryEntry() { if (data_.file_ref) Module::Get()->core().ReleaseResource(data_.file_ref); } DirectoryEntry& DirectoryEntry::operator=(const DirectoryEntry& other) { DirectoryEntry copy(other); swap(copy); return *this; } void DirectoryEntry::swap(DirectoryEntry& other) { std::swap(data_.file_ref, other.data_.file_ref); std::swap(data_.file_type, other.data_.file_type); } } // namespace pp
// 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 "ppapi/cpp/directory_entry.h" #include <string.h> #include "ppapi/cpp/module.h" namespace pp { DirectoryEntry::DirectoryEntry() { memset(&data_, 0, sizeof(data_)); } DirectoryEntry::DirectoryEntry(const DirectoryEntry& other) { data_.file_ref = other.data_.file_ref; data_.file_type = other.data_.file_type; if (data_.file_ref) Module::Get()->core().AddRefResource(data_.file_ref); } DirectoryEntry::~DirectoryEntry() { if (data_.file_ref) Module::Get()->core().ReleaseResource(data_.file_ref); } DirectoryEntry& DirectoryEntry::operator=(const DirectoryEntry& other) { DirectoryEntry copy(other); swap(copy); return *this; } void DirectoryEntry::swap(DirectoryEntry& other) { std::swap(data_.file_ref, other.data_.file_ref); std::swap(data_.file_type, other.data_.file_type); } } // namespace pp
Mark death callback as unstable while we investigate the cause in AArch64
// RUN: %clangxx -O2 %s -o %t && not %run %t 2>&1 | FileCheck %s #include <sanitizer/common_interface_defs.h> #include <stdio.h> volatile char *zero = 0; void Death() { fprintf(stderr, "DEATH CALLBACK EXECUTED\n"); } // CHECK: DEATH CALLBACK EXECUTED char global; volatile char *sink; __attribute__((noinline)) void MaybeInit(int *uninitialized) { if (zero) *uninitialized = 1; } __attribute__((noinline)) void Leak() { sink = new char[100]; // trigger lsan report. } int main(int argc, char **argv) { int uninitialized; __sanitizer_set_death_callback(Death); MaybeInit(&uninitialized); if (uninitialized) // trigger msan report. global = 77; sink = new char[100]; delete[] sink; global = sink[0]; // use-after-free: trigger asan/tsan report. Leak(); sink = 0; }
// RUN: %clangxx -O2 %s -o %t && not %run %t 2>&1 | FileCheck %s // REQUIRES: stable-runtime #include <sanitizer/common_interface_defs.h> #include <stdio.h> volatile char *zero = 0; void Death() { fprintf(stderr, "DEATH CALLBACK EXECUTED\n"); } // CHECK: DEATH CALLBACK EXECUTED char global; volatile char *sink; __attribute__((noinline)) void MaybeInit(int *uninitialized) { if (zero) *uninitialized = 1; } __attribute__((noinline)) void Leak() { sink = new char[100]; // trigger lsan report. } int main(int argc, char **argv) { int uninitialized; __sanitizer_set_death_callback(Death); MaybeInit(&uninitialized); if (uninitialized) // trigger msan report. global = 77; sink = new char[100]; delete[] sink; global = sink[0]; // use-after-free: trigger asan/tsan report. Leak(); sink = 0; }
Improve the global middelware test.
#include <iostream> #include <silicon/backends/mhd_serve.hh> #include <silicon/api.hh> using namespace sl; struct request_logger { request_logger(std::string x) : xx(x) { std::cout << "Request start!" << std::endl; } ~request_logger() { std::cout << "Request end! " << xx << std::endl; } std::string xx; static auto instantiate() { return request_logger("xxxx"); } }; auto hello_api = make_api( @test = [] () { return D(@message = "hello world."); } ).global_middlewares([] (request_logger&) {}); int main(int argc, char* argv[]) { if (argc == 2) sl::mhd_json_serve(hello_api, atoi(argv[1])); else std::cerr << "Usage: " << argv[0] << " port" << std::endl; }
#include <iostream> #include <silicon/backends/mhd_serve.hh> #include <silicon/api.hh> using namespace sl; struct request_logger { request_logger() { time = get_time(); std::cout << "Request start!" << std::endl; } ~request_logger() { std::cout << "Request took " << (get_time() - time) << " microseconds." << std::endl; } inline double get_time() { timespec ts; clock_gettime(CLOCK_REALTIME, &ts); return double(ts.tv_sec) * 1e6 + double(ts.tv_nsec) / 1e3; } static auto instantiate() { return request_logger(); } private: double time; }; auto hello_api = make_api( @test = [] () { return D(@message = "hello world."); } ).global_middlewares([] (request_logger&) {}); int main(int argc, char* argv[]) { if (argc == 2) sl::mhd_json_serve(hello_api, atoi(argv[1])); else std::cerr << "Usage: " << argv[0] << " port" << std::endl; }
Add empty constructor for Word object
/** * word.cpp * Copyright (C) 2015 Tony Lim <atomictheorist@gmail.com> * * Distributed under terms of the MIT license. */ #include "word.h" namespace NLP { Word::Word(const Token &other, set<WordType> tags, set<string> defs) : Token::Token(other), mTypes(tags), mDefinitions(defs) { } Word::Word(const Word &other) : Token ( other.getTokenString() , other.getType() ), mTypes ( other.getTypes() ), mDefinitions ( other.getDefinitions() ) { } std::set<WordType> Word::getTypes() const { return mTypes; } string Word::getRawtypes() const { string rawT; for(WordType WT : mTypes) rawT += WordStringMap[WT] + string(" ,"); return rawT.substr(0,rawT.length() - 2); } std::set<string> Word::getDefinitions() const { return mDefinitions; } string Word::getName() const { return getTokenString(); } /** * @brief Do nothing */ Word::~Word() { } } /* NLP */
/** * word.cpp * Copyright (C) 2015 Tony Lim <atomictheorist@gmail.com> * * Distributed under terms of the MIT license. */ #include "word.h" namespace NLP { Word::Word() : Token() { } Word::Word(const Token &other, set<WordType> tags, set<string> defs) : Token::Token(other), mTypes(tags), mDefinitions(defs) { } Word::Word(const Word &other) : Token ( other.getTokenString() , other.getType() ), mTypes ( other.getTypes() ), mDefinitions ( other.getDefinitions() ) { } Word &Word::operator =(const Word &newToken) { this->mType = newToken.getType(); mTypes = newToken.getTypes(); mDefinitions = newToken.getDefinitions(); } std::set<WordType> Word::getTypes() const { return mTypes; } string Word::getRawtypes() const { string rawT; for(WordType WT : mTypes) rawT += WordStringMap[WT] + string(" ,"); return rawT.substr(0,rawT.length() - 2); } std::set<string> Word::getDefinitions() const { return mDefinitions; } string Word::getName() const { return getTokenString(); } /** * @brief Do nothing */ Word::~Word() { } } /* NLP */
Change 'tests' to 'test_run' in output
#include <map> #include <stdio.h> #include <string> #include <sys/utsname.h> #include "tcp.h" #include "udss.h" #include "udds.h" int main() { struct utsname name; std::map<std::string, std::string> options; options["port"] = "10000"; options["items"] = "1000000"; options["max_msg_size"] = "4096"; options["max_threads"] = "32"; options["path"] = "/tmp/queueable-socket"; options["client_path"] = "/tmp/queueable-socket-client"; uname(&name); printf("<?xml version=\"1.0\">\n"); printf("<tests>\n"); printf("<platform><sysname>%s</sysname><release>%s</release><version>%s</version><machine>%s</machine></platform>\n", name.sysname, name.release, name.version, name.machine); Tcp tcp; tcp.run_tests(options); Udss udss; udss.run_tests(options); Udds udds; udds.run_tests(options); printf("</tests>\n"); return 0; }
#include <map> #include <stdio.h> #include <string> #include <sys/utsname.h> #include "tcp.h" #include "udss.h" #include "udds.h" int main() { struct utsname name; std::map<std::string, std::string> options; options["port"] = "10000"; options["items"] = "1000000"; options["max_msg_size"] = "4096"; options["max_threads"] = "32"; options["path"] = "/tmp/queueable-socket"; options["client_path"] = "/tmp/queueable-socket-client"; uname(&name); printf("<?xml version=\"1.0\"?>\n"); printf("<test_run>\n"); printf("<platform><sysname>%s</sysname><release>%s</release><version>%s</version><machine>%s</machine></platform>\n", name.sysname, name.release, name.version, name.machine); Tcp tcp; tcp.run_tests(options); Udss udss; udss.run_tests(options); Udds udds; udds.run_tests(options); printf("</test_run>\n"); return 0; }
Use slightly more appropriate header
#include <cstring> #include "framework/gamecontroller.hh" using namespace Framework; GameController::GameController() : m_keyboardState(NULL) { } void GameController::SetKeyboardState(ReadingKeyboardState *state) { m_keyboardState = state; } ReadingKeyboardState *GameController::GetKeyboardState() { return m_keyboardState; }
#include <cstddef> #include "framework/gamecontroller.hh" using namespace Framework; GameController::GameController() : m_keyboardState(NULL) { } void GameController::SetKeyboardState(ReadingKeyboardState *state) { m_keyboardState = state; } ReadingKeyboardState *GameController::GetKeyboardState() { return m_keyboardState; }
Build fix fo windows only
/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkRefCnt.h" #include "SkWeakRefCnt.h" SK_DEFINE_INST_COUNT(SkRefCnt) SK_DEFINE_INST_COUNT(SkWeakRefCnt) SkRefCnt::SkRefCnt(const SkRefCnt&) { } SkRefCnt::operator=(const SkRefCnt&) { }
/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkRefCnt.h" #include "SkWeakRefCnt.h" SK_DEFINE_INST_COUNT(SkRefCnt) SK_DEFINE_INST_COUNT(SkWeakRefCnt) #ifdef SK_BUILD_FOR_WIN SkRefCnt::SkRefCnt(const SkRefCnt&) { } SkRefCnt& SkRefCnt::operator=(const SkRefCnt&) { return *this; } #endif
Use drawing of convex polygons in QImageDrawer.
#include "./qimage_drawer.h" #include <QPainter> #include <vector> namespace Graphics { QImageDrawer::QImageDrawer(int width, int height) { image = std::make_shared<QImage>(width, height, QImage::Format_Grayscale8); } void QImageDrawer::drawElementVector(std::vector<float> positions) { QPainter painter; painter.begin(image.get()); painter.setBrush(QBrush(Qt::GlobalColor::white)); painter.setPen(Qt::GlobalColor::white); std::vector<QPointF> points; size_t i = 0; if (positions[0] == positions[2] && positions[1] == positions[3]) i = 1; for (; i < positions.size() / 2; ++i) { float x = positions[i * 2]; float y = positions[i * 2 + 1]; if (i * 2 + 3 < positions.size() && x == positions[i * 2 + 2] && y == positions[i * 2 + 3]) { painter.drawConvexPolygon(points.data(), points.size()); points.clear(); i += 2; } points.push_back(QPointF(x, y)); } painter.drawPolygon(points.data(), points.size(), Qt::FillRule::OddEvenFill); painter.end(); } void QImageDrawer::clear() { image->fill(Qt::GlobalColor::black); } } // namespace Graphics
#include "./qimage_drawer.h" #include <QPainter> #include <vector> namespace Graphics { QImageDrawer::QImageDrawer(int width, int height) { image = std::make_shared<QImage>(width, height, QImage::Format_Grayscale8); } void QImageDrawer::drawElementVector(std::vector<float> positions) { QPainter painter; painter.begin(image.get()); painter.setBrush(QBrush(Qt::GlobalColor::white)); painter.setPen(Qt::GlobalColor::white); std::vector<QPointF> points; size_t i = 0; if (positions[0] == positions[2] && positions[1] == positions[3]) i = 1; for (; i < positions.size() / 2; ++i) { float x = positions[i * 2]; float y = positions[i * 2 + 1]; if (i * 2 + 3 < positions.size() && x == positions[i * 2 + 2] && y == positions[i * 2 + 3]) { painter.drawConvexPolygon(points.data(), points.size()); points.clear(); i += 2; } points.push_back(QPointF(x, y)); } painter.drawConvexPolygon(points.data(), points.size()); painter.end(); } void QImageDrawer::clear() { image->fill(Qt::GlobalColor::black); } } // namespace Graphics
Fix output error for fraction field.
#include "stats.h" void Stats::update(ReadType type, bool paired) { auto it = reads.find(type); if (it == reads.end()) { reads[type] = 1; } else { ++it->second; } ++complete; if (type == ReadType::ok) { if (paired) { ++pe; } else { ++se; } } } std::ostream & operator << (std::ostream & out, const Stats & stats) { out << stats.filename << std::endl; unsigned int bad = 0; for (auto it = stats.reads.begin(); it != stats.reads.end(); ++it) { out << "\t" << get_type_name(it->first) << "\t" << it->second << std::endl; if (it->first != ReadType::ok) { bad += it->second; } } out << "\t" << "fraction" << (double)(stats.complete - bad)/stats.complete << std::endl; if (stats.pe) { out << "\t" << "se\t" << stats.se << std::endl; out << "\t" << "pe\t" << stats.pe << std::endl; } return out; }
#include "stats.h" void Stats::update(ReadType type, bool paired) { auto it = reads.find(type); if (it == reads.end()) { reads[type] = 1; } else { ++it->second; } ++complete; if (type == ReadType::ok) { if (paired) { ++pe; } else { ++se; } } } std::ostream & operator << (std::ostream & out, const Stats & stats) { out << stats.filename << std::endl; unsigned int bad = 0; for (auto it = stats.reads.begin(); it != stats.reads.end(); ++it) { out << "\t" << get_type_name(it->first) << "\t" << it->second << std::endl; if (it->first != ReadType::ok) { bad += it->second; } } out << "\t" << "fraction\t" << (double)(stats.complete - bad)/stats.complete << std::endl; if (stats.pe) { out << "\t" << "se\t" << stats.se << std::endl; out << "\t" << "pe\t" << stats.pe << std::endl; } return out; }
Use correct API for fillByPosition()
// Written by : Chirantan Mitra #include <matrix.h> #include <cmath> class testFunctionoid { public: double operator() (double x, double y) { return (sin(x * y) + 1.0) / 2.0; } }; using namespace CMatrix; int main() { int size = 5; Matrix<double> matrix(size, size); matrix = matrix.fillByPosition(new testFunctionoid, size/2, size/2, 1.0/size, 1.0/size); std::cout << matrix << std::endl; }
// Written by : Chirantan Mitra #include <matrix.h> #include <cmath> class testFunctionoid { public: double operator() (double x, double y) { return (sin(x * y) + 1.0) / 2.0; } }; using namespace CMatrix; int main() { int size = 5; Matrix<double> matrix(size, size); matrix.fillByPosition(new testFunctionoid, size/2, size/2, 1.0/size, 1.0/size); std::cout << matrix << std::endl; }
Use auto to avoid repeat the type twice.
// Copyright 2015 Alessio Sclocco <alessio@sclocco.eu> // // 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 <utils.hpp> namespace isa { namespace utils { std::string * replace(std::string * src, const std::string & placeholder, const std::string & item, bool deleteSrc) { std::string * newString = new std::string(); size_t position = 0; size_t oldPosition = 0; while ( (position = src->find(placeholder, position)) < std::string::npos ) { newString->append(src->substr(oldPosition, position - oldPosition)); newString->append(item); position += placeholder.length(); oldPosition = position; } newString->append(src->substr(oldPosition)); if ( deleteSrc ) { delete src; } return newString; } } // utils } // isa
// Copyright 2015 Alessio Sclocco <alessio@sclocco.eu> // // 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 <utils.hpp> namespace isa { namespace utils { std::string * replace(std::string * src, const std::string & placeholder, const std::string & item, bool deleteSrc) { auto * newString = new std::string(); size_t position = 0; size_t oldPosition = 0; while ( (position = src->find(placeholder, position)) < std::string::npos ) { newString->append(src->substr(oldPosition, position - oldPosition)); newString->append(item); position += placeholder.length(); oldPosition = position; } newString->append(src->substr(oldPosition)); if ( deleteSrc ) { delete src; } return newString; } } // utils } // isa
Use an even more precise triple to avoid errors on Darwin, where we don't use comdats for inline entities.
// RUN: %clang_cc1 -fmodules -std=c++14 -emit-llvm %s -o - -triple %itanium_abi_triple | FileCheck %s #pragma clang module build A module A {} #pragma clang module contents #pragma clang module begin A template<int> int n = 42; decltype(n<0>) f(); #pragma clang module end #pragma clang module endbuild #pragma clang module build B module B {} #pragma clang module contents #pragma clang module begin B #pragma clang module import A inline int f() { return n<0>; } #pragma clang module end #pragma clang module endbuild #pragma clang module import B // CHECK: @_Z1nILi0EE = linkonce_odr global i32 42, comdat int g() { return f(); }
// RUN: %clang_cc1 -fmodules -std=c++14 -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s #pragma clang module build A module A {} #pragma clang module contents #pragma clang module begin A template<int> int n = 42; decltype(n<0>) f(); #pragma clang module end #pragma clang module endbuild #pragma clang module build B module B {} #pragma clang module contents #pragma clang module begin B #pragma clang module import A inline int f() { return n<0>; } #pragma clang module end #pragma clang module endbuild #pragma clang module import B // CHECK: @_Z1nILi0EE = linkonce_odr global i32 42, comdat int g() { return f(); }
Remove undeclared symbols in snippet
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "CustomViewer.h" #include "CustomViewerWorkbenchAdvisor.h" #include <berryPlatformUI.h> CustomViewer::CustomViewer() { } CustomViewer::~CustomViewer() { } //! [MinimalApplicationClass_StartMethod] int CustomViewer::Start() { berry::Display *display = berry::PlatformUI::CreateDisplay(); wbAdvisor.reset(new berry::WorkbenchAdvisor); int code = berry::PlatformUI::CreateAndRunWorkbench(display, wbAdvisor.data()); // exit the application with an appropriate return code return code == berry::PlatformUI::RETURN_RESTART ? EXIT_RESTART : EXIT_OK; } //! [MinimalApplicationClass_StartMethod] void CustomViewer::Stop() { }
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ //! [MinimalApplicationClass_StartMethod] berry::Display *display = berry::PlatformUI::CreateDisplay(); wbAdvisor.reset(new berry::WorkbenchAdvisor); int code = berry::PlatformUI::CreateAndRunWorkbench(display, wbAdvisor.data()); // exit the application with an appropriate return code return code == berry::PlatformUI::RETURN_RESTART ? EXIT_RESTART : EXIT_OK; //! [MinimalApplicationClass_StartMethod]
Fix up TestLldbGdbServer C++ test slug exe.
#include <cstdlib> #include <cstring> #include <iostream> #include <unistd.h> static const char *const RETVAL_PREFIX = "retval:"; static const char *const SLEEP_PREFIX = "sleep:"; static const char *const STDERR_PREFIX = "stderr:"; int main (int argc, char **argv) { int return_value = 0; for (int i = 1; i < argc; ++i) { if (std::strstr (argv[i], STDERR_PREFIX)) { // Treat remainder as text to go to stderr. std::cerr << (argv[i] + strlen (STDERR_PREFIX)) << std::endl; } else if (std::strstr (argv[i], RETVAL_PREFIX)) { // Treat as the return value for the program. return_value = std::atoi (argv[i] + strlen (RETVAL_PREFIX)); } else if (std::strstr (argv[i], SLEEP_PREFIX)) { // Treat as the amount of time to have this process sleep (in seconds). const int sleep_seconds = std::atoi (argv[i] + strlen (SLEEP_PREFIX)); const int sleep_result = sleep(sleep_seconds); printf("sleep result: %d\n", sleep_result); } else { // Treat the argument as text for stdout. std::cout << argv[i] << std::endl; } } return return_value; }
#include <cstdlib> #include <cstring> #include <iostream> #include <unistd.h> static const char *const RETVAL_PREFIX = "retval:"; static const char *const SLEEP_PREFIX = "sleep:"; static const char *const STDERR_PREFIX = "stderr:"; int main (int argc, char **argv) { int return_value = 0; for (int i = 1; i < argc; ++i) { if (std::strstr (argv[i], STDERR_PREFIX)) { // Treat remainder as text to go to stderr. std::cerr << (argv[i] + strlen (STDERR_PREFIX)) << std::endl; } else if (std::strstr (argv[i], RETVAL_PREFIX)) { // Treat as the return value for the program. return_value = std::atoi (argv[i] + strlen (RETVAL_PREFIX)); } else if (std::strstr (argv[i], SLEEP_PREFIX)) { // Treat as the amount of time to have this process sleep (in seconds). const int sleep_seconds = std::atoi (argv[i] + strlen (SLEEP_PREFIX)); const int sleep_result = sleep(sleep_seconds); std::cout << "sleep result: " << sleep_result << std::endl; } else { // Treat the argument as text for stdout. std::cout << argv[i] << std::endl; } } return return_value; }
Add allocation test for native_device (check ptr is not null)
#include "xchainer/native_device.h" #include <gtest/gtest.h> #include "xchainer/native_backend.h" namespace xchainer { namespace { TEST(NativeDeviceTest, Ctor) { NativeBackend backend; { NativeDevice device{backend, 0}; EXPECT_EQ(&backend, &deivce.backend()); EXPECT_EQ(0, device.index()); } { NativeDevice device{backend, 1}; EXPECT_EQ(&backend, &deivce.backend()); EXPECT_EQ(1, device.index()); } } } // namespace } // namespace xchainer
#include "xchainer/native_device.h" #include <gtest/gtest.h> #include "xchainer/native_backend.h" namespace xchainer { namespace { TEST(NativeDeviceTest, Ctor) { NativeBackend backend; { NativeDevice device{backend, 0}; EXPECT_EQ(&backend, &deivce.backend()); EXPECT_EQ(0, device.index()); } { NativeDevice device{backend, 1}; EXPECT_EQ(&backend, &deivce.backend()); EXPECT_EQ(1, device.index()); } } TEST(NativeDeviceTest, Allocate) { size_t size = 3; NativeBackend backend; NativeDevice device{backend, 0}; std::shared_ptr<void> ptr = device.Allocate(size); EXPECT_NE(nullptr, ptr); } } // namespace } // namespace xchainer
Add code to attack/health regex and parse it
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <Rosetta/Cards/Cards.hpp> #include <Rosetta/Enchants/Effects.hpp> #include <Rosetta/Enchants/Enchants.hpp> #include <regex> namespace RosettaStone { Enchant Enchants::GetEnchantFromText(const std::string& cardID) { std::vector<Effect> effects; static std::regex attackRegex("\\+([[:digit:]]+) Attack"); const std::string text = Cards::FindCardByID(cardID).text; std::smatch values; if (std::regex_search(text, values, attackRegex)) { effects.emplace_back(Effects::AttackN(std::stoi(values[1].str()))); } return Enchant(effects); } } // namespace RosettaStone
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <Rosetta/Cards/Cards.hpp> #include <Rosetta/Enchants/Effects.hpp> #include <Rosetta/Enchants/Enchants.hpp> #include <regex> namespace RosettaStone { Enchant Enchants::GetEnchantFromText(const std::string& cardID) { std::vector<Effect> effects; static std::regex attackHealthRegex("\\+([[:digit:]]+)/\\+([[:digit:]]+)"); static std::regex attackRegex("\\+([[:digit:]]+) Attack"); const std::string text = Cards::FindCardByID(cardID).text; std::smatch values; if (std::regex_search(text, values, attackHealthRegex)) { effects.emplace_back(Effects::AttackN(std::stoi(values[1].str()))); effects.emplace_back(Effects::HealthN(std::stoi(values[2].str()))); } else if (std::regex_search(text, values, attackRegex)) { effects.emplace_back(Effects::AttackN(std::stoi(values[1].str()))); } return Enchant(effects); } } // namespace RosettaStone
Use `coderInfoList` and prepare for a `writable` flag
#include <iostream> #include <Magick++/Blob.h> #include <Magick++/Image.h> extern "C" int main() { size_t nFormats; Magick::ExceptionInfo ex; const Magick::MagickInfo **formats = GetMagickInfoList("*", &nFormats, &ex); for (size_t i = 0; i < nFormats; i++) { const Magick::MagickInfo *format = formats[i]; if (format->encoder && format->name) { std::cout << format->name << std::endl; } } RelinquishMagickMemory(formats); }
#include <iostream> #include <list> #include <Magick++/Image.h> #include <Magick++/STL.h> int main() { std::list<Magick::CoderInfo> coderList; coderInfoList(&coderList, Magick::CoderInfo::TrueMatch, Magick::CoderInfo::AnyMatch, Magick::CoderInfo::AnyMatch); for (std::list<Magick::CoderInfo>::iterator it = coderList.begin(); it != coderList.end(); it++) { //std::cout << ((*it).isWritable() ? "+" : "-") << (*it).name() << std::endl; std::cout << (*it).name() << std::endl; } }
Remove BrowserList::GetLastActive usage in cocoa-land.
// 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/ui/cocoa/last_active_browser_cocoa.h" #include "chrome/browser/ui/browser_list.h" namespace chrome { Browser* GetLastActiveBrowser() { return BrowserList::GetLastActive(); } } // namespace chrome
// 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/ui/cocoa/last_active_browser_cocoa.h" #include "chrome/browser/ui/browser_finder.h" namespace chrome { Browser* GetLastActiveBrowser() { return browser::FindLastActiveWithHostDesktopType(HOST_DESKTOP_TYPE_NATIVE); } } // namespace chrome
Fix build on OS X.
#include "keytar.h" #include <Security/Security.h> namespace keytar { bool AddPassword(const std::string& service, const std::string& account, const std::string& password) { OSStatus status = SecKeychainAddGenericPassword(NULL, service.length(), service.data(), account.length(), account.data(), password.length(), password.data(), NULL); return status == errSecSuccess; } bool GetPassword(const std::string& service, const std::string& account, std::string* password) { void *data; UInt32 length; OSStatus status = SecKeychainFindGenericPassword(NULL, service.length(), service.data(), account.length(), account.data(), &length, &data, NULL); if (status != errSecSuccess) return false; *password = std::string(reinterpret_cast<const char*>(data), length); SecKeychainItemFreeContent(data); return true; } bool DeletePassword(const std::string& service, const std::string& account) { OSStatus status = SecKeychainFindGenericPassword(NULL, service.length(), service.data(), account.length(), account.data(), NULL, NULL, NULL); return status == errSecSuccess; } } // namespace keytar
#include "keytar.h" #include <Security/Security.h> namespace keytar { bool AddPassword(const std::string& service, const std::string& account, const std::string& password) { OSStatus status = SecKeychainAddGenericPassword(NULL, service.length(), service.data(), account.length(), account.data(), password.length(), password.data(), NULL); return status == errSecSuccess; } bool GetPassword(const std::string& service, const std::string& account, std::string* password) { void *data; UInt32 length; OSStatus status = SecKeychainFindGenericPassword(NULL, service.length(), service.data(), account.length(), account.data(), &length, &data, NULL); if (status != errSecSuccess) return false; *password = std::string(reinterpret_cast<const char*>(data), length); SecKeychainItemFreeContent(NULL, data); return true; } bool DeletePassword(const std::string& service, const std::string& account) { SecKeychainItemRef item; OSStatus status = SecKeychainFindGenericPassword(NULL, service.length(), service.data(), account.length(), account.data(), NULL, NULL, &item); if (status != errSecSuccess) return false; status = SecKeychainItemDelete(item); CFRelease(item); return status == errSecSuccess; } } // namespace keytar
Fix the loop expr of Bubble sort
#include "bubble.hpp" #include "swap.hpp" void bubble(int *data, const int size_of_data) { if(size_of_data <= 0) return; for(int i = 0; i < size_of_data; ++i) if(data[i] > data[i + 1]) swap(data[i], data[i + 1]); return bubble(data, size_of_data - 1); }
#include "bubble.hpp" #include "swap.hpp" void bubble(int *data, const int size_of_data) { if(size_of_data <= 0) return; for(int i = 0; i + 1 < size_of_data; ++i) if(data[i] > data[i + 1]) swap(data[i], data[i + 1]); return bubble(data, size_of_data - 1); }
Remove name, add body. Causes llvmg++ segfault!
// This tests compilation of EMPTY_CLASS_EXPR's struct empty {}; void foo(empty E); void bar() { foo(empty()); }
// This tests compilation of EMPTY_CLASS_EXPR's struct empty {}; void foo(empty) {} void bar() { foo(empty()); }
Define stacktrace functions only if __GLIBC__ is defined
// StackTrace.cpp // Implements the functions to print current stack traces #include "Globals.h" #include "StackTrace.h" #ifdef _WIN32 #include "../StackWalker.h" #else #include <execinfo.h> #include <unistd.h> #endif // FreeBSD uses size_t for the return type of backtrace() #if defined(__FreeBSD__) && (__FreeBSD__ >= 10) #define btsize size_t #else #define btsize int #endif void PrintStackTrace(void) { #ifdef _WIN32 // Reuse the StackWalker from the LeakFinder project already bound to MCS // Define a subclass of the StackWalker that outputs everything to stdout class PrintingStackWalker : public StackWalker { virtual void OnOutput(LPCSTR szText) override { puts(szText); } } sw; sw.ShowCallstack(); #else // Use the backtrace() function to get and output the stackTrace: // Code adapted from http://stackoverflow.com/questions/77005/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes void * stackTrace[30]; btsize numItems = backtrace(stackTrace, ARRAYCOUNT(stackTrace)); backtrace_symbols_fd(stackTrace, numItems, STDERR_FILENO); #endif }
// StackTrace.cpp // Implements the functions to print current stack traces #include "Globals.h" #include "StackTrace.h" #ifdef _WIN32 #include "../StackWalker.h" #else #include <execinfo.h> #include <unistd.h> #endif // FreeBSD uses size_t for the return type of backtrace() #if defined(__FreeBSD__) && (__FreeBSD__ >= 10) #define btsize size_t #else #define btsize int #endif void PrintStackTrace(void) { #ifdef _WIN32 // Reuse the StackWalker from the LeakFinder project already bound to MCS // Define a subclass of the StackWalker that outputs everything to stdout class PrintingStackWalker : public StackWalker { virtual void OnOutput(LPCSTR szText) override { puts(szText); } } sw; sw.ShowCallstack(); #else #ifdef __GLIBC__ // Use the backtrace() function to get and output the stackTrace: // Code adapted from http://stackoverflow.com/questions/77005/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes void * stackTrace[30]; btsize numItems = backtrace(stackTrace, ARRAYCOUNT(stackTrace)); backtrace_symbols_fd(stackTrace, numItems, STDERR_FILENO); #endif #endif }
Verify JVM libraries found in the filesystem as being 1.7 or higher during tests.
/** * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ #include "stdafx.h" #ifndef __cplusplus_cli int main (int argc, char **argv) { CAbstractTest::Main (argc, argv); return 0; } #endif /* ifndef __cplusplus_cli */
/** * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ #include "stdafx.h" #include "Service/Service.h" #ifndef __cplusplus_cli int main (int argc, char **argv) { if ((argc == 3) && !strcmp (argv[1], "jvm")) { return ServiceTestJVM (argv[2]) ? 0 : 1; } CAbstractTest::Main (argc, argv); return 0; } #endif /* ifndef __cplusplus_cli */
Check device count before claiming to be enabled
#include <occa/defines.hpp> #include <occa/modes/metal/registration.hpp> namespace occa { namespace metal { modeInfo::modeInfo() {} bool modeInfo::init() { return OCCA_METAL_ENABLED; } styling::section& modeInfo::getDescription() { static styling::section section("Metal"); if (section.size() == 0) { int deviceCount = api::metal::getDeviceCount(); for (int deviceId = 0; deviceId < deviceCount; ++deviceId) { api::metal::device_t device = api::metal::getDevice(deviceId); udim_t bytes = device.getMemorySize(); std::string bytesStr = stringifyBytes(bytes); section .add("Device Name", device.getName()) .add("Device ID" , toString(deviceId)) .add("Memory" , bytesStr) .addDivider(); } // Remove last divider section.groups.pop_back(); } return section; } occa::mode<metal::modeInfo, metal::device> mode("Metal"); } }
#include <occa/defines.hpp> #include <occa/modes/metal/registration.hpp> namespace occa { namespace metal { modeInfo::modeInfo() {} bool modeInfo::init() { #if OCCA_METAL_ENABLED // Only consider metal enabled if there is a device return api::metal::getDeviceCount(); #else return false; #endif } styling::section& modeInfo::getDescription() { static styling::section section("Metal"); if (section.size() == 0) { int deviceCount = api::metal::getDeviceCount(); for (int deviceId = 0; deviceId < deviceCount; ++deviceId) { api::metal::device_t device = api::metal::getDevice(deviceId); udim_t bytes = device.getMemorySize(); std::string bytesStr = stringifyBytes(bytes); section .add("Device Name", device.getName()) .add("Device ID" , toString(deviceId)) .add("Memory" , bytesStr) .addDivider(); } // Remove last divider section.groups.pop_back(); } return section; } occa::mode<metal::modeInfo, metal::device> mode("Metal"); } }
Use PRIi64 macro to work around clang weirdness.
#include "rdb_protocol/configured_limits.hpp" #include <limits> #include "rdb_protocol/wire_func.hpp" #include "rdb_protocol/func.hpp" namespace ql { configured_limits_t from_optargs(rdb_context_t *ctx, signal_t *interruptor, global_optargs_t *arguments) { if (arguments->has_optarg("array_limit")) { // Fake an environment with no arguments. We have to fake it // because of a chicken/egg problem; this function gets called // before there are any extant environments at all. Only // because we use an empty argument list do we prevent an // infinite loop. env_t env(ctx, interruptor, std::map<std::string, wire_func_t>(), nullptr); int64_t limit = arguments->get_optarg(&env, "array_limit")->as_int(); rcheck_datum(limit > 1, base_exc_t::GENERIC, strprintf("Illegal array size limit `%ld`.", limit)); return configured_limits_t(limit); } else { return configured_limits_t(); } } RDB_IMPL_ME_SERIALIZABLE_1(configured_limits_t, array_size_limit_); INSTANTIATE_SERIALIZABLE_SELF_FOR_CLUSTER(configured_limits_t); const configured_limits_t configured_limits_t::unlimited(std::numeric_limits<size_t>::max()); } // namespace ql
#include "rdb_protocol/configured_limits.hpp" #include <limits> #include "rdb_protocol/wire_func.hpp" #include "rdb_protocol/func.hpp" namespace ql { configured_limits_t from_optargs(rdb_context_t *ctx, signal_t *interruptor, global_optargs_t *arguments) { if (arguments->has_optarg("array_limit")) { // Fake an environment with no arguments. We have to fake it // because of a chicken/egg problem; this function gets called // before there are any extant environments at all. Only // because we use an empty argument list do we prevent an // infinite loop. env_t env(ctx, interruptor, std::map<std::string, wire_func_t>(), nullptr); int64_t limit = arguments->get_optarg(&env, "array_limit")->as_int(); rcheck_datum(limit > 1, base_exc_t::GENERIC, strprintf("Illegal array size limit `%" PRIi64 "`.", limit)); return configured_limits_t(limit); } else { return configured_limits_t(); } } RDB_IMPL_ME_SERIALIZABLE_1(configured_limits_t, array_size_limit_); INSTANTIATE_SERIALIZABLE_SELF_FOR_CLUSTER(configured_limits_t); const configured_limits_t configured_limits_t::unlimited(std::numeric_limits<size_t>::max()); } // namespace ql
Add an HTTP basic auth unit test for an empty username.
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "testing/gtest/include/gtest/gtest.h" #include "base/basictypes.h" #include "net/http/http_auth_handler_basic.h" namespace net { TEST(HttpAuthHandlerBasicTest, GenerateCredentials) { static const struct { const wchar_t* username; const wchar_t* password; const char* expected_credentials; } tests[] = { { L"foo", L"bar", "Basic Zm9vOmJhcg==" }, // Empty password { L"anon", L"", "Basic YW5vbjo=" }, }; for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) { std::string challenge = "Basic realm=\"Atlantis\""; HttpAuthHandlerBasic basic; basic.InitFromChallenge(challenge.begin(), challenge.end(), HttpAuth::AUTH_SERVER); std::string credentials = basic.GenerateCredentials(tests[i].username, tests[i].password, NULL, NULL); EXPECT_STREQ(tests[i].expected_credentials, credentials.c_str()); } } } // namespace net
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "testing/gtest/include/gtest/gtest.h" #include "base/basictypes.h" #include "net/http/http_auth_handler_basic.h" namespace net { TEST(HttpAuthHandlerBasicTest, GenerateCredentials) { static const struct { const wchar_t* username; const wchar_t* password; const char* expected_credentials; } tests[] = { { L"foo", L"bar", "Basic Zm9vOmJhcg==" }, // Empty username { L"", L"foobar", "Basic OmZvb2Jhcg==" }, // Empty password { L"anon", L"", "Basic YW5vbjo=" }, }; for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) { std::string challenge = "Basic realm=\"Atlantis\""; HttpAuthHandlerBasic basic; basic.InitFromChallenge(challenge.begin(), challenge.end(), HttpAuth::AUTH_SERVER); std::string credentials = basic.GenerateCredentials(tests[i].username, tests[i].password, NULL, NULL); EXPECT_STREQ(tests[i].expected_credentials, credentials.c_str()); } } } // namespace net
Enable function keys in ncurses mode.
#include <stdint.h> #include <ncurses.h> #include "display/Screen.h" Screen::Screen() { //Initialized the screen initscr(); //Start with a clean slate clear(); //Don't echo entered characters on the screen noecho(); //Hide the cursor curs_set(false); //Refresh the screen (to our blank state) /// @todo Why does it seem necessary to refresh() before we draw anything? /// Only required when going straight into multiple windows? refresh(); //Get our height and width for later getmaxyx(stdscr, _height, _width); } Screen::~Screen() { endwin(); } uint32_t Screen::getHeight() { return _height; } uint32_t Screen::getWidth() { return _width; }
#include <stdint.h> #include <ncurses.h> #include "display/Screen.h" Screen::Screen() { //Initialized the screen initscr(); //Start with a clean slate clear(); //Don't echo entered characters on the screen noecho(); //Enable getting function keys keypad(stdscr, true); //Hide the cursor curs_set(false); //Refresh the screen (to our blank state) /// @todo Why does it seem necessary to refresh() before we draw anything? /// Only required when going straight into multiple windows? refresh(); //Get our height and width for later getmaxyx(stdscr, _height, _width); } Screen::~Screen() { endwin(); } uint32_t Screen::getHeight() { return _height; } uint32_t Screen::getWidth() { return _width; }
Create ProblemSolver instance with method create.
// Copyright (C) 2009, 2010 by Florent Lamiraux, Thomas Moulard, JRL. // // This file is part of the hpp-corbaserver. // // This software is provided "as is" without warranty of any kind, // either expressed or implied, including but not limited to the // implied warranties of fitness for a particular purpose. // // See the COPYING file for more information. #include <iostream> #include <hpp/util/debug.hh> #include "hpp/corbaserver/server.hh" using hpp::corbaServer::Server; int main (int argc, const char* argv[]) { hpp::core::ProblemSolverPtr_t problemSolver = new hpp::core::ProblemSolver; Server server (problemSolver, argc, argv, true); server.startCorbaServer (); server.processRequest(true); }
// Copyright (C) 2009, 2010 by Florent Lamiraux, Thomas Moulard, JRL. // // This file is part of the hpp-corbaserver. // // This software is provided "as is" without warranty of any kind, // either expressed or implied, including but not limited to the // implied warranties of fitness for a particular purpose. // // See the COPYING file for more information. #include <iostream> #include <hpp/util/debug.hh> #include "hpp/corbaserver/server.hh" using hpp::corbaServer::Server; int main (int argc, const char* argv[]) { hpp::core::ProblemSolverPtr_t problemSolver = hpp::core::ProblemSolver::create (); Server server (problemSolver, argc, argv, true); server.startCorbaServer (); server.processRequest(true); }
Add a version info function which returns a u32bit. The currently expected value is 20100728 (ie, today). This will allow for checking for and/or working around changes to interfaces.
/** * Dynamically Loaded Engine * (C) 2010 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/dyn_engine.h> #include <botan/internal/dyn_load.h> namespace Botan { namespace { extern "C" { typedef Engine* (*creator_function)(void); typedef void (*destructor_function)(Engine*); } } Dynamically_Loaded_Engine::Dynamically_Loaded_Engine( const std::string& library_path) : engine(0) { lib = new Dynamically_Loaded_Library(library_path); try { creator_function creator = lib->resolve<creator_function>("create_engine"); engine = creator(); if(!engine) throw std::runtime_error("Creator function in " + library_path + " failed"); } catch(...) { delete lib; lib = 0; throw; } } Dynamically_Loaded_Engine::~Dynamically_Loaded_Engine() { if(lib && engine) { try { destructor_function destroy = lib->resolve<destructor_function>("destroy_engine"); destroy(engine); } catch(...) { delete lib; lib = 0; throw; } } if(lib) delete lib; } }
/** * Dynamically Loaded Engine * (C) 2010 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/dyn_engine.h> #include <botan/internal/dyn_load.h> namespace Botan { namespace { extern "C" { typedef Engine* (*creator_function)(void); typedef void (*destructor_function)(Engine*); typedef u32bit (*module_version)(void); } } Dynamically_Loaded_Engine::Dynamically_Loaded_Engine( const std::string& library_path) : engine(0) { lib = new Dynamically_Loaded_Library(library_path); try { module_version version = lib->resolve<module_version>("module_version"); u32bit mod_version = version(); if(mod_version != 20100728) throw std::runtime_error("Unexpected or incompatible version in " + library_path); creator_function creator = lib->resolve<creator_function>("create_engine"); engine = creator(); if(!engine) throw std::runtime_error("Creator function in " + library_path + " failed"); } catch(...) { delete lib; lib = 0; throw; } } Dynamically_Loaded_Engine::~Dynamically_Loaded_Engine() { if(lib && engine) { try { destructor_function destroy = lib->resolve<destructor_function>("destroy_engine"); destroy(engine); } catch(...) { delete lib; lib = 0; throw; } } if(lib) delete lib; } }
Update cpuid test to expect failure on non intel cpu
/* * Copyright 2017 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 <folly/CpuId.h> #include <folly/portability/GTest.h> using namespace folly; TEST(CpuId, Simple) { // All CPUs should support MMX CpuId id; EXPECT_TRUE(id.mmx()); }
/* * Copyright 2017-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 <folly/CpuId.h> #include <folly/portability/GTest.h> using namespace folly; TEST(CpuId, Simple) { CpuId id; // All x64 CPUs should support MMX EXPECT_EQ(kIsArchAmd64, id.mmx()); }
Disable test failing since r29947.
// 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_; }
// 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" // Started failing with r29947. WebKit merge 49961:49992. IN_PROC_BROWSER_TEST_F(DISABLED_ExtensionApiTest, Storage) { ASSERT_TRUE(RunExtensionTest("storage")) << message_; }