Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Fix the not matching header file path
#include <stdio.h> #include "../excercise04/make_random_data/make_random_data.hpp" #include "../excercise04/sort/quick.hpp" int get_index_smallest(const int k, int *data, const int start, const int end) { if(k < 0 || k > end) return -1; /* Base case */ int p = partition(data, start, end); if(k == 0) return data[start]; else if(p - start == k) return data[p]; else if(p - start > k) return get_index_smallest(k, data, start, p - 1); else return get_index_smallest(k - p - 1, data, p + 1, end); } int main(void) { int k; printf("Enter k= "); scanf("%d", &k); const int size = 100000; int *data = make_random_data(size); printf("%d\n", get_index_smallest(k, data, 0, size - 1)); free_random_data(data); return 0; }
#include <stdio.h> #include "../excercise04/make_random_data/make_random_data.hpp" #include "../excercise04/sort/quicksort.hpp" int get_index_smallest(const int k, int *data, const int start, const int end) { if(k < 0 || k > end) return -1; /* Base case */ int p = partition(data, start, end); if(k == 0) return data[start]; else if(p - start == k) return data[p]; else if(p - start > k) return get_index_smallest(k, data, start, p - 1); else return get_index_smallest(k - p - 1, data, p + 1, end); } int main(void) { int k; printf("Enter k= "); scanf("%d", &k); const int size = 100000; int *data = make_random_data(size); printf("%d\n", get_index_smallest(k, data, 0, size - 1)); free_random_data(data); return 0; }
Check that region list isn't empty before attempting to retrieve a region from it
/* * This file is part of Maliit framework * * * Copyright (C) 2014 Dinesh Manajipet <saidinesh5@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation * and appearing in the file LICENSE.LGPL included in the packaging * of this file. */ #include "mirplatform.h" #include "mirplatformconnection.h" #include <QRegion> #include <QWindow> namespace Maliit { MirPlatform::MirPlatform(): AbstractPlatform(), m_mirPlatformConnection(new MirPlatformConnection) { } void MirPlatform::setupInputPanel(QWindow *window, Maliit::Position position) { Q_UNUSED(window) Q_UNUSED(position) } void MirPlatform::setInputRegion(QWindow *window, const QRegion &region) { Q_UNUSED(window) m_mirPlatformConnection->setGeometry(region.rects().first()); } }
/* * This file is part of Maliit framework * * * Copyright (C) 2014 Dinesh Manajipet <saidinesh5@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation * and appearing in the file LICENSE.LGPL included in the packaging * of this file. */ #include "mirplatform.h" #include "mirplatformconnection.h" #include <QRegion> #include <QWindow> namespace Maliit { MirPlatform::MirPlatform(): AbstractPlatform(), m_mirPlatformConnection(new MirPlatformConnection) { } void MirPlatform::setupInputPanel(QWindow *window, Maliit::Position position) { Q_UNUSED(window) Q_UNUSED(position) } void MirPlatform::setInputRegion(QWindow *window, const QRegion &region) { Q_UNUSED(window) if (!region.rects().isEmpty()) { m_mirPlatformConnection->setGeometry(region.rects().first()); } } }
Fix typo in exception documentation
#define SOL_ALL_SAFETIES_ON 1 #include <sol/sol.hpp> #include <iostream> inline void my_panic(sol::optional<std::string> maybe_msg) { std::cerr << "Lua is in a panic state and will now abort() the application" << std::endl; if (maybe_msg) { const std::string& msg = maybe_msg.value(); std::cerr << "\terror message: " << msg << std::endl; } // When this function exits, Lua will exhibit default behavior and abort() } int main (int, char*[]) { sol::state lua(sol::c_call<decltype(&my_panic), &my_panic>); // or, if you already have a lua_State* L // lua_atpanic( L, sol::c_call<decltype(&my_panic)>, &my_panic> ); // or, with state/state_view: // sol::state_view lua(L); // lua.set_panic( sol::c_call<decltype(&my_panic)>, &my_panic> ); // uncomment the below to see //lua.script("boom_goes.the_dynamite"); return 0; }
#define SOL_ALL_SAFETIES_ON 1 #include <sol/sol.hpp> #include <iostream> inline void my_panic(sol::optional<std::string> maybe_msg) { std::cerr << "Lua is in a panic state and will now abort() the application" << std::endl; if (maybe_msg) { const std::string& msg = maybe_msg.value(); std::cerr << "\terror message: " << msg << std::endl; } // When this function exits, Lua will exhibit default behavior and abort() } int main (int, char*[]) { sol::state lua(sol::c_call<decltype(&my_panic), &my_panic>); // or, if you already have a lua_State* L // lua_atpanic( L, sol::c_call<decltype(&my_panic), &my_panic> ); // or, with state/state_view: // sol::state_view lua(L); // lua.set_panic( sol::c_call<decltype(&my_panic), &my_panic> ); // uncomment the below to see //lua.script("boom_goes.the_dynamite"); return 0; }
Call InitializeMagick to make sure all initializers are called.
#include <Magick++/ResourceLimits.h> #include <Magick++/SecurityPolicy.h> #ifndef FUZZ_MAX_SIZE #define FUZZ_MAX_SIZE 2048 #endif class FuzzingLimits { public: FuzzingLimits() { Magick::SecurityPolicy::maxMemoryRequest(256000000); Magick::ResourceLimits::memory(1000000000); Magick::ResourceLimits::map(500000000); Magick::ResourceLimits::width(FUZZ_MAX_SIZE); Magick::ResourceLimits::height(FUZZ_MAX_SIZE); Magick::ResourceLimits::listLength(32); } }; FuzzingLimits fuzzingLimits; #if BUILD_MAIN #include "encoder_format.h" EncoderFormat encoderFormat; #define FUZZ_ENCODER encoderFormat.get() #endif // BUILD_MAIN
#include <Magick++/Functions.h> #include <Magick++/ResourceLimits.h> #include <Magick++/SecurityPolicy.h> #ifndef FUZZ_MAX_SIZE #define FUZZ_MAX_SIZE 2048 #endif class FuzzingInitializer { public: FuzzingInitializer() { Magick::InitializeMagick((const char *) NULL); Magick::SecurityPolicy::maxMemoryRequest(256000000); Magick::ResourceLimits::memory(1000000000); Magick::ResourceLimits::map(500000000); Magick::ResourceLimits::width(FUZZ_MAX_SIZE); Magick::ResourceLimits::height(FUZZ_MAX_SIZE); Magick::ResourceLimits::listLength(32); } }; FuzzingInitializer fuzzingInitializer; #if BUILD_MAIN #include "encoder_format.h" EncoderFormat encoderFormat; #define FUZZ_ENCODER encoderFormat.get() #endif // BUILD_MAIN
Test now initializes using variables_init()
#define NO_EXTERN #include"variables.hpp" #include"processes.hpp" #include<iostream> int main(int argc, const char* argv[]){ globals.reset(new Globals()); NILATOM = globals->lookup("nil"); TATOM = globals->lookup("t"); /*tests!*/ Process proc; /*allocate stuff*/ //(cons t ...) proc.stack.push(new(proc) Sym(TATOM));//t //(cons t nil) proc.stack.push(new(proc) Sym(TATOM)); //t proc.stack.push(new(proc) Sym(NILATOM)); //nil //cons { Cons* cp = new(proc) Cons(); cp->a = proc.stack.top(2); cp->d = proc.stack.top(); proc.stack.top(2) = cp; proc.stack.pop(); } //another cons { Cons* cp = new(proc) Cons(); cp->a = proc.stack.top(2); cp->d = proc.stack.top(); proc.stack.top(2) = cp; proc.stack.pop(); } proc.stack.top()->probe(0); }
#include"variables.hpp" #include"processes.hpp" #include<iostream> int main(int argc, const char* argv[]){ variables_init(); /*tests!*/ Process proc; /*allocate stuff*/ //(cons t ...) proc.stack.push(new(proc) Sym(TATOM));//t //(cons t nil) proc.stack.push(new(proc) Sym(TATOM)); //t proc.stack.push(new(proc) Sym(NILATOM)); //nil //cons { Cons* cp = new(proc) Cons(); cp->a = proc.stack.top(2); cp->d = proc.stack.top(); proc.stack.top(2) = cp; proc.stack.pop(); } //another cons { Cons* cp = new(proc) Cons(); cp->a = proc.stack.top(2); cp->d = proc.stack.top(); proc.stack.top(2) = cp; proc.stack.pop(); } proc.stack.top()->probe(0); }
Replace c++ libraries by c standard libraries, make working for c language too
#include<cmath> #include<iostream> using namespace std; bool isPrimeBruteForce(double x) { if (x < 2) return false; double sqroot_x = sqrt(x); for(int i=0; i <= sqroot_x; i++) { /* If there were only factors above the square root of x, they would be bigger than x itself. */ if (x%i==0) return false; } return true; } int main(int argc, char* argv[]) { double number; bool result; cout << "Enter number to test if it's prime: "; cin >> number; result = isPrimeBruteForce(number); if (result) { cout << number << " is a prime number."; } else { cout << number << " is not a prime number."; } return 0; }
#include<math.h> #include<stdio.h> /*#include<iostream> using namespace std;*/ int isPrimeBruteForce(int x) { if (x < 2) return false; double sqroot_x; sqroot_x = sqrt (x); for(int i=0; i <= sqroot_x; i++) { /* If there were only factors above the square root of x, they would be bigger than x itself. */ if (x%i==0) return 0; } return 1; } int main(int argc, char* argv[]) { int result; /* int number; cout << "Enter number to test if it's prime: "; cin >> number; result = isPrimeBruteForce(number); if (result) { cout << number << " is a prime number."; } else { cout << number << " is not a prime number."; }*/ result = isPrimeBruteForce(37); printf("Is 37 a prime number? %i", result); return 0; }
Rewrite test to check intent instead of implementation.
// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -emit-llvm -o - %s | FileCheck %s // PR7490 int main() { // CHECK: {{for.cond:|:4}} // CHECK: %{{.*}} = icmp ult i64 %{{.*}}, 1133 // CHECK: {{for.body:|:6}} // CHECK: store i8 0 // CHECK: br label %{{for.inc|7}} // CHECK: {{for.inc:|:7}} // CHECK: %{{.*}} = add i64 %{{.*}}, 1 // CHECK: store i64 %{{.*}} // CHECK: br label %{{for.cond|4}} // CHECK: {{for.end:|:12}} volatile char *buckets = new char[1133](); }
// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -O3 -emit-llvm -o - %s | FileCheck %s // PR7490 // CHECK: define signext i8 @_Z2f0v // CHECK: ret i8 0 // CHECK: } inline void* operator new[](unsigned long, void* __p) { return __p; } static void f0_a(char *a) { new (a) char[4](); } char f0() { char a[4]; f0_a(a); return a[0] + a[1] + a[2] + a[3]; }
Add context to why test was disabled on Windows
// RUN: rm -rf %t // RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t/modules.cache \ // RUN: -I %S/Inputs/odr_hash-Friend \ // RUN: -emit-obj -o /dev/null \ // RUN: -fmodules \ // RUN: -fimplicit-module-maps \ // RUN: -fmodules-cache-path=%t/modules.cache \ // RUN: -std=c++11 -x c++ %s -verify // UNSUPPORTED: system-windows // expected-no-diagnostics #include "Box.h" #include "M1.h" #include "M3.h" void Run() { Box<> Present; }
// RUN: rm -rf %t // RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t/modules.cache \ // RUN: -I %S/Inputs/odr_hash-Friend \ // RUN: -emit-obj -o /dev/null \ // RUN: -fmodules \ // RUN: -fimplicit-module-maps \ // RUN: -fmodules-cache-path=%t/modules.cache \ // RUN: -std=c++11 -x c++ %s -verify // PR35939: MicrosoftMangle.cpp triggers an assertion failure on this test. // UNSUPPORTED: system-windows // expected-no-diagnostics #include "Box.h" #include "M1.h" #include "M3.h" void Run() { Box<> Present; }
Add test for allocation/freeing heap.
int main(int argc, char **argv) { return 0; }
#include "heap.h" #include <ctime> #include <cstdlib> #include <iostream> #include <glibmm/error.h> int main(int argc, char **argv) { VM::Heap heap; const size_t ARR_SIZE = 128; const size_t TEST_SIZE = 50; size_t ptrs[ARR_SIZE] = { 0 }; srand(0); try { for(size_t i = 0; i < TEST_SIZE; i ++) { size_t index = rand() % ARR_SIZE; if(ptrs[index]) { std::cout << "= Free " << ptrs[index] << std::endl; heap.Detach(ptrs[index]); ptrs[index] = 0; } else { ptrs[index] = heap.Alloc(0x1, i); std::cout << "= Alloc " << ptrs[index] << std::endl; if(! ptrs[index]) { std::cout << "Error Alloc" << std::endl; break; } } } for(size_t index = 0; index < ARR_SIZE; index ++) { if(ptrs[index]) { heap.Detach(ptrs[index]); } } } catch(Glib::Error &e) { std::cout << "Glib::Error: " << e.what() << std::endl; } catch(std::exception &e) { std::cout << "std::exception: " << e.what() << std::endl; } return 0; }
Raise window to foreground if another instance was launched
#include "stdafx.h" #include "SettingsUI.h" #include "SettingsSheet.h" IMPLEMENT_DYNAMIC(SettingsSheet, CPropertySheet) SettingsSheet::SettingsSheet( UINT nIDCaption, CWnd* pParentWnd, UINT iSelectPage) : CPropertySheet(nIDCaption, pParentWnd, iSelectPage) { } SettingsSheet::SettingsSheet(LPCTSTR pszCaption, CWnd* pParentWnd, UINT iSelectPage) : CPropertySheet(pszCaption, pParentWnd, iSelectPage) { } SettingsSheet::~SettingsSheet() { } BOOL SettingsSheet::OnInitDialog() { CPropertySheet::OnInitDialog(); return TRUE; } BEGIN_MESSAGE_MAP(SettingsSheet, CPropertySheet) END_MESSAGE_MAP()
#include "stdafx.h" #include "SettingsUI.h" #include "SettingsSheet.h" IMPLEMENT_DYNAMIC(SettingsSheet, CPropertySheet) SettingsSheet::SettingsSheet( UINT nIDCaption, CWnd* pParentWnd, UINT iSelectPage) : CPropertySheet(nIDCaption, pParentWnd, iSelectPage) { } SettingsSheet::SettingsSheet(LPCTSTR pszCaption, CWnd* pParentWnd, UINT iSelectPage) : CPropertySheet(pszCaption, pParentWnd, iSelectPage) { } SettingsSheet::~SettingsSheet() { } BOOL SettingsSheet::OnInitDialog() { CPropertySheet::OnInitDialog(); return TRUE; } LRESULT SettingsSheet::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) { if (message == WM_3RVX_SETTINGSCTRL) { SetForegroundWindow(); } return CPropertySheet::WindowProc(message, wParam, lParam); } BEGIN_MESSAGE_MAP(SettingsSheet, CPropertySheet) END_MESSAGE_MAP()
Make the server bind to localhost. We don't really want to expose it to the world, and it pops up firewall warnings if you have an app aware firewall enabled (e.g. OSX firewall).
#include "Server.h" #include "WebPage.h" #include "Connection.h" #include <QTcpServer> Server::Server(QObject *parent, bool ignoreSslErrors) : QObject(parent) { m_tcp_server = new QTcpServer(this); m_page = new WebPage(this); m_page->setIgnoreSslErrors(ignoreSslErrors); } bool Server::start() { connect(m_tcp_server, SIGNAL(newConnection()), this, SLOT(handleConnection())); return m_tcp_server->listen(QHostAddress::Any, 0); } quint16 Server::server_port() const { return m_tcp_server->serverPort(); } void Server::handleConnection() { QTcpSocket *socket = m_tcp_server->nextPendingConnection(); new Connection(socket, m_page, this); }
#include "Server.h" #include "WebPage.h" #include "Connection.h" #include <QTcpServer> Server::Server(QObject *parent, bool ignoreSslErrors) : QObject(parent) { m_tcp_server = new QTcpServer(this); m_page = new WebPage(this); m_page->setIgnoreSslErrors(ignoreSslErrors); } bool Server::start() { connect(m_tcp_server, SIGNAL(newConnection()), this, SLOT(handleConnection())); return m_tcp_server->listen(QHostAddress::LocalHost, 0); } quint16 Server::server_port() const { return m_tcp_server->serverPort(); } void Server::handleConnection() { QTcpSocket *socket = m_tcp_server->nextPendingConnection(); new Connection(socket, m_page, this); }
Update view for angle arrow
#include <cmath> #include <ros/ros.h> #include <geometry_msgs/TransformStamped.h> #include <rviz_visual_tools/rviz_visual_tools.h> #include <tf2_eigen/tf2_eigen.h> #include <tf2_ros/transform_listener.h> #include <Eigen/Geometry> int main(int argc, char** argv) { ros::init(argc, argv, "body_angle_visualizer"); ros::NodeHandle n {}; ros::Rate r {5}; tf2_ros::Buffer tfBuffer {}; tf2_ros::TransformListener tfListener {tfBuffer}; rviz_visual_tools::RvizVisualTools rvt {"openni_depth_frame", "rviz_visual_markers"}; while (ros::ok()) { auto head_pos {tf2::transformToEigen(tfBuffer.lookupTransform("openni_depth_frame", "head", ros::Time {0}))}; auto torso_pos {tf2::transformToEigen(tfBuffer.lookupTransform("openni_depth_frame", "torso", ros::Time {0}))}; const auto stand_vec {head_pos.translation() - torso_pos.translation()}; Eigen::Affine3d arrow {}; arrow.translation() = stand_vec; rvt.deleteAllMarkers(); rvt.publishArrow(arrow); rvt.trigger(); r.sleep(); } }
#include <cmath> #include <ros/ros.h> #include <rviz_visual_tools/rviz_visual_tools.h> #include <tf2_eigen/tf2_eigen.h> #include <tf2_ros/transform_listener.h> #include <Eigen/Geometry> int main(int argc, char** argv) { ros::init(argc, argv, "body_angle_visualizer"); ros::NodeHandle n {}; ros::Rate r {5}; tf2_ros::Buffer tfBuffer {}; tf2_ros::TransformListener tfListener {tfBuffer}; rviz_visual_tools::RvizVisualTools rvt {"openni_depth_frame", "rviz_visual_markers"}; while (ros::ok()) { try { const auto head_pos {tf2::transformToEigen(tfBuffer.lookupTransform("openni_depth_frame", "head_1", ros::Time {0}))}; const auto torso_pos {tf2::transformToEigen(tfBuffer.lookupTransform("openni_depth_frame", "torso_1", ros::Time {0}))}; const auto stand_vec {head_pos.translation() - torso_pos.translation()}; const auto stand_quaternion {Eigen::Quaterniond::FromTwoVectors(Eigen::Vector3d::UnitX(), stand_vec)}; rvt.deleteAllMarkers(); Eigen::Affine3d arrow {stand_quaternion}; rvt.publishArrow(arrow); rvt.trigger(); } catch (tf2::TransformException &e) { ROS_WARN("%s", e.what()); } r.sleep(); } }
Change image data components detection
#include "ImageData.h" #include <OpenGL/gl3.h> #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wold-style-cast" #pragma clang diagnostic ignored "-Wunused-function" #pragma clang diagnostic ignored "-Wdisabled-macro-expansion" #define STB_IMAGE_IMPLEMENTATION #define STBI_ONLY_PNG #include "stb/stb_image.h" #pragma clang diagnostic pop bool ImageData::LoadPng(const char* filePath) { int components = 0; data = stbi_load(filePath, &size.x, &size.y, &components, 0); if (data != nullptr) { pixelFormat = (components == 4 ? GL_RGBA : GL_RGB); return true; } else { assert(false); return false; } } void ImageData::DeallocateData() { if (data != nullptr) stbi_image_free(data); }
#include "ImageData.h" #include <OpenGL/gl3.h> #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wold-style-cast" #pragma clang diagnostic ignored "-Wunused-function" #pragma clang diagnostic ignored "-Wdisabled-macro-expansion" #define STB_IMAGE_IMPLEMENTATION #define STBI_ONLY_PNG #include "stb/stb_image.h" #pragma clang diagnostic pop bool ImageData::LoadPng(const char* filePath) { int components = 0; data = stbi_load(filePath, &size.x, &size.y, &components, 0); if (data != nullptr) { assert(components >= 0 && components < 4); static const GLenum formats[] = { GL_RED, GL_RG, GL_RGB, GL_RGBA }; pixelFormat = formats[components - 1]; return true; } else { assert(false); return false; } } void ImageData::DeallocateData() { if (data != nullptr) stbi_image_free(data); }
Fix missing LoadLibrary symbol on windows.
#include "runtime_internal.h" #ifdef BITS_64 #define WIN32API #else #define WIN32API __stdcall #endif extern "C" { WIN32API void *LoadLibrary(const char *); WIN32API void *GetProcAddress(void *, const char *); WEAK void *halide_get_symbol(const char *name) { return GetProcAddress(NULL, name); } WEAK void *halide_load_library(const char *name) { return LoadLibrary(name); } WEAK void *halide_get_library_symbol(void *lib, const char *name) { return GetProcAddress(lib, name); } }
#include "runtime_internal.h" #ifdef BITS_64 #define WIN32API #else #define WIN32API __stdcall #endif extern "C" { WIN32API void *LoadLibraryA(const char *); WIN32API void *GetProcAddress(void *, const char *); WEAK void *halide_get_symbol(const char *name) { return GetProcAddress(NULL, name); } WEAK void *halide_load_library(const char *name) { return LoadLibraryA(name); } WEAK void *halide_get_library_symbol(void *lib, const char *name) { return GetProcAddress(lib, name); } }
Use a correct format string in the unittest JNI wrapper
#include <string.h> #include <stdlib.h> #include <stdio.h> #include <jni.h> #include <android/log.h> #define LOG_TAG "codec_unittest" #define LOGI(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) int CodecUtMain(int argc, char** argv); extern "C" JNIEXPORT void JNICALL Java_com_cisco_codec_unittest_MainActivity_DoUnittest (JNIEnv* env, jobject thiz,jstring jspath) { /**************** Add the native codes/API *****************/ char* argv[2]; int argc = 2; argv[0] = (char*) ("codec_unittest.exe"); argv[1] = (char*) ((*env).GetStringUTFChars (jspath,NULL)); LOGI ("PATH:",+argv[1]); LOGI ("Start to run JNI module!+++"); CodecUtMain(argc,argv); LOGI ("End to run JNI module!+++"); }
#include <string.h> #include <stdlib.h> #include <stdio.h> #include <jni.h> #include <android/log.h> #define LOG_TAG "codec_unittest" #define LOGI(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) int CodecUtMain(int argc, char** argv); extern "C" JNIEXPORT void JNICALL Java_com_cisco_codec_unittest_MainActivity_DoUnittest (JNIEnv* env, jobject thiz,jstring jspath) { /**************** Add the native codes/API *****************/ char* argv[2]; int argc = 2; argv[0] = (char*) ("codec_unittest.exe"); argv[1] = (char*) ((*env).GetStringUTFChars (jspath,NULL)); LOGI ("PATH: %s", argv[1]); LOGI ("Start to run JNI module!+++"); CodecUtMain(argc,argv); LOGI ("End to run JNI module!+++"); }
Reset hero graphic on map change (if it was changed by a move event). Fix RPG::Event default value for y. Minor cleanups.
///////////////////////////////////////////////////////////////////////////// // This file is part of EasyRPG. // // EasyRPG is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // EasyRPG is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with EasyRPG Player. If not, see <http://www.gnu.org/licenses/>. ///////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include "rpg_event.h" //////////////////////////////////////////////////////////// /// Constructor //////////////////////////////////////////////////////////// RPG::Event::Event() { ID = 0; name = ""; x = 0; y = 5; }
///////////////////////////////////////////////////////////////////////////// // This file is part of EasyRPG. // // EasyRPG is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // EasyRPG is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with EasyRPG Player. If not, see <http://www.gnu.org/licenses/>. ///////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include "rpg_event.h" //////////////////////////////////////////////////////////// /// Constructor //////////////////////////////////////////////////////////// RPG::Event::Event() { ID = 0; name = ""; x = 0; y = 0; }
Fix miner_test unit test bug
#include <boost/test/unit_test.hpp> #include "../uint256.h" extern void SHA256Transform(void* pstate, void* pinput, const void* pinit); BOOST_AUTO_TEST_SUITE(miner_tests) BOOST_AUTO_TEST_CASE(sha256transform_equality) { unsigned int pSHA256InitState[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; unsigned char pstate[32]; unsigned char pinput[32]; int i; for (i = 0; i < 32; i++) { pinput[i] = i; pstate[i] = 0; } uint256 hash; SHA256Transform(&hash, pinput, pSHA256InitState); BOOST_TEST_MESSAGE(hash.GetHex()); uint256 hash_reference("0x2df5e1c65ef9f8cde240d23cae2ec036d31a15ec64bc68f64be242b1da6631f3"); BOOST_CHECK(hash == hash_reference); } BOOST_AUTO_TEST_SUITE_END()
#include <boost/test/unit_test.hpp> #include "../uint256.h" extern void SHA256Transform(void* pstate, void* pinput, const void* pinit); BOOST_AUTO_TEST_SUITE(miner_tests) BOOST_AUTO_TEST_CASE(sha256transform_equality) { unsigned int pSHA256InitState[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; unsigned char pstate[32]; unsigned char pinput[64]; int i; for (i = 0; i < 32; i++) { pinput[i] = i; pinput[i+32] = 0; } uint256 hash; SHA256Transform(&hash, pinput, pSHA256InitState); BOOST_TEST_MESSAGE(hash.GetHex()); uint256 hash_reference("0x2df5e1c65ef9f8cde240d23cae2ec036d31a15ec64bc68f64be242b1da6631f3"); BOOST_CHECK(hash == hash_reference); } BOOST_AUTO_TEST_SUITE_END()
Use Support/Thread.h instead of <thread> to fix the Windows build
//===- unittests/TimerTest.cpp - Timer tests ------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/Timer.h" #include "gtest/gtest.h" #include <chrono> #include <thread> using namespace llvm; namespace { TEST(Timer, Additivity) { Timer T1("T1"); EXPECT_TRUE(T1.isInitialized()); T1.startTimer(); T1.stopTimer(); auto TR1 = T1.getTotalTime(); T1.startTimer(); std::this_thread::sleep_for(std::chrono::milliseconds(1)); T1.stopTimer(); auto TR2 = T1.getTotalTime(); EXPECT_TRUE(TR1 < TR2); } TEST(Timer, CheckIfTriggered) { Timer T1("T1"); EXPECT_FALSE(T1.hasTriggered()); T1.startTimer(); EXPECT_TRUE(T1.hasTriggered()); T1.stopTimer(); EXPECT_TRUE(T1.hasTriggered()); T1.clear(); EXPECT_FALSE(T1.hasTriggered()); } } // end anon namespace
//===- unittests/TimerTest.cpp - Timer tests ------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/Timer.h" #include "llvm/Support/Thread.h" #include "gtest/gtest.h" #include <chrono> using namespace llvm; namespace { TEST(Timer, Additivity) { Timer T1("T1"); EXPECT_TRUE(T1.isInitialized()); T1.startTimer(); T1.stopTimer(); auto TR1 = T1.getTotalTime(); T1.startTimer(); std::this_thread::sleep_for(std::chrono::milliseconds(1)); T1.stopTimer(); auto TR2 = T1.getTotalTime(); EXPECT_TRUE(TR1 < TR2); } TEST(Timer, CheckIfTriggered) { Timer T1("T1"); EXPECT_FALSE(T1.hasTriggered()); T1.startTimer(); EXPECT_TRUE(T1.hasTriggered()); T1.stopTimer(); EXPECT_TRUE(T1.hasTriggered()); T1.clear(); EXPECT_FALSE(T1.hasTriggered()); } } // end anon namespace
Exclude skipped lines from coverage.
#include <iostream> #include <stdexcept> #include <type_traits> #include "fsm.h" class state_machine: public fsmlite::fsm<state_machine> { friend class fsm; // base class needs access to transition_table public: enum states { Init, Exit }; private: void process(const int& event) { std::cout << "Processing event: " << event << "\n"; #ifdef NDEBUG if (event != 0) { throw std::logic_error("recursive invocation detected"); } #endif process_event(event + 1); } private: typedef state_machine m; using transition_table = table< // Start Event Target Action // -----------+-----+------+------+-----------+- mem_fn_row< Init, int, Exit, &m::process > // -----------+-----+------+------+-----------+- >; }; int main() { state_machine m; try { m.process_event(0); } catch (std::logic_error& e) { std::cerr << e.what() << "\n"; return 0; } return 1; }
#include <iostream> #include <stdexcept> #include <type_traits> #include "fsm.h" class state_machine: public fsmlite::fsm<state_machine> { friend class fsm; // base class needs access to transition_table public: enum states { Init, Exit }; private: void process(const int& event) { std::cout << "Processing event: " << event << "\n"; #ifdef NDEBUG if (event != 0) { throw std::logic_error("recursive invocation detected"); } #endif process_event(event + 1); } private: typedef state_machine m; using transition_table = table< // Start Event Target Action // -----------+-----+------+------+-----------+- mem_fn_row< Init, int, Exit, &m::process > // -----------+-----+------+------+-----------+- >; }; int main() { state_machine m; try { m.process_event(0); } catch (std::logic_error& e) { std::cerr << e.what() << "\n"; return 0; } return 1; /* LCOV_EXCL_LINE */ }
Use `size_t` when needed instead of just `int`
#include "catch.hpp" #include "visual.hh" #include "configuration.hh" using namespace vick; TEST_CASE("to_visual") { std::string first("assert"), second("\tblah"); for (int i = 0; i < first.size(); i++) REQUIRE(i == to_visual(first, i)); for (int i = 0; i < second.size(); i++) REQUIRE(TAB_SIZE - 1 + i == to_visual(second, i)); } TEST_CASE("from_visual") { std::string first("\thi"), second("\t\thi"); for (int i = 1; i < TAB_SIZE - 1; i++) { REQUIRE(0 == from_visual(first, TAB_SIZE - i)); } REQUIRE(0 == from_visual(first, TAB_SIZE - 1)); REQUIRE(1 == from_visual(first, TAB_SIZE)); REQUIRE(2 == from_visual(first, TAB_SIZE + 1)); }
#include "catch.hpp" #include "visual.hh" #include "configuration.hh" using namespace vick; TEST_CASE("to_visual") { std::string first("assert"), second("\tblah"); for (size_t i = 0; i < first.size(); i++) REQUIRE(i == to_visual(first, i)); for (size_t i = 0; i < second.size(); i++) REQUIRE(TAB_SIZE - 1 + i == to_visual(second, i)); } TEST_CASE("from_visual") { std::string first("\thi"), second("\t\thi"); for (int i = 1; i < TAB_SIZE - 1; i++) { REQUIRE(0 == from_visual(first, TAB_SIZE - i)); } REQUIRE(0 == from_visual(first, TAB_SIZE - 1)); REQUIRE(1 == from_visual(first, TAB_SIZE)); REQUIRE(2 == from_visual(first, TAB_SIZE + 1)); }
Add small explanation to the filter dialog.
#include "dlgfilters.h" #include "filterwidget.h" #include <QHBoxLayout> #include <QVBoxLayout> #include <QPushButton> DlgFilters::DlgFilters(const QList<QPair<bool,QString> >& filters, QWidget *parent) : QDialog(parent, Qt::Dialog) { setWindowTitle(tr("strigiclient - Edit filters")); filterwidget = new FilterWidget(); filterwidget->setFilters(filters); QPushButton* ok = new QPushButton(tr("&Ok")); ok->setDefault(true); QPushButton* cancel = new QPushButton(tr("&Cancel")); QVBoxLayout* layout = new QVBoxLayout(); setLayout(layout); layout->addWidget(filterwidget); QHBoxLayout* hl = new QHBoxLayout(); layout->addLayout(hl); hl->addStretch(); hl->addWidget(ok); hl->addWidget(cancel); connect(ok, SIGNAL(clicked()), this, SLOT(accept())); connect(cancel, SIGNAL(clicked()), this, SLOT(reject())); } const QList<QPair<bool,QString> >& DlgFilters::getFilters() const { return filterwidget->getFilters(); }
#include "dlgfilters.h" #include "filterwidget.h" #include <QHBoxLayout> #include <QVBoxLayout> #include <QPushButton> #include <QLabel> DlgFilters::DlgFilters(const QList<QPair<bool,QString> >& filters, QWidget *parent) : QDialog(parent, Qt::Dialog) { setWindowTitle(tr("strigiclient - Edit filters")); QLabel* explanation = new QLabel(tr("Define filters that determine which files will be included and which will be excluded from the index, e.g. '*.html' or '.svn/' (do not index directories called '.svn').")); explanation->setWordWrap(true); filterwidget = new FilterWidget(); filterwidget->setFilters(filters); QPushButton* ok = new QPushButton(tr("&Ok")); ok->setDefault(true); QPushButton* cancel = new QPushButton(tr("&Cancel")); QVBoxLayout* layout = new QVBoxLayout(); setLayout(layout); layout->addWidget(explanation); layout->addWidget(filterwidget); QHBoxLayout* hl = new QHBoxLayout(); layout->addLayout(hl); hl->addStretch(); hl->addWidget(ok); hl->addWidget(cancel); connect(ok, SIGNAL(clicked()), this, SLOT(accept())); connect(cancel, SIGNAL(clicked()), this, SLOT(reject())); } const QList<QPair<bool,QString> >& DlgFilters::getFilters() const { return filterwidget->getFilters(); }
Edit subsidy_limit_test to account for BIP42
#include "core.h" #include "main.h" #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(main_tests) BOOST_AUTO_TEST_CASE(subsidy_limit_test) { uint64_t nSum = 0; for (int nHeight = 0; nHeight < 7000000; nHeight += 1000) { uint64_t nSubsidy = GetBlockValue(nHeight, 0); BOOST_CHECK(nSubsidy <= 50 * COIN); nSum += nSubsidy * 1000; BOOST_CHECK(MoneyRange(nSum)); } BOOST_CHECK(nSum == 2099999997690000ULL); } BOOST_AUTO_TEST_SUITE_END()
#include "core.h" #include "main.h" #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(main_tests) BOOST_AUTO_TEST_CASE(subsidy_limit_test) { uint64_t nSum = 0; for (int nHeight = 0; nHeight < 14000000; nHeight += 1000) { uint64_t nSubsidy = GetBlockValue(nHeight, 0); BOOST_CHECK(nSubsidy <= 50 * COIN); nSum += nSubsidy * 1000; BOOST_CHECK(MoneyRange(nSum)); } BOOST_CHECK(nSum == 2099999997690000ULL); } BOOST_AUTO_TEST_SUITE_END()
Fix compilation error with C++11 compliant compiler (user-defined literals)
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /*********************************************************************************** ** ** DateTimeStamp.cpp ** ** Copyright (C) September 2017 Hotride ** ************************************************************************************ */ //---------------------------------------------------------------------------------- #include "stdafx.h" //---------------------------------------------------------------------------------- string GetBuildDateTimeStamp() { return string(__DATE__" "__TIME__); } //----------------------------------------------------------------------------------
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /*********************************************************************************** ** ** DateTimeStamp.cpp ** ** Copyright (C) September 2017 Hotride ** ************************************************************************************ */ //---------------------------------------------------------------------------------- #include "stdafx.h" //---------------------------------------------------------------------------------- string GetBuildDateTimeStamp() { return string(__DATE__ " " __TIME__); } //----------------------------------------------------------------------------------
Fix bug in Tech Target Check hook module.
//Injector source file for the Tech Target Check hook module. #include "tech_target_check.h" #include <hook_tools.h> namespace { const u32 Func_GetTechUseErrorMessage = 0x00491E80; void __declspec(naked) getTechUseErrorMessageWrapper() { static CUnit *target; static u8 castingPlayer; static u16 techId; static u16 errorMessage; __asm { PUSHAD MOV target, EAX MOV castingPlayer, BL MOV EAX, [EBP + 4] MOV techId, AX } errorMessage = hooks::getTechUseErrorMessageHook(target, castingPlayer, techId); __asm { POPAD MOV AX, errorMessage RETN 4 } } } //Unnamed namespace namespace hooks { void injectTechTargetCheckHooks() { jmpPatch(getTechUseErrorMessageWrapper, Func_GetTechUseErrorMessage); } u16 getTechUseErrorMessage(const CUnit *target, s8 castingPlayer, u16 techId) { u32 techId_ = techId; static u16 errorMessage; __asm { PUSHAD PUSH techId_ MOV BL, castingPlayer MOV EAX, target CALL Func_GetTechUseErrorMessage MOV errorMessage, AX POPAD } return errorMessage; } } //hooks
//Injector source file for the Tech Target Check hook module. #include "tech_target_check.h" #include <hook_tools.h> namespace { const u32 Func_GetTechUseErrorMessage = 0x00491E80; void __declspec(naked) getTechUseErrorMessageWrapper() { static CUnit *target; static u8 castingPlayer; static u16 techId; static u16 errorMessage; __asm { PUSHAD MOV EBP, ESP MOV target, EAX MOV castingPlayer, BL MOV EAX, [ESP + 36] ;// (PUSHAD saves 32) + (CALL saves 4) == 36 MOV techId, AX } errorMessage = hooks::getTechUseErrorMessageHook(target, castingPlayer, techId); __asm { POPAD MOV AX, errorMessage RETN 4 } } } //Unnamed namespace namespace hooks { void injectTechTargetCheckHooks() { jmpPatch(getTechUseErrorMessageWrapper, Func_GetTechUseErrorMessage); } u16 getTechUseErrorMessage(const CUnit *target, s8 castingPlayer, u16 techId) { u32 techId_ = techId; static u16 errorMessage; __asm { PUSHAD PUSH techId_ MOV BL, castingPlayer MOV EAX, target CALL Func_GetTechUseErrorMessage MOV errorMessage, AX POPAD } return errorMessage; } } //hooks
Add a dtor to ensure that they are called the right number of times.
struct Foo { Foo(int); }; void foo() { struct { Foo name; } Int[] = { 1 }; }
struct Foo { Foo(int); ~Foo(); }; void foo() { struct { Foo name; } Int[] = { 1 }; }
Disable random shape optimizations by default
#include "settings.h" int N_POLY_POINTS = 4; int N_COLOR_VAR = 5; int N_POS_VAR = 5; int SHAPE_OPT_FREQ = 25; int GUI_REFRESH_RATE = 1; int AUTOFOCUS_RES = 2; int FOCUS_LEFT=0, FOCUS_RIGHT=100, FOCUS_TOP=0, FOCUS_BOTTOM=100;
#include "settings.h" int N_POLY_POINTS = 4; int N_COLOR_VAR = 5; int N_POS_VAR = 5; int SHAPE_OPT_FREQ = 0; int GUI_REFRESH_RATE = 1; int AUTOFOCUS_RES = 2; int FOCUS_LEFT=0, FOCUS_RIGHT=100, FOCUS_TOP=0, FOCUS_BOTTOM=100;
Use entity position rather than bbox center
#include "gamelib/components/update/CameraTracker.hpp" #include "gamelib/core/rendering/CameraSystem.hpp" #include "gamelib/core/ecs/Entity.hpp" namespace gamelib { CameraTracker::CameraTracker() : UpdateComponent(1, UpdateHookType::PostPostFrame), camera(0), shakerad(5), _shake(false) { _props.registerProperty("shakeradius", shakerad); _props.registerProperty("camera", camera); } void CameraTracker::update(float elapsed) { auto ent = getEntity(); if (!ent) return; Camera* cam = getCamera(); if (!cam) return; if (_shake) { _secondsleft -= elapsed; if (_secondsleft <= 0) { _shake = false; return; } math::Vec2f off(-shakerad, -shakerad); off += math::Vec2f(std::fmod(random(), shakerad * 2), std::fmod(random(), shakerad * 2)); cam->center(ent->getTransform().getBBox().getCenter() + off); } else { cam->center(ent->getTransform().getBBox().getCenter()); } } void CameraTracker::shake(float seconds) { _shake = true; _secondsleft = seconds; } Camera* CameraTracker::getCamera() const { return getSubsystem<CameraSystem>()->get(camera); } }
#include "gamelib/components/update/CameraTracker.hpp" #include "gamelib/core/rendering/CameraSystem.hpp" #include "gamelib/core/ecs/Entity.hpp" namespace gamelib { CameraTracker::CameraTracker() : UpdateComponent(1, UpdateHookType::PostPostFrame), camera(0), shakerad(5), _shake(false) { _props.registerProperty("shakeradius", shakerad); _props.registerProperty("camera", camera); } void CameraTracker::update(float elapsed) { auto ent = getEntity(); if (!ent) return; Camera* cam = getCamera(); if (!cam) return; math::Vec2f offset; if (_shake) { _secondsleft -= elapsed; if (_secondsleft <= 0) { _shake = false; return; } offset.fill(-shakerad); offset += math::Vec2f(std::fmod(random(), shakerad * 2), std::fmod(random(), shakerad * 2)); } cam->center(ent->getTransform().getPosition() + offset); } void CameraTracker::shake(float seconds) { _shake = true; _secondsleft = seconds; } Camera* CameraTracker::getCamera() const { return getSubsystem<CameraSystem>()->get(camera); } }
Add comment regarding use of std::cout.
#include <franka/robot.h> #include <iostream> int main(int argc, char** argv) { if (argc != 2) { std::cerr << "Usage: ./echo_robot_state <robot-hostname>" << std::endl; return -1; } try { franka::Robot robot(argv[1]); size_t count = 0; robot.read([&count](const franka::RobotState& robot_state) { std::cout << robot_state << std::endl; return count++ < 100; }); std::cout << "Done." << std::endl; } catch (franka::Exception const& e) { std::cout << e.what() << std::endl; return -1; } return 0; }
#include <franka/robot.h> #include <iostream> int main(int argc, char** argv) { if (argc != 2) { std::cerr << "Usage: ./echo_robot_state <robot-hostname>" << std::endl; return -1; } try { franka::Robot robot(argv[1]); size_t count = 0; robot.read([&count](const franka::RobotState& robot_state) { // Printing to std::cout adds a delay. This is acceptable for a read loop such as this, // but should not be done in a control loop. std::cout << robot_state << std::endl; return count++ < 100; }); std::cout << "Done." << std::endl; } catch (franka::Exception const& e) { std::cout << e.what() << std::endl; return -1; } return 0; }
Create alias for integer and floating point type
// Standard headers #include <cmath> #include <iostream> // Libraries #include "Math.hpp" const double PI = 3.141592653589793238462643; unsigned long int factorial (unsigned long int n) { return (n == 1 || n == 0) ? 1 : factorial(n - 1) * n; } double fixRadians_impl(double radians) { if (radians > 2*PI) return fixRadians_impl(radians - 2*PI); return radians; } double fixRadians(double radians) { return fixRadians_impl(std::abs(radians)); } double calculateCosine(double radians) { double cos = 0; radians = fixRadians(radians); for (int n = 0; n < 10; n++) { int signal = n % 2 == 0 ? 1 : -1; cos += signal * (std::pow(radians, 2*n) / factorial(2*n)); } return cos; }
// Standard headers #include <cmath> #include <iostream> // Libraries #include "Math.hpp" const double PI = 3.141592653589793238462643; // Alias using mpz = unsigned long int; using mpf = double; mpz factorial (mpz n) { return (n == 1 || n == 0) ? 1 : factorial(n - 1) * n; } mpf fixRadians_impl(mpf radians) { if (radians > 2*PI) return fixRadians_impl(radians - 2*PI); return radians; } mpf fixRadians(mpf radians) { return fixRadians_impl(std::abs(radians)); } mpf calculateCosine(mpf radians) { mpf cos = 0; radians = fixRadians(radians); for (int n = 0; n < 10; n++) { int signal = n % 2 == 0 ? 1 : -1; cos += signal * (std::pow(radians, 2*n) / factorial(2*n)); } return cos; }
Update the number of iterations
#include "GlobalContext.hpp" #include "ast/SourceFile.hpp" #include "parser/SpiritParser.hpp" int main(int argc, char* args[]) { const std::vector<std::string> argv(args+1, args+argc); using namespace eddic; using namespace eddic::parser; for (int i=0; i<5; i++) for (auto& fname : argv) { SpiritParser parser; eddic::ast::SourceFile program; parser.parse(fname, program, std::make_shared<GlobalContext>(Platform::INTEL_X86_64)); } }
#include "GlobalContext.hpp" #include "ast/SourceFile.hpp" #include "parser/SpiritParser.hpp" int main(int argc, char* args[]) { const std::vector<std::string> argv(args+1, args+argc); using namespace eddic; using namespace eddic::parser; for (int i=0; i<100; i++) for (auto& fname : argv) { SpiritParser parser; eddic::ast::SourceFile program; parser.parse(fname, program, std::make_shared<GlobalContext>(Platform::INTEL_X86_64)); } }
Reorganize main() for clarity and modern C++-ness.
/* * Justin's Awesome Game Engine * or * * Just Another Game Engine * * Copyright 2016 Justin White * * See included LICENSE file for distribution and reuse. */ #include <cstdio> #include <Engine.hpp> int main(const int argc, const char** argv) { std::cout << "Start" << std::endl;; Engine theGame(argc, argv); if (theGame.ready()) { if (theGame.run()) { } else { std::cerr << "Error running Engine, quitting." << std::endl;; return EXIT_FAILURE; } } else { std::cerr << "Could not initialize Engine, quitting." << std::endl;; return EXIT_FAILURE; } std::cout << "Done" << std::endl;; return EXIT_SUCCESS; }
/* * Justin's Awesome Game Engine * or * * Just Another Game Engine * * Copyright 2016 Justin White * * See included LICENSE file for distribution and reuse. */ #include <Engine.hpp> static std::unique_ptr<Engine> theGame; int success(const std::string& msg); int fail(const std::string& msg); int main(const int argc, const char** argv) { std::cout << "Start" << std::endl; theGame = std::make_unique<Engine>(argc, argv); if (not theGame->ready()) { return fail("Could not initialize Engine, quitting."); } if (not theGame->run()) { return fail("Error running Engine, quitting."); } return success("Done"); } int success(const std::string& msg) { theGame.release(); std::cout << msg << std::endl; return EXIT_SUCCESS; } int fail(const std::string& msg) { theGame.release(); std::cerr << msg << std::endl; return EXIT_FAILURE; }
Add simple event handling to quit
#include <iostream> #include "Board.h" #include "Renderer.h" int main(int argc, char** argv) { Board board(10, 10, 2); Renderer renderer; if(renderer.init() != 0) { renderer.quit(); return 1; } for(int i = 0; i < 5; ++i) { renderer.render(); SDL_Delay(1000); } renderer.quit(); return 0; }
#include <iostream> #include "Board.h" #include "Renderer.h" int main(int argc, char** argv) { Board board(10, 10, 2); Renderer renderer; if(renderer.init() != 0) { renderer.quit(); return 1; } bool running = true; SDL_Event event; while(running) { while(SDL_PollEvent(&event)) { // Close window if(event.type == SDL_QUIT) { running = false; } // Presses any key if(event.type == SDL_KEYDOWN) { running = false; } // Click the mouse if(event.type == SDL_MOUSEBUTTONDOWN) { running = false; } } renderer.render(); } renderer.quit(); return 0; }
Read credentials from the keyboard if the file is not found
#include "../src/vault.h" #include <fstream> #include <iostream> namespace { // Copy example/credentials.txt.example to example/credentials.txt and // put your username and then password on the next line. std::pair<std::string, std::string> read_credentials() { std::ifstream f("example/credentials.txt"); if (!f.is_open()) throw std::runtime_error("Failed to open credentials file"); std::string username; std::string password; f >> username >> password; return std::make_pair(username, password); } } int main(int argc, char const *argv[]) { using namespace lastpass; try { auto credentials = read_credentials(); auto vault = Vault::create(credentials.first, credentials.second); for (auto const &i: vault.accounts()) { std::cout << " id: " << i.id() << '\n' << " name: " << i.name() << '\n' << "username: " << i.username() << '\n' << "password: " << i.password() << '\n' << " group: " << i.group() << '\n' << " url: " << i.url() << '\n' << '\n'; } } catch (std::exception const &e) { std::cerr << e.what() << std::endl; } return 0; }
#include "../src/vault.h" #include <fstream> #include <iostream> namespace { // Copy example/credentials.txt.example to example/credentials.txt and // put your username and then password on the next line. std::pair<std::string, std::string> read_credentials() { std::string username; std::string password; std::ifstream f("example/credentials.txt"); if (f.is_open()) { f >> username >> password; } else { std::cout << "Enter username: " << std::flush; std::cin >> username; std::cout << "Enter password: " << std::flush; std::cin >> password; } return std::make_pair(username, password); } } int main(int argc, char const *argv[]) { using namespace lastpass; try { auto credentials = read_credentials(); auto vault = Vault::create(credentials.first, credentials.second); for (auto const &i: vault.accounts()) { std::cout << " id: " << i.id() << '\n' << " name: " << i.name() << '\n' << "username: " << i.username() << '\n' << "password: " << i.password() << '\n' << " group: " << i.group() << '\n' << " url: " << i.url() << '\n' << '\n'; } } catch (std::exception const &e) { std::cerr << e.what() << std::endl; } return 0; }
Fix failing attribute test on Windows
// RUN: %clang_cc1 -emit-llvm %s -o - | FileCheck %s // PR39118 // Make sure that attributes are properly applied to explicit template // instantiations. #define HIDDEN __attribute__((__visibility__("hidden"))) #define VISIBLE __attribute__((__visibility__("default"))) namespace ns HIDDEN { struct A { }; template <typename T> struct B { static A a; }; template <typename T> A B<T>::a; // CHECK: @_ZN2ns1BIiE1aE = weak_odr global // CHECK-NOT: hidden template VISIBLE A B<int>::a; } struct C { }; template <typename T> struct D { static C c; }; template <typename T> C D<T>::c; // CHECK-DAG: @_ZN1DIiE1cB3TAGE template __attribute__((abi_tag("TAG"))) C D<int>::c;
// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -emit-llvm %s -o - | FileCheck %s // PR39118 // Make sure that attributes are properly applied to explicit template // instantiations. #define HIDDEN __attribute__((__visibility__("hidden"))) #define VISIBLE __attribute__((__visibility__("default"))) namespace ns HIDDEN { struct A { }; template <typename T> struct B { static A a; }; template <typename T> A B<T>::a; // CHECK: @_ZN2ns1BIiE1aE = weak_odr global // CHECK-NOT: hidden template VISIBLE A B<int>::a; } struct C { }; template <typename T> struct D { static C c; }; template <typename T> C D<T>::c; // CHECK-DAG: @_ZN1DIiE1cB3TAGE template __attribute__((abi_tag("TAG"))) C D<int>::c;
Fix bug in Cpp parser base class initialization. Regression tests all pass now.
#include "PythonParserBase.h" using namespace antlr4; PythonParserBase::PythonParserBase(antlr4::TokenStream *input) : Parser(input) { } bool PythonParserBase::CheckVersion(int version) { return Version == PythonVersion::Autodetect || version == (int) Version; } void PythonParserBase::SetVersion(int requiredVersion) { Version = (PythonVersion) requiredVersion; }
#include "PythonParserBase.h" using namespace antlr4; PythonParserBase::PythonParserBase(antlr4::TokenStream *input) : Parser(input) { Version = PythonVersion::Autodetect; } bool PythonParserBase::CheckVersion(int version) { return Version == PythonVersion::Autodetect || version == (int) Version; } void PythonParserBase::SetVersion(int requiredVersion) { Version = (PythonVersion) requiredVersion; }
Fix yet another Apple buildit bug
//===------------------------- typeinfo.cpp -------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "typeinfo" #if (!defined(_LIBCPP_ABI_MICROSOFT) && !defined(LIBCXX_BUILDING_LIBCXXABI) && \ !defined(LIBCXXRT) && !defined(__GLIBCXX__)) || \ defined(_LIBCPP_BUILDING_HAS_NO_ABI_LIBRARY) // FIXME: remove this configuration. std::type_info::~type_info() { } #endif
//===------------------------- typeinfo.cpp -------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "typeinfo" // FIXME: Remove __APPLE__ default here once buildit is gone. #if (!defined(_LIBCPP_ABI_MICROSOFT) && !defined(LIBCXX_BUILDING_LIBCXXABI) && \ !defined(LIBCXXRT) && !defined(__GLIBCXX__) && \ !defined(__APPLE__)) || \ defined(_LIBCPP_BUILDING_HAS_NO_ABI_LIBRARY) // FIXME: remove this configuration. std::type_info::~type_info() { } #endif
Fix one more clang test which didn't have \5C in it
// RUN: %clang_cc1 -fprofile-instrument=clang -fcoverage-mapping -emit-llvm -main-file-name abspath.cpp %S/Inputs/../abspath.cpp -o - | FileCheck -check-prefix=RMDOTS %s // RMDOTS: @__llvm_coverage_mapping = {{.*}}"\01 // RMDOTS-NOT: Inputs // RMDOTS: " // RUN: mkdir -p %t/test && cd %t/test // RUN: echo "void f1() {}" > f1.c // RUN: %clang_cc1 -fprofile-instrument=clang -fcoverage-mapping -emit-llvm -main-file-name abspath.cpp ../test/f1.c -o - | FileCheck -check-prefix=RELPATH %s // RELPATH: @__llvm_coverage_mapping = {{.*}}"\01 // RELPATH: {{[/\\]}}{{.*}}{{[/\\][^/\\]*}}test{{[/\\][^/\\]*}}f1.c // RELPATH: " void f1() {}
// RUN: %clang_cc1 -fprofile-instrument=clang -fcoverage-mapping -emit-llvm -main-file-name abspath.cpp %S/Inputs/../abspath.cpp -o - | FileCheck -check-prefix=RMDOTS %s // RMDOTS: @__llvm_coverage_mapping = {{.*}}"\01 // RMDOTS-NOT: Inputs // RMDOTS: " // RUN: mkdir -p %t/test && cd %t/test // RUN: echo "void f1() {}" > f1.c // RUN: %clang_cc1 -fprofile-instrument=clang -fcoverage-mapping -emit-llvm -main-file-name abspath.cpp ../test/f1.c -o - | FileCheck -check-prefix=RELPATH %s // RELPATH: @__llvm_coverage_mapping = {{.*}}"\01 // RELPATH: {{[/\\].*(/|\\\\)test(/|\\\\)f1}}.c // RELPATH: " void f1() {}
Use auto when grabbing the agent's index, otherwise we don't get vectorization
#include <algorithm> #include <cassert> #include <iostream> #include <agency/execution_policy.hpp> int main() { using namespace agency; size_t n = 1 << 16; std::vector<float> x(n, 1), y(n, 2), z(n); float a = 13.; bulk_invoke(vec(n), [&](vector_agent &self) { int i = self.index(); z[i] = a * x[i] + y[i]; }); float expected = a * 1. + 2.; assert(std::all_of(z.begin(), z.end(), [=](float x){ return expected == x; })); std::cout << "OK" << std::endl; return 0; }
#include <algorithm> #include <cassert> #include <iostream> #include <agency/execution_policy.hpp> int main() { using namespace agency; size_t n = 1 << 16; std::vector<float> x(n, 1), y(n, 2), z(n); float a = 13.; bulk_invoke(vec(n), [&](vector_agent &self) { auto i = self.index(); z[i] = a * x[i] + y[i]; }); float expected = a * 1. + 2.; assert(std::all_of(z.begin(), z.end(), [=](float x){ return expected == x; })); std::cout << "OK" << std::endl; return 0; }
Test what happen if task ends
#include <avr/io.h> #include <util/delay.h> #include <OS.hpp> #include <avr/interrupt.h> #include "drivers/serial.hpp" Serial serial; mutex muteks_01; void Task1() { while (1) { static uint8_t i = 0; PORTB ^= (1 << PB2); _delay_ms(50); serial.printf("Test %d\r\n", i); i++; } } void Task2() { while (1) { PORTB ^= (1 << PB1); _delay_ms(100); } } void Task3() { while (1) { PORTB ^= (1 << PB0); _delay_ms(200); } } int main() { // TP ONLY BEGIN serial.init(9600U); DDRB = (1 << PB0)|(1 << PB1)|(1 << PB2); PORTB = 0; sys::taskCreate(&Task1, 0, 0xFF); sys::taskCreate(&Task2, 0, 0x20); sys::taskCreate(&Task3, 0, 0x20); // TP ONLY END sys::boot(); return 0; }
#include <avr/io.h> #include <util/delay.h> #include <OS.hpp> #include <avr/interrupt.h> #include "drivers/serial.hpp" Serial serial; mutex muteks_01; void Task1() { while (1) { static uint8_t i = 0; PORTB ^= (1 << PB2); _delay_ms(50); serial.printf("Test %d\r\n", i); i++; } } void Task2() { while (1) { PORTB ^= (1 << PB1); _delay_ms(100); } } void Task3() { while (1) { PORTB ^= (1 << PB0); _delay_ms(200); } } void Task4() { for(uint8_t i=0 ; i < 10 ; i++){ PORTB ^= (1 << PB3); _delay_ms(200); } } int main() { // TP ONLY BEGIN serial.init(9600U); DDRB = (1 << PB0)|(1 << PB1)|(1 << PB2)|(1 << PB3); PORTB = 0; sys::taskCreate(&Task1, 0, 0xFF); sys::taskCreate(&Task2, 0, 0x20); sys::taskCreate(&Task3, 0, 0x20); sys::taskCreate(&Task4, 0, 0x20); // TP ONLY END sys::boot(); return 0; }
Test mmap() for large chunk of memory
#include <cstdio> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <string.h> int main() { int fd = open("/tmp/bwtree.tmp", O_RDWR | O_TRUNC | O_CREAT); if(fd == -1) { printf("open() returned -1\n"); return -1; } int ret = ftruncate(fd, (0x1L << 38)); if(ret == -1) { printf("ftruncate() returns -1; reason = %s\n", strerror(errno)); } struct stat s; fstat(fd, &s); printf("file size = %lu\n", s.st_size); return 0; }
#include <cstdio> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/mman.h> int main() { /* int fd = open("/tmp/bwtree.tmp", O_RDWR | O_TRUNC | O_CREAT); if(fd == -1) { printf("open() returned -1\n"); return -1; } int ret = ftruncate(fd, (0x1L << 38)); if(ret == -1) { printf("ftruncate() returns -1; reason = %s\n", strerror(errno)); } struct stat s; fstat(fd, &s); printf("file size = %lu\n", s.st_size); */ void *p = mmap(NULL, 0x1L << 36, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE | MAP_NORESERVE, -1, 0); if(p == MAP_FAILED) { printf("mmap() returns -1; reason = %s\n", strerror(errno)); } return 0; }
Use std::signal and csignal header
// // Created by samueli on 2017-10-02. // #include "ins_service.hpp" #include <signal.h> volatile sig_atomic_t is_server_running = 1; void kill_server(int sig) { is_server_running = 0; } int main(int argc, char* argv[]) { spdlog::set_level(spdlog::level::debug); Pistache::Port port(9080); int thread_count = 2; if (argc >= 2) { port = static_cast<uint16_t>(std::stol(argv[1])); if (argc == 3) thread_count = static_cast<int>(std::stol(argv[2])); } Pistache::Address addr(Pistache::Ipv4::any(), port); auto console = spdlog::stdout_logger_mt("main_console"); console->info("Indoor Navigation System service setting up on {1}:{0:d}", addr.port(), addr.host()); console->info("Cores = {0}", Pistache::hardware_concurrency()); console->info("Using {0} threads", thread_count); ins_service::IndoorNavigationService ins; ins.Init(addr, thread_count); // Register abort & terminate signals respectively signal(SIGINT, kill_server); signal(SIGTERM, kill_server); // start server ins.Start(); while (is_server_running) sleep(1); // shutdown server ins.Shutdown(); }
// // Created by samueli on 2017-10-02. // #include "ins_service.hpp" #include <csignal> volatile sig_atomic_t is_server_running = 1; void kill_server(int sig) { is_server_running = 0; } int main(int argc, char* argv[]) { spdlog::set_level(spdlog::level::debug); Pistache::Port port(9080); int thread_count = 2; if (argc >= 2) { port = static_cast<uint16_t>(std::stol(argv[1])); if (argc == 3) thread_count = static_cast<int>(std::stol(argv[2])); } Pistache::Address addr(Pistache::Ipv4::any(), port); auto console = spdlog::stdout_logger_mt("main_console"); console->info("Indoor Navigation System service setting up on {1}:{0:d}", addr.port(), addr.host()); console->info("Cores = {0}", Pistache::hardware_concurrency()); console->info("Using {0} threads", thread_count); ins_service::IndoorNavigationService ins; ins.Init(addr, thread_count); // Register abort & terminate signals respectively std::signal(SIGINT, kill_server); std::signal(SIGTERM, kill_server); // start server ins.Start(); while (is_server_running) sleep(1); // shutdown server ins.Shutdown(); }
Make Hint encoding safe for passing them as GET parameter in URLs
#include "engine/hint.hpp" #include "engine/base64.hpp" #include "engine/datafacade/datafacade_base.hpp" #include <boost/assert.hpp> namespace osrm { namespace engine { bool Hint::IsValid(const util::Coordinate new_input_coordinates, const datafacade::BaseDataFacade &facade) const { auto is_same_input_coordinate = new_input_coordinates.lon == phantom.input_location.lon && new_input_coordinates.lat == phantom.input_location.lat; return is_same_input_coordinate && phantom.IsValid(facade.GetNumberOfNodes()) && facade.GetCheckSum() == data_checksum; } std::string Hint::ToBase64() const { return encodeBase64Bytewise(*this); } Hint Hint::FromBase64(const std::string &base64Hint) { BOOST_ASSERT_MSG(base64Hint.size() == ENCODED_HINT_SIZE, "Hint has invalid size"); return decodeBase64Bytewise<Hint>(base64Hint); } } }
#include "engine/hint.hpp" #include "engine/base64.hpp" #include "engine/datafacade/datafacade_base.hpp" #include <boost/assert.hpp> #include <iterator> #include <algorithm> namespace osrm { namespace engine { bool Hint::IsValid(const util::Coordinate new_input_coordinates, const datafacade::BaseDataFacade &facade) const { auto is_same_input_coordinate = new_input_coordinates.lon == phantom.input_location.lon && new_input_coordinates.lat == phantom.input_location.lat; return is_same_input_coordinate && phantom.IsValid(facade.GetNumberOfNodes()) && facade.GetCheckSum() == data_checksum; } std::string Hint::ToBase64() const { auto base64 = encodeBase64Bytewise(*this); // Make safe for usage as GET parameter in URLs std::replace(begin(base64), end(base64), '+', '-'); std::replace(begin(base64), end(base64), '/', '_'); return base64; } Hint Hint::FromBase64(const std::string &base64Hint) { BOOST_ASSERT_MSG(base64Hint.size() == ENCODED_HINT_SIZE, "Hint has invalid size"); // We need mutability but don't want to change the API auto encoded = base64Hint; // Reverses above encoding we need for GET parameters in URL std::replace(begin(encoded), end(encoded), '-', '+'); std::replace(begin(encoded), end(encoded), '_', '/'); return decodeBase64Bytewise<Hint>(encoded); } } }
Mark camera transform not dirty after update
// Copyright (C) 2015 Elviss Strazdins // This file is part of the Ouzel engine. #include "Camera.h" namespace ouzel { Camera::Camera() { } Camera::~Camera() { } void Camera::setZoom(float zoom) { _zoom = zoom; if (_zoom < 0.1f) { _zoom = 0.1f; } markTransformDirty(); } void Camera::calculateTransform() const { Matrix4 translation; translation.translate(-_position.x, -_position.y, 0.0f); Matrix4 rotation; rotation.rotate(Vector3(0.0f, 0.0f, -1.0f), -_rotation); Matrix4 scale; scale.scale(_zoom); _transform = _parentTransform * scale * rotation * translation; for (NodePtr child : _children) { child->updateTransform(_transform); } } }
// Copyright (C) 2015 Elviss Strazdins // This file is part of the Ouzel engine. #include "Camera.h" namespace ouzel { Camera::Camera() { } Camera::~Camera() { } void Camera::setZoom(float zoom) { _zoom = zoom; if (_zoom < 0.1f) { _zoom = 0.1f; } markTransformDirty(); } void Camera::calculateTransform() const { Matrix4 translation; translation.translate(-_position.x, -_position.y, 0.0f); Matrix4 rotation; rotation.rotate(Vector3(0.0f, 0.0f, -1.0f), -_rotation); Matrix4 scale; scale.scale(_zoom); _transform = _parentTransform * scale * rotation * translation; _transformDirty = false; for (NodePtr child : _children) { child->updateTransform(_transform); } } }
Raise the 500px photos rpp to 10
#include "px500.h" Px500::Px500(QObject *parent) : ServerBase(parent) { } const QString Px500::serverBaseUrl() const { return QStringLiteral("https://api.500px.com/v1"); } const Parameters Px500::requestHeaders() const { const QHash<QString, QString> headers = QHash<QString, QString> { // {"Authorization", "Bearer " + PX500_OAUTH_TOKEN} }; return headers; } void Px500::photos(OnCompleted onCompleted) { const Parameters params = Parameters { { "rpp", "1" }, { "consumer_key", PX500_CONSUMER_KEY } }; get(QStringLiteral("/photos"), params, Parameters(), onCompleted); } void Px500::photoComments(int id, OnCompleted onCompleted) { const Parameters params = Parameters { { "consumer_key", PX500_CONSUMER_KEY }, { "id", QString::number(id) } }; get(QStringLiteral("/photos/:id/comments"), params, Parameters(), onCompleted); }
#include "px500.h" Px500::Px500(QObject *parent) : ServerBase(parent) { } const QString Px500::serverBaseUrl() const { return QStringLiteral("https://api.500px.com/v1"); } const Parameters Px500::requestHeaders() const { const QHash<QString, QString> headers = QHash<QString, QString> { // {"Authorization", "Bearer " + PX500_OAUTH_TOKEN} }; return headers; } void Px500::photos(OnCompleted onCompleted) { const Parameters params = Parameters { { "rpp", "10" }, { "consumer_key", PX500_CONSUMER_KEY } }; get(QStringLiteral("/photos"), params, Parameters(), onCompleted); } void Px500::photoComments(int id, OnCompleted onCompleted) { const Parameters params = Parameters { { "consumer_key", PX500_CONSUMER_KEY }, { "id", QString::number(id) } }; get(QStringLiteral("/photos/:id/comments"), params, Parameters(), onCompleted); }
Remove unnecessary IRQ priority settings
#include <mbed.h> extern void setup(); extern void loop(); void setIrqPriorities() { NVIC_SetPriority(UART5_IRQn, 1); NVIC_SetPriority(TIM5_IRQn, 2); NVIC_SetPriority(TIM4_IRQn, 3); } int main() { setIrqPriorities(); setup(); for (;;) { loop(); } }
#include <mbed.h> extern void setup(); extern void loop(); void setIrqPriorities() { } int main() { setIrqPriorities(); setup(); for (;;) { loop(); } }
Fix bug where EAGAIN and EWOULDBLOCK can cause data corruption.
#include "SocketHandler.hpp" namespace et { void SocketHandler::readAll(int fd, void* buf, size_t count) { size_t pos = 0; while (pos < count) { ssize_t bytesRead = read(fd, ((char*)buf) + pos, count - pos); if (bytesRead < 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) { // This is fine, just keep retrying at 10hz usleep(1000 * 100); } else { VLOG(1) << "Failed a call to readAll: " << strerror(errno); throw std::runtime_error("Failed a call to readAll"); } } pos += bytesRead; } } void SocketHandler::writeAll(int fd, const void* buf, size_t count) { size_t pos = 0; while (pos < count) { ssize_t bytesWritten = write(fd, ((const char*)buf) + pos, count - pos); if (bytesWritten < 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) { // This is fine, just keep retrying at 10hz usleep(1000 * 100); } else { VLOG(1) << "Failed a call to writeAll: " << strerror(errno); throw std::runtime_error("Failed a call to writeAll"); } } pos += bytesWritten; } } }
#include "SocketHandler.hpp" namespace et { void SocketHandler::readAll(int fd, void* buf, size_t count) { size_t pos = 0; while (pos < count) { ssize_t bytesRead = read(fd, ((char*)buf) + pos, count - pos); if (bytesRead < 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) { // This is fine, just keep retrying at 10hz usleep(1000 * 100); } else { VLOG(1) << "Failed a call to readAll: " << strerror(errno); throw std::runtime_error("Failed a call to readAll"); } } else { pos += bytesRead; } } } void SocketHandler::writeAll(int fd, const void* buf, size_t count) { size_t pos = 0; while (pos < count) { ssize_t bytesWritten = write(fd, ((const char*)buf) + pos, count - pos); if (bytesWritten < 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) { // This is fine, just keep retrying at 10hz usleep(1000 * 100); } else { VLOG(1) << "Failed a call to writeAll: " << strerror(errno); throw std::runtime_error("Failed a call to writeAll"); } } else { pos += bytesWritten; } } } }
Revert r7595 due to housekeeper warning-as-error.
/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrTypes.h" #include "SkThread.h" // for sk_atomic_inc // This used to be a global scope, but we got a warning about unused variable // so we moved it into here. We just want it to compile, so we can test the // static asserts. static inline void dummy_function_to_avoid_unused_var_warning() { static const GrCacheID::Key kAssertKey; GR_STATIC_ASSERT(sizeof(kAssertKey.fData8) == sizeof(kAssertKey.fData32)); GR_STATIC_ASSERT(sizeof(kAssertKey.fData8) == sizeof(kAssertKey.fData64)); GR_STATIC_ASSERT(sizeof(kAssertKey.fData8) == sizeof(kAssertKey)); } GrCacheID::Domain GrCacheID::GenerateDomain() { static int32_t gNextDomain = kInvalid_Domain + 1; int32_t domain = sk_atomic_inc(&gNextDomain); if (domain >= 1 << (8 * sizeof(Domain))) { GrCrash("Too many Cache Domains"); } return static_cast<Domain>(domain); }
/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrTypes.h" #include "SkThread.h" // for sk_atomic_inc // Well, the dummy_ "fix" caused a warning on windows, so hiding all of it // until we can find a universal fix. #if 0 // This used to be a global scope, but we got a warning about unused variable // so we moved it into here. We just want it to compile, so we can test the // static asserts. static inline void dummy_function_to_avoid_unused_var_warning() { GrCacheID::Key kAssertKey; GR_STATIC_ASSERT(sizeof(kAssertKey.fData8) == sizeof(kAssertKey.fData32)); GR_STATIC_ASSERT(sizeof(kAssertKey.fData8) == sizeof(kAssertKey.fData64)); GR_STATIC_ASSERT(sizeof(kAssertKey.fData8) == sizeof(kAssertKey)); } #endif GrCacheID::Domain GrCacheID::GenerateDomain() { static int32_t gNextDomain = kInvalid_Domain + 1; int32_t domain = sk_atomic_inc(&gNextDomain); if (domain >= 1 << (8 * sizeof(Domain))) { GrCrash("Too many Cache Domains"); } return static_cast<Domain>(domain); }
Set small screen + high resolution profile on Android.
// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2015 Gábor Péterffy <peterffy95@gmail.com> // #include <QApplication> #include <QQmlApplicationEngine> #include "declarative/MarbleDeclarativePlugin.h" #include "MarbleMaps.h" int main(int argc, char ** argv) { QApplication app(argc, argv); MarbleDeclarativePlugin declarativePlugin; const char * uri = "org.kde.edu.marble"; declarativePlugin.registerTypes(uri); qmlRegisterType<Marble::MarbleMaps>(uri, 0, 20, "MarbleMaps"); QQmlApplicationEngine engine(QUrl("qrc:/MainScreen.qml")); return app.exec(); }
// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2015 Gábor Péterffy <peterffy95@gmail.com> // #include <QApplication> #include <QQmlApplicationEngine> #include "declarative/MarbleDeclarativePlugin.h" #include <MarbleGlobal.h> #include "MarbleMaps.h" using namespace Marble; int main(int argc, char ** argv) { QApplication app(argc, argv); #ifdef Q_OS_ANDROID MarbleGlobal::Profiles profiles = MarbleGlobal::SmallScreen | MarbleGlobal::HighResolution; MarbleGlobal::getInstance()->setProfiles( profiles ); #endif MarbleDeclarativePlugin declarativePlugin; const char * uri = "org.kde.edu.marble"; declarativePlugin.registerTypes(uri); qmlRegisterType<MarbleMaps>(uri, 0, 20, "MarbleMaps"); QQmlApplicationEngine engine(QUrl("qrc:/MainScreen.qml")); return app.exec(); }
Fix handling of replies to show the number of words at the end.
#include "hiredis/hiredis.h" #include <cstdlib> #include <iostream> #include <fstream> #include <string> using namespace std; int main (int argc, const char** argv) { auto context = redisConnect("127.0.0.1", 6379); // auto context = redisConnectUnix("/tmp/redis.sock"); if (context != NULL && context->err) { cerr << "Error: " << context->errstr << endl; return 1; } redisCommand (context, "FLUSHDB"); string line; for (size_t param = 1; param < argc; ++param) { cout << argv [param] << endl; string filename = argv[param]; ifstream dict (filename); if (dict.is_open()) { size_t count = 0; while (getline(dict, line)) { redisAppendCommand (context, "SET %s true", line.c_str()); count++; if (count == 10000) { for (size_t j = 0; j < count; ++j) redisGetReply (context, NULL); count = 0; cout << "." << flush; } } } dict.close(); cout << endl; } cout << endl; auto reply = (redisReply*) redisCommand (context, "DBSIZE"); cout << "# Words: " << reply->integer << endl; }
#include "hiredis/hiredis.h" #include <cstdlib> #include <iostream> #include <fstream> #include <string> using namespace std; int main (int argc, const char** argv) { auto context = redisConnect("127.0.0.1", 6379); // auto context = redisConnectUnix("/tmp/redis.sock"); if (context != NULL && context->err) { cerr << "Error: " << context->errstr << endl; return 1; } redisCommand (context, "FLUSHDB"); redisReply* reply; string line; for (size_t param = 1; param < argc; ++param) { cout << argv [param] << endl; string filename = argv[param]; ifstream dict (filename); if (dict.is_open()) { size_t count = 0; while (getline(dict, line)) { redisAppendCommand (context, "SET %s true", line.c_str()); count++; if (count == 10000) { for (size_t j = 0; j < count; ++j) { redisGetReply (context, (void**) &reply); } count = 0; cout << "." << flush; } } for (size_t j = 0; j < count; ++j) { redisGetReply (context, (void**) &reply); } } dict.close(); cout << endl; } cout << endl; reply = (redisReply*) redisCommand (context, "DBSIZE"); cout << "# Words: " << reply->integer << endl; }
Use c++11 syntax for succinct iterator syntax
#include <functional> #include <stack> #include <string> #include <ccspec/core/example_group.h> namespace ccspec { namespace core { using std::function; using std::stack; using std::string; stack<ExampleGroup*> groups_being_defined; // Public methods. ExampleGroup::~ExampleGroup() { for (auto it = children_.begin(); it != children_.end(); ++it) delete *it; } void ExampleGroup::addExample(Example& example) { examples_.push_back(example); } void ExampleGroup::run() { for (auto& example : examples_) example.run(); for (auto child : children_) child->run(); } // Private methods. ExampleGroup::ExampleGroup(string desc) : desc_(desc) {} void ExampleGroup::addChild(ExampleGroup* example_group) { children_.push_back(example_group); } // Friend methods. ExampleGroup* describe(string desc, function<void ()> spec) { ExampleGroup* example_group = new ExampleGroup(desc); if (!groups_being_defined.empty()) { ExampleGroup* current_group = groups_being_defined.top(); current_group->addChild(example_group); } groups_being_defined.push(example_group); spec(); groups_being_defined.pop(); return example_group; } ExampleGroup* context(string desc, function<void ()> spec) { return describe(desc, spec); } } // namespace core } // namespace ccspec
#include <functional> #include <stack> #include <string> #include <ccspec/core/example_group.h> namespace ccspec { namespace core { using std::function; using std::stack; using std::string; stack<ExampleGroup*> groups_being_defined; // Public methods. ExampleGroup::~ExampleGroup() { for (auto& child : children_) delete child; } void ExampleGroup::addExample(Example& example) { examples_.push_back(example); } void ExampleGroup::run() { for (auto& example : examples_) example.run(); for (auto child : children_) child->run(); } // Private methods. ExampleGroup::ExampleGroup(string desc) : desc_(desc) {} void ExampleGroup::addChild(ExampleGroup* example_group) { children_.push_back(example_group); } // Friend methods. ExampleGroup* describe(string desc, function<void ()> spec) { ExampleGroup* example_group = new ExampleGroup(desc); if (!groups_being_defined.empty()) { ExampleGroup* current_group = groups_being_defined.top(); current_group->addChild(example_group); } groups_being_defined.push(example_group); spec(); groups_being_defined.pop(); return example_group; } ExampleGroup* context(string desc, function<void ()> spec) { return describe(desc, spec); } } // namespace core } // namespace ccspec
Remove check invalid self; it only created ICS3
#include "ics3/eeprom.hpp" #include "ics3/eepparam.hpp" #include "ics3/ics3.hpp" #include <stdexcept> ics::EepParam ics::Eeprom::get(EepParam param) const { try { param.read(data); } catch (...) { throw std::runtime_error {"Fail data: non initialize EEPROM by ICS"}; } return param; } void ics::Eeprom::set(const EepParam& param) noexcept { param.write(data); } void ics::Eeprom::copyTo(std::vector<unsigned char>& dest) const noexcept { dest.resize(data.size()); std::copy(data.begin(), data.end(), dest.begin()); } void ics::Eeprom::copyTo(std::array<unsigned char, 64>& dest) const noexcept { dest = data; } ics::Eeprom::Eeprom(const std::array<unsigned char, 64>& src) : data {src} {}
#include "ics3/eeprom.hpp" #include "ics3/eepparam.hpp" #include <stdexcept> ics::EepParam ics::Eeprom::get(EepParam param) const { param.read(data); return param; } void ics::Eeprom::set(const EepParam& param) noexcept { param.write(data); } void ics::Eeprom::copyTo(std::vector<unsigned char>& dest) const noexcept { dest.resize(data.size()); std::copy(data.begin(), data.end(), dest.begin()); } void ics::Eeprom::copyTo(std::array<unsigned char, 64>& dest) const noexcept { dest = data; } ics::Eeprom::Eeprom(const std::array<unsigned char, 64>& src) : data {src} {}
Implement util functions to read stage2
#ifndef NULL #ifdef __cplusplus #define NULL 0 #else #define NULL ((void *)0) #endif #endif extern "C" void KMain() { __asm { mov ah, 0h int 010h } }
#ifndef NULL #ifdef __cplusplus #define NULL 0 #else #define NULL ((void *)0) #endif #endif static struct { char size; char res; short transferSize; int dest; long source; } LBAPacket = {0x10, 0, 0, 0, 0}; inline void PrintChar(char c) { __asm { mov AH, 0x0A; mov AL, c; mov CX, 1; int 0x10; } } inline char* ReadSector(int source, int size) { LBAPacket.source = source; LBAPacket.transferSize = size; __asm { mov SI, LBAPacket; mov AH, 0x42; mov DL, 0x80; int 0x13; } return (char*)0; } extern "C" void KMain() { }
Make this test more portable
// RUN: %clangxx_tsan -O1 %s -DLIB -fPIC -fno-sanitize=thread -shared -o %T/libignore_lib0.so // RUN: %clangxx_tsan -O1 %s -L%T -lignore_lib0 -o %t // RUN: echo running w/o suppressions: // RUN: LD_LIBRARY_PATH=%T not %t 2>&1 | FileCheck %s --check-prefix=CHECK-NOSUPP // RUN: echo running with suppressions: // RUN: LD_LIBRARY_PATH=%T TSAN_OPTIONS="$TSAN_OPTIONS suppressions=%s.supp" %t 2>&1 | FileCheck %s --check-prefix=CHECK-WITHSUPP // Tests that interceptors coming from a library specified in called_from_lib // suppression are ignored. #ifndef LIB extern "C" void libfunc(); int main() { libfunc(); } #else // #ifdef LIB #include "ignore_lib_lib.h" #endif // #ifdef LIB // CHECK-NOSUPP: WARNING: ThreadSanitizer: data race // CHECK-NOSUPP: OK // CHECK-WITHSUPP-NOT: WARNING: ThreadSanitizer: data race // CHECK-WITHSUPP: OK
// RUN: %clangxx_tsan -O1 %s -DLIB -fPIC -fno-sanitize=thread -shared -o %T/libignore_lib0.so // RUN: %clangxx_tsan -O1 %s -L%T -lignore_lib0 -o %t // RUN: echo running w/o suppressions: // RUN: LD_LIBRARY_PATH=%T${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH} not %t 2>&1 | FileCheck %s --check-prefix=CHECK-NOSUPP // RUN: echo running with suppressions: // RUN: LD_LIBRARY_PATH=%T${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH} TSAN_OPTIONS="$TSAN_OPTIONS suppressions=%s.supp" %t 2>&1 | FileCheck %s --check-prefix=CHECK-WITHSUPP // Tests that interceptors coming from a library specified in called_from_lib // suppression are ignored. #ifndef LIB extern "C" void libfunc(); int main() { libfunc(); } #else // #ifdef LIB #include "ignore_lib_lib.h" #endif // #ifdef LIB // CHECK-NOSUPP: WARNING: ThreadSanitizer: data race // CHECK-NOSUPP: OK // CHECK-WITHSUPP-NOT: WARNING: ThreadSanitizer: data race // CHECK-WITHSUPP: OK
Use filesystem library path concatenation
#include "extract.hpp" #include "../huffman/decompress.hpp" #include<fstream> #include<vector> #include<experimental/filesystem> void extract(const char* in_file, const char* out_dir) { std::ifstream in(in_file); extract(in, out_dir); } void extract(std::istream& in_stream, const char* out_dir) { std::istreambuf_iterator<char> in_iterator(in_stream); std::vector<std::string> filenames; std::string fn; while(true) { char next = *in_iterator; ++in_iterator; if(next == '\0') { if(fn.empty()) break; filenames.push_back(fn); fn.clear(); } else { fn.push_back(next); } } BinaryRead bin_in(in_iterator); for(auto& fn : filenames) { std::string full_name = out_dir + ("/" + fn); const auto ind = full_name.find_last_of("/"); std::experimental::filesystem::create_directories(full_name.substr(0, ind)); std::ofstream out(full_name); std::ostreambuf_iterator<char> out_iterator(out); decompress(bin_in, out_iterator); } }
#include "extract.hpp" #include "../huffman/decompress.hpp" #include<fstream> #include<vector> #include<experimental/filesystem> namespace fs = std::experimental::filesystem; void extract(const char* in_file, const char* out_dir) { std::ifstream in(in_file); extract(in, out_dir); } void extract(std::istream& in_stream, const char* out_dir) { std::istreambuf_iterator<char> in_iterator(in_stream); std::vector<std::string> filenames; std::string fn; while(true) { char next = *in_iterator; ++in_iterator; if(next == '\0') { if(fn.empty()) break; filenames.push_back(fn); fn.clear(); } else { fn.push_back(next); } } BinaryRead bin_in(in_iterator); for(auto& fn : filenames) { std::string full_name = fs::path(out_dir) / fn; const auto ind = full_name.find_last_of("/"); fs::create_directories(full_name.substr(0, ind)); std::ofstream out(full_name); std::ostreambuf_iterator<char> out_iterator(out); decompress(bin_in, out_iterator); } }
Add a std::string reverse test
#include <algorithm> #include <gtest/gtest.h> TEST(array, sorting) { int foo[3] = {1, 3, 2}; std::sort(foo, foo + 3); EXPECT_EQ(1, foo[0]); EXPECT_EQ(2, foo[1]); EXPECT_EQ(3, foo[2]); } TEST(swap, test1) { int a = 1; int b = 2; std::swap(a, b); EXPECT_EQ(2, a); EXPECT_EQ(1, b); }
#include <algorithm> #include <gtest/gtest.h> TEST(array, sorting) { int foo[3] = {1, 3, 2}; std::sort(foo, foo + 3); EXPECT_EQ(1, foo[0]); EXPECT_EQ(2, foo[1]); EXPECT_EQ(3, foo[2]); } TEST(swap, test1) { int a = 1; int b = 2; std::swap(a, b); EXPECT_EQ(2, a); EXPECT_EQ(1, b); } TEST(reverse, string) { std::string s = "abc"; std::reverse(s.begin(), s.end()); EXPECT_EQ("cba", s); }
Refactor word decoder unit tests
#include <catch.hpp> #include "WordDecoder.hpp" namespace { using namespace Core8; TEST_CASE("Decode X from pattern vXvv", "[decoder]") { REQUIRE(WordDecoder::readX(0x0F00) == 0XF); REQUIRE(WordDecoder::readX(0xF0FF) == 0X0); } TEST_CASE("Decode Y from pattern vvYv", "[decoder]") { REQUIRE(WordDecoder::readY(0x00F0) == 0XF); REQUIRE(WordDecoder::readY(0xFF0F) == 0X0); } TEST_CASE("Decode N from pattern vvvN", "[decoder]") { REQUIRE(WordDecoder::readN(0x000F) == 0XF); REQUIRE(WordDecoder::readN(0xFFF0) == 0X0); } TEST_CASE("Decode NN from pattern vvNN", "[decoder]") { REQUIRE(WordDecoder::readNN(0x00FF) == 0XFF); REQUIRE(WordDecoder::readNN(0xFF11) == 0X11); } TEST_CASE("Decode NNN from pattern vNNN", "[decoder]") { REQUIRE(WordDecoder::readNNN(0x0FFF) == 0XFFF); REQUIRE(WordDecoder::readNNN(0xF111) == 0X111); } } // unnamed namespace
#include <catch.hpp> #include "WordDecoder.hpp" namespace { TEST_CASE("Decode X from pattern vXvv", "[decoder]") { REQUIRE(Core8::WordDecoder::readX(0x0F00) == 0XF); REQUIRE(Core8::WordDecoder::readX(0xF0FF) == 0X0); } TEST_CASE("Decode Y from pattern vvYv", "[decoder]") { REQUIRE(Core8::WordDecoder::readY(0x00F0) == 0XF); REQUIRE(Core8::WordDecoder::readY(0xFF0F) == 0X0); } TEST_CASE("Decode N from pattern vvvN", "[decoder]") { REQUIRE(Core8::WordDecoder::readN(0x000F) == 0XF); REQUIRE(Core8::WordDecoder::readN(0xFFF0) == 0X0); } TEST_CASE("Decode NN from pattern vvNN", "[decoder]") { REQUIRE(Core8::WordDecoder::readNN(0x00FF) == 0XFF); REQUIRE(Core8::WordDecoder::readNN(0xFF11) == 0X11); } TEST_CASE("Decode NNN from pattern vNNN", "[decoder]") { REQUIRE(Core8::WordDecoder::readNNN(0x0FFF) == 0XFFF); REQUIRE(Core8::WordDecoder::readNNN(0xF111) == 0X111); } } // namespace
Fix gl error debug print.
/* * 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 "GrGLConfig.h" #include "GrGLInterface.h" void GrGLClearErr(const GrGLInterface* gl) { while (GR_GL_NO_ERROR != gl->fGetError()) {} } void GrGLCheckErr(const GrGLInterface* gl, const char* location, const char* call) { uint32_t err = GR_GL_GET_ERROR(gl); if (GR_GL_NO_ERROR != err) { GrPrintf("---- glGetError %x", GR_GL_GET_ERROR(gl)); if (NULL != location) { GrPrintf(" at\n\t%s", location); } if (NULL != call) { GrPrintf("\n\t\t%s", call); } GrPrintf("\n"); } } void GrGLResetRowLength(const GrGLInterface* gl) { if (gl->supportsDesktop()) { GR_GL_CALL(gl, PixelStorei(GR_GL_UNPACK_ROW_LENGTH, 0)); } } /////////////////////////////////////////////////////////////////////////////// #if GR_GL_LOG_CALLS bool gLogCallsGL = !!(GR_GL_LOG_CALLS_START); #endif #if GR_GL_CHECK_ERROR bool gCheckErrorGL = !!(GR_GL_CHECK_ERROR_START); #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 "GrGLConfig.h" #include "GrGLInterface.h" void GrGLClearErr(const GrGLInterface* gl) { while (GR_GL_NO_ERROR != gl->fGetError()) {} } void GrGLCheckErr(const GrGLInterface* gl, const char* location, const char* call) { uint32_t err = GR_GL_GET_ERROR(gl); if (GR_GL_NO_ERROR != err) { GrPrintf("---- glGetError %x", err); if (NULL != location) { GrPrintf(" at\n\t%s", location); } if (NULL != call) { GrPrintf("\n\t\t%s", call); } GrPrintf("\n"); } } void GrGLResetRowLength(const GrGLInterface* gl) { if (gl->supportsDesktop()) { GR_GL_CALL(gl, PixelStorei(GR_GL_UNPACK_ROW_LENGTH, 0)); } } /////////////////////////////////////////////////////////////////////////////// #if GR_GL_LOG_CALLS bool gLogCallsGL = !!(GR_GL_LOG_CALLS_START); #endif #if GR_GL_CHECK_ERROR bool gCheckErrorGL = !!(GR_GL_CHECK_ERROR_START); #endif
Remove some headers which are not frequently used
# include <algorithm> # include <iostream> # include <iterator> # include <vector> # include <string> # include <queue> # include <stack> # include <cmath> # include <set> using namespace std; int main() { return 0; }
# include <cmath> # include <iostream> # include <queue> # include <set> # include <stack> # include <string> # include <vector> using namespace std; int main() { return 0; }
Add regression test for PR41576 (which is already fixed in trunk, perhaps by r361300).
// RUN: %clang_cc1 -std=c++2a -verify %s // expected-no-diagnostics template<typename ...T, typename ...Lambda> void check_sizes(Lambda ...L) { static_assert(((sizeof(T) == sizeof(Lambda)) && ...)); } template<typename ...T> void f(T ...v) { // Pack expansion of lambdas: each lambda captures only one pack element. check_sizes<T...>([=] { (void)&v; } ...); // Pack expansion inside lambda: captures all pack elements. auto l = [=] { ((void)&v, ...); }; static_assert(sizeof(l) >= (sizeof(T) + ...)); } template void f(int, char, double);
// RUN: %clang_cc1 -std=c++2a -verify %s template<typename ...T, typename ...Lambda> void check_sizes(Lambda ...L) { static_assert(((sizeof(T) == sizeof(Lambda)) && ...)); } template<typename ...T> void f(T ...v) { // Pack expansion of lambdas: each lambda captures only one pack element. check_sizes<T...>([=] { (void)&v; } ...); // Pack expansion inside lambda: captures all pack elements. auto l = [=] { ((void)&v, ...); }; static_assert(sizeof(l) >= (sizeof(T) + ...)); } template void f(int, char, double); namespace PR41576 { template <class... Xs> constexpr int f(Xs ...xs) { return [&](auto ...ys) { // expected-note {{instantiation}} return ((xs + ys), ...); // expected-warning {{unused}} }(1, 2); } static_assert(f(3, 4) == 6); // expected-note {{instantiation}} }
Fix for issue that would cause an occasional segmentation fault on Linux if already in an error state in throwV8Exception. va_list must be reinitialized after each use.
#include "edge_common.h" v8::Local<Value> throwV8Exception(v8::Local<Value> exception) { Nan::EscapableHandleScope scope; Nan::ThrowError(exception); return scope.Escape(exception); } v8::Local<Value> throwV8Exception(const char* format, ...) { va_list args; va_start(args, format); size_t size = vsnprintf(NULL, 0, format, args); char* message = new char[size + 1]; vsnprintf(message, size + 1, format, args); Nan::EscapableHandleScope scope; v8::Local<v8::Object> exception = Nan::New<v8::Object>(); exception->SetPrototype(Nan::GetCurrentContext(), v8::Exception::Error(Nan::New<v8::String>(message).ToLocalChecked())); v8::Local<v8::Value> exceptionValue = exception; Nan::ThrowError(exceptionValue); return scope.Escape(exception); }
#include "edge_common.h" v8::Local<Value> throwV8Exception(v8::Local<Value> exception) { Nan::EscapableHandleScope scope; Nan::ThrowError(exception); return scope.Escape(exception); } v8::Local<Value> throwV8Exception(const char* format, ...) { va_list args; va_start(args, format); size_t size = vsnprintf(NULL, 0, format, args); char* message = new char[size + 1]; va_start(args, format); vsnprintf(message, size + 1, format, args); Nan::EscapableHandleScope scope; v8::Local<v8::Object> exception = Nan::New<v8::Object>(); exception->SetPrototype(Nan::GetCurrentContext(), v8::Exception::Error(Nan::New<v8::String>(message).ToLocalChecked())); v8::Local<v8::Value> exceptionValue = exception; Nan::ThrowError(exceptionValue); return scope.Escape(exception); }
Remove entry from map if vector<Tuple> empty in ForgetThread::processForget()
#include "forgetthread.h" void ForgetThread::launch(){ //Aliases transactionHistory = transactionHistoryPtr[thread]; tupleContent = tupleContentPtr[thread]; mutexForget.lock(); while(true){ //Waits for the signal from main thread processingForgetThreadsNb++; conditionForget.wait(mutexForget); mutexForget.unlock(); //Checks if the program is over if(referenceOver) break; //Actual forget work processForget(); //When done processing decrements processingThreadNb if(--processingForgetThreadsNb==0){ //Signals main thread mutexForget.lock(); conditionForget.notify_all(); mutexForget.unlock(); }else{ //waits for the releaser thread mutexForget.lock(); conditionForget.wait(mutexForget); } } pthread_exit(EXIT_SUCCESS); } void ForgetThread::processForget(){ Tuple bound{forgetTransactionId, 0}; for(auto iter=transactionHistory->begin(); iter!=transactionHistory->end(); ++iter){ auto * secondMap = &(iter->second); for(auto iter2=secondMap->begin(); iter2!=secondMap->end(); ++iter2){ vector<Tuple> * tuples = &(iter2->second); tuples->erase(tuples->begin(), lower_bound(tuples->begin(), tuples->end(), bound)); } } //Erase from tupleContent tupleContent->erase(tupleContent->begin(), tupleContent->lower_bound(bound)); }
#include "forgetthread.h" void ForgetThread::launch(){ //Aliases transactionHistory = transactionHistoryPtr[thread]; tupleContent = tupleContentPtr[thread]; mutexForget.lock(); while(true){ //Waits for the signal from main thread processingForgetThreadsNb++; conditionForget.wait(mutexForget); mutexForget.unlock(); //Checks if the program is over if(referenceOver) break; //Actual forget work processForget(); //When done processing decrements processingThreadNb if(--processingForgetThreadsNb==0){ //Signals main thread mutexForget.lock(); conditionForget.notify_all(); mutexForget.unlock(); }else{ //waits for the releaser thread mutexForget.lock(); conditionForget.wait(mutexForget); } } pthread_exit(EXIT_SUCCESS); } void ForgetThread::processForget(){ Tuple bound{forgetTransactionId, 0}; for(auto iter=transactionHistory->begin(); iter!=transactionHistory->end(); ++iter){ auto * secondMap = &(iter->second); for(auto iter2=secondMap->begin(); iter2!=secondMap->end();){ vector<Tuple> * tuples = &(iter2->second); tuples->erase(tuples->begin(), lower_bound(tuples->begin(), tuples->end(), bound)); if(tuples->empty()){ auto toErase = iter2; ++iter2; secondMap->erase(toErase); }else{ ++iter2; } } } //Erase from tupleContent tupleContent->erase(tupleContent->begin(), tupleContent->lower_bound(bound)); }
Fix building for pre-C++14 standards
#include "test.h" #include "floaxie/ftoa.h" void dtoa_floaxie(double v, char* buffer) { floaxie::ftoa(v, buffer); } REGISTER_TEST(floaxie);
#if __cplusplus >= 201402L #include "test.h" #include "floaxie/ftoa.h" void dtoa_floaxie(double v, char* buffer) { floaxie::ftoa(v, buffer); } REGISTER_TEST(floaxie); #endif
Allow configuraiton of state-store log dir / name. Also add debug webserver to state-store.
// Copyright (c) 2012 Cloudera, Inc. All rights reserved. // // This file contains the main() function for the state store process, // which exports the Thrift service StateStoreService. #include <glog/logging.h> #include <gflags/gflags.h> #include "sparrow/state-store-service.h" #include "util/cpu-info.h" DEFINE_int32(state_store_port, 24000, "port where StateStoreService is exported"); int main(int argc, char** argv) { google::InitGoogleLogging(argv[0]); google::ParseCommandLineFlags(&argc, &argv, true); impala::CpuInfo::Init(); boost::shared_ptr<sparrow::StateStore> state_store(new sparrow::StateStore()); state_store->Start(FLAGS_state_store_port); state_store->WaitForServerToStop(); }
// Copyright (c) 2012 Cloudera, Inc. All rights reserved. // // This file contains the main() function for the state store process, // which exports the Thrift service StateStoreService. #include <glog/logging.h> #include <gflags/gflags.h> #include <iostream> #include "common/status.h" #include "sparrow/state-store-service.h" #include "util/cpu-info.h" #include "util/webserver.h" #include "util/logging.h" #include "util/default-path-handlers.h" DECLARE_int32(state_store_port); DECLARE_int32(webserver_port); DECLARE_bool(enable_webserver); using impala::Webserver; using impala::Status; using namespace std; int main(int argc, char** argv) { // Override default for webserver port FLAGS_webserver_port = 9190; google::ParseCommandLineFlags(&argc, &argv, true); impala::InitGoogleLoggingSafe(argv[0]); impala::CpuInfo::Init(); boost::shared_ptr<sparrow::StateStore> state_store(new sparrow::StateStore()); boost::scoped_ptr<Webserver> webserver(new Webserver()); if (FLAGS_enable_webserver) { impala::AddDefaultPathHandlers(webserver.get()); EXIT_IF_ERROR(webserver->Start()); } else { LOG(INFO) << "Not starting webserver"; } state_store->Start(FLAGS_state_store_port); state_store->WaitForServerToStop(); }
Add test to retrieve a table from database.
#include "ReQL-ast-test.hpp" class BlankTest : public ASTTest { public: BlankTest() : ASTTest() { } void setup() { setName("BlankTest"); } void run() { } void cleanup() { } }; void ASTTest::setup() { setName("ASTTest"); addTest(BlankTest()); }
#include "ReQL-ast-test.hpp" using namespace ReQL; class BlankTest : public ASTTest { public: BlankTest() : ASTTest() { } void setup(); void cleanup() { conn.close(); } Connection conn; }; class TableTermTest : public BlankTest { public: TableTermTest() : BlankTest() {}; void run() { table({expr("test")}).run(conn); } }; void BlankTest::setup() { setName("BlankTest"); conn = connect(); assert(conn.isOpen(), "Connection failed."); addTest(TableTermTest()); } void ASTTest::setup() { setName("ASTTest"); addTest(BlankTest()); }
Fix reference to unavailable nodes
#include<iostream> using namespace std; class node{ public: int data; node *left, *right; node(){} node(int d) { data=d; left=NULL; right=NULL; } node *insertNode(node *root, int d) { if(!root) return new node(d); else if(d <= root->data) root->left=insertNode(root->left,d); else root->right=insertNode(root->right,d); return root; } node *inorder(node *root) { if(root) { inorder(root->left); cout<<root->data<<"\n"; inorder(root->right); } } }; int main() { int n,d; node nd; node *root=NULL; cout<<"Enter the number of elements in the tree:"; cin>>n; for(int i=0;i<n;i++){ cout<<"\nEnter the element "<<i+1<<" of the tree:"; cin>>d; root=nd.insertNode(root,d); } cout<<"\nInorder traversal of the tree gives:\n"; nd.inorder(root); }
#include<iostream> using namespace std; class node{ public: int data; node *left, *right; node(){} node(int d) { data=d; left=NULL; right=NULL; } node *insertNode(node *root, int d) { if(!root) return new node(d); if(d <= root->data) root->left=insertNode(root->left,d); else root->right=insertNode(root->right,d); return root; } node *inorder(node *root) { if(root) { if(root->left) inorder(root->left); cout<<root->data<<"\n"; if(root->right) inorder(root->right); } } }; int main() { int n,d; node nd; node *root=NULL; cout<<"Enter the number of elements in the tree:"; cin>>n; for(int i=0;i<n;i++){ cout<<"\nEnter the element "<<i+1<<" of the tree:"; cin>>d; root=nd.insertNode(root,d); } cout<<"\nInorder traversal of the tree gives:\n"; nd.inorder(root); }
Clear database between each test & add a test for file insertion
#include "gtest/gtest.h" #include "IMediaLibrary.h" TEST( MediaLibary, Init ) { IMediaLibrary* ml = MediaLibraryFactory::create(); ASSERT_TRUE( ml->initialize( "test.db" ) ); }
#include "gtest/gtest.h" #include "IMediaLibrary.h" class MLTest : public testing::Test { public: static IMediaLibrary* ml; protected: virtual void SetUp() { ml = MediaLibraryFactory::create(); bool res = ml->initialize( "test.db" ); ASSERT_TRUE( res ); } virtual void TearDown() { delete ml; unlink("test.db"); } }; IMediaLibrary* MLTest::ml; TEST_F( MLTest, Init ) { // only test for correct test fixture behavior } TEST_F( MLTest, InsertFile ) { IFile* f = ml->addFile( "/dev/null" ); ASSERT_TRUE( f != NULL ); std::vector<IFile*> files = ml->files(); ASSERT_EQ( files.size(), 1u ); ASSERT_EQ( files[0]->mrl(), f->mrl() ); }
Use cv::VideoCapture properties to get width and height.
#include "WebcamDataProvider.h" namespace yarrar { WebcamDataProvider::WebcamDataProvider(const json11::Json& config) : DataProvider(config) , m_videoCapture(0) , m_dp({}) { if(!m_videoCapture.isOpened()) { throw std::runtime_error("cant open video"); } } const LockableData<Datapoint>& WebcamDataProvider::getData() { cv::Mat ret; m_videoCapture >> ret; auto handle = m_dp.lockReadWrite(); handle.set({ std::chrono::high_resolution_clock::now(), ret }); return m_dp; } Dimensions WebcamDataProvider::getDimensions() { const auto& data = getData(); auto handle = data.lockRead(); return { handle.get().data.cols, handle.get().data.rows }; } DatatypeFlags WebcamDataProvider::provides() { return RGB_CAMERA_FLAG; } }
#include "WebcamDataProvider.h" namespace yarrar { WebcamDataProvider::WebcamDataProvider(const json11::Json& config) : DataProvider(config) , m_videoCapture(0) , m_dp({}) { if(!m_videoCapture.isOpened()) { throw std::runtime_error("cant open video"); } } const LockableData<Datapoint>& WebcamDataProvider::getData() { cv::Mat ret; m_videoCapture >> ret; auto handle = m_dp.lockReadWrite(); handle.set({ std::chrono::high_resolution_clock::now(), ret }); return m_dp; } Dimensions WebcamDataProvider::getDimensions() { return { static_cast<int>(m_videoCapture.get(CV_CAP_PROP_FRAME_WIDTH)), static_cast<int>(m_videoCapture.get(CV_CAP_PROP_FRAME_HEIGHT)) }; } DatatypeFlags WebcamDataProvider::provides() { return RGB_CAMERA_FLAG; } }
Make apps/pe accept problem number as argument
#include <iostream> using std::cout; using std::endl; #include "problems/Factory.h" #include "util/Timer.h" using util::Timer; int main(int argc, char **argv) { auto problem = problems::Factory::create(1); Timer t; t.start(); problem->solve(); t.stop(); cout << problem->answer() << endl; cout << "Time elapsed: " << t << endl; return 0; }
#include <iostream> using std::cerr; using std::cout; using std::endl; #include <stdexcept> using std::exception; using std::out_of_range; #include <string> using std::stoul; #include "problems/Factory.h" #include "util/Timer.h" using util::Timer; void all_problems(); void one_problem(const unsigned long problem); int main(int argc, char **argv) { bool usage = false; try { if (argc > 2) usage = true; else if (argc == 2) one_problem(stoul(argv[1])); else all_problems(); } catch (out_of_range oor) { usage = true; cerr << "Number too large.\n"; } catch (exception ia) { usage = true; } if (usage) { cerr << "Invalid usage. Pass either a number or nothing to run all" << endl; return 1; } return 0; } void all_problems() { } void one_problem(const unsigned long problem) { auto p = problems::Factory::create(problem); Timer t; t.start(); p->solve(); t.stop(); cout << p->answer() << "\n" << "Time elapsed: " << t << endl; }
Remove header from notebook tree
#include "notebooktree.h" #include "treenotebookitem.h" #include "treenotebookpageitem.h" #include "notebookexception.h" NotebookTree::NotebookTree(QWidget* parent) : QTreeWidget(parent) { this->setColumnCount(1); } void NotebookTree::addNotebook(Notebook& notebook) { TreeNotebookItem* treeItem = new TreeNotebookItem(notebook); if (this->notebookTrees.find(&notebook) == this->notebookTrees.end()) { this->notebookTrees[&notebook] = treeItem; this->addTopLevelItem(treeItem); } else { delete treeItem; throw NotebookException("Cannot add a notebook multiple times to the tree"); } } void NotebookTree::selectPage(Notebook* notebook, NotebookPage* page) { auto notebookTreeIter = this->notebookTrees.find(notebook); if (notebookTreeIter == this->notebookTrees.end()) throw NotebookException("Could not find tree node for the page to select"); TreeNotebookItem* notebookTree = *notebookTreeIter; QTreeWidgetItem* sectionTree = 0; TreeNotebookPageItem* pageNode = 0; notebookTree->getPathToPage(page, sectionTree, pageNode); if (!sectionTree) throw NotebookException("Result from getPathToPage; sectionTree is null"); if (!pageNode) throw NotebookException("Result from getPathToPage; pageNode is null"); notebookTree->setExpanded(true); sectionTree->setExpanded(true); pageNode->setSelected(true); }
#include "notebooktree.h" #include "treenotebookitem.h" #include "treenotebookpageitem.h" #include "notebookexception.h" #include <QHeaderView> NotebookTree::NotebookTree(QWidget* parent) : QTreeWidget(parent) { this->setColumnCount(1); this->header()->hide(); } void NotebookTree::addNotebook(Notebook& notebook) { TreeNotebookItem* treeItem = new TreeNotebookItem(notebook); if (this->notebookTrees.find(&notebook) == this->notebookTrees.end()) { this->notebookTrees[&notebook] = treeItem; this->addTopLevelItem(treeItem); } else { delete treeItem; throw NotebookException("Cannot add a notebook multiple times to the tree"); } } void NotebookTree::selectPage(Notebook* notebook, NotebookPage* page) { auto notebookTreeIter = this->notebookTrees.find(notebook); if (notebookTreeIter == this->notebookTrees.end()) throw NotebookException("Could not find tree node for the page to select"); TreeNotebookItem* notebookTree = *notebookTreeIter; QTreeWidgetItem* sectionTree = 0; TreeNotebookPageItem* pageNode = 0; notebookTree->getPathToPage(page, sectionTree, pageNode); if (!sectionTree) throw NotebookException("Result from getPathToPage; sectionTree is null"); if (!pageNode) throw NotebookException("Result from getPathToPage; pageNode is null"); notebookTree->setExpanded(true); sectionTree->setExpanded(true); pageNode->setSelected(true); }
Fix bug in name demangling.
// Copyright (c) 2015 Andrew Sutton // All rights reserved #include "lingo/utility.hpp" #include <cstdlib> #include <cxxabi.h> namespace lingo { String type_str(std::type_info const& t) { std::size_t n = 0; char* buf = abi::__cxa_demangle(t.name(), nullptr, &n, 0); String result(buf, n); std::free(buf); return result; } } // namespace lingo
// Copyright (c) 2015 Andrew Sutton // All rights reserved #include "lingo/utility.hpp" #include <cstdlib> #include <cxxabi.h> #include <iostream> namespace lingo { String type_str(std::type_info const& t) { std::size_t n = 0; char* buf = abi::__cxa_demangle(t.name(), nullptr, &n, 0); String result(buf); std::free(buf); return result; } } // namespace lingo
Return !0 when qt tests fail.
#include <QTest> #include <QObject> #include "uritests.h" // This is all you need to run all the tests int main(int argc, char *argv[]) { URITests test1; QTest::qExec(&test1); }
#include <QTest> #include <QObject> #include "uritests.h" // This is all you need to run all the tests int main(int argc, char *argv[]) { bool fInvalid = false; URITests test1; if (QTest::qExec(&test1) != 0) fInvalid = true; return fInvalid; }
Make sure skin has OSD before initializing it
#include "EjectOSD.h" #include <Dbt.h> #include "..\Monitor.h" #include "..\Skin.h" EjectOSD::EjectOSD() : OSD(L"3RVX-EjectDispatcher") { _mWnd = new MeterWnd(L"3RVX-EjectOSD", L"3RVX-EjectOSD"); Skin *skin = _settings.CurrentSkin(); Gdiplus::Bitmap *bg = skin->OSDBgImg("eject"); _mWnd->BackgroundImage(bg); _mWnd->Update(); _mWnd->VisibleDuration(800); HMONITOR monitor = Monitor::Default(); const int mWidth = Monitor::Width(monitor); const int mHeight = Monitor::Height(monitor); _mWnd->X(mWidth / 2 - _mWnd->Width() / 2); _mWnd->Y(mHeight - _mWnd->Height() - 140); } void EjectOSD::Hide() { _mWnd->Hide(false); } LRESULT EjectOSD::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { if (message == WM_DEVICECHANGE) { if (wParam == DBT_DEVICEREMOVECOMPLETE) { CLOG(L"Device removal notification received"); HideOthers(Eject); _mWnd->Show(); } } return DefWindowProc(hWnd, message, wParam, lParam); }
#include "EjectOSD.h" #include <Dbt.h> #include "..\Monitor.h" #include "..\Skin.h" EjectOSD::EjectOSD() : OSD(L"3RVX-EjectDispatcher") { _mWnd = new MeterWnd(L"3RVX-EjectOSD", L"3RVX-EjectOSD"); Skin *skin = _settings.CurrentSkin(); if (skin->HasOSD("eject") == false) { return; } Gdiplus::Bitmap *bg = skin->OSDBgImg("eject"); _mWnd->BackgroundImage(bg); _mWnd->Update(); _mWnd->VisibleDuration(800); HMONITOR monitor = Monitor::Default(); const int mWidth = Monitor::Width(monitor); const int mHeight = Monitor::Height(monitor); _mWnd->X(mWidth / 2 - _mWnd->Width() / 2); _mWnd->Y(mHeight - _mWnd->Height() - 140); } void EjectOSD::Hide() { _mWnd->Hide(false); } LRESULT EjectOSD::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { if (message == WM_DEVICECHANGE) { if (wParam == DBT_DEVICEREMOVECOMPLETE) { CLOG(L"Device removal notification received"); HideOthers(Eject); _mWnd->Show(); } } return DefWindowProc(hWnd, message, wParam, lParam); }
Fix build error, forgot to replace a "slots" to "Q_SLOTS"
#include <QtCore/QCoreApplication> #include <QtCore/QDebug> #include <QtCore/QTimer> #include <QtDBus/QtDBus> #include <QtTest/QtTest> #include <tests/lib/test.h> class TestDoNothing : public Test { Q_OBJECT public: TestDoNothing(QObject *parent = 0) : Test(parent) { } private slots: void initTestCase(); void init(); void doNothing(); void doNothing2(); void cleanup(); void cleanupTestCase(); }; void TestDoNothing::initTestCase() { initTestCaseImpl(); } void TestDoNothing::init() { initImpl(); } void TestDoNothing::doNothing() { QTimer::singleShot(0, mLoop, SLOT(quit())); QCOMPARE(mLoop->exec(), 0); } void TestDoNothing::doNothing2() { QTimer::singleShot(0, mLoop, SLOT(quit())); QCOMPARE(mLoop->exec(), 0); } void TestDoNothing::cleanup() { cleanupImpl(); } void TestDoNothing::cleanupTestCase() { cleanupTestCaseImpl(); } QTEST_MAIN(TestDoNothing) #include "_gen/do-nothing.cpp.moc.hpp"
#include <QtCore/QCoreApplication> #include <QtCore/QDebug> #include <QtCore/QTimer> #include <QtDBus/QtDBus> #include <QtTest/QtTest> #include <tests/lib/test.h> class TestDoNothing : public Test { Q_OBJECT public: TestDoNothing(QObject *parent = 0) : Test(parent) { } private Q_SLOTS: void initTestCase(); void init(); void doNothing(); void doNothing2(); void cleanup(); void cleanupTestCase(); }; void TestDoNothing::initTestCase() { initTestCaseImpl(); } void TestDoNothing::init() { initImpl(); } void TestDoNothing::doNothing() { QTimer::singleShot(0, mLoop, SLOT(quit())); QCOMPARE(mLoop->exec(), 0); } void TestDoNothing::doNothing2() { QTimer::singleShot(0, mLoop, SLOT(quit())); QCOMPARE(mLoop->exec(), 0); } void TestDoNothing::cleanup() { cleanupImpl(); } void TestDoNothing::cleanupTestCase() { cleanupTestCaseImpl(); } QTEST_MAIN(TestDoNothing) #include "_gen/do-nothing.cpp.moc.hpp"
Use a different define to decide which CRC library to use.
// 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. // Calculate Crc by calling CRC method in LZMA SDK #include "courgette/crc.h" extern "C" { #include "third_party/lzma_sdk/7zCrc.h" } namespace courgette { uint32 CalculateCrc(const uint8* buffer, size_t size) { CrcGenerateTable(); uint32 crc = 0xffffffffL; crc = ~CrcCalc(buffer, size); return crc; } } // namespace
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "courgette/crc.h" #ifdef COURGETTE_USE_CRC_LIB # include "zlib.h" #else extern "C" { # include "third_party/lzma_sdk/7zCrc.h" } #endif #include "base/basictypes.h" namespace courgette { uint32 CalculateCrc(const uint8* buffer, size_t size) { uint32 crc; #ifdef COURGETTE_USE_CRC_LIB // Calculate Crc by calling CRC method in zlib crc = crc32(0, buffer, size); #else // Calculate Crc by calling CRC method in LZMA SDK CrcGenerateTable(); crc = CrcCalc(buffer, size); #endif return ~crc; } } // namespace
Remove debugging aids from this test and fix its expectations.
// RUN: rm -rf %t // RUN: %clang_cc1 -fsyntax-only -verify %s -fmodules -fmodules-cache-path=%t -I%S/Inputs/PR28438 -fimplicit-module-maps #include "a.h" #include "b2.h" #pragma clang __debug macro FOO FOO // xpected-no-diagnostics
// RUN: rm -rf %t // RUN: %clang_cc1 -fsyntax-only -verify %s -fmodules -fmodules-cache-path=%t -I%S/Inputs/PR28438 -fimplicit-module-maps #include "a.h" #include "b2.h" FOO // expected-no-diagnostics
Fix class name for SinogramCreatorMC
/** * @copyright Copyright 2017 The J-PET Framework 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 find a copy of the License in the LICENCE file. * * 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. * * @file main.cpp */ #include "JPetManager/JPetManager.h" #include "ImageReco.h" #include "SinogramCreator.h" #include "SinogramCreatorMC.h" using namespace std; int main(int argc, const char* argv[]) { JPetManager& manager = JPetManager::getManager(); manager.registerTask<ImageReco>("ImageReco"); manager.registerTask<SinogramCreator>("SinogramCreator"); manager.registerTask<SinogramCreator>("SinogramCreatorMC"); manager.useTask("ImageReco", "unk.evt", "reco"); manager.useTask("SinogramCreator", "unk.evt", "sino"); manager.useTask("SinogramCreatorMC", "unk.evt", "sino"); manager.run(argc, argv); }
/** * @copyright Copyright 2017 The J-PET Framework 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 find a copy of the License in the LICENCE file. * * 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. * * @file main.cpp */ #include "JPetManager/JPetManager.h" #include "ImageReco.h" #include "SinogramCreator.h" #include "SinogramCreatorMC.h" using namespace std; int main(int argc, const char* argv[]) { JPetManager& manager = JPetManager::getManager(); manager.registerTask<ImageReco>("ImageReco"); manager.registerTask<SinogramCreator>("SinogramCreator"); manager.registerTask<SinogramCreatorMC>("SinogramCreatorMC"); manager.useTask("ImageReco", "unk.evt", "reco"); manager.useTask("SinogramCreator", "unk.evt", "sino"); manager.useTask("SinogramCreatorMC", "unk.evt", "sino.mc"); manager.run(argc, argv); }
Enable the new dialog style by default; etc.
// Copyright (c) 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 "ui/base/ui_base_switches_util.h" #include "base/command_line.h" #include "ui/base/ui_base_switches.h" namespace switches { bool IsTouchDragDropEnabled() { return CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableTouchDragDrop); } bool IsTouchEditingEnabled() { return CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableTouchEditing); } bool IsNewDialogStyleEnabled() { CommandLine* command_line = CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kDisableNewDialogStyle)) return false; if (command_line->HasSwitch(switches::kEnableNewDialogStyle)) return true; return false; } } // namespace switches
// Copyright (c) 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 "ui/base/ui_base_switches_util.h" #include "base/command_line.h" #include "ui/base/ui_base_switches.h" namespace switches { bool IsTouchDragDropEnabled() { return CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableTouchDragDrop); } bool IsTouchEditingEnabled() { return CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableTouchEditing); } bool IsNewDialogStyleEnabled() { CommandLine* command_line = CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kDisableNewDialogStyle)) return false; if (command_line->HasSwitch(switches::kEnableNewDialogStyle)) return true; return true; } } // namespace switches
Disable shared memory test for OpenCL until bugginess is resolved.
#include <stdio.h> #include <Halide.h> using namespace Halide; int main(int argc, char **argv) { Var x, y; Var xo, xi, yo, yi; Func f, g; printf("Defining function...\n"); f(x, y) = cast<float>(x); g(x, y) = f(x+1, y) + f(x-1, y); Target target = get_jit_target_from_environment(); if (target.has_gpu_feature()) { Var xi, yi; g.gpu_tile(x, y, 8, 8, GPU_DEFAULT); f.compute_at(g, Var("blockidx")).gpu_threads(x, y, GPU_DEFAULT); } printf("Realizing function...\n"); Image<float> im = g.realize(32, 32, target); for (int i = 0; i < 32; i++) { for (int j = 0; j < 32; j++) { if (im(i,j) != 2*i) { printf("im[%d, %d] = %f\n", i, j, im(i,j)); return -1; } } } printf("Success!\n"); return 0; }
#include <stdio.h> #include <Halide.h> using namespace Halide; int main(int argc, char **argv) { Var x, y; Var xo, xi, yo, yi; Func f, g; printf("Defining function...\n"); f(x, y) = cast<float>(x); g(x, y) = f(x+1, y) + f(x-1, y); Target target = get_jit_target_from_environment(); // shared memory not currently working in OpenCL if (target.features & Target::CUDA) { Var xi, yi; g.gpu_tile(x, y, 8, 8, GPU_CUDA); f.compute_at(g, Var("blockidx")).gpu_threads(x, y, GPU_CUDA); } printf("Realizing function...\n"); Image<float> im = g.realize(32, 32, target); for (int i = 0; i < 32; i++) { for (int j = 0; j < 32; j++) { if (im(i,j) != 2*i) { printf("im[%d, %d] = %f\n", i, j, im(i,j)); return -1; } } } printf("Success!\n"); return 0; }
Use strerror_r instead of strerror_s for GCC/Linux
#include "Precompiled.hpp" #include "Error.hpp" #include "SmartPtr.hpp" #include "String.hpp" std::string errno_string(int err) { char buffer[1024]; if (!strerror_s(buffer, sizeof(buffer), err)) throw std::runtime_error("strerror_s failed"); return buffer; } #ifdef _WIN32 std::string win_error_string(int err) { std::unique_ptr<wchar_t[], LocalFreeDeleter> buffer; FormatMessageW( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)(wchar_t**)unique_out_ptr(buffer), 0, nullptr); return utf16_to_utf8(buffer.get()); } #endif
#include "Precompiled.hpp" #include "Error.hpp" #include "SmartPtr.hpp" #include "String.hpp" std::string errno_string(int err) { char buffer[1024]; #ifdef _WIN32 if (!strerror_s(buffer, sizeof(buffer), err)) throw std::runtime_error("strerror_s failed"); return buffer; #else return strerror_r(err, buffer, sizeof(buffer)); #endif } #ifdef _WIN32 std::string win_error_string(int err) { std::unique_ptr<wchar_t[], LocalFreeDeleter> buffer; FormatMessageW( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)(wchar_t**)unique_out_ptr(buffer), 0, nullptr); return utf16_to_utf8(buffer.get()); } #endif
Add an item per port of each selected node
#include "properties.h" #include <QHeaderView> Properties::Properties(QWidget* parent) : QTreeWidget(parent) { setRootIsDecorated(false); headerItem()->setText(0, "item"); headerItem()->setText(1, "value"); headerItem()->setFirstColumnSpanned(false); header()->setStretchLastSection(true); } void Properties::show(const std::vector<std::reference_wrapper<dependency_graph::Node>>& selection) { clear(); for(auto& node : selection) { // create a top level item for each node QTreeWidgetItem* nodeItem = new QTreeWidgetItem(); nodeItem->setText(0, node.get().name().c_str()); addTopLevelItem(nodeItem); } }
#include "properties.h" #include <QHeaderView> Properties::Properties(QWidget* parent) : QTreeWidget(parent) { setRootIsDecorated(false); headerItem()->setText(0, "item"); headerItem()->setText(1, "value"); headerItem()->setFirstColumnSpanned(false); header()->setStretchLastSection(true); } void Properties::show(const std::vector<std::reference_wrapper<dependency_graph::Node>>& selection) { clear(); for(const auto& node : selection) { // create a top level item for each node QTreeWidgetItem* nodeItem = new QTreeWidgetItem(); nodeItem->setText(0, node.get().name().c_str()); addTopLevelItem(nodeItem); // add each port as a subitem for(unsigned pi = 0; pi != node.get().portCount(); ++pi) { const auto& port = node.get().port(pi); QTreeWidgetItem* portItem = new QTreeWidgetItem(); portItem->setText(0, port.name().c_str()); nodeItem->addChild(portItem); } } expandAll(); }
Fix include, add namespace and copyright
#include <openssl/eng_ossl.h> /** * Look for an OpenSSL-suported stream cipher (ARC4) */ StreamCipher* OpenSSL_Engine::find_stream_cipher(const std::string& algo_spec) const { SCAN_Name request(algo_spec); if(request.algo_name() == "ARC4") return new ARC4_OpenSSL(request.argument_as_u32bit(0, 0)); if(request.algo_name() == "RC4_drop") return new ARC4_OpenSSL(768); return 0; }
/** OpenSSL Engine (C) 2008 Jack Lloyd */ #include <botan/eng_ossl.h> namespace Botan { /** * Look for an OpenSSL-suported stream cipher (ARC4) */ StreamCipher* OpenSSL_Engine::find_stream_cipher(const std::string& algo_spec) const { SCAN_Name request(algo_spec); if(request.algo_name() == "ARC4") return new ARC4_OpenSSL(request.argument_as_u32bit(0, 0)); if(request.algo_name() == "RC4_drop") return new ARC4_OpenSSL(768); return 0; } }
Enhance debug info namespace test to check for context/scope reference
// RUN: %clang -g -S -emit-llvm %s -o - | FileCheck %s namespace A { int i; } // CHECK: [[FILE:![0-9]*]] = {{.*}} ; [ DW_TAG_file_type ] [{{.*}}/test/CodeGenCXX/debug-info-namespace.cpp] // CHECK: [[VAR:![0-9]*]] = {{.*}}, metadata [[NS:![0-9]*]], metadata !"i", {{.*}} ; [ DW_TAG_variable ] [i] // CHECK: [[NS]] = {{.*}}, metadata [[FILE]], {{.*}} ; [ DW_TAG_namespace ] [A] [line 3]
// RUN: %clang -g -S -emit-llvm %s -o - | FileCheck %s namespace A { #line 1 "foo.cpp" namespace B { int i; } } // CHECK: [[FILE:![0-9]*]] = {{.*}} ; [ DW_TAG_file_type ] [{{.*}}/test/CodeGenCXX/debug-info-namespace.cpp] // CHECK: [[VAR:![0-9]*]] = {{.*}}, metadata [[NS:![0-9]*]], metadata !"i", {{.*}} ; [ DW_TAG_variable ] [i] // CHECK: [[NS]] = {{.*}}, metadata [[FILE2:![0-9]*]], metadata [[CTXT:![0-9]*]], {{.*}} ; [ DW_TAG_namespace ] [B] [line 1] // CHECK: [[FILE2:![0-9]*]] = {{.*}} ; [ DW_TAG_file_type ] [{{.*}}foo.cpp] // CHECK: [[CTXT]] = {{.*}}, metadata [[FILE]], null, {{.*}} ; [ DW_TAG_namespace ] [A] [line 3]
Fix the native part of Util.OpenUrl
#include <ctime> class util { public: int static GetTimestamp() { return std::time(0); } void static OpenUrl(String url) { system("open " + url); } };
#include <ctime> class util { public: int static GetTimestamp() { return std::time(0); } void static OpenUrl(const String url) { String cmd("open "); cmd += url; system(cmd.ToCString<char>()); } };
Use uint32_t as return type.
#include "main.h" #include "EventHandler.h" #include "PythonModule.h" extern "C" EXPORT unsigned int VcmpPluginInit(PluginFuncs* pluginFunctions, PluginCallbacks* pluginCallbacks, PluginInfo* pluginInfo) { pluginInfo->pluginVersion = 0x103; pluginInfo->apiMajorVersion = PLUGIN_API_MAJOR; pluginInfo->apiMinorVersion = PLUGIN_API_MINOR; strcpy(pluginInfo->name, "vcmp-python-plugin"); vcmpFunctions = pluginFunctions; if (pluginFunctions->structSize == sizeof(PluginFuncsNew)) haveNewFunctions = true; vcmpCallbacks = pluginCallbacks; if (pluginCallbacks->structSize == sizeof(PluginCallbacksNew)) haveNewCallbacks = true; RegisterCallbacks(pluginCallbacks); py::initialize_interpreter(); return 1; }
#include "main.h" #include "EventHandler.h" #include "PythonModule.h" extern "C" EXPORT uint32_t VcmpPluginInit(PluginFuncs* pluginFunctions, PluginCallbacks* pluginCallbacks, PluginInfo* pluginInfo) { pluginInfo->pluginVersion = 0x103; pluginInfo->apiMajorVersion = PLUGIN_API_MAJOR; pluginInfo->apiMinorVersion = PLUGIN_API_MINOR; strcpy(pluginInfo->name, "vcmp-python-plugin"); vcmpFunctions = pluginFunctions; if (pluginFunctions->structSize == sizeof(PluginFuncsNew)) haveNewFunctions = true; vcmpCallbacks = pluginCallbacks; if (pluginCallbacks->structSize == sizeof(PluginCallbacksNew)) haveNewCallbacks = true; RegisterCallbacks(pluginCallbacks); py::initialize_interpreter(); return 1; }
Break if task file don`t exists
#include "task_simple.h" #include "factory_simple.h" #include "on_tick_simple.h" #include <fstream> using namespace std; int main(int argc, char *argv[]) { const string task_fname = "task_list.txt"; const size_t concurrency = 2; ifstream task_stream{task_fname}; TaskListSimple task_list{task_stream, "./"}; JobList job_list; auto loop = AIO_UVW::Loop::getDefault(); auto factory = make_shared<FactorySimple>(loop); auto on_tick = make_shared< OnTickSimple<JobList> >(job_list, factory, task_list); factory->set_OnTick(on_tick); for (size_t i = 1; i <= concurrency; i++) { auto task = task_list.get(); if (!task) break; auto downloader = factory->create(*task); if (!downloader) continue; job_list.emplace_back(task, downloader); } loop->run(); return 0; }
#include "task_simple.h" #include "factory_simple.h" #include "on_tick_simple.h" #include <fstream> #include <iostream> using namespace std; int main(int argc, char *argv[]) { const string task_fname = "task_list.txt"; const size_t concurrency = 2; ifstream task_stream{task_fname}; if ( !task_stream.is_open() ) { cout << "Can`t open <" << task_fname << ">, break." << endl; return 1; } TaskListSimple task_list{task_stream, "./"}; JobList job_list; auto loop = AIO_UVW::Loop::getDefault(); auto factory = make_shared<FactorySimple>(loop); auto on_tick = make_shared< OnTickSimple<JobList> >(job_list, factory, task_list); factory->set_OnTick(on_tick); for (size_t i = 1; i <= concurrency; i++) { auto task = task_list.get(); if (!task) break; auto downloader = factory->create(*task); if (!downloader) continue; job_list.emplace_back(task, downloader); } loop->run(); return 0; }
Change return value to EXIT_SUCCESS
// // main.cpp // // Created on: 17 Mar 2015 // Author: Guotai Wang // // Copyright (c) 2014-2016 University College London, United Kingdom. All rights reserved. // http://cmictig.cs.ucl.ac.uk // // Distributed under the BSD-3 licence. Please see the file licence.txt // #include <fstream> #include <iostream> #include "Test/RFTestExample.h" int main(int argc, char ** argv) { srand (time(NULL)); RFTestExample testExample; if(testExample.LoadData(BIODEG)) //DataSetName: BIODEG, MUSK, CTG, WINE { testExample.SetTrainDataChunk(0.5,1.0, 0.05); testExample.Run(100); testExample.PrintPerformance(); } return 0; }
// // main.cpp // // Created on: 17 Mar 2015 // Author: Guotai Wang // // Copyright (c) 2014-2016 University College London, United Kingdom. All rights reserved. // http://cmictig.cs.ucl.ac.uk // // Distributed under the BSD-3 licence. Please see the file licence.txt // #include <fstream> #include <iostream> #include "Test/RFTestExample.h" int main(int argc, char ** argv) { srand (time(NULL)); RFTestExample testExample; if(testExample.LoadData(BIODEG)) //DataSetName: BIODEG, MUSK, CTG, WINE { testExample.SetTrainDataChunk(0.5,1.0, 0.05); testExample.Run(100); testExample.PrintPerformance(); } return EXIT_SUCCESS; }
Use preprocessor 'defined' instead of relying on the preprocessor doing this automatically.
//---------------------------- job_identifier.cc --------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 1998, 1999, 2000, 2001, 2002 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 (HAVE_GETHOSTNAME && (!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(" "); #endif id += std::string(std::ctime(&t)); } const std::string JobIdentifier::operator ()() const { return id; }
Make sure to convert path to utf8 for json output of folder name.
/* Copyright: © 2018 SIL International. Description: Internal keyboard class and adaptor class for the API. Create Date: 2 Oct 2018 Authors: Tim Eves (TSE) History: 7 Oct 2018 - TSE - Refactored out of km_kbp_keyboard_api.cpp */ #include "keyboard.hpp" #include "json.hpp" using namespace km::kbp; keyboard::keyboard(std::filesystem::path const & path) : _keyboard_id(path.stem().string()), _version_string("3.145"), _folder_path(path.parent_path()), _default_opts {KM_KBP_OPTIONS_END} { version_string = _version_string.c_str(); id = _keyboard_id.c_str(); folder_path = _folder_path.native().c_str(); default_options = _default_opts.data(); } json & km::kbp::operator << (json & j, km::kbp::keyboard const & kb) { j << json::object << "id" << kb.id << "folder" << kb.folder_path << "version" << kb.version_string << "rules" << json::array << json::close; return j << json::close; }
/* Copyright: © 2018 SIL International. Description: Internal keyboard class and adaptor class for the API. Create Date: 2 Oct 2018 Authors: Tim Eves (TSE) History: 7 Oct 2018 - TSE - Refactored out of km_kbp_keyboard_api.cpp */ #include "keyboard.hpp" #include "json.hpp" using namespace km::kbp; keyboard::keyboard(std::filesystem::path const & path) : _keyboard_id(path.stem().string()), _version_string("3.145"), _folder_path(path.parent_path()), _default_opts {KM_KBP_OPTIONS_END} { version_string = _version_string.c_str(); id = _keyboard_id.c_str(); folder_path = _folder_path.native().c_str(); default_options = _default_opts.data(); } json & km::kbp::operator << (json & j, km::kbp::keyboard const & kb) { j << json::object << "id" << kb.id << "folder" << kb._folder_path.string() << "version" << kb.version_string << "rules" << json::array << json::close; return j << json::close; }
Add timestamp field to agent logs
#include <iostream> #include <boost/log/common.hpp> #include <boost/log/expressions.hpp> #include <boost/log/utility/setup/file.hpp> #include <boost/log/trivial.hpp> #ifdef HAVE_CONFIG_H #include "config.h" #endif namespace expr = boost::log::expressions; namespace keywords = boost::log::keywords; int main(int argc, char *argv[]) { try { boost::log::add_file_log( keywords::file_name = LOGDIR "/agent.log", keywords::format = ( expr::stream << "<" << boost::log::trivial::severity << ">\t" << expr::smessage ), keywords::auto_flush = true ); BOOST_LOG_TRIVIAL(info) << "Agent - HelloWorld"; #ifdef HAVE_CONFIG_H BOOST_LOG_TRIVIAL(info) << "Version: " << VERSION; #endif } catch (std::exception &ex) { std::cerr << ex.what() << '\n'; BOOST_LOG_TRIVIAL(fatal) << ex.what(); return 1; } return 0; }
#include <iostream> #include <boost/date_time/posix_time/posix_time_types.hpp> #include <boost/log/common.hpp> #include <boost/log/expressions.hpp> #include <boost/log/utility/setup/file.hpp> #include <boost/log/trivial.hpp> #include <boost/log/support/date_time.hpp> #include <boost/log/utility/setup/common_attributes.hpp> #ifdef HAVE_CONFIG_H #include "config.h" #endif namespace expr = boost::log::expressions; namespace keywords = boost::log::keywords; int main(int argc, char *argv[]) { try { boost::log::add_common_attributes(); boost::log::add_file_log( keywords::file_name = LOGDIR "/agent.log", keywords::format = ( expr::stream << expr::format_date_time< boost::posix_time::ptime >("TimeStamp", "%d.%m.%Y %H:%M:%S") << ": <" << boost::log::trivial::severity << ">\t" << expr::smessage ), keywords::auto_flush = true ); BOOST_LOG_TRIVIAL(info) << "Agent - HelloWorld"; #ifdef HAVE_CONFIG_H BOOST_LOG_TRIVIAL(info) << "Version: " << VERSION; #endif } catch (std::exception &ex) { std::cerr << ex.what() << '\n'; BOOST_LOG_TRIVIAL(fatal) << ex.what(); return 1; } return 0; }
Add NODE_ADDRESS value to slave_node program
/*----------------------------------------*/ // Test receiving messages from master // // This receives a message from master (command 0x01), // which tells it to turn an LED on or off. // /*----------------------------------------*/ #include <stdint.h> #include "MultidropSlave.h" #include "MultidropDataUart.h" #define NODE_COUNT 5 int main() { uint8_t ledOn = 0; // LED on PB0 DDRB |= (1 << PB0); PORTB &= ~(1 << PB0); MultidropDataUart serial; serial.begin(9600); MultidropSlave slave(&serial); slave.setAddress(1); while(1) { slave.read(); if (slave.isReady() && slave.isAddressedToMe() && slave.getCommand() == 0x01) { ledOn = slave.getData()[0]; if (ledOn) { PORTB |= (1 << PB0); } else { PORTB &= ~(1 << PB0); } slave.reset(); } } }
/*----------------------------------------*/ // Test receiving messages from master // // This receives a message from master (command 0x01), // which tells it to turn an LED on or off. // /*----------------------------------------*/ #include <stdint.h> #include "MultidropSlave.h" #include "MultidropDataUart.h" #define NODE_ADDRESS 1 int main() { uint8_t ledOn = 0; // LED on PB0 DDRB |= (1 << PB0); PORTB &= ~(1 << PB0); MultidropDataUart serial; serial.begin(9600); MultidropSlave slave(&serial); slave.setAddress(NODE_ADDRESS); while(1) { slave.read(); if (slave.isReady() && slave.isAddressedToMe() && slave.getCommand() == 0x01) { ledOn = slave.getData()[0]; if (ledOn) { PORTB |= (1 << PB0); } else { PORTB &= ~(1 << PB0); } slave.reset(); } } }
Fix for generation of QR code when google analytics referrer token is unset. Buddy: Jonty
// Copyright eeGeo Ltd (2012-2015), All Rights Reserved #include "WatermarkDataFactory.h" namespace ExampleApp { namespace Watermark { namespace View { WatermarkDataFactory::WatermarkDataFactory(const std::string& appName, const std::string& googleAnalyticsReferrerToken) : m_appName(appName) , m_googleAnalyticsReferrerToken(googleAnalyticsReferrerToken) { } WatermarkData WatermarkDataFactory::Create(const std::string& imageAssetUrl, const std::string& popupTitle, const std::string& popupBody, const std::string& webUrl, const bool shouldShowShadow) { return WatermarkData(imageAssetUrl, popupTitle, popupBody, webUrl, shouldShowShadow); } WatermarkData WatermarkDataFactory::CreateDefaultEegeo() { std::string imageAssetName = "eegeo_logo"; std::string popupTitle = "Maps by WRLD"; std::string popupBody = "This app is open source. It's built using the WRLD maps SDK, a cross platform API for building engaging, customizable apps."; std::string webUrl = "http://wrld3d.com/?utm_source=" + m_googleAnalyticsReferrerToken + "&utm_medium=referral&utm_campaign=eegeo"; return Create(imageAssetName, popupTitle, popupBody, webUrl); } } } }
// Copyright eeGeo Ltd (2012-2015), All Rights Reserved #include "WatermarkDataFactory.h" namespace ExampleApp { namespace Watermark { namespace View { WatermarkDataFactory::WatermarkDataFactory(const std::string& appName, const std::string& googleAnalyticsReferrerToken) : m_appName(appName) , m_googleAnalyticsReferrerToken(googleAnalyticsReferrerToken) { } WatermarkData WatermarkDataFactory::Create(const std::string& imageAssetUrl, const std::string& popupTitle, const std::string& popupBody, const std::string& webUrl, const bool shouldShowShadow) { return WatermarkData(imageAssetUrl, popupTitle, popupBody, webUrl, shouldShowShadow); } WatermarkData WatermarkDataFactory::CreateDefaultEegeo() { std::string imageAssetName = "eegeo_logo"; std::string popupTitle = "Maps by WRLD"; std::string popupBody = "This app is open source. It's built using the WRLD maps SDK, a cross platform API for building engaging, customizable apps."; std::string utmSource = m_googleAnalyticsReferrerToken.empty() ? "unspecified" : m_googleAnalyticsReferrerToken; std::string webUrl = "http://wrld3d.com/?utm_source=" + utmSource + "&utm_medium=referral&utm_campaign=eegeo"; return Create(imageAssetName, popupTitle, popupBody, webUrl); } } } }
Make apps/pe only run a problem once
#include <iostream> using std::cout; using std::endl; #include "problems/Factory.h" #include "util/Timer.h" using util::Timer; int main(int argc, char **argv) { auto problem = problems::Factory::create(1); Timer t; t.start(); for (int i = 0; i < 1000000; ++i) problem->solve(); t.stop(); cout << problem->answer() << endl; cout << "Time elapsed: " << t << endl; return 0; }
#include <iostream> using std::cout; using std::endl; #include "problems/Factory.h" #include "util/Timer.h" using util::Timer; int main(int argc, char **argv) { auto problem = problems::Factory::create(1); Timer t; t.start(); problem->solve(); t.stop(); cout << problem->answer() << endl; cout << "Time elapsed: " << t << endl; return 0; }
Print REPL output on std::cerr instead of cout.
#include <iostream> #include "cons.h" #include "error.h" #include "eval.h" #include "init.h" #include "load.h" #include "reader.h" #include "utils.h" namespace { class Repl { std::istream& in_; std::ostream& out_; std::string prompt_ = "mclisp> "; mclisp::Reader reader_; public: explicit Repl(std::istream& in=std::cin, std::ostream& out=std::cout): in_(in), out_(out), reader_(in_) {}; int loop(); }; int Repl::loop() { while (true) { out_ << prompt_; try { mclisp::ConsCell *exp = reader_.Read(); if (mclisp::ShouldQuit(exp)) break; mclisp::ConsCell *value = Eval(exp); out_ << *value << std::endl; } catch (mclisp::Error& e) { out_ << e.what() << std::endl; } } return 0; } } //end namespace int main() { // InitLisp must be called before the Reader object is initialized. mclisp::InitLisp(); mclisp::LoadFile("mclisp.lisp"); Repl repl; return repl.loop(); }
#include <iostream> #include "cons.h" #include "error.h" #include "eval.h" #include "init.h" #include "load.h" #include "reader.h" #include "utils.h" namespace { class Repl { std::istream& in_; std::ostream& out_; std::string prompt_ = "mclisp> "; mclisp::Reader reader_; public: explicit Repl(std::istream& in=std::cin, std::ostream& out=std::cerr): in_(in), out_(out), reader_(in_) {}; int loop(); }; int Repl::loop() { while (true) { out_ << prompt_; try { mclisp::ConsCell *exp = reader_.Read(); if (mclisp::ShouldQuit(exp)) break; mclisp::ConsCell *value = Eval(exp); out_ << *value << std::endl; } catch (mclisp::Error& e) { out_ << e.what() << std::endl; } } return 0; } } //end namespace int main() { // InitLisp must be called before the Reader object is initialized. mclisp::InitLisp(); mclisp::LoadFile("mclisp.lisp"); Repl repl; return repl.loop(); }
Use CRLF in requests instead of just LF
#include "RequestParser.h" #include <sstream> #include <vector> std::vector<std::string> ApiMock::RequestParser::projectToCollection(std::string const& request) { std::vector<std::string> fromRequest; std::string::size_type pos = 0; std::string::size_type prev = 0; while ((pos = request.find('\n', prev)) != std::string::npos) { fromRequest.push_back(request.substr(prev, pos - prev)); prev = pos + 1; } fromRequest.push_back(request.substr(prev)); return fromRequest; } ApiMock::RequestData ApiMock::RequestParser::parse(std::string const& requestBuffer) { std::vector<std::string> entireRequest = projectToCollection(requestBuffer); RequestData request; return request; }
#include "RequestParser.h" #include <sstream> #include <vector> std::vector<std::string> ApiMock::RequestParser::projectToCollection(std::string const& request) { const std::string CRLF = "\r\n"; std::vector<std::string> fromRequest; std::string::size_type pos = 0; std::string::size_type prev = 0; while ((pos = request.find(CRLF, prev)) != std::string::npos) { fromRequest.push_back(request.substr(prev, pos - prev)); prev = pos + 1; } fromRequest.push_back(request.substr(prev)); return fromRequest; } ApiMock::RequestData ApiMock::RequestParser::parse(std::string const& requestBuffer) { std::vector<std::string> entireRequest = projectToCollection(requestBuffer); RequestData request; return request; }
Address Sanitation for the win: found memory bug.
#include <iostream> #include "rapidcheck/detail/NonRandomData.h" namespace rc { RandomData::RandomData(const uint8_t *Data, size_t Size) { std::cout << Data << std::endl; // TODO: really stupid way to fill the container const size_t size64 = Size / 8; auto Data64 = reinterpret_cast<const uint64_t *>(Data); for (size_t i = 0; i < size64; i++) { m_data.push(Data64[i]); } } } // namespace rc
#include <iostream> #include "rapidcheck/detail/NonRandomData.h" namespace rc { RandomData::RandomData(const uint8_t *Data, size_t Size) { // TODO: really stupid way to fill the container const size_t size64 = Size / 8; auto Data64 = reinterpret_cast<const uint64_t *>(Data); for (size_t i = 0; i < size64; i++) { m_data.push(Data64[i]); } } } // namespace rc
Add basic thresholding of green markers
#include <iostream> using namespace std; int main() { cout << "Hello World!" << endl; return 0; }
#include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> using namespace cv; using namespace std; int main(int argc, char** argv) { VideoCapture cap(0); namedWindow("MyVideo", CV_WINDOW_AUTOSIZE); int w = cap.get(CV_CAP_PROP_FRAME_WIDTH); int h = cap.get(CV_CAP_PROP_FRAME_HEIGHT); //cap.set(CV_CAP_PROP_SETTINGS, 1); // 24 x 19 while (true) { Mat frame, frame2; cap.read(frame); Point2f src[] = {Point2f(140, 0), Point2f(520, 0), Point2f(73, 479), Point2f(586, 479)}; Point2f dst[] = {Point2f(0, 0), Point2f(640, 0), Point2f(0, 480), Point2f(640, 480)}; Mat m = getPerspectiveTransform(src, dst); warpPerspective(frame, frame2, m, cv::Size(w, h)); resize(frame2, frame, cv::Size(21 * 30, 24 * 30)); //cvtColor(frame, frame2, CV_BGR2GRAY); Mat frameParts[3]; split(frame, frameParts); inRange(frameParts[1], cv::Scalar(60), cv::Scalar(255), frame); inRange(frameParts[0], cv::Scalar(60), cv::Scalar(255), frame2); Mat result = frame & ~frame2; Mat result2; auto kernel = getStructuringElement(MORPH_RECT, cv::Size(3, 3)); erode(result, result2, kernel); auto kernel2 = getStructuringElement(MORPH_RECT, cv::Size(9, 9)); dilate(result2, result, kernel2); imshow("MyVideo", result); if (waitKey(10) == 27) { break; } } return 0; }
Improve comments in the external interrupt pin change example
#include "board.h" #include <aery32/gpio.h> #include <aery32/delay.h> #include <aery32/intc.h> using namespace aery; void isrhandler_group2(void) { gpio_toggle_pin(LED); delay_ms(100); /* Reduce glitch */ porta->ifrc = (1 << 0); /* Remember to clear the interrupt */ } int main(void) { init_board(); /* GPIO pins 0-13 can be "wired" to int group 2, see datasheet p. 42 */ gpio_init_pin(AVR32_PIN_PA00, GPIO_INPUT|GPIO_PULLUP|GPIO_INT_PIN_CHANGE); /* Init interrupt controller */ intc_init(); intc_register_isrhandler( &isrhandler_group2, /* Function pointer to the ISR handler */ 2, /* Interrupt group number */ 0 /* Priority level */ ); /* Enable interrupts globally */ intc_enable_globally(); for(;;) { /* * Now try to connect PA00 to GND and then disconnecting it * to let pull-up to set the pin state high again. The LED * should toggle between the pin change. */ } return 0; }
#include "board.h" #include <aery32/gpio.h> #include <aery32/delay.h> #include <aery32/intc.h> using namespace aery; void isrhandler_group2(void) { gpio_toggle_pin(LED); delay_ms(100); /* Reduce glitches */ porta->ifrc = (1 << 0); /* Remember to clear the interrupt */ } int main(void) { init_board(); /* GPIO pins 0-13 can be "wired" to int group 2, see datasheet p. 42 */ gpio_init_pin(AVR32_PIN_PA00, GPIO_INPUT|GPIO_PULLUP|GPIO_INT_PIN_CHANGE); /* Init interrupt controller */ intc_init(); intc_register_isrhandler( &isrhandler_group2, /* Function pointer to the ISR handler */ 2, /* Interrupt group number */ 0 /* Priority level */ ); /* Enable interrupts globally */ intc_enable_globally(); for(;;) { /* * Now try to connect PA00 to GND and then disconnecting it * to let the pull-up to set the pin state high again. The LED * should toggle on the pin change. */ } return 0; }
Add missing code that assigns new owner
// This code is based on Sabberstone project. // Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva // RosettaStone is hearthstone simulator using C++ with reinforcement learning. // Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon #include <Rosetta/Tasks/SimpleTasks/ControlTask.hpp> #include <Rosetta/Tasks/SimpleTasks/IncludeTask.hpp> namespace RosettaStone::SimpleTasks { ControlTask::ControlTask(EntityType entityType) : ITask(entityType) { // Do nothing } TaskID ControlTask::GetTaskID() const { return TaskID::CONTROL; } TaskStatus ControlTask::Impl(Player& player) { auto entities = IncludeTask::GetEntities(m_entityType, player, m_source, m_target); auto& myField = player.GetField(); auto& opField = player.opponent->GetField(); for (auto& entity : entities) { const auto minion = dynamic_cast<Minion*>(entity); if (minion == nullptr) { continue; } if (myField.IsFull()) { entity->Destroy(); continue; } const auto minionClone = new Minion(*minion); myField.AddMinion(*minionClone); opField.RemoveMinion(*minion); } return TaskStatus::COMPLETE; } } // namespace RosettaStone::SimpleTasks
// This code is based on Sabberstone project. // Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva // RosettaStone is hearthstone simulator using C++ with reinforcement learning. // Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon #include <Rosetta/Tasks/SimpleTasks/ControlTask.hpp> #include <Rosetta/Tasks/SimpleTasks/IncludeTask.hpp> namespace RosettaStone::SimpleTasks { ControlTask::ControlTask(EntityType entityType) : ITask(entityType) { // Do nothing } TaskID ControlTask::GetTaskID() const { return TaskID::CONTROL; } TaskStatus ControlTask::Impl(Player& player) { auto entities = IncludeTask::GetEntities(m_entityType, player, m_source, m_target); auto& myField = player.GetField(); auto& opField = player.opponent->GetField(); for (auto& entity : entities) { const auto minion = dynamic_cast<Minion*>(entity); if (minion == nullptr) { continue; } if (myField.IsFull()) { entity->Destroy(); continue; } const auto minionClone = new Minion(*minion); minionClone->owner = &player; myField.AddMinion(*minionClone); opField.RemoveMinion(*minion); } return TaskStatus::COMPLETE; } } // namespace RosettaStone::SimpleTasks
Print firmware name and version at boot
#include "Boot.hpp" using namespace HomieInternals; Boot::Boot(const char* name) : _name(name) { } void Boot::setup() { if (Interface::get().led.enabled) { pinMode(Interface::get().led.pin, OUTPUT); digitalWrite(Interface::get().led.pin, !Interface::get().led.on); } WiFi.persistent(true); // Persist data on SDK as it seems Wi-Fi connection is faster Interface::get().getLogger() << F("🔌 Booting into ") << _name << F(" mode 🔌") << endl; } void Boot::loop() { }
#include "Boot.hpp" using namespace HomieInternals; Boot::Boot(const char* name) : _name(name) { } void Boot::setup() { if (Interface::get().led.enabled) { pinMode(Interface::get().led.pin, OUTPUT); digitalWrite(Interface::get().led.pin, !Interface::get().led.on); } WiFi.persistent(true); // Persist data on SDK as it seems Wi-Fi connection is faster Interface::get().getLogger() << F("💡 Firmware ") << Interface::get().firmware.name << F(" (") << Interface::get().firmware.version << F(")") << endl; Interface::get().getLogger() << F("🔌 Booting into ") << _name << F(" mode 🔌") << endl; } void Boot::loop() { }
Convert Sorted Array to Binary Search Tree
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* sortedArrayToBST(vector<int>& nums) { if(nums.size()==0) return NULL; return insertnode(0,nums.size(),nums); } private: TreeNode* insertnode(int f,int r,vector<int>& nums){ cout<<f<<" "<<r<<endl; if(f==r && f!=0) return NULL; if(f==nums.size()) return NULL; if(f==r || f==r-1){ TreeNode* now=new TreeNode(nums[f]); return now; } TreeNode* now=new TreeNode(nums[(f+r)/2]); now->left=insertnode(f,(f+r)/2,nums); now->right=insertnode((f+r)/2+1,r,nums); return now; } };
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* sortedArrayToBST(vector<int>& nums) { if(nums.size()==0) return NULL; return insertnode(0,nums.size(),nums); } private: TreeNode* insertnode(int f,int r,vector<int>& nums){ cout<<f<<" "<<r<<endl; if(f==r && f!=0) return NULL; if(f==nums.size()) return NULL; if(f==r || f==r-1){ TreeNode* now=new TreeNode(nums[f]); return now; } TreeNode* now=new TreeNode(nums[(f+r)/2]); now->left=insertnode(f,(f+r)/2,nums); now->right=insertnode((f+r)/2+1,r,nums); return now; } };