Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Set Console object to non writable
#include "library.h" #include "libs/console.h" // console.log, console.error namespace grok { namespace libs { using namespace grok::vm; using namespace grok::obj; int LoadLibraries(VMContext *ctx) { // just console for now auto V = GetVStore(ctx); auto C = std::make_shared<Console>(); auto Wrapped = Value(std::make_shared<Object>(C)); V->StoreValue("console", Wrapped); return 0; } } }
#include "library.h" #include "libs/console.h" // console.log, console.error namespace grok { namespace libs { using namespace grok::vm; using namespace grok::obj; int LoadLibraries(VMContext *ctx) { // just console for now auto V = GetVStore(ctx); auto C = std::make_shared<Console>(); DefineInternalObjectProperties(C.get()); C->SetNonWritable(); auto Wrapped = Value(std::make_shared<Object>(C)); V->StoreValue("console", Wrapped); return 0; } } }
Fix missing symbols in thread cache.
#include "thread_cache.h" #include "allocators/dq_sc_allocator.h" #include "runtime_vars.h" namespace { cache_aligned SpinLock g_threadcache_lock(LINKER_INITIALIZED); cache_aligned scalloc::PageHeapAllocator<scalloc::ThreadCache, 64> g_threadcache_alloc; cache_aligned uint64_t g_thread_id; } // namespace namespace scalloc { void ThreadCache::InitModule() { SpinLockHolder holder(&g_threadcache_lock); CompilerBarrier(); if(!module_init_) { RuntimeVars::InitModule(); SlabScAllocator::InitModule(); DQScAllocator::InitModule(); g_threadcache_alloc.Init(RuntimeVars::SystemPageSize()); module_init_ = true; } } ThreadCache* ThreadCache::NewCache() { ThreadCache* cache = NULL; { SpinLockHolder holder(&g_threadcache_lock); CompilerBarrier(); cache = g_threadcache_alloc.New(); } cache->allocator_.Init(__sync_fetch_and_add(&g_thread_id, 1)); return cache; } } // namespace scalloc
#include "thread_cache.h" #include "allocators/dq_sc_allocator.h" #include "runtime_vars.h" namespace { cache_aligned SpinLock g_threadcache_lock(LINKER_INITIALIZED); cache_aligned scalloc::PageHeapAllocator<scalloc::ThreadCache, 64> g_threadcache_alloc; cache_aligned uint64_t g_thread_id; } // namespace namespace scalloc { bool ThreadCache::module_init_; __thread ThreadCache* ThreadCache::tl_cache_ TLS_MODE; void ThreadCache::InitModule() { SpinLockHolder holder(&g_threadcache_lock); CompilerBarrier(); if(!module_init_) { RuntimeVars::InitModule(); SlabScAllocator::InitModule(); DQScAllocator::InitModule(); SizeMap::Instance().Init(); g_threadcache_alloc.Init(RuntimeVars::SystemPageSize()); module_init_ = true; } } ThreadCache* ThreadCache::NewCache() { ThreadCache* cache = NULL; { SpinLockHolder holder(&g_threadcache_lock); CompilerBarrier(); cache = g_threadcache_alloc.New(); } cache->allocator_.Init(__sync_fetch_and_add(&g_thread_id, 1)); return cache; } } // namespace scalloc
Extend first camera test and add another one.
#include "./test.h" #include "../src/camera.h" TEST(Test_Camera, ConstructorFromMatrices) { Camera expected; Camera camera(expected.getViewMatrix(), expected.getProjectionMatrix(), expected.getOrigin()); EXPECT_Vector3f_NEAR(expected.getPosition(), camera.getPosition(), 1e-5f); EXPECT_NEAR(expected.getRadius(), camera.getRadius(), 1e-5f); // just to recalculate the view matrix from the angles and test them camera.changeAzimuth(0); EXPECT_Matrix4f_NEAR(expected.getViewMatrix(), camera.getViewMatrix(), 1e-5f); }
#include "./test.h" #include "../src/camera.h" TEST(Test_Camera, ConstructorFromMatricesWithDefaultValues) { Camera expected; Camera camera(expected.getViewMatrix(), expected.getProjectionMatrix(), expected.getOrigin()); EXPECT_Vector3f_NEAR(expected.getPosition(), camera.getPosition(), 1e-5f); EXPECT_NEAR(expected.getRadius(), camera.getRadius(), 1e-5f); // just to recalculate the view matrix from the angles and test them camera.changeAzimuth(0); EXPECT_Matrix4f_NEAR(expected.getViewMatrix(), camera.getViewMatrix(), 1e-5f); EXPECT_Matrix4f_NEAR(expected.getProjectionMatrix(), camera.getProjectionMatrix(), 1e-5f); EXPECT_Vector3f_NEAR(expected.getPosition(), camera.getPosition(), 1e-5f); } TEST(Test_Camera, ConstructorFromMatricesAfterRotation) { Camera expected; expected.changeAzimuth(M_PI * 0.25f); Camera camera(expected.getViewMatrix(), expected.getProjectionMatrix(), expected.getOrigin()); EXPECT_Vector3f_NEAR(expected.getPosition(), camera.getPosition(), 1e-5f); EXPECT_NEAR(expected.getRadius(), camera.getRadius(), 1e-5f); // just to recalculate the view matrix from the angles and test them camera.changeAzimuth(0); EXPECT_Matrix4f_NEAR(expected.getViewMatrix(), camera.getViewMatrix(), 1e-5f); EXPECT_Matrix4f_NEAR(expected.getProjectionMatrix(), camera.getProjectionMatrix(), 1e-5f); EXPECT_Vector3f_NEAR(expected.getPosition(), camera.getPosition(), 1e-5f); }
Simplify LightingFilter in add-free case am: 0698300cc5
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkColorMatrixFilter.h" static SkScalar byte_to_scale(U8CPU byte) { if (0xFF == byte) { // want to get this exact return 1; } else { return byte * 0.00392156862745f; } } SkColorFilter* SkColorMatrixFilter::CreateLightingFilter(SkColor mul, SkColor add) { SkColorMatrix matrix; matrix.setScale(byte_to_scale(SkColorGetR(mul)), byte_to_scale(SkColorGetG(mul)), byte_to_scale(SkColorGetB(mul)), 1); matrix.postTranslate(SkIntToScalar(SkColorGetR(add)), SkIntToScalar(SkColorGetG(add)), SkIntToScalar(SkColorGetB(add)), 0); return SkColorMatrixFilter::Create(matrix); }
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkColorMatrixFilter.h" static SkScalar byte_to_scale(U8CPU byte) { if (0xFF == byte) { // want to get this exact return 1; } else { return byte * 0.00392156862745f; } } SkColorFilter* SkColorMatrixFilter::CreateLightingFilter(SkColor mul, SkColor add) { if (0 == add) { return SkColorFilter::CreateModeFilter(mul | SK_ColorBLACK, SkXfermode::Mode::kModulate_Mode); } SkColorMatrix matrix; matrix.setScale(byte_to_scale(SkColorGetR(mul)), byte_to_scale(SkColorGetG(mul)), byte_to_scale(SkColorGetB(mul)), 1); matrix.postTranslate(SkIntToScalar(SkColorGetR(add)), SkIntToScalar(SkColorGetG(add)), SkIntToScalar(SkColorGetB(add)), 0); return SkColorMatrixFilter::Create(matrix); }
Allow to run doer as a different user on the same machine
#include <QApplication> #include "mainwindow.h" #include "runguard.h" int main(int argc, char **argv) { RunGuard guard("UwNDcyZjc6MjE1tN2Ma3NGIf5OGx"); if (!guard.tryToRun()) return 0; QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }
#include <QApplication> #include "mainwindow.h" #include "runguard.h" QString getUserName() { QString name = qgetenv("USER"); if (name.isEmpty()) name = qgetenv("USERNAME"); return name; } int main(int argc, char **argv) { RunGuard guard(getUserName() + "-doer-UwNDcyZjc6MjE1tN2Ma3NGIf5OGx"); if (!guard.tryToRun()) return 0; QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }
Use C++11 <random> instead of C rand().
#include <iostream> #include <cstdlib> // for RAND_MAX #include <ctime> using namespace std; int main(int argc, char* argv[]) { const int LARGEST_POSSIBLE = 100; srand(time(0)); // seed the random number generator based on current time //srand(10); rand(); // the rand() function generates a random integer from 0 to RAND_MAX int chosen = rand() % 101 ; // how to cut interval to [0, 100]? cout << "I choose the number " << chosen << "!" << endl; cout << "RAND_MAX is " << RAND_MAX << endl; }
#include <iostream> #include <random> using namespace std; int main(int argc, char* argv[]) { const int LARGEST_POSSIBLE = 100; // Some of this will look funny for now; we will explain later. // A random_device helps to "seed" a number generator. random_device rd; // a compiler-chosen "good" random number generator. default_random_engine engine(rd()); // Takes the output of the engine and maps it to a uniform distribution // between two parameters. uniform_int_distribution<int> distr(1, LARGEST_POSSIBLE); // Now "call" the distribution to get a number. int chosen = distr(engine); cout << "I choose the number " << chosen << "!" << endl; // Every time I call the distribution I get a new number. cout << "Next number: " << distr(engine) << endl; cout << "Next number: " << distr(engine) << endl; }
Mark stack allocated page as unused
#include <Pith/Config.hpp> #include <Pith/Page.hpp> #include <gtest/gtest.h> using namespace Pith; TEST(TestPage, StackAllocate) { Page p; } TEST(TestPage, mapOnePage) { Span<Page> pages{nullptr, 1}; auto result = Page::map(pages); EXPECT_TRUE(result); EXPECT_NE(result(), nullptr); pages.value(result()); EXPECT_EQ(Page::unmap(pages), 0); } TEST(TestPage, setPermissions) { Span<Page> pages{nullptr, 1}; } TEST(TestPage, setPermissionsOnUnmappedPage) { Span<Page> pages{nullptr, 1}; // Get a fresh page. { auto r = Page::map(pages); ASSERT_TRUE(r); pages.value(r()); } // Explicitly unmap it. { auto e = Page::unmap(pages); ASSERT_EQ(e, 0); } // Fail to set permissions on unmapped page. { auto e = Page::setPermissions(pages, Page::Permissions::READ); ASSERT_NE(e, 0); } } #if 0 TEST(PageSpan, mapAndUnmap) { PageSpan pages{nullptr, 1}; auto map = pages.map(); map.unmap(); } #endif // 0
#include <Pith/Config.hpp> #include <Pith/Page.hpp> #include <gtest/gtest.h> using namespace Pith; TEST(TestPage, stackAllocate) { [[maybe_unused]] Page p; } TEST(TestPage, mapOnePage) { Span<Page> pages{nullptr, 1}; auto result = Page::map(pages); EXPECT_TRUE(result); EXPECT_NE(result(), nullptr); pages.value(result()); EXPECT_EQ(Page::unmap(pages), 0); } TEST(TestPage, setPermissions) { Span<Page> pages{nullptr, 1}; } TEST(TestPage, setPermissionsOnUnmappedPage) { Span<Page> pages{nullptr, 1}; // Get a fresh page. { auto r = Page::map(pages); ASSERT_TRUE(r); pages.value(r()); } // Explicitly unmap it. { auto e = Page::unmap(pages); ASSERT_EQ(e, 0); } // Fail to set permissions on unmapped page. { auto e = Page::setPermissions(pages, Page::Permissions::READ); ASSERT_NE(e, 0); } } #if 0 TEST(PageSpan, mapAndUnmap) { PageSpan pages{nullptr, 1}; auto map = pages.map(); map.unmap(); } #endif // 0
Update nanoFramework.Networking.Sntp version to 1.0.2 ***NO_CI***
// // Copyright (c) 2018 The nanoFramework project contributors // See LICENSE file in the project root for full license information. // #include "nf_networking_sntp.h" static const CLR_RT_MethodHandler method_lookup[] = { NULL, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::Start___STATIC__VOID, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::Stop___STATIC__VOID, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::UpdateNow___STATIC__VOID, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_IsStarted___STATIC__BOOLEAN, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_Server1___STATIC__STRING, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::set_Server1___STATIC__VOID__STRING, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_Server2___STATIC__STRING, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::set_Server2___STATIC__VOID__STRING, }; const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_nanoFramework_Networking_Sntp = { "nanoFramework.Networking.Sntp", 0x733B4551, method_lookup, { 1, 0, 2, 49 } };
// // Copyright (c) 2018 The nanoFramework project contributors // See LICENSE file in the project root for full license information. // #include "nf_networking_sntp.h" static const CLR_RT_MethodHandler method_lookup[] = { NULL, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::Start___STATIC__VOID, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::Stop___STATIC__VOID, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::UpdateNow___STATIC__VOID, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_IsStarted___STATIC__BOOLEAN, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_Server1___STATIC__STRING, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::set_Server1___STATIC__VOID__STRING, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_Server2___STATIC__STRING, Library_nf_networking_sntp_nanoFramework_Networking_Sntp::set_Server2___STATIC__VOID__STRING, }; const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_nanoFramework_Networking_Sntp = { "nanoFramework.Networking.Sntp", 0x733B4551, method_lookup, { 1, 0, 2, 2 } };
Fix warning: convert from char** to const char**
/** * Zillians MMO * Copyright (C) 2007-2010 Zillians.com, Inc. * For more information see http://www.zillians.com * * Zillians MMO is the library and runtime for massive multiplayer online game * development in utility computing model, which runs as a service for every * developer to build their virtual world running on our GPU-assisted machines. * * This is a close source library intended to be used solely within Zillians.com * * 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 * COPYRIGHT HOLDER(S) 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 "language/logging/LoggerWrapper.h" #include "language/ThorScriptVM.h" int main(int argc, char** argv) { zillians::language::ThorScriptVM vm; return vm.main(argc, argv); }
/** * Zillians MMO * Copyright (C) 2007-2010 Zillians.com, Inc. * For more information see http://www.zillians.com * * Zillians MMO is the library and runtime for massive multiplayer online game * development in utility computing model, which runs as a service for every * developer to build their virtual world running on our GPU-assisted machines. * * This is a close source library intended to be used solely within Zillians.com * * 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 * COPYRIGHT HOLDER(S) 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 "language/logging/LoggerWrapper.h" #include "language/ThorScriptVM.h" int main(int argc, const char** argv) { zillians::language::ThorScriptVM vm; return vm.main(argc, argv); }
Use std::async() instead of std::thread()
#include "Halide.h" #include <stdio.h> #include <thread> using namespace Halide; int main(int argc, char **argv) { // Test if the compiler itself is thread-safe. This test is // intended to be run in a thread-sanitizer. std::vector<std::thread> threads; for (int i = 0; i < 1000; i++) { threads.emplace_back([]{ Func f; Var x; f(x) = x; f.realize(100); }); } for (auto &t : threads) { t.join(); } printf("Success!\n"); return 0; }
#include "Halide.h" #include <stdio.h> #include <future> using namespace Halide; static std::atomic<int> foo; int main(int argc, char **argv) { // Test if the compiler itself is thread-safe. This test is // intended to be run in a thread-sanitizer. std::vector<std::future<void>> futures; for (int i = 0; i < 1000; i++) { futures.emplace_back(std::async(std::launch::async, []{ Func f; Var x; f(x) = x; f.realize(100); })); } for (auto &f : futures) { f.wait(); } printf("Success!\n"); return 0; }
Make the initial window size larger to see all text
#include "MainWindow.h" #include <Application.h> #include <Menu.h> #include <MenuItem.h> #include <View.h> #include "MainView.h" MainWindow::MainWindow(void) : BWindow(BRect(100,100,500,400),"Font Demo", B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS) { BRect r(Bounds()); r.bottom = 20; fMenuBar = new BMenuBar(r,"menubar"); AddChild(fMenuBar); r = Bounds(); r.top = 20; MainView *view = new MainView(r); AddChild(view); } void MainWindow::MessageReceived(BMessage *msg) { switch (msg->what) { default: { BWindow::MessageReceived(msg); break; } } } bool MainWindow::QuitRequested(void) { be_app->PostMessage(B_QUIT_REQUESTED); return true; }
#include "MainWindow.h" #include <Application.h> #include <Menu.h> #include <MenuItem.h> #include <View.h> #include "MainView.h" MainWindow::MainWindow(void) : BWindow(BRect(100, 100, 900, 550),"Font Demo", B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS) { BRect r(Bounds()); r.bottom = 20; fMenuBar = new BMenuBar(r,"menubar"); AddChild(fMenuBar); r = Bounds(); r.top = 20; MainView *view = new MainView(r); AddChild(view); } void MainWindow::MessageReceived(BMessage *msg) { switch (msg->what) { default: { BWindow::MessageReceived(msg); break; } } } bool MainWindow::QuitRequested(void) { be_app->PostMessage(B_QUIT_REQUESTED); return true; }
Add null check in WebExternalBitmapImpl::pixels.
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "cc/blink/web_external_bitmap_impl.h" #include "cc/resources/shared_bitmap.h" namespace cc_blink { namespace { SharedBitmapAllocationFunction g_memory_allocator; } // namespace void SetSharedBitmapAllocationFunction( SharedBitmapAllocationFunction allocator) { g_memory_allocator = allocator; } WebExternalBitmapImpl::WebExternalBitmapImpl() { } WebExternalBitmapImpl::~WebExternalBitmapImpl() { } void WebExternalBitmapImpl::setSize(blink::WebSize size) { if (size != size_) { shared_bitmap_ = g_memory_allocator(gfx::Size(size)); size_ = size; } } blink::WebSize WebExternalBitmapImpl::size() { return size_; } uint8* WebExternalBitmapImpl::pixels() { return shared_bitmap_->pixels(); } } // namespace cc_blink
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "cc/blink/web_external_bitmap_impl.h" #include "cc/resources/shared_bitmap.h" namespace cc_blink { namespace { SharedBitmapAllocationFunction g_memory_allocator; } // namespace void SetSharedBitmapAllocationFunction( SharedBitmapAllocationFunction allocator) { g_memory_allocator = allocator; } WebExternalBitmapImpl::WebExternalBitmapImpl() { } WebExternalBitmapImpl::~WebExternalBitmapImpl() { } void WebExternalBitmapImpl::setSize(blink::WebSize size) { if (size != size_) { shared_bitmap_ = g_memory_allocator(gfx::Size(size)); size_ = size; } } blink::WebSize WebExternalBitmapImpl::size() { return size_; } uint8* WebExternalBitmapImpl::pixels() { if (!shared_bitmap_) { // crbug.com/520417: not sure why a non-null WebExternalBitmap is // being passed to prepareMailbox when the shared_bitmap_ is null. // Best hypothesis is that the bitmap is zero-sized. DCHECK(size_.isEmpty()); return nullptr; } return shared_bitmap_->pixels(); } } // namespace cc_blink
Fix the windows allocator to behave properly on realloc.
// 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. // This is a simple allocator based on the windows heap. extern "C" { HANDLE win_heap; bool win_heap_init(bool use_lfh) { win_heap = HeapCreate(0, 0, 0); if (win_heap == NULL) return false; if (use_lfh) { ULONG enable_lfh = 2; HeapSetInformation(win_heap, HeapCompatibilityInformation, &enable_lfh, sizeof(enable_lfh)); // NOTE: Setting LFH may fail. Vista already has it enabled. // And under the debugger, it won't use LFH. So we // ignore any errors. } return true; } void* win_heap_malloc(size_t s) { return HeapAlloc(win_heap, 0, s); } void* win_heap_realloc(void* p, size_t s) { if (!p) return win_heap_malloc(s); return HeapReAlloc(win_heap, 0, p, s); } void win_heap_free(void* s) { HeapFree(win_heap, 0, s); } size_t win_heap_msize(void* p) { return HeapSize(win_heap, 0, p); } } // extern "C"
// 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. // This is a simple allocator based on the windows heap. extern "C" { HANDLE win_heap; bool win_heap_init(bool use_lfh) { win_heap = HeapCreate(0, 0, 0); if (win_heap == NULL) return false; if (use_lfh) { ULONG enable_lfh = 2; HeapSetInformation(win_heap, HeapCompatibilityInformation, &enable_lfh, sizeof(enable_lfh)); // NOTE: Setting LFH may fail. Vista already has it enabled. // And under the debugger, it won't use LFH. So we // ignore any errors. } return true; } void* win_heap_malloc(size_t size) { return HeapAlloc(win_heap, 0, size); } void win_heap_free(void* size) { HeapFree(win_heap, 0, size); } void* win_heap_realloc(void* ptr, size_t size) { if (!ptr) return win_heap_malloc(size); if (!size) { win_heap_free(ptr); return NULL; } return HeapReAlloc(win_heap, 0, ptr, size); } size_t win_heap_msize(void* ptr) { return HeapSize(win_heap, 0, ptr); } } // extern "C"
Use C++-style reinterpret_cast when possible.
#include "yugong.hpp" #include <cstdint> #include <cstdlib> namespace yg { void YGStack::alloc(YGStack &stack, uintptr_t size) { void *mem = std::malloc(size); uintptr_t start = (uintptr_t)mem; stack.start = start; stack.size = size; stack.sp = start + size; } void YGStack::free(YGStack &stack) { void *mem = (void*)stack.start; std::free(mem); } void ll::push_initial_frame(YGStack &stack, FuncPtr func) { uintptr_t *stack_bottom = (uintptr_t*)(stack.start + stack.size); stack_bottom[-1] = 0; stack_bottom[-2] = (uintptr_t)func; stack_bottom[-3] = (uintptr_t)_yg_func_begin_resume; stack.sp = (uintptr_t)(&stack_bottom[-3]); } }
#include "yugong.hpp" #include <cstdint> #include <cstdlib> namespace yg { void YGStack::alloc(YGStack &stack, uintptr_t size) { void *mem = std::malloc(size); uintptr_t start = reinterpret_cast<uintptr_t>(mem); stack.start = start; stack.size = size; stack.sp = start + size; } void YGStack::free(YGStack &stack) { void *mem = reinterpret_cast<void*>(stack.start); std::free(mem); } void ll::push_initial_frame(YGStack &stack, FuncPtr func) { uintptr_t *stack_bottom = reinterpret_cast<uintptr_t*>(stack.start + stack.size); stack_bottom[-1] = 0; stack_bottom[-2] = reinterpret_cast<uintptr_t>(func); stack_bottom[-3] = reinterpret_cast<uintptr_t>(_yg_func_begin_resume); stack.sp = reinterpret_cast<uintptr_t>(&stack_bottom[-3]); } }
Make the test fixture use QApplication
#define BOOST_TEST_MODULE rainback #include "init.hpp" #include <QApplication> struct QApplicationFixture { int argc; char name[100]; char* argv[1]; QApplication* app; public: QApplicationFixture() : argc(1) { strcpy(name, "rainback"); argv[0] = name; app = new QApplication(argc, argv); } ~QApplicationFixture() { delete app; } }; BOOST_GLOBAL_FIXTURE(QApplicationFixture); // vim: set ts=4 sw=4 :
#define BOOST_TEST_MODULE rainback #include "init.hpp" #include <QCoreApplication> struct QApplicationFixture { int argc; char name[100]; char* argv[1]; QCoreApplication* app; public: QApplicationFixture() : argc(1) { strcpy(name, "rainback"); argv[0] = name; app = new QCoreApplication(argc, argv); } ~QApplicationFixture() { delete app; } }; BOOST_GLOBAL_FIXTURE(QApplicationFixture); // vim: set ts=4 sw=4 :
Fix test on MSVC: since the test includes a system header it cannot use clang_cc1.
// RUN: %clang_cc1 -fsyntax-only -verify %s // RUN: %clang_cc1 -fsyntax-only -verify -fshort-wchar %s #include <limits.h> const bool swchar = (wchar_t)-1 > (wchar_t)0; #ifdef __WCHAR_UNSIGNED__ int signed_test[!swchar]; #else int signed_test[swchar]; #endif int max_test[WCHAR_MAX == (swchar ? -(WCHAR_MIN+1) : (wchar_t)-1)]; int min_test[WCHAR_MIN == (swchar ? 0 : -WCHAR_MAX-1)];
// RUN: %clang -fsyntax-only -verify %s // RUN: %clang -fsyntax-only -verify -fshort-wchar %s #include <limits.h> const bool swchar = (wchar_t)-1 > (wchar_t)0; #ifdef __WCHAR_UNSIGNED__ int signed_test[!swchar]; #else int signed_test[swchar]; #endif int max_test[WCHAR_MAX == (swchar ? -(WCHAR_MIN+1) : (wchar_t)-1)]; int min_test[WCHAR_MIN == (swchar ? 0 : -WCHAR_MAX-1)];
Fix State Tracking when thread stops
#include <libclientserver.h> Thread::Thread() { m_IsRunning = false; m_IsDetached = false; } Thread::~Thread() { if (IsRunning()) Stop(); } void Thread::Start() { m_IsRunning = true; if (pthread_create(&m_thread, NULL, RunInternal, this) != 0) abort(); } void Thread::Stop() { #ifdef DEBUG if (IsDetached() == true) abort(); if (m_IsRunning == false) { abort(); //Attempted to stop an already stopped thread } #endif if (pthread_join(m_thread, NULL) != 0) abort(); } void Thread::Detach() { if (pthread_detach(m_thread) != 0) abort(); m_IsDetached = true; } bool Thread::IsRunning() { return m_IsRunning; } bool Thread::IsDetached() { return m_IsDetached; } void Thread::Run() { abort(); //You should override this function } void *Thread::RunInternal(void *ptr) { class Thread *self = (Thread *) ptr; self->Run(); return NULL; }
#include <libclientserver.h> Thread::Thread() { m_IsRunning = false; m_IsDetached = false; } Thread::~Thread() { if (IsRunning()) Stop(); } void Thread::Start() { m_IsRunning = true; if (pthread_create(&m_thread, NULL, RunInternal, this) != 0) abort(); } void Thread::Stop() { #ifdef DEBUG if (IsDetached() == true) abort(); if (m_IsRunning == false) { abort(); //Attempted to stop an already stopped thread } #endif if (pthread_join(m_thread, NULL) != 0) abort(); m_IsRunning = false; } void Thread::Detach() { if (pthread_detach(m_thread) != 0) abort(); m_IsDetached = true; } bool Thread::IsRunning() { return m_IsRunning; } bool Thread::IsDetached() { return m_IsDetached; } void Thread::Run() { abort(); //You should override this function } void *Thread::RunInternal(void *ptr) { class Thread *self = (Thread *) ptr; self->Run(); return NULL; }
Allow meta key to be shortcut assigned
#include "hotkey.h" #include "ui_hotkey.h" hotkey::hotkey(QWidget *parent) : s(s), QWidget(parent), ui(new Ui::hotkey) { ui->setupUi(this); } hotkey::~hotkey() { delete ui; } void hotkey::keyPressEvent(QKeyEvent *event) { int uKey = event->key(); Qt::Key key = static_cast<Qt::Key>(uKey); if(key == Qt::Key_unknown) { return; } if(key == Qt::Key_Control || key == Qt::Key_Shift || key == Qt::Key_Alt ) { return ; } Qt::KeyboardModifiers modifiers = event->modifiers(); if(modifiers & Qt::ShiftModifier) uKey += Qt::SHIFT; if(modifiers & Qt::ControlModifier) uKey += Qt::CTRL; if(modifiers & Qt::AltModifier) uKey += Qt::ALT; ui->label_2->setText(QKeySequence(uKey).toString()); this->s->setText(QKeySequence(uKey).toString()); } void hotkey::keyReleaseEvent(QKeyEvent *event) { this->~hotkey(); }
#include "hotkey.h" #include "ui_hotkey.h" hotkey::hotkey(QWidget *parent) : s(s), QWidget(parent), ui(new Ui::hotkey) { ui->setupUi(this); } hotkey::~hotkey() { delete ui; } void hotkey::keyPressEvent(QKeyEvent *event) { int uKey = event->key(); Qt::Key key = static_cast<Qt::Key>(uKey); if(key == Qt::Key_unknown) { return; } if(key == Qt::Key_Control || key == Qt::Key_Shift || key == Qt::Key_Alt || key == Qt::Key_Meta) { return ; } Qt::KeyboardModifiers modifiers = event->modifiers(); if(modifiers & Qt::ShiftModifier) uKey += Qt::SHIFT; if(modifiers & Qt::ControlModifier) uKey += Qt::CTRL; if(modifiers & Qt::AltModifier) uKey += Qt::ALT; if(modifiers & Qt::MetaModifier) uKey += Qt::META; ui->label_2->setText(QKeySequence(uKey).toString()); this->s->setText(QKeySequence(uKey).toString()); } void hotkey::keyReleaseEvent(QKeyEvent *event) { this->~hotkey(); }
Add dummy area and volume methods.
#include "box.hpp" Box::Box(): // default constructor min_{0.0, 0.0, 0.0}, max_{0.0, 0.0, 0.0} {} Box::Box(Box const& b): // copy constructor min_{b.min_}, max_{b.max_} {} Box::Box(Box&& b): // move constructor Box() { swap(*this, b); } Box::Box(glm::vec3 const& min, glm::vec3 const& max): min_{min}, max_{max} {} void Box::swap(Box & b1, Box & b2) { std::swap(b1.min_, b2.min_); std::swap(b1.max_, b2.max_); } glm::vec3 Box::getMin() const { return min_; } glm::vec3 Box::getMax() const { return max_; }
#include "box.hpp" Box::Box(): // default constructor min_{0.0, 0.0, 0.0}, max_{0.0, 0.0, 0.0} {} Box::Box(Box const& b): // copy constructor min_{b.min_}, max_{b.max_} {} Box::Box(Box&& b): // move constructor Box() { swap(*this, b); } Box::Box(glm::vec3 const& min, glm::vec3 const& max): min_{min}, max_{max} {} void Box::swap(Box & b1, Box & b2) { std::swap(b1.min_, b2.min_); std::swap(b1.max_, b2.max_); } glm::vec3 Box::getMin() const { return min_; } glm::vec3 Box::getMax() const { return max_; } /* virtual */ double area() const { return 0.0; } /* virtual */ double volume() const { return 0.0; }
Clear interruption request flag just before interrupting
/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2012 Sandro Santilli <strk@keybit.net> * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * **********************************************************************/ #include <geos/util/Interrupt.h> #include <geos/util/GEOSException.h> // for inheritance namespace geos { namespace util { // geos::util class GEOS_DLL InterruptedException: public GEOSException { public: InterruptedException() : GEOSException("InterruptedException", "Interrupted!") {} }; void Interrupt::interrupt() { throw InterruptedException(); } bool Interrupt::requested = false; Interrupt::Callback *Interrupt::callback = 0; void *Interrupt::callback_arg = 0; } // namespace geos::util } // namespace geos
/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2012 Sandro Santilli <strk@keybit.net> * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * **********************************************************************/ #include <geos/util/Interrupt.h> #include <geos/util/GEOSException.h> // for inheritance namespace geos { namespace util { // geos::util class GEOS_DLL InterruptedException: public GEOSException { public: InterruptedException() : GEOSException("InterruptedException", "Interrupted!") {} }; void Interrupt::interrupt() { requested = false; throw InterruptedException(); } bool Interrupt::requested = false; Interrupt::Callback *Interrupt::callback = 0; void *Interrupt::callback_arg = 0; } // namespace geos::util } // namespace geos
Rename variable value to sum
// Solution to the TwoSum problem from LeetCode #include "two_sum.h" TwoSum::TwoSum() { } vector<int> TwoSum::solver(vector<int>& nums, int target) { for(int i=0; i<nums.size(); i++) { for(int j=0; j<nums.size(); j++) { int value = nums[i] + nums[j]; if ((value == target) && (i != j)) { // Return if value equals target vector<int> return_vector = {i,j}; return return_vector; } } } return {-1, -1}; } // Run Basic test cases on solver bool TwoSum::test_case() { vector<int> test_vector = {3,2,4}; vector<int> result = solver(test_vector, 6); if (result[0] == 1 && result[1] == 2) return true; else return false; }
// Solution to the TwoSum problem from LeetCode #include "two_sum.h" TwoSum::TwoSum() { } vector<int> TwoSum::solver(vector<int>& nums, int target) { for(int i=0; i<nums.size(); i++) { for(int j=0; j<nums.size(); j++) { int sum = nums[i] + nums[j]; if ((sum == target) && (i != j)) { // Return if sum equals target vector<int> return_vector = {i,j}; return return_vector; } } } return {-1, -1}; } // Run Basic test cases on solver bool TwoSum::test_case() { vector<int> test_vector = {3,2,4}; vector<int> result = solver(test_vector, 6); if (result[0] == 1 && result[1] == 2) return true; else return false; }
Set '-target' flag in the test checking the MacOS include dir
// Clang on MacOS can find libc++ living beside the installed compiler. // This test makes sure our libTooling-based tools emulate this properly with // fixed compilation database. // // RUN: rm -rf %t // RUN: mkdir %t // // Install the mock libc++ (simulates the libc++ directory structure). // RUN: cp -r %S/Inputs/mock-libcxx %t/ // // RUN: cp $(which clang-check) %t/mock-libcxx/bin/ // RUN: cp "%s" "%t/test.cpp" // RUN: %t/mock-libcxx/bin/clang-check -p "%t" "%t/test.cpp" -- -stdlib=libc++ #include <mock_vector> vector v;
// Clang on MacOS can find libc++ living beside the installed compiler. // This test makes sure our libTooling-based tools emulate this properly with // fixed compilation database. // // RUN: rm -rf %t // RUN: mkdir %t // // Install the mock libc++ (simulates the libc++ directory structure). // RUN: cp -r %S/Inputs/mock-libcxx %t/ // // RUN: cp $(which clang-check) %t/mock-libcxx/bin/ // RUN: cp "%s" "%t/test.cpp" // RUN: %t/mock-libcxx/bin/clang-check -p "%t" "%t/test.cpp" -- -stdlib=libc++ -target x86_64-apple-darwin #include <mock_vector> vector v;
Change default log level to WARN
#include "logger.h" Logger::Level Logger::logLevel = Logger::Level::ERROR; void Logger::Error(std::string msg) { std::cerr << "[Error]: " << msg.c_str() << std::endl; } void Logger::Warn(std::string msg) { if (Logger::logLevel >= Logger::Level::WARN) { std::cout << "[Warn]: " << msg.c_str() << std::endl; } } void Logger::Info(std::string msg) { if (Logger::logLevel >= Logger::Level::INFO) { std::cout << "[Info]: " << msg.c_str() << std::endl; } } void Logger::Debug(std::string msg) { if (Logger::logLevel == Logger::Level::DEBUG) { std::cout << "[Debug]: " << msg.c_str() << std::endl; } }
#include "logger.h" Logger::Level Logger::logLevel = Logger::Level::WARN; void Logger::Error(std::string msg) { std::cerr << "[Error]: " << msg.c_str() << std::endl; } void Logger::Warn(std::string msg) { if (Logger::logLevel >= Logger::Level::WARN) { std::cout << "[Warn]: " << msg.c_str() << std::endl; } } void Logger::Info(std::string msg) { if (Logger::logLevel >= Logger::Level::INFO) { std::cout << "[Info]: " << msg.c_str() << std::endl; } } void Logger::Debug(std::string msg) { if (Logger::logLevel == Logger::Level::DEBUG) { std::cout << "[Debug]: " << msg.c_str() << std::endl; } }
Update test becuase yaz_query_to_wrbuf now omits : before query type in string output.
/* * Copyright (c) 1998-2005, Index Data. * See the file LICENSE for details. * * $Id: tstquery.cpp,v 1.2 2006-03-29 13:14:15 adam Exp $ */ #include <stdlib.h> #include <yazpp/z-query.h> using namespace yazpp_1; void tst1(const char *query_str_in, const char *query_expected) { Yaz_Z_Query q; q = query_str_in; Yaz_Z_Query q2; q2 = q; char query_str_out[100]; q2.print(query_str_out, sizeof(query_str_out)-1); if (strcmp(query_str_out, query_expected)) { fprintf(stderr, "tstquery: query mismatch out=%s expected=%s\n", query_str_out, query_expected); exit(1); } } int main(int argc, char **argv) { tst1("", ""); tst1("x", "RPN: @attrset Bib-1 x"); tst1("@and a b", "RPN: @attrset Bib-1 @and a b"); } /* * Local variables: * c-basic-offset: 4 * indent-tabs-mode: nil * End: * vim: shiftwidth=4 tabstop=8 expandtab */
/* * Copyright (c) 1998-2006, Index Data. * See the file LICENSE for details. * * $Id: tstquery.cpp,v 1.3 2006-07-07 12:57:15 adam Exp $ */ #include <stdlib.h> #include <yazpp/z-query.h> using namespace yazpp_1; void tst1(const char *query_str_in, const char *query_expected) { Yaz_Z_Query q; q = query_str_in; Yaz_Z_Query q2; q2 = q; char query_str_out[100]; q2.print(query_str_out, sizeof(query_str_out)-1); if (strcmp(query_str_out, query_expected)) { fprintf(stderr, "tstquery: query mismatch out=%s expected=%s\n", query_str_out, query_expected); exit(1); } } int main(int argc, char **argv) { tst1("", ""); tst1("x", "RPN @attrset Bib-1 x"); tst1("@and a b", "RPN @attrset Bib-1 @and a b"); } /* * Local variables: * c-basic-offset: 4 * indent-tabs-mode: nil * End: * vim: shiftwidth=4 tabstop=8 expandtab */
Add failure tests into Board unittests.
#include "board.hpp" #include "gtest/gtest.h" class BoardTest : public ::testing::Test { protected: BoardTest() : board_(1, 2) { } virtual ~BoardTest() { } virtual void SetUp() { } Quoridor::Board board_; }; TEST_F(BoardTest, set_size) { board_.set_size(10, 11); EXPECT_EQ(10, board_.row_num()); EXPECT_EQ(11, board_.col_num()); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
#include "board.hpp" #include "exception.hpp" #include "gtest/gtest.h" class BoardTest : public ::testing::Test { protected: BoardTest() : board_(1, 2) { } Quoridor::Board board_; }; TEST_F(BoardTest, ctor) { EXPECT_EQ(1, board_.row_num()); EXPECT_EQ(2, board_.col_num()); // test invalid Board construction EXPECT_THROW(Quoridor::Board(-1, 1), Quoridor::Exception); EXPECT_THROW(Quoridor::Board(8, 0), Quoridor::Exception); } TEST_F(BoardTest, set_size) { // test invalid Board sizes EXPECT_THROW(board_.set_size(0, 0), Quoridor::Exception); EXPECT_THROW(board_.set_size(0, 1), Quoridor::Exception); EXPECT_THROW(board_.set_size(1, 0), Quoridor::Exception); EXPECT_THROW(board_.set_size(-1, -1), Quoridor::Exception); EXPECT_THROW(board_.set_size(-1, 1), Quoridor::Exception); EXPECT_THROW(board_.set_size(1, -1), Quoridor::Exception); board_.set_size(10, 11); EXPECT_EQ(10, board_.row_num()); EXPECT_EQ(11, board_.col_num()); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
Add stronger test for server
/* * ============================================================================ * Filename: server_main.cc * Description: Server main for testing * Version: 1.0 * Created: 04/25/2015 06:37:53 PM * Revision: none * Compiler: gcc * Author: Rafael Gozlan, rafael.gozlan@epita.fr * Organization: Flihabi * ============================================================================ */ #include <stdlib.h> #include <unistd.h> #include "server.hh" #define NB_TESTS 10 int main() { Server *s = new Server(); int ids[NB_TESTS]; for (int i = 0; i < NB_TESTS; ++i) ids[i] = s->execBytecode("This is some bytecode"); Result *r; for (int i = 0; i < NB_TESTS; ++i) { while ((r = s->getResult(ids[i])) == NULL) { std::cout << "Server: Waiting for result"; sleep(1); } std::cout << "Server received: " << r->value << std::endl; } }
/* * ============================================================================ * Filename: server_main.cc * Description: Server main for testing * Version: 1.0 * Created: 04/25/2015 06:37:53 PM * Revision: none * Compiler: gcc * Author: Rafael Gozlan, rafael.gozlan@epita.fr * Organization: Flihabi * ============================================================================ */ #include <stdlib.h> #include <unistd.h> #include "server.hh" #define NB_TESTS 10 int main() { Server *s = new Server(); int ids[NB_TESTS]; std::string string = "This is some bytecode"; string += '\0'; string += "This is something else"; for (int i = 0; i < NB_TESTS; ++i) ids[i] = s->execBytecode(string); Result *r; for (int i = 0; i < NB_TESTS; ++i) { while ((r = s->getResult(ids[i])) == NULL) { std::cout << "Server: Waiting for result"; sleep(1); } std::cout << "Server received: " << r->value << std::endl; } }
Tweak expected error to match what should happen, once using declarations work
// FIXME: Disabled, appears to have undefined behavior, and needs to be updated to match new warnings. // RUN: clang-cc -fsyntax-only -verify %s // XFAIL: * namespace A { int VA; void FA() {} struct SA { int V; }; } using A::VA; using A::FA; using typename A::SA; void main() { VA = 1; FA(); SA x; //Still needs handling. } struct B { void f(char){}; void g(char){}; }; struct D : B { using B::f; void f(int); void g(int); }; void D::f(int) { f('c'); } // calls B::f(char) void D::g(int) { g('c'); } // recursively calls D::g(int) namespace E { template <typename TYPE> int funcE(TYPE arg) { return(arg); } } using E::funcE<int>; // expected-error{{use of template specialization in using directive not allowed}} namespace F { struct X; } using F::X; // Should have some errors here. Waiting for implementation. void X(int); struct X *x;
// RUN: clang-cc -fsyntax-only -verify %s // XFAIL: * namespace A { int VA; void FA() {} struct SA { int V; }; } using A::VA; using A::FA; using typename A::SA; int main() { VA = 1; FA(); SA x; //Still needs handling. } struct B { void f(char){}; void g(char){}; }; struct D : B { using B::f; void f(int); void g(int); }; void D::f(int) { f('c'); } // calls B::f(char) void D::g(int) { g('c'); } // recursively calls D::g(int) namespace E { template <typename TYPE> int funcE(TYPE arg) { return(arg); } } using E::funcE<int>; // expected-error{{using declaration can not refer to a template specialization}} namespace F { struct X; } using F::X; // Should have some errors here. Waiting for implementation. void X(int); struct X *x;
Fix test to not use the AttributeSet's AttributeWithIndex creation method.
//===- llvm/unittest/IR/AttributesTest.cpp - Attributes unit tests --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/IR/Attributes.h" #include "llvm/IR/LLVMContext.h" #include "gtest/gtest.h" using namespace llvm; namespace { TEST(Attributes, Uniquing) { LLVMContext C; Attribute AttrA = Attribute::get(C, Attribute::AlwaysInline); Attribute AttrB = Attribute::get(C, Attribute::AlwaysInline); EXPECT_EQ(AttrA, AttrB); AttributeWithIndex AWIs[] = { AttributeWithIndex::get(C, 1, Attribute::ZExt), AttributeWithIndex::get(C, 2, Attribute::SExt) }; AttributeSet SetA = AttributeSet::get(C, AWIs); AttributeSet SetB = AttributeSet::get(C, AWIs); EXPECT_EQ(SetA, SetB); } } // end anonymous namespace
//===- llvm/unittest/IR/AttributesTest.cpp - Attributes unit tests --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/IR/Attributes.h" #include "llvm/IR/LLVMContext.h" #include "gtest/gtest.h" using namespace llvm; namespace { TEST(Attributes, Uniquing) { LLVMContext C; Attribute AttrA = Attribute::get(C, Attribute::AlwaysInline); Attribute AttrB = Attribute::get(C, Attribute::AlwaysInline); EXPECT_EQ(AttrA, AttrB); AttributeSet ASs[] = { AttributeSet::get(C, 1, Attribute::ZExt), AttributeSet::get(C, 2, Attribute::SExt) }; AttributeSet SetA = AttributeSet::get(C, ASs); AttributeSet SetB = AttributeSet::get(C, ASs); EXPECT_EQ(SetA, SetB); } } // end anonymous namespace
Add more tests for rope_node
/** * Tests of str_rope and rope_node. * * @author Jean-Claude Paquin **/ #include <catch.hpp> #include <primitives/str_rope.h> TEST_CASE("Empty rope_node", "[rope_node]") { std::unique_ptr<rope_node> node = std::make_unique<rope_node>(); SECTION("Empty node has nullptr left & right") { REQUIRE(!node->data.left); REQUIRE(!node->data.right); } SECTION("Empty node to string") { REQUIRE(*node->to_string().get() == ""); } } TEST_CASE("String rope_node", "[rope_node]") { std::unique_ptr<rope_node> node = std::make_unique<rope_node>(std::string("wow!")); } TEST_CASE("Copy constructor for rope_node", "[rope_node]") { std::unique_ptr<rope_node> node = std::make_unique<rope_node>(std::string("that's a low price!")); std::unique_ptr<rope_node> dupl = std::make_unique<rope_node>(*node.get()); REQUIRE(*dupl->to_string().get() == *node->to_string().get()); }
/** * Tests of str_rope and rope_node. * * @author Jean-Claude Paquin **/ #include <catch.hpp> #include <primitives/str_rope.h> TEST_CASE("Empty rope_node", "[rope_node]") { std::unique_ptr<rope_node> node = std::make_unique<rope_node>(); SECTION("Empty node has nullptr left & right") { REQUIRE(!node->data.left); REQUIRE(!node->data.right); } SECTION("Empty node to string") { REQUIRE(*node->to_string().get() == ""); } SECTION("Empty node is not a leaf") { REQUIRE(!node->is_leaf); } } TEST_CASE("String rope_node", "[rope_node]") { std::unique_ptr<rope_node> node = std::make_unique<rope_node>(std::string("wow!")); SECTION("String node is a leaf") { REQUIRE(node->is_leaf); } } TEST_CASE("Copy constructor for rope_node", "[rope_node]") { SECTION("Copied node is a leaf node") { std::unique_ptr<rope_node> node = std::make_unique<rope_node>(std::string("that's a low price!")); std::unique_ptr<rope_node> dupl = std::make_unique<rope_node>(*node.get()); REQUIRE(*dupl->to_string().get() == *node->to_string().get()); REQUIRE(dupl->is_leaf); } SECTION("Copied node is not a leaf node") { rope_node node; rope_node dupl(node); REQUIRE(!dupl.is_leaf); } }
Fix test case due to r196394 and improve it to not rely on LLVM code generation either.
// RUN: %clang_cc1 -g -S -masm-verbose -o - %s | FileCheck %s // CHECK: abbrev_begin: // CHECK: DW_AT_accessibility // CHECK-NEXT: DW_FORM_data1 class A { public: int p; private: int pr; }; A a;
// RUN: %clang -g -S -emit-llvm %s -o - | FileCheck %s // CHECK: [ DW_TAG_member ] [p] [{{[^]]*}}] [from int] // CHECK: [ DW_TAG_member ] [pr] [{{[^]]*}}] [private] [from int] class A { public: int p; private: int pr; }; A a;
Add a test case for PR22431
// RUN: %clang_cl_asan -O0 %s -Fe%t // RUN: echo "42" | %run %t 2>&1 | FileCheck %s #include <iostream> int main() { int i; std::cout << "Type i: "; std::cin >> i; return 0; // CHECK: Type i: // CHECK-NOT: AddressSanitizer: stack-buffer-overflow on address [[ADDR:0x[0-9a-f]+]] }
// First, check this works with the default blacklist: // RUN: %clang_cl_asan -O0 %s -Fe%t // RUN: echo "42" | %run %t 2>&1 | FileCheck %s // // Then, make sure it still works when a user uses his own blacklist file: // RUN: %clang_cl_asan -O0 %s -fsanitize-blacklist=%p/../Helpers/initialization-blacklist.txt -Fe%t2 // RUN: echo "42" | %run %t2 2>&1 | FileCheck %s #include <iostream> int main() { int i; std::cout << "Type i: "; std::cin >> i; return 0; // CHECK: Type i: // CHECK-NOT: AddressSanitizer: stack-buffer-overflow on address [[ADDR:0x[0-9a-f]+]] }
Add Conditional Map Access test
#include <ionCore.h> #include <catch.hpp> TEST_CASE("ionStandardLibrary::String::Build") { REQUIRE(String::Build("") == string()); REQUIRE(String::Build("Test") == "Test"); REQUIRE(String::Build("Hello %d", 123) == "Hello 123"); REQUIRE(String::Build("%c %d %X %s", 'a', 42, 0xABCD, "foo") == "a 42 ABCD foo"); }
#include <ionCore.h> #include <catch.hpp> TEST_CASE("ionStandardLibrary::ConditionalMapAccess") { map<int, int *> Test; REQUIRE(! ConditionalMapAccess(Test, 0)); REQUIRE(! ConditionalMapAccess(Test, 1)); REQUIRE(! ConditionalMapAccess(Test, 2)); int X, Y; Test[0] = & X; Test[1] = & Y; Test[2] = & Y; REQUIRE(! ConditionalMapAccess(Test, -1)); REQUIRE(& X == ConditionalMapAccess(Test, 0)); REQUIRE(& Y == ConditionalMapAccess(Test, 1)); REQUIRE(& Y == ConditionalMapAccess(Test, 2)); REQUIRE(! ConditionalMapAccess(Test, 3)); REQUIRE(! ConditionalMapAccess(Test, 4)); } TEST_CASE("ionStandardLibrary::String::Build") { REQUIRE(String::Build("") == string()); REQUIRE(String::Build("Test") == "Test"); REQUIRE(String::Build("Hello %d", 123) == "Hello 123"); REQUIRE(String::Build("%c %d %X %s", 'a', 42, 0xABCD, "foo") == "a 42 ABCD foo"); }
UPDATE Initialize now calls InitializeBase as expected
#include "ButtonEntity.h" ButtonEntity::ButtonEntity() { } ButtonEntity::~ButtonEntity() { } int ButtonEntity::Update(float dT, InputHandler * inputHandler) { int result = 0; return result; } int ButtonEntity::React(int entityID, EVENT reactEvent) { int result = 0; return result; } int ButtonEntity::Initialize(int entityID, PhysicsComponent * pComp, GraphicsComponent * gComp) { int result = 0; return result; }
#include "ButtonEntity.h" ButtonEntity::ButtonEntity() { } ButtonEntity::~ButtonEntity() { } int ButtonEntity::Update(float dT, InputHandler * inputHandler) { int result = 0; return result; } int ButtonEntity::React(int entityID, EVENT reactEvent) { int result = 0; return result; } int ButtonEntity::Initialize(int entityID, PhysicsComponent * pComp, GraphicsComponent * gComp) { int result = 0; this->InitializeBase(entityID, pComp, gComp); return result; }
Reset ruby_errinfo when catching exceptions, otherwise exceptions can strangely be resurrected.
#include "protect.hpp" #include "../Exception.hpp" #include "../Jump_Tag.hpp" #ifndef TAG_RAISE #define TAG_RAISE 0x6 #endif VALUE Rice::detail:: protect( RUBY_VALUE_FUNC f, VALUE arg) { int state = 0; VALUE retval = rb_protect(f, arg, &state); if(state != 0) { if(state == TAG_RAISE && ruby_errinfo != Qnil) { // TODO: convert NoMemoryError into bad_alloc? throw Rice::Exception(ruby_errinfo); } throw Jump_Tag(state); } return retval; }
#include "protect.hpp" #include "../Exception.hpp" #include "../Jump_Tag.hpp" #ifndef TAG_RAISE #define TAG_RAISE 0x6 #endif VALUE Rice::detail:: protect( RUBY_VALUE_FUNC f, VALUE arg) { int state = 0; VALUE retval = rb_protect(f, arg, &state); if(state != 0) { if(state == TAG_RAISE && RTEST(ruby_errinfo)) { // TODO: convert NoMemoryError into bad_alloc? VALUE err = ruby_errinfo; ruby_errinfo = 0; throw Rice::Exception(err); } throw Jump_Tag(state); } return retval; }
Fix buffer size and memory offset calculations in VstEventKeeper
#include "vsteventkeeper.h" #include <cstdint> namespace Airwave { VstEventKeeper::VstEventKeeper() : events_(nullptr), data_(nullptr) { } VstEventKeeper::~VstEventKeeper() { delete [] events_; } void VstEventKeeper::reload(int count, const VstEvent events[]) { if(!events_ || events_->numEvents < count) { delete [] events_; size_t size = sizeof(VstEvents) + count * (sizeof(VstEvent*) + sizeof(VstEvent)); uint8_t* buffer = new uint8_t[size]; events_ = reinterpret_cast<VstEvents*>(buffer); size_t offset = sizeof(VstEvents) + count * sizeof(VstEvent*); data_ = reinterpret_cast<VstEvent*>(buffer + offset); } events_->numEvents = count; events_->reserved = 0; for(int i = 0; i < count; ++i) { data_[i] = events[i]; events_->events[i] = &data_[i]; } } VstEvents* VstEventKeeper::events() { return events_; } } // namespace Airwave
#include "vsteventkeeper.h" #include <algorithm> #include <cstdint> namespace Airwave { VstEventKeeper::VstEventKeeper() : events_(nullptr), data_(nullptr) { } VstEventKeeper::~VstEventKeeper() { delete [] events_; } void VstEventKeeper::reload(int count, const VstEvent events[]) { if(!events_ || events_->numEvents < count) { delete [] events_; int extraCount = std::max(count - 2, 0); size_t size = sizeof(VstEvents) + extraCount * sizeof(VstEvent*) + count * sizeof(VstEvent); uint8_t* buffer = new uint8_t[size]; events_ = reinterpret_cast<VstEvents*>(buffer); size_t offset = sizeof(VstEvents) + extraCount * sizeof(VstEvent*); data_ = reinterpret_cast<VstEvent*>(buffer + offset); } events_->numEvents = count; events_->reserved = 0; for(int i = 0; i < count; ++i) { data_[i] = events[i]; events_->events[i] = &data_[i]; } } VstEvents* VstEventKeeper::events() { return events_; } } // namespace Airwave
Enable http link in about box to launch system web browser
#include "configuration.h" #include "AboutDialog.h" #include "ui_AboutDialog.h" #define define2string_p(x) #x #define define2string(x) define2string_p(x) AboutDialog::AboutDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AboutDialog) { ui->setupUi(this); connect(ui->okButton, SIGNAL(clicked()), this, SLOT(accept())); ui->appnameLabel->setText(tr("%1 %2").arg(QGC_APPLICATION_NAME).arg(QGC_APPLICATION_VERSION)); QString hash = QString(define2string(GIT_HASH)); hash.truncate(8); ui->versionLabel->setText(tr("(%1-%2)").arg(hash) .arg(define2string(GIT_COMMIT))); } AboutDialog::~AboutDialog() { delete ui; }
#include "configuration.h" #include "AboutDialog.h" #include "ui_AboutDialog.h" #define define2string_p(x) #x #define define2string(x) define2string_p(x) AboutDialog::AboutDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AboutDialog) { ui->setupUi(this); connect(ui->okButton, SIGNAL(clicked()), this, SLOT(accept())); ui->appnameLabel->setText(tr("%1 %2").arg(QGC_APPLICATION_NAME).arg(QGC_APPLICATION_VERSION)); QString hash = QString(define2string(GIT_HASH)); hash.truncate(8); ui->versionLabel->setText(tr("(%1-%2)").arg(hash) .arg(define2string(GIT_COMMIT))); ui->linkLabel->setOpenExternalLinks(true); } AboutDialog::~AboutDialog() { delete ui; }
Increase buffer size to 1024 in SysErrorString
// Copyright (c) 2020-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <tinyformat.h> #include <util/syserror.h> #include <cstring> std::string SysErrorString(int err) { char buf[256]; /* Too bad there are three incompatible implementations of the * thread-safe strerror. */ const char *s = nullptr; #ifdef WIN32 if (strerror_s(buf, sizeof(buf), err) == 0) s = buf; #else #ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */ s = strerror_r(err, buf, sizeof(buf)); #else /* POSIX variant always returns message in buffer */ if (strerror_r(err, buf, sizeof(buf)) == 0) s = buf; #endif #endif if (s != nullptr) { return strprintf("%s (%d)", s, err); } else { return strprintf("Unknown error (%d)", err); } }
// Copyright (c) 2020-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <tinyformat.h> #include <util/syserror.h> #include <cstring> std::string SysErrorString(int err) { char buf[1024]; /* Too bad there are three incompatible implementations of the * thread-safe strerror. */ const char *s = nullptr; #ifdef WIN32 if (strerror_s(buf, sizeof(buf), err) == 0) s = buf; #else #ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */ s = strerror_r(err, buf, sizeof(buf)); #else /* POSIX variant always returns message in buffer */ if (strerror_r(err, buf, sizeof(buf)) == 0) s = buf; #endif #endif if (s != nullptr) { return strprintf("%s (%d)", s, err); } else { return strprintf("Unknown error (%d)", err); } }
Add <type_traits> for is_pod, fixing r241947
//===- MCSchedule.cpp - Scheduling ------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the default scheduling model. // //===----------------------------------------------------------------------===// #include "llvm/MC/MCSchedule.h" using namespace llvm; static_assert(std::is_pod<MCSchedModel>::value, "We shouldn't have a static constructor here"); const MCSchedModel MCSchedModel::Default = {DefaultIssueWidth, DefaultMicroOpBufferSize, DefaultLoopMicroOpBufferSize, DefaultLoadLatency, DefaultHighLatency, DefaultMispredictPenalty, false, true, 0, nullptr, nullptr, 0, 0, nullptr};
//===- MCSchedule.cpp - Scheduling ------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the default scheduling model. // //===----------------------------------------------------------------------===// #include "llvm/MC/MCSchedule.h" #include <type_traits> using namespace llvm; static_assert(std::is_pod<MCSchedModel>::value, "We shouldn't have a static constructor here"); const MCSchedModel MCSchedModel::Default = {DefaultIssueWidth, DefaultMicroOpBufferSize, DefaultLoopMicroOpBufferSize, DefaultLoadLatency, DefaultHighLatency, DefaultMispredictPenalty, false, true, 0, nullptr, nullptr, 0, 0, nullptr};
Fix GC-related SEGV when heavily using AtomicReference
#include "builtin/class.hpp" #include "builtin/atomic.hpp" #include "ontology.hpp" namespace rubinius { void AtomicReference::init(STATE) { GO(atomic_ref).set(ontology::new_class(state, "AtomicReference", G(object), G(rubinius))); G(atomic_ref)->set_object_type(state, AtomicReferenceType); } AtomicReference* AtomicReference::allocate(STATE) { return state->new_object<AtomicReference>(G(atomic_ref)); } Object* AtomicReference::compare_and_set(STATE, Object* old, Object* new_) { Object** pp = &value_; return atomic::compare_and_swap((void**)pp, old, new_) ? cTrue : cFalse; } }
#include "builtin/class.hpp" #include "builtin/atomic.hpp" #include "ontology.hpp" namespace rubinius { void AtomicReference::init(STATE) { GO(atomic_ref).set(ontology::new_class(state, "AtomicReference", G(object), G(rubinius))); G(atomic_ref)->set_object_type(state, AtomicReferenceType); } AtomicReference* AtomicReference::allocate(STATE) { return state->new_object<AtomicReference>(G(atomic_ref)); } Object* AtomicReference::compare_and_set(STATE, Object* old, Object* new_) { Object** pp = &value_; if (atomic::compare_and_swap((void**)pp, old, new_)) { if(mature_object_p()) this->write_barrier(state, new_); return cTrue; } else { return cFalse; } } }
Fix the incorrect output bug
#include <stdio.h> #define MAX_LOOP 10000 double formula(const double x, const double k) { return (x * x) / ((2 * k - 1) * (2 * k)); } int main(void) { double x; printf("Enter x= "); scanf("%lf", &x); double cosx = 1, sinx = x; int k = 2; while(k < MAX_LOOP) { cosx = cosx - cosx * formula(x, k++); sinx = sinx - sinx * formula(x, k++); cosx = cosx + cosx * formula(x, k++); sinx = sinx + sinx * formula(x, k++); } printf("Result is: cosx=%f sinx=%f\n", cosx, sinx); return 0; }
#include <stdio.h> #define MAX_LOOP 100 double cosine_formula(const double x, const double k) { if(k == 0) return 1; return (x * x) / ((2 * k - 1) * (2 * k)); } double sine_formula(const double x, const double k) { if(k == 0) return x; return (x * x) / ((2 * k) * (2 * k + 1)); } int main(void) { double x; printf("Enter x= "); scanf("%lf", &x); double cosx = 0, sinx = 0; { double cosx_cache = 1, sinx_cache = 1; for(int k = 0; k < MAX_LOOP; ++k) { cosx_cache *= cosine_formula(x, k); (k % 2 == 0) ? cosx += cosx_cache : cosx -= cosx_cache; sinx_cache *= sine_formula(x, k); (k % 2 == 0) ? sinx += sinx_cache : sinx -= sinx_cache; } } printf("Result is: cosx=%f sinx=%f\n", cosx, sinx); return 0; }
Fix bug to see efect for Travis
#include "arithmetics.hpp" namespace arithmetics { int add(int a, int b) { return a + b; } int add_buggy(int a, int b) { return a + b + 1; } }
#include "arithmetics.hpp" namespace arithmetics { int add(int a, int b) { return a + b; } int add_buggy(int a, int b) { return a + b; } }
Make Other chase after items
#include "other.hpp" using namespace LD22; Other::~Other() { } void Other::advance() { Walker::advance(); }
#include "other.hpp" #include "item.hpp" using namespace LD22; Other::~Other() { } void Other::advance() { scanItems(); if (m_item) { int wx = centerx(), wy = centery(); int ix = m_item->centerx(), iy = m_item->centery(); int dx = ix - wx, dy = iy - wy; if (dx < -20) m_xpush = -PUSH_SCALE; else if (dx > 20) m_xpush = PUSH_SCALE; else m_xpush = 0; (void) dy; } else { m_xpush = 0; } Walker::advance(); }
Allow early ack on non-zero visibility delay.
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "lid_reuse_delayer_config.h" #include <vespa/searchcore/proton/server/documentdbconfig.h> namespace proton::documentmetastore { LidReuseDelayerConfig::LidReuseDelayerConfig(const DocumentDBConfig & configSnapshot) : _visibilityDelay(configSnapshot.getMaintenanceConfigSP()->getVisibilityDelay()), _allowEarlyAck(configSnapshot.getMaintenanceConfigSP()->allowEarlyAck()), _hasIndexedOrAttributeFields(configSnapshot.getSchemaSP()->getNumIndexFields() > 0 || configSnapshot.getSchemaSP()->getNumAttributeFields() > 0) { } LidReuseDelayerConfig::LidReuseDelayerConfig() : LidReuseDelayerConfig(vespalib::duration::zero(), false) {} LidReuseDelayerConfig::LidReuseDelayerConfig(vespalib::duration visibilityDelay, bool hasIndexedOrAttributeFields_in) : _visibilityDelay(visibilityDelay), _allowEarlyAck(visibilityDelay > 1ms), _hasIndexedOrAttributeFields(hasIndexedOrAttributeFields_in) { } }
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "lid_reuse_delayer_config.h" #include <vespa/searchcore/proton/server/documentdbconfig.h> namespace proton::documentmetastore { LidReuseDelayerConfig::LidReuseDelayerConfig(const DocumentDBConfig & configSnapshot) : _visibilityDelay(configSnapshot.getMaintenanceConfigSP()->getVisibilityDelay()), _allowEarlyAck(configSnapshot.getMaintenanceConfigSP()->allowEarlyAck()), _hasIndexedOrAttributeFields(configSnapshot.getSchemaSP()->getNumIndexFields() > 0 || configSnapshot.getSchemaSP()->getNumAttributeFields() > 0) { } LidReuseDelayerConfig::LidReuseDelayerConfig() : LidReuseDelayerConfig(vespalib::duration::zero(), false) {} LidReuseDelayerConfig::LidReuseDelayerConfig(vespalib::duration visibilityDelay, bool hasIndexedOrAttributeFields_in) : _visibilityDelay(visibilityDelay), _allowEarlyAck(visibilityDelay > vespalib::duration::zero()), _hasIndexedOrAttributeFields(hasIndexedOrAttributeFields_in) { } }
Fix for 0.9.0 texture issues
// ------------------------------------------------------------------ // ofxTPSprite.cpp // ofxTexturePacker - https://www.github.com/danoli3/ofxTexturePacker // Created by Daniel Rosser and Colin Friend on 9/06/2014. // ------------------------------------------------------------------ #include "ofxTPSprite.h" ofxTPSprite::ofxTPSprite(ofxTPSpriteData* theData) { data = theData; } void ofxTPSprite::draw(int x, int y) { if(data->getRotated()) { ofPushMatrix(); ofRotate(90); } texture->drawSubsection(x+data->getOffsetX(), y+data->getOffsetY(), data->getW(), data->getH(), data->getX(), data->getY()); if(data->getRotated()) { ofPopMatrix(); } }
// ------------------------------------------------------------------ // ofxTPSprite.cpp // ofxTexturePacker - https://www.github.com/danoli3/ofxTexturePacker // Created by Daniel Rosser and Colin Friend on 9/06/2014. // ------------------------------------------------------------------ #include "ofxTPSprite.h" ofxTPSprite::ofxTPSprite(ofxTPSpriteData* theData) { data = theData; } void ofxTPSprite::draw(int x, int y) { if(data->getRotated()) { ofPushMatrix(); ofRotate(90); } texture->drawSubsection(x+data->getOffsetX(), y+data->getOffsetY(), data->getW(), data->getH(), data->getX(), data->getY(), data->getW(), data->getH()); if(data->getRotated()) { ofPopMatrix(); } }
Enable usage of CuptiErrorManager on all the platforms.
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "absl/memory/memory.h" #include "tensorflow/core/profiler/internal/gpu/cupti_interface.h" #include "tensorflow/core/profiler/internal/gpu/cupti_wrapper.h" #if defined(PLATFORM_GOOGLE) #include "tensorflow/core/profiler/internal/gpu/cupti_error_manager.h" #endif namespace tensorflow { namespace profiler { CuptiInterface* GetCuptiInterface() { static CuptiInterface* cupti_interface = #if defined(PLATFORM_GOOGLE) new CuptiErrorManager(absl::make_unique<CuptiWrapper>()); #else new CuptiWrapper(); #endif return cupti_interface; } } // namespace profiler } // namespace tensorflow
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "absl/memory/memory.h" #include "tensorflow/core/profiler/internal/gpu/cupti_interface.h" #include "tensorflow/core/profiler/internal/gpu/cupti_wrapper.h" #include "tensorflow/core/profiler/internal/gpu/cupti_error_manager.h" namespace tensorflow { namespace profiler { CuptiInterface* GetCuptiInterface() { static CuptiInterface* cupti_interface = new CuptiErrorManager(absl::make_unique<CuptiWrapper>()); return cupti_interface; } } // namespace profiler } // namespace tensorflow
Fix timing of setting HiDPI options
/* * Copyright 2016 - 2019 gtalent2@gmail.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <QApplication> #include <QDebug> #include <ox/clargs/clargs.hpp> #include "mainwindow.hpp" using namespace nostalgia::studio; int main(int argc, char **args) { ox::ClArgs clargs(argc, const_cast<const char**>(args)); QString argProfilePath = clargs.getString("profile").c_str(); QApplication app(argc, args); app.setAttribute(Qt::AA_UseHighDpiPixmaps); try { MainWindow w(argProfilePath); app.setApplicationName(w.windowTitle()); w.show(); QObject::connect(&app, &QApplication::aboutToQuit, &w, &MainWindow::onExit); return app.exec(); } catch (ox::Error err) { oxPanic(err, "Unhandled ox::Error"); } }
/* * Copyright 2016 - 2019 gtalent2@gmail.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <QApplication> #include <QDebug> #include <ox/clargs/clargs.hpp> #include "mainwindow.hpp" using namespace nostalgia::studio; int main(int argc, char **args) { ox::ClArgs clargs(argc, const_cast<const char**>(args)); QString argProfilePath = clargs.getString("profile").c_str(); QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QApplication app(argc, args); try { MainWindow w(argProfilePath); app.setApplicationName(w.windowTitle()); w.show(); QObject::connect(&app, &QApplication::aboutToQuit, &w, &MainWindow::onExit); return app.exec(); } catch (ox::Error err) { oxPanic(err, "Unhandled ox::Error"); } }
Revert "Testing -lPUBLIC error using turbo_computing blockdependencies"
/****************************************************************************** * Turbo C++11 metaprogramming Library * * * * Copyright (C) 2013 - 2014, Manuel Sánchez Pérez * * * * This file is part of The Turbo Library. * * * * The Turbo Library is free software: you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation, version 2 of the License. * * * * The Turbo Library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with The Turbo Library. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************/ //#include "manu343726/turbo_core/turbo_core.hpp" #include "manu343726/turbo_computing/float.hpp" #include <type_traits> #include <iostream> #include <iomanip> using a = FLOAT(2.54); int main() { //std::cout << tml::to_string<decltype("hello")>() << std::endl; }
/****************************************************************************** * Turbo C++11 metaprogramming Library * * * * Copyright (C) 2013 - 2014, Manuel Sánchez Pérez * * * * This file is part of The Turbo Library. * * * * The Turbo Library is free software: you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation, version 2 of the License. * * * * The Turbo Library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with The Turbo Library. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************/ #include "manu343726/turbo_core/turbo_core.hpp" //#include "manu343726/turbo_computing/float.hpp" #include <type_traits> #include <iostream> #include <iomanip> int main() { std::cout << tml::to_string<decltype("hello")>() << std::endl; }
Add return statement to a test class's assignment operator. Defect found by Coverity Scan.
//===----------------------------------------------------------------------===// // // 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 default ctor // default unique_ptr ctor should require default Deleter ctor #include <memory> class Deleter { Deleter() {} public: Deleter(Deleter&) {} Deleter& operator=(Deleter&) {} void operator()(void*) const {} }; int main() { std::unique_ptr<int[], Deleter> p; }
//===----------------------------------------------------------------------===// // // 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 default ctor // default unique_ptr ctor should require default Deleter ctor #include <memory> class Deleter { Deleter() {} public: Deleter(Deleter&) {} Deleter& operator=(Deleter&) { return *this; } void operator()(void*) const {} }; int main() { std::unique_ptr<int[], Deleter> p; }
Reset stack before benchmark finishes.
#include "BenchmarkStack.h" #include "StackAllocator.h" BenchmarkStack::BenchmarkStack(const int runtime) : Benchmark(runtime) { } BenchmarkResults BenchmarkStack::allocation() { setStartTimer(); StackAllocator stackAllocator(1e10); int operations = 0; while(!outOfTime()){ stackAllocator.Allocate(sizeof(int), alignof(int)); // 4 -> 4 stackAllocator.Allocate(sizeof(bool), alignof(bool)); // 1 -> 5 // 3 -> 8 stackAllocator.Allocate(sizeof(foo), alignof(foo)); // 16 -> 24 ++operations; } BenchmarkResults results = buildResults(operations, m_runtime, 0, 0); printResults(results); return results; } BenchmarkResults BenchmarkStack::free() { return buildResults(0, 0, 0, 0); } BenchmarkResults BenchmarkStack::read() { return buildResults(0, 0, 0, 0); } BenchmarkResults BenchmarkStack::write() { return buildResults(0, 0, 0, 0); } BenchmarkResults BenchmarkStack::all() { return buildResults(0, 0, 0, 0); }
#include "BenchmarkStack.h" #include "StackAllocator.h" BenchmarkStack::BenchmarkStack(const int runtime) : Benchmark(runtime) { } BenchmarkResults BenchmarkStack::allocation() { setStartTimer(); StackAllocator stackAllocator(1e10); int operations = 0; while(!outOfTime()){ stackAllocator.Allocate(sizeof(int), alignof(int)); // 4 -> 4 stackAllocator.Allocate(sizeof(bool), alignof(bool)); // 1 -> 5 // 3 -> 8 stackAllocator.Allocate(sizeof(foo), alignof(foo)); // 16 -> 24 ++operations; } BenchmarkResults results = buildResults(operations, m_runtime, 0, 0); printResults(results); stackAllocator.Reset(); return results; } BenchmarkResults BenchmarkStack::free() { return buildResults(0, 0, 0, 0); } BenchmarkResults BenchmarkStack::read() { return buildResults(0, 0, 0, 0); } BenchmarkResults BenchmarkStack::write() { return buildResults(0, 0, 0, 0); } BenchmarkResults BenchmarkStack::all() { return buildResults(0, 0, 0, 0); }
Update IUnknown lit test to pass on Win32
// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fsyntax-only -verify -fms-extensions %s typedef long HRESULT; typedef unsigned long ULONG; typedef struct _GUID { unsigned long Data1; unsigned short Data2; unsigned short Data3; unsigned char Data4[8]; } GUID; typedef GUID IID; // remove stdcall, since the warnings have nothing to do with // what is being tested. #define __stdcall extern "C" { extern "C++" { // expected-warning@+1 {{__declspec attribute 'novtable'}} struct __declspec(uuid("00000000-0000-0000-C000-000000000046")) __declspec(novtable) IUnknown { public: virtual HRESULT __stdcall QueryInterface( const IID &riid, void **ppvObject) = 0; virtual ULONG __stdcall AddRef(void) = 0; virtual ULONG __stdcall Release(void) = 0; template <class Q> HRESULT __stdcall QueryInterface(Q **pp) { return QueryInterface(__uuidof(Q), (void **)pp); } }; } } __interface ISfFileIOPropertyPage : public IUnknown{};
// RUN: %clang_cc1 -fsyntax-only -verify -fms-extensions %s // expected-no-diagnostics typedef long HRESULT; typedef unsigned long ULONG; typedef struct _GUID { unsigned long Data1; unsigned short Data2; unsigned short Data3; unsigned char Data4[8]; } GUID; typedef GUID IID; // remove stdcall, since the warnings have nothing to do with // what is being tested. #define __stdcall extern "C" { extern "C++" { struct __declspec(uuid("00000000-0000-0000-C000-000000000046")) IUnknown { public: virtual HRESULT __stdcall QueryInterface( const IID &riid, void **ppvObject) = 0; virtual ULONG __stdcall AddRef(void) = 0; virtual ULONG __stdcall Release(void) = 0; template <class Q> HRESULT __stdcall QueryInterface(Q **pp) { return QueryInterface(__uuidof(Q), (void **)pp); } }; } } __interface ISfFileIOPropertyPage : public IUnknown{};
Fix help system which was not registering factory methods before trying to enumerate them.
#include <pangolin/video/video_help.h> #include <pangolin/video/video_interface.h> namespace pangolin { void PrintPixelFormats(std::ostream& out, bool color) { const std::string c_normal = color ? "\033[0m" : ""; const std::string c_alias = color ? "\033[32m" : ""; out << "Supported pixel format codes (and their respective bits-per-pixel):" << std::endl; std::vector<pangolin::PixelFormat> pixelFormats = pangolin::GetSupportedPixelFormats(); for(const auto& format: pixelFormats ){ out << c_alias << format.format << c_normal << " (" << format.bpp << "), "; } out << std::endl; } void VideoHelp( std::ostream& out, const std::string& scheme_filter, HelpVerbosity verbosity) { #ifndef _WIN32_ const bool use_color = true; #else const bool use_color = false; #endif if( verbosity >= HelpVerbosity::SYNOPSIS ) { PrintSchemeHelp(out, use_color); out << std::endl; } PrintFactoryRegistryDetails(out, *FactoryRegistry::I(), typeid(VideoInterface), scheme_filter, verbosity, use_color); if( verbosity >= HelpVerbosity::PARAMS ) { PrintPixelFormats(out, use_color); } } }
#include <pangolin/video/video_help.h> #include <pangolin/video/video_interface.h> #include <pangolin/factory/RegisterFactoriesVideoInterface.h> #include <pangolin/factory/RegisterFactoriesVideoOutputInterface.h> namespace pangolin { void PrintPixelFormats(std::ostream& out, bool color) { const std::string c_normal = color ? "\033[0m" : ""; const std::string c_alias = color ? "\033[32m" : ""; out << "Supported pixel format codes (and their respective bits-per-pixel):" << std::endl; std::vector<pangolin::PixelFormat> pixelFormats = pangolin::GetSupportedPixelFormats(); for(const auto& format: pixelFormats ){ out << c_alias << format.format << c_normal << " (" << format.bpp << "), "; } out << std::endl; } void VideoHelp( std::ostream& out, const std::string& scheme_filter, HelpVerbosity verbosity) { RegisterFactoriesVideoInterface(); #ifndef _WIN32_ const bool use_color = true; #else const bool use_color = false; #endif if( verbosity >= HelpVerbosity::SYNOPSIS ) { PrintSchemeHelp(out, use_color); out << std::endl; } PrintFactoryRegistryDetails(out, *FactoryRegistry::I(), typeid(VideoInterface), scheme_filter, verbosity, use_color); if( verbosity >= HelpVerbosity::PARAMS ) { PrintPixelFormats(out, use_color); } } }
Fix use of terse static assert. Patch from STL@microsoft.com
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // type_traits // is_swappable // IMPORTANT: The include order is part of the test. We want to pick up // the following definitions in this order: // 1) is_swappable, is_nothrow_swappable // 2) iter_swap, swap_ranges // 3) swap(T (&)[N], T (&)[N]) // This test checks that (1) and (2) see forward declarations // for (3). #include <type_traits> #include <algorithm> #include <utility> #include "test_macros.h" int main() { // Use a builtin type so we don't get ADL lookup. typedef double T[17][29]; { LIBCPP_STATIC_ASSERT(std::__is_swappable<T>::value, ""); #if TEST_STD_VER > 14 static_assert(std::is_swappable_v<T>); #endif } { T t1 = {}; T t2 = {}; std::iter_swap(t1, t2); std::swap_ranges(t1, t1 + 17, t2); } }
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // type_traits // is_swappable // IMPORTANT: The include order is part of the test. We want to pick up // the following definitions in this order: // 1) is_swappable, is_nothrow_swappable // 2) iter_swap, swap_ranges // 3) swap(T (&)[N], T (&)[N]) // This test checks that (1) and (2) see forward declarations // for (3). #include <type_traits> #include <algorithm> #include <utility> #include "test_macros.h" int main() { // Use a builtin type so we don't get ADL lookup. typedef double T[17][29]; { LIBCPP_STATIC_ASSERT(std::__is_swappable<T>::value, ""); #if TEST_STD_VER > 14 static_assert(std::is_swappable_v<T>, ""); #endif } { T t1 = {}; T t2 = {}; std::iter_swap(t1, t2); std::swap_ranges(t1, t1 + 17, t2); } }
Change energy absorption, so you only absorb part of the enemy energy
#include <memory> #include "Vec2i.h" #include "IMapElement.h" #include "CActor.h" namespace WizardOfGalicia { CActor::CActor() { emission = 0; stance = Stance::STANDING; attack = 0; defence = 0; hp = 0; direction = Direction::N; } bool CActor::canMove() { return true; } bool CActor::canAttack() { return true; } void CActor::turnLeft() { if ( direction == Direction::N ) { direction = Direction::W; } else { direction = static_cast<Direction>( static_cast<int>(direction) - 1); } } void CActor::turnRight() { if ( direction == Direction::W ) { direction = Direction::N; } else { direction = static_cast<Direction>( static_cast<int>(direction) + 1); } } void CActor::onMove() { } void CActor::onAttack() { } void CActor::endOfTurn() { } void CActor::performAttack( std::shared_ptr<CActor> other ) { if ( abs( magicEnergy ) < abs( other->magicEnergy ) ) { return; } onAttack(); int diff = ( attack - other->defence ); if ( diff > 0 ) { other->hp -= diff; } int deltaEnergy = (magicEnergy + other->magicEnergy) / 2; magicEnergy += deltaEnergy; } }
#include <memory> #include "Vec2i.h" #include "IMapElement.h" #include "CActor.h" namespace WizardOfGalicia { CActor::CActor() { emission = 0; stance = Stance::STANDING; attack = 0; defence = 0; hp = 0; direction = Direction::N; } bool CActor::canMove() { return true; } bool CActor::canAttack() { return true; } void CActor::turnLeft() { if ( direction == Direction::N ) { direction = Direction::W; } else { direction = static_cast<Direction>( static_cast<int>(direction) - 1); } } void CActor::turnRight() { if ( direction == Direction::W ) { direction = Direction::N; } else { direction = static_cast<Direction>( static_cast<int>(direction) + 1); } } void CActor::onMove() { } void CActor::onAttack() { } void CActor::endOfTurn() { } void CActor::performAttack( std::shared_ptr<CActor> other ) { if ( abs( magicEnergy ) < abs( other->magicEnergy ) ) { return; } onAttack(); int diff = ( attack - other->defence ); if ( diff > 0 ) { other->hp -= diff; } int deltaEnergy = (other->magicEnergy) / 2; magicEnergy += deltaEnergy; } }
Add a simple option parser
/* Copyright 2014-2015 Juhani Numminen * * 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 <clocale> #include <cstring> #include <exception> #include <iostream> #include "config.hpp" #include "game.hpp" #include "i18n.hpp" int main(int argc, char *argv[]) { std::setlocale(LC_ALL, ""); bindtextdomain("pong--11", LOCALEDIR); textdomain("pong--11"); try { if (argc > 1 && std::strcmp(argv[1], "-s") == 0) Game{}.run(true); else Game{}.run(false); } catch (const std::exception& e) { std::cerr << _("Exception: ") << e.what() << std::endl; return EXIT_FAILURE; } }
/* Copyright 2014-2015 Juhani Numminen * * 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 <clocale> #include <cstring> #include <exception> #include <iostream> #include "config.hpp" #include "game.hpp" #include "i18n.hpp" int main(int argc, char *argv[]) { std::setlocale(LC_ALL, ""); bindtextdomain("pong--11", LOCALEDIR); textdomain("pong--11"); bool isSingleplayer = false; if (argc > 1) { for (int i = 1; i < argc; ++i) { if (std::strcmp(argv[i], "-s") == 0) { isSingleplayer = true; } else { std::fprintf(stderr, _("Invalid option: '%s'\n"), argv[i]); return EXIT_FAILURE; } } } try { Game{}.run(isSingleplayer); } catch (const std::exception& e) { std::cerr << _("Exception: ") << e.what() << std::endl; return EXIT_FAILURE; } }
Check for positive number of threads.
#include "DownloadManager.h" #include <cstdio> #include <iostream> #include <string> using namespace tinydm; int main(int argc, char **argv) { if (argc < 2) { std::cerr << "Usage: tinydm [threads]" << std::endl; return EXIT_FAILURE; } int threads = std::atoi(argv[1]); if (threads == 0) { std::cerr << "Invalid number of threads specified" << std::endl; return EXIT_FAILURE; } DownloadManager dm(threads); std::string line; while (std::getline(std::cin, line)) { if (line.empty()) break; dm.download(line); } return EXIT_SUCCESS; }
#include "DownloadManager.h" #include <cstdio> #include <iostream> #include <string> using namespace tinydm; int main(int argc, char **argv) { if (argc < 2) { std::cerr << "Usage: tinydm [threads]" << std::endl; return EXIT_FAILURE; } int threads = std::atoi(argv[1]); if (threads <= 0) { std::cerr << "Invalid number of threads specified" << std::endl; return EXIT_FAILURE; } DownloadManager dm(threads); std::string line; while (std::getline(std::cin, line)) { if (line.empty()) break; dm.download(line); } return EXIT_SUCCESS; }
Add a test case for some builtin objects
// Copyright 2008 Paul Hodge #include "common_headers.h" #include "circa.h" #include "tests/common.h" namespace circa { namespace primitive_type_tests { void strings() { Branch* branch = new Branch(); Term* str1 = constant_string(branch, "one"); Term* str2 = constant_string(branch, "two"); test_assert(as_string(str1) == "one"); test_assert(as_string(str2) == "two"); duplicate_value(str1,str2); test_assert(as_string(str1) == "one"); test_assert(as_string(str2) == "one"); } } // namespace primitive_type_tests void register_primitive_type_tests() { REGISTER_TEST_CASE(primitive_type_tests::strings); } } // namespace circa
// Copyright 2008 Paul Hodge #include "common_headers.h" #include "circa.h" #include "tests/common.h" namespace circa { namespace primitive_type_tests { void strings() { Branch* branch = new Branch(); Term* str1 = constant_string(branch, "one"); Term* str2 = constant_string(branch, "two"); test_assert(as_string(str1) == "one"); test_assert(as_string(str2) == "two"); duplicate_value(str1,str2); test_assert(as_string(str1) == "one"); test_assert(as_string(str2) == "one"); } void builtin_objects() { test_assert(KERNEL->findNamed("int") == INT_TYPE); test_assert(KERNEL->findNamed("float") == FLOAT_TYPE); test_assert(KERNEL->findNamed("string") == STRING_TYPE); test_assert(KERNEL->findNamed("bool") == BOOL_TYPE); } } // namespace primitive_type_tests void register_primitive_type_tests() { REGISTER_TEST_CASE(primitive_type_tests::strings); REGISTER_TEST_CASE(primitive_type_tests::builtin_objects); } } // namespace circa
Change to use LinkDynamicObject instead of dlopen.
//===-- PluginLoader.cpp - Implement -load command line option ------------===// // // This file implements the -load <plugin> command line option processor. When // linked into a program, this new command line option is available that allows // users to load shared objects into the running program. // // Note that there are no symbols exported by the .o file generated for this // .cpp file. Because of this, a program must link against support.o instead of // support.a: otherwise this translation unit will not be included. // //===----------------------------------------------------------------------===// #include "Support/CommandLine.h" #include "Config/dlfcn.h" #include "Config/link.h" #include <iostream> namespace { struct PluginLoader { void operator=(const std::string &Filename) { if (dlopen(Filename.c_str(), RTLD_NOW|RTLD_GLOBAL) == 0) std::cerr << "Error opening '" << Filename << "': " << dlerror() << "\n -load request ignored.\n"; } }; } // This causes operator= above to be invoked for every -load option. static cl::opt<PluginLoader, false, cl::parser<std::string> > LoadOpt("load", cl::ZeroOrMore, cl::value_desc("plugin.so"), cl::desc("Load the specified plugin"));
//===-- PluginLoader.cpp - Implement -load command line option ------------===// // // This file implements the -load <plugin> command line option processor. When // linked into a program, this new command line option is available that allows // users to load shared objects into the running program. // // Note that there are no symbols exported by the .o file generated for this // .cpp file. Because of this, a program must link against support.o instead of // support.a: otherwise this translation unit will not be included. // //===----------------------------------------------------------------------===// #include "Support/DynamicLinker.h" #include "Support/CommandLine.h" #include "Config/dlfcn.h" #include "Config/link.h" #include <iostream> namespace { struct PluginLoader { void operator=(const std::string &Filename) { std::string ErrorMessage; if (LinkDynamicObject (Filename.c_str (), &ErrorMessage)) std::cerr << "Error opening '" << Filename << "': " << ErrorMessage << "\n -load request ignored.\n"; } }; } // This causes operator= above to be invoked for every -load option. static cl::opt<PluginLoader, false, cl::parser<std::string> > LoadOpt("load", cl::ZeroOrMore, cl::value_desc("plugin.so"), cl::desc("Load the specified plugin"));
Fix unused variable warning in a scenario.
/** * This test checks whether we detect a deadlock arising from a parent thread * trying to join a child who requires a lock held by its parent in order to * finish. */ #include <d2mock.hpp> int main(int argc, char const* argv[]) { d2mock::mutex G; d2mock::thread t1([&] { G.lock(); G.unlock(); }); d2mock::thread t0([&] { t1.start(); // if t0 acquires G before t1 does, t1 can never be joined G.lock(); t1.join(); G.unlock(); }); auto test_main = [&] { t0.start(); t0.join(); }; // Right now, we have no way of encoding these kinds of deadlocks, // and we're obviously not detecting them too. For now, we'll always // make the test fail. #if 1 return EXIT_FAILURE; #else return d2mock::check_scenario(test_main, argc, argv, { { // t0 holds G, and waits for t1 to join {t0, G, join(t1)}, // t1 waits for G, and will never be joined {t1, G} } }); #endif }
/** * This test checks whether we detect a deadlock arising from a parent thread * trying to join a child who requires a lock held by its parent in order to * finish. */ #include <d2mock.hpp> int main(int argc, char const* argv[]) { d2mock::mutex G; d2mock::thread t1([&] { G.lock(); G.unlock(); }); d2mock::thread t0([&] { t1.start(); // if t0 acquires G before t1 does, t1 can never be joined G.lock(); t1.join(); G.unlock(); }); auto test_main = [&] { t0.start(); t0.join(); }; // Right now, we have no way of encoding these kinds of deadlocks, // and we're obviously not detecting them too. For now, we'll always // make the test fail. #if 1 (void)test_main; return EXIT_FAILURE; #else return d2mock::check_scenario(test_main, argc, argv, { { // t0 holds G, and waits for t1 to join {t0, G, join(t1)}, // t1 waits for G, and will never be joined {t1, G} } }); #endif }
Remove unneeded OpenMP header import.
#include <omp.h> #include "proctor/detector.h" #include "proctor/proctor.h" #include "proctor/scanning_model_source.h" #include "proctor/basic_proposer.h" using pcl::proctor::Detector; //using pcl::proctor::ProctorMPI; using pcl::proctor::Proctor; using pcl::proctor::ScanningModelSource; using pcl::proctor::BasicProposer; int main(int argc, char **argv) { unsigned int model_seed = 2; unsigned int test_seed = 0; //time(NULL); if (argc >= 2) { model_seed = atoi(argv[1]); } if (argc >= 3) { test_seed = atoi(argv[2]); } Detector detector; Proctor proctor; BasicProposer::Ptr proposer(new BasicProposer); detector.setProposer(proposer); ScanningModelSource model_source("Princeton", "/home/justin/Documents/benchmark/db"); model_source.loadModels(); //detector.enableVisualization(); proctor.setModelSource(&model_source); proctor.train(detector); proctor.test(detector, test_seed); proctor.printResults(detector); sleep(100000); return 0; }
#include "proctor/detector.h" #include "proctor/proctor.h" #include "proctor/scanning_model_source.h" #include "proctor/basic_proposer.h" using pcl::proctor::Detector; //using pcl::proctor::ProctorMPI; using pcl::proctor::Proctor; using pcl::proctor::ScanningModelSource; using pcl::proctor::BasicProposer; int main(int argc, char **argv) { unsigned int model_seed = 2; unsigned int test_seed = 0; //time(NULL); if (argc >= 2) { model_seed = atoi(argv[1]); } if (argc >= 3) { test_seed = atoi(argv[2]); } Detector detector; Proctor proctor; BasicProposer::Ptr proposer(new BasicProposer); detector.setProposer(proposer); ScanningModelSource model_source("Princeton", "/home/justin/Documents/benchmark/db"); model_source.loadModels(); //detector.enableVisualization(); proctor.setModelSource(&model_source); proctor.train(detector); proctor.test(detector, test_seed); proctor.printResults(detector); sleep(100000); return 0; }
Fix node-structural Rand measure to not to be binary
/* * RandMeasure.cpp * * Created on: 19.01.2013 * Author: Christian Staudt (christian.staudt@kit.edu) */ #include "NodeStructuralRandMeasure.h" namespace NetworKit { double NodeStructuralRandMeasure::getDissimilarity(const Graph& G, const Partition& first, const Partition& second) { count n = G.numberOfNodes(); assert (n > 0); count s11 = 0; // number of node pairs for which clusterings aggree count s00 = 0; // number of node pairs for which clusterings disagree G.forNodePairs([&](node u, node v){ if ((first[u] == first[v]) && (second[u] == second[v])) { s11 += 1; } else if ((first[u] != first[v]) && (second[u] != second[v])) { s00 += 1; } }); double rand = 1 - ((2 * (s11 + s00)) / (n * (n-1))); // assert range [0, 1] assert (rand <= 1.0); assert (rand >= 0.0); return rand; } } /* namespace NetworKit */
/* * RandMeasure.cpp * * Created on: 19.01.2013 * Author: Christian Staudt (christian.staudt@kit.edu) */ #include "NodeStructuralRandMeasure.h" namespace NetworKit { double NodeStructuralRandMeasure::getDissimilarity(const Graph& G, const Partition& first, const Partition& second) { count n = G.numberOfNodes(); assert (n > 0); count s11 = 0; // number of node pairs for which clusterings aggree count s00 = 0; // number of node pairs for which clusterings disagree G.forNodePairs([&](node u, node v){ if ((first[u] == first[v]) && (second[u] == second[v])) { s11 += 1; } else if ((first[u] != first[v]) && (second[u] != second[v])) { s00 += 1; } }); double rand = 1 - ((2 * (s11 + s00)) * 1.0 / (n * (n-1))); // assert range [0, 1] assert (rand <= 1.0); assert (rand >= 0.0); return rand; } } /* namespace NetworKit */
Check for updates on startup
// For conditions of distribution and use, see copyright notice in license.txt #include "UpdateModuleMac.h" #include "Framework.h" #include "CoreDefines.h" #include "Application.h" UpdateModule::UpdateModule() : IModule("UpdateModule"), updater_(0) { } UpdateModule::~UpdateModule() { } void UpdateModule::Initialize() { CocoaInitializer initializer; updater_ = new SparkleAutoUpdater("http://adminotech.data.s3.amazonaws.com/clients/tundra2/appcast.xml"); } void UpdateModule::RunUpdater(QString parameter) { if (updater_) updater_->checkForUpdates(); } extern "C" { DLLEXPORT void TundraPluginMain(Framework *fw) { Framework::SetInstance(fw); // Inside this DLL, remember the pointer to the global framework object. IModule *module = new UpdateModule(); fw->RegisterModule(module); } }
// For conditions of distribution and use, see copyright notice in license.txt #include "UpdateModuleMac.h" #include "Framework.h" #include "CoreDefines.h" #include "Application.h" UpdateModule::UpdateModule() : IModule("UpdateModule"), updater_(0) { } UpdateModule::~UpdateModule() { } void UpdateModule::Initialize() { CocoaInitializer initializer; updater_ = new SparkleAutoUpdater("http://adminotech.data.s3.amazonaws.com/clients/tundra2/appcast.xml"); if (updater_) updater_->checkForUpdates(); } void UpdateModule::RunUpdater(QString parameter) { if (updater_) updater_->checkForUpdates(); } extern "C" { DLLEXPORT void TundraPluginMain(Framework *fw) { Framework::SetInstance(fw); // Inside this DLL, remember the pointer to the global framework object. IModule *module = new UpdateModule(); fw->RegisterModule(module); } }
Change seed generation using MINSTD
/* * rngs * ECE 541 Project 2 * Kashev Dalmia - dalmia3 * David Huang - huang157 */ #include "ranlux32.h" namespace rng { RANLUX32::RANLUX32() : RandomNumberGenerator(), prev(0), count(0), state(), index(0) {} void RANLUX32::seed(fuint seed_num) { state[0] = seed_num; /* * Initialize seed vector using MINSTD */ static constexpr uint64_t g = 48271; static constexpr uint64_t n = (1UL << 48UL); // 2^49 for(size_t i = 1; i < state.size(); ++i) { state[i] = static_cast<fuint>((static_cast<uint64_t>(state[i-1]) * g) % n); } } fuint RANLUX32::operator()() { if(count == discard) { count = 0; for(uint i = 0; i < block_size-discard; ++i) { next_state(); } } uint64_t output = next_state(); count++; return static_cast<fuint>(output); } }
/* * rngs * ECE 541 Project 2 * Kashev Dalmia - dalmia3 * David Huang - huang157 */ #include "ranlux32.h" namespace rng { RANLUX32::RANLUX32() : RandomNumberGenerator(), prev(0), count(0), state(), index(0) {} void RANLUX32::seed(fuint seed_num) { state[0] = seed_num; /* * Initialize seed vector using MINSTD */ static constexpr uint64_t g = 48271; static constexpr uint64_t n = (1UL << 31UL) - 1UL; // 2^32 -1 fuint first, second; for(size_t i = 1; i < state.size(); ++i) { first = static_cast<fuint>((static_cast<uint64_t>(state[i-1]) * g) % n); second = static_cast<fuint>((static_cast<uint64_t>(first) * g) % n); state[i] = ((static_cast<uint64_t>(first)) << 32UL) << second; } } fuint RANLUX32::operator()() { if(count == discard) { count = 0; for(uint i = 0; i < block_size-discard; ++i) { next_state(); } } uint64_t output = next_state(); count++; return static_cast<fuint>(output); } }
Remove confusing transpose() in setLinSpaced() docs.
VectorXf v; v.setLinSpaced(5,0.5f,1.5f).transpose(); cout << v << endl;
VectorXf v; v.setLinSpaced(5,0.5f,1.5f); cout << v << endl;
Fix crash for mono 5.0.
#include "edge.h" void Dictionary::Add(MonoObject* _this, const char* name, MonoObject* value) { static MonoMethod* add; if(!add) { add = mono_class_get_method_from_name(mono_object_get_class(_this), "System.Collections.Generic.IDictionary<string,object>.Add", -1); } void* params[2]; params[0] = mono_string_new(mono_domain_get(), name); params[1] = value; mono_runtime_invoke(add, _this, params, NULL); }
#include "edge.h" void Dictionary::Add(MonoObject* _this, const char* name, MonoObject* value) { static MonoMethod* add; if(!add) { add = mono_class_get_method_from_name(mono_object_get_class(_this), "System.Collections.Generic.IDictionary<string,object>.Add", -1); // This is to work around a crash due to updating to MONO 5.0. // We still need the previous call to be backwards compatible. if (add == NULL) { add = mono_class_get_method_from_name(mono_object_get_class(_this), "System.Collections.Generic.IDictionary<System.String,System.Object>.Add", -1); } } void* params[2]; params[0] = mono_string_new(mono_domain_get(), name); params[1] = value; mono_runtime_invoke(add, _this, params, NULL); }
Add more tests for Transaction
#include "stdafx.h" #include "CppUnitTest.h" #include "datastore.h" #include "transaction.h" #include "internal/operations/post_operation.h" #include "dummy_values.h" using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; namespace You { namespace DataStore { namespace UnitTests { TEST_CLASS(DataStoreApiTest) { public: TEST_METHOD(pushOperationToTransaction) { Transaction sut; std::shared_ptr<Internal::IOperation> postOp = std::make_shared<Internal::PostOperation>(0, task1); sut.push(postOp); Assert::AreEqual(boost::lexical_cast<size_t>(1), sut.operationsQueue.size()); } }; } // namespace UnitTests } // namespace DataStore } // namespace You
#include "stdafx.h" #include "CppUnitTest.h" #include "datastore.h" #include "transaction.h" #include "internal/operations/post_operation.h" #include "internal/operations/put_operation.h" #include "internal/operations/erase_operation.h" #include "dummy_values.h" using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; namespace You { namespace DataStore { namespace UnitTests { TEST_CLASS(DataStoreApiTest) { public: TEST_METHOD(pushOperationsToTransaction) { Transaction sut; std::shared_ptr<Internal::IOperation> postOp = std::make_shared<Internal::PostOperation>(0, task1); sut.push(postOp); Assert::AreEqual(boost::lexical_cast<size_t>(1), sut.operationsQueue.size()); std::shared_ptr<Internal::IOperation> putOp = std::make_shared<Internal::PutOperation>(0, task2); sut.push(putOp); Assert::AreEqual(boost::lexical_cast<size_t>(2), sut.operationsQueue.size()); std::shared_ptr<Internal::IOperation> eraseOp = std::make_shared<Internal::EraseOperation>(0); sut.push(eraseOp); Assert::AreEqual(boost::lexical_cast<size_t>(3), sut.operationsQueue.size()); } }; } // namespace UnitTests } // namespace DataStore } // namespace You
Revert "remove georgs fancy camera and mesh stuff"
#include <zombye/gameplay/states/menu_state.hpp> #include <zombye/rendering/camera_component.hpp> using namespace std::string_literals; zombye::menu_state::menu_state(zombye::state_machine *sm) : sm_(sm) { } void zombye::menu_state::enter() { zombye::log("enter menu state"); } void zombye::menu_state::leave() { zombye::log("leave menu state"); } void zombye::menu_state::update(float delta_time) { sm_->use(GAME_STATE_PLAY); }
#include <zombye/gameplay/states/menu_state.hpp> #include <zombye/rendering/camera_component.hpp> using namespace std::string_literals; zombye::menu_state::menu_state(zombye::state_machine *sm) : sm_(sm) { } void zombye::menu_state::enter() { zombye::log("enter menu state"); auto& camera = sm_->get_game()->entity_manager().emplace(glm::vec3{-2.f, 2.f, -3.0f}, glm::quat{}, glm::vec3{}); camera.emplace<camera_component>(glm::vec3{}, glm::vec3{0.f, 1.f, 0.f}); sm_->get_game()->rendering_system().activate_camera(camera.id()); sm_->get_game()->entity_manager().emplace("dummy", glm::vec3{}, glm::quat{}, glm::vec3{1}); } void zombye::menu_state::leave() { zombye::log("leave menu state"); } void zombye::menu_state::update(float delta_time) { sm_->use(GAME_STATE_PLAY); }
Remove useless include from Example.cpp
// Copyright (c) 2015 The Bitcoin Core developers // Copyright (c) 2015-2018 The Bitcoin Unlimited developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bench.h" #include "main.h" #include "utiltime.h" // Sanity test: this should loop ten times, and // min/max/average should be close to 100ms. static void Sleep100ms(benchmark::State &state) { while (state.KeepRunning()) { MilliSleep(100); } } BENCHMARK(Sleep100ms); // Extremely fast-running benchmark: #include <math.h> volatile double sum = 0.0; // volatile, global so not optimized away static void Trig(benchmark::State &state) { double d = 0.01; while (state.KeepRunning()) { sum += sin(d); d += 0.000001; } } BENCHMARK(Trig);
// Copyright (c) 2015 The Bitcoin Core developers // Copyright (c) 2015-2018 The Bitcoin Unlimited developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bench.h" #include "utiltime.h" // Sanity test: this should loop ten times, and // min/max/average should be close to 100ms. static void Sleep100ms(benchmark::State &state) { while (state.KeepRunning()) { MilliSleep(100); } } BENCHMARK(Sleep100ms); // Extremely fast-running benchmark: #include <math.h> volatile double sum = 0.0; // volatile, global so not optimized away static void Trig(benchmark::State &state) { double d = 0.01; while (state.KeepRunning()) { sum += sin(d); d += 0.000001; } } BENCHMARK(Trig);
Remove spurious mode marker from .cpp file.
//===- ChainedDiagnosticConsumer.cpp - Chain Diagnostic Clients -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/Frontend/ChainedDiagnosticConsumer.h" using namespace clang; void ChainedDiagnosticConsumer::anchor() { }
//===- ChainedDiagnosticConsumer.cpp - Chain Diagnostic Clients -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/Frontend/ChainedDiagnosticConsumer.h" using namespace clang; void ChainedDiagnosticConsumer::anchor() { }
Add timer to Linux example
/** * @file main.cpp * @author Volodymyr Shymanskyy * @license This project is released under the MIT License (MIT) * @copyright Copyright (c) 2015 Volodymyr Shymanskyy * @date Mar 2015 * @brief */ //#define BLYNK_DEBUG #define BLYNK_PRINT stdout #ifdef RASPBERRY #include <BlynkApiWiringPi.h> #else #include <BlynkApiLinux.h> #endif #include <BlynkSocket.h> #include <BlynkOptionsParser.h> static BlynkTransportSocket _blynkTransport; BlynkSocket Blynk(_blynkTransport); static const char *auth, *serv; static uint16_t port; #include <BlynkWidgets.h> BLYNK_WRITE(V1) { printf("Got a value: %s\n", param[0].asStr()); } void setup() { Blynk.begin(auth, serv, port); } void loop() { Blynk.run(); } int main(int argc, char* argv[]) { parse_options(argc, argv, auth, serv, port); setup(); while(true) { loop(); } return 0; }
/** * @file main.cpp * @author Volodymyr Shymanskyy * @license This project is released under the MIT License (MIT) * @copyright Copyright (c) 2015 Volodymyr Shymanskyy * @date Mar 2015 * @brief */ //#define BLYNK_DEBUG #define BLYNK_PRINT stdout #ifdef RASPBERRY #include <BlynkApiWiringPi.h> #else #include <BlynkApiLinux.h> #endif #include <BlynkSocket.h> #include <BlynkOptionsParser.h> static BlynkTransportSocket _blynkTransport; BlynkSocket Blynk(_blynkTransport); static const char *auth, *serv; static uint16_t port; #include <BlynkWidgets.h> BlynkTimer tmr; BLYNK_WRITE(V1) { printf("Got a value: %s\n", param[0].asStr()); } void setup() { Blynk.begin(auth, serv, port); tmr.setInterval(1000, [](){ Blynk.virtualWrite(V0, BlynkMillis()/1000); }); } void loop() { Blynk.run(); tmr.run(); } int main(int argc, char* argv[]) { parse_options(argc, argv, auth, serv, port); setup(); while(true) { loop(); } return 0; }
Add heuristics for finding QObject::connect
#include "ConnectCallVisitor.h" bool ConnectCallVisitor::VisitCallExpr(clang::CallExpr *expr) { return true; }
#include <iostream> #include "ConnectCallVisitor.h" namespace { bool isQObjectConnect(clang::CallExpr *expr) { // These are needed a lot so keep them around static const clang::StringRef expectedMethodName("connect"); static const clang::StringRef expectedClassName("QObject"); const clang::Decl *calleeDecl = expr->getCalleeDecl(); // Assume this is a method const auto *methodDecl = clang::dyn_cast_or_null<clang::CXXMethodDecl>(calleeDecl); if (!methodDecl) { // Nope return false; } if (!methodDecl->isStatic()) { // XXX: We only handle the static version for now return false; } // Check the name of the class and methond if (methodDecl->getName() != expectedMethodName) { return false; } if (methodDecl->getParent()->getName() != expectedClassName) { return false; } return true; } } bool ConnectCallVisitor::VisitCallExpr(clang::CallExpr *expr) { if (!isQObjectConnect(expr)) { return true; } std::cout << "Found QObject::connect" << std::endl; return true; }
Use t(nu=2) instead of Cauchy
#include "RNG.h" #include "Utils.h" #include <cmath> namespace DNest4 { RNG::RNG() :uniform(0., 1.) ,normal(0., 1.) { } void RNG::set_seed(unsigned int seed) { twister.seed(seed); } double RNG::rand() { return uniform(twister); } double RNG::randn() { return normal(twister); } double RNG::randh() { return pow(10.0, 1.5 - 3*std::abs(tan(M_PI*(this->rand() - 0.5)))) *this->randn(); } int RNG::rand_int(int N) { return static_cast<int>(floor(N*this->rand())); } } // namespace DNest4
#include "RNG.h" #include "Utils.h" #include <cmath> namespace DNest4 { RNG::RNG() :uniform(0., 1.) ,normal(0., 1.) { } void RNG::set_seed(unsigned int seed) { twister.seed(seed); } double RNG::rand() { return uniform(twister); } double RNG::randn() { return normal(twister); } double RNG::randh() { // t-distribution with 2 degrees of freedom (less ridiculous than Cauchy) double T = this->randn()/ sqrt((pow(this->randn(), 2) + pow(this->randn(), 2))/2); return pow(10.0, 1.5 - 3*std::abs(T))*this->randn(); } int RNG::rand_int(int N) { return static_cast<int>(floor(N*this->rand())); } } // namespace DNest4
Set log level to Debug by default
#include "gameboy.h" #include "cartridge.h" #include "video/screen.h" #include "util/log.h" #include "video/screens/null_screen.h" #include "video/screens/sfml_screen.h" int main(int argc, char* argv[]) { log_set_level(LogLevel::Trace); if (argc < 2) { log_error("Please provide a ROM file to run") return 1; } bool should_debug = (argc == 3); if (should_debug) { log_info("Enabling debugger..."); } std::string rom_name = argv[1]; Cartridge cartridge(rom_name); SFMLScreen screen; Gameboy gameboy(screen, cartridge, should_debug); gameboy.run(); }
#include "gameboy.h" #include "cartridge.h" #include "video/screen.h" #include "util/log.h" #include "video/screens/null_screen.h" #include "video/screens/sfml_screen.h" int main(int argc, char* argv[]) { log_set_level(LogLevel::Debug); if (argc < 2) { log_error("Please provide a ROM file to run") return 1; } bool should_debug = (argc == 3); if (should_debug) { log_info("Enabling debugger..."); } std::string rom_name = argv[1]; Cartridge cartridge(rom_name); SFMLScreen screen; Gameboy gameboy(screen, cartridge, should_debug); gameboy.run(); }
Make test require 'linux' instead of 'linux2'
//===--------------------- cxa_thread_atexit_test.cpp ---------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // REQUIRES: linux2 #include <assert.h> #include <cxxabi.h> static bool AtexitImplCalled = false; extern "C" int __cxa_thread_atexit_impl(void (*dtor)(void *), void *obj, void *dso_symbol) { assert(dtor == reinterpret_cast<void (*)(void *)>(1)); assert(obj == reinterpret_cast<void *>(2)); assert(dso_symbol == reinterpret_cast<void *>(3)); AtexitImplCalled = true; return 4; } int main() { int RV = __cxxabiv1::__cxa_thread_atexit( reinterpret_cast<void (*)(void *)>(1), reinterpret_cast<void *>(2), reinterpret_cast<void *>(3)); assert(RV = 4); assert(AtexitImplCalled); return 0; }
//===--------------------- cxa_thread_atexit_test.cpp ---------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // REQUIRES: linux #include <assert.h> #include <cxxabi.h> static bool AtexitImplCalled = false; extern "C" int __cxa_thread_atexit_impl(void (*dtor)(void *), void *obj, void *dso_symbol) { assert(dtor == reinterpret_cast<void (*)(void *)>(1)); assert(obj == reinterpret_cast<void *>(2)); assert(dso_symbol == reinterpret_cast<void *>(3)); AtexitImplCalled = true; return 4; } int main() { int RV = __cxxabiv1::__cxa_thread_atexit( reinterpret_cast<void (*)(void *)>(1), reinterpret_cast<void *>(2), reinterpret_cast<void *>(3)); assert(RV = 4); assert(AtexitImplCalled); return 0; }
Add information about the keyfile "format".
#include "ihex.h" #include <stdlib.h> int main(int argc, char* argv[]) { if (argc != 4) { std::cerr << argv[0] << " input.hex keyfile output.hex\n" << "Encrypts or decrypts the data in an Intel Hex file.\n" << "Addresses are unchanged, but checksum is updated.\n"; exit(-1); } IntelHex file; file.Read(argv[1]); std::ifstream keyfile; keyfile.open(argv[2], std::ios::in | std::ios::binary | std::ios::ate); if(!keyfile.is_open()) { std::cerr << "Error reading keyfile.\n"; exit(-2); } keyfile.seekg(0, std::ios::end); int size = keyfile.tellg(); keyfile.seekg(0, std::ios::beg); uint8_t key[size]; keyfile.read((char*)key, size); file.Cipher(key, size); file.Write(argv[3]); }
#include "ihex.h" #include <stdlib.h> int main(int argc, char* argv[]) { if (argc != 4) { std::cerr << argv[0] << " input.hex keyfile output.hex\n" "Encrypts or decrypts the data in an Intel Hex file.\n" "Addresses are unchanged, but checksum is updated.\n\n" "The [keyfile] is a raw binary file with the key data. The whole file is\n" "used as key data, and can be of arbitrary size.\n" ; exit(-1); } IntelHex file; file.Read(argv[1]); std::ifstream keyfile; keyfile.open(argv[2], std::ios::in | std::ios::binary | std::ios::ate); if(!keyfile.is_open()) { std::cerr << "Error reading keyfile.\n"; exit(-2); } keyfile.seekg(0, std::ios::end); int size = keyfile.tellg(); keyfile.seekg(0, std::ios::beg); uint8_t key[size]; keyfile.read((char*)key, size); file.Cipher(key, size); file.Write(argv[3]); }
Update for new SliderWnd class
#include "VolumeSlider.h" #include "Skin.h" VolumeSlider::VolumeSlider(HINSTANCE hInstance, Settings &settings) : OSD(hInstance, L"3RVX-VolumeSlider", settings), _mWnd(hInstance, L"3RVX-VolumeSliderWnd", L"3RVX Volume Slider") { std::wstring skinXML = settings.SkinXML(); Skin skin(skinXML); long styles = GetWindowLongPtr(_mWnd.HWnd(), GWL_EXSTYLE); styles &= ~(WS_EX_NOACTIVATE | WS_EX_TRANSPARENT); SetWindowLongPtr(_mWnd.HWnd(), GWL_EXSTYLE, styles); Gdiplus::Bitmap *bg = skin.ControllerBgImg("volume"); _mWnd.BackgroundImage(bg); _mWnd.Update(); _mWnd.Show(); } void VolumeSlider::Hide() { _mWnd.Hide(false); }
#include "VolumeSlider.h" #include "Skin.h" VolumeSlider::VolumeSlider(HINSTANCE hInstance, Settings &settings) : OSD(hInstance, L"3RVX-VolumeSlider", settings), _sWnd(hInstance, L"3RVX-VolumeSliderWnd", L"3RVX Volume Slider") { std::wstring skinXML = settings.SkinXML(); Skin skin(skinXML); Gdiplus::Bitmap *bg = skin.ControllerBgImg("volume"); _sWnd.BackgroundImage(bg); _sWnd.Update(); _sWnd.Show(); } void VolumeSlider::Hide() { _sWnd.Hide(false); }
Make widget always fit the view
#include "mainwindow.h" #include "bucketlist.h" #include <QLabel> #include <QBoxLayout> #include <QtWebKit> #include <QSettings> #include <QInputDialog> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { QWidget *central = new QWidget; setCentralWidget(central); QBoxLayout *topLayout = new QHBoxLayout(central); BucketList *bucketList = new BucketList; topLayout->addWidget(bucketList); m_view = new QWebView; topLayout->addWidget(m_view); getServerPath(); connect(&m_server, SIGNAL(started()), SLOT(loadView())); m_server.start(); } MainWindow::~MainWindow() { m_server.stop(); } void MainWindow::getServerPath() { QSettings settings; QString path = settings.value("view/path").toString(); if (path.isEmpty()) { path = QInputDialog::getText(this, "View path", "Enter base path of view for web server"); } settings.setValue("view/path", path); m_server.setPath(path); } void MainWindow::loadView() { m_view->setUrl(QUrl("http://localhost:8765")); m_view->show(); }
#include "mainwindow.h" #include "bucketlist.h" #include <QLabel> #include <QBoxLayout> #include <QtWebKit> #include <QSettings> #include <QInputDialog> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { QWidget *central = new QWidget; setCentralWidget(central); QBoxLayout *topLayout = new QHBoxLayout(central); BucketList *bucketList = new BucketList; topLayout->addWidget(bucketList); m_view = new QWebView; topLayout->addWidget(m_view, 1); m_view->setMinimumSize(1000, 540); getServerPath(); connect(&m_server, SIGNAL(started()), SLOT(loadView())); m_server.start(); } MainWindow::~MainWindow() { m_server.stop(); } void MainWindow::getServerPath() { QSettings settings; QString path = settings.value("view/path").toString(); if (path.isEmpty()) { path = QInputDialog::getText(this, "View path", "Enter base path of view for web server"); } settings.setValue("view/path", path); m_server.setPath(path); } void MainWindow::loadView() { m_view->setUrl(QUrl("http://localhost:8765")); m_view->show(); }
Use the correct lsb key when fetching the CrOS device type.
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromeos/system/devicetype.h" #include <string> #include "base/sys_info.h" namespace chromeos { namespace { const char kDeviceType[] = "CHROMEOS_DEVICE_TYPE"; } DeviceType GetDeviceType() { std::string value; if (base::SysInfo::GetLsbReleaseValue(kDeviceType, &value)) { if (value == "CHROMEBASE") return DeviceType::kChromebase; else if (value == "CHROMEBIT") return DeviceType::kChromebit; // Most devices are Chromebooks, so we will also consider reference boards // as chromebooks. else if (value == "CHROMEBOOK" || value == "REFERENCE") return DeviceType::kChromebook; else if (value == "CHROMEBOX") return DeviceType::kChromebox; else LOG(ERROR) << "Unknown device type \"" << value << "\""; } return DeviceType::kUnknown; } } // namespace chromeos
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromeos/system/devicetype.h" #include <string> #include "base/sys_info.h" namespace chromeos { namespace { const char kDeviceType[] = "DEVICETYPE"; } DeviceType GetDeviceType() { std::string value; if (base::SysInfo::GetLsbReleaseValue(kDeviceType, &value)) { if (value == "CHROMEBASE") return DeviceType::kChromebase; else if (value == "CHROMEBIT") return DeviceType::kChromebit; // Most devices are Chromebooks, so we will also consider reference boards // as chromebooks. else if (value == "CHROMEBOOK" || value == "REFERENCE") return DeviceType::kChromebook; else if (value == "CHROMEBOX") return DeviceType::kChromebox; else LOG(ERROR) << "Unknown device type \"" << value << "\""; } return DeviceType::kUnknown; } } // namespace chromeos
Call it NSS_ShutdownAsync instead of shutdown3DS.
#include <3ds.h> #include <stdio.h> void shutdown3DS() { Handle nssHandle = 0; Result result = srvGetServiceHandle(&nssHandle, "ns:s"); if (result != 0) return; // http://3dbrew.org/wiki/NSS:ShutdownAsync u32 *commandBuffer = getThreadCommandBuffer(); commandBuffer[0] = 0x000E0000; svcSendSyncRequest(nssHandle); svcCloseHandle(nssHandle); } int main(int argc, char **argv) { shutdown3DS(); // Hack: the 3ds crashes ("An error has occcurred.") for some reason // without one iteration of the APT main loop. aptMainLoop(); return 0; }
#include <3ds.h> #include <stdio.h> // http://3dbrew.org/wiki/NSS:ShutdownAsync void NSS_ShutdownAsync(void) { Handle nssHandle = 0; Result result = srvGetServiceHandle(&nssHandle, "ns:s"); if (result != 0) return; u32 *commandBuffer = getThreadCommandBuffer(); commandBuffer[0] = 0x000E0000; svcSendSyncRequest(nssHandle); svcCloseHandle(nssHandle); } int main(int argc, char **argv) { NSS_ShutdownAsync(); // Hack: the 3ds crashes ("An error has occcurred.") for some reason // without one iteration of the APT main loop. aptMainLoop(); return 0; }
Correct buffer overflow in match(...)
#include "Name.h" bool Name::init(String name) { size = name.length() + 1; data = (uint8_t *) malloc(size); if (data != NULL) { uint8_t lastDot = size; for (uint8_t i = size - 1; i > 0; i--) { uint8_t c = name.charAt(i - 1); if (c == '.') { data[i] = lastDot - i - 1; lastDot = i; } else { data[i] = c; } } data[0] = lastDot - 1; } return data != NULL; } uint8_t Name::getSize() { return size; } bool Name::match(uint8_t c) { matches &= data[matchOffset++] = c; return matches; } void Name::write(Buffer buffer) { if (writtenOffset == 0) { writtenOffset = buffer.getOffset(); for (int i = 0; i < size; i++) { buffer.writeUInt8(data[i]); } } else { buffer.writeUInt16((BACK_REF << 8) | writtenOffset); } } void Name::reset() { matches = true; matchOffset = 0; writtenOffset = 0; }
#include "Name.h" bool Name::init(String name) { size = name.length() + 1; data = (uint8_t *) malloc(size); if (data != NULL) { uint8_t lastDot = size; for (uint8_t i = size - 1; i > 0; i--) { uint8_t c = name.charAt(i - 1); if (c == '.') { data[i] = lastDot - i - 1; lastDot = i; } else { data[i] = c; } } data[0] = lastDot - 1; } return data != NULL; } uint8_t Name::getSize() { return size; } bool Name::match(uint8_t c) { matches = matches && matchOffset < size && data[matchOffset++] == c; return matches; } void Name::write(Buffer buffer) { if (writtenOffset == 0) { writtenOffset = buffer.getOffset(); for (int i = 0; i < size; i++) { buffer.writeUInt8(data[i]); } } else { buffer.writeUInt16((BACK_REF << 8) | writtenOffset); } } void Name::reset() { matches = true; matchOffset = 0; writtenOffset = 0; }
Remove duplicated call to std::cos
#include "./Sphere.hpp" #include "./misc.hpp" #include <algorithm> #include <cmath> namespace yks { Optional<float> intersect(const vec3& origin, float radius, const Ray& r) { const vec3 o = r.origin - origin; const vec3 v = r.direction; float t1, t2; const int solutions = solve_quadratic(dot(v, v), 2*dot(o, v), dot(o, o) - radius*radius, t1, t2); if (solutions == 0) { return Optional<float>(); } else if (solutions == 1) { return make_optional<float>(t1); } else { return make_optional<float>(std::min(t1, t2)); } } vec3 uniform_point_on_sphere(float a, float b) { const float y = 2.0f * a - 1.0f; const float latitude = std::asin(y); const float longitude = b * two_pi; return mvec3(cos(latitude) * cos(longitude), y, cos(latitude) * sin(longitude)); } }
#include "./Sphere.hpp" #include "./misc.hpp" #include <algorithm> #include <cmath> namespace yks { Optional<float> intersect(const vec3& origin, float radius, const Ray& r) { const vec3 o = r.origin - origin; const vec3 v = r.direction; float t1, t2; const int solutions = solve_quadratic(dot(v, v), 2*dot(o, v), dot(o, o) - radius*radius, t1, t2); if (solutions == 0) { return Optional<float>(); } else if (solutions == 1) { return make_optional<float>(t1); } else { return make_optional<float>(std::min(t1, t2)); } } vec3 uniform_point_on_sphere(float a, float b) { const float y = 2.0f * a - 1.0f; const float latitude = std::asin(y); const float longitude = b * two_pi; const float cos_latitude = std::cos(latitude); return mvec3(cos_latitude * cos(longitude), y, cos_latitude * sin(longitude)); } }
Add a test for -Warc-abi as requested by Fariborz.
// RUN: %clang -### -Wlarge-by-value-copy %s 2>&1 | FileCheck -check-prefix=LARGE_VALUE_COPY_DEFAULT %s // LARGE_VALUE_COPY_DEFAULT: -Wlarge-by-value-copy=64 // RUN: %clang -### -Wlarge-by-value-copy=128 %s 2>&1 | FileCheck -check-prefix=LARGE_VALUE_COPY_JOINED %s // LARGE_VALUE_COPY_JOINED: -Wlarge-by-value-copy=128 // RUN: %clang -### -c -Wmonkey -Wno-monkey -Wno-unused-command-line-arguments \ // RUN: -Wno-unused-command-line-argument %s 2>&1 | FileCheck %s // CHECK: unknown warning option '-Wmonkey' // CHECK: unknown warning option '-Wno-monkey' // CHECK: unknown warning option '-Wno-unused-command-line-arguments'; did you mean '-Wno-unused-command-line-argument'?
// RUN: %clang -### -Wlarge-by-value-copy %s 2>&1 | FileCheck -check-prefix=LARGE_VALUE_COPY_DEFAULT %s // LARGE_VALUE_COPY_DEFAULT: -Wlarge-by-value-copy=64 // RUN: %clang -### -Wlarge-by-value-copy=128 %s 2>&1 | FileCheck -check-prefix=LARGE_VALUE_COPY_JOINED %s // LARGE_VALUE_COPY_JOINED: -Wlarge-by-value-copy=128 // RUN: %clang -### -c -Wmonkey -Wno-monkey -Wno-unused-command-line-arguments \ // RUN: -Wno-unused-command-line-argument %s 2>&1 | FileCheck %s // CHECK: unknown warning option '-Wmonkey' // CHECK: unknown warning option '-Wno-monkey' // CHECK: unknown warning option '-Wno-unused-command-line-arguments'; did you mean '-Wno-unused-command-line-argument'? // FIXME: Remove this together with -Warc-abi once an Xcode is released that doesn't pass this flag. // RUN: %clang -### -Warc-abi -Wno-arc-abi %s 2>&1 | FileCheck -check-prefix=ARCABI %s // ARCABI-NOT: unknown warning option '-Warc-abi' // ARCABI-NOT: unknown warning option '-Wno-arc-abi'
Expand on why we need a fake, here.
#include "rdb_protocol/configured_limits.hpp" #include "rdb_protocol/wire_func.hpp" #include "rdb_protocol/func.hpp" namespace ql { configured_limits_t from_optargs(const std::map<std::string, wire_func_t> &arguments) { auto p = arguments.find("arrayLimit"); if (p != arguments.end()) { // Fake an environment with no arguments. cond_t cond; rdb_context_t context; // Can't use the original arguments, because it will cause an infinite loop. env_t env(&context, &cond, std::map<std::string, wire_func_t>(), profile_bool_t::DONT_PROFILE); return configured_limits_t((*p).second.compile_wire_func()->call(&env)->as_int()); } else { return configured_limits_t(); } } } // namespace ql
#include "rdb_protocol/configured_limits.hpp" #include "rdb_protocol/wire_func.hpp" #include "rdb_protocol/func.hpp" namespace ql { configured_limits_t from_optargs(const std::map<std::string, wire_func_t> &arguments) { auto p = arguments.find("arrayLimit"); if (p != arguments.end()) { // 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. cond_t cond; rdb_context_t context; env_t env(&context, &cond, std::map<std::string, wire_func_t>(), profile_bool_t::DONT_PROFILE); return configured_limits_t((*p).second.compile_wire_func()->call(&env)->as_int()); } else { return configured_limits_t(); } } } // namespace ql
Add a little paranoia for testing purposes.
//===---------------------------- temporary.cpp ---------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #pragma GCC visibility push(default) extern "C" { void (*__cxa_new_handler)() = 0; void (*__cxa_terminate_handler)() = 0; void (*__cxa_unexpected_handler)() = 0; } #pragma GCC visibility pop
//===---------------------------- temporary.cpp ---------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "abort_message.h" #pragma GCC visibility push(default) extern "C" { static void f() { abort_message("this shouldn't be called"); } void (*__cxa_new_handler)() = f; void (*__cxa_terminate_handler)() = f; void (*__cxa_unexpected_handler)() = f; } #pragma GCC visibility pop
Add a throw-away parameter for task start to remove warning
/* * main.cpp * * Copyright (C) 2018 [ A Legge Up ] * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ #include <stdio.h> #include "HardwareConfig.h" #include "AnimationTask.h" extern "C" void app_main() { HardwareConfig hardwareConfig(HardwareConfig::DEV0); AnimationTask *pAnimationTask = new AnimationTask("AnimationTask"); pAnimationTask->start(); }
/* * main.cpp * * Copyright (C) 2018 [ A Legge Up ] * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ #include <stdio.h> #include "HardwareConfig.h" #include "AnimationTask.h" extern "C" void app_main() { HardwareConfig hardwareConfig(HardwareConfig::DEV0); AnimationTask *pAnimationTask = new AnimationTask("AnimationTask"); pAnimationTask->start(0); }
Mark RssItem tests with appropriate tag
#include "rssitem.h" #include "3rd-party/catch.hpp" #include "cache.h" #include "configcontainer.h" using namespace newsboat; TEST_CASE("RssItem::sort_flags() cleans up flags", "[rss]") { ConfigContainer cfg; Cache rsscache(":memory:", &cfg); RssItem item(&rsscache); SECTION("Repeated letters do not erase other letters") { std::string inputflags = "Abcdecf"; std::string result = "Abcdef"; item.set_flags(inputflags); REQUIRE(result == item.flags()); } SECTION("Non alpha characters in input flags are ignored") { std::string inputflags = "Abcd"; item.set_flags(inputflags + "1234568790^\"#'é(£"); REQUIRE(inputflags == item.flags()); } }
#include "rssitem.h" #include "3rd-party/catch.hpp" #include "cache.h" #include "configcontainer.h" using namespace newsboat; TEST_CASE("RssItem::sort_flags() cleans up flags", "[RssItem]") { ConfigContainer cfg; Cache rsscache(":memory:", &cfg); RssItem item(&rsscache); SECTION("Repeated letters do not erase other letters") { std::string inputflags = "Abcdecf"; std::string result = "Abcdef"; item.set_flags(inputflags); REQUIRE(result == item.flags()); } SECTION("Non alpha characters in input flags are ignored") { std::string inputflags = "Abcd"; item.set_flags(inputflags + "1234568790^\"#'é(£"); REQUIRE(inputflags == item.flags()); } }
Use constant delta time when in measure mode
#include "Renderer.hpp" #include "Window.hpp" #include <cstring> #include <iostream> #include "Particle.png.hpp" int main(int argc, char* argv[]) { Window window; bool measure = false; if (argc > 1 && strcmp(argv[1], "measure") == 0) { std::cout << "Measuring..." << std::endl; measure = true; } Renderer* renderer = new Renderer(window); renderer->setTexture(PARTICLE_PNG, PARTICLE_PNG_LENGTH); double lastTime = glfwGetTime(); while(!glfwWindowShouldClose(window.getWindow())){ glfwPollEvents(); double deltaTime = glfwGetTime() - lastTime; lastTime = glfwGetTime(); renderer->update(deltaTime); renderer->render(); glfwSwapBuffers(window.getWindow()); } delete renderer; return 0; }
#include "Renderer.hpp" #include "Window.hpp" #include <cstring> #include <iostream> #include "Particle.png.hpp" int main(int argc, char* argv[]) { Window window; bool measure = false; if (argc > 1 && strcmp(argv[1], "measure") == 0) { std::cout << "Measuring..." << std::endl; measure = true; } Renderer* renderer = new Renderer(window); renderer->setTexture(PARTICLE_PNG, PARTICLE_PNG_LENGTH); double lastTime = glfwGetTime(); while(!glfwWindowShouldClose(window.getWindow())){ glfwPollEvents(); double deltaTime = glfwGetTime() - lastTime; lastTime = glfwGetTime(); renderer->update(measure ? 1.0/60.0 : deltaTime); renderer->render(); glfwSwapBuffers(window.getWindow()); } delete renderer; return 0; }
Add missing header in a test.
// If user provides his own libc functions, ASan doesn't // intercept these functions. // RUN: %clangxx_asan -O0 %s -o %t && %run %t 2>&1 | FileCheck %s // RUN: %clangxx_asan -O1 %s -o %t && %run %t 2>&1 | FileCheck %s // RUN: %clangxx_asan -O2 %s -o %t && %run %t 2>&1 | FileCheck %s // RUN: %clangxx_asan -O3 %s -o %t && %run %t 2>&1 | FileCheck %s // XFAIL: freebsd // On Windows, defining strtoll in a static build results in linker errors, but // it works with the dynamic runtime. // XFAIL: win32-static-asan #include <stdlib.h> #include <stdio.h> extern "C" long strtol(const char *nptr, char **endptr, int base) { fprintf(stderr, "my_strtol_interceptor\n"); if (endptr) *endptr = (char*)nptr + strlen(nptr); return 0; } int main() { char *x = (char*)malloc(10 * sizeof(char)); free(x); return (int)strtol(x, 0, 10); // CHECK: my_strtol_interceptor // CHECK-NOT: heap-use-after-free }
// If user provides his own libc functions, ASan doesn't // intercept these functions. // RUN: %clangxx_asan -O0 %s -o %t && %run %t 2>&1 | FileCheck %s // RUN: %clangxx_asan -O1 %s -o %t && %run %t 2>&1 | FileCheck %s // RUN: %clangxx_asan -O2 %s -o %t && %run %t 2>&1 | FileCheck %s // RUN: %clangxx_asan -O3 %s -o %t && %run %t 2>&1 | FileCheck %s // XFAIL: freebsd // On Windows, defining strtoll in a static build results in linker errors, but // it works with the dynamic runtime. // XFAIL: win32-static-asan #include <stdlib.h> #include <stdio.h> #include <string.h> extern "C" long strtol(const char *nptr, char **endptr, int base) { fprintf(stderr, "my_strtol_interceptor\n"); if (endptr) *endptr = (char*)nptr + strlen(nptr); return 0; } int main() { char *x = (char*)malloc(10 * sizeof(char)); free(x); return (int)strtol(x, 0, 10); // CHECK: my_strtol_interceptor // CHECK-NOT: heap-use-after-free }
Fix breaking tests when sequencer can not be opened
#include "iomidi.h" #include "db.h" #include <QtTest> class TestIOMIdi : public QObject { Q_OBJECT private slots: void test_handle(); void test_clientId(); void test_portId(); private: IOMidi io; }; void TestIOMIdi::test_handle() { snd_seq_t* seq = io.handle(); QVERIFY(seq); snd_seq_client_info_t *info; snd_seq_client_info_alloca(&info); QCOMPARE(snd_seq_get_client_info(seq, info), 0); QVERIFY(!QString(snd_seq_client_info_get_name(info)).isNull()); } void TestIOMIdi::test_clientId() { QVERIFY(io.clientId() > 0); } void TestIOMIdi::test_portId() { QVERIFY(io.clientId() > 0); } QTEST_APPLESS_MAIN(TestIOMIdi) #include "tst_iomidi.moc"
#include "iomidi.h" #include "db.h" #include <QtTest> class TestIOMIdi : public QObject { Q_OBJECT private slots: void initTestCase(); void test_handle(); void test_clientId(); void test_portId(); private: IOMidi* io; }; void TestIOMIdi::initTestCase() { io = nullptr; try { io = new IOMidi(this); } catch (const std::exception&) { } } void TestIOMIdi::test_handle() { if (!io) { return; } snd_seq_t* seq = io->handle(); QVERIFY(seq); snd_seq_client_info_t *info; snd_seq_client_info_alloca(&info); QCOMPARE(snd_seq_get_client_info(seq, info), 0); QVERIFY(!QString(snd_seq_client_info_get_name(info)).isNull()); } void TestIOMIdi::test_clientId() { if (!io) { return; } QVERIFY(io->clientId() > 0); } void TestIOMIdi::test_portId() { if (!io) { return; } QVERIFY(io->clientId() > 0); } QTEST_APPLESS_MAIN(TestIOMIdi) #include "tst_iomidi.moc"
Create node once in ign_nodes_examples_client
#include <iostream> #include "ignition/transport.hh" #include "fcmt/ign_nodes/examples/proto/echo.pb.h" int main(int argc, char *argv[]) { auto i = 0; while (true) { ignition::transport::Node node; fcmt::ign_nodes::examples::proto::EchoRequest request; request.set_value(i++); fcmt::ign_nodes::examples::proto::EchoReply reply; bool result = false; auto timeout = 5000; auto executed = node.Request("/echo", request, timeout, reply, result); if (executed) { if (result) { std::cout << "Reply: [" << reply.value() << "]" << std::endl; } else { std::cout << "Service call failed" << std::endl; } } else { std::cerr << "Service call timed out" << std::endl; } } }
#include <iostream> #include "ignition/transport.hh" #include "fcmt/ign_nodes/examples/proto/echo.pb.h" int main(int argc, char *argv[]) { auto i = 0; ignition::transport::Node node; while (true) { fcmt::ign_nodes::examples::proto::EchoRequest request; request.set_value(i++); fcmt::ign_nodes::examples::proto::EchoReply reply; bool result = false; auto timeout = 5000; auto executed = node.Request("/echo", request, timeout, reply, result); if (executed) { if (result) { std::cout << "Reply: [" << reply.value() << "]" << std::endl; } else { std::cout << "Service call failed" << std::endl; } } else { std::cerr << "Service call timed out" << std::endl; } } }
Add a catch for std::length_error for the case where the string can't handle 2GB. (like say 32-bit big-endian)
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // <streambuf> // template <class charT, class traits = char_traits<charT> > // class basic_streambuf; // void pbump(int n); // // REQUIRES: long_tests #include <sstream> #include <cassert> #include "test_macros.h" struct SB : std::stringbuf { SB() : std::stringbuf(std::ios::ate|std::ios::out) { } const char* pubpbase() const { return pbase(); } const char* pubpptr() const { return pptr(); } }; int main() { #ifndef TEST_HAS_NO_EXCEPTIONS try { #endif std::string str(2147483648, 'a'); SB sb; sb.str(str); assert(sb.pubpbase() <= sb.pubpptr()); #ifndef TEST_HAS_NO_EXCEPTIONS } catch (const std::bad_alloc &) {} #endif }
//===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // <streambuf> // template <class charT, class traits = char_traits<charT> > // class basic_streambuf; // void pbump(int n); // // REQUIRES: long_tests #include <sstream> #include <cassert> #include "test_macros.h" struct SB : std::stringbuf { SB() : std::stringbuf(std::ios::ate|std::ios::out) { } const char* pubpbase() const { return pbase(); } const char* pubpptr() const { return pptr(); } }; int main() { #ifndef TEST_HAS_NO_EXCEPTIONS try { #endif std::string str(2147483648, 'a'); SB sb; sb.str(str); assert(sb.pubpbase() <= sb.pubpptr()); #ifndef TEST_HAS_NO_EXCEPTIONS } catch (const std::length_error &) {} // maybe the string can't take 2GB catch (const std::bad_alloc &) {} // maybe we don't have enough RAM #endif }
Add code to catch NSAMPS size wraparound.
/* RTcmix - Copyright (C) 2000 The RTcmix Development Team See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for the license to this software and for a DISCLAIMER OF ALL WARRANTIES. */ #include <RTcmix.h> #include <Instrument.h> #include <ugens.h> int Instrument::rtsetoutput(float start, float dur, Instrument *theInst) { // DS: Adding check to be sure rtoutput() did not fail. if (!RTcmix::outputOpen()) { die(theInst->name(), "rtsetoutput: No output open for this instrument (rtoutput failed?)!"); return -1; } if (start < 0.0f) { die(theInst->name(), "rtsetoutput: start time must be >= 0.0"); return -1; } if (dur < 0.0f) { die(theInst->name(), "rtsetoutput: duration must be >= 0.0"); return -1; } theInst->_start = start; theInst->_dur = dur; theInst->_nsamps = (int)(0.5 + dur * RTcmix::sr()); return 0; }
/* RTcmix - Copyright (C) 2000 The RTcmix Development Team See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for the license to this software and for a DISCLAIMER OF ALL WARRANTIES. */ #include <RTcmix.h> #include <Instrument.h> #include <ugens.h> int Instrument::rtsetoutput(float start, float dur, Instrument *theInst) { // DS: Adding check to be sure rtoutput() did not fail. if (!RTcmix::outputOpen()) { die(theInst->name(), "rtsetoutput: No output open for this instrument (rtoutput failed?)!"); return -1; } if (start < 0.0f) { die(theInst->name(), "rtsetoutput: start time must be >= 0.0"); return -1; } if (dur < 0.0f) { die(theInst->name(), "rtsetoutput: duration must be >= 0.0"); return -1; } theInst->_start = start; theInst->_dur = dur; theInst->_nsamps = (int)(0.5 + dur * RTcmix::sr()); if (theInst->_nsamps < 0) { rtcmix_warn(theInst->name(), "rtsetoutput: sample count exceeds MAXINT - limiting"); theInst->_nsamps = INT_MAX; } return 0; }
Set local to C. Maybe not the best longterm solution.
#include "mainwindow.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }
#include "mainwindow.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); std::locale::global( std::locale( "C" ) ); MainWindow w; w.show(); return a.exec(); }
Fix test suppressed in r166683 on 32-bit Linux
// RUN: %clang_cc1 %s -g -S -emit-llvm -o - | FileCheck %s // FIXME: Failing on i686. // XFAIL: * // RUN: %clang_cc1 -triple i686-linux %s -g -S -emit-llvm -o - | FileCheck %s struct A { virtual void f(); }; struct B { virtual void f(); }; struct C : A, B { virtual void f(); }; void C::f() { } // CHECK: [ DW_TAG_subprogram ] [line 15] [def] [_ZThn8_N1C1fEv]
// RUN: %clang_cc1 %s -g -S -emit-llvm -o - | FileCheck %s struct A { virtual void f(); }; struct B { virtual void f(); }; struct C : A, B { virtual void f(); }; void C::f() { } // CHECK: [ DW_TAG_subprogram ] [line 15] [def] [_ZThn{{4|8}}_N1C1fEv]
Revert r302476 "Update testcase for upstream LLVM changes."
// RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm -debug-info-kind=line-tables-only %s -o - | FileCheck %s // Crasher for PR22929. class Base { virtual void VariadicFunction(...); }; class Derived : public virtual Base { virtual void VariadicFunction(...); }; void Derived::VariadicFunction(...) { } // CHECK: define void @_ZN7Derived16VariadicFunctionEz({{.*}} !dbg ![[SP:[0-9]+]] // CHECK: ret void, !dbg ![[LOC:[0-9]+]] // CHECK: define void @_ZT{{.+}}N7Derived16VariadicFunctionEz({{.*}} !dbg ![[SP_I:[0-9]+]] // CHECK: ret void, !dbg ![[LOC_I:[0-9]+]] // // CHECK: ![[SP]] = distinct !DISubprogram(name: "VariadicFunction" // CHECK: ![[LOC]] = !DILocation({{.*}}scope: ![[SP]]) // CHECK: ![[SP_I]] = distinct !DISubprogram(name: "VariadicFunction" // CHECK: ![[LOC_I]] = !DILocation({{.*}}scope: ![[SP_I]])
// RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm -debug-info-kind=line-tables-only %s -o - | FileCheck %s // Crasher for PR22929. class Base { virtual void VariadicFunction(...); }; class Derived : public virtual Base { virtual void VariadicFunction(...); }; void Derived::VariadicFunction(...) { } // CHECK: define void @_ZN7Derived16VariadicFunctionEz({{.*}} !dbg ![[SP:[0-9]+]] // CHECK: ret void, !dbg ![[LOC:[0-9]+]] // CHECK-LABEL: define void @_ZT{{.+}}N7Derived16VariadicFunctionEz( // CHECK: ret void, !dbg ![[LOC:[0-9]+]] // // CHECK: ![[SP]] = distinct !DISubprogram(name: "VariadicFunction" // CHECK: ![[LOC]] = !DILocation({{.*}}scope: ![[SP]])
Include header file instead of cpp
#include "dota2api/gamemode.cpp" #include "gtest/gtest.h" TEST(GameMode, gameModeFromInt) { EXPECT_EQ ( dota2::GameMode::Unknown, dota2::gameModeFromInt(-1) ); for(const auto &mode : dota2::gameModes) { EXPECT_EQ ( mode.second, dota2::gameModeFromInt(mode.first) ); } }
#include "dota2api/gamemode.hpp" #include "gtest/gtest.h" TEST(GameMode, gameModeFromInt) { EXPECT_EQ ( dota2::GameMode::Unknown, dota2::gameModeFromInt(-1) ); for(const auto &mode : dota2::gameModes) { EXPECT_EQ ( mode.second, dota2::gameModeFromInt(mode.first) ); } }
Fix bug where we were using a KCodeSet** as a KCodeSet* in codeset finding
#include "kobjects.h" #include "constants.h" #define PAGE_SIZE 0x1000 KCodeSet* FindTitleCodeSet(u64 title_id) { for (unsigned kproc_index = 0; kproc_index < kproc_num; kproc_index++) { KCodeSet* curr_codeset = (KCodeSet*)(kproc_start + kproc_size * kproc_index + kproc_codeset_offset); if (curr_codeset != nullptr && curr_codeset->title_id == title_id) return curr_codeset; } return nullptr; } u32 FindCodeOffsetKAddr(KCodeSet* code_set, u32 code_offset) { u32 curr_offset = 0; if (code_set == nullptr) return 0; KLinkedListNode* node = code_set->text_info.first_node; // Iterate through all the blocks in the codeset do { KBlockInfo* block_info = (KBlockInfo*)node->data; u32 block_size = block_info->page_count * PAGE_SIZE; // The code offset is within this block if (code_offset > curr_offset && code_offset < curr_offset + block_size) return block_info->mem_section_start + (code_offset - curr_offset); // Current offset: amount of bytes searched so far curr_offset += block_size; node = node->next; } while (node->next != nullptr); return 0; }
#include "kobjects.h" #include "constants.h" #define PAGE_SIZE 0x1000 KCodeSet* FindTitleCodeSet(u64 title_id) { for (unsigned kproc_index = 0; kproc_index < kproc_num; kproc_index++) { KCodeSet* curr_codeset = *(KCodeSet**)(kproc_start + kproc_size * kproc_index + kproc_codeset_offset); if (curr_codeset != nullptr && curr_codeset->title_id == title_id) return curr_codeset; } return nullptr; } u32 FindCodeOffsetKAddr(KCodeSet* code_set, u32 code_offset) { u32 curr_offset = 0; if (code_set == nullptr) return 0; KLinkedListNode* node = code_set->text_info.first_node; // Iterate through all the blocks in the codeset do { KBlockInfo* block_info = (KBlockInfo*)node->data; u32 block_size = block_info->page_count * PAGE_SIZE; // The code offset is within this block if (code_offset > curr_offset && code_offset < curr_offset + block_size) return block_info->mem_section_start + (code_offset - curr_offset); // Current offset: amount of bytes searched so far curr_offset += block_size; node = node->next; } while (node->next != nullptr); return 0; }
Add missing lazy instance initializer
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/public/test/layouttest_support.h" #include "base/callback.h" #include "base/lazy_instance.h" #include "content/renderer/render_view_impl.h" #include "third_party/WebKit/Tools/DumpRenderTree/chromium/TestRunner/public/WebTestProxy.h" using WebTestRunner::WebTestProxy; using WebTestRunner::WebTestProxyBase; namespace content { namespace { base::LazyInstance<base::Callback<void(RenderView*, WebTestProxyBase*)> >::Leaky g_callback; RenderViewImpl* CreateWebTestProxy(RenderViewImplParams* params) { typedef WebTestProxy<RenderViewImpl, RenderViewImplParams*> ProxyType; ProxyType* render_view_proxy = new ProxyType( reinterpret_cast<RenderViewImplParams*>(params)); if (g_callback == 0) return render_view_proxy; g_callback.Get().Run( static_cast<RenderView*>(render_view_proxy), render_view_proxy); return render_view_proxy; } } // namespace void EnableWebTestProxyCreation( const base::Callback<void(RenderView*, WebTestProxyBase*)>& callback) { g_callback.Get() = callback; RenderViewImpl::InstallCreateHook(CreateWebTestProxy); } } // namespace content
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/public/test/layouttest_support.h" #include "base/callback.h" #include "base/lazy_instance.h" #include "content/renderer/render_view_impl.h" #include "third_party/WebKit/Tools/DumpRenderTree/chromium/TestRunner/public/WebTestProxy.h" using WebTestRunner::WebTestProxy; using WebTestRunner::WebTestProxyBase; namespace content { namespace { base::LazyInstance<base::Callback<void(RenderView*, WebTestProxyBase*)> >::Leaky g_callback = LAZY_INSTANCE_INITIALIZER; RenderViewImpl* CreateWebTestProxy(RenderViewImplParams* params) { typedef WebTestProxy<RenderViewImpl, RenderViewImplParams*> ProxyType; ProxyType* render_view_proxy = new ProxyType( reinterpret_cast<RenderViewImplParams*>(params)); if (g_callback == 0) return render_view_proxy; g_callback.Get().Run( static_cast<RenderView*>(render_view_proxy), render_view_proxy); return render_view_proxy; } } // namespace void EnableWebTestProxyCreation( const base::Callback<void(RenderView*, WebTestProxyBase*)>& callback) { g_callback.Get() = callback; RenderViewImpl::InstallCreateHook(CreateWebTestProxy); } } // namespace content
Fix DeleteCache on POSIX. It wasn't successfully deleting before.
// 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 "net/disk_cache/cache_util.h" #include "base/file_util.h" #include "base/logging.h" #include "base/string_util.h" namespace disk_cache { bool MoveCache(const std::wstring& from_path, const std::wstring& to_path) { // Just use the version from base. return file_util::Move(from_path.c_str(), to_path.c_str()); } void DeleteCache(const std::wstring& path, bool remove_folder) { if (remove_folder) { file_util::Delete(path, false); } else { std::wstring name(path); // TODO(rvargas): Fix this after file_util::delete is fixed. // file_util::AppendToPath(&name, L"*"); file_util::Delete(name, true); } } bool DeleteCacheFile(const std::wstring& name) { return file_util::Delete(name, false); } void WaitForPendingIO(int* num_pending_io) { if (*num_pending_io) { NOTIMPLEMENTED(); } } } // namespace disk_cache
// 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 "net/disk_cache/cache_util.h" #include "base/file_util.h" #include "base/logging.h" #include "base/string_util.h" namespace disk_cache { bool MoveCache(const std::wstring& from_path, const std::wstring& to_path) { // Just use the version from base. return file_util::Move(from_path.c_str(), to_path.c_str()); } void DeleteCache(const std::wstring& path, bool remove_folder) { file_util::FileEnumerator iter(path, /* recursive */ false, file_util::FileEnumerator::FILES); for (std::wstring file = iter.Next(); !file.empty(); file = iter.Next()) { if (!file_util::Delete(file, /* recursive */ false)) NOTREACHED(); } if (remove_folder) { if (!file_util::Delete(path, /* recursive */ false)) NOTREACHED(); } } bool DeleteCacheFile(const std::wstring& name) { return file_util::Delete(name, false); } void WaitForPendingIO(int* num_pending_io) { if (*num_pending_io) { NOTIMPLEMENTED(); } } } // namespace disk_cache
Stop printing stack trace noise
#include "exceptions.hpp" #include <nan.h> #include <gfcpp/GemfireCppCache.hpp> #include <sstream> void ThrowGemfireException(const gemfire::Exception & e) { std::stringstream errorMessageStream; errorMessageStream << e.getName() << ": " << e.getMessage(); e.printStackTrace(); NanThrowError(errorMessageStream.str().c_str()); }
#include "exceptions.hpp" #include <nan.h> #include <gfcpp/GemfireCppCache.hpp> #include <sstream> void ThrowGemfireException(const gemfire::Exception & e) { std::stringstream errorMessageStream; errorMessageStream << e.getName() << ": " << e.getMessage(); NanThrowError(errorMessageStream.str().c_str()); }
Revert r7595 due to housekeeper warning-as-error.
/* * 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 "GrTypes.h" #include "SkThread.h" // for sk_atomic_inc // This used to be a global scope, but we got a warning about unused variable // so we moved it into here. We just want it to compile, so we can test the // static asserts. static inline void dummy_function_to_avoid_unused_var_warning() { static const GrCacheID::Key kAssertKey; GR_STATIC_ASSERT(sizeof(kAssertKey.fData8) == sizeof(kAssertKey.fData32)); GR_STATIC_ASSERT(sizeof(kAssertKey.fData8) == sizeof(kAssertKey.fData64)); GR_STATIC_ASSERT(sizeof(kAssertKey.fData8) == sizeof(kAssertKey)); } GrCacheID::Domain GrCacheID::GenerateDomain() { static int32_t gNextDomain = kInvalid_Domain + 1; int32_t domain = sk_atomic_inc(&gNextDomain); if (domain >= 1 << (8 * sizeof(Domain))) { GrCrash("Too many Cache Domains"); } return static_cast<Domain>(domain); }
/* * 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 "GrTypes.h" #include "SkThread.h" // for sk_atomic_inc // Well, the dummy_ "fix" caused a warning on windows, so hiding all of it // until we can find a universal fix. #if 0 // This used to be a global scope, but we got a warning about unused variable // so we moved it into here. We just want it to compile, so we can test the // static asserts. static inline void dummy_function_to_avoid_unused_var_warning() { GrCacheID::Key kAssertKey; GR_STATIC_ASSERT(sizeof(kAssertKey.fData8) == sizeof(kAssertKey.fData32)); GR_STATIC_ASSERT(sizeof(kAssertKey.fData8) == sizeof(kAssertKey.fData64)); GR_STATIC_ASSERT(sizeof(kAssertKey.fData8) == sizeof(kAssertKey)); } #endif GrCacheID::Domain GrCacheID::GenerateDomain() { static int32_t gNextDomain = kInvalid_Domain + 1; int32_t domain = sk_atomic_inc(&gNextDomain); if (domain >= 1 << (8 * sizeof(Domain))) { GrCrash("Too many Cache Domains"); } return static_cast<Domain>(domain); }