Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Fix swift_slowAlloc to respect its alignMask parameter.
//===--- Heap.cpp - Swift Language Heap Logic -----------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Implementations of the Swift heap // //===----------------------------------------------------------------------===// #include "swift/Runtime/HeapObject.h" #include "swift/Runtime/Heap.h" #include "Private.h" #include "swift/Runtime/Debug.h" #include <stdlib.h> using namespace swift; void *swift::swift_slowAlloc(size_t size, size_t alignMask) { // FIXME: use posix_memalign if alignMask is larger than the system guarantee. void *p = malloc(size); if (!p) swift::crash("Could not allocate memory."); return p; } void swift::swift_slowDealloc(void *ptr, size_t bytes, size_t alignMask) { free(ptr); }
//===--- Heap.cpp - Swift Language Heap Logic -----------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Implementations of the Swift heap // //===----------------------------------------------------------------------===// #include "swift/Runtime/HeapObject.h" #include "swift/Runtime/Heap.h" #include "Private.h" #include "swift/Runtime/Debug.h" #include <stdlib.h> using namespace swift; void *swift::swift_slowAlloc(size_t size, size_t alignMask) { void *p = AlignedAlloc(size, alignMask + 1); if (!p) swift::crash("Could not allocate memory."); return p; } void swift::swift_slowDealloc(void *ptr, size_t bytes, size_t alignMask) { AlignedFree(ptr); }
Fix bug in test; found by AddressSanitizer
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <random> // template<class RealType = double> // class piecewise_linear_distribution // param_type param() const; #include <random> #include <cassert> int main() { { typedef std::piecewise_linear_distribution<> D; typedef D::param_type P; double b[] = {10, 14, 16, 17}; double p[] = {25, 62.5, 12.5, 10}; const size_t Np = sizeof(p) / sizeof(p[0]); P pa(b, b+Np+1, p); D d(pa); assert(d.param() == pa); } }
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <random> // template<class RealType = double> // class piecewise_linear_distribution // param_type param() const; #include <random> #include <cassert> int main() { { typedef std::piecewise_linear_distribution<> D; typedef D::param_type P; double b[] = {10, 14, 16, 17}; double p[] = {25, 62.5, 12.5, 10}; const size_t Np = sizeof(p) / sizeof(p[0]); P pa(b, b+Np, p); D d(pa); assert(d.param() == pa); } }
Add more same scale ops
/* Copyright 2022 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/compiler/mlir/quantization/tensorflow/utils/quant_spec.h" #include <memory> #include "tensorflow/compiler/mlir/lite/quantization/quantization_utils.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h" namespace mlir { namespace quant { std::unique_ptr<OpQuantScaleSpec> GetTfQuantScaleSpec(Operation* op) { auto scale_spec = std::make_unique<OpQuantScaleSpec>(); if (llvm::isa< // clang-format off // go/keep-sorted start TF::ConcatV2Op, TF::IdentityOp, TF::MaxPoolOp, TF::ReshapeOp // go/keep-sorted end // clang-format on >(op)) { scale_spec->has_same_scale_requirement = true; } return scale_spec; } } // namespace quant } // namespace mlir
/* Copyright 2022 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/compiler/mlir/quantization/tensorflow/utils/quant_spec.h" #include <memory> #include "tensorflow/compiler/mlir/lite/quantization/quantization_utils.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h" namespace mlir { namespace quant { std::unique_ptr<OpQuantScaleSpec> GetTfQuantScaleSpec(Operation* op) { auto scale_spec = std::make_unique<OpQuantScaleSpec>(); if (llvm::isa< // clang-format off // go/keep-sorted start TF::ConcatV2Op, TF::IdentityOp, TF::MaxPoolOp, TF::PadV2Op, TF::ReshapeOp, TF::SqueezeOp // go/keep-sorted end // clang-format on >(op)) { scale_spec->has_same_scale_requirement = true; } return scale_spec; } } // namespace quant } // namespace mlir
Fix incorrect comment in std::function test
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // <functional> // class function<R(ArgTypes...)> // explicit function(); #include <functional> #include <cassert> int main(int, char**) { std::function<int(int)> f; assert(!f); return 0; }
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // <functional> // class function<R(ArgTypes...)> // function(); #include <functional> #include <cassert> int main(int, char**) { std::function<int(int)> f; assert(!f); return 0; }
Add offset from rosparam on kinect_broadcaster
#include <ros/ros.h> #include <tf2_ros/transform_broadcaster.h> #include <geometry_msgs/TransformStamped.h> #include <geometry_msgs/Point.h> void pointCallback(const geometry_msgs::Point::ConstPtr& msg) { static tf2_ros::TransformBroadcaster br; geometry_msgs::TransformStamped transformStamped; transformStamped.header.stamp = ros::Time::now(); transformStamped.header.frame_id = "kinect"; transformStamped.child_frame_id = "tomato"; transformStamped.transform.translation.x = msg->x; transformStamped.transform.translation.y = msg->y; transformStamped.transform.translation.z = msg->z; transformStamped.transform.rotation.x = 0; transformStamped.transform.rotation.y = 0; transformStamped.transform.rotation.z = 0; transformStamped.transform.rotation.w = 1; br.sendTransform(transformStamped); } int main(int argc, char** argv){ ros::init(argc, argv, "tomato_broadcaster"); ros::NodeHandle node; ros::Subscriber sub = node.subscribe("/tomato_point", 1, &pointCallback); ros::spin(); return 0; }
#include <ros/ros.h> #include <tf2_ros/transform_broadcaster.h> #include <geometry_msgs/TransformStamped.h> #include <geometry_msgs/Point.h> int offsetX, offsetY, offsetZ; void pointCallback(const geometry_msgs::Point::ConstPtr& msg) { static tf2_ros::TransformBroadcaster br; geometry_msgs::TransformStamped transformStamped; transformStamped.header.stamp = ros::Time::now(); transformStamped.header.frame_id = "kinect"; transformStamped.child_frame_id = "tomato"; transformStamped.transform.translation.x = msg->x + offsetX; transformStamped.transform.translation.y = msg->y + offsetY; transformStamped.transform.translation.z = msg->z + offsetZ; transformStamped.transform.rotation.x = 0; transformStamped.transform.rotation.y = 0; transformStamped.transform.rotation.z = 0; transformStamped.transform.rotation.w = 1; br.sendTransform(transformStamped); } int main(int argc, char** argv){ ros::init(argc, argv, "tomato_broadcaster"); ros::NodeHandle node; ros::NodeHandle private_node; private_node.getParam("kinect_offset_x", offsetX); private_node.getPrram("kinect_offset_y", offsetY); private_node.getPrram("kinect_offset_z", offsetZ); ros::Subscriber sub = node.subscribe("/tomato_point", 1, &pointCallback); ros::spin(); return 0; }
Fix QtQuick->Preview shortcut to start a qmlviewer
#include "qmljspreviewrunner.h" #include <projectexplorer/environment.h> #include <utils/synchronousprocess.h> #include <QtGui/QMessageBox> #include <QtGui/QApplication> #include <QDebug> namespace QmlJSEditor { namespace Internal { QmlJSPreviewRunner::QmlJSPreviewRunner(QObject *parent) : QObject(parent) { // prepend creator/bin dir to search path (only useful for special creator-qml package) const QString searchPath = QCoreApplication::applicationDirPath() + Utils::SynchronousProcess::pathSeparator() + QString(qgetenv("PATH")); m_qmlViewerDefaultPath = Utils::SynchronousProcess::locateBinary(searchPath, QLatin1String("qml")); ProjectExplorer::Environment environment = ProjectExplorer::Environment::systemEnvironment(); m_applicationLauncher.setEnvironment(environment.toStringList()); } void QmlJSPreviewRunner::run(const QString &filename) { QString errorMessage; if (!filename.isEmpty()) { m_applicationLauncher.start(ProjectExplorer::ApplicationLauncher::Gui, m_qmlViewerDefaultPath, QStringList() << filename); } else { errorMessage = "No file specified."; } if (!errorMessage.isEmpty()) QMessageBox::warning(0, tr("Failed to preview Qt Quick file"), tr("Could not preview Qt Quick (QML) file. Reason: \n%1").arg(errorMessage)); } } // namespace Internal } // namespace QmlJSEditor
#include "qmljspreviewrunner.h" #include <projectexplorer/environment.h> #include <utils/synchronousprocess.h> #include <QtGui/QMessageBox> #include <QtGui/QApplication> #include <QDebug> namespace QmlJSEditor { namespace Internal { QmlJSPreviewRunner::QmlJSPreviewRunner(QObject *parent) : QObject(parent) { // prepend creator/bin dir to search path (only useful for special creator-qml package) const QString searchPath = QCoreApplication::applicationDirPath() + Utils::SynchronousProcess::pathSeparator() + QString(qgetenv("PATH")); m_qmlViewerDefaultPath = Utils::SynchronousProcess::locateBinary(searchPath, QLatin1String("qmlviewer")); ProjectExplorer::Environment environment = ProjectExplorer::Environment::systemEnvironment(); m_applicationLauncher.setEnvironment(environment.toStringList()); } void QmlJSPreviewRunner::run(const QString &filename) { QString errorMessage; if (!filename.isEmpty()) { m_applicationLauncher.start(ProjectExplorer::ApplicationLauncher::Gui, m_qmlViewerDefaultPath, QStringList() << filename); } else { errorMessage = "No file specified."; } if (!errorMessage.isEmpty()) QMessageBox::warning(0, tr("Failed to preview Qt Quick file"), tr("Could not preview Qt Quick (QML) file. Reason: \n%1").arg(errorMessage)); } } // namespace Internal } // namespace QmlJSEditor
Add logic to this behavior
/* * GoForward.cpp * * Created on: Mar 25, 2014 * Author: user */ #include "GoBackward.h" GoBackward::GoBackward(Robot* robot):Behavior(robot) { // TODO Auto-generated constructor stub } bool GoBackward::startCondition() { return false; } void GoBackward::action() { } bool GoBackward::stopCondition() { return false; } GoBackward::~GoBackward() { // TODO Auto-generated destructor stub }
/* * GoForward.cpp * * Created on: Mar 25, 2014 * Author: user */ #include "GoBackward.h" GoBackward::GoBackward(Robot* robot):Behavior(robot), _steps_count(0) { } bool GoBackward::startCondition() { return true; } void GoBackward::action() { ++_steps_count; _robot->setSpeed(-0.1,0.0); } bool GoBackward::stopCondition() { if (_steps_count < 10) { return false; } else { _steps_count = 0; _robot->setSpeed(0.0, 0.0); return true; } } GoBackward::~GoBackward() { }
Include headers for GLEW and glfw3
#include <stdio.h> #include <iostream> /// The main function int main () { std::cout << "Hello !" << std::endl; return 0; }
#include <GL/glew.h> // to load OpenGL extensions at runtime #include <GLFW/glfw3.h> // to set up the OpenGL context and manage window lifecycle and inputs #include <stdio.h> #include <iostream> /// The main function int main () { std::cout << "Hello !" << std::endl; return 0; }
Make program usable for all locales
#include <iostream> #include "configure.hpp" #include "parsers/md_parser.hpp" #include "display_drivers/ncurses_display_driver.hpp" using namespace std; int main(int argc, char ** argv) { cout << "mdl v" << MDL_VERSION_STRING << endl; if (argc < 2) { cerr << "mdl: missing at least one argument" << endl; return 1; } MdParser parser(argv[1]); NcursesDisplayDriver drv; drv.display(parser.get_document()); return 0; }
#include "configure.hpp" #include "parsers/md_parser.hpp" #include "display_drivers/ncurses_display_driver.hpp" #include <iostream> #include <locale.h> using namespace std; int main(int argc, char ** argv) { setlocale(LC_ALL, ""); cout << "mdl v" << MDL_VERSION_STRING << endl; if (argc < 2) { cerr << "mdl: missing at least one argument" << endl; return 1; } MdParser parser(argv[1]); NcursesDisplayDriver drv; drv.display(parser.get_document()); return 0; }
Fix module registry name and description for Darwin clang-tidy module.
//===--- MiscTidyModule.cpp - clang-tidy ----------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "../ClangTidy.h" #include "../ClangTidyModule.h" #include "../ClangTidyModuleRegistry.h" #include "DispatchOnceNonstaticCheck.h" namespace clang { namespace tidy { namespace darwin { class DarwinModule : public ClangTidyModule { public: void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override { CheckFactories.registerCheck<DispatchOnceNonstaticCheck>( "darwin-dispatch-once-nonstatic"); } }; } // namespace darwin // Register the DarwinTidyModule using this statically initialized variable. static ClangTidyModuleRegistry::Add<darwin::DarwinModule> X("misc-module", "Adds miscellaneous lint checks."); // This anchor is used to force the linker to link in the generated object file // and thus register the DarwinModule. volatile int DarwinModuleAnchorSource = 0; } // namespace tidy } // namespace clang
//===--- MiscTidyModule.cpp - clang-tidy ----------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "../ClangTidy.h" #include "../ClangTidyModule.h" #include "../ClangTidyModuleRegistry.h" #include "DispatchOnceNonstaticCheck.h" namespace clang { namespace tidy { namespace darwin { class DarwinModule : public ClangTidyModule { public: void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override { CheckFactories.registerCheck<DispatchOnceNonstaticCheck>( "darwin-dispatch-once-nonstatic"); } }; } // namespace darwin // Register the DarwinTidyModule using this statically initialized variable. static ClangTidyModuleRegistry::Add<darwin::DarwinModule> X("darwin-module", "Adds Darwin-specific lint checks."); // This anchor is used to force the linker to link in the generated object file // and thus register the DarwinModule. volatile int DarwinModuleAnchorSource = 0; } // namespace tidy } // namespace clang
Update Load test to work on 32 bits.
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Simple test for a fuzzer: find interesting value of array index. #include <assert.h> #include <cstdint> #include <cstring> #include <cstddef> #include <iostream> static volatile int Sink; const int kArraySize = 1234567; int array[kArraySize]; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { if (Size < 8) return 0; size_t a = 0; memcpy(&a, Data, 8); Sink = array[a % (kArraySize + 1)]; return 0; }
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Simple test for a fuzzer: find interesting value of array index. #include <assert.h> #include <cstdint> #include <cstring> #include <cstddef> #include <iostream> static volatile int Sink; const int kArraySize = 1234567; int array[kArraySize]; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { if (Size < 8) return 0; uint64_t a = 0; memcpy(&a, Data, 8); Sink = array[a % (kArraySize + 1)]; return 0; }
Convert luma pixels from YUYV to YUV420
#include "yuyvtoyuv420.h" YUYVtoYUV420::YUYVtoYUV420(QString id, StatisticsInterface *stats, std::shared_ptr<HWResourceManager> hwResources) : Filter(id, "YUYVtoYUV420", stats, hwResources, YUYVVIDEO, YUV420VIDEO) {} void YUYVtoYUV420::process() { std::unique_ptr<Data> input = getInput(); while(input) { uint32_t finalDataSize = input->width*input->height*2; std::unique_ptr<uchar[]> yuyv_frame(new uchar[finalDataSize]); yuyv2yuv420_cpu(input->data.get(), yuyv_frame.get(), input->width, input->height); input->type = YUYVVIDEO; input->data = std::move(yuyv_frame); input->data_size = finalDataSize; sendOutput(std::move(input)); input = getInput(); } } void YUYVtoYUV420::yuyv2yuv420_cpu(uint8_t* input, uint8_t* output, uint16_t width, uint16_t height) { }
#include "yuyvtoyuv420.h" YUYVtoYUV420::YUYVtoYUV420(QString id, StatisticsInterface *stats, std::shared_ptr<HWResourceManager> hwResources) : Filter(id, "YUYVtoYUV420", stats, hwResources, YUYVVIDEO, YUV420VIDEO) {} void YUYVtoYUV420::process() { std::unique_ptr<Data> input = getInput(); while(input) { uint32_t finalDataSize = input->width*input->height + input->width*input->height/2; std::unique_ptr<uchar[]> yuyv_frame(new uchar[finalDataSize]); yuyv2yuv420_cpu(input->data.get(), yuyv_frame.get(), input->width, input->height); input->type = YUYVVIDEO; input->data = std::move(yuyv_frame); input->data_size = finalDataSize; sendOutput(std::move(input)); input = getInput(); } } void YUYVtoYUV420::yuyv2yuv420_cpu(uint8_t* input, uint8_t* output, uint16_t width, uint16_t height) { // Luma pixels for(int i = 0; i < width*height; i += 2) { output[i] = input[i*2]; output[i + 1] = input[i*2 + 2]; } }
Support batching on discard kernel
#include "scanner/api/kernel.h" #include "scanner/api/op.h" #include "scanner/util/memory.h" namespace scanner { class DiscardKernel : public BatchedKernel { public: DiscardKernel(const KernelConfig& config) : BatchedKernel(config), device_(config.devices[0]), work_item_size_(config.work_item_size) {} void execute(const BatchedColumns& input_columns, BatchedColumns& output_columns) override { i32 input_count = (i32)num_rows(input_columns[0]); u8* output_block = new_block_buffer(device_, 1, input_count); for (i32 i = 0; i < input_count; ++i) { insert_element(output_columns[0], output_block, 1); } } private: DeviceHandle device_; i32 work_item_size_; }; REGISTER_OP(Discard).input("ignore").output("dummy"); REGISTER_OP(DiscardFrame).frame_input("ignore").output("dummy"); REGISTER_KERNEL(Discard, DiscardKernel).device(DeviceType::CPU).num_devices(1); REGISTER_KERNEL(Discard, DiscardKernel).device(DeviceType::GPU).num_devices(1); REGISTER_KERNEL(DiscardFrame, DiscardKernel) .device(DeviceType::CPU) .num_devices(1); REGISTER_KERNEL(DiscardFrame, DiscardKernel) .device(DeviceType::GPU) .num_devices(1); }
#include "scanner/api/kernel.h" #include "scanner/api/op.h" #include "scanner/util/memory.h" namespace scanner { class DiscardKernel : public BatchedKernel { public: DiscardKernel(const KernelConfig& config) : BatchedKernel(config), device_(config.devices[0]), work_item_size_(config.work_item_size) {} void execute(const BatchedColumns& input_columns, BatchedColumns& output_columns) override { i32 input_count = (i32)num_rows(input_columns[0]); u8* output_block = new_block_buffer(device_, 1, input_count); for (i32 i = 0; i < input_count; ++i) { insert_element(output_columns[0], output_block, 1); } } private: DeviceHandle device_; i32 work_item_size_; }; REGISTER_OP(Discard).input("ignore").output("dummy"); REGISTER_OP(DiscardFrame).frame_input("ignore").output("dummy"); REGISTER_KERNEL(Discard, DiscardKernel).device(DeviceType::CPU).num_devices(1); REGISTER_KERNEL(Discard, DiscardKernel).device(DeviceType::GPU).num_devices(1); REGISTER_KERNEL(DiscardFrame, DiscardKernel) .device(DeviceType::CPU) .batch() .num_devices(1); REGISTER_KERNEL(DiscardFrame, DiscardKernel) .device(DeviceType::GPU) .batch() .num_devices(1); }
Fix test from r330245 on Windows.
// RUN: mkdir -p %T/read-file-config/ // RUN: cp %s %T/read-file-config/test.cpp // RUN: echo 'Checks: "-*,modernize-use-nullptr"' > %T/read-file-config/.clang-tidy // RUN: echo '[{"command": "cc -c -o test.o test.cpp", "directory": "%T/read-file-config", "file": "%T/read-file-config/test.cpp"}]' > %T/read-file-config/compile_commands.json // RUN: clang-tidy %T/read-file-config/test.cpp | not grep "warning: .*\[clang-analyzer-deadcode.DeadStores\]$" // RUN: clang-tidy -checks="-*,clang-analyzer-*" %T/read-file-config/test.cpp | grep "warning: .*\[clang-analyzer-deadcode.DeadStores\]$" void f() { int x; x = 1; x = 2; }
// RUN: mkdir -p %T/read-file-config/ // RUN: cp %s %T/read-file-config/test.cpp // RUN: echo 'Checks: "-*,modernize-use-nullptr"' > %T/read-file-config/.clang-tidy // RUN: echo '[{"command": "cc -c -o test.o test.cpp", "directory": "%/T/read-file-config", "file": "%/T/read-file-config/test.cpp"}]' > %T/read-file-config/compile_commands.json // RUN: clang-tidy %T/read-file-config/test.cpp | not grep "warning: .*\[clang-analyzer-deadcode.DeadStores\]$" // RUN: clang-tidy -checks="-*,clang-analyzer-*" %T/read-file-config/test.cpp | grep "warning: .*\[clang-analyzer-deadcode.DeadStores\]$" void f() { int x; x = 1; x = 2; }
Make the recanonicalization-for-an-out-of-line-definition test case a bit trickier
// RUN: clang-cc -fsyntax-only -verify %s // XFAIL template<typename T> struct X0 { typedef int size_type; size_type f0() const; }; template<typename T> typename X0<T>::size_type X0<T>::f0() const { }
// RUN: clang-cc -fsyntax-only -verify %s // XFAIL template<typename T> struct X1 { }; template<typename T> struct X0 { typedef int size_type; typedef T value_type; size_type f0() const; value_type *f1(); X1<value_type*> f2(); }; template<typename T> typename X0<T>::size_type X0<T>::f0() const { return 0; } template<typename U> typename X0<U>::value_type *X0<U>::f1() { return 0; }; template<typename U> X1<typename X0<U>::value_type*> X0<U>::f2() { return 0; };
Simplify imul (no need to check both signs)
#include "common.th" // c <- multiplicand // d <- multiplier // b -> product .global imul imul: pushall(h,i,j,k) i <- d == 0 jnzrel(i, L_done) h <- 1 b <- 0 j <- c >> 31 // save sign bit in j j <- -j // convert sign to flag c <- c ^ j // adjust multiplicand c <- c - j k <- d >> 31 // save sign bit in k k <- -k // convert sign to flag d <- d ^ k // adjust multiplier d <- d - k j <- j ^ k // final flip flag is in j L_top: // use constant 1 in h to combine instructions i <- d & h - 1 i <- c &~ i b <- b + i c <- c << 1 d <- d >> 1 i <- d <> 0 jnzrel(i, L_top) L_done: b <- b ^ j // adjust product for signed math b <- b - j popall(h,i,j,k) ret
#include "common.th" // c <- multiplicand // d <- multiplier // b -> product .global imul imul: pushall(h,i,j) i <- d == 0 jnzrel(i, L_done) h <- 1 b <- 0 j <- d >> 31 // save sign bit in j j <- -j // convert sign to flag d <- d ^ j // adjust multiplier d <- d - j L_top: // use constant 1 in h to combine instructions i <- d & h - 1 i <- c &~ i b <- b + i c <- c << 1 d <- d >> 1 i <- d <> 0 jnzrel(i, L_top) L_done: b <- b ^ j // adjust product for signed math b <- b - j popall(h,i,j) ret
Verify that gin_shell and hello_world.js exist.
// 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/command_line.h" #include "base/files/file_path.h" #include "base/path_service.h" #include "base/process/launch.h" #include "base/strings/string_util.h" #include "testing/gtest/include/gtest/gtest.h" base::FilePath GinShellPath() { base::FilePath dir; PathService::Get(base::DIR_EXE, &dir); return dir.AppendASCII("gin_shell"); } base::FilePath HelloWorldPath() { base::FilePath path; PathService::Get(base::DIR_SOURCE_ROOT, &path); return path .AppendASCII("gin") .AppendASCII("shell") .AppendASCII("hello_world.js"); } TEST(GinShellTest, HelloWorld) { CommandLine cmd(GinShellPath()); cmd.AppendArgPath(HelloWorldPath()); std::string output; ASSERT_TRUE(base::GetAppOutput(cmd, &output)); base::TrimWhitespaceASCII(output, base::TRIM_ALL, &output); ASSERT_EQ("Hello World", output); }
// 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/command_line.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/process/launch.h" #include "base/strings/string_util.h" #include "testing/gtest/include/gtest/gtest.h" base::FilePath GinShellPath() { base::FilePath dir; PathService::Get(base::DIR_EXE, &dir); return dir.AppendASCII("gin_shell"); } base::FilePath HelloWorldPath() { base::FilePath path; PathService::Get(base::DIR_SOURCE_ROOT, &path); return path .AppendASCII("gin") .AppendASCII("shell") .AppendASCII("hello_world.js"); } TEST(GinShellTest, HelloWorld) { base::FilePath gin_shell_path(GinShellPath()); base::FilePath hello_world_path(HelloWorldPath()); ASSERT_TRUE(base::PathExists(gin_shell_path)); ASSERT_TRUE(base::PathExists(hello_world_path)); CommandLine cmd(gin_shell_path); cmd.AppendArgPath(hello_world_path); std::string output; ASSERT_TRUE(base::GetAppOutput(cmd, &output)); base::TrimWhitespaceASCII(output, base::TRIM_ALL, &output); ASSERT_EQ("Hello World", output); }
Add missing cpp file header
#include "AddressPool.h" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/MC/MCStreamer.h" #include "llvm/Target/TargetLoweringObjectFile.h" using namespace llvm; class MCExpr; unsigned AddressPool::getIndex(const MCSymbol *Sym, bool TLS) { auto IterBool = Pool.insert(std::make_pair(Sym, AddressPoolEntry(Pool.size(), TLS))); return IterBool.first->second.Number; } // Emit addresses into the section given. void AddressPool::emit(AsmPrinter &Asm, const MCSection *AddrSection) { if (Pool.empty()) return; // Start the dwarf addr section. Asm.OutStreamer.SwitchSection(AddrSection); // Order the address pool entries by ID SmallVector<const MCExpr *, 64> Entries(Pool.size()); for (const auto &I : Pool) Entries[I.second.Number] = I.second.TLS ? Asm.getObjFileLowering().getDebugThreadLocalSymbol(I.first) : MCSymbolRefExpr::Create(I.first, Asm.OutContext); for (const MCExpr *Entry : Entries) Asm.OutStreamer.EmitValue(Entry, Asm.getDataLayout().getPointerSize()); }
//===-- llvm/CodeGen/AddressPool.cpp - Dwarf Debug Framework ---*- C++ -*--===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "AddressPool.h" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/MC/MCStreamer.h" #include "llvm/Target/TargetLoweringObjectFile.h" using namespace llvm; class MCExpr; unsigned AddressPool::getIndex(const MCSymbol *Sym, bool TLS) { auto IterBool = Pool.insert(std::make_pair(Sym, AddressPoolEntry(Pool.size(), TLS))); return IterBool.first->second.Number; } // Emit addresses into the section given. void AddressPool::emit(AsmPrinter &Asm, const MCSection *AddrSection) { if (Pool.empty()) return; // Start the dwarf addr section. Asm.OutStreamer.SwitchSection(AddrSection); // Order the address pool entries by ID SmallVector<const MCExpr *, 64> Entries(Pool.size()); for (const auto &I : Pool) Entries[I.second.Number] = I.second.TLS ? Asm.getObjFileLowering().getDebugThreadLocalSymbol(I.first) : MCSymbolRefExpr::Create(I.first, Asm.OutContext); for (const MCExpr *Entry : Entries) Asm.OutStreamer.EmitValue(Entry, Asm.getDataLayout().getPointerSize()); }
Revert "define cpu_* if not set"
#include "CPU.h" #if defined(__x86_64__) || defined(__i386__) #include <cpuid.h> #endif #include "Log.h" #ifndef bit_AES #define bit_AES (1 << 25) #endif #ifndef bit_AVX #define bit_AVX (1 << 28) #endif namespace i2p { namespace cpu { bool aesni = false; bool avx = false; void Detect() { #if defined(__x86_64__) || defined(__i386__) int info[4]; __cpuid(0, info[0], info[1], info[2], info[3]); if (info[0] >= 0x00000001) { __cpuid(0x00000001, info[0], info[1], info[2], info[3]); aesni = info[2] & bit_AES; // AESNI avx = info[2] & bit_AVX; // AVX } #endif if(aesni) { LogPrint(eLogInfo, "AESNI enabled"); } if(avx) { LogPrint(eLogInfo, "AVX enabled"); } } } }
#include "CPU.h" #if defined(__x86_64__) || defined(__i386__) #include <cpuid.h> #endif #include "Log.h" namespace i2p { namespace cpu { bool aesni = false; bool avx = false; void Detect() { #if defined(__x86_64__) || defined(__i386__) int info[4]; __cpuid(0, info[0], info[1], info[2], info[3]); if (info[0] >= 0x00000001) { __cpuid(0x00000001, info[0], info[1], info[2], info[3]); aesni = info[2] & bit_AES; // AESNI avx = info[2] & bit_AVX; // AVX } #endif if(aesni) { LogPrint(eLogInfo, "AESNI enabled"); } if(avx) { LogPrint(eLogInfo, "AVX enabled"); } } } }
Convert sandbox NOTIMPLEMENTED()s into a bug.
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/renderer_main_platform_delegate.h" #include "base/debug_util.h" // This is a no op class because we do not have a sandbox on linux. RendererMainPlatformDelegate::RendererMainPlatformDelegate( const MainFunctionParams& parameters) : parameters_(parameters) { } RendererMainPlatformDelegate::~RendererMainPlatformDelegate() { } void RendererMainPlatformDelegate::PlatformInitialize() { } void RendererMainPlatformDelegate::PlatformUninitialize() { } bool RendererMainPlatformDelegate::InitSandboxTests(bool no_sandbox) { NOTIMPLEMENTED(); return true; } bool RendererMainPlatformDelegate::EnableSandbox() { NOTIMPLEMENTED(); return true; } void RendererMainPlatformDelegate::RunSandboxTests() { NOTIMPLEMENTED(); }
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/renderer_main_platform_delegate.h" #include "base/debug_util.h" // This is a no op class because we do not have a sandbox on linux. RendererMainPlatformDelegate::RendererMainPlatformDelegate( const MainFunctionParams& parameters) : parameters_(parameters) { } RendererMainPlatformDelegate::~RendererMainPlatformDelegate() { } void RendererMainPlatformDelegate::PlatformInitialize() { } void RendererMainPlatformDelegate::PlatformUninitialize() { } bool RendererMainPlatformDelegate::InitSandboxTests(bool no_sandbox) { // We have no sandbox. // http://code.google.com/p/chromium/issues/detail?id=8081 return true; } bool RendererMainPlatformDelegate::EnableSandbox() { // We have no sandbox. // http://code.google.com/p/chromium/issues/detail?id=8081 return true; } void RendererMainPlatformDelegate::RunSandboxTests() { // We have no sandbox. // http://code.google.com/p/chromium/issues/detail?id=8081 }
Fix boos usage on mock test
/** * \file * \brief Unit Test for Thermal Mock Config * * \author Uilian Ries <uilianries@gmail.com> */ /** Should not link with unit test lib */ #define BOOST_TEST_NO_LIB #include <string> #include <boost/filesystem.hpp> #include <boost/test/unit_test.hpp> #include <Poco/File.h> #include "bbbgpio/thermal_config.hpp" namespace bbb { namespace test { /** * \brief Test mock config gpio class. * Create a fake gpio fd */ BOOST_AUTO_TEST_SUITE(MockGPIO) BOOST_AUTO_TEST_CASE(FileValidation) { bbb::gpio::thermal_config thermal_config; auto&& thermal_config_path = thermal_config.get_config_file().toString(); BOOST_CHECK(boost::filesystem::exists(thermal_config_path)); BOOST_CHECK(boost::filesystem::is_regular_file(thermal_config_path)); Poco::File file(thermal_config_path); BOOST_CHECK(file.canRead()); BOOST_CHECK(file.canWrite()); } BOOST_AUTO_TEST_SUITE_END() // BOOST_AUTO_TEST_SUITE(MockGPIO) } // namespace test } // namespace bbb
/** * \file * \brief Unit Test for Thermal Mock Config * * \author Uilian Ries <uilianries@gmail.com> */ /** Should not link with unit test lib */ #define BOOST_TEST_NO_LIB #include <string> #include <boost/filesystem.hpp> #include <boost/test/unit_test.hpp> #include <boost/filesystem/operations.hpp> #include "bbbgpio/thermal_config.hpp" namespace bbb { namespace test { /** * \brief Test mock config gpio class. * Create a fake gpio fd */ BOOST_AUTO_TEST_SUITE(MockGPIO) BOOST_AUTO_TEST_CASE(FileValidation) { bbb::gpio::thermal_config thermal_config; auto&& thermal_config_path = thermal_config.get_config_file(); BOOST_CHECK(boost::filesystem::exists(thermal_config_path)); BOOST_CHECK(boost::filesystem::is_regular_file(thermal_config_path)); } BOOST_AUTO_TEST_SUITE_END() // BOOST_AUTO_TEST_SUITE(MockGPIO) } // namespace test } // namespace bbb
Throw an exception when the user attempt to create more than one instance of QApplication.
// Borrowed reference to QtGui module extern PyObject* moduleQtGui; int SbkQApplication_Init(PyObject* self, PyObject* args, PyObject*) { int numArgs = PyTuple_GET_SIZE(args); if (numArgs != 1) { PyErr_BadArgument(); return -1; } char** argv; int argc; if (!PySequence_to_argc_argv(PyTuple_GET_ITEM(args, 0), &argc, &argv)) { PyErr_BadArgument(); return -1; } SbkBaseWrapper_setCptr(self, new QApplication(argc, argv)); SbkBaseWrapper_setValidCppObject(self, 1); Shiboken::BindingManager::instance().registerWrapper(reinterpret_cast<SbkBaseWrapper*>(self)); // Verify if qApp is in main module const char QAPP_MACRO[] = "qApp"; PyObject* localsDict = PyEval_GetLocals(); if (localsDict) { PyObject* qAppObj = PyDict_GetItemString(localsDict, QAPP_MACRO); if (qAppObj) PyDict_SetItemString(localsDict, QAPP_MACRO, self); } PyObject_SetAttrString(moduleQtGui, QAPP_MACRO, self); return 1; }
// Borrowed reference to QtGui module extern PyObject* moduleQtGui; int SbkQApplication_Init(PyObject* self, PyObject* args, PyObject*) { if (QApplication::instance()) { PyErr_SetString(PyExc_RuntimeError, "A QApplication instance already exists."); return -1; } int numArgs = PyTuple_GET_SIZE(args); if (numArgs != 1) { PyErr_BadArgument(); return -1; } char** argv; int argc; if (!PySequence_to_argc_argv(PyTuple_GET_ITEM(args, 0), &argc, &argv)) { PyErr_BadArgument(); return -1; } SbkBaseWrapper_setCptr(self, new QApplication(argc, argv)); SbkBaseWrapper_setValidCppObject(self, 1); Shiboken::BindingManager::instance().registerWrapper(reinterpret_cast<SbkBaseWrapper*>(self)); // Verify if qApp is in main module const char QAPP_MACRO[] = "qApp"; PyObject* localsDict = PyEval_GetLocals(); if (localsDict) { PyObject* qAppObj = PyDict_GetItemString(localsDict, QAPP_MACRO); if (qAppObj) PyDict_SetItemString(localsDict, QAPP_MACRO, self); } PyObject_SetAttrString(moduleQtGui, QAPP_MACRO, self); return 1; }
Expand bench to cover no-draw SkPictures too.
/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ // A benchmark designed to isolate the constant overheads of picture recording. // We record a very tiny (one op) picture; one op is better than none, as it forces // us to allocate memory to store that op... we can't just cheat by holding onto NULLs. #include "Benchmark.h" #include "SkCanvas.h" #include "SkPictureRecorder.h" struct PictureOverheadBench : public Benchmark { const char* onGetName() override { return "picture_overhead"; } bool isSuitableFor(Backend backend) override { return backend == kNonRendering_Backend; } void onDraw(const int loops, SkCanvas*) override { SkPictureRecorder rec; for (int i = 0; i < loops; i++) { SkCanvas* c = rec.beginRecording(SkRect::MakeWH(2000,3000)); c->drawRect(SkRect::MakeXYWH(10, 10, 1000, 1000), SkPaint()); SkAutoTUnref<SkPicture> pic(rec.endRecordingAsPicture()); } } }; DEF_BENCH(return new PictureOverheadBench;)
/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ // A benchmark designed to isolate the constant overheads of picture recording. // We record an empty picture and a picture with one draw op to force memory allocation. #include "Benchmark.h" #include "SkCanvas.h" #include "SkPictureRecorder.h" template <bool kDraw> struct PictureOverheadBench : public Benchmark { const char* onGetName() override { return kDraw ? "picture_overhead_draw" : "picture_overhead_nodraw"; } bool isSuitableFor(Backend backend) override { return backend == kNonRendering_Backend; } void onDraw(const int loops, SkCanvas*) override { SkPictureRecorder rec; for (int i = 0; i < loops; i++) { rec.beginRecording(SkRect::MakeWH(2000,3000)); if (kDraw) { rec.getRecordingCanvas()->drawRect(SkRect::MakeXYWH(10, 10, 1000, 1000), SkPaint()); } SkAutoTUnref<SkPicture> pic(rec.endRecordingAsPicture()); } } }; DEF_BENCH(return (new PictureOverheadBench<false>);) DEF_BENCH(return (new PictureOverheadBench< true>);)
Include execinfo.h only on __GLIBC__
// StackTrace.cpp // Implements the functions to print current stack traces #include "Globals.h" #include "StackTrace.h" #ifdef _WIN32 #include "../StackWalker.h" #else #include <execinfo.h> #include <unistd.h> #endif // FreeBSD uses size_t for the return type of backtrace() #if defined(__FreeBSD__) && (__FreeBSD__ >= 10) #define btsize size_t #else #define btsize int #endif void PrintStackTrace(void) { #ifdef _WIN32 // Reuse the StackWalker from the LeakFinder project already bound to MCS // Define a subclass of the StackWalker that outputs everything to stdout class PrintingStackWalker : public StackWalker { virtual void OnOutput(LPCSTR szText) override { puts(szText); } } sw; sw.ShowCallstack(); #else #ifdef __GLIBC__ // Use the backtrace() function to get and output the stackTrace: // Code adapted from http://stackoverflow.com/questions/77005/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes void * stackTrace[30]; btsize numItems = backtrace(stackTrace, ARRAYCOUNT(stackTrace)); backtrace_symbols_fd(stackTrace, numItems, STDERR_FILENO); #endif #endif }
// StackTrace.cpp // Implements the functions to print current stack traces #include "Globals.h" #include "StackTrace.h" #ifdef _WIN32 #include "../StackWalker.h" #else #ifdef __GLIBC__ #include <execinfo.h> #endif #include <unistd.h> #endif // FreeBSD uses size_t for the return type of backtrace() #if defined(__FreeBSD__) && (__FreeBSD__ >= 10) #define btsize size_t #else #define btsize int #endif void PrintStackTrace(void) { #ifdef _WIN32 // Reuse the StackWalker from the LeakFinder project already bound to MCS // Define a subclass of the StackWalker that outputs everything to stdout class PrintingStackWalker : public StackWalker { virtual void OnOutput(LPCSTR szText) override { puts(szText); } } sw; sw.ShowCallstack(); #else #ifdef __GLIBC__ // Use the backtrace() function to get and output the stackTrace: // Code adapted from http://stackoverflow.com/questions/77005/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes void * stackTrace[30]; btsize numItems = backtrace(stackTrace, ARRAYCOUNT(stackTrace)); backtrace_symbols_fd(stackTrace, numItems, STDERR_FILENO); #endif #endif }
Add -f flag option to RPi version of he example
#include "ofMain.h" #include "ofApp.h" int main() { #ifdef TARGET_RASPBERRY_PI ofSetupOpenGL(600, 500, OF_FULLSCREEN); #else ofSetupOpenGL(600, 500, OF_WINDOW); #endif ofRunApp(new ofApp()); }
#include "ofMain.h" #include "ofApp.h" #include <string> #ifdef TARGET_RASPBERRY_PI // Accept arguments in the Pi version int main(int argc, char* argv[]) { bool fullscreen = false; if (argc > 0) { std::string fullscreenFlag = "-f"; for (int i = 0; i < argc; i++) { if (strcmp(argv[i], fullscreenFlag.c_str()) == 0) { fullscreen = true; break; } } } if (fullscreen) { ofSetupOpenGL(600, 500, OF_FULLSCREEN); } else { ofSetupOpenGL(800, 450, OF_WINDOW); } ofRunApp(new ofApp()); } #else int main() { ofSetupOpenGL(800, 600, OF_WINDOW); ofRunApp(new ofApp()); } #endif
Update tcp server example to accept cmd args
#include <iostream> #include <tcp_server.hpp> int main() { TcpServer server(12001); server.Listen(2000); return 0; }
#include <iostream> #include <tcp/tcp_server.hpp> #include <sstream> int main(int argc, char** argv) { //initalize default port number and max connection cout int port = 12001, max_connection_count= 1000; // check if there are any passed arguments if(argc > 1) { // initialize string stream from argument std::istringstream arg_stream(argv[1]); // bind arguments stream to port int variable if valid if ( !(arg_stream >> port) ) std::cerr << "Invalid number " << argv[1] << '\n'; } // create server instance with specified port number TcpServer server(port); //start listening to connections server.Listen(max_connection_count); return 0; }
Add a little more testing for default arguments of constructors in a class template
// RUN: clang-cc -fsyntax-only -verify %s struct S { }; template<typename T> void f1(T a, T b = 10) { } // expected-error{{cannot initialize 'b' with an rvalue of type 'int'}} template<typename T> void f2(T a, T b = T()) { } template<typename T> void f3(T a, T b = T() + T()); // expected-error{{invalid operands to binary expression ('struct S' and 'struct S')}} void g() { f1(10); f1(S()); // expected-note{{in instantiation of default argument for 'f1<struct S>' required here}} f2(10); f2(S()); f3(10); f3(S()); // expected-note{{in instantiation of default argument for 'f3<struct S>' required here}} } template<typename T> struct F { F(T t = 10); }; void g2() { F<int> f; } template<typename T> struct G { G(T) {} }; void s(G<int> flags = 10) { }
// RUN: clang-cc -fsyntax-only -verify %s struct S { }; template<typename T> void f1(T a, T b = 10) { } // expected-error{{cannot initialize 'b' with an rvalue of type 'int'}} template<typename T> void f2(T a, T b = T()) { } template<typename T> void f3(T a, T b = T() + T()); // expected-error{{invalid operands to binary expression ('struct S' and 'struct S')}} void g() { f1(10); f1(S()); // expected-note{{in instantiation of default argument for 'f1<struct S>' required here}} f2(10); f2(S()); f3(10); f3(S()); // expected-note{{in instantiation of default argument for 'f3<struct S>' required here}} } template<typename T> struct F { F(T t = 10); }; struct FD : F<int> { }; void g2() { F<int> f; FD fd; } template<typename T> struct G { G(T) {} }; void s(G<int> flags = 10) { }
Remove outdated bucket space assertion
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "servicelayercomponent.h" #include <vespa/storage/common/content_bucket_space_repo.h> #include <vespa/storage/common/nodestateupdater.h> #include <vespa/vdslib/distribution/distribution.h> using document::BucketSpace; namespace storage { const ContentBucketSpaceRepo & ServiceLayerComponent::getBucketSpaceRepo() const { assert(_bucketSpaceRepo != nullptr); return *_bucketSpaceRepo; } StorBucketDatabase& ServiceLayerComponent::getBucketDatabase(BucketSpace bucketSpace) const { assert(bucketSpace == BucketSpace::placeHolder()); assert(_bucketSpaceRepo != nullptr); return _bucketSpaceRepo->get(bucketSpace).bucketDatabase(); } uint16_t ServiceLayerComponent::getIdealPartition(const document::Bucket& bucket) const { return _bucketSpaceRepo->get(bucket.getBucketSpace()).getDistribution()->getIdealDisk( *getStateUpdater().getReportedNodeState(), getIndex(), bucket.getBucketId(), lib::Distribution::IDEAL_DISK_EVEN_IF_DOWN); } uint16_t ServiceLayerComponent::getPreferredAvailablePartition( const document::Bucket& bucket) const { return _bucketSpaceRepo->get(bucket.getBucketSpace()).getDistribution()->getPreferredAvailableDisk( *getStateUpdater().getReportedNodeState(), getIndex(), bucket.getBucketId()); } } // storage
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "servicelayercomponent.h" #include <vespa/storage/common/content_bucket_space_repo.h> #include <vespa/storage/common/nodestateupdater.h> #include <vespa/vdslib/distribution/distribution.h> using document::BucketSpace; namespace storage { const ContentBucketSpaceRepo & ServiceLayerComponent::getBucketSpaceRepo() const { assert(_bucketSpaceRepo != nullptr); return *_bucketSpaceRepo; } StorBucketDatabase& ServiceLayerComponent::getBucketDatabase(BucketSpace bucketSpace) const { assert(_bucketSpaceRepo != nullptr); return _bucketSpaceRepo->get(bucketSpace).bucketDatabase(); } uint16_t ServiceLayerComponent::getIdealPartition(const document::Bucket& bucket) const { return _bucketSpaceRepo->get(bucket.getBucketSpace()).getDistribution()->getIdealDisk( *getStateUpdater().getReportedNodeState(), getIndex(), bucket.getBucketId(), lib::Distribution::IDEAL_DISK_EVEN_IF_DOWN); } uint16_t ServiceLayerComponent::getPreferredAvailablePartition( const document::Bucket& bucket) const { return _bucketSpaceRepo->get(bucket.getBucketSpace()).getDistribution()->getPreferredAvailableDisk( *getStateUpdater().getReportedNodeState(), getIndex(), bucket.getBucketId()); } } // storage
Use -emit-llvm-only, to avoid leaving a temp around.
// RUN: %clang_cc1 %s -emit-llvm namespace test0 { template <typename T> struct X { virtual void foo(); virtual void bar(); virtual void baz(); }; template <typename T> void X<T>::foo() {} template <typename T> void X<T>::bar() {} template <typename T> void X<T>::baz() {} template <> void X<char>::foo() {} template <> void X<char>::bar() {} } namespace test1 { template <typename T> struct X { virtual void foo(); virtual void bar(); virtual void baz(); }; template <typename T> void X<T>::foo() {} template <typename T> void X<T>::bar() {} template <typename T> void X<T>::baz() {} template <> void X<char>::bar() {} template <> void X<char>::foo() {} }
// RUN: %clang_cc1 %s -emit-llvm-only namespace test0 { template <typename T> struct X { virtual void foo(); virtual void bar(); virtual void baz(); }; template <typename T> void X<T>::foo() {} template <typename T> void X<T>::bar() {} template <typename T> void X<T>::baz() {} template <> void X<char>::foo() {} template <> void X<char>::bar() {} } namespace test1 { template <typename T> struct X { virtual void foo(); virtual void bar(); virtual void baz(); }; template <typename T> void X<T>::foo() {} template <typename T> void X<T>::bar() {} template <typename T> void X<T>::baz() {} template <> void X<char>::bar() {} template <> void X<char>::foo() {} }
Add portable (no-op) version of StatefulNnApiDelegate
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/delegates/nnapi/nnapi_delegate.h" namespace tflite { // Return a non-functional NN API Delegate struct. TfLiteDelegate* NnApiDelegate() { static TfLiteDelegate delegate = [] { TfLiteDelegate delegate = TfLiteDelegateCreate(); delegate.Prepare = [](TfLiteContext* context, TfLiteDelegate* delegate) -> TfLiteStatus { // Silently succeed without modifying the graph. return kTfLiteOk; }; return delegate; }(); return &delegate; } } // namespace tflite
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/delegates/nnapi/nnapi_delegate.h" namespace tflite { // Return a non-functional NN API Delegate struct. TfLiteDelegate* NnApiDelegate() { static StatefulNnApiDelegate* delegate = new StatefulNnApiDelegate(); return delegate; } StatefulNnApiDelegate::StatefulNnApiDelegate(Options /* options */) : StatefulNnApiDelegate() {} StatefulNnApiDelegate::StatefulNnApiDelegate() : TfLiteDelegate(TfLiteDelegateCreate()) { Prepare = DoPrepare; } TfLiteStatus StatefulNnApiDelegate::DoPrepare(TfLiteContext* /* context */, TfLiteDelegate* /* delegate */) { return kTfLiteOk; } } // namespace tflite
Add enum definitions for ADC's.
#include <avr/io.h> #include <avr/interrupt.h> /* _____ ___ ___ RESET -| U |- VCC (Mode) ADC3 -| AT13A |- ADC1 (Depth) (Speed) ADC2 -| |- OC0B (PWM Output) GND -|_______|- PB0 (Button) */ int main() { while(1) { cli(); } }
#include <avr/io.h> #include <avr/interrupt.h> /* _____ ___ ___ RESET -| U |- VCC (Mode) ADC3 -| AT13A |- ADC1 (Depth) (Speed) ADC2 -| |- OC0B (PWM Output) GND -|_______|- PB0 (Button) */ enum { ADC_DEPTH = 1, ADC_SPEED = 2, ADC_MODE = 3, }; int main() { while(1) { cli(); } }
Fix function signature in ATenOp for at::Half Set function (GPU version)
/** * Copyright (c) 2016-present, Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "aten_op.h" #include "caffe2/core/context_gpu.h" namespace caffe2 { REGISTER_CUDA_OPERATOR(ATen, ATenOp<CUDAContext>); template<> at::Backend ATenOp<CUDAContext>::backend() const { return at::kCUDA; } namespace math { template<> void Set<at::Half,CUDAContext>(TIndex N, at::Half h, at::Half* v, CUDAContext * c) { Set(0, h.x, (uint16_t*) v, c); } } }
/** * Copyright (c) 2016-present, Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "aten_op.h" #include "caffe2/core/context_gpu.h" namespace caffe2 { REGISTER_CUDA_OPERATOR(ATen, ATenOp<CUDAContext>); template<> at::Backend ATenOp<CUDAContext>::backend() const { return at::kCUDA; } namespace math { template<> void Set<at::Half,CUDAContext>(const size_t N, const at::Half h, at::Half* v, CUDAContext * c) { Set(0, h.x, (uint16_t*) v, c); } } }
Adjust classificator theshold for opentable.
#include "generator/sponsored_scoring.hpp" #include "generator/opentable_dataset.hpp" #include "generator/feature_builder.hpp" namespace { // Calculated with tools/python/booking_hotels_quality.py. double constexpr kOptimalThreshold = 0.304875; } // namespace namespace generator { namespace sponsored_scoring { template <> double MatchStats<OpentableRestaurant>::GetMatchingScore() const { // TODO(mgsergio): Use tuner to get optimal function. return m_linearNormDistanceScore * m_nameSimilarityScore; } template <> bool MatchStats<OpentableRestaurant>::IsMatched() const { return GetMatchingScore() > kOptimalThreshold; } template <> MatchStats<OpentableRestaurant> Match(OpentableRestaurant const & h, FeatureBuilder1 const & fb) { MatchStats<OpentableRestaurant> score; auto const fbCenter = MercatorBounds::ToLatLon(fb.GetKeyPoint()); auto const distance = ms::DistanceOnEarth(fbCenter.lat, fbCenter.lon, h.m_lat, h.m_lon); score.m_linearNormDistanceScore = impl::GetLinearNormDistanceScore(distance, OpentableDataset::kDistanceLimitInMeters); score.m_nameSimilarityScore = impl::GetNameSimilarityScore(h.m_name, fb.GetName(StringUtf8Multilang::kDefaultCode)); return score; } } // namespace sponsored_scoring } // namespace generator
#include "generator/sponsored_scoring.hpp" #include "generator/opentable_dataset.hpp" #include "generator/feature_builder.hpp" namespace { // Calculated with tools/python/booking_hotels_quality.py. double constexpr kOptimalThreshold = 0.312887; } // namespace namespace generator { namespace sponsored_scoring { template <> double MatchStats<OpentableRestaurant>::GetMatchingScore() const { // TODO(mgsergio): Use tuner to get optimal function. return m_linearNormDistanceScore * m_nameSimilarityScore; } template <> bool MatchStats<OpentableRestaurant>::IsMatched() const { return GetMatchingScore() > kOptimalThreshold; } template <> MatchStats<OpentableRestaurant> Match(OpentableRestaurant const & h, FeatureBuilder1 const & fb) { MatchStats<OpentableRestaurant> score; auto const fbCenter = MercatorBounds::ToLatLon(fb.GetKeyPoint()); auto const distance = ms::DistanceOnEarth(fbCenter.lat, fbCenter.lon, h.m_lat, h.m_lon); score.m_linearNormDistanceScore = impl::GetLinearNormDistanceScore(distance, OpentableDataset::kDistanceLimitInMeters); score.m_nameSimilarityScore = impl::GetNameSimilarityScore(h.m_name, fb.GetName(StringUtf8Multilang::kDefaultCode)); return score; } } // namespace sponsored_scoring } // namespace generator
Add fuzzing coverage for StringForFeeReason(...)
// Copyright (c) 2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <amount.h> #include <optional.h> #include <policy/fees.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <cstdint> #include <string> #include <vector> void test_one_input(const std::vector<uint8_t>& buffer) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const CFeeRate minimal_incremental_fee{ConsumeMoney(fuzzed_data_provider)}; FeeFilterRounder fee_filter_rounder{minimal_incremental_fee}; while (fuzzed_data_provider.ConsumeBool()) { const CAmount current_minimum_fee = ConsumeMoney(fuzzed_data_provider); const CAmount rounded_fee = fee_filter_rounder.round(current_minimum_fee); assert(MoneyRange(rounded_fee)); } }
// Copyright (c) 2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <amount.h> #include <optional.h> #include <policy/fees.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <util/fees.h> #include <cstdint> #include <string> #include <vector> void test_one_input(const std::vector<uint8_t>& buffer) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const CFeeRate minimal_incremental_fee{ConsumeMoney(fuzzed_data_provider)}; FeeFilterRounder fee_filter_rounder{minimal_incremental_fee}; while (fuzzed_data_provider.ConsumeBool()) { const CAmount current_minimum_fee = ConsumeMoney(fuzzed_data_provider); const CAmount rounded_fee = fee_filter_rounder.round(current_minimum_fee); assert(MoneyRange(rounded_fee)); } const FeeReason fee_reason = fuzzed_data_provider.PickValueInArray({FeeReason::NONE, FeeReason::HALF_ESTIMATE, FeeReason::FULL_ESTIMATE, FeeReason::DOUBLE_ESTIMATE, FeeReason::CONSERVATIVE, FeeReason::MEMPOOL_MIN, FeeReason::PAYTXFEE, FeeReason::FALLBACK, FeeReason::REQUIRED}); (void)StringForFeeReason(fee_reason); }
Fix off-by-one memory access error.
#include "alnindex.hpp" #include <cstring> AlnIndex::AlnIndex() { t = hattrie_create(); } AlnIndex::~AlnIndex() { hattrie_free(t); } size_t AlnIndex::size() const { return hattrie_size(t); } void AlnIndex::clear() { hattrie_clear(t); } long AlnIndex::add(const char* key) { value_t* val = hattrie_get(t, key, strlen(key)); if (*val == 0) { *val = hattrie_size(t) + 1; } return *val; } long AlnIndex::get(const char* key) { value_t* val = hattrie_tryget(t, key, strlen(key)); if (val == NULL) return -1; else { return *val - 1;; } } size_t AlnIndex::used_memory() const { return hattrie_sizeof(t); }
#include "alnindex.hpp" #include <cstring> AlnIndex::AlnIndex() { t = hattrie_create(); } AlnIndex::~AlnIndex() { hattrie_free(t); } size_t AlnIndex::size() const { return hattrie_size(t); } void AlnIndex::clear() { hattrie_clear(t); } long AlnIndex::add(const char* key) { value_t* val = hattrie_get(t, key, strlen(key)); if (*val == 0) { *val = hattrie_size(t); } return *val; } long AlnIndex::get(const char* key) { value_t* val = hattrie_tryget(t, key, strlen(key)); if (val == NULL) return -1; else { return *val - 1;; } } size_t AlnIndex::used_memory() const { return hattrie_sizeof(t); }
Add color and timestamp to loggin messages
#include <QCoreApplication> #include <QSettings> #include "Application.h" int main(int argc, char *argv[]) { Application a(argc, argv); return a.exec(); }
#include <QCoreApplication> #include <QSettings> #include "Application.h" #include <QtGlobal> #include <QTime> #include <iostream> #define COLOR_LIGHTRED "\033[31;1m" #define COLOR_RED "\033[31m" #define COLOR_LIGHTBLUE "\033[34;1m" #define COLOR_BLUE "\033[34m" #define COLOR_GREEN "\033[32;1m" #define COLOR_YELLOW "\033[33;1m" #define COLOR_ORANGE "\033[0;33m" #define COLOR_WHITE "\033[37;1m" #define COLOR_LIGHTCYAN "\033[36;1m" #define COLOR_CYAN "\033[36m" #define COLOR_RESET "\033[0m" #define COLOR_HIGH "\033[1m" #define LOG_WRITE(OUTPUT, COLOR, LEVEL, MSG) OUTPUT << COLOR << \ QTime::currentTime().toString("hh:mm:ss:zzz").toStdString() << \ " " LEVEL " " << COLOR_RESET << MSG << "\n" static void EmsCustomLogWriter(QtMsgType type, const QMessageLogContext &context, const QString &msg) { switch (type) { case QtWarningMsg: LOG_WRITE(std::cout, COLOR_YELLOW, "WARN", msg.toStdString()); break; case QtCriticalMsg: LOG_WRITE(std::cout, COLOR_RED, "CRIT", msg.toStdString()); break; case QtFatalMsg: LOG_WRITE(std::cout, COLOR_ORANGE, "FATAL", msg.toStdString()); break; case QtDebugMsg: LOG_WRITE(std::cout, COLOR_CYAN, "DEBUG", msg.toStdString()); break; default: LOG_WRITE(std::cout, COLOR_CYAN, "DEBUG", msg.toStdString()); break; } } int main(int argc, char *argv[]) { qInstallMessageHandler(EmsCustomLogWriter); Application a(argc, argv); return a.exec(); }
Support pointers to "None" as used in the wanproxy.conf.
#include <string> #include <config/config.h> #include <config/config_type_pointer.h> #include <config/config_value.h> ConfigTypePointer config_type_pointer; bool ConfigTypePointer::set(ConfigValue *cv, const std::string& vstr) { if (pointers_.find(cv) != pointers_.end()) return (false); Config *config = cv->config_; ConfigObject *co = config->lookup(vstr); if (co == NULL) return (false); pointers_[cv] = co; return (true); }
#include <string> #include <config/config.h> #include <config/config_type_pointer.h> #include <config/config_value.h> ConfigTypePointer config_type_pointer; bool ConfigTypePointer::set(ConfigValue *cv, const std::string& vstr) { if (pointers_.find(cv) != pointers_.end()) return (false); /* XXX Have a magic None that is easily-detected? */ if (vstr == "None") { pointers_[cv] = NULL; return (true); } Config *config = cv->config_; ConfigObject *co = config->lookup(vstr); if (co == NULL) return (false); pointers_[cv] = co; return (true); }
Fix forgotten case in previous commit.
#include <cassert> #include "structures/congruence_atom.h" using namespace theorysolver; Term::Term(unsigned int symbol_id) : type(Term::SYMBOL), symbol_id(symbol_id), function_name(), arguments() { } Term::Term(std::string function_name, std::vector<std::shared_ptr<Term>> arguments) : type(Term::FUNCTION), symbol_id(0), function_name(function_name), arguments(arguments) { } bool Term::operator==(const Term &that) const { if (this->type != that.type) return false; else if (this->type == Term::SYMBOL) return this->symbol_id == that.symbol_id; else if (this->type == Term::FUNCTION) { if (this->arguments.size() != that.arguments.size()) return false; for (unsigned i=0; i<this->arguments.size(); i++) if (!(this->arguments[i] == that.arguments[i])) return false; return true; } else assert(false); } CongruenceAtom::CongruenceAtom(std::shared_ptr<Term> left, enum Operator op, std::shared_ptr<Term> right) : left(left), right(right), op(op) { } std::string CongruenceAtom::to_string() const { // TODO return std::string(); }
#include <cassert> #include "structures/congruence_atom.h" using namespace theorysolver; Term::Term(unsigned int symbol_id) : type(Term::SYMBOL), symbol_id(symbol_id), function_name(), arguments() { } Term::Term(std::string function_name, std::vector<std::shared_ptr<Term>> arguments) : type(Term::FUNCTION), symbol_id(0), function_name(function_name), arguments(arguments) { } bool Term::operator==(const Term &that) const { if (this->type != that.type) return false; else if (this->type == Term::SYMBOL) return this->symbol_id == that.symbol_id; else if (this->type == Term::FUNCTION) { if (this->arguments.size() != that.arguments.size()) return false; if (this->function_name != that.function_name) return false; for (unsigned i=0; i<this->arguments.size(); i++) if (!(this->arguments[i] == that.arguments[i])) return false; return true; } else assert(false); } CongruenceAtom::CongruenceAtom(std::shared_ptr<Term> left, enum Operator op, std::shared_ptr<Term> right) : left(left), right(right), op(op) { } std::string CongruenceAtom::to_string() const { // TODO return std::string(); }
Optimize number to bitset conversion
#include <iostream> #include <limits> #include <bitset> std::bitset<10> split(unsigned number) noexcept { std::bitset<10> result; while (number > 0) { unsigned digit = number % 10; number /= 10; result[digit] = true; } return result; } template <size_t size> bool isPermutation(std::bitset<size> const &first, std::bitset<size> const &second) noexcept { for (size_t i = 0; i < second.size(); ++i) { if (first[i] != second[i]) { return false; } } return true; } bool isPermutation(unsigned first, unsigned second) noexcept { std::bitset<10> i = split(first); std::bitset<10> k = split(second); return isPermutation(i, k); } int main(int count, char *arguments[]) { for (unsigned i = 1; i < std::numeric_limits<unsigned>::max(); ++i) { unsigned k = 2; for (; k < 7; ++k) { if (isPermutation(i, i * k) == false) { break; } } if (k == 7) { std::cout << i << '\n'; return 0; } } return 0; }
#include <iostream> #include <limits> #include <bitset> std::bitset<10> split(unsigned number) noexcept { std::bitset<10> result; while (number > 0) { unsigned digit = number % 10; number /= 10; result[digit] = true; } return result; } template <size_t size> bool isPermutation(std::bitset<size> const &first, std::bitset<size> const &second) noexcept { for (size_t i = 0; i < second.size(); ++i) { if (first[i] != second[i]) { return false; } } return true; } int main(int count, char *arguments[]) { for (unsigned i = 1; i < std::numeric_limits<unsigned>::max(); ++i) { std::bitset<10> r = split(i); unsigned k = 2; for (; k < 7; ++k) { std::bitset<10> l = split(i * k); if (isPermutation(r, l) == false) { break; } } if (k == 7) { std::cout << i << '\n'; return 0; } } return 0; }
Modify board::board to call print_board()
#include <ncurses.h> #include <stdlib.h> #include <time.h> #include "lightsout.hpp" namespace roadagain { board::board(int width, int height) : width(width), height(height) { // init seed of rand() by current time srand(time(NULL)); lights = new bool*[height + 2](); for (int i = 0; i < height + 2; i++){ lights[i] = new bool[width + 2](); for (int j = 1; j < width + 1; j++){ lights[i][j] = (rand() % 2 == 0); } } } board::~board() { ; } }
#include <ncurses.h> #include <stdlib.h> #include <time.h> #include "lightsout.hpp" #include "print.hpp" namespace roadagain { board::board(int width, int height) : width(width), height(height) { // init seed of rand() by current time srand(time(NULL)); lights = new bool*[height + 2](); for (int i = 0; i < height + 2; i++){ lights[i] = new bool[width + 2](); for (int j = 1; j < width + 1; j++){ lights[i][j] = (rand() % 2 == 0); } } // print the board print_board(width, height); } board::~board() { ; } }
Fix crash: CoinControl "space" bug
#include "coincontroltreewidget.h" #include "coincontroldialog.h" CoinControlTreeWidget::CoinControlTreeWidget(QWidget *parent) : QTreeWidget(parent) { } void CoinControlTreeWidget::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Space) // press spacebar -> select checkbox { event->ignore(); int COLUMN_CHECKBOX = 0; this->currentItem()->setCheckState(COLUMN_CHECKBOX, ((this->currentItem()->checkState(COLUMN_CHECKBOX) == Qt::Checked) ? Qt::Unchecked : Qt::Checked)); } else if (event->key() == Qt::Key_Escape) // press esc -> close dialog { event->ignore(); CoinControlDialog *coinControlDialog = (CoinControlDialog*)this->parentWidget(); coinControlDialog->done(QDialog::Accepted); } else { this->QTreeWidget::keyPressEvent(event); } }
#include "coincontroltreewidget.h" #include "coincontroldialog.h" CoinControlTreeWidget::CoinControlTreeWidget(QWidget *parent) : QTreeWidget(parent) { } void CoinControlTreeWidget::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Space) // press spacebar -> select checkbox { event->ignore(); int COLUMN_CHECKBOX = 0; if(this->currentItem()) this->currentItem()->setCheckState(COLUMN_CHECKBOX, ((this->currentItem()->checkState(COLUMN_CHECKBOX) == Qt::Checked) ? Qt::Unchecked : Qt::Checked)); } else if (event->key() == Qt::Key_Escape) // press esc -> close dialog { event->ignore(); CoinControlDialog *coinControlDialog = (CoinControlDialog*)this->parentWidget(); coinControlDialog->done(QDialog::Accepted); } else { this->QTreeWidget::keyPressEvent(event); } }
Fix a bug with J-type target address calculation.
#include "instr.h" #define MIPS_JTYPE_EXTRACT_TARGET(Instr) (Instr & ((1 << 26) - 1)) namespace sasm { namespace instr { namespace mips { namespace jtype { jtype_instr::jtype_instr(const sasm::elf::elf& elf, uint64 addr) : mips_instr(elf, addr) { auto instr = elf.image.read<uint32>(addr); _target_val = MIPS_JTYPE_EXTRACT_TARGET(instr); } void jtype_instr::dump_asm(std::ostream& out) const { _dump_addr(out); out << _name << " " << _get_abs_addr(_target_val << 2) << std::endl; } }}}}
#include "instr.h" #define MIPS_JTYPE_EXTRACT_TARGET(Instr) (Instr & ((1 << 26) - 1)) namespace sasm { namespace instr { namespace mips { namespace jtype { jtype_instr::jtype_instr(const sasm::elf::elf& elf, uint64 addr) : mips_instr(elf, addr) { auto instr = elf.image.read<uint32>(addr); _target_val = MIPS_JTYPE_EXTRACT_TARGET(instr); } void jtype_instr::dump_asm(std::ostream& out) const { _dump_addr(out); uint32 dst_addr = (_target_val << 2) + ((_addr >> 28) << 28); out << _name << " " << _get_abs_addr(dst_addr) << std::endl; } }}}}
Add prim test for size zero input
#include <stan/math/prim/mat.hpp> #include <gtest/gtest.h> TEST(MathMatrixPrimMat, singular_values) { stan::math::matrix_d m0(1, 1); m0 << 1.0; using stan::math::singular_values; EXPECT_NO_THROW(singular_values(m0)); }
#include <stan/math/prim/mat.hpp> #include <gtest/gtest.h> TEST(MathMatrixPrimMat, singular_values) { using stan::math::singular_values; stan::math::matrix_d m0(0, 0); EXPECT_NO_THROW(singular_values(m0)); stan::math::matrix_d m1(1, 1); m1 << 1.0; EXPECT_NO_THROW(singular_values(m1)); }
Change type of function pointer
#include <functional> #include "apsp.h" #include "cuda/cuda_apsp.cuh" /** * Naive implementation algorithm Floyd Wharshall for APSP * * @param data: unique ptr to graph data with allocated fields */ static void naiveFW(const std::unique_ptr<graphAPSPTopology>& data) { int newPath = 0; int n = data->nvertex; for(int u=0; u < n; ++u) { for(int v1=0; v1 < n; ++v1) { for(int v2=0; v2 < n; ++v2) { newPath = data->graph[v1 * n + u] + data->graph[u * n + v2]; if (data->graph[v1 * n + v2] > newPath) { data->graph[v1 * n + v2] = newPath; data->pred[v1 * n + v2] = data->pred[u * n + v2]; } } } } } /** * APSP API to compute all pairs shortest paths in graph * * @param data: unique ptr to graph data with allocated fields * @param algorithm: algorithm type for APSP */ void apsp(const std::unique_ptr<graphAPSPTopology>& data, graphAPSPAlgorithm algorithm) { std::function<int(const std::unique_ptr<graphAPSPTopology>&)> algorithms[] = { naiveFW, cudaNaiveFW, cudaBlockedFW }; algorithms[algorithm](data); }
#include <functional> #include "apsp.h" #include "cuda/cuda_apsp.cuh" /** * Naive implementation algorithm Floyd Wharshall for APSP * * @param data: unique ptr to graph data with allocated fields */ static void naiveFW(const std::unique_ptr<graphAPSPTopology>& data) { int newPath = 0; int n = data->nvertex; for(int u=0; u < n; ++u) { for(int v1=0; v1 < n; ++v1) { for(int v2=0; v2 < n; ++v2) { newPath = data->graph[v1 * n + u] + data->graph[u * n + v2]; if (data->graph[v1 * n + v2] > newPath) { data->graph[v1 * n + v2] = newPath; data->pred[v1 * n + v2] = data->pred[u * n + v2]; } } } } } /** * APSP API to compute all pairs shortest paths in graph * * @param data: unique ptr to graph data with allocated fields * @param algorithm: algorithm type for APSP */ void apsp(const std::unique_ptr<graphAPSPTopology>& data, graphAPSPAlgorithm algorithm) { std::function<void(const std::unique_ptr<graphAPSPTopology>&)> algorithms[] = { naiveFW, cudaNaiveFW, cudaBlockedFW }; algorithms[algorithm](data); }
Print a backtrace before terminating on supported platforms
#include <iostream> #include <tightdb/util/terminate.hpp> using namespace std; namespace tightdb { namespace util { TIGHTDB_NORETURN void terminate(string message, const char* file, long line) TIGHTDB_NOEXCEPT { cerr << file << ":" << line << ": " << message << endl; abort(); } } // namespace util } // namespace tightdb
#include <iostream> #ifdef __APPLE__ #include <execinfo.h> #endif #include <tightdb/util/terminate.hpp> using namespace std; namespace tightdb { namespace util { TIGHTDB_NORETURN void terminate(string message, const char* file, long line) TIGHTDB_NOEXCEPT { cerr << file << ":" << line << ": " << message << endl; #ifdef __APPLE__ void* callstack[128]; int frames = backtrace(callstack, 128); char** strs = backtrace_symbols(callstack, frames); for (int i = 0; i < frames; ++i) { cerr << strs[i] << endl; } free(strs); #endif abort(); } } // namespace util } // namespace tightdb
Move processEvents call to properly maximize.
#include "MainWindow.h" #include <QApplication> namespace cygnus { class MainApp : public QApplication { QString fileName_{}; MainWindow *mainWindow_; public: MainApp(int argc, char *argv[]) : QApplication(argc, argv), mainWindow_(new MainWindow()) { mainWindow_->showMaximized(); if (argc > 1 && argv[1]) { fileName_ = argv[1]; } if (!fileName_.isEmpty()) { mainWindow_->setFileName(fileName_); mainWindow_->loadFile(); } else { mainWindow_->open(); } } protected: bool event(QEvent *event) override { switch (event->type()) { case QEvent::FileOpen: { QFileOpenEvent *fileOpenEvent = static_cast<QFileOpenEvent *>(event); if (fileOpenEvent) { fileName_ = fileOpenEvent->file(); if (!fileName_.isEmpty()) { if (mainWindow_) { mainWindow_->setFileName(fileName_); } return true; } } } default: break; } return QApplication::event(event); } }; } int main(int argc, char *argv[]) { QCoreApplication::setOrganizationName("Cygnus Crosswords"); cygnus::MainApp a(argc, argv); QApplication::processEvents(); return a.exec(); }
#include "MainWindow.h" #include <QApplication> namespace cygnus { class MainApp : public QApplication { QString fileName_{}; MainWindow *mainWindow_; public: MainApp(int argc, char *argv[]) : QApplication(argc, argv), mainWindow_(new MainWindow()) { mainWindow_->showMaximized(); QApplication::processEvents(); if (argc > 1 && argv[1]) { fileName_ = argv[1]; } if (!fileName_.isEmpty()) { mainWindow_->setFileName(fileName_); mainWindow_->loadFile(); } else { mainWindow_->open(); } } protected: bool event(QEvent *event) override { switch (event->type()) { case QEvent::FileOpen: { QFileOpenEvent *fileOpenEvent = static_cast<QFileOpenEvent *>(event); if (fileOpenEvent) { fileName_ = fileOpenEvent->file(); if (!fileName_.isEmpty()) { if (mainWindow_) { mainWindow_->setFileName(fileName_); } return true; } } } default: break; } return QApplication::event(event); } }; } // namespace cygnus int main(int argc, char *argv[]) { QCoreApplication::setOrganizationName("Cygnus Crosswords"); cygnus::MainApp a(argc, argv); return a.exec(); }
Use return instead of exit.
#include "../include/parser.h" #include "../include/exceptions.h" int main(int argc, const char** argv) { if(argc != 2) { printf("Arguments: file name.\n"); exit(1); } else { try { FileAccess * file = new FileAccess(argv[1]); TextCursor cursor(file); parse_file(cursor); } catch(FileNotExistsError) { printf("File not exists.\n"); exit(2); } } }
#include "../include/parser.h" #include "../include/exceptions.h" int main(int argc, const char** argv) { if(argc != 2) { printf("Arguments: file name.\n"); return 1; } else { try { FileAccess * file = new FileAccess(argv[1]); TextCursor cursor(file); parse_file(cursor); } catch(FileNotExistsError) { printf("File not exists.\n"); return 2; } } return 0; }
Fix PR number in test case
// RUN: %clang_cc1 -fsyntax-only -verify -std=c++0x %s struct A {}; // expected-note {{candidate is the implicit copy constructor}} struct BASE { operator A(); // expected-note {{candidate function}} }; struct BASE1 { operator A(); // expected-note {{candidate function}} }; class B : public BASE , public BASE1 { public: B(); } b; extern B f(); const int& ri = (void)0; // expected-error {{reference to type 'int const' could not bind to an rvalue of type 'void'}} int main() { const A& rca = f(); // expected-error {{reference initialization of type 'struct A const &' with initializer of type 'class B' is ambiguous}} A& ra = f(); // expected-error {{non-const lvalue reference to type 'struct A' cannot bind to a temporary of type 'class B'}} } struct PR6177 { A (&x)[1]; }; PR6177 x = {{A()}}; // expected-error{{non-const lvalue reference to type 'struct A [1]' cannot bind to a temporary of type 'struct A'}}
// RUN: %clang_cc1 -fsyntax-only -verify -std=c++0x %s struct A {}; // expected-note {{candidate is the implicit copy constructor}} struct BASE { operator A(); // expected-note {{candidate function}} }; struct BASE1 { operator A(); // expected-note {{candidate function}} }; class B : public BASE , public BASE1 { public: B(); } b; extern B f(); const int& ri = (void)0; // expected-error {{reference to type 'int const' could not bind to an rvalue of type 'void'}} int main() { const A& rca = f(); // expected-error {{reference initialization of type 'struct A const &' with initializer of type 'class B' is ambiguous}} A& ra = f(); // expected-error {{non-const lvalue reference to type 'struct A' cannot bind to a temporary of type 'class B'}} } struct PR6139 { A (&x)[1]; }; PR6139 x = {{A()}}; // expected-error{{non-const lvalue reference to type 'struct A [1]' cannot bind to a temporary of type 'struct A'}}
Move these calls otuside the try block, they should never fail
#include <cstdint> #include <Magick++/Blob.h> #include <Magick++/Image.h> #include "utils.cc" #define FUZZ_ENCODER_STRING_LITERAL_X(name) FUZZ_ENCODER_STRING_LITERAL(name) #define FUZZ_ENCODER_STRING_LITERAL(name) #name #ifndef FUZZ_ENCODER #define FUZZ_ENCODER FUZZ_ENCODER_STRING_LITERAL_X(FUZZ_IMAGEMAGICK_ENCODER) #endif extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { const Magick::Blob blob(Data, Size); Magick::Image image; try { image.magick(FUZZ_ENCODER); image.fileName(std::string(FUZZ_ENCODER) + ":"); image.read(blob); } catch (Magick::Exception &e) { return 0; } Magick::Blob outBlob; try { image.write(&outBlob, FUZZ_ENCODER); } catch (Magick::Exception &e) { } return 0; }
#include <cstdint> #include <Magick++/Blob.h> #include <Magick++/Image.h> #include "utils.cc" #define FUZZ_ENCODER_STRING_LITERAL_X(name) FUZZ_ENCODER_STRING_LITERAL(name) #define FUZZ_ENCODER_STRING_LITERAL(name) #name #ifndef FUZZ_ENCODER #define FUZZ_ENCODER FUZZ_ENCODER_STRING_LITERAL_X(FUZZ_IMAGEMAGICK_ENCODER) #endif extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { const Magick::Blob blob(Data, Size); Magick::Image image; image.magick(FUZZ_ENCODER); image.fileName(std::string(FUZZ_ENCODER) + ":"); try { image.read(blob); } catch (Magick::Exception &e) { return 0; } Magick::Blob outBlob; try { image.write(&outBlob, FUZZ_ENCODER); } catch (Magick::Exception &e) { } return 0; }
Convert std::transform to std::for_each (not supported by GCC 4.6)
#include "Hostname.hpp" Hostname::Hostname() { } Hostname::Hostname(const ci_string& hostname) { create(hostname); } bool Hostname::isValid() { return !data.empty(); } void Hostname::create(const ci_string & hostname) { if (isValid()) { throw std::runtime_error("Hostname is defined!"); } data = hostname; std::transform(data.begin(), data.end(), data.begin(), std::tolower); } void Hostname::destroy() { data.clear(); } bool Hostname::operator==(const Hostname & other) const { return data == other.data; } bool Hostname::operator!=(const Hostname & other) const { return !(*this == other); } std::ostream& operator<<(std::ostream& output, const Hostname & hostname) { output << hostname.data.c_str(); return output; } std::istream& operator>>(std::istream& input, Hostname & hostname) { ci_string str; std::copy( std::istreambuf_iterator<char>(input), std::istreambuf_iterator<char>(), std::back_inserter(str)); if (hostname.isValid()) { hostname.destroy(); } hostname.create(str); return input; }
#include "Hostname.hpp" Hostname::Hostname() { } Hostname::Hostname(const ci_string& hostname) { create(hostname); } bool Hostname::isValid() { return !data.empty(); } void Hostname::create(const ci_string & hostname) { if (isValid()) { throw std::runtime_error("Hostname is defined!"); } data = hostname; std::for_each(data.begin(), data.end(), [](char& c) { c = std::tolower(c); }); } void Hostname::destroy() { data.clear(); } bool Hostname::operator==(const Hostname & other) const { return data == other.data; } bool Hostname::operator!=(const Hostname & other) const { return !(*this == other); } std::ostream& operator<<(std::ostream& output, const Hostname & hostname) { output << hostname.data.c_str(); return output; } std::istream& operator>>(std::istream& input, Hostname & hostname) { ci_string str; std::copy( std::istreambuf_iterator<char>(input), std::istreambuf_iterator<char>(), std::back_inserter(str)); if (hostname.isValid()) { hostname.destroy(); } hostname.create(str); return input; }
Fix GLInterfaceValidation test after "Remove GrContextFactory::getGLContext"
/* * 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 "Test.h" // This is a GPU-backend specific test #if SK_SUPPORT_GPU #include "GrContextFactory.h" DEF_GPUTEST(GLInterfaceValidation, reporter, factory) { for (int i = 0; i <= GrContextFactory::kLastGLContextType; ++i) { GrContextFactory::GLContextType glCtxType = (GrContextFactory::GLContextType)i; // this forces the factory to make the context if it hasn't yet GrContextFactory::ContextInfo* contextInfo = factory->getContextInfo(glCtxType); SkGLContext* glCtx = contextInfo->fGLContext; // We're supposed to fail the NVPR context type when we the native context that does not // support the NVPR extension. if (GrContextFactory::kNVPR_GLContextType == glCtxType && factory->getContextInfo(GrContextFactory::kNative_GLContextType) && !factory->getContextInfo(GrContextFactory::kNative_GLContextType)->fGLContext->gl()->hasExtension("GL_NV_path_rendering")) { REPORTER_ASSERT(reporter, nullptr == glCtx); continue; } REPORTER_ASSERT(reporter, glCtx); if (glCtx) { const GrGLInterface* interface = glCtx->gl(); REPORTER_ASSERT(reporter, interface->validate()); } } } #endif
/* * 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 "Test.h" // This is a GPU-backend specific test #if SK_SUPPORT_GPU #include "GrContextFactory.h" DEF_GPUTEST(GLInterfaceValidation, reporter, factory) { for (int i = 0; i <= GrContextFactory::kLastGLContextType; ++i) { GrContextFactory::GLContextType glCtxType = (GrContextFactory::GLContextType)i; // this forces the factory to make the context if it hasn't yet GrContextFactory::ContextInfo* contextInfo = factory->getContextInfo(glCtxType); SkGLContext* glCtx = contextInfo ? contextInfo->fGLContext : nullptr; // We're supposed to fail the NVPR context type when we the native context that does not // support the NVPR extension. if (GrContextFactory::kNVPR_GLContextType == glCtxType && factory->getContextInfo(GrContextFactory::kNative_GLContextType) && !factory->getContextInfo(GrContextFactory::kNative_GLContextType)->fGLContext->gl()->hasExtension("GL_NV_path_rendering")) { REPORTER_ASSERT(reporter, nullptr == glCtx); continue; } REPORTER_ASSERT(reporter, glCtx); if (glCtx) { const GrGLInterface* interface = glCtx->gl(); REPORTER_ASSERT(reporter, interface->validate()); } } } #endif
Test SetNow in nano seconds.
/****************************************************************************** * Copyright 2017 The Apollo 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 "modules/common/time/time.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace apollo { namespace common { namespace time { TEST(TimeTest, MockTime) { EXPECT_EQ(Clock::SYSTEM, Clock::mode()); Clock::SetMode(Clock::MOCK); EXPECT_EQ(Clock::MOCK, Clock::mode()); EXPECT_EQ(0, absl::ToUnixMicros(Clock::Now())); Clock::SetNow(absl::FromUnixMicros(123)); EXPECT_EQ(123, absl::ToUnixMicros(Clock::Now())); Clock::SetNowInSeconds(123.456); EXPECT_EQ(123.456, Clock::NowInSeconds()); } } // namespace time } // namespace common } // namespace apollo
/****************************************************************************** * Copyright 2017 The Apollo 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 "modules/common/time/time.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace apollo { namespace common { namespace time { TEST(TimeTest, MockTime) { EXPECT_EQ(Clock::SYSTEM, Clock::mode()); Clock::SetMode(Clock::MOCK); EXPECT_EQ(Clock::MOCK, Clock::mode()); EXPECT_EQ(0, absl::ToUnixMicros(Clock::Now())); Clock::SetNow(absl::FromUnixNanos(1)); EXPECT_EQ(1, absl::ToUnixNanos(Clock::Now())); Clock::SetNowInSeconds(123.456); EXPECT_DOUBLE_EQ(123.456, Clock::NowInSeconds()); } } // namespace time } // namespace common } // namespace apollo
Make checking for 'protected' access in debug info more legible.
// RUN: %clang_cc1 -emit-llvm -std=c++11 -g %s -o - | FileCheck %s // CHECK: metadata !"_ZN1A3fooEiS_3$_0", {{.*}}, i32 258 // CHECK: ""{{.*}}DW_TAG_arg_variable // CHECK: ""{{.*}}DW_TAG_arg_variable // CHECK: ""{{.*}}DW_TAG_arg_variable union { int a; float b; } u; class A { protected: void foo(int, A, decltype(u)); }; void A::foo(int, A, decltype(u)) { } A a;
// RUN: %clang_cc1 -emit-llvm -std=c++11 -g %s -o - | FileCheck %s // CHECK: metadata !"_ZN1A3fooEiS_3$_0", {{.*}} [protected] // CHECK: ""{{.*}}DW_TAG_arg_variable // CHECK: ""{{.*}}DW_TAG_arg_variable // CHECK: ""{{.*}}DW_TAG_arg_variable union { int a; float b; } u; class A { protected: void foo(int, A, decltype(u)); }; void A::foo(int, A, decltype(u)) { } A a;
Initialize shader program member to with NULL.
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. 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 "mitkVtkShaderProgram.h" #include "vtkShader2.h" mitk::VtkShaderProgram::VtkShaderProgram() { } mitk::VtkShaderProgram::~VtkShaderProgram() { } void mitk::VtkShaderProgram::SetVtkShaderProgram(vtkShaderProgram2* p) { m_VtkShaderProgram = p; } vtkShaderProgram2*mitk::VtkShaderProgram::GetVtkShaderProgram() const { return m_VtkShaderProgram; } itk::TimeStamp&mitk::VtkShaderProgram::GetShaderTimestampUpdate(){return m_ShaderTimestampUpdate;}
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. 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 "mitkVtkShaderProgram.h" #include "vtkShader2.h" mitk::VtkShaderProgram::VtkShaderProgram() : m_VtkShaderProgram(NULL) { } mitk::VtkShaderProgram::~VtkShaderProgram() { } void mitk::VtkShaderProgram::SetVtkShaderProgram(vtkShaderProgram2* p) { m_VtkShaderProgram = p; } vtkShaderProgram2*mitk::VtkShaderProgram::GetVtkShaderProgram() const { return m_VtkShaderProgram; } itk::TimeStamp&mitk::VtkShaderProgram::GetShaderTimestampUpdate(){return m_ShaderTimestampUpdate;}
Fix image filter quality handling
/* * Copyright 2018 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkSGImage.h" #include "SkCanvas.h" #include "SkImage.h" namespace sksg { Image::Image(sk_sp<SkImage> image) : fImage(std::move(image)) {} void Image::onRender(SkCanvas* canvas) const { SkPaint paint; paint.setAntiAlias(fAntiAlias); paint.setFilterQuality(fQuality); canvas->drawImage(fImage, 0, 0); } SkRect Image::onRevalidate(InvalidationController*, const SkMatrix& ctm) { return SkRect::Make(fImage->bounds()); } } // namespace sksg
/* * Copyright 2018 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkSGImage.h" #include "SkCanvas.h" #include "SkImage.h" namespace sksg { Image::Image(sk_sp<SkImage> image) : fImage(std::move(image)) {} void Image::onRender(SkCanvas* canvas) const { SkPaint paint; paint.setAntiAlias(fAntiAlias); paint.setFilterQuality(fQuality); canvas->drawImage(fImage, 0, 0, &paint); } SkRect Image::onRevalidate(InvalidationController*, const SkMatrix& ctm) { return SkRect::Make(fImage->bounds()); } } // namespace sksg
Check the paragraph for its existence and size
#include "document.hpp" Document::Document(const std::string & filename) : _filename(filename) {} Document::~Document() {} std::string Document::filename(void) const { return _filename; } void Document::append_paragraph(Paragraph * p) { _paragraph.push_back(p); } size_t Document::size(void) const { return _paragraph.size(); } Paragraph* Document::operator[](size_t index) const { if (index < _paragraph.size()) { return _paragraph[index]; } else { return nullptr; } }
#include "document.hpp" Document::Document(const std::string & filename) : _filename(filename) {} Document::~Document() {} std::string Document::filename(void) const { return _filename; } void Document::append_paragraph(Paragraph * p) { if (p and p->size()) { _paragraph.push_back(p); } } size_t Document::size(void) const { return _paragraph.size(); } Paragraph* Document::operator[](size_t index) const { if (index < _paragraph.size()) { return _paragraph[index]; } else { return nullptr; } }
Remove pointless forward declaration, MSVC got confused by this.
//===-- GCMetadataPrinter.cpp - Garbage collection infrastructure ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the abstract base class GCMetadataPrinter. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/GCMetadataPrinter.h" class MCAsmInfo; using namespace llvm; GCMetadataPrinter::GCMetadataPrinter() { } GCMetadataPrinter::~GCMetadataPrinter() { } void GCMetadataPrinter::beginAssembly(raw_ostream &OS, AsmPrinter &AP, const MCAsmInfo &MAI) { // Default is no action. } void GCMetadataPrinter::finishAssembly(raw_ostream &OS, AsmPrinter &AP, const MCAsmInfo &MAI) { // Default is no action. }
//===-- GCMetadataPrinter.cpp - Garbage collection infrastructure ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the abstract base class GCMetadataPrinter. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/GCMetadataPrinter.h" using namespace llvm; GCMetadataPrinter::GCMetadataPrinter() { } GCMetadataPrinter::~GCMetadataPrinter() { } void GCMetadataPrinter::beginAssembly(raw_ostream &OS, AsmPrinter &AP, const MCAsmInfo &MAI) { // Default is no action. } void GCMetadataPrinter::finishAssembly(raw_ostream &OS, AsmPrinter &AP, const MCAsmInfo &MAI) { // Default is no action. }
Fix CC1101 example to start RX and use timeouts
#include "common.h" uint8_t packet[64]; int main(void) { DCO::init(); ACLK::init(); SMCLK::init(); MCLK::init(); WDT::init(); WDT::enable_irq(); PORT1::init(); PORT2::init(); LED_RED::set_high(); #ifndef __MSP430_HAS_USCI__ TIMER::init(); #endif UART::init(); printf<UART>("CC110X example start.\n"); SPI::init(); CC1101::reset(); CC1101::init(cc110x_default_init_values, ARRAY_COUNT(cc110x_default_init_values)); LED_RED::set_low(); while (1) { CC1101::rx_buffer(packet, sizeof(packet)); LED_RED::set_high(); TIMEOUT::set_and_wait(50); LED_RED::set_low(); } }
#include "common.h" uint8_t packet[64]; int main(void) { DCO::init(); ACLK::init(); SMCLK::init(); MCLK::init(); WDT::init(); WDT::enable_irq(); PORT1::init(); PORT2::init(); LED_RED::set_high(); #ifndef __MSP430_HAS_USCI__ TIMER::init(); #endif UART::init(); printf<UART>("CC110X example start.\n"); SPI::init(); CC1101::reset(); CC1101::init(cc110x_default_init_values, ARRAY_COUNT(cc110x_default_init_values)); CC1101::start_rx(); LED_RED::set_low(); while (1) { CC1101::rx_buffer<TIMEOUT_NEVER>(packet, sizeof(packet)); LED_RED::set_high(); TIMEOUT::set_and_wait(50); LED_RED::set_low(); } }
Check loop return value to stop the FSM if false
#include "YarpStateDirector.hpp" const int rd::YarpStateDirector::DEFAULT_RATE_MS = 100; rd::YarpStateDirector::YarpStateDirector(rd::State *state) : StateDirector(state), RateThread(DEFAULT_RATE_MS) { } bool rd::YarpStateDirector::Start() { RD_DEBUG("Starting StateDirector for id %s\n", state->getStateId().c_str()); active = true; state->setup(); return yarp::os::RateThread::start(); } bool rd::YarpStateDirector::Stop() { RD_DEBUG("Stopping StateDirector for id %s\n", state->getStateId().c_str()); active = false; yarp::os::RateThread::askToStop(); yarp::os::RateThread::stop(); state->cleanup(); return true; } void rd::YarpStateDirector::run() { //RD_DEBUG("Entering loop in StateDirector with id %s\n", state->getStateId().c_str()); state->loop(); int condition = state->evaluateConditions(); if (nextStates.find(condition) != nextStates.end()) { this->Stop(); nextStates.find(condition)->second->Start(); } }
#include "YarpStateDirector.hpp" const int rd::YarpStateDirector::DEFAULT_RATE_MS = 100; rd::YarpStateDirector::YarpStateDirector(rd::State *state) : StateDirector(state), RateThread(DEFAULT_RATE_MS) { } bool rd::YarpStateDirector::Start() { RD_DEBUG("Starting StateDirector for id %s\n", state->getStateId().c_str()); active = true; state->setup(); return yarp::os::RateThread::start(); } bool rd::YarpStateDirector::Stop() { RD_DEBUG("Stopping StateDirector for id %s\n", state->getStateId().c_str()); active = false; yarp::os::RateThread::askToStop(); yarp::os::RateThread::stop(); state->cleanup(); return true; } void rd::YarpStateDirector::run() { //RD_DEBUG("Entering loop in StateDirector with id %s\n", state->getStateId().c_str()); if ( !state->loop() ) { RD_ERROR("Error in loop. Stopping this state...\n"); this->Stop(); } int condition = state->evaluateConditions(); if (nextStates.find(condition) != nextStates.end()) { this->Stop(); nextStates.find(condition)->second->Start(); } }
Fix plugin data refreshing to work again.
// Copyright (c) 2008 The Chromium Authors. All rights reserved. Use of this // source code is governed by a BSD-style license that can be found in the // LICENSE file. #include "config.h" #include "PluginData.h" #include "PluginInfoStore.h" #undef LOG #include "webkit/glue/glue_util.h" #include "webkit/glue/webkit_glue.h" namespace WebCore { static bool refreshData = false; void PluginData::initPlugins() { std::vector<WebPluginInfo> plugins; if (!webkit_glue::GetPlugins(refreshData, &plugins)) return; refreshData = false; PluginInfoStore c; for (size_t i = 0; i < plugins.size(); ++i) { PluginInfo* info = c.createPluginInfoForPluginAtIndex(i); m_plugins.append(info); } } void PluginData::refresh() { // When next we initialize a PluginData, it'll be fresh. refreshData = true; } }
// Copyright (c) 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "config.h" #include "PluginData.h" #include "PluginInfoStore.h" namespace WebCore { void PluginData::initPlugins() { PluginInfoStore c; for (size_t i = 0; i < c.pluginCount(); ++i) m_plugins.append(c.createPluginInfoForPluginAtIndex(i)); } void PluginData::refresh() { refreshPlugins(true); } }
Change the process name to loom-daemon
#include <cstdio> #include <cstdlib> #include <signal.h> #include <unistd.h> #include "Updater.h" static int DaemonPID = -1; int RunDaemon(void *Arg) { while (1) { printf("daemon is running...\n"); sleep(1); } return 0; } int StartDaemon() { static const int ChildStackSize = 1024 * 1024; char *ChildStack = (char *)malloc(ChildStackSize); if (!ChildStack) { perror("malloc"); return -1; } DaemonPID = clone(RunDaemon, ChildStack + ChildStackSize, CLONE_VM, NULL); if (DaemonPID == -1) { perror("clone"); return -1; } fprintf(stderr, "Daemon PID = %d\n", DaemonPID); return 0; } int StopDaemon() { if (DaemonPID != -1) { if (kill(DaemonPID, SIGTERM) == -1) { perror("kill"); return -1; } } return 0; }
#include <cstdio> #include <cstdlib> #include <signal.h> #include <unistd.h> #include <sys/prctl.h> #include "Updater.h" static int DaemonPID = -1; int RunDaemon(void *Arg) { if (prctl(PR_SET_NAME, "loom-daemon", 0, 0, 0) == -1) { perror("prctl"); } while (1) { fprintf(stderr, "daemon is running...\n"); sleep(1); } return 0; } int StartDaemon() { static const int ChildStackSize = 1024 * 1024; char *ChildStack = (char *)malloc(ChildStackSize); if (!ChildStack) { perror("malloc"); return -1; } DaemonPID = clone(RunDaemon, ChildStack + ChildStackSize, CLONE_VM, NULL); if (DaemonPID == -1) { perror("clone"); return -1; } fprintf(stderr, "Daemon PID = %d\n", DaemonPID); return 0; } int StopDaemon() { if (DaemonPID != -1) { if (kill(DaemonPID, SIGTERM) == -1) { perror("kill"); return -1; } } return 0; }
Change default txn manager to occ
//===----------------------------------------------------------------------===// // // Peloton // // transaction_manager_factory.h // // Identification: src/backend/concurrency/transaction_manager_factory.h // // Copyright (c) 2015-16, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "transaction_manager_factory.h" namespace peloton { namespace concurrency { ConcurrencyType TransactionManagerFactory::protocol_ = CONCURRENCY_TYPE_PESSIMISTIC; IsolationLevelType TransactionManagerFactory::isolation_level_ = ISOLATION_LEVEL_TYPE_FULL; } }
//===----------------------------------------------------------------------===// // // Peloton // // transaction_manager_factory.h // // Identification: src/backend/concurrency/transaction_manager_factory.h // // Copyright (c) 2015-16, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "transaction_manager_factory.h" namespace peloton { namespace concurrency { ConcurrencyType TransactionManagerFactory::protocol_ = CONCURRENCY_TYPE_OPTIMISTIC; IsolationLevelType TransactionManagerFactory::isolation_level_ = ISOLATION_LEVEL_TYPE_FULL; } }
Interrupt signal handler for POSIX.
#include "platform.hpp" #ifndef WIN32 namespace Mirb { namespace Platform { std::string BenchmarkResult::format() { std::stringstream result; result << ((double)time / 1000) << " ms"; return result.str(); } void *allocate_region(size_t bytes) { void *result = mmap(0, bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); mirb_runtime_assert(result != 0); return result; } void free_region(void *region, size_t bytes) { munmap(region, bytes); } void initialize() { } }; }; #endif
#include "platform.hpp" #include "../collector.hpp" #include <signal.h> #ifndef WIN32 namespace Mirb { namespace Platform { std::string BenchmarkResult::format() { std::stringstream result; result << ((double)time / 1000) << " ms"; return result.str(); } void *allocate_region(size_t bytes) { void *result = mmap(0, bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); mirb_runtime_assert(result != 0); return result; } void free_region(void *region, size_t bytes) { munmap(region, bytes); } void signal_handler(int) { Collector::signal(); } void initialize() { signal(SIGINT, signal_handler); } }; }; #endif
Change type to appease GPU builds.
/* Copyright 2017 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/compiler/xla/legacy_flags/debug_options_flags.h" #include "tensorflow/core/platform/test.h" GTEST_API_ int main(int argc, char** argv) { std::vector<tensorflow::Flag> flag_list; xla::legacy_flags::AppendDebugOptionsFlags(&flag_list); string usage = tensorflow::Flags::Usage(argv[0], flag_list); if (!tensorflow::Flags::Parse(&argc, argv, flag_list)) { LOG(ERROR) << "\n" << usage; return 2; } testing::InitGoogleTest(&argc, argv); if (argc > 1) { LOG(ERROR) << "Unknown argument " << argv[1] << "\n" << usage; return 2; } return RUN_ALL_TESTS(); }
/* Copyright 2017 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/compiler/xla/legacy_flags/debug_options_flags.h" #include "tensorflow/core/platform/test.h" GTEST_API_ int main(int argc, char** argv) { std::vector<tensorflow::Flag> flag_list; xla::legacy_flags::AppendDebugOptionsFlags(&flag_list); auto usage = tensorflow::Flags::Usage(argv[0], flag_list); if (!tensorflow::Flags::Parse(&argc, argv, flag_list)) { LOG(ERROR) << "\n" << usage; return 2; } testing::InitGoogleTest(&argc, argv); if (argc > 1) { LOG(ERROR) << "Unknown argument " << argv[1] << "\n" << usage; return 2; } return RUN_ALL_TESTS(); }
Copy constructor test minor fixes
/* * This file is part of Peli - universal JSON interaction library * Copyright (C) 2014 Alexey Chernov <4ernov@gmail.com> * * Peli is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see <http://www.gnu.org/licenses/>. * */ #include <cassert> #include "peli/json/value.h" using namespace std; using namespace peli; int main(int argc, char* argv[]) { json::value v1(json::make_value<json::object>()); json::object& obj1(v1); obj1["test"] = json::value(52); json::value v2(v1); assert(v1 == v2); json::object& obj2(v2); obj2["test"] = json::value(53); assert(v1 != v2); return 0; }
/* * This file is part of Peli - universal JSON interaction library * Copyright (C) 2014 Alexey Chernov <4ernov@gmail.com> * * Peli is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see <http://www.gnu.org/licenses/>. * */ #include <cassert> #include "peli/json/value.h" using namespace std; using namespace peli; int main(int argc, char* argv[]) { json::object a; json::value v1(a); json::object& obj1(v1); obj1["test"] = json::value(52); json::value v2(v1); assert(v1 == v2); json::object& obj2(v2); obj2["test"] = json::value(53); assert(v1 != v2); return 0; }
Scale tag by 255 when saving sample image.
// An empty test as a placeholder #include "gtest/gtest.h" #include <opencv2/core.hpp> using namespace cv; #include "AprilTags/Corners.h" #include "AprilTags/TagFamily.h" #include "AprilTags/Tag36h11.h" using namespace AprilTags; TEST( CornersTest, MakeTagMat ) { const int WhichTag = 34; const TagCodes &code( AprilTags::tagCodes36h11 ); const int edge = (int)std::sqrt((float)code.bits); Mat tag( Corners::makeTagMat( code.codes[ WhichTag ], edge )); EXPECT_EQ( 6, edge ); EXPECT_EQ( 10, tag.rows ); EXPECT_EQ( 10, tag.cols ); Mat huge; const double scale = 10.0; cv::resize(tag, huge, Size(), scale, scale ); imwrite("/tmp/tag.jpg", huge); }
// An empty test as a placeholder #include "gtest/gtest.h" #include <opencv2/core.hpp> using namespace cv; #include "AprilTags/Corners.h" #include "AprilTags/TagFamily.h" #include "AprilTags/Tag36h11.h" using namespace AprilTags; TEST( CornersTest, MakeTagMat ) { const int WhichTag = 34; const TagCodes &code( AprilTags::tagCodes36h11 ); const int edge = (int)std::sqrt((float)code.bits); Mat tag( Corners::makeTagMat( code.codes[ WhichTag ], edge )); EXPECT_EQ( 6, edge ); EXPECT_EQ( 10, tag.rows ); EXPECT_EQ( 10, tag.cols ); Mat huge; const double scale = 10.0; cv::resize( 255*tag, huge, Size(), scale, scale ); imwrite("/tmp/tag.jpg", huge); }
Fix a typo (chek => check)
// RUN: %clang_cc1 -fsyntax-only %s 2>&1|FileCheck %s // <rdar://problem/9221993> // We only care to chek whether the compiler crashes; the actual // diagnostics are uninteresting. // CHECK: 8 errors generated. template<class _CharT> struct char_traits; template<typename _CharT, typename _Traits = char_traits<_CharT> > class basic_ios; template<typename _CharT, typename _Traits = char_traits<_CharT> > class ostreambuf_iterator; template<typename _CharT, typename _InIter = istreambuf_iterator<_CharT> > class num_get; template<typename _CharT, typename _Traits> class basic_ostream : virtual public basic_ios<_CharT, _Traits> { template<typename _CharT, typename _InIter> _InIter num_get<_CharT, _InIter>:: _M_extract_float(_InIter __beg, _InIter __end, ios_base& __io, ios_base::iostate& __err, string& __xtrc) const { const bool __plus = __c == __lit[__num_base::_S_iplus]; if ((__plus || __c == __lit[__num_base::_S_iminus]) && !(__lc->_M_use_grouping && __c == __lc->_M_thousands_sep) && !(__c == __lc->_M_decimal_point)) {
// RUN: %clang_cc1 -fsyntax-only %s 2>&1|FileCheck %s // <rdar://problem/9221993> // We only care to check whether the compiler crashes; the actual // diagnostics are uninteresting. // CHECK: 8 errors generated. template<class _CharT> struct char_traits; template<typename _CharT, typename _Traits = char_traits<_CharT> > class basic_ios; template<typename _CharT, typename _Traits = char_traits<_CharT> > class ostreambuf_iterator; template<typename _CharT, typename _InIter = istreambuf_iterator<_CharT> > class num_get; template<typename _CharT, typename _Traits> class basic_ostream : virtual public basic_ios<_CharT, _Traits> { template<typename _CharT, typename _InIter> _InIter num_get<_CharT, _InIter>:: _M_extract_float(_InIter __beg, _InIter __end, ios_base& __io, ios_base::iostate& __err, string& __xtrc) const { const bool __plus = __c == __lit[__num_base::_S_iplus]; if ((__plus || __c == __lit[__num_base::_S_iminus]) && !(__lc->_M_use_grouping && __c == __lc->_M_thousands_sep) && !(__c == __lc->_M_decimal_point)) {
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) { s_max = max; max = n; } else if (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) { max = n; } if (n <= max && s_max < n) { s_max = n; } } cout << s_max; return 0; }
Use fancy chrono_literals with a this_thread::sleep
//////////////////////////////////////////////////////////////////////////////// // // cagey-engine - Toy 3D Engine // Copyright (c) 2014 Kyle Girard <theycallmecoach@gmail.com> // // The MIT License (MIT) // // 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 <cagey/window/WindowFactory.hh> #include <gtest/gtest.h> using namespace cagey::window; TEST(Window, DefaultConstructor) { auto win = WindowFactory::createWindow("HelloWorld", VideoMode{640,480}); SDL_Delay(2000); }
//////////////////////////////////////////////////////////////////////////////// // // cagey-engine - Toy 3D Engine // Copyright (c) 2014 Kyle Girard <theycallmecoach@gmail.com> // // The MIT License (MIT) // // 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 <cagey/window/WindowFactory.hh> #include <gtest/gtest.h> #include <thread> using namespace cagey::window; using namespace std::literals; //need this for fancy chrono_literals TEST(Window, DefaultConstructor) { auto win = WindowFactory::createWindow("HelloWorld", VideoMode{640,480}); std::this_thread::sleep_for( 2000ms ); }
Call setlocale(LC_ALL, "") in a renderer process for subsequent calls to SysNativeMBToWide and WideToSysNativeMB (that use mbstowcs and wcstombs) to work correctly.
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/renderer_main_platform_delegate.h" #include "base/debug_util.h" // This is a no op class because we do not have a sandbox on linux. RendererMainPlatformDelegate::RendererMainPlatformDelegate( const MainFunctionParams& parameters) : parameters_(parameters) { } RendererMainPlatformDelegate::~RendererMainPlatformDelegate() { } void RendererMainPlatformDelegate::PlatformInitialize() { } void RendererMainPlatformDelegate::PlatformUninitialize() { } bool RendererMainPlatformDelegate::InitSandboxTests(bool no_sandbox) { // The sandbox is started in the zygote process: zygote_main_linux.cc // http://code.google.com/p/chromium/wiki/LinuxSUIDSandbox return true; } bool RendererMainPlatformDelegate::EnableSandbox() { // The sandbox is started in the zygote process: zygote_main_linux.cc // http://code.google.com/p/chromium/wiki/LinuxSUIDSandbox return true; } void RendererMainPlatformDelegate::RunSandboxTests() { // The sandbox is started in the zygote process: zygote_main_linux.cc // http://code.google.com/p/chromium/wiki/LinuxSUIDSandbox }
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/renderer_main_platform_delegate.h" #include "base/debug_util.h" // This is a no op class because we do not have a sandbox on linux. RendererMainPlatformDelegate::RendererMainPlatformDelegate( const MainFunctionParams& parameters) : parameters_(parameters) { } RendererMainPlatformDelegate::~RendererMainPlatformDelegate() { } void RendererMainPlatformDelegate::PlatformInitialize() { // To make wcstombs/mbstowcs work in a renderer. const char* locale = setlocale(LC_ALL, ""); LOG_IF(WARNING, locale == NULL) << "setlocale failed."; } void RendererMainPlatformDelegate::PlatformUninitialize() { } bool RendererMainPlatformDelegate::InitSandboxTests(bool no_sandbox) { // The sandbox is started in the zygote process: zygote_main_linux.cc // http://code.google.com/p/chromium/wiki/LinuxSUIDSandbox return true; } bool RendererMainPlatformDelegate::EnableSandbox() { // The sandbox is started in the zygote process: zygote_main_linux.cc // http://code.google.com/p/chromium/wiki/LinuxSUIDSandbox return true; } void RendererMainPlatformDelegate::RunSandboxTests() { // The sandbox is started in the zygote process: zygote_main_linux.cc // http://code.google.com/p/chromium/wiki/LinuxSUIDSandbox }
Save json lookup in variable
#include "details.hpp" #include "json/json.h" dota2::DetailsRequest &dota2::DetailsRequest::id(MatchID id) { query.insert({"match_id", std::to_string(id)}); return *this; } dota2::Details::Details(const Json::Value &json) { matchID = json["result"]["match_id"].asInt(); startTime = timePoint(json["result"]["start_time"].asInt64()); firstBloodTime = timePoint(json["result"]["first_blood_time"].asInt64()); if(json["result"]["radiant_win"].asBool()) { winningTeam = Team::RADIANT; } else { winningTeam = Team::DIRE; } } dota2::MatchID dota2::Details::getMatchID() const { return matchID; } dota2::Team dota2::Details::getWinningTeam() const { return winningTeam; } dota2::Details::timePoint dota2::Details::getStartTime() const { return startTime; } dota2::Details::timePoint dota2::Details::getFirstBloodTime() const { return firstBloodTime; }
#include "details.hpp" #include "json/json.h" dota2::DetailsRequest &dota2::DetailsRequest::id(MatchID id) { query.insert({"match_id", std::to_string(id)}); return *this; } dota2::Details::Details(const Json::Value &json) { const auto& result = json["result"]; matchID = result["match_id"].asInt(); startTime = timePoint(result["start_time"].asInt64()); firstBloodTime = timePoint(result["first_blood_time"].asInt64()); if(result["radiant_win"].asBool()) { winningTeam = Team::RADIANT; } else { winningTeam = Team::DIRE; } } dota2::MatchID dota2::Details::getMatchID() const { return matchID; } dota2::Team dota2::Details::getWinningTeam() const { return winningTeam; } dota2::Details::timePoint dota2::Details::getStartTime() const { return startTime; } dota2::Details::timePoint dota2::Details::getFirstBloodTime() const { return firstBloodTime; }
Fix version number of libContacts plugin
/* * Copyright 2011 Intel Corporation. * * This program is licensed under the terms and conditions of the * Apache License, version 2.0. The full text of the Apache License is at * http://www.apache.org/licenses/LICENSE-2.0 */ #include <QtDeclarative/QDeclarativeEngine> #include <QDeclarativeContext> #include "contacts.h" #include "peoplemodel.h" #include "proxymodel.h" void contacts::registerTypes(const char *uri) { qmlRegisterType<PeopleModel>(uri, 0, 0, "PeopleModel"); qmlRegisterType<ProxyModel>(uri, 0, 0, "ProxyModel"); } void contacts::initializeEngine(QDeclarativeEngine *engine, const char *uri) { qDebug() << "MeeGo Contacts initializeEngine" << uri; Q_ASSERT(engine); mRootContext = engine->rootContext(); Q_ASSERT(mRootContext); mRootContext->setContextProperty(QString::fromLatin1("settingsDataStore"), SettingsDataStore::self()); mRootContext->setContextProperty(QString::fromLatin1("localeUtils"), LocaleUtils::self()); } Q_EXPORT_PLUGIN(contacts);
/* * Copyright 2011 Intel Corporation. * * This program is licensed under the terms and conditions of the * Apache License, version 2.0. The full text of the Apache License is at * http://www.apache.org/licenses/LICENSE-2.0 */ #include <QtDeclarative/QDeclarativeEngine> #include <QDeclarativeContext> #include "contacts.h" #include "peoplemodel.h" #include "proxymodel.h" void contacts::registerTypes(const char *uri) { qmlRegisterType<PeopleModel>(uri, 0, 1, "PeopleModel"); qmlRegisterType<ProxyModel>(uri, 0, 1, "ProxyModel"); } void contacts::initializeEngine(QDeclarativeEngine *engine, const char *uri) { qDebug() << "MeeGo Contacts initializeEngine" << uri; Q_ASSERT(engine); mRootContext = engine->rootContext(); Q_ASSERT(mRootContext); mRootContext->setContextProperty(QString::fromLatin1("settingsDataStore"), SettingsDataStore::self()); mRootContext->setContextProperty(QString::fromLatin1("localeUtils"), LocaleUtils::self()); } Q_EXPORT_PLUGIN(contacts);
Use getline so program doesn't break functionality in javascript with multiple word inputs
#include <node.h> #include <v8.h> #include <iostream> #include <string> using namespace v8; using namespace std; Handle<Value> Prompt(const Arguments& args) { HandleScope scope; string retval; cin >> retval; return scope.Close(String::New(retval.c_str())); } void init(Handle<Object> exports) { exports->Set(String::NewSymbol("prompt"), FunctionTemplate::New(Prompt)->GetFunction()); } NODE_MODULE(sync_prompt, init)
#include <node.h> #include <v8.h> #include <iostream> #include <string> using namespace v8; using namespace std; Handle<Value> Prompt(const Arguments& args) { HandleScope scope; string retval; getline(cin, retval); return scope.Close(String::New(retval.c_str())); } void init(Handle<Object> exports) { exports->Set(String::NewSymbol("prompt"), FunctionTemplate::New(Prompt)->GetFunction()); } NODE_MODULE(sync_prompt, init)
Use an alternate string if DEBUG isn't set.
//---------------------------- job_identifier.cc --------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 by the deal authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------- job_identifier.cc --------------------------- #include <base/job_identifier.h> #include <ctime> #include <sys/time.h> #if HAVE_GETHOSTNAME # include <unistd.h> #endif JobIdentifier dealjobid; JobIdentifier::JobIdentifier() { time_t t = std::time(0); id = std::string(program_id()); //TODO:[GK] try to avoid this hack // It should be possible not to check DEBUG, but there is this // tedious -ansi, which causes problems with linux headers #if defined(HAVE_GETHOSTNAME) && !defined(DEBUG) char name[100]; gethostname(name,99); id += std::string(name) + std::string(" "); #endif id += std::string(std::ctime(&t)); } const std::string JobIdentifier::operator ()() const { return id; }
//---------------------------- job_identifier.cc --------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 by the deal authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------- job_identifier.cc --------------------------- #include <base/job_identifier.h> #include <ctime> #include <sys/time.h> #if HAVE_GETHOSTNAME # include <unistd.h> #endif JobIdentifier dealjobid; JobIdentifier::JobIdentifier() { time_t t = std::time(0); id = std::string(program_id()); //TODO:[GK] try to avoid this hack // It should be possible not to check DEBUG, but there is this // tedious -ansi, which causes problems with linux headers #if defined(HAVE_GETHOSTNAME) && !defined(DEBUG) char name[100]; gethostname(name,99); id += std::string(name) + std::string(" "); #else id += std::string("unknown "); #endif id += std::string(std::ctime(&t)); } const std::string JobIdentifier::operator ()() const { return id; }
Update clang test for r350939
// REQUIRES: x86-registered-target // RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -O1 -fmerge-functions -emit-llvm -o - -x c++ < %s | FileCheck %s // Basic functionality test. Function merging doesn't kick in on functions that // are too simple. struct A { virtual int f(int x, int *p) { return x ? *p : 1; } virtual int g(int x, int *p) { return x ? *p : 1; } } a; // CHECK: define {{.*}} @_ZN1A1gEiPi // CHECK-NEXT: tail call i32 @_ZN1A1fEiPi // CHECK-NEXT: ret
// REQUIRES: x86-registered-target // RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -O1 -fmerge-functions -emit-llvm -o - -x c++ < %s | FileCheck %s -implicit-check-not=_ZN1A1gEiPi // Basic functionality test. Function merging doesn't kick in on functions that // are too simple. struct A { virtual int f(int x, int *p) { return x ? *p : 1; } virtual int g(int x, int *p) { return x ? *p : 1; } } a; // CHECK: define {{.*}} @_ZN1A1fEiPi
Test code must call functions that it wants to test.
#include <test.hpp> TEST_CASE("default constructed varint_iterators are equal") { protozero::const_varint_iterator<uint32_t> a{}; protozero::const_varint_iterator<uint32_t> b{}; protozero::iterator_range<protozero::const_varint_iterator<uint32_t>> r{}; REQUIRE(a == a); REQUIRE(a == b); REQUIRE(a == r.begin()); REQUIRE(a == r.end()); REQUIRE(r.empty()); REQUIRE(r.size() == 0); REQUIRE(r.begin() == r.end()); }
#include <test.hpp> TEST_CASE("default constructed varint_iterators are equal") { protozero::const_varint_iterator<uint32_t> a{}; protozero::const_varint_iterator<uint32_t> b{}; protozero::iterator_range<protozero::const_varint_iterator<uint32_t>> r{}; REQUIRE(a == a); REQUIRE(a == b); REQUIRE(a == r.begin()); REQUIRE(a == r.end()); REQUIRE(r.empty()); REQUIRE(r.size() == 0); // NOLINT(readability-container-size-empty) REQUIRE(r.begin() == r.end()); }
Convert Binary Number in a Linked List to Integer
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: int getDecimalValue(ListNode* head) { std::vector<int> v; while (head) { v.emplace_back(head->val); head = head->next; } int ret = 0, index = 1; for (int i = 0; i < v.size(); ++i) { ret += v[v.size()-i-1] * index; index *= 2; } return ret; } };
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: int getDecimalValue(ListNode* head) { std::vector<int> v; while (head) { v.emplace_back(head->val); head = head->next; } int ret = 0, index = 1; for (int i = 0; i < v.size(); ++i) { ret += v[v.size()-i-1] * index; index *= 2; } return ret; } }; /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: int getDecimalValue(ListNode* head) { std::vector<int> nums; nums.reserve(30); while (head) { nums.emplace_back(head->val); head = head->next; } int mul = 1; int ret = 0; for (int i = nums.size()-1; i >= 0; --i) { ret += mul * nums[i]; mul *= 2; } return ret; } };
Use cppassist to determine path
#include <gloperate/gloperate.h> #include <cpplocate/cpplocate.h> namespace { std::string determineDataPath() { std::string path = cpplocate::locatePath("data/gloperate", "share/gloperate", reinterpret_cast<void *>(&gloperate::dataPath)); if (path.empty()) path = "./data"; else path = path + "/data"; return path; } std::string getDirectoryPath(const std::string & fullpath) { if (fullpath.empty()) { return ""; } auto pos = fullpath.rfind("/"); const auto posBack = fullpath.rfind("\\"); if (pos == std::string::npos || (posBack != std::string::npos && posBack > pos)) { pos = posBack; } return fullpath.substr(0, pos); } std::string determinePluginPath() { std::string path = getDirectoryPath(cpplocate::getLibraryPath(reinterpret_cast<void *>(&gloperate::dataPath))); return path; } } // namespace namespace gloperate { const std::string & dataPath() { static const auto path = determineDataPath(); return path; } const std::string & pluginPath() { static const auto path = determinePluginPath(); return path; } } // namespace gloperate
#include <gloperate/gloperate.h> #include <cppassist/fs/FilePath.h> #include <cpplocate/cpplocate.h> namespace { std::string determineDataPath() { std::string path = cpplocate::locatePath("data/gloperate", "share/gloperate", reinterpret_cast<void *>(&gloperate::dataPath)); if (path.empty()) path = "./data"; else path = path + "/data"; return path; } std::string determinePluginPath() { std::string path = cppassist::FilePath(cpplocate::getLibraryPath(reinterpret_cast<void *>(&gloperate::dataPath))).directoryPath(); path = cppassist::FilePath(path).path(); return path; } } // namespace namespace gloperate { const std::string & dataPath() { static const auto path = determineDataPath(); return path; } const std::string & pluginPath() { static const auto path = determinePluginPath(); return path; } } // namespace gloperate
Return 0 instead of NULL for a non-pointer type. Eliminates a warning in GCC.
#include "SkTypeface.h" // ===== Begin Chrome-specific definitions ===== uint32_t SkTypeface::UniqueID(const SkTypeface* face) { return NULL; } void SkTypeface::serialize(SkWStream* stream) const { } SkTypeface* SkTypeface::Deserialize(SkStream* stream) { return NULL; } // ===== End Chrome-specific definitions =====
#include "SkTypeface.h" // ===== Begin Chrome-specific definitions ===== uint32_t SkTypeface::UniqueID(const SkTypeface* face) { return 0; } void SkTypeface::serialize(SkWStream* stream) const { } SkTypeface* SkTypeface::Deserialize(SkStream* stream) { return NULL; } // ===== End Chrome-specific definitions =====
Add log for insecure buils
/* * * Copyright 2015 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 <grpc/support/port_platform.h> #include "src/core/lib/surface/init.h" void grpc_security_pre_init(void) {} void grpc_register_security_filters(void) {} void grpc_security_init(void) {}
/* * * Copyright 2015 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 <grpc/support/port_platform.h> #include <grpc/support/log.h> #include "src/core/lib/surface/init.h" void grpc_security_pre_init(void) {} void grpc_register_security_filters(void) {} void grpc_security_init(void) { gpr_log(GPR_DEBUG, "Using insecure gRPC build. Security handshakers will not be invoked " "even if secure credentials are used."); }
Change partition() to return pivot instead of pe
#include "../quick.hpp" #include "../swap.hpp" void quick(int *data, const int size_of_data) { return quick(data, 0, size_of_data - 1); } void quick(int *data, const int start, const int end) { int size = end - start + 1; if(start >= end) return; /* Base case */ /* Conquer */ int pivot = partition(data, start, end); /* Divide */ quick(data, start, pivot - 1); quick(data, pivot + 1, end); } int partition(int *data, const int start, const int end) { int pivot = end; /* Set pivot */ int ps = start, pe = end - 1; while(ps < pe) { while(ps < pe && data[ps] < data[pivot]) ++ps; while(ps < pe && data[pe] >= data[pivot]) --pe; if(ps < pe) swap(data[ps], data[pe]); } if(data[pe] > data[pivot]) swap(data[pe], data[pivot]); else if(pe == end - 1) ++pe; return pe; }
#include "../quick.hpp" #include "../swap.hpp" void quick(int *data, const int size_of_data) { return quick(data, 0, size_of_data - 1); } void quick(int *data, const int start, const int end) { int size = end - start + 1; if(start >= end) return; /* Base case */ /* Conquer */ int pivot = partition(data, start, end); /* Divide */ quick(data, start, pivot - 1); quick(data, pivot + 1, end); } int partition(int *data, const int start, const int end) { int pivot = end; /* Set pivot */ int ps = start, pe = end - 1; while(ps != pe) { while(ps < pe && data[ps] < data[pivot]) ++ps; while(ps < pe && data[pe] >= data[pivot]) --pe; if(ps < pe) swap(data[ps], data[pe]); } if(data[pivot] < data[pe]) { swap(data[pivot], data[pe]); pivot = pe; } return pivot; }
Remove Elevatorup/down command from oi
#include "OI.h" #include "RobotMap.h" #include "Commands/ElevatorUpCommand.h" #include "Commands/ElevatorDownCommand.h" OI::OI() : joystick(JOYSTICK) { // Process operator interface input here. }
#include "OI.h" #include "RobotMap.h" OI::OI() : joystick(JOYSTICK) { // Process operator interface input here. }
Revert "small fix to make notQuery working proper"
#include "NOTDocumentIterator.h" using namespace sf1r; using namespace std; NOTDocumentIterator::NOTDocumentIterator() { setNot(true); } NOTDocumentIterator::~NOTDocumentIterator() { } void NOTDocumentIterator::add(DocumentIterator* pDocIterator) { docIteratorList_.push_back(pDocIterator); } bool NOTDocumentIterator::next() { return do_next(); }
#include "NOTDocumentIterator.h" using namespace sf1r; using namespace std; NOTDocumentIterator::NOTDocumentIterator() { } NOTDocumentIterator::~NOTDocumentIterator() { } void NOTDocumentIterator::add(DocumentIterator* pDocIterator) { docIteratorList_.push_back(pDocIterator); } bool NOTDocumentIterator::next() { return do_next(); }
Return the Module that we just materialized.
//===-- ModuleProvider.cpp - Base implementation for module providers -----===// // // Minimal implementation of the abstract interface for providing a module. // //===----------------------------------------------------------------------===// #include "llvm/ModuleProvider.h" #include "llvm/Module.h" /// ctor - always have a valid Module /// ModuleProvider::ModuleProvider() : TheModule(0) { } /// dtor - when we leave, we take our Module with us /// ModuleProvider::~ModuleProvider() { delete TheModule; } /// materializeFunction - make sure the given function is fully read. /// void ModuleProvider::materializeModule() { if (!TheModule) return; for (Module::iterator i = TheModule->begin(), e = TheModule->end(); i != e; ++i) materializeFunction(i); }
//===-- ModuleProvider.cpp - Base implementation for module providers -----===// // // Minimal implementation of the abstract interface for providing a module. // //===----------------------------------------------------------------------===// #include "llvm/ModuleProvider.h" #include "llvm/Module.h" /// ctor - always have a valid Module /// ModuleProvider::ModuleProvider() : TheModule(0) { } /// dtor - when we leave, we take our Module with us /// ModuleProvider::~ModuleProvider() { delete TheModule; } /// materializeFunction - make sure the given function is fully read. /// Module* ModuleProvider::materializeModule() { // FIXME: throw an exception instead? if (!TheModule) return 0; for (Module::iterator i = TheModule->begin(), e = TheModule->end(); i != e; ++i) materializeFunction(i); return TheModule; }
Remove unused arguments from test (fix warnings).
#include "tclap/CmdLine.h" #include <vector> #include <string> using namespace TCLAP; using namespace std; // https://sourceforge.net/p/tclap/bugs/30/ int main(int argc, char** argv) { CmdLine cmd("test empty argv"); std::vector<string> args; cmd.parse(args); }
#include "tclap/CmdLine.h" #include <vector> #include <string> using namespace TCLAP; using namespace std; // https://sourceforge.net/p/tclap/bugs/30/ int main() { CmdLine cmd("test empty argv"); std::vector<string> args; cmd.parse(args); }
Update to use new getStringOutput function of MatasanoConverter. Add line break after test pass message
#include <iostream> #include <string> #include "MatasanoConverter.h" using namespace std; int main() { string hexInput("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"); string testString = ("SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"); string result; MatasanoConverter m; m.loadString(hexInput, "hex"); result = m.getBase64(); cout << "Challenge 1: "; if (result.compare(testString) == 0) { cout << "PASSED" << endl << "Input: " << hexInput << endl << "Output: " << result << endl << "As Required."; } else { cout << "FAILED" << endl << "Input: " << hexInput << endl << "Expected: " << testString << endl << "Observed: " << result << endl; } }
#include <iostream> #include <string> #include "MatasanoConverter.h" using namespace std; int main() { string hexInput("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"); string testString = ("SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"); string result; MatasanoConverter m; m.loadString(hexInput, "hex"); result = m.getStringOutput("b64"); cout << "Challenge 1: "; if (result.compare(testString) == 0) { cout << "PASSED" << endl << "Input: " << hexInput << endl << "Output: " << result << endl << "As Required." << endl; } else { cout << "FAILED" << endl << "Input: " << hexInput << endl << "Expected: " << testString << endl << "Observed: " << result << endl; } }
Add CPU affinity to gcc build
#include "Platform.h" #include <stdio.h> void testRDTSC ( void ) { int64_t temp = rdtsc(); printf("%d",(int)temp); } #if defined(_MSC_VER) #include <windows.h> void SetAffinity ( int cpu ) { SetProcessAffinityMask(GetCurrentProcess(),cpu); SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST); } #else void SetAffinity ( int /*cpu*/ ) { } #endif
#include "Platform.h" #include <stdio.h> void testRDTSC ( void ) { int64_t temp = rdtsc(); printf("%d",(int)temp); } #if defined(_MSC_VER) #include <windows.h> void SetAffinity ( int cpu ) { SetProcessAffinityMask(GetCurrentProcess(),cpu); SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST); } #else #include <sched.h> void SetAffinity ( int /*cpu*/ ) { cpu_set_t mask; CPU_ZERO(&mask); CPU_SET(2,&mask); if( sched_setaffinity(0,sizeof(mask),&mask) == -1) { printf("WARNING: Could not set CPU affinity\n"); } } #endif
Mark a test as flaky on ChromeOS.
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" #if defined(TOOLKIT_VIEWS) // Need to port ExtensionInfoBarDelegate::CreateInfoBar() to other platforms. // See http://crbug.com/39916 for details. #define MAYBE_Infobars Infobars #else #define MAYBE_Infobars DISABLED_Infobars #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) { // TODO(finnur): Remove once infobars are no longer experimental (bug 39511). CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("infobars")) << message_; }
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" #if defined(TOOLKIT_VIEWS) #if defined (OS_WIN) #define MAYBE_Infobars Infobars #else // Flaky on ChromeOS, see http://crbug.com/40141. #define MAYBE_Infobars FLAKY_Infobars #endif #else // Need to port ExtensionInfoBarDelegate::CreateInfoBar() to other platforms. // See http://crbug.com/39916 for details. #define MAYBE_Infobars DISABLED_Infobars #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) { // TODO(finnur): Remove once infobars are no longer experimental (bug 39511). CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("infobars")) << message_; }
Allow static build on Windows
// Windy - main.cpp // Copyright (c) 2015 Arkadiusz Bokowy // // This file is a part of Windy. // // This projected is licensed under the terms of the MIT license. #include "Application.h" int main(int argc, char *argv[]) { Application app(argc, argv); return app.exec(); }
// Windy - main.cpp // Copyright (c) 2015 Arkadiusz Bokowy // // This file is a part of Windy. // // This projected is licensed under the terms of the MIT license. #include "Application.h" #if defined(Q_OS_WIN) && !defined(_DLL) // This sections allows static build on the Windows platform using MSVC++ // compiler. During the non-DLL build the _DLL is not defined. In such a // case we will enforce plug-ins to be loaded, which in turn will generate // linking errors if one omits them. #include <QtPlugin> Q_IMPORT_PLUGIN(QSvgIconPlugin) Q_IMPORT_PLUGIN(QSvgPlugin) Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin) #endif // Q_OS_WIN && !_DLL int main(int argc, char *argv[]) { Application app(argc, argv); return app.exec(); }
Set unused throttle message fields to zero.
#include "motor/esra_payload_motor_mapper.hpp" #include <array> #include <cstddef> #include "protocol/messages.hpp" EsraPayloadMotorMapper::EsraPayloadMotorMapper(PWMDeviceGroup<1>& motors, Communicator& communicator) : motors(motors), throttleStream(communicator, 5) { } void EsraPayloadMotorMapper::run(bool armed, ActuatorSetpoint& input) { // We only have one motor for now, but just in case.. std::array<float, 1> outputs; outputs[0] = input.throttle; motors.set(armed, outputs); if(throttleStream.ready()) { protocol::message::motor_throttle_message_t msg; msg.throttles[0] = outputs[0]; throttleStream.publish(msg); } }
#include "motor/esra_payload_motor_mapper.hpp" #include <array> #include <cstddef> #include "protocol/messages.hpp" EsraPayloadMotorMapper::EsraPayloadMotorMapper(PWMDeviceGroup<1>& motors, Communicator& communicator) : motors(motors), throttleStream(communicator, 5) { } void EsraPayloadMotorMapper::run(bool armed, ActuatorSetpoint& input) { // We only have one motor for now, but just in case.. std::array<float, 1> outputs; outputs[0] = input.throttle; motors.set(armed, outputs); if(throttleStream.ready()) { protocol::message::motor_throttle_message_t msg; msg.throttles[0] = outputs[0]; msg.throttles[1] = 0; msg.throttles[2] = 0; msg.throttles[3] = 0; throttleStream.publish(msg); } }
Fix build - missing header.
/** @file @brief Implementation @date 2014 @author Ryan Pavlik <ryan@sensics.com> <http://sensics.com> */ // Copyright 2014 Sensics, Inc. // // All rights reserved. // // (Final version intended to be licensed under // the Apache License, Version 2.0) // Internal Includes #include <ogvr/Client/CreateContext.h> #include "VRPNContext.h" // Library/third-party includes // - none // Standard includes // - none namespace ogvr { namespace client { ClientContext *createContext(const char appId[], const char host[]) { if (!appId || strlen(appId) == 0) { return NULL; } VRPNContext *ret = new VRPNContext(appId, host); return ret; } } // namespace client } // namespace ogvr
/** @file @brief Implementation @date 2014 @author Ryan Pavlik <ryan@sensics.com> <http://sensics.com> */ // Copyright 2014 Sensics, Inc. // // All rights reserved. // // (Final version intended to be licensed under // the Apache License, Version 2.0) // Internal Includes #include <ogvr/Client/CreateContext.h> #include "VRPNContext.h" // Library/third-party includes // - none // Standard includes #include <cstring> namespace ogvr { namespace client { ClientContext *createContext(const char appId[], const char host[]) { if (!appId || std::strlen(appId) == 0) { return NULL; } VRPNContext *ret = new VRPNContext(appId, host); return ret; } } // namespace client } // namespace ogvr
Make tests outcome easier to check.
#include <bin/tests.hh> BEGIN_TEST(removecallbacks, client, ) client.setCallback(&dump, "error"); // ping urbi::UCallbackID i1 = client.setCallback(&dump, "output"); urbi::UCallbackID i2 = client.setCallback(&dump, "output"); SEND("output << 1;"); //= D output 1 //= D output 1 dumpSem--; dumpSem--; SEND("error << 1;"); //ping //= D error 1 dumpSem--; client.deleteCallback(i1); SEND("output << 1;"); //= D output 1 SEND("error << 1;"); //ping //= D error 1 dumpSem--; dumpSem--; client.deleteCallback(i2); SEND("output << 1;"); //no callback left, not displayed SEND("error << 1;"); //ping //= D error 1 dumpSem--; client.setCallback(&removeOnZero, "output"); SEND("output << 1;"); //= D output 1 SEND("output << 0;"); //= D output 0 SEND("output << 1;"); SEND("error << 1;"); //ping //= D error 1 sleep(5); END_TEST
#include <bin/tests.hh> BEGIN_TEST(removecallbacks, client, ) client.setCallback(&dump, "error"); // ping urbi::UCallbackID i1 = client.setCallback(&dump, "output"); urbi::UCallbackID i2 = client.setCallback(&dump, "output"); SEND("output << 1;"); //= D output 1 //= D output 1 dumpSem--; dumpSem--; SEND("error << 2;"); //ping //= D error 2 dumpSem--; client.deleteCallback(i1); SEND("output << 3;"); //= D output 3 SEND("error << 4;"); //ping //= D error 4 dumpSem--; dumpSem--; client.deleteCallback(i2); SEND("output << 5;"); //no callback left, not displayed SEND("error << 6;"); //ping //= D error 6 dumpSem--; client.setCallback(&removeOnZero, "output"); SEND("output << 7;"); //= D output 7 SEND("output << 0;"); //= D output 0 SEND("output << 9;"); SEND("error << 10;"); //ping //= D error 10 sleep(5); END_TEST
Delete messages from rabbitmq once received
#include "MessageQueue.h" #include <vector> MessageQueue::MessageQueue(std::string identifier, std::string serverAddr, unsigned int serverPort, std::function<void(std::string) > onMessage) : identifier(identifier), mqConnection(&mqHandler, "amqp://" + serverAddr + ":" + std::to_string(serverPort)), channel(&mqConnection) { channel.declareQueue(identifier); channel.declareExchange("ctlms_exchanger", AMQP::ExchangeType::direct); channel.bindQueue("ctlms_exchanger", identifier, "ALL"); channel.bindQueue("ctlms_exchanger", identifier, identifier); channel.consume(identifier).onSuccess([]() { std::cout << "Starting to consume messages." << std::endl; }).onMessage([onMessage](const AMQP::Message &message, uint64_t deliveryTag, bool redelivered) { onMessage(std::string(message.body(), message.bodySize())); }).onError([](const char *message) { std::cout << "Error with the consumer: " << message << std::endl; }); } MessageQueue::~MessageQueue() { channel.removeQueue(identifier); } void MessageQueue::update() { for (auto fd : mqHandler.fdToMonitor) { int count = 0; ioctl(fd, FIONREAD, &count); if (count > 0) { mqConnection.process(fd, AMQP::readable | AMQP::writable); } } }
#include "MessageQueue.h" #include <vector> MessageQueue::MessageQueue(std::string identifier, std::string serverAddr, unsigned int serverPort, std::function<void(std::string) > onMessage) : identifier(identifier), mqConnection(&mqHandler, "amqp://" + serverAddr + ":" + std::to_string(serverPort)), channel(&mqConnection) { channel.declareQueue(identifier); channel.declareExchange("ctlms_exchanger", AMQP::ExchangeType::direct); channel.bindQueue("ctlms_exchanger", identifier, "ALL"); channel.bindQueue("ctlms_exchanger", identifier, identifier); channel.consume(identifier).onSuccess([]() { std::cout << "Starting to consume messages." << std::endl; }).onMessage([onMessage, this](const AMQP::Message &message, uint64_t deliveryTag, bool redelivered) { onMessage(std::string(message.body(), message.bodySize())); channel.ack(deliveryTag); // Delete the message from the queue }).onError([](const char *message) { std::cout << "Error with the consumer: " << message << std::endl; }); } MessageQueue::~MessageQueue() { channel.removeQueue(identifier); } void MessageQueue::update() { for (auto fd : mqHandler.fdToMonitor) { int count = 0; ioctl(fd, FIONREAD, &count); if (count > 0) { mqConnection.process(fd, AMQP::readable | AMQP::writable); } } }
Remove duplicate header in template source file
#include <functional> #include <iostream> #include <spdlog/spdlog.h> #include <docopt/docopt.h> #include <iostream> static constexpr auto USAGE = R"(Naval Fate. Usage: naval_fate ship new <name>... naval_fate ship <name> move <x> <y> [--speed=<kn>] naval_fate ship shoot <x> <y> naval_fate mine (set|remove) <x> <y> [--moored | --drifting] naval_fate (-h | --help) naval_fate --version Options: -h --help Show this screen. --version Show version. --speed=<kn> Speed in knots [default: 10]. --moored Moored (anchored) mine. --drifting Drifting mine. )"; int main(int argc, const char **argv) { std::map<std::string, docopt::value> args = docopt::docopt(USAGE, { std::next(argv), std::next(argv, argc) }, true,// show help if requested "Naval Fate 2.0");// version string for (auto const &arg : args) { std::cout << arg.first << arg.second << std::endl; } //Use the default logger (stdout, multi-threaded, colored) spdlog::info("Hello, {}!", "World"); fmt::print("Hello, from {}\n", "{fmt}"); }
#include <functional> #include <iostream> #include <spdlog/spdlog.h> #include <docopt/docopt.h> static constexpr auto USAGE = R"(Naval Fate. Usage: naval_fate ship new <name>... naval_fate ship <name> move <x> <y> [--speed=<kn>] naval_fate ship shoot <x> <y> naval_fate mine (set|remove) <x> <y> [--moored | --drifting] naval_fate (-h | --help) naval_fate --version Options: -h --help Show this screen. --version Show version. --speed=<kn> Speed in knots [default: 10]. --moored Moored (anchored) mine. --drifting Drifting mine. )"; int main(int argc, const char **argv) { std::map<std::string, docopt::value> args = docopt::docopt(USAGE, { std::next(argv), std::next(argv, argc) }, true,// show help if requested "Naval Fate 2.0");// version string for (auto const &arg : args) { std::cout << arg.first << arg.second << std::endl; } //Use the default logger (stdout, multi-threaded, colored) spdlog::info("Hello, {}!", "World"); fmt::print("Hello, from {}\n", "{fmt}"); }
Add a compilation test for mart::tmp::cartesian_value_product
#include <mart-common/experimental/tmp.h>
#include <mart-common/experimental/tmp.h> #include <tuple> namespace { constexpr auto v_list1 = mart::tmp::value_list<int, 1, 2, 3, 4, 5>{}; constexpr auto v_list2 = mart::tmp::value_list<char, 'H', 'e', 'l', 'l', 'o'>{}; static_assert( mart::tmp::get_Nth_element( 2, v_list1 ) == 3 ); template<int First, char Second> struct Type { static constexpr int first = First; static constexpr char second = Second; }; template<class... T> struct type_list {}; auto mtype = mart::tmp::cartesian_value_product<std::tuple,int,char, Type>( v_list1, v_list2 ); } // namespace
Load the correct fonts and reset hinting for Android layout tests
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/shell/webkit_test_platform_support.h" namespace content { bool CheckLayoutSystemDeps() { return true; } bool WebKitTestPlatformInitialize() { return true; } } // namespace
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/shell/webkit_test_platform_support.h" #include "third_party/skia/include/ports/SkTypeface_android.h" namespace { // The root directory on the device to which resources will be pushed. This // value needs to be equal to that set in chromium_android.py. #define DEVICE_SOURCE_ROOT_DIR "/data/local/tmp/content_shell/" // Primary font configuration file on the device for Skia. const char kPrimaryFontConfig[] = DEVICE_SOURCE_ROOT_DIR "android_main_fonts.xml"; // The file on the device containing the fallback font configuration for Skia. const char kFallbackFontConfig[] = DEVICE_SOURCE_ROOT_DIR "android_fallback_fonts.xml"; // The directory in which fonts will be stored on the Android device. const char kFontDirectory[] = DEVICE_SOURCE_ROOT_DIR "fonts/"; } // namespace namespace content { bool CheckLayoutSystemDeps() { return true; } bool WebKitTestPlatformInitialize() { // Initialize Skia with the font configuration files crafted for layout tests. SkUseTestFontConfigFile( kPrimaryFontConfig, kFallbackFontConfig, kFontDirectory); return true; } } // namespace content
Use a more specific application name for use in UA discrimination
#include "HumbugWindow.h" #include "HumbugApplication.h" #include "Config.h" #ifdef Q_OS_MAC #include "mac/Setup.h" #endif int main(int argc, char *argv[]) { HumbugApplication a(argc, argv); a.setApplicationName("Humbug"); a.setApplicationVersion(HUMBUG_VERSION_STRING); QCoreApplication::setOrganizationName("Humbug"); QCoreApplication::setOrganizationDomain("humbug.com"); QCoreApplication::setApplicationName("Humbug"); HumbugWindow w; if (argc == 3 && QString(argv[1]) == QString("--site")) { w.setUrl(QUrl(argv[2])); } #ifdef Q_OS_MAC macMain(); #endif a.setMainWindow(&w); w.show(); return a.exec(); }
#include "HumbugWindow.h" #include "HumbugApplication.h" #include "Config.h" #ifdef Q_OS_MAC #include "mac/Setup.h" #endif int main(int argc, char *argv[]) { HumbugApplication a(argc, argv); a.setApplicationName("Humbug"); a.setApplicationVersion(HUMBUG_VERSION_STRING); QCoreApplication::setOrganizationName("Humbug"); QCoreApplication::setOrganizationDomain("humbug.com"); QCoreApplication::setApplicationName("Humbug Desktop"); HumbugWindow w; if (argc == 3 && QString(argv[1]) == QString("--site")) { w.setUrl(QUrl(argv[2])); } #ifdef Q_OS_MAC macMain(); #endif a.setMainWindow(&w); w.show(); return a.exec(); }
Add note about negative indexes when using Apply
#include <lua.hpp> #include <luwra.hpp> #include <iostream> using namespace luwra; static double sum3(int a, int b, double c) { return (a + b) * c; } int main() { lua_State* state = luaL_newstate(); luaL_openlibs(state); // Build stack lua_pushinteger(state, 13); lua_pushinteger(state, 37); lua_pushnumber(state, 42); // Each value can be retrieved individually. std::cout << "a = " << Value<int>::Read(state, 1) << std::endl; std::cout << "b = " << Value<int>::Read(state, 2) << std::endl; std::cout << "c = " << Value<double>::Read(state, 3) << std::endl; // ... which is a little cumbersome. Instead we might apply a fitting function to our stack. std::cout << "(a + b) * c = " << Apply(state, sum3) << std::endl; lua_close(state); return 0; }
#include <lua.hpp> #include <luwra.hpp> #include <iostream> using namespace luwra; static double sum3(int a, int b, double c) { return (a + b) * c; } int main() { lua_State* state = luaL_newstate(); luaL_openlibs(state); // Build stack lua_pushinteger(state, 13); lua_pushinteger(state, 37); lua_pushnumber(state, 42); // Each value can be retrieved individually. std::cout << "a = " << Value<int>::Read(state, 1) << std::endl; std::cout << "b = " << Value<int>::Read(state, 2) << std::endl; std::cout << "c = " << Value<double>::Read(state, 3) << std::endl; // ... which is a little cumbersome. Instead we might apply a fitting function to our stack. std::cout << "(a + b) * c = " << Apply(state, sum3) // Equivalent to Apply(state, 1, sum3) or Apply(state, -3, sum3) << std::endl; lua_close(state); return 0; }
Convert to use Handlers. Could be simpler.
#include <unistd.h> #include <event/event_callback.h> #include <event/event_main.h> #include <io/stream_handle.h> class Sink { LogHandle log_; StreamHandle fd_; Action *action_; public: Sink(int fd) : log_("/sink"), fd_(fd), action_(NULL) { EventCallback *cb = callback(this, &Sink::read_complete); action_ = fd_.read(0, cb); } ~Sink() { ASSERT(log_, action_ == NULL); } void read_complete(Event e) { action_->cancel(); action_ = NULL; switch (e.type_) { case Event::Done: case Event::EOS: break; default: HALT(log_) << "Unexpected event: " << e; return; } if (e.type_ == Event::EOS) { SimpleCallback *cb = callback(this, &Sink::close_complete); action_ = fd_.close(cb); return; } EventCallback *cb = callback(this, &Sink::read_complete); action_ = fd_.read(0, cb); } void close_complete(void) { action_->cancel(); action_ = NULL; } }; int main(void) { Sink sink(STDIN_FILENO); event_main(); }
#include <unistd.h> #include <event/callback_handler.h> #include <event/event_callback.h> #include <event/event_handler.h> #include <event/event_main.h> #include <io/stream_handle.h> class Sink { LogHandle log_; StreamHandle fd_; CallbackHandler close_handler_; EventHandler read_handler_; public: Sink(int fd) : log_("/sink"), fd_(fd), read_handler_() { read_handler_.handler(Event::Done, this, &Sink::read_done); read_handler_.handler(Event::EOS, this, &Sink::read_eos); close_handler_.handler(this, &Sink::close_done); read_handler_.wait(fd_.read(0, read_handler_.callback())); } ~Sink() { } void read_done(Event) { read_handler_.wait(fd_.read(0, read_handler_.callback())); } void read_eos(Event) { close_handler_.wait(fd_.close(close_handler_.callback())); } void close_done(void) { } }; int main(void) { Sink sink(STDIN_FILENO); event_main(); }
Disable low memory device check for JB and lower
// Copyright 2013 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/android/sys_utils.h" #include "base/sys_info.h" #include "jni/SysUtils_jni.h" // Any device that reports a physical RAM size less than this, in megabytes // is considered 'low-end'. IMPORTANT: Read the LinkerLowMemoryThresholdTest // comments in build/android/pylib/linker/test_case.py before modifying this // value. #define ANDROID_LOW_MEMORY_DEVICE_THRESHOLD_MB 512 const int64 kLowEndMemoryThreshold = 1024 * 1024 * ANDROID_LOW_MEMORY_DEVICE_THRESHOLD_MB; // Defined and called by JNI static jboolean IsLowEndDevice(JNIEnv* env, jclass clazz) { return base::android::SysUtils::IsLowEndDevice(); } namespace base { namespace android { bool SysUtils::Register(JNIEnv* env) { return RegisterNativesImpl(env); } bool SysUtils::IsLowEndDevice() { return SysInfo::AmountOfPhysicalMemory() <= kLowEndMemoryThreshold; } SysUtils::SysUtils() { } } // namespace android } // namespace base
// Copyright 2013 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/android/sys_utils.h" #include "base/android/build_info.h" #include "base/sys_info.h" #include "jni/SysUtils_jni.h" // Any device that reports a physical RAM size less than this, in megabytes // is considered 'low-end'. IMPORTANT: Read the LinkerLowMemoryThresholdTest // comments in build/android/pylib/linker/test_case.py before modifying this // value. #define ANDROID_LOW_MEMORY_DEVICE_THRESHOLD_MB 512 const int64 kLowEndMemoryThreshold = 1024 * 1024 * ANDROID_LOW_MEMORY_DEVICE_THRESHOLD_MB; // Only support low end device changes on builds greater than JB MR2. const int kLowEndSdkIntThreshold = 18; // Defined and called by JNI static jboolean IsLowEndDevice(JNIEnv* env, jclass clazz) { return base::android::SysUtils::IsLowEndDevice(); } namespace base { namespace android { bool SysUtils::Register(JNIEnv* env) { return RegisterNativesImpl(env); } bool SysUtils::IsLowEndDevice() { return SysInfo::AmountOfPhysicalMemory() <= kLowEndMemoryThreshold && BuildInfo::GetInstance()->sdk_int() > kLowEndSdkIntThreshold; } SysUtils::SysUtils() { } } // namespace android } // namespace base