Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Fix response stream writes where we have a buffer offset
#include "response_stream.h" void rs::httpserver::ResponseStream::Flush() { socket_->Flush(); } int rs::httpserver::ResponseStream::Write(const Stream::byte* buffer, int offset, int count) { auto written = 0; while (written < count) { auto sentBytes = socket_->Send(buffer + written, count - written); if (sentBytes <= 0) { throw SocketWriteException(); } written += sentBytes; position_ += sentBytes; length_ += sentBytes; } return written; }
#include "response_stream.h" void rs::httpserver::ResponseStream::Flush() { socket_->Flush(); } int rs::httpserver::ResponseStream::Write(const Stream::byte* buffer, int offset, int count) { auto written = 0; while (written < count) { auto sentBytes = socket_->Send(buffer + offset + written, count - written); if (sentBytes <= 0) { throw SocketWriteException(); } written += sentBytes; position_ += sentBytes; length_ += sentBytes; } return written; }
Simplify LightingFilter in add-free case am: 0698300cc5 am: a184d5e49d am: 7e02270397
/* * 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); }
Fix a typo that broke the posix build.
// 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 "base/thread_local.h" #include <pthread.h> #include "base/logging.h" namespace base { // static void ThreadLocalPlatform::AllocateSlot(SlotType& slot) { int error = pthread_key_create(&slot, NULL); CHECK(error == 0); } // static void ThreadLocalPlatform::FreeSlot(SlotType& slot) { int error = pthread_key_delete(slot); DCHECK(error == 0); } // static void* ThreadLocalPlatform::GetValueFromSlot(SlotType& slot) { return pthread_getspecific(slot_); } // static void ThreadLocalPlatform::SetValueInSlot(SlotType& slot, void* value) { int error = pthread_setspecific(slot, value); CHECK(error == 0); } } // namespace base
// 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 "base/thread_local.h" #include <pthread.h> #include "base/logging.h" namespace base { // static void ThreadLocalPlatform::AllocateSlot(SlotType& slot) { int error = pthread_key_create(&slot, NULL); CHECK(error == 0); } // static void ThreadLocalPlatform::FreeSlot(SlotType& slot) { int error = pthread_key_delete(slot); DCHECK(error == 0); } // static void* ThreadLocalPlatform::GetValueFromSlot(SlotType& slot) { return pthread_getspecific(slot); } // static void ThreadLocalPlatform::SetValueInSlot(SlotType& slot, void* value) { int error = pthread_setspecific(slot, value); CHECK(error == 0); } } // namespace base
Add test for put method
#include "stdafx.h" #include "CppUnitTest.h" #include "datastore.h" using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; using DataStore = You::DataStore::DataStore; namespace YouDataStoreTests { TEST_CLASS(DataStoreApiTest) { public: TEST_METHOD(DataStore_Post_Basic_Test) { You::DataStore::DataStore sut; bool result = sut.post(0, DataStore::STask()); Assert::IsTrue(result); } TEST_METHOD(DataStore_Post_DuplicateId_Test) { You::DataStore::DataStore sut; sut.post(0, DataStore::STask()); bool result = sut.post(0, DataStore::STask()); Assert::IsFalse(result); } }; } // namespace YouDataStoreTests
#include "stdafx.h" #include "CppUnitTest.h" #include "datastore.h" using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; using DataStore = You::DataStore::DataStore; namespace YouDataStoreTests { TEST_CLASS(DataStoreApiTest) { public: DataStore sut; TEST_METHOD(DataStore_Post_Basic_Test) { bool result = sut.post(0, DataStore::STask()); Assert::IsTrue(result); } TEST_METHOD(DataStore_Post_DuplicateId_Test) { sut.post(0, DataStore::STask()); bool result = sut.post(0, DataStore::STask()); Assert::IsFalse(result); } TEST_METHOD(DataStore_Put_Basic_Test) { sut.post(0, DataStore::STask()); bool result = sut.put(0, DataStore::STask()); Assert::IsTrue(result); } }; } // namespace YouDataStoreTests
Disable wireless entry in combobox for now
#include "settingsview.h" #include "ui_settings.h" SettingsView::SettingsView(QWidget *parent) : QMainWindow(parent), ui(new Ui::SettingsView) { ui->setupUi(this); QSettings settings; int syncingPreference = settings.value("syncingPreference", QVariant(static_cast<int>(SyncOptions::MANUAL_ONLY))).toInt(); QStringList syncingOptions({ "Manual Only", // SyncOptions::MANUAL_ONLY "On Startup (Always)", // SyncOptions::ON_STARTUP "On Startup (WiFi)", // SyncOptions::WIFI }); ui->comboBox->addItems(syncingOptions); ui->comboBox->setCurrentIndex(syncingPreference); } SettingsView::~SettingsView() { delete ui; } void SettingsView::on_pushButton_2_clicked() { emit backButtonClicked(); } void SettingsView::on_pushButton_clicked() { emit syncButtonClicked(); } void SettingsView::on_comboBox_currentIndexChanged(int index) { QSettings settings; settings.setValue("syncingPreference", index); settings.sync(); } void SettingsView::updateLastSync() { QSettings settings; ui->label->setText(settings.value("lastUpdate").toString()); }
#include "settingsview.h" #include "ui_settings.h" SettingsView::SettingsView(QWidget *parent) : QMainWindow(parent), ui(new Ui::SettingsView) { ui->setupUi(this); QSettings settings; int syncingPreference = settings.value("syncingPreference", QVariant(static_cast<int>(SyncOptions::MANUAL_ONLY))).toInt(); QStringList syncingOptions({ "Manual Only", // SyncOptions::MANUAL_ONLY "On Startup (Always)", // SyncOptions::ON_STARTUP "On Startup (WiFi)", // SyncOptions::WIFI }); ui->comboBox->addItems(syncingOptions); ui->comboBox->setItemData(2, QVariant(0), Qt::UserRole - 1); // Horrible hack according to peppe ui->comboBox->setCurrentIndex(syncingPreference); } SettingsView::~SettingsView() { delete ui; } void SettingsView::on_pushButton_2_clicked() { emit backButtonClicked(); } void SettingsView::on_pushButton_clicked() { emit syncButtonClicked(); } void SettingsView::on_comboBox_currentIndexChanged(int index) { QSettings settings; settings.setValue("syncingPreference", index); settings.sync(); } void SettingsView::updateLastSync() { QSettings settings; ui->label->setText(settings.value("lastUpdate").toString()); }
Make test more platform independent.
// RUN: clang-cc -emit-llvm-only -verify %s // PR5454 class X {static void * operator new(unsigned long size) throw(); X(int); }; int a(), b(); void b(int x) { new X(x ? a() : b()); }
// RUN: clang-cc -emit-llvm-only -verify %s // PR5454 #include <stddef.h> class X {static void * operator new(size_t size) throw(); X(int); }; int a(), b(); void b(int x) { new X(x ? a() : b()); }
Add missing header on Linux
#include <cstdlib> #include <iostream> int main() { #ifdef __APPLE__ const char* name = "DYLD_LIBRARY_PATH"; #else const char* name = "LD_LIBRARY_PATH"; #endif const char* cetLDPathValue = getenv("CETD_LIBRARY_PATH"); int res = setenv("DYLD_LIBRARY_PATH", cetLDPathValue, 1); const char* localLDPathValue = getenv(name); if(strcmp(localLDPathValue,cetLDPathValue) != 0) { return 1; } std::cout << localLDPathValue << std::endl; return 0; }
#include <cstdlib> #include <string.h> #include <iostream> int main() { #ifdef __APPLE__ const char* name = "DYLD_LIBRARY_PATH"; #else const char* name = "LD_LIBRARY_PATH"; #endif const char* cetLDPathValue = getenv("CETD_LIBRARY_PATH"); int res = setenv("DYLD_LIBRARY_PATH", cetLDPathValue, 1); const char* localLDPathValue = getenv(name); if(strcmp(localLDPathValue,cetLDPathValue) != 0) { return 1; } std::cout << localLDPathValue << std::endl; return 0; }
Initialize object color to red for testing purposes
#include "GeometryObject.h" GeometryObject::GeometryObject() { } GeometryObject::GeometryObject(const std::vector<Point3D>& vertices, const std::vector<uint8_t>& indices) : m_vertices(vertices), m_indices(indices){ } GeometryObject::~GeometryObject() { } const std::vector<Triangle3D> GeometryObject::tessellate() const { //TODO: actual tessellation using vertices and indices return std::vector<Triangle3D> { Triangle3D( Point3D(-5.0f, 0.0f, 0.0f), Point3D(0.0f, 5.0f, 0.0f), Point3D(5.0f, 0.0f, 0.0f) ) }; }
#include "GeometryObject.h" GeometryObject::GeometryObject() { m_color = RGBColor(1, 0, 0); } GeometryObject::GeometryObject(const std::vector<Point3D>& vertices, const std::vector<uint8_t>& indices) : m_vertices(vertices), m_indices(indices){ m_color = RGBColor(1, 0, 0); } GeometryObject::~GeometryObject() { } const std::vector<Triangle3D> GeometryObject::tessellate() const { //TODO: actual tessellation using vertices and indices return std::vector<Triangle3D> { Triangle3D( Point3D(-25.0f, 0.0f, 20.0f), Point3D(0.0f, 25.0f, 20.0f), Point3D(25.0f, 0.0f, 20.0f) ) }; }
Disable app banners on 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 "chrome/browser/banners/app_banner_manager_desktop.h" #include "base/command_line.h" #include "chrome/browser/banners/app_banner_data_fetcher_desktop.h" #include "chrome/common/chrome_switches.h" #include "extensions/common/constants.h" namespace { // TODO(dominickn) Enforce the set of icons which will guarantee the best // user experience. int kMinimumIconSize = extension_misc::EXTENSION_ICON_LARGE; } // anonymous namespace DEFINE_WEB_CONTENTS_USER_DATA_KEY(banners::AppBannerManagerDesktop); namespace banners { bool AppBannerManagerDesktop::IsEnabled() { #if defined(OS_CHROMEOS) return !base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableAddToShelf); #else return base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableAddToShelf); #endif } AppBannerDataFetcher* AppBannerManagerDesktop::CreateAppBannerDataFetcher( base::WeakPtr<AppBannerDataFetcher::Delegate> weak_delegate, const int ideal_icon_size) { return new AppBannerDataFetcherDesktop(web_contents(), weak_delegate, ideal_icon_size); } AppBannerManagerDesktop::AppBannerManagerDesktop( content::WebContents* web_contents) : AppBannerManager(web_contents, kMinimumIconSize) { } } // namespace banners
// 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 "chrome/browser/banners/app_banner_manager_desktop.h" #include "base/command_line.h" #include "chrome/browser/banners/app_banner_data_fetcher_desktop.h" #include "chrome/common/chrome_switches.h" #include "extensions/common/constants.h" namespace { // TODO(dominickn) Enforce the set of icons which will guarantee the best // user experience. int kMinimumIconSize = extension_misc::EXTENSION_ICON_LARGE; } // anonymous namespace DEFINE_WEB_CONTENTS_USER_DATA_KEY(banners::AppBannerManagerDesktop); namespace banners { bool AppBannerManagerDesktop::IsEnabled() { return base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableAddToShelf); } AppBannerDataFetcher* AppBannerManagerDesktop::CreateAppBannerDataFetcher( base::WeakPtr<AppBannerDataFetcher::Delegate> weak_delegate, const int ideal_icon_size) { return new AppBannerDataFetcherDesktop(web_contents(), weak_delegate, ideal_icon_size); } AppBannerManagerDesktop::AppBannerManagerDesktop( content::WebContents* web_contents) : AppBannerManager(web_contents, kMinimumIconSize) { } } // namespace banners
Fix terrible perf test for FAST detector
#include "perf_precomp.hpp" using namespace std; using namespace cv; using namespace perf; using std::tr1::make_tuple; using std::tr1::get; typedef perf::TestBaseWithParam<std::string> fast; #define FAST_IMAGES \ "cv/detectors_descriptors_evaluation/images_datasets/leuven/img1.png",\ "stitching/a3.png" PERF_TEST_P(fast, detectForORB, testing::Values(FAST_IMAGES)) { String filename = getDataPath(GetParam()); Mat frame = imread(filename, IMREAD_GRAYSCALE); if (frame.empty()) FAIL() << "Unable to load source image " << filename; declare.in(frame); FastFeatureDetector fd(20, true, FastFeatureDetector::TYPE_5_8); vector<KeyPoint> points; TEST_CYCLE() fd.detect(frame, points); fd = FastFeatureDetector(20, true, FastFeatureDetector::TYPE_7_12); TEST_CYCLE() fd.detect(frame, points); fd = FastFeatureDetector(20, true, FastFeatureDetector::TYPE_9_16); TEST_CYCLE() fd.detect(frame, points); }
#include "perf_precomp.hpp" using namespace std; using namespace cv; using namespace perf; using std::tr1::make_tuple; using std::tr1::get; enum { TYPE_5_8 =FastFeatureDetector::TYPE_5_8, TYPE_7_12 = FastFeatureDetector::TYPE_7_12, TYPE_9_16 = FastFeatureDetector::TYPE_9_16 }; CV_ENUM(FastType, TYPE_5_8, TYPE_7_12, TYPE_9_16) typedef std::tr1::tuple<String, FastType> File_Type_t; typedef perf::TestBaseWithParam<File_Type_t> fast; #define FAST_IMAGES \ "cv/detectors_descriptors_evaluation/images_datasets/leuven/img1.png",\ "stitching/a3.png" PERF_TEST_P(fast, detect, testing::Combine( testing::Values(FAST_IMAGES), testing::ValuesIn(FastType::all()) )) { String filename = getDataPath(get<0>(GetParam())); int type = get<1>(GetParam()); Mat frame = imread(filename, IMREAD_GRAYSCALE); if (frame.empty()) FAIL() << "Unable to load source image " << filename; declare.in(frame); FastFeatureDetector fd(20, true, type); vector<KeyPoint> points; TEST_CYCLE() fd.detect(frame, points); SANITY_CHECK(points); }
Include stdio.h for printf() declaration.
/* BZWorkbench * Copyright (c) 1993 - 2008 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include "windows/ConsoleWindow.h" Console* ConsoleWindow::console = NULL; bool ConsoleWindow::initialized = false; // constructor ConsoleWindow::ConsoleWindow(int lineLimit) : Fl_Window(DEFAULT_WIDTH, DEFAULT_HEIGHT, "BZWorkbench Messages") { end(); console = new Console(10, 10, DEFAULT_WIDTH - 20, DEFAULT_HEIGHT - 20); add(console); initialized = true; console->setReadOnly(true); } // destructor ConsoleWindow::~ConsoleWindow() { initialized = false; } // outputs text to the console widget void ConsoleWindow::output(const char* text, ...) { // borrowed from TextUtils.cxx va_list args; va_start(args, text); string result = TextUtils::vformat(text, args); va_end(args); if(!initialized) { printf("%s", result.c_str()); } else { console->add( result ); } }
/* BZWorkbench * Copyright (c) 1993 - 2008 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include <stdio.h> #include "windows/ConsoleWindow.h" Console* ConsoleWindow::console = NULL; bool ConsoleWindow::initialized = false; // constructor ConsoleWindow::ConsoleWindow(int lineLimit) : Fl_Window(DEFAULT_WIDTH, DEFAULT_HEIGHT, "BZWorkbench Messages") { end(); console = new Console(10, 10, DEFAULT_WIDTH - 20, DEFAULT_HEIGHT - 20); add(console); initialized = true; console->setReadOnly(true); } // destructor ConsoleWindow::~ConsoleWindow() { initialized = false; } // outputs text to the console widget void ConsoleWindow::output(const char* text, ...) { // borrowed from TextUtils.cxx va_list args; va_start(args, text); string result = TextUtils::vformat(text, args); va_end(args); if(!initialized) { printf("%s", result.c_str()); } else { console->add( result ); } }
Increase core count for PerfettoDeviceFeatureTest
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <sys/sysinfo.h> #include "test/gtest_and_gmock.h" namespace perfetto { TEST(PerfettoDeviceFeatureTest, TestMaxCpusForAtraceChmod) { // Check that there are no more than 16 CPUs so that the assumption in the // atrace.rc for clearing CPU buffers is valid. ASSERT_LE(sysconf(_SC_NPROCESSORS_CONF), 16); } } // namespace perfetto
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <sys/sysinfo.h> #include "test/gtest_and_gmock.h" namespace perfetto { TEST(PerfettoDeviceFeatureTest, TestMaxCpusForAtraceChmod) { // Check that there are no more than 24 CPUs so that the assumption in the // atrace.rc for clearing CPU buffers is valid. ASSERT_LE(sysconf(_SC_NPROCESSORS_CONF), 24); } } // namespace perfetto
Fix memory leak found in xcode instruments
#include "queuemanager.h" #include "rdkafka.h" QueueManager::QueueManager(rd_kafka_t *rk) : rk_(rk) { } QueueManager::~QueueManager() { ASSERT(queues_.empty()); } void QueueManager::add(rd_kafka_queue_t* queue) { CritScope ss(&crt_); ASSERT(queues_.find(queue) == queues_.end()); //remove the queue forwarding on the main queue. rd_kafka_queue_forward(queue, NULL); queues_.insert(queue); } bool QueueManager::remove(rd_kafka_queue_t* queue) { CritScope ss(&crt_); auto it = queues_.find(queue); if(it == queues_.end()) return false; //forward the queue back to the main queue rd_kafka_queue_forward(*it, rd_kafka_queue_get_consumer(rk_)); queues_.erase(it); return true; } void QueueManager::clear_all() { CritScope ss(&crt_); //forwards all queues back on the main queue for(auto it = queues_.begin(); it != queues_.end(); ++ it) rd_kafka_queue_forward(*it, rd_kafka_queue_get_consumer(rk_)); queues_.clear(); }
#include "queuemanager.h" #include "rdkafka.h" QueueManager::QueueManager(rd_kafka_t *rk) : rk_(rk) { } QueueManager::~QueueManager() { ASSERT(queues_.empty()); } void QueueManager::add(rd_kafka_queue_t* queue) { CritScope ss(&crt_); ASSERT(queues_.find(queue) == queues_.end()); //remove the queue forwarding on the main queue. rd_kafka_queue_forward(queue, NULL); queues_.insert(queue); } bool QueueManager::remove(rd_kafka_queue_t* queue) { CritScope ss(&crt_); auto it = queues_.find(queue); if(it == queues_.end()) return false; //forward the queue back to the main queue rd_kafka_queue_t* main_queue = rd_kafka_queue_get_consumer(rk_); rd_kafka_queue_forward(*it, main_queue); rd_kafka_queue_destroy(main_queue); queues_.erase(it); return true; } void QueueManager::clear_all() { CritScope ss(&crt_); //forwards all queues back on the main queue for(auto it = queues_.begin(); it != queues_.end(); ++ it) { rd_kafka_queue_t* main_queue = rd_kafka_queue_get_consumer(rk_); rd_kafka_queue_forward(*it, main_queue); rd_kafka_queue_destroy(main_queue); } queues_.clear(); }
Include GrGLInterface.h instead of forward declaring, since we have to get NULL defined anyway.
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ struct GrGLInterface; const GrGLInterface* GrGLDefaultInterface() { return NULL; }
/* * 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 "GrGLInterface.h" const GrGLInterface* GrGLDefaultInterface() { return NULL; }
Change project name to the name of the Cargo.toml's parent dir
#include "cargoproject.h" #include "cargoprojectnode.h" #include "utils/fileutils.h" #include "cargoprojectmanager.h" #include "cargoprojectfile.h" using namespace Rust; CargoProject::CargoProject(CargoProjectManager* projectManager, QString projectFileName) : projectManager_(projectManager), projectFileName_(projectFileName), rootNode_(new CargoProjectNode(Utils::FileName::fromString(projectFileName))), projectFile_(new CargoProjectFile(projectFileName)) { } // The name of the project, that can be seen in the welcome project list, // and in the project root's contextual menu. QString CargoProject::displayName() const { return QString::fromLatin1("Stub Display Name"); } // Not sure in what context this document is used. Core::IDocument* CargoProject::document() const { return projectFile_.data(); } ProjectExplorer::IProjectManager* CargoProject::projectManager() const { return projectManager_; } // The returned object must be the same on each call to this method. ProjectExplorer::ProjectNode* CargoProject::rootProjectNode() const { return rootNode_.data(); } QStringList CargoProject::files(ProjectExplorer::Project::FilesMode fileMode) const { Q_UNUSED(fileMode) return QStringList(); }
#include "cargoproject.h" #include "cargoprojectnode.h" #include "utils/fileutils.h" #include "cargoprojectmanager.h" #include "cargoprojectfile.h" using namespace Rust; CargoProject::CargoProject(CargoProjectManager* projectManager, QString projectFileName) : projectManager_(projectManager), projectFileName_(projectFileName), rootNode_(new CargoProjectNode(Utils::FileName::fromString(projectFileName))), projectFile_(new CargoProjectFile(projectFileName)) { } // The name of the project, that can be seen in the welcome project list, // and in the project root's contextual menu. QString CargoProject::displayName() const { return Utils::FileName::fromString(projectFileName_).parentDir().fileName(); } // Not sure in what context this document is used. Core::IDocument* CargoProject::document() const { return projectFile_.data(); } ProjectExplorer::IProjectManager* CargoProject::projectManager() const { return projectManager_; } // The returned object must be the same on each call to this method. ProjectExplorer::ProjectNode* CargoProject::rootProjectNode() const { return rootNode_.data(); } QStringList CargoProject::files(ProjectExplorer::Project::FilesMode fileMode) const { Q_UNUSED(fileMode) return QStringList(); }
Enable async DNS field trial on CrOS (canary+dev channels).
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/net/async_dns_field_trial.h" #include "base/metrics/field_trial.h" #include "build/build_config.h" #include "chrome/common/chrome_version_info.h" namespace chrome_browser_net { bool ConfigureAsyncDnsFieldTrial() { #if defined(OS_ANDROID) || defined(OS_IOS) || defined(OS_CHROMEOS) // There is no DnsConfigService on those platforms so disable the field trial. return false; #endif const base::FieldTrial::Probability kAsyncDnsDivisor = 100; base::FieldTrial::Probability enabled_probability = 0; // TODO(szym): expand to DEV channel after fixing http://crbug.com/121085 if (chrome::VersionInfo::GetChannel() <= chrome::VersionInfo::CHANNEL_CANARY) enabled_probability = 0; scoped_refptr<base::FieldTrial> trial( base::FieldTrialList::FactoryGetFieldTrial( "AsyncDns", kAsyncDnsDivisor, "disabled", 2012, 9, 30, NULL)); int enabled_group = trial->AppendGroup("enabled", enabled_probability); return trial->group() == enabled_group; } } // namespace chrome_browser_net
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/net/async_dns_field_trial.h" #include "base/metrics/field_trial.h" #include "build/build_config.h" #include "chrome/common/chrome_version_info.h" namespace chrome_browser_net { bool ConfigureAsyncDnsFieldTrial() { #if defined(OS_ANDROID) || defined(OS_IOS) // There is no DnsConfigService on those platforms so disable the field trial. return false; #endif const base::FieldTrial::Probability kAsyncDnsDivisor = 100; base::FieldTrial::Probability enabled_probability = 0; #if defined(OS_CHROMEOS) if (chrome::VersionInfo::GetChannel() <= chrome::VersionInfo::CHANNEL_DEV) enabled_probability = 50; #endif scoped_refptr<base::FieldTrial> trial( base::FieldTrialList::FactoryGetFieldTrial( "AsyncDns", kAsyncDnsDivisor, "disabled", 2012, 10, 30, NULL)); int enabled_group = trial->AppendGroup("enabled", enabled_probability); return trial->group() == enabled_group; } } // namespace chrome_browser_net
Revert "[libFuzzer tests] Use substring comparison in libFuzzer tests"
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Make sure LLVMFuzzerInitialize is called. #include <assert.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> static char *argv0; extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv) { assert(*argc > 0); argv0 = **argv; fprintf(stderr, "LLVMFuzzerInitialize: %s\n", argv0); return 0; } extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { if (Size == strlen(argv0) && !strnstr(reinterpret_cast<const char *>(Data), argv0, Size)) { fprintf(stderr, "BINGO %s\n", argv0); exit(1); } return 0; }
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Make sure LLVMFuzzerInitialize is called. #include <assert.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> static char *argv0; extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv) { assert(*argc > 0); argv0 = **argv; fprintf(stderr, "LLVMFuzzerInitialize: %s\n", argv0); return 0; } extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { if (Size == strlen(argv0) && !strncmp(reinterpret_cast<const char *>(Data), argv0, Size)) { fprintf(stderr, "BINGO %s\n", argv0); exit(1); } return 0; }
Fix to make it work.
// https://github.com/KubaO/stackoverflown/tree/master/questions/html-get-24965972 #include <QtNetwork> #include <functional> void htmlGet(const QUrl &url, const std::function<void(const QString&)> & fun) { QScopedPointer<QNetworkAccessManager> manager(new QNetworkAccessManager); QNetworkReply * response = manager->get(QNetworkRequest(QUrl(url))); QObject::connect(manager, &QNetworkAccessManager::finished, [manager, response]{ response->deleteLater(); manager->deleteLater(); if (reponse->error() != QNetworkReply::NoError) return; QString contentType = response->header(QNetworkRequest::ContentTypeHeader).toString(); if (!contentType.contains("charset=utf-8")) { qWarning() << "Content charsets other than utf-8 are not implemented yet."; return; } QString html = QString::fromUtf8(response->readAll()); // do something with the data }) && manager.take(); } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); return a.exec(); }
// https://github.com/KubaO/stackoverflown/tree/master/questions/html-get-24965972 #include <QtNetwork> #include <functional> void htmlGet(const QUrl &url, const std::function<void(const QString&)> &fun) { QScopedPointer<QNetworkAccessManager> manager(new QNetworkAccessManager); QNetworkReply *response = manager->get(QNetworkRequest(QUrl(url))); QObject::connect(response, &QNetworkReply::finished, [response, fun]{ response->deleteLater(); response->manager()->deleteLater(); if (response->error() != QNetworkReply::NoError) return; auto const contentType = response->header(QNetworkRequest::ContentTypeHeader).toString(); static QRegularExpression re("charset=([!-~]+)"); auto const match = re.match(contentType); if (!match.hasMatch() || 0 != match.captured(1).compare("utf-8", Qt::CaseInsensitive)) { qWarning() << "Content charsets other than utf-8 are not implemented yet:" << contentType; return; } auto const html = QString::fromUtf8(response->readAll()); fun(html); // do something with the data }) && manager.take(); } int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); htmlGet({"http://www.google.com"}, [](const QString &body){ qDebug() << body; qApp->quit(); }); return app.exec(); }
Correct name of module initializer.
#include <Python.h> #include "Quantuccia/ql/time/calendars/unitedstates.hpp" static PyObject* get_holiday_date(PyObject *self, PyObject *args) { return NULL; } static PyMethodDef QuantucciaMethods[] = { {"get_holiday_date", (PyCFunction)get_holiday_date, METH_VARARGS, NULL}, {NULL, NULL} /* Sentinel */ }; static struct PyModuleDef quantuccia_module_def = { PyModuleDef_HEAD_INIT, "quantuccia", NULL, -1, QuantucciaMethods, }; PyObject* PyInit_pyQuantuccia(void){ PyObject *m; m = PyCreate_Module(&quantuccia_module_def); return m; }
#include <Python.h> #include "Quantuccia/ql/time/calendars/unitedstates.hpp" static PyObject* get_holiday_date(PyObject *self, PyObject *args) { return NULL; } static PyMethodDef QuantucciaMethods[] = { {"get_holiday_date", (PyCFunction)get_holiday_date, METH_VARARGS, NULL}, {NULL, NULL} /* Sentinel */ }; static struct PyModuleDef quantuccia_module_def = { PyModuleDef_HEAD_INIT, "quantuccia", NULL, -1, QuantucciaMethods, }; PyObject* PyInit_pyQuantuccia(void){ PyObject *m; m = PyModule_Create(&quantuccia_module_def); return m; }
Add basic implemention of icalc interface
//// Basic implementation of the icalcterm interface #include "icalc/icalc.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #define EXPORT __attribute__ ((visibility ("default"))) extern "C" { void EXPORT CI_init( CI_Config* config ) { printf("Starting defcalc.\n"); } // Note: this function returns a pointer, but for some strange // reason we must put the asterisk after the EXPORT. CI_Result EXPORT * CI_submit( char const* input ) { CI_Result* res = new CI_Result; res->one_line = strdup( input ); res->y = 3; res->grid = new char*[res->y]; for( int i = 0; i < res->y; ++i ) res->grid[i] = strdup( input ); return res; } void EXPORT CI_result_release( CI_Result* result ) { free( result->one_line ); for( int i = 0; i < result->y; ++i ) free( result->grid[i] ); delete[] result->grid; delete result; } } // extern "C"
Disable failing test on darwin during investigation.
// RUN: %clangxx_asan -O0 %s -o %t && not %run %t 2>&1 | FileCheck %s // RUN: %clangxx_asan -O1 %s -o %t && not %run %t 2>&1 | FileCheck %s // RUN: %clangxx_asan -O2 %s -o %t && not %run %t 2>&1 | FileCheck %s // RUN: %clangxx_asan -O3 %s -o %t && not %run %t 2>&1 | FileCheck %s // REQUIRES: compiler-rt-optimized // UNSUPPORTED: android #include <string.h> int main(int argc, char **argv) { char a1[] = {static_cast<char>(argc), 2, 3, 4}; char a2[] = {1, static_cast<char>(2 * argc), 3, 4}; int res = bcmp(a1, a2, 4 + argc); // BOOM // CHECK: AddressSanitizer: stack-buffer-overflow // CHECK: {{#1.*bcmp}} // CHECK: {{#2.*main}} return res; }
// RUN: %clangxx_asan -O0 %s -o %t && not %run %t 2>&1 | FileCheck %s // RUN: %clangxx_asan -O1 %s -o %t && not %run %t 2>&1 | FileCheck %s // RUN: %clangxx_asan -O2 %s -o %t && not %run %t 2>&1 | FileCheck %s // RUN: %clangxx_asan -O3 %s -o %t && not %run %t 2>&1 | FileCheck %s // REQUIRES: compiler-rt-optimized // UNSUPPORTED: android // XFAIL: darwin #include <string.h> int main(int argc, char **argv) { char a1[] = {static_cast<char>(argc), 2, 3, 4}; char a2[] = {1, static_cast<char>(2 * argc), 3, 4}; int res = bcmp(a1, a2, 4 + argc); // BOOM // CHECK: AddressSanitizer: stack-buffer-overflow // CHECK: {{#1.*bcmp}} // CHECK: {{#2.*main}} return res; }
Fix a typo in the test for r243066
// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++11 -fexceptions -fcxx-exceptions -fprofile-instr-generate -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name trymacro.cpp %s | FileCheck %s // CHECK: Z3fn1v: void fn1() try { return; } // CHECK: [[@LINE]]:12 -> [[@LINE+1]]:14 = #1 catch(...) {} // CHECK: [[@LINE]]:12 -> [[@LINE]]:14 = #2 #define RETURN_BLOCK { return; } // CHECK: Z3fn2v: void fn2() try RETURN_BLOCK // CHECK: [[@LINE]]:12 -> [[@LINE+1]]:14 = #1 catch(...) {} // CHECK: [[@LINE]]:12 -> [[@LINE]]:14 = #2 #define TRY try #define CATCH(x) catch (x) // CHECK: Z3fn3v: void fn3() TRY { return; } // CHECK: [[@LINE]]:12 -> [[@LINE+1]]:14 = #1 CATCH(...) {} // CHECK: [[@LINE]]:12 -> [[@LINE]]:14 = #2 int main() { fn1(); fn2(); fn3(); }
// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++11 -fexceptions -fcxx-exceptions -fprofile-instr-generate -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name trymacro.cpp %s | FileCheck %s // CHECK: Z3fn1v: void fn1() try { return; } // CHECK: [[@LINE]]:12 -> [[@LINE+1]]:14 = #1 catch(...) {} // CHECK: [[@LINE]]:12 -> [[@LINE]]:14 = #2 #define RETURN_BLOCK { return; } // CHECK: Z3fn2v: void fn2() try RETURN_BLOCK // CHECK: [[@LINE]]:12 -> [[@LINE+1]]:14 = #1 catch(...) {} // CHECK: [[@LINE]]:12 -> [[@LINE]]:14 = #2 #define TRY try #define CATCH(x) catch (x) // CHECK: Z3fn3v: void fn3() TRY { return; } // CHECK: [[@LINE]]:15 -> [[@LINE+1]]:14 = #1 CATCH(...) {} // CHECK: [[@LINE]]:12 -> [[@LINE]]:14 = #2 int main() { fn1(); fn2(); fn3(); }
Remove iostream inclusion in RANLUX
/* * rngs * ECE 541 Project 2 * Kashev Dalmia - dalmia3 * David Huang - huang157 */ #include <iostream> #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 << 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); } }
Define StaticCtorsSection and StaticDtorsSection for ARM.
//===-- ARMTargetAsmInfo.cpp - ARM asm properties ---------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by James M. Laskey and is distributed under the // University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains the declarations of the ARMTargetAsmInfo properties. // //===----------------------------------------------------------------------===// #include "ARMTargetAsmInfo.h" using namespace llvm; ARMTargetAsmInfo::ARMTargetAsmInfo(const ARMTargetMachine &TM) { Data16bitsDirective = "\t.half\t"; Data32bitsDirective = "\t.word\t"; Data64bitsDirective = 0; ZeroDirective = "\t.skip\t"; CommentString = "@"; ConstantPoolSection = "\t.text\n"; AlignmentIsInBytes = false; WeakRefDirective = "\t.weak\t"; }
//===-- ARMTargetAsmInfo.cpp - ARM asm properties ---------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by James M. Laskey and is distributed under the // University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains the declarations of the ARMTargetAsmInfo properties. // //===----------------------------------------------------------------------===// #include "ARMTargetAsmInfo.h" using namespace llvm; ARMTargetAsmInfo::ARMTargetAsmInfo(const ARMTargetMachine &TM) { Data16bitsDirective = "\t.half\t"; Data32bitsDirective = "\t.word\t"; Data64bitsDirective = 0; ZeroDirective = "\t.skip\t"; CommentString = "@"; ConstantPoolSection = "\t.text\n"; AlignmentIsInBytes = false; WeakRefDirective = "\t.weak\t"; StaticCtorsSection = "\t.section .ctors,\"aw\",%progbits"; StaticDtorsSection = "\t.section .dtors,\"aw\",%progbits"; }
Add a sanity check for the input file
#include <iostream> #include "word.h" using namespace std; string make_outfile(string namefile); int main(int argc, char* argv[]) { Word word; if (argc < 2) { cerr << "Usage: si [origin].si [destination].cpp" << endl; exit(EXIT_FAILURE); } else if (argc == 2) { string outfile = make_outfile(argv[1]); word.set_out(outfile); } else if (argc > 2) word.set_out(argv[2]); word.set_in(argv[1]); word.write(); word.close_files(); } /* if no destination file is provided, this will take the * first argument and turn its contents in to the name * of the destination file in .cpp format */ string make_outfile(string namefile) { string name = ""; for (int i = 0; i < (int)namefile.length(); i++) { if (namefile[i] == '.') { name = namefile.substr(0,i); name += ".cpp"; break; } } if (name == "") { cerr << "No .si file found\n"; exit(EXIT_FAILURE); } return name; }
#include <iostream> #include "word.h" using namespace std; string make_outfile(string namefile); int main(int argc, char* argv[]) { Word word; if (argc < 2) { cerr << "Usage: si origin.si [destination.cpp]" << endl; exit(EXIT_FAILURE); } else if (argc == 2) { ifstream inputFile(argv[1]); if (!inputFile) { cerr << "ERROR: Input file could not be read." << endl; exit(EXIT_FAILURE); } else { string outfile = make_outfile(argv[1]); word.set_out(outfile); } } else if (argc > 2) { ifstream inputFile(argv[1]); if (!inputFile) { cerr << "ERROR: Input file could not be read." << endl; exit(EXIT_FAILURE); } else { word.set_out(argv[2]); } } word.set_in(argv[1]); word.write(); word.close_files(); } /* if no destination file is provided, this will take the * first argument and turn its contents in to the name * of the destination file in .cpp format */ string make_outfile(string namefile) { string name = ""; for (int i = 0; i < (int)namefile.length(); i++) { if (namefile[i] == '.') { name = namefile.substr(0,i); name += ".cpp"; break; } } if (name == "") { cerr << "No .si file found\n"; exit(EXIT_FAILURE); } return name; }
Change the order of variables in the constructor init list
#include <iostream> #include <string> #include "job.h" Job::Job(int id, std::string machine_name) : job_id(id), state(State::Moveable), machine(machine_name) { std::cout << "Created new job: " << id << std::endl; } int Job::get_id() const { return job_id; } const std::string& Job::get_machine() const { return machine; } bool Job::moveable() const { return state == State::Moveable; }
#include <iostream> #include <string> #include "job.h" Job::Job(int id, std::string machine_name) : job_id(id), machine(machine_name), state(State::Moveable) { std::cout << "Created new job: " << id << std::endl; } int Job::get_id() const { return job_id; } const std::string& Job::get_machine() const { return machine; } bool Job::moveable() const { return state == State::Moveable; }
Clean up a couple things
#include <GL/glx.h> #include "linuxwindow.hh" #include "system/openglcontext.hh" #include <iostream> class LinuxOpenGLContext : public System::OpenGLContext { public: LinuxOpenGLContext(System::Window *window) : _window((LinuxWindow *)window) { Display *display = _window->getDisplay(); ::Window windowHandle = _window->getWindowHandle(); GLint attributes[] = { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None }; XVisualInfo *visualInfo = glXChooseVisual(display, 0, attributes); Colormap colorMap = XCreateColormap(display, windowHandle, visualInfo->visual, AllocNone); _context = glXCreateContext(display, visualInfo, NULL, GL_TRUE); glXMakeCurrent(display, windowHandle, _context); } ~LinuxOpenGLContext() { } void SwapBuffers() { } private: LinuxWindow *_window; GLXContext _context; }; System::OpenGLContext *System::OpenGLContext::Create(System::Window *window) { return new LinuxOpenGLContext(window); }
#include <GL/glx.h> #include "linuxwindow.hh" #include "system/openglcontext.hh" class LinuxOpenGLContext : public System::OpenGLContext { public: LinuxOpenGLContext(System::Window *window) : _window((LinuxWindow *)window) { Display *display = _window->getDisplay(); ::Window windowHandle = _window->getWindowHandle(); GLint attributes[] = { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None }; XVisualInfo *visualInfo = glXChooseVisual(display, 0, attributes); Colormap colorMap = XCreateColormap(display, windowHandle, visualInfo->visual, AllocNone); _context = glXCreateContext(display, visualInfo, NULL, GL_TRUE); glXMakeCurrent(display, windowHandle, _context); } ~LinuxOpenGLContext() { } void SwapBuffers() { } private: LinuxWindow *_window; GLXContext _context; }; System::OpenGLContext *System::OpenGLContext::Create(System::Window *window) { return new LinuxOpenGLContext(window); }
Fix compiler warning which is not support until c++11
#include <libclientserver.h> RateLimit::RateLimit() { m_last = {0, 0}; } RateLimit::~RateLimit() { } void RateLimit::SetTimeout(const struct timespec *tv) { memcpy(&m_timeout, tv, sizeof(*tv)); } bool RateLimit::Check() { struct timespec now; struct timespec when; Time::MonoTonic(&now); Time::Add(&now, &m_timeout, &when); if (Time::IsGreater(&now, &when)) { memcpy(&m_last, &now, sizeof(now)); return true; } return false; }
#include <libclientserver.h> RateLimit::RateLimit() { m_last.tv_sec = 0; m_last.tv_nsec = 0; } RateLimit::~RateLimit() { } void RateLimit::SetTimeout(const struct timespec *tv) { memcpy(&m_timeout, tv, sizeof(*tv)); } bool RateLimit::Check() { struct timespec now; struct timespec when; Time::MonoTonic(&now); Time::Add(&now, &m_timeout, &when); if (Time::IsGreater(&now, &when)) { memcpy(&m_last, &now, sizeof(now)); return true; } return false; }
Move ExtensionApiTest.Bookmarks from DISABLED to FLAKY since it doesn't crash.
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" // Flaky, http://crbug.com/19866. Please consult phajdan.jr before re-enabling. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Bookmarks) { ASSERT_TRUE(RunExtensionTest("bookmarks")) << message_; }
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" // Flaky, http://crbug.com/19866. Please consult phajdan.jr before re-enabling. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_Bookmarks) { ASSERT_TRUE(RunExtensionTest("bookmarks")) << message_; }
Reduce a scope of the temporary variable
#include <stdio.h> int main(void) { int a, b, c; scanf("%d %d %d", &a, &b, &c); int t; if(a > b) t = a, a = b, b = t; if(b > c) t = b, b = c, c = t; if(a > b) t = a, a = b, b = t; printf("%d %d %d\n", a, b, c); return 0; }
#include <stdio.h> int main(void) { int a, b, c; scanf("%d %d %d", &a, &b, &c); if(a > b) { int tmp = a; a = b; b = tmp; } if(b > c) { int tmp = b; b = c; c = tmp; } if(a > b) { int tmp = a; a = b; b = tmp; } printf("%d %d %d\n", a, b, c); return 0; }
Include sdk/config.h before testing configuration macros.
#ifndef SCHEDULER_CORO_OSTHREAD # include "Coro.c" #endif
#include <sdk/config.h> #ifndef SCHEDULER_CORO_OSTHREAD # include "Coro.c" #endif
Fix path to remoting webapp unittest results.
// 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 "base/path_service.h" #include "chrome/test/remoting/qunit_browser_test_runner.h" #if defined(OS_MACOSX) #include "base/mac/foundation_util.h" #endif // !defined(OS_MACOSX) namespace remoting { IN_PROC_BROWSER_TEST_F(QUnitBrowserTestRunner, Remoting_Webapp_Js_Unittest) { base::FilePath base_dir; ASSERT_TRUE(PathService::Get(base::DIR_EXE, &base_dir)); #if defined(OS_MACOSX) if (base::mac::AmIBundled()) { // If we are inside a mac bundle, navigate up to the output directory base_dir = base::mac::GetAppBundlePath(base_dir).DirName(); } #endif // !defined(OS_MACOSX) RunTest( base_dir.Append(FILE_PATH_LITERAL("remoting/unittests/unittest.html"))); } } // namespace remoting
// 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 "base/path_service.h" #include "chrome/test/remoting/qunit_browser_test_runner.h" #if defined(OS_MACOSX) #include "base/mac/foundation_util.h" #endif // !defined(OS_MACOSX) namespace remoting { IN_PROC_BROWSER_TEST_F(QUnitBrowserTestRunner, Remoting_Webapp_Js_Unittest) { base::FilePath base_dir; ASSERT_TRUE(PathService::Get(base::DIR_EXE, &base_dir)); #if defined(OS_MACOSX) if (base::mac::AmIBundled()) { // If we are inside a mac bundle, navigate up to the output directory base_dir = base::mac::GetAppBundlePath(base_dir).DirName(); } #endif // !defined(OS_MACOSX) RunTest( base_dir.Append(FILE_PATH_LITERAL("remoting/unittests/unittests.html"))); } } // namespace remoting
Expand - Handle another rustc internal macro
/* * MRustC - Rust Compiler * - By John Hodge (Mutabah/thePowersGang) * * expand/rustc_diagnostics.cpp * - Stubbed handling for __register_diagnostic and __diagnostic_used */ #include <synext.hpp> #include <parse/common.hpp> // TokenTree etc #include <parse/ttstream.hpp> class CExpanderRegisterDiagnostic: public ExpandProcMacro { ::std::unique_ptr<TokenStream> expand(const Span& sp, const AST::Crate& crate, const ::std::string& ident, const TokenTree& tt, AST::Module& mod) override { return box$( TTStreamO(TokenTree()) ); } }; class CExpanderDiagnosticUsed: public ExpandProcMacro { ::std::unique_ptr<TokenStream> expand(const Span& sp, const AST::Crate& crate, const ::std::string& ident, const TokenTree& tt, AST::Module& mod) override { return box$( TTStreamO(TokenTree()) ); } }; STATIC_MACRO("__register_diagnostic", CExpanderRegisterDiagnostic) STATIC_MACRO("__diagnostic_used", CExpanderDiagnosticUsed)
/* * MRustC - Rust Compiler * - By John Hodge (Mutabah/thePowersGang) * * expand/rustc_diagnostics.cpp * - Stubbed handling for __register_diagnostic and __diagnostic_used */ #include <synext.hpp> #include <parse/common.hpp> // TokenTree etc #include <parse/ttstream.hpp> class CExpanderRegisterDiagnostic: public ExpandProcMacro { ::std::unique_ptr<TokenStream> expand(const Span& sp, const AST::Crate& crate, const ::std::string& ident, const TokenTree& tt, AST::Module& mod) override { return box$( TTStreamO(TokenTree()) ); } }; class CExpanderDiagnosticUsed: public ExpandProcMacro { ::std::unique_ptr<TokenStream> expand(const Span& sp, const AST::Crate& crate, const ::std::string& ident, const TokenTree& tt, AST::Module& mod) override { return box$( TTStreamO(TokenTree()) ); } }; class CExpanderBuildDiagnosticArray: public ExpandProcMacro { ::std::unique_ptr<TokenStream> expand(const Span& sp, const AST::Crate& crate, const ::std::string& ident, const TokenTree& tt, AST::Module& mod) override { return box$( TTStreamO(TokenTree()) ); } }; STATIC_MACRO("__register_diagnostic", CExpanderRegisterDiagnostic) STATIC_MACRO("__diagnostic_used", CExpanderDiagnosticUsed) STATIC_MACRO("__build_diagnostic_array", CExpanderBuildDiagnosticArray)
Fix for file renaming in LLVM (CommandFlags.h -> CommandFlags.def)
//===-- TargetOptionsCommandFlags.cpp ---------------------------*- C++ -*-===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file exists as a place for global variables defined in LLVM's // CodeGen/CommandFlags.h. By putting the resulting object file in // an archive and linking with it, the definitions will automatically be // included when needed and skipped when already present. // //===----------------------------------------------------------------------===// #include "lld/Common/TargetOptionsCommandFlags.h" #include "llvm/CodeGen/CommandFlags.h" #include "llvm/Target/TargetOptions.h" // Define an externally visible version of // InitTargetOptionsFromCodeGenFlags, so that its functionality can be // used without having to include llvm/CodeGen/CommandFlags.h, which // would lead to multiple definitions of the command line flags. llvm::TargetOptions lld::InitTargetOptionsFromCodeGenFlags() { return ::InitTargetOptionsFromCodeGenFlags(); } llvm::Optional<llvm::CodeModel::Model> lld::GetCodeModelFromCMModel() { return getCodeModel(); }
//===-- TargetOptionsCommandFlags.cpp ---------------------------*- C++ -*-===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file exists as a place for global variables defined in LLVM's // CodeGen/CommandFlags.def. By putting the resulting object file in // an archive and linking with it, the definitions will automatically be // included when needed and skipped when already present. // //===----------------------------------------------------------------------===// #include "lld/Common/TargetOptionsCommandFlags.h" #include "llvm/CodeGen/CommandFlags.def" #include "llvm/Target/TargetOptions.h" // Define an externally visible version of // InitTargetOptionsFromCodeGenFlags, so that its functionality can be // used without having to include llvm/CodeGen/CommandFlags.def, which // would lead to multiple definitions of the command line flags. llvm::TargetOptions lld::InitTargetOptionsFromCodeGenFlags() { return ::InitTargetOptionsFromCodeGenFlags(); } llvm::Optional<llvm::CodeModel::Model> lld::GetCodeModelFromCMModel() { return getCodeModel(); }
Fix warning for nonused parameter.
/* * Copyright (C) 2017 Mario Alviano (mario@alviano.net) * * 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 "Propagator.h" #include "GlucoseWrapper.h" namespace zuccherino { Propagator::Propagator(GlucoseWrapper& solver_) : solver(solver_) { solver.add(this); } Propagator::Propagator(GlucoseWrapper& solver_, const Propagator& init) : solver(solver_) { solver.add(this); } }
/* * Copyright (C) 2017 Mario Alviano (mario@alviano.net) * * 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 "Propagator.h" #include "GlucoseWrapper.h" namespace zuccherino { Propagator::Propagator(GlucoseWrapper& solver_) : solver(solver_) { solver.add(this); } Propagator::Propagator(GlucoseWrapper& solver_, const Propagator& /*init*/) : solver(solver_) { solver.add(this); } }
Test cases for some recent work.
// RUN: clang-cc %s -emit-llvm -o - -std=c++0x class A { public: virtual void foo(); }; static_assert (sizeof (A) == (sizeof(void *)), "vtable pointer layout");
// RUN: clang-cc -triple x86_64-apple-darwin -frtti=0 -std=c++0x -S %s -o %t-64.s && // RUN: FileCheck -check-prefix LP64 --input-file=%t-64.s %s && // RUN: clang-cc -triple i386-apple-darwin -frtti=0 -std=c++0x -S %s -o %t-32.s && // RUN: FileCheck -check-prefix LP32 -input-file=%t-32.s %s && // RUN: true class A { public: virtual void foo1(); virtual void foo2(); A() { } } *a; static_assert (sizeof (A) == (sizeof(void *)), "vtable pointer layout"); int main() { A a; } // CHECK-LP64: __ZTV1A: // CHECK-LP64: .space 8 // CHECK-LP64: .space 8 // CHECK-LP64: .quad __ZN1A4foo1Ev // CHECK-LP64: .quad __ZN1A4foo2Ev // CHECK-LP32: __ZTV1A: // CHECK-LP32: .space 4 // CHECK-LP32: .space 4 // CHECK-LP32: .long __ZN1A4foo1Ev // CHECK-LP32: .long __ZN1A4foo2Ev
Fix creation of new ComponentDescriptorRegistry when switching surface
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "ComponentDescriptorProviderRegistry.h" namespace facebook { namespace react { void ComponentDescriptorProviderRegistry::add( ComponentDescriptorProvider provider) const { std::unique_lock<better::shared_mutex> lock(mutex_); componentDescriptorProviders_.insert({provider.handle, provider}); for (auto const &weakRegistry : componentDescriptorRegistries_) { auto registry = weakRegistry.lock(); if (!registry) { continue; } registry->add(provider); } } void ComponentDescriptorProviderRegistry::remove( ComponentDescriptorProvider provider) const { std::unique_lock<better::shared_mutex> lock(mutex_); componentDescriptorProviders_.erase(provider.handle); for (auto const &weakRegistry : componentDescriptorRegistries_) { auto registry = weakRegistry.lock(); if (!registry) { continue; } registry->remove(provider); } } ComponentDescriptorRegistry::Shared ComponentDescriptorProviderRegistry::createComponentDescriptorRegistry( ComponentDescriptorParameters const &parameters) const { std::shared_lock<better::shared_mutex> lock(mutex_); auto registry = std::make_shared<ComponentDescriptorRegistry const>(parameters); for (auto const &pair : componentDescriptorProviders_) { registry->add(pair.second); } return registry; } } // namespace react } // namespace facebook
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "ComponentDescriptorProviderRegistry.h" namespace facebook { namespace react { void ComponentDescriptorProviderRegistry::add( ComponentDescriptorProvider provider) const { std::unique_lock<better::shared_mutex> lock(mutex_); componentDescriptorProviders_.insert({provider.handle, provider}); for (auto const &weakRegistry : componentDescriptorRegistries_) { auto registry = weakRegistry.lock(); if (!registry) { continue; } registry->add(provider); } } void ComponentDescriptorProviderRegistry::remove( ComponentDescriptorProvider provider) const { std::unique_lock<better::shared_mutex> lock(mutex_); componentDescriptorProviders_.erase(provider.handle); for (auto const &weakRegistry : componentDescriptorRegistries_) { auto registry = weakRegistry.lock(); if (!registry) { continue; } registry->remove(provider); } } ComponentDescriptorRegistry::Shared ComponentDescriptorProviderRegistry::createComponentDescriptorRegistry( ComponentDescriptorParameters const &parameters) const { std::shared_lock<better::shared_mutex> lock(mutex_); auto registry = std::make_shared<ComponentDescriptorRegistry const>(parameters); for (auto const &pair : componentDescriptorProviders_) { registry->add(pair.second); } componentDescriptorRegistries_.push_back(registry); return registry; } } // namespace react } // namespace facebook
Fix change in message names
// PluginHelpers.cpp : Defines the exported functions for the DLL application. // #include "stdafx.h" #include "pluginhelpers.h" #include "ContentControl.h" #include "..\..\ToDoList_Dev\Interfaces\UITheme.h" #include "..\..\ToDoList_Dev\Interfaces\IContentControl.h" //////////////////////////////////////////////////////////////////////////////////////////////// using namespace Abstractspoon::Tdl::PluginHelpers; //////////////////////////////////////////////////////////////////////////////////////////////// ContentControl::ParentNotify::ParentNotify(IntPtr hwndParent) : m_hwndParent(NULL), m_hwndFrom(NULL) { m_hwndParent = static_cast<HWND>(hwndParent.ToPointer()); } ContentControl::ParentNotify::ParentNotify(IntPtr hwndParent, IntPtr hwndFrom) : m_hwndParent(NULL), m_hwndFrom(NULL) { m_hwndParent = static_cast<HWND>(hwndParent.ToPointer()); m_hwndFrom = static_cast<HWND>(hwndFrom.ToPointer()); } bool ContentControl::ParentNotify::NotifyChange() { if (!IsWindow(m_hwndParent)) return false; ::SendMessage(m_hwndParent, WM_ICC_COMMENTSCHANGE, 0, (LPARAM)m_hwndFrom); return true; } bool ContentControl::ParentNotify::NotifyKillFocus() { if (!IsWindow(m_hwndParent)) return false; ::SendMessage(m_hwndParent, WM_ICC_COMMENTSKILLFOCUS, 0, (LPARAM)m_hwndFrom); return true; }
// PluginHelpers.cpp : Defines the exported functions for the DLL application. // #include "stdafx.h" #include "pluginhelpers.h" #include "ContentControl.h" #include "..\..\ToDoList_Dev\Interfaces\UITheme.h" #include "..\..\ToDoList_Dev\Interfaces\IContentControl.h" //////////////////////////////////////////////////////////////////////////////////////////////// using namespace Abstractspoon::Tdl::PluginHelpers; //////////////////////////////////////////////////////////////////////////////////////////////// ContentControl::ParentNotify::ParentNotify(IntPtr hwndParent) : m_hwndParent(NULL), m_hwndFrom(NULL) { m_hwndParent = static_cast<HWND>(hwndParent.ToPointer()); } ContentControl::ParentNotify::ParentNotify(IntPtr hwndParent, IntPtr hwndFrom) : m_hwndParent(NULL), m_hwndFrom(NULL) { m_hwndParent = static_cast<HWND>(hwndParent.ToPointer()); m_hwndFrom = static_cast<HWND>(hwndFrom.ToPointer()); } bool ContentControl::ParentNotify::NotifyChange() { if (!IsWindow(m_hwndParent)) return false; ::SendMessage(m_hwndParent, WM_ICC_CONTENTCHANGE, 0, (LPARAM)m_hwndFrom); return true; } bool ContentControl::ParentNotify::NotifyKillFocus() { if (!IsWindow(m_hwndParent)) return false; ::SendMessage(m_hwndParent, WM_ICC_KILLFOCUS, 0, (LPARAM)m_hwndFrom); return true; }
Set the dest hwnd and start grabbing keys during init
#include "HotkeyInput.h" #include "../../3RVX/Logger.h" #include "../Controls/Controls.h" #include "KeyGrabber.h" HotkeyInput::HotkeyInput(HWND parent) : Dialog(parent, MAKEINTRESOURCE(IDD_HOTKEYPROMPT)) { } void HotkeyInput::Initialize() { _prompt = new Label(LBL_PROMPT, *this); }
#include "HotkeyInput.h" #include "../../3RVX/Logger.h" #include "../Controls/Controls.h" #include "KeyGrabber.h" HotkeyInput::HotkeyInput(HWND parent) : Dialog(parent, MAKEINTRESOURCE(IDD_HOTKEYPROMPT)) { } void HotkeyInput::Initialize() { _prompt = new Label(LBL_PROMPT, *this); KeyGrabber::Instance()->SetHwnd(DialogHandle()); KeyGrabber::Instance()->Grab(); }
Increase core count for PerfettoDeviceFeatureTest am: 542f1ede9d
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <sys/sysinfo.h> #include "test/gtest_and_gmock.h" namespace perfetto { TEST(PerfettoDeviceFeatureTest, TestMaxCpusForAtraceChmod) { // Check that there are no more than 16 CPUs so that the assumption in the // atrace.rc for clearing CPU buffers is valid. ASSERT_LE(sysconf(_SC_NPROCESSORS_CONF), 16); } } // namespace perfetto
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <sys/sysinfo.h> #include "test/gtest_and_gmock.h" namespace perfetto { TEST(PerfettoDeviceFeatureTest, TestMaxCpusForAtraceChmod) { // Check that there are no more than 24 CPUs so that the assumption in the // atrace.rc for clearing CPU buffers is valid. ASSERT_LE(sysconf(_SC_NPROCESSORS_CONF), 24); } } // namespace perfetto
Correct the comments and file header.
//===- Support/FileUtilities.cpp - File System Utilities ------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements a family of utility functions which are useful for doing // various things with files. // //===----------------------------------------------------------------------===// #include "FDHandle.h" #include <unistd.h> using namespace llvm; //===----------------------------------------------------------------------===// // FDHandle class implementation // FDHandle::~FDHandle() throw() { if (FD != -1) ::close(FD); } FDHandle &FDHandle::operator=(int fd) throw() { if (FD != -1) ::close(FD); FD = fd; return *this; }
//===- lib/Debugger/FDHandle.cpp - File Descriptor Handle -----------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements a class for ensuring that Unix file handles get closed. // //===----------------------------------------------------------------------===// #include "FDHandle.h" #include <unistd.h> using namespace llvm; //===----------------------------------------------------------------------===// // FDHandle class implementation // FDHandle::~FDHandle() throw() { if (FD != -1) ::close(FD); } FDHandle &FDHandle::operator=(int fd) throw() { if (FD != -1) ::close(FD); FD = fd; return *this; }
Implement shape inference function for AccumulateOp
#include "caffe2/operators/accumulate_op.h" namespace caffe2 { namespace { REGISTER_CPU_OPERATOR(Accumulate, AccumulateOp<float, CPUContext>); OPERATOR_SCHEMA(Accumulate) .NumInputs(1) .NumOutputs(1) // TODO: add Shape inference function (bootcamp) .SetDoc(R"DOC( Accumulate operator accumulates the input tensor to the output tensor. If the output tensor already has the right size, we add to it; otherwise, we first initialize the output tensor to all zeros, and then do accumulation. Any further calls to the operator, given that no one else fiddles with the output in the interim, will do simple accumulations. Accumulation is done using Axpby operation as shown: Y = 1*X + gamma*Y where X is the input tensor, Y is the output tensor and gamma is the multiplier argument. )DOC") .Arg("gamma", "(float, default 1.0) Accumulation multiplier") .Input(0, "input", "The input tensor that has to be accumulated to the " "output tensor. If the output size is not the same as input size, the " "output tensor is first reshaped and initialized to zero, and only " "then, accumulation is done.") .Output(0, "output", "Accumulated output tensor"); SHOULD_NOT_DO_GRADIENT(Accumulate); } // namespace } // namespace caffe2
#include "caffe2/operators/accumulate_op.h" namespace caffe2 { namespace { REGISTER_CPU_OPERATOR(Accumulate, AccumulateOp<float, CPUContext>); OPERATOR_SCHEMA(Accumulate) .NumInputs(1) .NumOutputs(1) .IdenticalTypeAndShape() .SetDoc(R"DOC( Accumulate operator accumulates the input tensor to the output tensor. If the output tensor already has the right size, we add to it; otherwise, we first initialize the output tensor to all zeros, and then do accumulation. Any further calls to the operator, given that no one else fiddles with the output in the interim, will do simple accumulations. Accumulation is done using Axpby operation as shown: Y = 1*X + gamma*Y where X is the input tensor, Y is the output tensor and gamma is the multiplier argument. )DOC") .Arg("gamma", "(float, default 1.0) Accumulation multiplier") .Input(0, "input", "The input tensor that has to be accumulated to the " "output tensor. If the output size is not the same as input size, the " "output tensor is first reshaped and initialized to zero, and only " "then, accumulation is done.") .Output(0, "output", "Accumulated output tensor"); SHOULD_NOT_DO_GRADIENT(Accumulate); } // namespace } // namespace caffe2
Make helloworld example also dump post data
#include "HelloWorld.h" void HelloWorld::respond() { out << "Content-type: text/html\r\n\r\n" << flush; out << "<h1>hello, world</h1>"; dumpHash(tr("Get variables"), request.getData()); dumpHash(tr("Server variables"), request.serverData()); } void HelloWorld::dumpHash(const QString& label, const QHash<QString, QString>& data) { // Print out server variables out << "<h2>" << label << "</h2>" << endl; out << "<table>" << endl; for( QHash<QString, QString>::ConstIterator it = data.constBegin(); it != data.constEnd(); ++it ) { out << "<tr><th>" << it.key() << "</th><td>" << it.value() << "</td></tr>" << endl; } out << "</table>" << endl; }
#include "HelloWorld.h" void HelloWorld::respond() { out << "Content-type: text/html\r\n\r\n" << flush; out << "<h1>hello, world</h1>"; dumpHash(tr("Get variables"), request.getData()); dumpHash(tr("Post variables"), request.postData()); dumpHash(tr("Server variables"), request.serverData()); } void HelloWorld::dumpHash(const QString& label, const QHash<QString, QString>& data) { // Print out server variables out << "<h2>" << label << "</h2>" << endl; out << "<table>" << endl; for( QHash<QString, QString>::ConstIterator it = data.constBegin(); it != data.constEnd(); ++it ) { out << "<tr><th>" << it.key() << "</th><td>" << it.value() << "</td></tr>" << endl; } out << "</table>" << endl; }
Add some tests for new exceptions.
#include <test.hpp> TEST_CASE("exceptions messages for pbf exception") { protozero::exception e; REQUIRE(std::string{e.what()} == std::string{"pbf exception"}); } TEST_CASE("exceptions messages for varint too long") { protozero::varint_too_long_exception e; REQUIRE(std::string{e.what()} == std::string{"varint too long exception"}); } TEST_CASE("exceptions messages for unknown pbf field type") { protozero::unknown_pbf_wire_type_exception e; REQUIRE(std::string{e.what()} == std::string{"unknown pbf field type exception"}); } TEST_CASE("exceptions messages for end of buffer") { protozero::end_of_buffer_exception e; REQUIRE(std::string{e.what()} == std::string{"end of buffer exception"}); }
#include <test.hpp> TEST_CASE("exceptions messages for pbf exception") { protozero::exception e; REQUIRE(std::string{e.what()} == std::string{"pbf exception"}); } TEST_CASE("exceptions messages for varint too long") { protozero::varint_too_long_exception e; REQUIRE(std::string{e.what()} == std::string{"varint too long exception"}); } TEST_CASE("exceptions messages for unknown pbf field type") { protozero::unknown_pbf_wire_type_exception e; REQUIRE(std::string{e.what()} == std::string{"unknown pbf field type exception"}); } TEST_CASE("exceptions messages for end of buffer") { protozero::end_of_buffer_exception e; REQUIRE(std::string{e.what()} == std::string{"end of buffer exception"}); } TEST_CASE("exceptions messages for invalid tag") { protozero::invalid_tag_exception e; REQUIRE(std::string{e.what()} == std::string{"invalid tag exception"}); } TEST_CASE("exceptions messages for invalid length") { protozero::invalid_length_exception e; REQUIRE(std::string{e.what()} == std::string{"invalid length exception"}); }
Revert "Forgot to update test for assign_event"
#ifdef STAN_OPENCL #include <stan/math/opencl/opencl.hpp> #include <stan/math/opencl/kernel_cl.hpp> #include <gtest/gtest.h> using stan::math::matrix_cl; using stan::math::opencl_kernels::in_buffer; using stan::math::opencl_kernels::in_out_buffer; using stan::math::opencl_kernels::internal::assign_events; using stan::math::opencl_kernels::out_buffer; TEST(assign_event, correct_vectors) { matrix_cl m; // pointers not set up to work yet; TBD if needed // matrix_cl *mp = &m; cl::Event e; assign_events<in_buffer>(e, m); EXPECT_EQ(m.in_events().size(), 1); EXPECT_EQ(m.out_events().size(), 0); assign_events<out_buffer>(e, m); EXPECT_EQ(m.in_events().size(), 1); EXPECT_EQ(m.out_events().size(), 1); assign_events<in_out_buffer>(e, m); EXPECT_EQ(m.in_events().size(), 2); EXPECT_EQ(m.out_events().size(), 2); } #endif
#ifdef STAN_OPENCL #include <stan/math/opencl/opencl.hpp> #include <stan/math/opencl/kernel_cl.hpp> #include <gtest/gtest.h> using stan::math::matrix_cl; using stan::math::opencl_kernels::in_buffer; using stan::math::opencl_kernels::in_out_buffer; using stan::math::opencl_kernels::internal::assign_events; using stan::math::opencl_kernels::out_buffer; TEST(assign_event, correct_vectors) { matrix_cl m; // pointers not set up to work yet; TBD if needed // matrix_cl *mp = &m; cl::Event e; assign_events<in_buffer>(e, m); EXPECT_EQ(m.read_events().size(), 1); EXPECT_EQ(m.write_events().size(), 0); assign_events<out_buffer>(e, m); EXPECT_EQ(m.read_events().size(), 1); EXPECT_EQ(m.write_events().size(), 1); assign_events<in_out_buffer>(e, m); EXPECT_EQ(m.read_events().size(), 2); EXPECT_EQ(m.write_events().size(), 2); } #endif
Extend log when connected to the IoT platform
#include "thingspeakSender.h" #include "ThingSpeak.h" #define USE_WIFI101_SHIELD #include "BridgeClient.h" BridgeClient client; void ThingspeakSender::init() { ThingSpeak.begin(client); Serial.println("\nconnected to ThingSpeak!"); } void ThingspeakSender::sendCounter(int counter) { //send '1' to the IoT server on the channel ThingSpeak.writeField(channelNumber, 1, counter, writeAPIKey); }
#include "thingspeakSender.h" #include "ThingSpeak.h" #define USE_WIFI101_SHIELD #include "BridgeClient.h" BridgeClient client; void ThingspeakSender::init() { ThingSpeak.begin(client); Serial.println("\nBottle-Opener is now connected to ThingSpeak!"); } void ThingspeakSender::sendCounter(int counter) { //send '1' to the IoT server on the channel ThingSpeak.writeField(channelNumber, 1, counter, writeAPIKey); }
Check if there is a valid model
#include "DirListMapModel.h" #include <QtCore/QDebug> #include <QtCore/QDir> namespace web { namespace page { namespace model { DirListMapModel::DirListMapModel(const QString & dirPath, const QString & addressPath, QObject *parent) : AbstractListModel(parent) { generateAllModels(dirPath, addressPath); } void DirListMapModel::load() { AbstractListModel * model = m_listModels.value(m_loadingModelsName); model->load(); } void DirListMapModel::unload() { AbstractListModel * model = m_listModels.value(m_loadingModelsName); model->unload(); } QList<AbstractModel *> DirListMapModel::models() { AbstractListModel * model = m_listModels.value(m_loadingModelsName); return model->models(); } void DirListMapModel::generateAllModels(const QString & dirPath, const QString & addressPath) { QDir dir(dirPath); dir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks); QStringList allFiles = dir.entryList(); for ( QString dir : allFiles ) { QString entry = addressPath + QDir::separator() + dir + QDir::separator(); QString path = dirPath + dir; AbstractListModel * model = new DirListModel(path, entry); m_listModels.insert(entry, model); } } } } }
#include "DirListMapModel.h" #include <QtCore/QDebug> #include <QtCore/QDir> namespace web { namespace page { namespace model { DirListMapModel::DirListMapModel(const QString & dirPath, const QString & addressPath, QObject *parent) : AbstractListModel(parent) { generateAllModels(dirPath, addressPath); } void DirListMapModel::load() { AbstractListModel * model = m_listModels.value(m_loadingModelsName); if (model) model->load(); } void DirListMapModel::unload() { AbstractListModel * model = m_listModels.value(m_loadingModelsName); if (model) model->unload(); } QList<AbstractModel *> DirListMapModel::models() { AbstractListModel * model = m_listModels.value(m_loadingModelsName); return (model) ? model->models() : QList<AbstractModel *>(); } void DirListMapModel::generateAllModels(const QString & dirPath, const QString & addressPath) { QDir dir(dirPath); dir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks); QStringList allFiles = dir.entryList(); for ( QString dir : allFiles ) { QString entry = addressPath + QDir::separator() + dir + QDir::separator(); QString path = dirPath + dir; AbstractListModel * model = new DirListModel(path, entry); m_listModels.insert(entry, model); } } } } }
Drop prerender abandon timeout to 3 seconds.
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/prerender/prerender_config.h" namespace prerender { Config::Config() : max_bytes(150 * 1024 * 1024), max_link_concurrency(1), max_link_concurrency_per_launcher(1), rate_limit_enabled(true), max_wait_to_launch(base::TimeDelta::FromMinutes(4)), time_to_live(base::TimeDelta::FromMinutes(5)), abandon_time_to_live(base::TimeDelta::FromSeconds(30)), default_tab_bounds(640, 480), is_overriding_user_agent(false) { } Config::~Config() { } } // namespace prerender
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/prerender/prerender_config.h" namespace prerender { Config::Config() : max_bytes(150 * 1024 * 1024), max_link_concurrency(1), max_link_concurrency_per_launcher(1), rate_limit_enabled(true), max_wait_to_launch(base::TimeDelta::FromMinutes(4)), time_to_live(base::TimeDelta::FromMinutes(5)), abandon_time_to_live(base::TimeDelta::FromSeconds(3)), default_tab_bounds(640, 480), is_overriding_user_agent(false) { } Config::~Config() { } } // namespace prerender
Increase draw value mutation rate
#include "Genes/Draw_Value_Gene.h" #include <string> #include <map> #include "Game/Color.h" #include "Utility/Random.h" class Board; std::string Draw_Value_Gene::name() const noexcept { return "Draw Value Gene"; } double Draw_Value_Gene::draw_value() const noexcept { return value_of_draw_in_centipawns; } double Draw_Value_Gene::score_board(const Board&, Piece_Color, size_t, double) const noexcept { return 0.0; } void Draw_Value_Gene::gene_specific_mutation() noexcept { value_of_draw_in_centipawns += Random::random_laplace(1.0); } void Draw_Value_Gene::adjust_properties(std::map<std::string, double>& properties) const noexcept { properties.erase("Priority - Opening"); properties.erase("Priority - Endgame"); properties["Draw Value"] = value_of_draw_in_centipawns/100.0; } void Draw_Value_Gene::load_gene_properties(const std::map<std::string, double>& properties) { value_of_draw_in_centipawns = properties.at("Draw Value")*100.; }
#include "Genes/Draw_Value_Gene.h" #include <string> #include <map> #include "Game/Color.h" #include "Utility/Random.h" class Board; std::string Draw_Value_Gene::name() const noexcept { return "Draw Value Gene"; } double Draw_Value_Gene::draw_value() const noexcept { return value_of_draw_in_centipawns; } double Draw_Value_Gene::score_board(const Board&, Piece_Color, size_t, double) const noexcept { return 0.0; } void Draw_Value_Gene::gene_specific_mutation() noexcept { value_of_draw_in_centipawns += Random::random_laplace(3.0); } void Draw_Value_Gene::adjust_properties(std::map<std::string, double>& properties) const noexcept { properties.erase("Priority - Opening"); properties.erase("Priority - Endgame"); properties["Draw Value"] = value_of_draw_in_centipawns/100.0; } void Draw_Value_Gene::load_gene_properties(const std::map<std::string, double>& properties) { value_of_draw_in_centipawns = properties.at("Draw Value")*100.; }
Add LOGGER messages as hello world to Tick and Tock.
#include "tutorial_storage_facility.h" namespace tutorial_storage { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Tutorial_storageFacility::Tutorial_storageFacility(cyclus::Context* ctx) : cyclus::Facility(ctx) {} // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - std::string Tutorial_storageFacility::str() { return Facility::str(); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Tutorial_storageFacility::Tick() {} // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Tutorial_storageFacility::Tock() {} // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - extern "C" cyclus::Agent* ConstructTutorial_storageFacility(cyclus::Context* ctx) { return new Tutorial_storageFacility(ctx); } } // namespace tutorial_storage
#include "tutorial_storage_facility.h" namespace tutorial_storage { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Tutorial_storageFacility::Tutorial_storageFacility(cyclus::Context* ctx) : cyclus::Facility(ctx) {} // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - std::string Tutorial_storageFacility::str() { return Facility::str(); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Tutorial_storageFacility::Tick() { LOG(cyclus::LEV_INFO1,"tutorial_storage") << "Hello..."; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Tutorial_storageFacility::Tock() { LOG(cyclus::LEV_INFO1,"tutorial_storage") << "World!"; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - extern "C" cyclus::Agent* ConstructTutorial_storageFacility(cyclus::Context* ctx) { return new Tutorial_storageFacility(ctx); } } // namespace tutorial_storage
Send SkDebugf through stderr and flush on Windows too.
/* * Copyright 2010 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkTypes.h" static const size_t kBufferSize = 2048; #include <stdarg.h> #include <stdio.h> #include <windows.h> void SkDebugf(const char format[], ...) { char buffer[kBufferSize + 1]; va_list args; va_start(args, format); vprintf(format, args); va_end(args); // When we crash on Windows we often are missing a lot of prints. Since we don't really care // about SkDebugf performance we flush after every print. // fflush(stdout); va_start(args, format); vsnprintf(buffer, kBufferSize, format, args); va_end(args); OutputDebugStringA(buffer); }
/* * Copyright 2010 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkTypes.h" static const size_t kBufferSize = 2048; #include <stdarg.h> #include <stdio.h> #include <windows.h> void SkDebugf(const char format[], ...) { char buffer[kBufferSize + 1]; va_list args; va_start(args, format); vfprintf(stderr, format, args); va_end(args); fflush(stderr); va_start(args, format); vsnprintf(buffer, kBufferSize, format, args); va_end(args); OutputDebugStringA(buffer); }
Set assimp flag to ignore up direction in collada files
/* * This file is part of ATLAS. It is subject to the license terms in * the LICENSE file found in the top-level directory of this distribution. * (Also avialable at http://www.apache.org/licenses/LICENSE-2.0.txt) * You may not use this file except in compliance with the License. */ #include <iostream> #include <assimp/postprocess.h> #include <assimp/scene.h> #include "AssimpImporter.hpp" namespace AssimpWorker { AssimpImporter::AssimpImporter() : importer() { return; } AssimpImporter::~AssimpImporter(){ return; } const aiScene* AssimpImporter::importSceneFromFile(std::string fileName, Log& log){ importer.SetPropertyBool(AI_CONFIG_PP_FD_REMOVE, true); //remove degenerate polys importer.SetPropertyBool(AI_CONFIG_IMPORT_NO_SKELETON_MESHES, true); //do not import skeletons importer.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_LINE | aiPrimitiveType_POINT); //Drop all primitives that aren't triangles const aiScene* scene = importer.ReadFile(fileName, aiProcessPreset_TargetRealtime_Quality); if (!scene) { log.error("Scene not imported: "+fileName); } log.error(importer.GetErrorString()); return scene; } }
/* * This file is part of ATLAS. It is subject to the license terms in * the LICENSE file found in the top-level directory of this distribution. * (Also avialable at http://www.apache.org/licenses/LICENSE-2.0.txt) * You may not use this file except in compliance with the License. */ #include <iostream> #include <assimp/postprocess.h> #include <assimp/scene.h> #include "AssimpImporter.hpp" namespace AssimpWorker { AssimpImporter::AssimpImporter() : importer() { return; } AssimpImporter::~AssimpImporter(){ return; } const aiScene* AssimpImporter::importSceneFromFile(std::string fileName, Log& log){ importer.SetPropertyBool(AI_CONFIG_PP_FD_REMOVE, true); //remove degenerate polys importer.SetPropertyBool(AI_CONFIG_IMPORT_NO_SKELETON_MESHES, true); //do not import skeletons importer.SetPropertyBool(AI_CONFIG_IMPORT_COLLADA_IGNORE_UP_DIRECTION, true); importer.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_LINE | aiPrimitiveType_POINT); //Drop all primitives that aren't triangles const aiScene* scene = importer.ReadFile(fileName, aiProcessPreset_TargetRealtime_Quality); if (!scene) { log.error("Scene not imported: "+fileName); } log.error(importer.GetErrorString()); return scene; } }
Remove redundant string comparisons in IsPathInLease()
/** * This file is part of the CernVM File System. */ #include "lease_path_util.h" namespace receiver { bool IsPathInLease(const PathString& lease, const PathString& path) { // If lease is "", any path falls within item if (!strcmp(lease.c_str(), "")) { return true; } // Is the lease string is the prefix of the path string and the next // character of the path string is a "/". if (path.StartsWith(lease) && path.GetChars()[lease.GetLength()] == '/') { return true; } // The lease is a prefix of the path and the last char of the lease is a "/" if (path.StartsWith(lease) && lease.GetChars()[lease.GetLength() - 1] == '/') { return true; } // If the path string is exactly the lease path return true (allow the // creation of the leased directory during the lease itself) if (lease == path) { return true; } return false; } } // namespace receiver
/** * This file is part of the CernVM File System. */ #include "lease_path_util.h" namespace receiver { bool IsPathInLease(const PathString& lease, const PathString& path) { // If lease is "", then any path is a subpath if (lease.GetLength() == 0) { return true; } // If the lease string is the prefix of the path string and either // the strings are identical or the separator character is a "/", // then the path is a subpath if (path.StartsWith(lease) && ((path.GetLength() == lease.GetLength()) || (path.GetChars()[lease.GetLength()] == '/') || (path.GetChars()[lease.GetLength() - 1] == '/'))) { return true; } return false; } } // namespace receiver
Update cpu times when refreshing the process list.
// Copyright (c) 2020 The Orbit Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ProcessServiceImpl.h" #include <memory> #include <string> using grpc::ServerContext; using grpc::Status; Status ProcessServiceImpl::GetProcessList(ServerContext*, const GetProcessListRequest*, GetProcessListResponse* response) { process_list_.Refresh(); for (const std::shared_ptr<Process> process : process_list_.GetProcesses()) { ProcessInfo* process_info = response->add_processes(); process_info->set_pid(process->GetID()); process_info->set_name(process->GetName()); process_info->set_cpu_usage(process->GetCpuUsage()); process_info->set_full_path(process->GetFullPath()); process_info->set_command_line(process->GetCmdLine()); process_info->set_is_64_bit(process->GetIs64Bit()); } return Status::OK; }
// Copyright (c) 2020 The Orbit Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ProcessServiceImpl.h" #include <memory> #include <string> using grpc::ServerContext; using grpc::Status; Status ProcessServiceImpl::GetProcessList(ServerContext*, const GetProcessListRequest*, GetProcessListResponse* response) { process_list_.Refresh(); process_list_.UpdateCpuTimes(); for (const std::shared_ptr<Process> process : process_list_.GetProcesses()) { ProcessInfo* process_info = response->add_processes(); process_info->set_pid(process->GetID()); process_info->set_name(process->GetName()); process_info->set_cpu_usage(process->GetCpuUsage()); process_info->set_full_path(process->GetFullPath()); process_info->set_command_line(process->GetCmdLine()); process_info->set_is_64_bit(process->GetIs64Bit()); } return Status::OK; }
Comment as to why the code for g2 actually doesn’t work yet.
#include <iostream> #include "fixed_point.hpp" int main() { auto g1 = [](double x) -> double { return (x * x + 2) / 3; }; auto g2 = [](double x) -> double { return std::sqrt(3 * x - 2); }; auto g3 = [](double x) -> double { return 3 - (2 / x); }; auto g4 = [](double x) -> double { return (x * x - 2) / (2 * x - 3); }; std::vector<std::function<double(double)>> vec {g1, g2, g3, g4}; std::vector<std::string> filenames {"g1.txt", "g2.txt", "g3.txt", "g4.txt"}; std::vector<std::string> funcnames {"g1", "g2", "g3", "g4"}; const double x0 = 0; const double abstol = 5e-7; for (auto i = 0; i < vec.size(); ++i) { fp::test_fixed_point(vec[i], x0, abstol, funcnames[i], filenames[i]); } }
#include <iostream> #include "fixed_point.hpp" int main() { auto g1 = [](double x) -> double { return (x * x + 2) / 3; }; // will result in NaNs because the value under the square root // will become negative at some point. auto g2 = [](double x) -> double { return std::sqrt(3 * x - 2); }; auto g3 = [](double x) -> double { return 3 - (2 / x); }; auto g4 = [](double x) -> double { return (x * x - 2) / (2 * x - 3); }; std::vector<std::function<double(double)>> vec {g1, g2, g3, g4}; std::vector<std::string> filenames {"g1.txt", "g2.txt", "g3.txt", "g4.txt"}; std::vector<std::string> funcnames {"g1", "g2", "g3", "g4"}; const double x0 = 0; const double abstol = 5e-7; for (auto i = 0; i < vec.size(); ++i) { fp::test_fixed_point(vec[i], x0, abstol, funcnames[i], filenames[i]); } }
Improve minimum width: Remove choose label, and use tool tip instead
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) University College London (UCL). All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "CommandLineModulesViewControls.h" #include <QIcon> #include <QSize> #include <QHBoxLayout> //----------------------------------------------------------------------------- CommandLineModulesViewControls::CommandLineModulesViewControls(QWidget *parent) { this->setupUi(parent); this->m_RunButton->setIcon(QIcon(":/CommandLineModulesResources/run.png")); this->m_RestoreDefaults->setIcon(QIcon(":/CommandLineModulesResources/undo.png")); } //----------------------------------------------------------------------------- CommandLineModulesViewControls::~CommandLineModulesViewControls() { }
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) University College London (UCL). All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "CommandLineModulesViewControls.h" #include <QIcon> #include <QSize> #include <QHBoxLayout> //----------------------------------------------------------------------------- CommandLineModulesViewControls::CommandLineModulesViewControls(QWidget *parent) { this->setupUi(parent); this->m_ChooseLabel->setVisible(false); this->m_ComboBox->setToolTip("Choose a command line module"); this->m_RunButton->setIcon(QIcon(":/CommandLineModulesResources/run.png")); this->m_RestoreDefaults->setIcon(QIcon(":/CommandLineModulesResources/undo.png")); } //----------------------------------------------------------------------------- CommandLineModulesViewControls::~CommandLineModulesViewControls() { }
Use Default style on non-Windows
#include <QApplication> #include <QQmlApplicationEngine> #include <QQuickStyle> #include "world.hpp" int main(int argc, char** argv) { QApplication app(argc, argv); app.setApplicationName("Headway"); #ifdef Q_OS_WINDOWS QQuickStyle::setStyle("Universal"); #else QQuickStyle::setStyle("Basic"); #endif QQmlApplicationEngine engine; qmlRegisterType<Headway::World>("Headway", 4, 1, "World"); engine.load(QUrl(QStringLiteral("qrc:/MainWindow.qml"))); if (engine.rootObjects().isEmpty()) return -1; return app.exec(); }
#include <QApplication> #include <QQmlApplicationEngine> #include <QQuickStyle> #include "world.hpp" int main(int argc, char** argv) { QApplication app(argc, argv); app.setApplicationName("Headway"); #ifdef Q_OS_WINDOWS QQuickStyle::setStyle("Universal"); #endif QQmlApplicationEngine engine; qmlRegisterType<Headway::World>("Headway", 4, 1, "World"); engine.load(QUrl(QStringLiteral("qrc:/MainWindow.qml"))); if (engine.rootObjects().isEmpty()) return -1; return app.exec(); }
Add an include to trigger Travis
#include <iostream> using namespace std; int main() { cout << "Hello world!" << endl; }
#include <iostream> #include <ncurses.h> using namespace std; int main() { cout << "Hello world!" << endl; }
Remove the focus rectangles that are rendered around the host/remote tree view widgets on OSX. Windows doesn't render this same focus rectangle so no change is necessary there.
#include "models/bucket.h" #include "views/session_view.h" SessionView::SessionView(Session* session, QWidget* parent) : QWidget(parent), m_session(session) { m_hostFileSystem = new QFileSystemModel(this); m_hostFileSystem->setRootPath(QDir::rootPath()); m_hostBrowser = new QTreeView; m_hostBrowser->setModel(m_hostFileSystem); m_hostBrowser->setRootIndex(m_hostFileSystem->index(QDir::rootPath())); m_remoteBrowser = new QTreeView; m_splitter = new QSplitter; m_splitter->addWidget(m_hostBrowser); m_splitter->addWidget(m_remoteBrowser); m_topLayout = new QVBoxLayout(this); m_topLayout->addWidget(m_splitter); setLayout(m_topLayout); m_client = new Client(m_session->GetHost(), m_session->GetPort(), m_session->GetAccessId(), m_session->GetSecretKey()); ds3_get_service_response* response = m_client->GetService(); Bucket* bucket = new Bucket(response); m_remoteBrowser->setModel(bucket); } SessionView::~SessionView() { delete m_client; }
#include "models/bucket.h" #include "views/session_view.h" SessionView::SessionView(Session* session, QWidget* parent) : QWidget(parent), m_session(session) { m_hostFileSystem = new QFileSystemModel(this); m_hostFileSystem->setRootPath(QDir::rootPath()); m_hostBrowser = new QTreeView; m_hostBrowser->setModel(m_hostFileSystem); m_hostBrowser->setRootIndex(m_hostFileSystem->index(QDir::rootPath())); // Remove the focus rectangle around the tree view on OSX. m_hostBrowser->setAttribute(Qt::WA_MacShowFocusRect, 0); m_remoteBrowser = new QTreeView; // Remove the focus rectangle around the tree view on OSX. m_remoteBrowser->setAttribute(Qt::WA_MacShowFocusRect, 0); m_splitter = new QSplitter; m_splitter->addWidget(m_hostBrowser); m_splitter->addWidget(m_remoteBrowser); m_topLayout = new QVBoxLayout(this); m_topLayout->addWidget(m_splitter); setLayout(m_topLayout); m_client = new Client(m_session->GetHost(), m_session->GetPort(), m_session->GetAccessId(), m_session->GetSecretKey()); ds3_get_service_response* response = m_client->GetService(); Bucket* bucket = new Bucket(response); m_remoteBrowser->setModel(bucket); } SessionView::~SessionView() { delete m_client; }
Add C++ demangle to the native symbol resolver
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "platform/globals.h" #if defined(TARGET_OS_FUCHSIA) #include "vm/native_symbol.h" #include <dlfcn.h> // NOLINT namespace dart { void NativeSymbolResolver::InitOnce() { } void NativeSymbolResolver::ShutdownOnce() { } char* NativeSymbolResolver::LookupSymbolName(uintptr_t pc, uintptr_t* start) { Dl_info info; int r = dladdr(reinterpret_cast<void*>(pc), &info); if (r == 0) { return NULL; } if (info.dli_sname == NULL) { return NULL; } if (start != NULL) { *start = reinterpret_cast<uintptr_t>(info.dli_saddr); } return strdup(info.dli_sname); } void NativeSymbolResolver::FreeSymbolName(char* name) { free(name); } } // namespace dart #endif // defined(TARGET_OS_FUCHSIA)
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "vm/globals.h" #if defined(TARGET_OS_FUCHSIA) #include "platform/memory_sanitizer.h" #include "vm/native_symbol.h" #include <cxxabi.h> // NOLINT #include <dlfcn.h> // NOLINT namespace dart { void NativeSymbolResolver::InitOnce() { } void NativeSymbolResolver::ShutdownOnce() { } char* NativeSymbolResolver::LookupSymbolName(uintptr_t pc, uintptr_t* start) { Dl_info info; int r = dladdr(reinterpret_cast<void*>(pc), &info); if (r == 0) { return NULL; } if (info.dli_sname == NULL) { return NULL; } if (start != NULL) { *start = reinterpret_cast<uintptr_t>(info.dli_saddr); } int status = 0; size_t len = 0; char* demangled = abi::__cxa_demangle(info.dli_sname, NULL, &len, &status); MSAN_UNPOISON(demangled, len); if (status == 0) { return demangled; } return strdup(info.dli_sname); } void NativeSymbolResolver::FreeSymbolName(char* name) { free(name); } } // namespace dart #endif // defined(TARGET_OS_FUCHSIA)
Consolidate main() helpers a bit.
/* * Justin's Awesome Game Engine * or * * Just Another Game Engine * * Copyright 2016 Justin White * * See included LICENSE file for distribution and reuse. */ #include <Engine.hpp> static std::unique_ptr<Engine> theGame; int success(const std::string& msg); int fail(const std::string& msg); int main(const int argc, const char** argv) { std::cout << "Start" << std::endl; theGame = std::make_unique<Engine>(argc, argv); if (not theGame->ready()) { return fail("Could not initialize Engine, quitting."); } if (not theGame->run()) { return fail("Error running Engine, quitting."); } return success("Done"); } int success(const std::string& msg) { theGame.release(); std::cout << msg << std::endl; return EXIT_SUCCESS; } int fail(const std::string& msg) { theGame.release(); std::cerr << msg << std::endl; return EXIT_FAILURE; }
/* * Justin's Awesome Game Engine * or * * Just Another Game Engine * * Copyright 2016 Justin White * * See included LICENSE file for distribution and reuse. */ #include <Engine.hpp> int done(std::unique_ptr<Engine> theGame, int exitCode, const std::string& msg = "Done"); int main(const int argc, const char** argv) { std::cout << "Start" << std::endl; auto theGame = std::make_unique<Engine>(argc, argv); if (not theGame->ready()) { return done(std::move(theGame), EXIT_FAILURE, "Could not initialize Engine, quitting."); } if (not theGame->run()) { return done(std::move(theGame), EXIT_FAILURE, "Error running Engine, quitting."); } return done(std::move(theGame), EXIT_SUCCESS); } int done(std::unique_ptr<Engine> theGame, int exitCode, const std::string& msg) { // shutdown the Engine theGame.release(); std::string fullMsg; if (exitCode == EXIT_SUCCESS) { fullMsg = "Success: " + msg; } else { //EXIT_FAILURE fullMsg = "Error: " + msg; } std::cout << fullMsg << std::endl; return exitCode; }
Update example using a TTY instead of assert. Buddy: Malc
// Copyright (c) 2014 eeGeo. All rights reserved. #import <EegeoWorld.h> #include "TrafficCongestionExample.h" namespace Examples { TrafficCongestionExample::TrafficCongestionExample( Eegeo::TrafficCongestion::ITrafficCongestionService& trafficCongestionService, Eegeo::EegeoWorld& world) : m_trafficCongestionService(trafficCongestionService), m_world(world), m_hasCalled(false) { } void TrafficCongestionExample::Update(float dt) { if(!m_hasCalled && !m_world.Initialising()) { m_hasCalled = true; bool success = m_trafficCongestionService.TrySetCongestionFor( Eegeo::Streaming::MortonKey::CreateFromString("01131232132001"), 0, Eegeo::TrafficCongestion::CongestionLevel::Heavy); Eegeo_ASSERT(success, "should've worked"); } } }
// Copyright (c) 2014 eeGeo. All rights reserved. #import <EegeoWorld.h> #include "TrafficCongestionExample.h" namespace Examples { TrafficCongestionExample::TrafficCongestionExample( Eegeo::TrafficCongestion::ITrafficCongestionService& trafficCongestionService, Eegeo::EegeoWorld& world) : m_trafficCongestionService(trafficCongestionService), m_world(world), m_hasCalled(false) { } void TrafficCongestionExample::Update(float dt) { if(!m_hasCalled && !m_world.Initialising()) { m_hasCalled = true; const int roadId = 0; Eegeo::Streaming::MortonKey key = Eegeo::Streaming::MortonKey::CreateFromString("01131232132001"); bool success = m_trafficCongestionService.TrySetCongestionFor( key, roadId, Eegeo::TrafficCongestion::CongestionLevel::Heavy); Eegeo_TTY("%s congestion level on road id %d for morton key %s\n", success ? "Successfully set" : "Failed to set", roadId, key.ToString().c_str()); } } }
Switch to the other stack trace printer
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "sky/engine/tonic/dart_error.h" #include "base/logging.h" namespace blink { namespace DartError { const char kInvalidArgument[] = "Invalid argument."; } // namespace DartError bool LogIfError(Dart_Handle handle) { if (Dart_IsError(handle)) { // Only unhandled exceptions have stacktraces. if (!Dart_ErrorHasException(handle)) { LOG(ERROR) << Dart_GetError(handle); return true; } Dart_Handle stacktrace = Dart_ErrorGetStacktrace(handle); const char* stacktrace_cstr = ""; Dart_StringToCString(Dart_ToString(stacktrace), &stacktrace_cstr); LOG(ERROR) << "Unhandled exception:"; LOG(ERROR) << stacktrace_cstr; return true; } return false; } } // namespace blink
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "sky/engine/tonic/dart_error.h" #include "base/logging.h" namespace blink { namespace DartError { const char kInvalidArgument[] = "Invalid argument."; } // namespace DartError bool LogIfError(Dart_Handle handle) { if (Dart_IsError(handle)) { LOG(ERROR) << Dart_GetError(handle); return true; } return false; } } // namespace blink
Add debug LEDs to digital platform setup.
#include "variant/digital_platform.hpp" #include "hal.h" DigitalPlatform::DigitalPlatform() { palSetPadMode(GPIOA, 4, PAL_MODE_OUTPUT_PUSHPULL); palSetPadMode(GPIOA, 5, PAL_MODE_OUTPUT_PUSHPULL); palSetPadMode(GPIOC, 4, PAL_MODE_OUTPUT_PUSHPULL); palSetPadMode(GPIOC, 5, PAL_MODE_OUTPUT_PUSHPULL); palClearPad(GPIOA, 4); palClearPad(GPIOA, 5); palClearPad(GPIOC, 4); palClearPad(GPIOC, 5); } void DigitalPlatform::set(std::uint8_t ch, bool on) { switch (ch) { case 0: palWritePad(GPIOA, 4, on); break; case 1: palWritePad(GPIOA, 5, on); break; case 2: palWritePad(GPIOC, 4, on); break; case 3: palWritePad(GPIOC, 5, on); break; default: break; } }
#include "variant/digital_platform.hpp" #include "hal.h" DigitalPlatform::DigitalPlatform() { palSetPadMode(GPIOA, 4, PAL_MODE_OUTPUT_PUSHPULL); palSetPadMode(GPIOA, 5, PAL_MODE_OUTPUT_PUSHPULL); palSetPadMode(GPIOC, 4, PAL_MODE_OUTPUT_PUSHPULL); palSetPadMode(GPIOC, 5, PAL_MODE_OUTPUT_PUSHPULL); palSetPadMode(GPIOA, 12, PAL_MODE_OUTPUT_PUSHPULL); palSetPadMode(GPIOA, 15, PAL_MODE_OUTPUT_PUSHPULL); palSetPadMode(GPIOB, 2, PAL_MODE_OUTPUT_PUSHPULL); palClearPad(GPIOA, 4); palClearPad(GPIOA, 5); palClearPad(GPIOC, 4); palClearPad(GPIOC, 5); palClearPad(GPIOA, 12); palClearPad(GPIOA, 15); palClearPad(GPIOB, 2); } void DigitalPlatform::set(std::uint8_t ch, bool on) { switch (ch) { case 0: palWritePad(GPIOA, 4, on); break; case 1: palWritePad(GPIOA, 5, on); break; case 2: palWritePad(GPIOC, 4, on); break; case 3: palWritePad(GPIOC, 5, on); break; case 4: palWritePad(GPIOA, 12, on); break; case 5: palWritePad(GPIOA, 15, on); break; case 6: palWritePad(GPIOB, 2, on); break; default: break; } }
Return !0 when qt tests fail.
#include <QTest> #include <QObject> #include "uritests.h" // This is all you need to run all the tests int main(int argc, char *argv[]) { URITests test1; QTest::qExec(&test1); }
#include <QTest> #include <QObject> #include "uritests.h" // This is all you need to run all the tests int main(int argc, char *argv[]) { bool fInvalid = false; URITests test1; if (QTest::qExec(&test1) != 0) fInvalid = true; return fInvalid; }
Simplify LightingFilter in add-free case
/* * 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); }
Change preprocessors and namespaces to c++ std library; make data types consistent (at least trying to)
#include<math.h> #include<stdio.h> /*#include<iostream> using namespace std;*/ int isPrimeBruteForce(int x) { if (x < 2) return false; double sqroot_x; sqroot_x = sqrt (x); for(int i=0; i <= sqroot_x; i++) { /* If there were only factors above the square root of x, they would be bigger than x itself. */ if (x%i==0) return 0; } return 1; } int main(int argc, char* argv[]) { int result; /* int number; cout << "Enter number to test if it's prime: "; cin >> number; result = isPrimeBruteForce(number); if (result) { cout << number << " is a prime number."; } else { cout << number << " is not a prime number."; }*/ result = isPrimeBruteForce(37); printf("Is 37 a prime number? %i", result); return 0; }
#include <iostream> #include <cmath> //using namespace std; int isPrimeBruteForce(int x) { if (x < 2) return false; double sqroot_x; double square = x; sqroot_x = std::sqrt(square); for(int i=0; i <= sqroot_x; i++) { /* If there were only factors above the square root of x, they would be bigger than x itself. */ if (x%i==0) return 0; } return 1; } int main(int argc, char* argv[]) { int result; int number; std::cout << "Enter number to test if it's prime: " << std::endl; std::cin >> number; result = isPrimeBruteForce(number); std::cout << std::endl; if (result == 1) { std::cout << number << " is a prime number." << std::endl; } else { std::cout << number << " is not a prime number." << std::endl; } /* result = isPrimeBruteForce(37); printf("Is 37 a prime number? %i", result);*/ return 0; }
Add /usr/local/cuda to the list of CUDA data directories that XLA searches by default.
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/platform/cuda_libdevice_path.h" #include <stdlib.h> #include <vector> #if !defined(PLATFORM_GOOGLE) #include "third_party/gpus/cuda/cuda_config.h" #endif #include "tensorflow/core/platform/logging.h" namespace tensorflow { std::vector<string> CandidateCudaRoots() { VLOG(3) << "CUDA root = " << TF_CUDA_TOOLKIT_PATH; return {TF_CUDA_TOOLKIT_PATH}; } } // namespace tensorflow
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/platform/cuda_libdevice_path.h" #include <stdlib.h> #include <vector> #if !defined(PLATFORM_GOOGLE) #include "third_party/gpus/cuda/cuda_config.h" #endif #include "tensorflow/core/platform/logging.h" namespace tensorflow { std::vector<string> CandidateCudaRoots() { VLOG(3) << "CUDA root = " << TF_CUDA_TOOLKIT_PATH; return {TF_CUDA_TOOLKIT_PATH, string("/usr/local/cuda")}; } } // namespace tensorflow
Add changes to first option
#include <iostream> #include "lotto.h" using namespace std; /* So I guess I should use arrays? Seems like quite good idea, hopefully it'll work as intended. * Also I'm still not sure how to avoid duplicates... */ void lotto::lotek(){ for(int i = 0; i < 6; i++) { int a = rand()%49+1; cout << '\t' << a << " " << endl; } } void lotto::multilotek() { for(int i = 0; i < 20; i++) { int a = rand()%80+1; cout << a << endl; } } void lotto::simpleMenu() { cout << "Bardzo prosty program używający generator liczb pseudolosowych.\n" << endl; cout << "1. Lotto (bez plusa i innych super szans)\n2. Multi multi (bez plusa i super szansy)\n3. Koniec (kończy program)" << endl; }
#include <iostream> #include "lotto.h" using namespace std; /* So I guess I should use arrays? Seems like quite good idea, hopefully it'll work as intended. * Also I'm still not sure how to avoid duplicates... */ void lotto::lotek(){ int lotteryPool[50]; for(int x = 0; x < 50; x++) { lotteryPool[x] = x + 1; } srand (time(NULL)); int random; int y = 0; while(y < 6) { random = rand()%50; if(lotteryPool[random] != 0) { cout << lotteryPool[random] << " "; lotteryPool[random] = 0; y++; } } } void lotto::multilotek() { for(int i = 0; i < 20; i++) { int a = rand()%80+1; cout << a << endl; } } void lotto::simpleMenu() { cout << "Bardzo prosty program używający generator liczb pseudolosowych.\n" << endl; cout << "1. Lotto (bez plusa i innych super szans)\n2. Multi multi (bez plusa i super szansy)\n3. Koniec (kończy program)" << endl; }
Change the title bar caption
/* The Halfling Project - A Graphics Engine and Projects * * The Halfling Project is the legal property of Adrian Astley * Copyright Adrian Astley 2013 */ #include "halfling/halfling_engine.h" #include "deferred_shading_demo/graphics_manager.h" #include "deferred_shading_demo/game_state_manager.h" int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { DeferredShadingDemo::GameStateManager gameStateManager; DeferredShadingDemo::GraphicsManager graphicsManager(&gameStateManager); Halfling::HalflingEngine engine(hInstance, &graphicsManager, &gameStateManager); engine.Initialize(L"Lighting Demo", 800, 600, false); engine.Run(); engine.Shutdown(); return 0; }
/* The Halfling Project - A Graphics Engine and Projects * * The Halfling Project is the legal property of Adrian Astley * Copyright Adrian Astley 2013 */ #include "halfling/halfling_engine.h" #include "deferred_shading_demo/graphics_manager.h" #include "deferred_shading_demo/game_state_manager.h" int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { DeferredShadingDemo::GameStateManager gameStateManager; DeferredShadingDemo::GraphicsManager graphicsManager(&gameStateManager); Halfling::HalflingEngine engine(hInstance, &graphicsManager, &gameStateManager); engine.Initialize(L"Deferred Shading Demo", 800, 600, false); engine.Run(); engine.Shutdown(); return 0; }
Revert "Revert "Solution for week 3, task 9""
/* Author: vpetrigo Task: 0. , , , . , 0 ( 0 , ). . Sample Input 1: 4 4 2 3 0 Sample Output 1: 4 Sample Input 2: 2 1 0 Sample Output 2: 1 */ #include <iostream> using namespace std; int main() { int n; int max = -1; int s_max = -1; while (cin >> n && n != 0) { if (max < n) { max = n; } if (n <= max && s_max < n) { s_max = n; } } cout << s_max; return 0; }
/* Author: vpetrigo Task: 0. , , , . , 0 ( 0 , ). . Sample Input 1: 4 4 2 3 0 Sample Output 1: 4 Sample Input 2: 2 1 0 Sample Output 2: 1 */ #include <iostream> using namespace std; int main() { int n; int max = -1; int s_max = -1; while (cin >> n && n != 0) { if (max <= n) { s_max = max; max = n; } else if (s_max < n) { s_max = n; } } cout << s_max; return 0; }
Enable colorful logs in tests
/* * Copyright (c) 2015 Roc authors * * 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 <CppUTest/CommandLineArguments.h> #include <CppUTest/CommandLineTestRunner.h> #include "roc_core/crash.h" #include "roc_core/exit.h" #include "roc_core/log.h" int main(int argc, const char** argv) { roc::core::CrashHandler crash_handler; CommandLineArguments args(argc, argv); if (args.parse(NULL) && args.isVerbose()) { roc::core::Logger::instance().set_level(roc::LogDebug); } else { roc::core::Logger::instance().set_level(roc::LogNone); } MemoryLeakWarningPlugin::turnOffNewDeleteOverloads(); const int code = CommandLineTestRunner::RunAllTests(argc, argv); if (code != 0) { roc::core::fast_exit(code); } return 0; }
/* * Copyright (c) 2015 Roc authors * * 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 <CppUTest/CommandLineArguments.h> #include <CppUTest/CommandLineTestRunner.h> #include "roc_core/colors.h" #include "roc_core/crash.h" #include "roc_core/exit.h" #include "roc_core/log.h" int main(int argc, const char** argv) { roc::core::CrashHandler crash_handler; CommandLineArguments args(argc, argv); if (args.parse(NULL) && args.isVerbose()) { roc::core::Logger::instance().set_level(roc::LogDebug); } else { roc::core::Logger::instance().set_level(roc::LogNone); } roc::core::Logger::instance().set_colors(roc::core::colors_available() ? roc::core::ColorsEnabled : roc::core::ColorsDisabled); MemoryLeakWarningPlugin::turnOffNewDeleteOverloads(); const int code = CommandLineTestRunner::RunAllTests(argc, argv); if (code != 0) { roc::core::fast_exit(code); } return 0; }
Implement getPostureKey of PPG node.
#include "ros/ros.h" #include "pattern_posture_generator_node.hpp" int main(int argc, char* argv[]) { ros::init(argc, argv, "pattern_posture_generator"); ros::NodeHandle nh; PatternPostureGenerator ppg(nh); ros::spin(); return 0; } PatternPostureGenerator::PatternPostureGenerator(){} PatternPostureGenerator::PatternPostureGenerator(ros::NodeHandle& nh) { if (!nh.getParam("pattern", pattern_names)) return; for (std::map<std::string, std::string >::iterator it = pattern_names.begin(); it != pattern_names.end(); it++) { std::vector<double> posture; if (!nh.getParam(std::string("pattern/").append(it->second), posture)) return; std::copy(posture.begin(), posture.end(), std::back_inserter(posture_datas[it->second])); } key_srv = nh.advertiseService("getPostureKey", &PatternPostureGenerator::getPostureKey, this); } bool PatternPostureGenerator::getPostureKey(pattern_posture_generator::PatternKeyPosture::Request& req, pattern_posture_generator::PatternKeyPosture::Response& res) { return true; }
#include "ros/ros.h" #include "pattern_posture_generator_node.hpp" int main(int argc, char* argv[]) { ros::init(argc, argv, "pattern_posture_generator"); ros::NodeHandle nh; PatternPostureGenerator ppg(nh); ros::spin(); return 0; } PatternPostureGenerator::PatternPostureGenerator(){} PatternPostureGenerator::PatternPostureGenerator(ros::NodeHandle& nh) { if (!nh.getParam("pattern", pattern_names)) return; for (std::map<std::string, std::string >::iterator it = pattern_names.begin(); it != pattern_names.end(); it++) { std::vector<double> posture; if (!nh.getParam(std::string("pattern/").append(it->second), posture)) return; std::copy(posture.begin(), posture.end(), std::back_inserter(posture_datas[it->second])); } key_srv = nh.advertiseService("getPostureKey", &PatternPostureGenerator::getPostureKey, this); } bool PatternPostureGenerator::getPostureKey(pattern_posture_generator::PatternKeyPosture::Request& req, pattern_posture_generator::PatternKeyPosture::Response& res) { std::copy(posture_datas[req.name].begin(), posture_datas[req.name].end(), std::back_inserter(res.posture)); return true; }
Disable logging in agent tests
/* * Copyright 2014-2015 Adam Chyła, adam@chyla.org * All rights reserved. Distributed under the terms of the MIT License. */ #include "../config.h" #if defined(HAVE_GTEST) && defined(HAVE_GMOCK) #include <gtest/gtest.h> int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } #else #error Cannot make tests. Google Test or Google Mock library not found. #endif // HAVE_BOOST_UNIT_TEST_FRAMEWORK
/* * Copyright 2014-2015 Adam Chyła, adam@chyla.org * All rights reserved. Distributed under the terms of the MIT License. */ #include "../config.h" #if defined(HAVE_GTEST) && defined(HAVE_GMOCK) #include <boost/log/common.hpp> #include <gtest/gtest.h> int main(int argc, char **argv) { boost::log::core::get()->set_logging_enabled(false); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } #else #error Cannot make tests. Google Test or Google Mock library not found. #endif // HAVE_BOOST_UNIT_TEST_FRAMEWORK
Enhance example to write flash
#include <cstring> #include "board.h" #include <aery32/all.h> using namespace aery; int main(void) { int errno; uint16_t page = FLASH_LAST_PAGE; char buf[512] = {'\0'}; init_board(); gpio_init_pin(LED, GPIO_OUTPUT|GPIO_HIGH); /* If page is empty, write "foo". Else read page. */ if (flashc_page_isempty(page)) { strcpy(buf, "foo"); errno = flashc_save_page(page, buf); switch (errno) { case EFLASH_PAGE_LOCKED: /* Page was locked */ break; case EFLASH_PROG_ERR: /* Programming error was accured */ break; } } else { flashc_read_page(page, buf); } for(;;) { /* Put your application code here */ } return 0; }
#include <cstring> #include "board.h" #include <aery32/all.h> using namespace aery; void lock_flash_programspace(void) { int i = FLASH_LAST_PAGE; for (; flashc_page_isempty(i); i--); for (; i >= 0; i--) { flashc_lock_page(i); } } int main(void) { int errno; uint16_t page = FLASH_LAST_PAGE; char buf[512] = {'\0'}; init_board(); gpio_init_pin(LED, GPIO_OUTPUT|GPIO_HIGH); /* Lock flash region for the uploaded program. Just to be in safe. */ lock_flash_programspace(); /* If page is empty, write "foo". Else read page. */ if (flashc_page_isempty(page)) { strcpy(buf, "foo"); errno = flashc_save_page(page, buf); switch (errno) { case EFLASH_PAGE_LOCKED: /* Page was locked */ break; case EFLASH_PROG_ERR: /* Programming error was accured */ break; } } else { flashc_read_page(page, buf); } for(;;) { /* Put your application code here */ } return 0; }
Fix compilation on clang and gcc
#include <algorithm> #include <iostream> #include <numeric> #include <string> int main() { size_t T; std::cin >> T; for (auto testCase{1u}; testCase <= T; ++testCase) { size_t N; std::cin >> N; std::string beautyScores; std::cin >> beautyScores; std::transform(beautyScores.begin(), beautyScores.end(), beautyScores.begin(), [](const auto &score) { return char{score - '0'}; }); const size_t windowSize = (N + 1) / 2; size_t numberOfWindows = N - windowSize + 1; auto sum = std::accumulate(beautyScores.begin(), beautyScores.begin() + windowSize, 0u); auto max = sum; for (auto i{0u}; i < numberOfWindows; ++i) { sum -= beautyScores[i]; sum += beautyScores[i + windowSize]; max = std::max(max, sum); } std::cout << "Case #" << testCase << ": " << max << std::endl; } }
#include <algorithm> #include <iostream> #include <numeric> #include <string> int main() { size_t T; std::cin >> T; for (auto testCase{1u}; testCase <= T; ++testCase) { size_t N; std::cin >> N; std::string beautyScores; std::cin >> beautyScores; std::transform(beautyScores.begin(), beautyScores.end(), beautyScores.begin(), [](const auto &score) { return static_cast<char>(score - '0'); }); const size_t windowSize = (N + 1) / 2; size_t numberOfWindows = N - windowSize + 1; auto sum = std::accumulate(beautyScores.begin(), beautyScores.begin() + windowSize, 0u); auto max = sum; for (auto i{0u}; i < numberOfWindows; ++i) { sum -= beautyScores[i]; sum += beautyScores[i + windowSize]; max = std::max(max, sum); } std::cout << "Case #" << testCase << ": " << max << std::endl; } }
Mark a sancov test as unsupported on x86_64h-darwin
// Tests -fsanitize-coverage=inline-8bit-counters // // REQUIRES: has_sancovcc,stable-runtime // UNSUPPORTED: i386-darwin, x86_64-darwin // // RUN: %clangxx -O0 %s -fsanitize-coverage=inline-8bit-counters 2>&1 #include <stdio.h> #include <assert.h> const char *first_counter; extern "C" void __sanitizer_cov_8bit_counters_init(const char *start, const char *end) { printf("INIT: %p %p\n", start, end); assert(end - start > 1); first_counter = start; } int main() { assert(first_counter); assert(*first_counter == 1); }
// Tests -fsanitize-coverage=inline-8bit-counters // // REQUIRES: has_sancovcc,stable-runtime // UNSUPPORTED: i386-darwin, x86_64-darwin, x86_64h-darwin // // RUN: %clangxx -O0 %s -fsanitize-coverage=inline-8bit-counters 2>&1 #include <stdio.h> #include <assert.h> const char *first_counter; extern "C" void __sanitizer_cov_8bit_counters_init(const char *start, const char *end) { printf("INIT: %p %p\n", start, end); assert(end - start > 1); first_counter = start; } int main() { assert(first_counter); assert(*first_counter == 1); }
Add fake voltage decay schemes
#include "configs/includes.h" #include "power/gb_abstract_battery.h" #include "power/gb_battery.h" #include "utilities/gb_utility.h" #include <Arduino.h> class FakeBattery : public GbAbstractBattery { public: FakeBattery() : GbAbstractBattery(1, 3.4, 3.5, 3){}; float GetVoltage() { return (sin(millis()/10000.0)/2.0) + 3.7; } }; static const int BATTERY_WAIT_TIME = 4; FakeBattery battery1 = FakeBattery(); FakeBattery battery2 = FakeBattery(); void setup() { Serial.begin(115200); Serial.println(F("Wait_for_batteries test starting...")); } void loop() { GbUtility::WaitForBatteries(BATTERY_WAIT_TIME, battery1, battery2); Serial.print("battery1 voltage: "); Serial.print(battery1.GetVoltage()); Serial.print(" | battery1 status: "); Serial.println(battery1.Status()); Serial.print("battery2 voltage: "); Serial.print(battery2.GetVoltage()); Serial.print(" | battery2 status: "); Serial.println(battery2.Status()); Serial.println("*******************************************"); delay(500); }
#include "configs/includes.h" #include "power/gb_abstract_battery.h" #include "power/gb_battery.h" #include "utilities/gb_utility.h" #include <Arduino.h> class FakeBattery : public GbAbstractBattery { private: char _scheme; public: FakeBattery(char scheme) : GbAbstractBattery(1, 3.4, 3.5, 3), _scheme(scheme) {}; float GetVoltage() { float voltage; switch (_scheme) { case 's': voltage = (sin(millis()/10000.0)/2.0) + 3.7; break; case 'a': voltage = (sin(millis()/5000.0)/2.0) + 3.7; break; default: voltage = 3.89; break; } return voltage; } }; static const int BATTERY_WAIT_TIME = 4; FakeBattery battery1 = FakeBattery('s'); FakeBattery battery2 = FakeBattery('a'); void setup() { Serial.begin(115200); Serial.println(F("Wait_for_batteries test starting...")); } void loop() { GbUtility::WaitForBatteries(BATTERY_WAIT_TIME, battery1, battery2); Serial.print("battery1 voltage: "); Serial.print(battery1.GetVoltage()); Serial.print(" | battery1 status: "); Serial.println(battery1.Status()); Serial.print("battery2 voltage: "); Serial.print(battery2.GetVoltage()); Serial.print(" | battery2 status: "); Serial.println(battery2.Status()); Serial.println("*******************************************"); delay(500); }
Set the thread to non active after waiting for it.
#include "Thread/Unix/ThreadImpl.hh" #include "Thread/ThreadException.hh" namespace LilWrapper { ThreadImpl::ThreadImpl(Thread *thread) { this->_isActive = pthread_create(&this->_thread, NULL, &ThreadImpl::entryPoint, thread) == 0; if (!this->_isActive) throw ThreadException("Thread Exception: " "Error while creating the Thread."); } ThreadImpl::~ThreadImpl() { if (this->_isActive) terminate(); } void ThreadImpl::wait() { if (this->_isActive) { if (pthread_equal(pthread_self(), this->_thread) != 0) throw ThreadException("Thread Exception: " "A thread cannot wait for itself."); if (pthread_join(this->_thread, NULL) != 0) throw ThreadException("Thread Exception: " "Error while waiting for the thread to finish."); } } void ThreadImpl::terminate() { if (this->_isActive) if (pthread_cancel(this->_thread) != 0) throw ThreadException("Thread Exception: " "Error while canceling the thread."); this->_isActive = false; } void *ThreadImpl::entryPoint(void *data) { Thread *self = static_cast<Thread *>(data); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); self->run(); return (NULL); } }
#include "Thread/Unix/ThreadImpl.hh" #include "Thread/ThreadException.hh" namespace LilWrapper { ThreadImpl::ThreadImpl(Thread *thread) { this->_isActive = pthread_create(&this->_thread, NULL, &ThreadImpl::entryPoint, thread) == 0; if (!this->_isActive) throw ThreadException("Thread Exception: " "Error while creating the Thread."); } ThreadImpl::~ThreadImpl() { if (this->_isActive) terminate(); } void ThreadImpl::wait() { if (this->_isActive) { if (pthread_equal(pthread_self(), this->_thread) != 0) throw ThreadException("Thread Exception: " "A thread cannot wait for itself."); if (pthread_join(this->_thread, NULL) != 0) throw ThreadException("Thread Exception: " "Error while waiting for the thread to finish."); } this->_isActive = false; } void ThreadImpl::terminate() { if (this->_isActive) if (pthread_cancel(this->_thread) != 0) throw ThreadException("Thread Exception: " "Error while canceling the thread."); this->_isActive = false; } void *ThreadImpl::entryPoint(void *data) { Thread *self = static_cast<Thread *>(data); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); self->run(); return (NULL); } }
Improve top-level-semicolon test a bit
// RUN: clang-cc -fsyntax-only -pedantic -std=c++0x -verify %s void foo(); void bar() { }; void wibble(); ;
// RUN: clang-cc -fsyntax-only -pedantic -std=c++0x -verify %s void foo(); void bar() { }; void wibble(); ; namespace Blah { void f() { }; void g(); }
Fix SkNWayCanvas cons call when creating null canvas.
/* * 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 "SkNullCanvas.h" #include "SkCanvas.h" #include "SKNWayCanvas.h" SkCanvas* SkCreateNullCanvas() { // An N-Way canvas forwards calls to N canvas's. When N == 0 it's // effectively a null canvas. return SkNEW(SkNWayCanvas); }
/* * 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 "SkNullCanvas.h" #include "SkCanvas.h" #include "SKNWayCanvas.h" SkCanvas* SkCreateNullCanvas() { // An N-Way canvas forwards calls to N canvas's. When N == 0 it's // effectively a null canvas. return SkNEW(SkNWayCanvas(0,0)); }
Improve test coverage of status for HTTP.
/* The MIT License (MIT) Copyright (c) 2013-2019 Winlin Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <srs_utest_http.hpp> #include <srs_http_stack.hpp>
/* The MIT License (MIT) Copyright (c) 2013-2019 Winlin Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <srs_utest_http.hpp> #include <srs_http_stack.hpp> VOID TEST(ProtoStackTest, StatusCode2Text) { EXPECT_STREQ(SRS_CONSTS_HTTP_OK_str, srs_generate_http_status_text(SRS_CONSTS_HTTP_OK).c_str()); EXPECT_STREQ("Status Unknown", srs_generate_http_status_text(999).c_str()); }
Add code to update aura and minion to summoned minions
// This code is based on Sabberstone project. // Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva // RosettaStone is hearthstone simulator using C++ with reinforcement learning. // Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon #include <Rosetta/Actions/Summon.hpp> #include <Rosetta/Games/Game.hpp> namespace RosettaStone::Generic { void Summon(Player& player, Minion* minion, int fieldPos) { player.GetField().AddMinion(*minion, fieldPos); } } // namespace RosettaStone::Generic
// This code is based on Sabberstone project. // Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva // RosettaStone is hearthstone simulator using C++ with reinforcement learning. // Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon #include <Rosetta/Actions/Summon.hpp> #include <Rosetta/Games/Game.hpp> namespace RosettaStone::Generic { void Summon(Player& player, Minion* minion, int fieldPos) { player.GetField().AddMinion(*minion, fieldPos); player.GetGame()->UpdateAura(); player.GetGame()->summonedMinions.emplace_back(minion); } } // namespace RosettaStone::Generic
Fix hello example, variable not defined
#include "sleepy_discord/sleepy_discord.h" class myClientClass : public SleepyDiscord::DiscordClient { public: using SleepyDiscord::DiscordClient::DiscordClient; void onMessage(SleepyDiscord::Message message) { if (message.startsWith("whcg hello")) sendMessage(message.channelID, "Hello " + message.author.username); } }; int main() { myClientClass client("token", SleepyDiscord::BaseDiscordClient::USER_CONTROLED_THREADS); client.run(); }
#include "sleepy_discord/sleepy_discord.h" class myClientClass : public SleepyDiscord::DiscordClient { public: using SleepyDiscord::DiscordClient::DiscordClient; void onMessage(SleepyDiscord::Message message) { if (message.startsWith("whcg hello")) sendMessage(message.channelID, "Hello " + message.author.username); } }; int main() { myClientClass client("token", SleepyDiscord::USER_CONTROLED_THREADS); client.run(); }
Fix test case compilation problem
/* * var_len_pool_test.cpp - Test suite for varrable lengthed allocation pool */ #include "test_suite.h" /* * VarLenPoolBasicTest() - This function allocates a series of memory * using an increasing sequence and then check * for correctness */ void VarLenPoolBasicTest() { PrintTestName("VarLenPoolBasicTest"); static const iter = 10; void *p_list[iter]; // Chunk size = 64 VarLenPool vlp{64}; for(int i = 1;i <= 10;i++) { p_list[i - 1] = vlp.Allocate(i); memset(p_list[i - 1], i, i); } // Verify for correctness for(int i = 1;i <= 10;i++) { char *p = reinterpret_cast<char *>(p_list[i - 1]); for(int j = 0;j < i;j++) { assert(p[j] == static_cast<char>(i)); } } return; } int main() { VarLenPoolBasicTest(); return; }
/* * var_len_pool_test.cpp - Test suite for varrable lengthed allocation pool */ #include "test_suite.h" #include "../src/VarLenPool.h" /* * VarLenPoolBasicTest() - This function allocates a series of memory * using an increasing sequence and then check * for correctness */ void VarLenPoolBasicTest() { PrintTestName("VarLenPoolBasicTest"); static const int iter = 10; void *p_list[iter]; // Chunk size = 64 VarLenPool vlp{64}; for(int i = 1;i <= 10;i++) { p_list[i - 1] = vlp.Allocate(i); memset(p_list[i - 1], i, i); } // Verify for correctness for(int i = 1;i <= 10;i++) { char *p = reinterpret_cast<char *>(p_list[i - 1]); for(int j = 0;j < i;j++) { assert(p[j] == static_cast<char>(i)); } } return; } int main() { VarLenPoolBasicTest(); return 0; }
Fix infinite recursion in GetTickCount() on Windows
// Copyright (C) 2011-2012, Zeex // // 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. #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include "timers.h" namespace sampgdk { int GetTickCount() { return GetTickCount(); } } // namespace sampgdk
// Copyright (C) 2011-2012, Zeex // // 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. #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include "timers.h" namespace sampgdk { int GetTickCount() { return ::GetTickCount(); } } // namespace sampgdk
Add frequency table to output
#include "compress.hpp" #include "huffman.hpp" std::string compress(const std::string& data) { using uch = unsigned char; std::array<uint64_t, BYTES_COUNT> freq_table; freq_table.fill(0); for(uch c : data) ++freq_table[c]; auto root = buildHuffmanTree(freq_table); auto table = buildCompressTable(root); std::string compressed; uint64_t index = 0; for(uch c : data) { for(unsigned f : table[c]) { if((index & 7) == 0) compressed.push_back(0); compressed.back() |= f << (~index & 7); ++index; } } return compressed; }
#include "compress.hpp" #include "huffman.hpp" std::string compress(const std::string& data) { using uch = unsigned char; std::array<uint64_t, BYTES_COUNT> freq_table; freq_table.fill(0); for(uch c : data) ++freq_table[c]; auto root = buildHuffmanTree(freq_table); auto table = buildCompressTable(root); std::string compressed((char*)freq_table.data(), sizeof(freq_table)); uint64_t index = 0; for(uch c : data) { for(unsigned f : table[c]) { if((index & 7) == 0) compressed.push_back(0); compressed.back() |= f << (~index & 7); ++index; } } return compressed; }
Fix an issue with the call to posix_memalign
// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved. #include "stdafx.h" #include "CreationRules.h" #include <cstdlib> void* autowiring::aligned_malloc(size_t ncb, size_t align) { void* pRetVal; if(posix_memalign(&pRetVal, ncb, align)) return nullptr; return pRetVal; } void autowiring::aligned_free(void* ptr) { free(ptr); }
// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved. #include "stdafx.h" #include "CreationRules.h" #include <cstdlib> void* autowiring::aligned_malloc(size_t ncb, size_t align) { void* pRetVal; if(posix_memalign(&pRetVal, align, ncb)) return nullptr; return pRetVal; } void autowiring::aligned_free(void* ptr) { free(ptr); }
Switch to predefined color output.
#include "shape.hpp" Shape::Shape(): name_{}, color_{0.0, 0.0, 0.0} {} Shape::Shape(std::string const& name): name_{name}, color_{1.0, 1.0, 1.0} {} Shape::Shape(Color const& color): name_{}, color_{color} {} Shape::Shape(std::string const& name, Color const& color): name_{name}, color_{color} {} std::string Shape::getName() const { return name_; } Color Shape::getColor() const { return color_; } std::ostream& Shape::print(std::ostream& os) const { os << "Shape " << name_ << ", RGB: {" << color_.r << ", " << color_.g << ", " << color_.b << "}"; return os; } std::ostream& operator<<(std::ostream& os, Shape const& s) { s.print(os); return os; }
#include "shape.hpp" Shape::Shape(): name_{}, color_{0.0, 0.0, 0.0} {} Shape::Shape(std::string const& name): name_{name}, color_{1.0, 1.0, 1.0} {} Shape::Shape(Color const& color): name_{}, color_{color} {} Shape::Shape(std::string const& name, Color const& color): name_{name}, color_{color} {} std::string Shape::getName() const { return name_; } Color Shape::getColor() const { return color_; } std::ostream& Shape::print(std::ostream& os) const { os << "Shape " << name_ << ", RGB: " << color_; return os; } /* virtual */ std::ostream& operator<<(std::ostream& os, Shape const& s) { s.print(os); return os; }
Add a define to simplify compilation
#define CATCH_CONFIG_MAIN #include "../catch.hpp" #include "../../NumberTheory/Fibonacci.cpp" TEST_CASE("Base cases", "[fibonacci]") { REQUIRE(fibonacci(0) == 0); REQUIRE(fibonacci(1) == 1); } TEST_CASE("Normal cases", "[fibonacci]") { REQUIRE(fibonacci(2) == 1); REQUIRE(fibonacci(7) == 13); REQUIRE(fibonacci(15) == 610); REQUIRE(fibonacci(18) == 2584); REQUIRE(fibonacci(23) == 28657); REQUIRE(fibonacci(50) == 12586269025); REQUIRE(fibonacci(93) == 12200160415121876738U); } TEST_CASE("Overflow cases", "[fibonacci]") { REQUIRE(fibonacci(94) == 1293530146158671551U); REQUIRE(fibonacci(1500) == 13173307912845686352U); }
#define CATCH_CONFIG_MAIN #define TEST #include "../catch.hpp" #include "../../NumberTheory/Fibonacci.cpp" TEST_CASE("Base cases", "[fibonacci]") { REQUIRE(fibonacci(0) == 0); REQUIRE(fibonacci(1) == 1); } TEST_CASE("Normal cases", "[fibonacci]") { REQUIRE(fibonacci(2) == 1); REQUIRE(fibonacci(7) == 13); REQUIRE(fibonacci(15) == 610); REQUIRE(fibonacci(18) == 2584); REQUIRE(fibonacci(23) == 28657); REQUIRE(fibonacci(50) == 12586269025); REQUIRE(fibonacci(93) == 12200160415121876738U); } TEST_CASE("Overflow cases", "[fibonacci]") { REQUIRE(fibonacci(94) == 1293530146158671551U); REQUIRE(fibonacci(1500) == 13173307912845686352U); }
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"
Revert "Attempt to fix unity builds."
#pragma push_macro("N") #undef N #include <llvm/IR/IRBuilder.h> #pragma pop_macro("N") namespace eosio { namespace chain { namespace eosvmoc { namespace LLVMJIT { llvm::Value* CreateInBoundsGEPWAR(llvm::IRBuilder<>& irBuilder, llvm::Value* Ptr, llvm::Value* v1, llvm::Value* v2) { if(!v2) return irBuilder.CreateInBoundsGEP(Ptr, v1); else return irBuilder.CreateInBoundsGEP(Ptr, {v1, v2}); } } }}}
#include <llvm/IR/IRBuilder.h> namespace eosio { namespace chain { namespace eosvmoc { namespace LLVMJIT { llvm::Value* CreateInBoundsGEPWAR(llvm::IRBuilder<>& irBuilder, llvm::Value* Ptr, llvm::Value* v1, llvm::Value* v2) { if(!v2) return irBuilder.CreateInBoundsGEP(Ptr, v1); else return irBuilder.CreateInBoundsGEP(Ptr, {v1, v2}); } } }}}
Add trasparency support for the app cover
#include <QGuiApplication> #include <QQuickView> #include <QQmlContext> #include "sailfishapplication.h" #include "servercomm.h" Q_DECL_EXPORT int main(int argc, char *argv[]) { QScopedPointer<QGuiApplication> app(Sailfish::createApplication(argc, argv)); QScopedPointer<QQuickView> view(Sailfish::createView("main.qml")); ServerComm sc; view->rootContext()->setContextProperty("serverComm", &sc); Sailfish::showView(view.data()); return app->exec(); }
#include <QGuiApplication> #include <QQuickView> #include <QQmlContext> #include <QQuickWindow> #include "sailfishapplication.h" #include "servercomm.h" Q_DECL_EXPORT int main(int argc, char *argv[]) { QQuickWindow::setDefaultAlphaBuffer(true); QScopedPointer<QGuiApplication> app(Sailfish::createApplication(argc, argv)); QScopedPointer<QQuickView> view(Sailfish::createView("main.qml")); ServerComm sc; view->rootContext()->setContextProperty("serverComm", &sc); Sailfish::showView(view.data()); return app->exec(); }
Add getting width and height from argv
#include <ncurses.h> #include "print.hpp" #include "lightsout.hpp" using namespace roadagain; int main() { initscr(); cbreak(); noecho(); start_color(); init_colors(); board b(5, 5); while (!b.is_perfect()){ char c = getch(); switch (c){ case 'h': b.move_board(0, -1); break; case 'j': b.move_board(1, 0); break; case 'k': b.move_board(-1, 0); break; case 'l': b.move_board(0, 1); break; case '\n': b.turn(); break; } } endwin(); return 0; }
#include <ncurses.h> #include <cstring> #include <cstdlib> #include "print.hpp" #include "lightsout.hpp" using namespace roadagain; int main(int argc, char** argv) { initscr(); cbreak(); noecho(); start_color(); init_colors(); int width = 5; int height = 5; for (int i = 1; i < argc; i++){ if (std::strncmp("--width=", argv[i], 8) == 0){ width = std::atoi(argv[i] + 8); } else if (std::strncmp("--height=", argv[i], 9) == 0){ height = std::atoi(argv[i] + 9); } } board b(width, height); while (!b.is_perfect()){ char c = getch(); switch (c){ case 'h': b.move_board(0, -1); break; case 'j': b.move_board(1, 0); break; case 'k': b.move_board(-1, 0); break; case 'l': b.move_board(0, 1); break; case '\n': b.turn(); break; } } endwin(); return 0; }
Remove espaço no fim da linha.
#include <iostream> using namespace std; int week_day(int day, int month, int year) { int t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4}; year -= month < 3; return (year + year / 4 - year / 100 + year / 400 + t[month - 1] + day) % 7; } int main() { int y, m, count = 0; for (y = 1901; y <= 2000; y++) { for (m = 1; m <= 12; m++) { if (week_day(1, m, y) == 0) count++; } } cout << count << endl; return 0; }
#include <iostream> using namespace std; int week_day(int day, int month, int year) { int t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4}; year -= month < 3; return (year + year / 4 - year / 100 + year / 400 + t[month - 1] + day) % 7; } int main() { int y, m, count = 0; for (y = 1901; y <= 2000; y++) { for (m = 1; m <= 12; m++) { if (week_day(1, m, y) == 0) count++; } } cout << count << endl; return 0; }
Improve c++ version of thr converter
#include <iostream> #include <vector> #include <string> using namespace std; class StringBuilder { vector<string> _buffer; StringBuilder() { // this._buffer = new List(); } public: StringBuilder append(string text) { _buffer.push_back(text); return *this; } /* StringBuilder insert(index, text) { _buffer.insert(index, text); return *this; } int length() { return toString().length(); } StringBuilder deleteCharAt(index) { var str = this.toString(); this._buffer = new List(); append(str.substring(0, index)); return this; } String toString() { return _buffer.join(""); } */ }; int main(){ vector<string> strings; strings.push_back("string 1"); strings.push_back("string 2"); vector<string>::const_iterator strIter; string result(""); for (strIter=strings.begin(); strIter!=strings.end(); strIter++) { cout << *strIter << endl; result = result + *strIter; } cout << "Basic list programm!" << endl; cout << "Together: " << result << endl; return 0; }
#include <iostream> #include <vector> #include <string> using namespace std; class StringBuilder { vector<string> _buffer; public: StringBuilder() { } StringBuilder append(string text) { _buffer.push_back(text); return *this; } StringBuilder insert(int index, string text) { _buffer.insert(_buffer.begin() + index, text); return *this; } int length() { return toString().length(); } StringBuilder deleteCharAt(int index) { string str = toString(); _buffer.clear(); append(str.substr(0, index)); return *this; } string toString() { string result(""); for (vector<string>::const_iterator strIter = _buffer.begin(); strIter != _buffer.end(); strIter++) { result = result + *strIter; } return result; } }; class MoneyToStr { public: MoneyToStr(string currency, string language, string pennies) { if (currency == "") { throw std::invalid_argument("currency is null"); } if (language == "") { throw std::invalid_argument("language is null"); } if (pennies == "") { throw std::invalid_argument("pennies is null"); } } }; int main(int argc, char *argv[]) { string amount = "123.25"; string language = "ENG"; string currency = "USD"; string pennies = "TEXT"; if (argc == 1) { cout << "Usage: MoneyToStr --amount=123.25 --language=rus|ukr|eng --currency=rur|uah|usd --pennies=text|number" << endl; } return 0; }
Change order of entities in space game
#include "gamescreen.hpp" #include "ui/menu.hpp" #include "ui/event.hpp" #include "world.hpp" #include "player.hpp" #include "scenery.hpp" namespace Space { void GameScreen::handleEvent(UI::Event const &evt) { switch (evt.type) { case UI::KeyDown: case UI::KeyUp: handleKey(evt.keyEvent()); break; default: break; } } void GameScreen::handleKey(UI::KeyEvent const &evt) { // bool state = evt.type == UI::KeyDown; switch (evt.key) { case UI::KEscape: setActive(new UI::Menu); break; case UI::KUp: break; case UI::KDown: break; case UI::KLeft: break; case UI::KRight: break; case UI::KSelect: break; default: break; } } void GameScreen::update(unsigned int ticks) { if (!world_) { world_ = new World; player_ = new Player(); world_->addThinker(player_); world_->setPlayer(player_); Scenery *s = new Scenery; s->radius = 32.0f; world_->addEntity(s); } world_->update(ticks); } void GameScreen::draw() { glClear(GL_COLOR_BUFFER_BIT); world_->draw(); } }
#include "gamescreen.hpp" #include "ui/menu.hpp" #include "ui/event.hpp" #include "world.hpp" #include "player.hpp" #include "scenery.hpp" namespace Space { void GameScreen::handleEvent(UI::Event const &evt) { switch (evt.type) { case UI::KeyDown: case UI::KeyUp: handleKey(evt.keyEvent()); break; default: break; } } void GameScreen::handleKey(UI::KeyEvent const &evt) { // bool state = evt.type == UI::KeyDown; switch (evt.key) { case UI::KEscape: setActive(new UI::Menu); break; case UI::KUp: break; case UI::KDown: break; case UI::KLeft: break; case UI::KRight: break; case UI::KSelect: break; default: break; } } void GameScreen::update(unsigned int ticks) { if (!world_) { world_ = new World; Scenery *s = new Scenery; s->radius = 32.0f; world_->addEntity(s); player_ = new Player(); world_->addThinker(player_); world_->setPlayer(player_); } world_->update(ticks); } void GameScreen::draw() { glClear(GL_COLOR_BUFFER_BIT); world_->draw(); } }
Fix Mac OS X compilation issue
#include <bitcoin/utility/timed_section.hpp> #include <bitcoin/utility/logger.hpp> namespace libbitcoin { timed_section::timed_section( const std::string& context, const std::string& section) : context_(context), section_(section) { clock_gettime(CLOCK_REALTIME, &start_); } timed_section::~timed_section() { log_debug(context_) << section_ << " " << std::fixed << elapsed(); } double timed_section::elapsed() const { timespec end; clock_gettime(CLOCK_REALTIME, &end); return 1e3 * (end.tv_sec - start_.tv_sec) + 1e-6 * (end.tv_nsec - start_.tv_nsec); } } // namespace libbitcoin
#include <bitcoin/utility/timed_section.hpp> #include <bitcoin/utility/logger.hpp> #ifdef __MACH__ #include <mach/clock.h> #include <mach/mach.h> #define CLOCK_REALTIME 0 void clock_gettime(int ign, struct timespec * ts) { clock_serv_t cclock; mach_timespec_t mts; host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); clock_get_time(cclock, &mts); mach_port_deallocate(mach_task_self(), cclock); ts->tv_sec = mts.tv_sec; ts->tv_nsec = mts.tv_nsec; } #endif namespace libbitcoin { timed_section::timed_section( const std::string& context, const std::string& section) : context_(context), section_(section) { clock_gettime(CLOCK_REALTIME, &start_); } timed_section::~timed_section() { log_debug(context_) << section_ << " " << std::fixed << elapsed(); } double timed_section::elapsed() const { timespec end; clock_gettime(CLOCK_REALTIME, &end); return 1e3 * (end.tv_sec - start_.tv_sec) + 1e-6 * (end.tv_nsec - start_.tv_nsec); } } // namespace libbitcoin
Mend bad macro in stringtable
#define CAT(X,Y) CAT_(X,Y) #define CAT_(X,Y) X ## Y #define COUNTSTRING(Stem,Val) \ Stem: \ CAT(.L_,Stem): \ .word (CAT(CAT(.L_,Stem),_end) - CAT(.L_,undefined_word) - 1) ; \ .utf32 Val ; \ .global Stem ; \ CAT(CAT(.L_,Stem),_end): \ // COUNTSTRING(undefined_word, "undefined word") COUNTSTRING(ok , "ok" ) .word 0
#define CAT(X,Y) CAT_(X,Y) #define CAT_(X,Y) X ## Y #define COUNTSTRING(Stem,Val) \ Stem: \ CAT(.L_,Stem): \ .word (CAT(CAT(.L_,Stem),_end) - CAT(.L_,Stem) - 1) ; \ .utf32 Val ; \ .global Stem ; \ CAT(CAT(.L_,Stem),_end): \ // COUNTSTRING(undefined_word, "undefined word") COUNTSTRING(ok , "ok" ) .word 0
Add warning if not all platform-specific constants are known for a given platform.
#include <string.h> #include <stdlib.h> #include <stdio.h> #include <3ds.h> #include "constants.h" #include "patches.h" #define log(...) fprintf(stderr, __VA_ARGS__) int main(int argc, char** argv) { gfxInitDefault(); consoleInit(GFX_TOP, NULL); GetVersionConstants(); PatchSrvAccess(); // ONLY UNCOMMENT AFTER CUSTOMIZING PatchProcessWrapper // svcBackdoor(PatchProcessWrapper); // log("[0x%08X] - Patched process\n", ret); // Main loop while (aptMainLoop()) { hidScanInput(); u32 kDown = hidKeysDown(); if (kDown & KEY_START) break; gspWaitForVBlank(); } gfxExit(); return 0; }
#include <string.h> #include <stdlib.h> #include <stdio.h> #include <3ds.h> #include "constants.h" #include "patches.h" #define log(...) fprintf(stderr, __VA_ARGS__) int main(int argc, char** argv) { gfxInitDefault(); consoleInit(GFX_TOP, NULL); if (!GetVersionConstants()) { log("Warning, your platform is (either fully or partially) unsupported!\n"); } PatchSrvAccess(); // ONLY UNCOMMENT AFTER CUSTOMIZING PatchProcessWrapper // svcBackdoor(PatchProcessWrapper); // log("[0x%08X] - Patched process\n", ret); // Main loop while (aptMainLoop()) { hidScanInput(); u32 kDown = hidKeysDown(); if (kDown & KEY_START) break; gspWaitForVBlank(); } gfxExit(); return 0; }