Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Use a for each loop | #include "util.h"
#include <sstream>
#include <vector>
Header cpr::util::parseHeader(std::string headers) {
Header header;
std::vector<std::string> lines;
std::istringstream stream(headers);
{
std::string line;
while (std::getline(stream, line, '\n')) {
lines.push_back(line);
}
}
for (auto line = lines.begin(); line != lines.end(); ++line) {
if (line->substr(0, 5) == "HTTP/") {
header.clear();
}
if (line->length() > 0) {
auto found = line->find(":");
if (found != std::string::npos) {
auto value = line->substr(found + 2, line->length() - 1);
if (value.back() == '\r') {
value = value.substr(0, value.length() - 1);
}
header[line->substr(0, found)] = value;
}
}
}
return header;
}
std::string cpr::util::parseResponse(std::string response) {
if (!response.empty()) {
if (response.back() == '\n') {
return response.substr(0, response.length() - 1);
}
}
return response;
}
size_t cpr::util::writeFunction(void *ptr, size_t size, size_t nmemb, std::string* data) {
data->append((char*) ptr, size * nmemb);
return size * nmemb;
}
| #include "util.h"
#include <sstream>
#include <vector>
Header cpr::util::parseHeader(std::string headers) {
Header header;
std::vector<std::string> lines;
std::istringstream stream(headers);
{
std::string line;
while (std::getline(stream, line, '\n')) {
lines.push_back(line);
}
}
for (auto& line : lines) {
if (line.substr(0, 5) == "HTTP/") {
header.clear();
}
if (line.length() > 0) {
auto found = line.find(":");
if (found != std::string::npos) {
auto value = line.substr(found + 2, line.length() - 1);
if (value.back() == '\r') {
value = value.substr(0, value.length() - 1);
}
header[line.substr(0, found)] = value;
}
}
}
return header;
}
std::string cpr::util::parseResponse(std::string response) {
if (!response.empty()) {
if (response.back() == '\n') {
return response.substr(0, response.length() - 1);
}
}
return response;
}
size_t cpr::util::writeFunction(void *ptr, size_t size, size_t nmemb, std::string* data) {
data->append((char*) ptr, size * nmemb);
return size * nmemb;
}
|
Fix a compilation error on Win32 | #include "GUI.hpp"
#if __APPLE__
#import <IOKit/pwr_mgt/IOPMLib.h>
#elif _WIN32
#include <Windows.h>
#pragma comment(lib, "user32.lib")
#endif
namespace Slic3r { namespace GUI {
IOPMAssertionID assertionID;
void
disable_screensaver()
{
#if __APPLE__
CFStringRef reasonForActivity = CFSTR("Slic3r");
IOReturn success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep,
kIOPMAssertionLevelOn, reasonForActivity, &assertionID);
// ignore result: success == kIOReturnSuccess
#elif _WIN32
SetThreadExecutionState(EXECUTION_STATE.ES_DISPLAY_REQUIRED | EXECUTION_STATE.ES_CONTINUOUS);
#endif
}
void
enable_screensaver()
{
#if __APPLE__
IOReturn success = IOPMAssertionRelease(assertionID);
#elif _WIN32
SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS);
#endif
}
} }
| #include "GUI.hpp"
#if __APPLE__
#import <IOKit/pwr_mgt/IOPMLib.h>
#elif _WIN32
#include <Windows.h>
#pragma comment(lib, "user32.lib")
#endif
namespace Slic3r { namespace GUI {
#if __APPLE__
IOPMAssertionID assertionID;
#endif
void
disable_screensaver()
{
#if __APPLE__
CFStringRef reasonForActivity = CFSTR("Slic3r");
IOReturn success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep,
kIOPMAssertionLevelOn, reasonForActivity, &assertionID);
// ignore result: success == kIOReturnSuccess
#elif _WIN32
SetThreadExecutionState(EXECUTION_STATE.ES_DISPLAY_REQUIRED | EXECUTION_STATE.ES_CONTINUOUS);
#endif
}
void
enable_screensaver()
{
#if __APPLE__
IOReturn success = IOPMAssertionRelease(assertionID);
#elif _WIN32
SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS);
#endif
}
} }
|
Prepare to add archive and extract | #include "compress.hpp"
#include "decompress.hpp"
#include<iostream>
#include<fstream>
void printUsage() {
std::cout << "Give option\n";
}
const std::string COMPRESS_COMMAND = "c";
const std::string DECOMPRESS_COMMAND = "d";
int main(int argc, char** argv) {
if(argc < 2) {
printUsage();
return 1;
}
std::istream* const in = argc > 2 ? new std::ifstream(argv[2]) : &std::cin;
std::ostream* const out = argc > 3 ? new std::ofstream(argv[3]) : &std::cout;
if(argv[1] == COMPRESS_COMMAND) {
std::string data;
data.assign(std::istreambuf_iterator<char>(*in), std::istreambuf_iterator<char>());
*out << compress(data);
}
else if(argv[1] == DECOMPRESS_COMMAND) {
std::string data;
data.assign(std::istreambuf_iterator<char>(*in), std::istreambuf_iterator<char>());
*out << decompress(data);
}
else {
printUsage();
return 1;
}
}
| #include "compress.hpp"
#include "decompress.hpp"
#include<iostream>
#include<fstream>
void printUsage() {
std::cout << "Give option\n";
}
const std::string COMPRESS_COMMAND = "c";
const std::string DECOMPRESS_COMMAND = "d";
const std::string ARCHIVE_COMMAND = "a";
const std::string EXTRACT_COMMAND = "x";
int main(int argc, char** argv) {
if(argc < 2) {
printUsage();
return 1;
}
std::istream* const in = argc > 2 ? new std::ifstream(argv[2]) : &std::cin;
std::ostream* const out = argc > 3 ? new std::ofstream(argv[3]) : &std::cout;
if(argv[1] == COMPRESS_COMMAND) {
std::string data;
data.assign(std::istreambuf_iterator<char>(*in), std::istreambuf_iterator<char>());
*out << compress(data);
}
else if(argv[1] == DECOMPRESS_COMMAND) {
std::string data;
data.assign(std::istreambuf_iterator<char>(*in), std::istreambuf_iterator<char>());
*out << decompress(data);
}
else if(argv[1] == ARCHIVE_COMMAND) {
std::cerr << "Archive is not implemented\n";
return 1;
}
else if(argv[1] == EXTRACT_COMMAND) {
std::cerr << "Extract is not implemented\n";
return 1;
}
else {
printUsage();
return 1;
}
}
|
Set OpenGL ES version to 2 on Android | // Copyright (C) 2016 Elviss Strazdins
// This file is part of the Ouzel engine.
#include "WindowAndroid.h"
namespace ouzel
{
WindowAndroid::WindowAndroid(const Size2& pSize, bool pResizable, bool pFullscreen, uint32_t pSampleCount, const std::string& pTitle):
Window(pSize, pResizable, pFullscreen, pSampleCount, pTitle)
{
}
WindowAndroid::~WindowAndroid()
{
}
bool WindowAndroid::init()
{
return Window::init();
}
}
| // Copyright (C) 2016 Elviss Strazdins
// This file is part of the Ouzel engine.
#include "WindowAndroid.h"
#include "Engine.h"
#include "opengl/RendererOGL.h"
namespace ouzel
{
WindowAndroid::WindowAndroid(const Size2& pSize, bool pResizable, bool pFullscreen, uint32_t pSampleCount, const std::string& pTitle):
Window(pSize, pResizable, pFullscreen, pSampleCount, pTitle)
{
}
WindowAndroid::~WindowAndroid()
{
}
bool WindowAndroid::init()
{
std::shared_ptr<graphics::RendererOGL> rendererOGL = std::static_pointer_cast<graphics::RendererOGL>(sharedEngine->getRenderer());
rendererOGL->setAPIVersion(2);
return Window::init();
}
}
|
Add support for halo's to TextSymbolizer(). | /* This file is part of python_mapnik (c++/python mapping toolkit)
* Copyright (C) 2005 Artem Pavlenko, Jean-Francois Doyon
*
* Mapnik 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 2
* of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
//$Id$
#include <boost/python.hpp>
#include <mapnik.hpp>
using mapnik::text_symbolizer;
using mapnik::Color;
void export_text_symbolizer()
{
using namespace boost::python;
class_<text_symbolizer>("TextSymbolizer",
init<std::string const&,unsigned,Color const&>("TODO"))
;
}
| /* This file is part of python_mapnik (c++/python mapping toolkit)
* Copyright (C) 2005 Artem Pavlenko, Jean-Francois Doyon
*
* Mapnik 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 2
* of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
//$Id$
#include <boost/python.hpp>
#include <mapnik.hpp>
using mapnik::text_symbolizer;
using mapnik::Color;
void export_text_symbolizer()
{
using namespace boost::python;
class_<text_symbolizer>("TextSymbolizer",
init<std::string const&,unsigned,Color const&>())
.add_property("halo_fill",make_function(
&text_symbolizer::get_halo_fill,return_value_policy<copy_const_reference>()),
&text_symbolizer::set_halo_fill)
.add_property("halo_radius",&text_symbolizer::get_halo_radius, &text_symbolizer::set_halo_radius)
;
}
|
Test to see if AppVeyor styles work when not explicitly set | #include "mainwindow.h"
#include <QApplication>
#include <QStyleFactory> // TODO
int main(int argc, char *argv[])
{
using namespace HedgeEdit;
QApplication a(argc, argv);
QApplication::setStyle(QStyleFactory::create("WindowsVista"));
UI::MainWindow w;
w.show();
return a.exec();
}
| #include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
using namespace HedgeEdit;
QApplication a(argc, argv);
UI::MainWindow w;
w.show();
return a.exec();
}
|
Use correct header and namespace for isfinite | #include "CalculatorBase.h"
#include <algorithm>
#include <numeric>
#include "common.h"
namespace tilegen
{
namespace alpha
{
CalculatorBase::CalculatorBase():
mAlphas((int)CORNERS)
{
zeroAlphas();
}
void CalculatorBase::zeroAlphas()
{
for (auto& alpha : mAlphas)
alpha = 0;
}
sf::Uint8 & CalculatorBase::getAlpha(size_t index)
{
return mAlphas[index];
}
const CalculatorBase::Alphas & CalculatorBase::getAlphas() const
{
return mAlphas;
}
void CalculatorBase::updateAlphas(const Weights & weights)
{
zeroAlphas();
for (double weight : weights)
{
if(!isfinite(weight))
return;
}
updateAlphasAux(weights);
}
} // namespace alpha
} // namespace tilegen
| #include "CalculatorBase.h"
#include <algorithm>
#include <cmath>
#include "common.h"
namespace tilegen
{
namespace alpha
{
CalculatorBase::CalculatorBase():
mAlphas((int)CORNERS)
{
zeroAlphas();
}
void CalculatorBase::zeroAlphas()
{
for (auto& alpha : mAlphas)
alpha = 0;
}
sf::Uint8 & CalculatorBase::getAlpha(size_t index)
{
return mAlphas[index];
}
const CalculatorBase::Alphas & CalculatorBase::getAlphas() const
{
return mAlphas;
}
void CalculatorBase::updateAlphas(const Weights & weights)
{
zeroAlphas();
for (double weight : weights)
{
if(!std::isfinite(weight))
return;
}
updateAlphasAux(weights);
}
} // namespace alpha
} // namespace tilegen
|
Fix linux cooked header ether type | #include <netinet/ether.h>
#include <netinet/ip.h>
#include "sll.h"
#include "IPv4Processor.h"
#include "LinuxCookedProcessor.h"
void LinuxCookedProcessor::process(const struct pcap_pkthdr *pkthdr, const u_char *packet, const vector<NetData> &netData) {
struct ip* ipHeader;
struct ether_header* etherHeader = (struct ether_header*)packet;
int etherType = ntohs(etherHeader->ether_type);
switch (etherType) {
case ETHERTYPE_IP:
ipHeader = (struct ip*)(packet + SLL_HDR_LEN);
IPv4Processor().process(ipHeader, pkthdr, netData);
break;
default:
break;
}
}
| #include <netinet/ether.h>
#include <netinet/ip.h>
#include "sll.h"
#include "IPv4Processor.h"
#include "LinuxCookedProcessor.h"
void LinuxCookedProcessor::process(const struct pcap_pkthdr *pkthdr, const u_char *packet, const vector<NetData> &netData) {
struct ip* ipHeader;
struct sll_header* linuxCookedHeader = (struct sll_header*)packet;
int etherType = ntohs(linuxCookedHeader->sll_protocol);
switch (etherType) {
case ETHERTYPE_IP:
ipHeader = (struct ip*)(packet + SLL_HDR_LEN);
IPv4Processor().process(ipHeader, pkthdr, netData);
break;
default:
break;
}
}
|
Fix invalid write in RenderViewHostObserver. | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/render_view_host_observer.h"
#include "content/browser/renderer_host/render_view_host.h"
RenderViewHostObserver::RenderViewHostObserver(RenderViewHost* render_view_host)
: render_view_host_(render_view_host),
routing_id_(render_view_host->routing_id()) {
render_view_host_->AddObserver(this);
}
RenderViewHostObserver::~RenderViewHostObserver() {
if (render_view_host_)
render_view_host_->RemoveObserver(this);
}
void RenderViewHostObserver::RenderViewHostDestroyed() {
delete this;
}
bool RenderViewHostObserver::OnMessageReceived(const IPC::Message& message) {
return false;
}
bool RenderViewHostObserver::Send(IPC::Message* message) {
if (!render_view_host_) {
delete message;
return false;
}
return render_view_host_->Send(message);
}
void RenderViewHostObserver::RenderViewHostDestruction() {
render_view_host_->RemoveObserver(this);
RenderViewHostDestroyed();
render_view_host_ = NULL;
}
| // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/render_view_host_observer.h"
#include "content/browser/renderer_host/render_view_host.h"
RenderViewHostObserver::RenderViewHostObserver(RenderViewHost* render_view_host)
: render_view_host_(render_view_host),
routing_id_(render_view_host->routing_id()) {
render_view_host_->AddObserver(this);
}
RenderViewHostObserver::~RenderViewHostObserver() {
if (render_view_host_)
render_view_host_->RemoveObserver(this);
}
void RenderViewHostObserver::RenderViewHostDestroyed() {
delete this;
}
bool RenderViewHostObserver::OnMessageReceived(const IPC::Message& message) {
return false;
}
bool RenderViewHostObserver::Send(IPC::Message* message) {
if (!render_view_host_) {
delete message;
return false;
}
return render_view_host_->Send(message);
}
void RenderViewHostObserver::RenderViewHostDestruction() {
render_view_host_->RemoveObserver(this);
render_view_host_ = NULL;
RenderViewHostDestroyed();
}
|
Switch create window message from debug to info | // Copyright 2016 Zheng Xian Qiu
#include "framework.h"
Window::Window() {
}
// Display Information
int Window::DISPLAY_INDEX = 0;
bool Window::displayModeLoaded = false;
SDL_DisplayMode Window::displayMode;
int Window::getDisplayWidth() {
loadDisplayMode();
return displayMode.w;
}
int Window::getDisplayHeight() {
loadDisplayMode();
return displayMode.h;
}
void Window::loadDisplayMode(bool reload) {
if(!displayModeLoaded || reload) {
if(SDL_GetCurrentDisplayMode(DISPLAY_INDEX, &displayMode) != 0) {
displayModeLoaded = false;
}
displayModeLoaded = true;
}
}
// Window Manager
bool Window::create(string title, bool hide) {
uint flags = hide ? 0 : SDL_WINDOW_SHOWN;
flags = flags | SDL_WINDOW_ALLOW_HIGHDPI | SDL_WINDOW_INPUT_GRABBED;
currentWindow = SDL_CreateWindow(title.c_str(), 0, 0, getDisplayWidth(), getDisplayHeight(), flags);
if(currentWindow == NULL) {
SDL_DestroyWindow(currentWindow);
return false;
}
Logger::Debug("Initialize window with %dx%dpx resolution.", getDisplayWidth(), getDisplayHeight());
return true;
}
void Window::destroy() {
SDL_DestroyWindow(currentWindow);
}
| // Copyright 2016 Zheng Xian Qiu
#include "framework.h"
Window::Window() {
}
// Display Information
int Window::DISPLAY_INDEX = 0;
bool Window::displayModeLoaded = false;
SDL_DisplayMode Window::displayMode;
int Window::getDisplayWidth() {
loadDisplayMode();
return displayMode.w;
}
int Window::getDisplayHeight() {
loadDisplayMode();
return displayMode.h;
}
void Window::loadDisplayMode(bool reload) {
if(!displayModeLoaded || reload) {
if(SDL_GetCurrentDisplayMode(DISPLAY_INDEX, &displayMode) != 0) {
displayModeLoaded = false;
}
displayModeLoaded = true;
}
}
// Window Manager
bool Window::create(string title, bool hide) {
uint flags = hide ? 0 : SDL_WINDOW_SHOWN;
flags = flags | SDL_WINDOW_ALLOW_HIGHDPI | SDL_WINDOW_INPUT_GRABBED;
currentWindow = SDL_CreateWindow(title.c_str(), 0, 0, getDisplayWidth(), getDisplayHeight(), flags);
if(currentWindow == NULL) {
SDL_DestroyWindow(currentWindow);
return false;
}
Logger::Info("Initialize window with %dx%dpx resolution.", getDisplayWidth(), getDisplayHeight());
return true;
}
void Window::destroy() {
SDL_DestroyWindow(currentWindow);
}
|
Improve advice for attaching the debugger | #include "DebugAndroid.hpp"
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <cutils/properties.h>
void AndroidEnterDebugger()
{
ALOGE(__FUNCTION__);
#ifndef NDEBUG
static volatile int * const makefault = nullptr;
char value[PROPERTY_VALUE_MAX];
property_get("debug.db.uid", value, "-1");
int debug_uid = atoi(value);
if ((debug_uid >= 0) && (geteuid() < static_cast<uid_t>(debug_uid)))
{
ALOGE("Waiting for debugger: gdbserver :${PORT} --attach %u", gettid());
while (1) {
pause();
}
} else {
ALOGE("No debugger");
}
#endif
}
void trace(const char *format, ...)
{
va_list vararg;
va_start(vararg, format);
android_vprintLog(ANDROID_LOG_VERBOSE, NULL, LOG_TAG, format, vararg);
va_end(vararg);
}
| #include "DebugAndroid.hpp"
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <cutils/properties.h>
void AndroidEnterDebugger()
{
ALOGE(__FUNCTION__);
#ifndef NDEBUG
static volatile int * const makefault = nullptr;
char value[PROPERTY_VALUE_MAX];
property_get("debug.db.uid", value, "-1");
int debug_uid = atoi(value);
if ((debug_uid >= 0) && (geteuid() < static_cast<uid_t>(debug_uid)))
{
ALOGE("Waiting for debugger: gdbserver :${PORT} --attach %u. Look for thread %u", getpid(), gettid());
volatile int waiting = 1;
while (waiting) {
sleep(1);
}
} else {
ALOGE("No debugger");
}
#endif
}
void trace(const char *format, ...)
{
va_list vararg;
va_start(vararg, format);
android_vprintLog(ANDROID_LOG_VERBOSE, NULL, LOG_TAG, format, vararg);
va_end(vararg);
}
|
Make geoclue-support more robust to missing master, second attempt | #include "MasterClient_p.h"
#include <QtCore/QString>
#include <QtDBus/QDBusMessage>
#include <QtDBus/QDBusReply>
#include <QtDBus/QDBusObjectPath>
#include "PositionProvider.h"
using namespace GeoCute;
static QString createClientPath() {
SimpleDBusInterface masterInterface(serviceName, masterPathName,
masterInterfaceName);
QDBusReply<QDBusObjectPath> reply = masterInterface.call("Create");
if (reply.isValid())
return reply.value().path();
else
return QString();
}
MasterClient::Private::Private()
: interface(serviceName, createClientPath(), interfaceName) { }
MasterClient::MasterClient(QObject* parent)
: QObject(parent), d(new Private) { }
MasterClient::~MasterClient() {
delete d;
}
void MasterClient::setRequirements(AccuracyLevel accuracy, int min_time,
SignallingFlags signalling, ResourceFlags resources)
{
d->interface.call("SetRequirements", accuracy, min_time,
signalling == SignallingRequired, resources);
}
PositionProvider* MasterClient::positionProvider() {
if (!d->interface.path().isEmpty()) {
d->interface.call("PositionStart");
return new PositionProvider(d->interface.service(), d->interface.path());
} else
return 0;
}
#include "MasterClient.moc"
| #include "MasterClient_p.h"
#include <QtCore/QString>
#include <QtDBus/QDBusMessage>
#include <QtDBus/QDBusReply>
#include <QtDBus/QDBusObjectPath>
#include "PositionProvider.h"
using namespace GeoCute;
static QString createClientPath() {
SimpleDBusInterface masterInterface(serviceName, masterPathName,
masterInterfaceName);
QDBusReply<QDBusObjectPath> reply = masterInterface.call("Create");
if (reply.isValid())
return reply.value().path();
else
return QString();
}
MasterClient::Private::Private()
: interface(serviceName, createClientPath(), interfaceName) { }
MasterClient::MasterClient(QObject* parent)
: QObject(parent), d(new Private) { }
MasterClient::~MasterClient() {
delete d;
}
void MasterClient::setRequirements(AccuracyLevel accuracy, int min_time,
SignallingFlags signalling, ResourceFlags resources)
{
if (!d->interface.path().isEmpty()) {
d->interface.call("SetRequirements", accuracy, min_time,
signalling == SignallingRequired, resources);
}
}
PositionProvider* MasterClient::positionProvider() {
if (!d->interface.path().isEmpty()) {
d->interface.call("PositionStart");
return new PositionProvider(d->interface.service(), d->interface.path());
} else
return 0;
}
#include "MasterClient.moc"
|
Update Provider to Manager from clean branch | #include "Device.h"
#include "../../Drivers/SPIDisplay/SPIDisplay.h"
#include "../../Drivers/DevicesInterop/GHIElectronics_TinyCLR_Devices.h"
#include "../../Drivers/DevicesInterop/GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Interop.h"
void STM32F4_Startup_OnSoftResetDevice(const TinyCLR_Api_Provider* apiProvider, const TinyCLR_Interop_Provider* interopProvider) {
apiProvider->Add(apiProvider, SPIDisplay_GetApi());
interopProvider->Add(interopProvider, &Interop_GHIElectronics_TinyCLR_Devices);
} | #include "Device.h"
#include "../../Drivers/SPIDisplay/SPIDisplay.h"
#include "../../Drivers/DevicesInterop/GHIElectronics_TinyCLR_Devices.h"
#include "../../Drivers/DevicesInterop/GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Interop.h"
void STM32F4_Startup_OnSoftResetDevice(const TinyCLR_Api_Manager* apiManager, const TinyCLR_Interop_Manager* interopManager) {
apiManager->Add(apiManager, SPIDisplay_GetApi());
interopManager->Add(interopManager, &Interop_GHIElectronics_TinyCLR_Devices);
} |
Remove extra stuff from simplest example | #include "helloworld.h"
#include <QCoreApplication>
#include <QDebug>
#include <qhttpserver.h>
#include <qhttprequest.h>
#include <qhttpresponse.h>
Hello::Hello()
{
QHttpServer *server = new QHttpServer;
server->listen(QHostAddress::Any, 5000);
connect(server, SIGNAL(newRequest(QHttpRequest*, QHttpResponse*)),
this, SLOT(handle(QHttpRequest*, QHttpResponse*)));
}
void Hello::handle(QHttpRequest *req, QHttpResponse *resp)
{
qDebug() << "Handling request";
qDebug() << "Method" << req->method();
qDebug() << "HTTP Version" << req->httpVersion();
qDebug() << "URL" << req->url();
resp->setHeader("Content-Type", "text/html");
resp->setHeader("Content-Length", "11");
resp->writeHead(200);
resp->write(QString("Hello World"));
resp->end();
}
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
Hello hello;
app.exec();
}
| #include "helloworld.h"
#include <QCoreApplication>
#include <qhttpserver.h>
#include <qhttprequest.h>
#include <qhttpresponse.h>
Hello::Hello()
{
QHttpServer *server = new QHttpServer;
server->listen(QHostAddress::Any, 5000);
connect(server, SIGNAL(newRequest(QHttpRequest*, QHttpResponse*)),
this, SLOT(handle(QHttpRequest*, QHttpResponse*)));
}
void Hello::handle(QHttpRequest *req, QHttpResponse *resp)
{
resp->setHeader("Content-Length", "11");
resp->writeHead(200);
resp->write(QString("Hello World"));
resp->end();
}
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
Hello hello;
app.exec();
}
|
Make test 64 bit safe. | // RUN: clang-cc -emit-llvm %s -o - | FileCheck %s
struct A;
typedef int A::*param_t;
struct {
const char *name;
param_t par;
} *ptr;
// CHECK: type { i8*, i32 }
| // RUN: clang-cc -emit-llvm %s -o - | FileCheck %s
struct A;
typedef int A::*param_t;
struct {
const char *name;
param_t par;
} *ptr;
// CHECK: type { i8*, {{i..}} }
|
Add triple to new test to try to pacify bots | // RUN: %clang_cc1 -emit-llvm %s -gcodeview -debug-info-kind=limited -o - | FileCheck %s
struct a {
~a();
};
template <typename b> struct c : a {
c(void (b::*)());
};
struct B {
virtual void e();
};
c<B> *d() { static c<B> f(&B::e); return &f; }
// CHECK: define internal void @"??__Ff@?1??d@@YAPEAU?$c@UB@@@@XZ@YAXXZ"()
// CHECK-SAME: !dbg ![[SUBPROGRAM:[0-9]+]] {
// CHECK: call void @"??1?$c@UB@@@@QEAA@XZ"(%struct.c* @"?f@?1??d@@YAPEAU?$c@UB@@@@XZ@4U2@A"), !dbg ![[LOCATION:[0-9]+]]
// CHECK-NEXT: ret void, !dbg ![[LOCATION]]
// CHECK: ![[SUBPROGRAM]] = distinct !DISubprogram(name: "`dynamic atexit destructor for 'f'"
// CHECK-SAME: flags: DIFlagArtificial
// CHECK: ![[LOCATION]] = !DILocation(line: 0, scope: ![[SUBPROGRAM]])
| // RUN: %clang_cc1 -triple x86_64-windows-msvc -emit-llvm %s -gcodeview -debug-info-kind=limited -o - | FileCheck %s
struct a {
~a();
};
template <typename b> struct c : a {
c(void (b::*)());
};
struct B {
virtual void e();
};
c<B> *d() { static c<B> f(&B::e); return &f; }
// CHECK: define internal void @"??__Ff@?1??d@@YAPEAU?$c@UB@@@@XZ@YAXXZ"()
// CHECK-SAME: !dbg ![[SUBPROGRAM:[0-9]+]] {
// CHECK: call void @"??1?$c@UB@@@@QEAA@XZ"(%struct.c* @"?f@?1??d@@YAPEAU?$c@UB@@@@XZ@4U2@A"), !dbg ![[LOCATION:[0-9]+]]
// CHECK-NEXT: ret void, !dbg ![[LOCATION]]
// CHECK: ![[SUBPROGRAM]] = distinct !DISubprogram(name: "`dynamic atexit destructor for 'f'"
// CHECK-SAME: flags: DIFlagArtificial
// CHECK: ![[LOCATION]] = !DILocation(line: 0, scope: ![[SUBPROGRAM]])
|
Call state pause method when not replacing state. | #include "state_machine.hpp"
namespace kg {
void StateMachine::startState(StateRef newState, bool isReplacing) {
if (isReplacing && !_states.empty()) {
_states.pop();
}
_states.push(std::move(newState));
_states.top()->start();
}
void StateMachine::exitState() {
if (_states.empty()) return;
_states.pop();
if (!_states.empty()) {
_states.top()->resume();
}
}
}
| #include "state_machine.hpp"
namespace kg {
void StateMachine::startState(StateRef newState, bool isReplacing) {
if (isReplacing && !_states.empty()) {
_states.pop();
}
if (!isReplacing) {
_states->top()->pause();
}
_states.push(std::move(newState));
_states.top()->start();
}
void StateMachine::exitState() {
if (_states.empty()) return;
_states.pop();
if (!_states.empty()) {
_states.top()->resume();
}
}
}
|
Add Media Router Mojo service to the renderer service registry. Guard access to the Media Router service using a manifest permission. | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/chrome_mojo_service_registration.h"
#include "base/logging.h"
namespace extensions {
void RegisterChromeServicesForFrame(content::RenderFrameHost* render_frame_host,
const Extension* extension) {
DCHECK(render_frame_host);
DCHECK(extension);
// TODO(kmarshall): Add Mojo service registration.
}
} // namespace extensions
| // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/chrome_mojo_service_registration.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "chrome/common/chrome_switches.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/service_registry.h"
#include "extensions/common/extension.h"
#include "extensions/common/permissions/api_permission.h"
#include "extensions/common/permissions/permissions_data.h"
#include "extensions/common/switches.h"
#if defined(ENABLE_MEDIA_ROUTER)
#include "chrome/browser/media/router/media_router_mojo_impl.h"
#endif
namespace extensions {
void RegisterChromeServicesForFrame(content::RenderFrameHost* render_frame_host,
const Extension* extension) {
DCHECK(render_frame_host);
DCHECK(extension);
content::ServiceRegistry* service_registry =
render_frame_host->GetServiceRegistry();
#if defined(ENABLE_MEDIA_ROUTER)
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
::switches::kEnableMediaRouter)) {
if (extension->permissions_data()->HasAPIPermission(
APIPermission::kMediaRouterPrivate)) {
service_registry->AddService(base::Bind(
media_router::MediaRouterMojoImpl::BindToRequest, extension->id(),
render_frame_host->GetProcess()->GetBrowserContext()));
}
}
#endif // defined(ENABLE_MEDIA_ROUTER)
}
} // namespace extensions
|
Fix test failure with GCC 4.9 | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++98, c++03
// Verify TEST_WORKAROUND_C1XX_BROKEN_IS_TRIVIALLY_COPYABLE.
#include <type_traits>
#include "test_workarounds.h"
struct S {
S(S const&) = default;
S(S&&) = default;
S& operator=(S const&) = delete;
S& operator=(S&&) = delete;
};
int main() {
#if defined(TEST_WORKAROUND_C1XX_BROKEN_IS_TRIVIALLY_COPYABLE)
static_assert(!std::is_trivially_copyable<S>::value, "");
#else
static_assert(std::is_trivially_copyable<S>::value, "");
#endif
}
| //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++98, c++03
// This workaround option is specific to MSVC's C1XX, so we don't care that
// it isn't set for older GCC versions.
// XFAIL: gcc-4.9
// Verify TEST_WORKAROUND_C1XX_BROKEN_IS_TRIVIALLY_COPYABLE.
#include <type_traits>
#include "test_workarounds.h"
struct S {
S(S const&) = default;
S(S&&) = default;
S& operator=(S const&) = delete;
S& operator=(S&&) = delete;
};
int main() {
#if defined(TEST_WORKAROUND_C1XX_BROKEN_IS_TRIVIALLY_COPYABLE)
static_assert(!std::is_trivially_copyable<S>::value, "");
#else
static_assert(std::is_trivially_copyable<S>::value, "");
#endif
}
|
Revert 273648 "skia: Use medium filter quality in PaintSimplifier." | // 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 <limits>
#include "skia/ext/paint_simplifier.h"
#include "third_party/skia/include/core/SkPaint.h"
namespace skia {
PaintSimplifier::PaintSimplifier()
: INHERITED() {
}
PaintSimplifier::~PaintSimplifier() {
}
bool PaintSimplifier::filter(SkPaint* paint, Type type) {
// Preserve a modicum of text quality; black & white text is
// just too blocky, even during a fling.
if (type != kText_Type) {
paint->setAntiAlias(false);
}
paint->setSubpixelText(false);
paint->setLCDRenderText(false);
// Reduce filter level to medium or less. Note that reducing the filter to
// less than medium can have a negative effect on performance as the filtered
// image is not cached in this case.
paint->setFilterLevel(
std::min(paint->getFilterLevel(), SkPaint::kMedium_FilterLevel));
paint->setMaskFilter(NULL);
// Uncomment this line to shade simplified tiles pink during debugging.
//paint->setColor(SkColorSetRGB(255, 127, 127));
return true;
}
} // namespace skia
| // 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 "skia/ext/paint_simplifier.h"
#include "third_party/skia/include/core/SkPaint.h"
namespace skia {
PaintSimplifier::PaintSimplifier()
: INHERITED() {
}
PaintSimplifier::~PaintSimplifier() {
}
bool PaintSimplifier::filter(SkPaint* paint, Type type) {
// Preserve a modicum of text quality; black & white text is
// just too blocky, even during a fling.
if (type != kText_Type) {
paint->setAntiAlias(false);
}
paint->setSubpixelText(false);
paint->setLCDRenderText(false);
paint->setMaskFilter(NULL);
// Uncomment this line to shade simplified tiles pink during debugging.
//paint->setColor(SkColorSetRGB(255, 127, 127));
return true;
}
} // namespace skia
|
Change tests in JPetAnalysisTools to use double instead of int | #define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetEventTest
#include <boost/test/unit_test.hpp>
#include "../JPetAnalysisTools/JPetAnalysisTools.h"
BOOST_AUTO_TEST_SUITE(FirstSuite)
BOOST_AUTO_TEST_CASE(constructor_getHitsOrderedByTime)
{
std::vector<JPetHit> hits(4);
hits[0].setTime(2);
hits[1].setTime(1);
hits[2].setTime(4);
hits[3].setTime(3);
auto results = JPetAnalysisTools::getHitsOrderedByTime(hits);
BOOST_REQUIRE_EQUAL(results[0].getTime(), 1);
BOOST_REQUIRE_EQUAL(results[1].getTime(), 2);
BOOST_REQUIRE_EQUAL(results[2].getTime(), 3);
BOOST_REQUIRE_EQUAL(results[3].getTime(), 4);
}
BOOST_AUTO_TEST_SUITE_END()
| #define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetEventTest
#include <boost/test/unit_test.hpp>
#include "../JPetAnalysisTools/JPetAnalysisTools.h"
BOOST_AUTO_TEST_SUITE(FirstSuite)
BOOST_AUTO_TEST_CASE(constructor_getHitsOrderedByTime)
{
std::vector<JPetHit> hits(4);
hits[0].setTime(2);
hits[1].setTime(1);
hits[2].setTime(4);
hits[3].setTime(3);
auto results = JPetAnalysisTools::getHitsOrderedByTime(hits);
double epsilon = 0.0001;
BOOST_REQUIRE_CLOSE(results[0].getTime(), 1, epsilon );
BOOST_REQUIRE_CLOSE(results[1].getTime(), 2, epsilon );
BOOST_REQUIRE_CLOSE(results[2].getTime(), 3, epsilon );
BOOST_REQUIRE_CLOSE(results[3].getTime(), 4, epsilon );
}
BOOST_AUTO_TEST_SUITE_END()
|
Fix a bug found by @rperrot |
#include "SimpleString.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
SimpleString::SimpleString ()
: buffer(new char [1])
{
buffer [0] = '\0';
}
SimpleString::SimpleString (const char *otherBuffer)
: buffer (new char [strlen (otherBuffer) + 1])
{
strcpy (buffer, otherBuffer);
}
SimpleString::SimpleString (const SimpleString& other)
{
buffer = new char [other.size() + 1];
strcpy(buffer, other.buffer);
}
SimpleString & SimpleString::operator= (const SimpleString& other)
{
delete buffer;
buffer = new char [other.size() + 1];
strcpy(buffer, other.buffer);
return *this;
}
char *SimpleString::asCharString () const
{
return buffer;
}
int SimpleString::size() const
{
return strlen (buffer);
}
SimpleString::~SimpleString ()
{
delete [] buffer;
}
bool operator== (const SimpleString& left, const SimpleString& right)
{
return !strcmp (left.asCharString (), right.asCharString ());
}
|
#include "SimpleString.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
SimpleString::SimpleString ()
: buffer(new char [1])
{
buffer [0] = '\0';
}
SimpleString::SimpleString (const char *otherBuffer)
: buffer (new char [strlen (otherBuffer) + 1])
{
strcpy (buffer, otherBuffer);
}
SimpleString::SimpleString (const SimpleString& other)
{
buffer = new char [other.size() + 1];
strcpy(buffer, other.buffer);
}
SimpleString & SimpleString::operator= (const SimpleString& other)
{
delete []buffer;
buffer = new char [other.size() + 1];
strcpy(buffer, other.buffer);
return *this;
}
char *SimpleString::asCharString () const
{
return buffer;
}
int SimpleString::size() const
{
return strlen (buffer);
}
SimpleString::~SimpleString ()
{
delete [] buffer;
}
bool operator== (const SimpleString& left, const SimpleString& right)
{
return !strcmp (left.asCharString (), right.asCharString ());
}
|
Include main hdf5 header to successful build | //============================================================================
// Name : benchpress.cpp
// Author : Ulrik Kofoed Pedersen
// Version :
// Copyright : MIT. See LICENSE file.
// Description : Use blosc with different algorithms to compress data from
// datasets in an HDF5 file - and benchmark the performance
//============================================================================
#include <iostream>
using namespace std;
#include <blosc.h>
#include <hdf5_hl.h>
int main() {
cout << "hi there" << endl; // prints hi there
return 0;
}
| //============================================================================
// Name : benchpress.cpp
// Author : Ulrik Kofoed Pedersen
// Version :
// Copyright : MIT. See LICENSE file.
// Description : Use blosc with different algorithms to compress data from
// datasets in an HDF5 file - and benchmark the performance
//============================================================================
#include <iostream>
using namespace std;
#include <blosc.h>
#include <hdf5.h>
#include <hdf5_hl.h>
int main() {
cout << "hi there" << endl; // prints hi there
return 0;
}
|
FIx GCC was unable to compile in Linux | #include "paddle.h"
int Paddle::numOfPaddles = 0;
void Paddle::update()
{
al_get_mouse_state(&mouseState);
mouseY = al_get_mouse_state_axis(&mouseState, 1);
setPosition(x, mouseY);
}
void Paddle::reset()
{
al_get_mouse_state(&mouseState);
mouseY = al_get_mouse_state_axis(&mouseState, 1);
setPosition(x, mouseY);
} | #include "Paddle.h"
int Paddle::numOfPaddles = 0;
void Paddle::update()
{
al_get_mouse_state(&mouseState);
mouseY = al_get_mouse_state_axis(&mouseState, 1);
setPosition(x, mouseY);
}
void Paddle::reset()
{
al_get_mouse_state(&mouseState);
mouseY = al_get_mouse_state_axis(&mouseState, 1);
setPosition(x, mouseY);
}
|
Clean up some namespace things | #include <stdio.h>
#include "mutex.h"
#include "thread.h"
#include "window.h"
using System::Window;
class DisplayThreadEntry : public System::ThreadEntry {
public:
virtual ~DisplayThreadEntry() {}
virtual void *Run(void *arg) {
Window *mainWindow = Window::Create();
int exitValue = mainWindow->DoMessageLoop();
delete mainWindow;
}
};
int applicationMain()
{
DisplayThreadEntry displayThreadEntry;
System::Thread *displayThread = System::Thread::Create(&displayThreadEntry);
displayThread->Start();
displayThread->Wait();
return 0;
}
| #include <stdio.h>
#include "mutex.h"
#include "thread.h"
#include "window.h"
using System::Window;
using System::Thread;
using System::ThreadEntry;
class DisplayThreadEntry : public ThreadEntry {
public:
virtual ~DisplayThreadEntry() {}
virtual void *Run(void *arg) {
Window *mainWindow = Window::Create();
int exitValue = mainWindow->DoMessageLoop();
delete mainWindow;
}
};
int applicationMain()
{
DisplayThreadEntry displayThreadEntry;
Thread *displayThread = Thread::Create(&displayThreadEntry);
displayThread->Start();
displayThread->Wait();
return 0;
}
|
Add code to destroy window upon quit | #include <GL/glew.h>
#include <SDL2/SDL.h>
int main(void)
{
int flags = SDL_WINDOW_OPENGL | SDL_RENDERER_PRESENTVSYNC;
SDL_Init(SDL_INIT_EVERYTHING);
auto window = SDL_CreateWindow("title", 0, 0, 320, 240, flags);
auto context = SDL_GL_CreateContext(window);
glewInit();
glClearColor(0, 1, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);
SDL_Event event;
while (true)
{
while (SDL_PollEvent(&event) != 0)
if (event.type == SDL_QUIT)
goto quit;
SDL_Delay(10);
SDL_GL_SwapWindow(window);
}
quit:
SDL_Quit();
return 0;
}
| #include <GL/glew.h>
#include <SDL2/SDL.h>
int main(void)
{
int flags = SDL_WINDOW_OPENGL | SDL_RENDERER_PRESENTVSYNC;
SDL_Init(SDL_INIT_EVERYTHING);
auto window = SDL_CreateWindow("title", 0, 0, 320, 240, flags);
auto context = SDL_GL_CreateContext(window);
glewInit();
glClearColor(0, 1, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);
SDL_Event event;
while (true)
{
while (SDL_PollEvent(&event) != 0)
if (event.type == SDL_QUIT)
goto quit;
SDL_Delay(10);
SDL_GL_SwapWindow(window);
}
quit:
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
|
Test Main: Set up logging | #include <iostream>
#include "gtest/gtest.h"
int main(int argc, char* argv[])
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| #include "core/logging.hpp"
#include <iostream>
#include <gtest/gtest.h>
int main(int argc, char* argv[])
{
core::logging_init();
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
Remove extra blank line and include | #include <glog/logging.h>
#include <atom/atom.h>
#include <core.h>
int main(int argc, char **argv)
{
atom_initialize();
{
ATOM_GC;
atom_attach_thread();
start_core(argc, argv);
}
atom_terminate();
return 0;
}
| #include <atom/atom.h>
#include <core.h>
int main(int argc, char **argv)
{
atom_initialize();
{
ATOM_GC;
atom_attach_thread();
start_core(argc, argv);
}
atom_terminate();
return 0;
}
|
Consolidate creation of storage::spi::Bucket in unit tests. | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "bucketfactory.h"
using document::BucketId;
using document::DocumentId;
using storage::spi::Bucket;
using storage::spi::PartitionId;
namespace proton {
BucketId
BucketFactory::getBucketId(const DocumentId &docId)
{
BucketId bId = docId.getGlobalId().convertToBucketId();
bId.setUsedBits(getNumBucketBits());
return bId;
}
Bucket
BucketFactory::getBucket(const DocumentId &docId)
{
return Bucket(document::Bucket(document::BucketSpace::placeHolder(), getBucketId(docId)), PartitionId(0));
}
} // namespace proton
| // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "bucketfactory.h"
#include <vespa/persistence/spi/test.h>
using document::BucketId;
using document::DocumentId;
using storage::spi::Bucket;
using storage::spi::PartitionId;
using storage::spi::test::makeBucket;
namespace proton {
BucketId
BucketFactory::getBucketId(const DocumentId &docId)
{
BucketId bId = docId.getGlobalId().convertToBucketId();
bId.setUsedBits(getNumBucketBits());
return bId;
}
Bucket
BucketFactory::getBucket(const DocumentId &docId)
{
return makeBucket(getBucketId(docId));
}
} // namespace proton
|
Use var for enabling or disabling sound | #include <SFML/Graphics.hpp>
//#include "libs/GUI-SFML/include/GUI-SFML.hpp"
#include <iostream>
#include "Game.hpp"
int main()
{
sf::RenderWindow window(sf::VideoMode(800, 600), "My window");
//gsf::GUIEnvironment environment( window );
Game game(false, true, false);
game.run();
return 0;
}
| #include <SFML/Graphics.hpp>
//#include "libs/GUI-SFML/include/GUI-SFML.hpp"
#include <iostream>
#include "Game.hpp"
int main()
{
sf::RenderWindow window(sf::VideoMode(800, 600), "My window");
//gsf::GUIEnvironment environment( window );
bool soundEnabled{ false };
Game game(false, true, soundEnabled);
game.run();
return 0;
}
|
Use C++ string instead of C string | #include <iostream>
#include <opencv2/opencv.hpp>
#include "clicker.hpp"
using namespace cv;
using namespace std;
const char* window_title = "Join-Robockets Clientside Software";
int main() {
//Initialize camera.
VideoCapture cap(CV_CAP_ANY);
if(!cap.isOpened()) {
cerr << "Could not open image capture device!" << endl;
exit(EXIT_FAILURE);
}
Mat frame;
namedWindow(window_title);
while(1) {
//Capture and show image.
cap >> frame;
imshow(window_title, frame);
//Quit if any key has been pressed.
if(waitKey(30) >= 0) {
break;
}
}
//VideoCapture is closed automatically.
return 0;
} | #include <iostream>
#include <opencv2/opencv.hpp>
#include "clicker.hpp"
using namespace cv;
using namespace std;
string window_title = "Join-Robockets Clientside Software";
int main() {
//Initialize camera.
VideoCapture cap(CV_CAP_ANY);
if(!cap.isOpened()) {
cerr << "Could not open image capture device!" << endl;
exit(EXIT_FAILURE);
}
Mat frame;
namedWindow(window_title);
while(1) {
//Capture and show image.
cap >> frame;
imshow(window_title, frame);
//Quit if any key has been pressed.
if(waitKey(30) >= 0) {
break;
}
}
//VideoCapture is closed automatically.
return 0;
} |
Fix a memory leak in FPDFPageFuncEmbeddertest. | // Copyright 2015 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "testing/embedder_test.h"
#include "testing/gtest/include/gtest/gtest.h"
class FPDFRenderPatternEmbeddertest : public EmbedderTest {};
TEST_F(FPDFRenderPatternEmbeddertest, LoadError_547706) {
// Test shading where object is a dictionary instead of a stream.
EXPECT_TRUE(OpenDocument("bug_547706.pdf"));
FPDF_PAGE page = LoadPage(0);
RenderPage(page);
UnloadPage(page);
}
| // Copyright 2015 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "testing/embedder_test.h"
#include "testing/gtest/include/gtest/gtest.h"
class FPDFRenderPatternEmbeddertest : public EmbedderTest {};
TEST_F(FPDFRenderPatternEmbeddertest, LoadError_547706) {
// Test shading where object is a dictionary instead of a stream.
EXPECT_TRUE(OpenDocument("bug_547706.pdf"));
FPDF_PAGE page = LoadPage(0);
FPDF_BITMAP bitmap = RenderPage(page);
FPDFBitmap_Destroy(bitmap);
UnloadPage(page);
}
|
Fix to match the enum definitions in C and nodejs for indextypes. | /*******************************************************************************
* Copyright 2013-2014 Aerospike, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
#include <node.h>
#include "enums.h"
using namespace v8;
#define set(__obj, __name, __value) __obj->Set(String::NewSymbol(__name), Integer::New(__value), ReadOnly)
Handle<Object> indexType()
{
HANDLESCOPE;
Handle<Object> obj = Object::New();
set(obj, "NUMERIC", 0);
set(obj, "STRING", 1);
return scope.Close(obj);
}
| /*******************************************************************************
* Copyright 2013-2014 Aerospike, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
#include <node.h>
#include "enums.h"
using namespace v8;
#define set(__obj, __name, __value) __obj->Set(String::NewSymbol(__name), Integer::New(__value), ReadOnly)
Handle<Object> indexType()
{
HANDLESCOPE;
Handle<Object> obj = Object::New();
set(obj, "STRING", 0);
set(obj, "NUMERIC", 1);
return scope.Close(obj);
}
|
Use vector instead of list | #include "Controller.h"
#include "JobHandler.h"
#include "JobQueue.h"
#include "Sensor.h"
#include <list>
std::list<Sensor> sensors;
std::list<Controller> controllers;
std::list<JobHandler> jobHandlers;
JobQueue jobQueue;
/** Initializes a Sensor object for each sensor */
void initializeSensors() {
// "TODO: initializeSensors"
}
/** Initializes a Controller object for each controller */
void initializeControllers() {
// "TODO: initializeControllers"
}
/** Initializes a JobHandler object for each job type */
void initializeJobHandlers() {
// "TODO: initializeJobHandlers"
}
/** Initializes the JobQueue object */
void initializeJobQueue() {
// "TODO: initializeJobQueue"
}
/** Returns the JobHandler object suited to deal with the given job */
JobHandler getHandlerByJob(std::string job) {
// "TODO: initializeJobQueue"
}
int main(int argc, char *argv[]) {
initializeSensors();
initializeControllers();
initializeJobHandlers();
initializeJobQueue();
/** Main execution loop */
while (1) {
std::string job;
if (jobQueue.getJob(&job)) {
JobHandler handler = getHandlerByJob(job);
handler.execute(job);
}
// TODO: Complete this function
}
} | #include "Controller.h"
#include "JobHandler.h"
#include "JobQueue.h"
#include "Sensor.h"
#include <vector>
std::vector<Sensor> sensors;
std::vector<Controller> controllers;
std::vector<JobHandler> jobHandlers;
JobQueue jobQueue;
/** Initializes a Sensor object for each sensor */
void initializeSensors() {
// "TODO: initializeSensors"
}
/** Initializes a Controller object for each controller */
void initializeControllers() {
// "TODO: initializeControllers"
}
/** Initializes a JobHandler object for each job type */
void initializeJobHandlers() {
// "TODO: initializeJobHandlers"
}
/** Initializes the JobQueue object */
void initializeJobQueue() {
// "TODO: initializeJobQueue"
}
/** Returns the JobHandler object suited to deal with the given job */
JobHandler getHandlerByJob(std::string job) {
// "TODO: initializeJobQueue"
}
int main(int argc, char *argv[]) {
initializeSensors();
initializeControllers();
initializeJobHandlers();
initializeJobQueue();
/** Main execution loop */
while (1) {
std::string job;
if (jobQueue.getJob(&job)) {
JobHandler handler = getHandlerByJob(job);
handler.execute(job);
}
// TODO: Complete this function
}
} |
Fix missing write call in SubWorldMsg | /******************************************************************************
* This file is part of dirtsand. *
* *
* dirtsand is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* dirtsand 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 Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with dirtsand. If not, see <http://www.gnu.org/licenses/>. *
******************************************************************************/
#include "SimulationMsg.h"
void MOUL::SubWorldMsg::read(DS::Stream* stream)
{
m_world.read(stream);
}
void MOUL::SubWorldMsg::write(DS::Stream* stream) const
{
m_world.write(stream);
}
| /******************************************************************************
* This file is part of dirtsand. *
* *
* dirtsand is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* dirtsand 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 Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with dirtsand. If not, see <http://www.gnu.org/licenses/>. *
******************************************************************************/
#include "SimulationMsg.h"
void MOUL::SubWorldMsg::read(DS::Stream* stream)
{
MOUL::Message::read(stream);
m_world.read(stream);
}
void MOUL::SubWorldMsg::write(DS::Stream* stream) const
{
MOUL::Message::write(stream);
m_world.write(stream);
}
|
Use QGraphicsWebView instead of QWebView | #include <QtGui/QApplication>
#include <QtCore/QProcess>
#include <QtWebKit/QWebView>
#if defined(Q_OS_SYMBIAN) && defined(ORIENTATIONLOCK)
#include <eikenv.h>
#include <eikappui.h>
#include <aknenv.h>
#include <aknappui.h>
#endif // Q_OS_SYMBIAN && ORIENTATIONLOCK
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
#if defined(Q_OS_SYMBIAN) && defined(ORIENTATIONLOCK)
const CAknAppUiBase::TAppUiOrientation uiOrientation = CAknAppUi::EAppUiOrientationLandscape;
CAknAppUi* appUi = dynamic_cast<CAknAppUi*> (CEikonEnv::Static()->AppUi());
TRAPD(error,
if (appUi)
appUi->SetOrientationL(uiOrientation);
);
Q_UNUSED(error)
#endif // ORIENTATIONLOCK
QWebView webView;
webView.load(QString::fromLatin1("html/examples/kitchensink/index.html"));
#if defined(Q_OS_SYMBIAN)
webView.showFullScreen();
#elif defined(Q_WS_MAEMO_5)
webView.showMaximized();
#else
webView.show();
#endif
return app.exec();
}
| #include <QtGui>
#include <QtWebKit>
#if defined(Q_OS_SYMBIAN) && defined(ORIENTATIONLOCK)
#include <eikenv.h>
#include <eikappui.h>
#include <aknenv.h>
#include <aknappui.h>
#endif // Q_OS_SYMBIAN && ORIENTATIONLOCK
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
#if defined(Q_OS_SYMBIAN) && defined(ORIENTATIONLOCK)
const CAknAppUiBase::TAppUiOrientation uiOrientation = CAknAppUi::EAppUiOrientationLandscape;
CAknAppUi* appUi = dynamic_cast<CAknAppUi*> (CEikonEnv::Static()->AppUi());
TRAPD(error,
if (appUi)
appUi->SetOrientationL(uiOrientation);
);
Q_UNUSED(error)
#endif // ORIENTATIONLOCK
const QSize screenSize(640, 360);
QGraphicsScene scene;
QGraphicsView view(&scene);
view.setFrameShape(QFrame::NoFrame);
view.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
view.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
QGraphicsWebView webview;
webview.resize(screenSize);
webview.load(QString::fromLatin1("html/examples/kitchensink/index.html"));
scene.addItem(&webview);
#if defined(Q_OS_SYMBIAN)
view.showFullScreen();
#elif defined(Q_WS_MAEMO_5)
view.showMaximized();
#else
view.resize(screenSize);
view.show();
#endif
return app.exec();
}
|
Remove second argument from VideoCapture_Reading perf test | #include "perf_precomp.hpp"
using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;
typedef std::tr1::tuple<String, bool> VideoCapture_Reading_t;
typedef perf::TestBaseWithParam<VideoCapture_Reading_t> VideoCapture_Reading;
PERF_TEST_P(VideoCapture_Reading, ReadFile,
testing::Combine( testing::Values( "highgui/video/big_buck_bunny.avi",
"highgui/video/big_buck_bunny.mov",
"highgui/video/big_buck_bunny.mp4",
"highgui/video/big_buck_bunny.mpg",
"highgui/video/big_buck_bunny.wmv" ),
testing::Values(true, true, true, true, true) ))
{
string filename = getDataPath(get<0>(GetParam()));
VideoCapture cap;
TEST_CYCLE() cap.open(filename);
bool dummy = cap.isOpened();
SANITY_CHECK(dummy);
}
| #include "perf_precomp.hpp"
using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;
typedef perf::TestBaseWithParam<String> VideoCapture_Reading;
PERF_TEST_P(VideoCapture_Reading, ReadFile, testing::Values( "highgui/video/big_buck_bunny.avi",
"highgui/video/big_buck_bunny.mov",
"highgui/video/big_buck_bunny.mp4",
"highgui/video/big_buck_bunny.mpg",
"highgui/video/big_buck_bunny.wmv" ) )
{
string filename = getDataPath(GetParam());
VideoCapture cap;
TEST_CYCLE() cap.open(filename);
bool dummy = cap.isOpened();
SANITY_CHECK(dummy);
}
|
Allow for struct padding in test | #include <stdio.h>
#include "Halide.h"
#define CHECK(f, s32, s64) \
static_assert(offsetof(buffer_t, f) == (sizeof(void*) == 8 ? (s64) : (s32)), #f " is wrong")
int main(int argc, char **argv) {
CHECK(dev, 0, 0);
CHECK(host, 8, 8);
CHECK(extent, 12, 16);
CHECK(stride, 28, 32);
CHECK(min, 44, 48);
CHECK(elem_size, 60, 64);
CHECK(host_dirty, 64, 68);
CHECK(dev_dirty, 65, 69);
CHECK(_padding, 66, 70);
static_assert(sizeof(buffer_t) == (sizeof(void*) == 8 ? 72 : 68), "size is wrong");
// Ensure alignment is at least that of a pointer.
static_assert(alignof(buffer_t) >= alignof(uint8_t*), "align is wrong");
printf("Success!\n");
return 0;
}
| #include <stdio.h>
#include "Halide.h"
#define CHECK(f, s32, s64) \
static_assert(offsetof(buffer_t, f) == (sizeof(void*) == 8 ? (s64) : (s32)), #f " is wrong")
int main(int argc, char **argv) {
CHECK(dev, 0, 0);
CHECK(host, 8, 8);
CHECK(extent, 12, 16);
CHECK(stride, 28, 32);
CHECK(min, 44, 48);
CHECK(elem_size, 60, 64);
CHECK(host_dirty, 64, 68);
CHECK(dev_dirty, 65, 69);
CHECK(_padding, 66, 70);
static_assert(sizeof(void*) == 8 ?
sizeof(buffer_t) == 72 :
// Some compilers may insert padding at the end of the struct
// so that an array will stay appropriately aligned for
// the int64 field.
(sizeof(buffer_t) == 68 || sizeof(buffer_t) == 72), "size is wrong");
// Ensure alignment is at least that of a pointer.
static_assert(alignof(buffer_t) >= alignof(uint8_t*), "align is wrong");
printf("Success!\n");
return 0;
}
|
Rename to match an LLVM change | //===-- TargetOptionsCommandFlags.cpp ---------------------------*- C++ -*-===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file exists as a place for global variables defined in LLVM's
// CodeGen/CommandFlags.def. By putting the resulting object file in
// an archive and linking with it, the definitions will automatically be
// included when needed and skipped when already present.
//
//===----------------------------------------------------------------------===//
#include "lld/Common/TargetOptionsCommandFlags.h"
#include "llvm/CodeGen/CommandFlags.def"
#include "llvm/Target/TargetOptions.h"
// Define an externally visible version of
// InitTargetOptionsFromCodeGenFlags, so that its functionality can be
// used without having to include llvm/CodeGen/CommandFlags.def, which
// would lead to multiple definitions of the command line flags.
llvm::TargetOptions lld::InitTargetOptionsFromCodeGenFlags() {
return ::InitTargetOptionsFromCodeGenFlags();
}
llvm::Optional<llvm::CodeModel::Model> lld::GetCodeModelFromCMModel() {
return getCodeModel();
}
std::string lld::GetCPUStr() { return ::getCPUStr(); }
| //===-- TargetOptionsCommandFlags.cpp ---------------------------*- C++ -*-===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file exists as a place for global variables defined in LLVM's
// CodeGen/CommandFlags.def. By putting the resulting object file in
// an archive and linking with it, the definitions will automatically be
// included when needed and skipped when already present.
//
//===----------------------------------------------------------------------===//
#include "lld/Common/TargetOptionsCommandFlags.h"
#include "llvm/CodeGen/CommandFlags.inc"
#include "llvm/Target/TargetOptions.h"
// Define an externally visible version of
// InitTargetOptionsFromCodeGenFlags, so that its functionality can be
// used without having to include llvm/CodeGen/CommandFlags.def, which
// would lead to multiple definitions of the command line flags.
llvm::TargetOptions lld::InitTargetOptionsFromCodeGenFlags() {
return ::InitTargetOptionsFromCodeGenFlags();
}
llvm::Optional<llvm::CodeModel::Model> lld::GetCodeModelFromCMModel() {
return getCodeModel();
}
std::string lld::GetCPUStr() { return ::getCPUStr(); }
|
Make a test more explicit. NFC. | // Tests for instrumentation of C++ constructors and destructors.
//
// RUN: %clang_cc1 -triple x86_64-apple-macosx10.11.0 -x c++ %s -o - -emit-llvm -fprofile-instrument=clang | FileCheck %s
struct Foo {
Foo() {}
Foo(int) {}
~Foo() {}
};
struct Bar : public Foo {
Bar() {}
Bar(int x) : Foo(x) {}
~Bar();
};
Foo foo;
Foo foo2(1);
Bar bar;
// Profile data for complete constructors and destructors must absent.
// CHECK-NOT: @__profc__ZN3FooC1Ev
// CHECK-NOT: @__profc__ZN3FooC1Ei
// CHECK-NOT: @__profc__ZN3FooD1Ev
// CHECK-NOT: @__profc__ZN3BarC1Ev
// CHECK-NOT: @__profc__ZN3BarD1Ev
// CHECK-NOT: @__profc__ZN3FooD1Ev
int main() {
}
| // Tests for instrumentation of C++ constructors and destructors.
//
// RUN: %clang_cc1 -triple x86_64-apple-macosx10.11.0 -x c++ %s -o %t -emit-llvm -fprofile-instrument=clang
// RUN: FileCheck %s -input-file=%t -check-prefix=INSTR
// RUN: FileCheck %s -input-file=%t -check-prefix=NOINSTR
struct Foo {
Foo() {}
Foo(int) {}
~Foo() {}
};
struct Bar : public Foo {
Bar() {}
Bar(int x) : Foo(x) {}
~Bar();
};
Foo foo;
Foo foo2(1);
Bar bar;
// Profile data for complete constructors and destructors must absent.
// INSTR: @__profc_main =
// INSTR: @__profc__ZN3FooC2Ev =
// INSTR: @__profc__ZN3FooD2Ev =
// INSTR: @__profc__ZN3FooC2Ei =
// INSTR: @__profc__ZN3BarC2Ev =
// NOINSTR-NOT: @__profc__ZN3FooC1Ev
// NOINSTR-NOT: @__profc__ZN3FooC1Ei
// NOINSTR-NOT: @__profc__ZN3FooD1Ev
// NOINSTR-NOT: @__profc__ZN3BarC1Ev
// NOINSTR-NOT: @__profc__ZN3BarD1Ev
// NOINSTR-NOT: @__profc__ZN3FooD1Ev
int main() {
}
|
Print Preview: Fix typo from r78639. | // 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 "chrome/browser/ui/webui/print_preview_ui.h"
#include "base/values.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/print_preview_handler.h"
#include "chrome/browser/ui/webui/print_preview_ui_html_source.h"
#include "content/browser/browser_thread.h"
#include "content/browser/tab_contents/tab_contents.h"
PrintPreviewUI::PrintPreviewUI(TabContents* contents)
: WebUI(contents),
html_source_(new PrintPreviewUIHTMLSource()) {
// PrintPreviewUI owns |handler|.
PrintPreviewHandler* handler = new PrintPreviewHandler();
AddMessageHandler(handler->Attach(this));
// Set up the chrome://print/ source.
contents->profile()->GetChromeURLDataManager()->AddDataSource(html_source_);
}
PrintPreviewUI::~PrintPreviewUI() {
}
PrintPreviewUIHTMLSource* PrintPreviewUI::html_source() {
return html_source_.get();
}
void PrintPreviewUI::PreviewDataIsAvailable(int expected_pages_count) {
FundamentalValue pages_count(expected_pages_count);
CallJavascriptFunction("createPDFPlugin", pages_count);
}
| // 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 "chrome/browser/ui/webui/print_preview_ui.h"
#include "base/values.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/print_preview_handler.h"
#include "chrome/browser/ui/webui/print_preview_ui_html_source.h"
#include "content/browser/browser_thread.h"
#include "content/browser/tab_contents/tab_contents.h"
PrintPreviewUI::PrintPreviewUI(TabContents* contents)
: WebUI(contents),
html_source_(new PrintPreviewUIHTMLSource()) {
// PrintPreviewUI owns |handler|.
PrintPreviewHandler* handler = new PrintPreviewHandler();
AddMessageHandler(handler->Attach(this));
// Set up the chrome://print/ source.
contents->profile()->GetChromeURLDataManager()->AddDataSource(html_source_);
}
PrintPreviewUI::~PrintPreviewUI() {
}
PrintPreviewUIHTMLSource* PrintPreviewUI::html_source() {
return html_source_.get();
}
void PrintPreviewUI::PreviewDataIsAvailable(int expected_pages_count) {
FundamentalValue pages_count(expected_pages_count);
CallJavascriptFunction("updatePrintPreview", pages_count);
}
|
Replace the alpha calculator with winner-takes-all | #include "TilePartitionerBase.h"
void TilePartitionerBase::applyWeights(const std::vector<float>& weights, std::vector<sf::Uint8>& alphas)
{
int err = 255;
float total_weight = 0.f;
for (auto weight : weights)
total_weight += weight;
if (total_weight == 0.f)
{
// This shouldn't happen, but it is easy to make weight masks
// where this does happen.
for (auto& alpha : alphas)
{
alpha = 0;
}
return;
}
for (size_t i = 0; i < weights.size(); i++)
{
int alpha = (int)((255 * weights[i]) / total_weight);
err -= alpha;
alphas[i] = (sf::Uint8)alpha;
}
size_t i = 0;
while (err > 0)
{
sf::Uint8& alpha = alphas[i%alphas.size()];
if (alpha > 0)
{
alpha++;
err--;
}
i++;
}
}
TilePartitionerBase::TilePartitionerBase(const Options & options) :
mOptions(options)
{
}
TilePartitionerBase::~TilePartitionerBase()
{
} | #include "TilePartitionerBase.h"
void TilePartitionerBase::applyWeights(const std::vector<float>& weights, std::vector<sf::Uint8>& alphas)
{
int err = 255;
float total_weight = 0.f;
for (auto weight : weights)
total_weight += weight;
for (auto& alpha : alphas)
{
alpha = 0;
}
if (total_weight == 0.f)
{
// This shouldn't happen, but it is easy to make weight masks
// where this does happen.
return;
}
else
{
size_t max_idx = -1;
float max_weight = -1.;
for (size_t i = 0; i < weights.size(); i++)
{
if (weights[i] > max_weight)
{
max_idx = i;
max_weight = weights[i];
}
}
alphas[max_idx] = 255;
}
//for (size_t i = 0; i < weights.size(); i++)
//{
// int alpha = (int)((255 * weights[i]) / total_weight);
// err -= alpha;
// alphas[i] = (sf::Uint8)alpha;
//}
//size_t i = 0;
//while (err > 0)
//{
// sf::Uint8& alpha = alphas[i%alphas.size()];
// if (alpha > 0)
// {
// alpha++;
// err--;
// }
// i++;
//}
}
TilePartitionerBase::TilePartitionerBase(const Options & options) :
mOptions(options)
{
}
TilePartitionerBase::~TilePartitionerBase()
{
} |
Replace manual locking by ScopedLock | #include "capu/util/ConsoleLogAppender.h"
#include "capu/util/LogMessage.h"
#include "capu/os/Console.h"
#include "capu/os/Time.h"
#include <stdio.h>
namespace capu
{
Mutex ConsoleLogAppender::m_logMutex;
ConsoleLogAppender::~ConsoleLogAppender()
{
}
void ConsoleLogAppender::logMessage(const LogMessage& logMessage)
{
m_logMutex.lock();
const uint64_t now = Time::GetMilliseconds();
Console::Print(Console::WHITE, "%.3f ", now/1000.0);
switch(logMessage.getLogLevel())
{
case LL_TRACE:
Console::Print(Console::WHITE, "[ Trace ] ");
break;
default:
case LL_DEBUG :
Console::Print(Console::WHITE, "[ Debug ] ");
break;
case LL_INFO :
Console::Print(Console::GREEN, "[ Info ] ");
break;
case LL_WARN :
Console::Print(Console::YELLOW, "[ Warn ] ");
break;
case LL_ERROR :
Console::Print(Console::RED, "[ Error ] ");
break;
case LL_FATAL :
Console::Print(Console::RED, "[ Fatal ] ");
break;
}
Console::Print(Console::AQUA, logMessage.getContext().getContextName().c_str());
Console::Print(" | %s\n", logMessage.getLogMessage());
Console::Flush();
m_logMutex.unlock();
}
}
| #include "capu/util/ConsoleLogAppender.h"
#include "capu/util/LogMessage.h"
#include "capu/util/ScopedLock.h"
#include "capu/os/Console.h"
#include "capu/os/Time.h"
#include <stdio.h>
namespace capu
{
Mutex ConsoleLogAppender::m_logMutex;
ConsoleLogAppender::~ConsoleLogAppender()
{
}
void ConsoleLogAppender::logMessage(const LogMessage& logMessage)
{
ScopedMutexLock lock(m_logMutex);
const uint64_t now = Time::GetMilliseconds();
Console::Print(Console::WHITE, "%.3f ", now/1000.0);
switch(logMessage.getLogLevel())
{
case LL_TRACE:
Console::Print(Console::WHITE, "[ Trace ] ");
break;
default:
case LL_DEBUG :
Console::Print(Console::WHITE, "[ Debug ] ");
break;
case LL_INFO :
Console::Print(Console::GREEN, "[ Info ] ");
break;
case LL_WARN :
Console::Print(Console::YELLOW, "[ Warn ] ");
break;
case LL_ERROR :
Console::Print(Console::RED, "[ Error ] ");
break;
case LL_FATAL :
Console::Print(Console::RED, "[ Fatal ] ");
break;
}
Console::Print(Console::AQUA, logMessage.getContext().getContextName().c_str());
Console::Print(" | %s\n", logMessage.getLogMessage());
Console::Flush();
}
}
|
Correct wrong type of variables 'number' and 'x' (int->double) | #include<cmath>
#include<iostream>
using namespace std;
bool isPrimeBruteForce(int x)
{
if (x < 2)
return false;
float 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[])
{
int 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<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;
}
|
Fix bug where uninitialized index buffers still wouldn't work after initialization |
#include "CIndexBuffer.h"
#include <glad/glad.h>
namespace ion
{
namespace Graphics
{
namespace GL
{
void CIndexBuffer::UploadData(void const * Data, size_t const Elements, EValueType const ValueType)
{
CheckedGLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, Handle));
CheckedGLCall(glBufferData(GL_ELEMENT_ARRAY_BUFFER, Elements * GetValueTypeSize(ValueType), Data, GL_STATIC_DRAW));
CheckedGLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0));
}
}
}
}
|
#include "CIndexBuffer.h"
#include <glad/glad.h>
namespace ion
{
namespace Graphics
{
namespace GL
{
void CIndexBuffer::UploadData(void const * Data, size_t const Elements, EValueType const ValueType)
{
CheckedGLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, Handle));
CheckedGLCall(glBufferData(GL_ELEMENT_ARRAY_BUFFER, Elements * GetValueTypeSize(ValueType), Data, GL_STATIC_DRAW));
CheckedGLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0));
Size = Elements;
}
}
}
}
|
Put nodes into middle of scene to improve zooming | #include "MainWindow.h"
#include "ui_MainWindow.h"
#include "CuteNode.h"
#include "NodeScene.h"
MainWindow::MainWindow(QWidget* parent)
: QMainWindow(parent)
, _scene{std::make_unique<NodeScene>(QRectF(0.0, 0.0, 3000.0, 3000.0))}
, _ui{std::make_unique<Ui::MainWindow>()}
{
_ui->setupUi(this);
for (int i=0; i<5; ++i)
{
CuteNode* node = new CuteNode;
node->setPos(i*300.0, 300.0);
_scene->addItem(node);
}
_ui->nodeView->setScene(_scene.get());
_ui->nodeView->centerOn(0.0, 0.0);
connect(_ui->actionToggleSnap, &QAction::triggered, _scene.get(), &NodeScene::toggleGridSnapping);
connect(_ui->actionToggleOverlap, &QAction::triggered, _scene.get(), &NodeScene::toggleNodeOverlap);
}
MainWindow::~MainWindow()
{
}
void MainWindow::on_actionAddNode_triggered()
{
CuteNode* node = new CuteNode;
node->setPos(500, 300);
_scene->addItem(node);
}
| #include "MainWindow.h"
#include "ui_MainWindow.h"
#include "CuteNode.h"
#include "NodeScene.h"
MainWindow::MainWindow(QWidget* parent)
: QMainWindow(parent)
, _scene{std::make_unique<NodeScene>(QRectF(0.0, 0.0, 3000.0, 3000.0))}
, _ui{std::make_unique<Ui::MainWindow>()}
{
_ui->setupUi(this);
for (int i=3; i<8; ++i)
{
CuteNode* node = new CuteNode;
node->setPos(i*300.0, 1000.0);
_scene->addItem(node);
}
_ui->nodeView->setScene(_scene.get());
_ui->nodeView->centerOn(1000.0, 1000.0);
connect(_ui->actionToggleSnap, &QAction::triggered, _scene.get(), &NodeScene::toggleGridSnapping);
connect(_ui->actionToggleOverlap, &QAction::triggered, _scene.get(), &NodeScene::toggleNodeOverlap);
}
MainWindow::~MainWindow()
{
}
void MainWindow::on_actionAddNode_triggered()
{
CuteNode* node = new CuteNode;
node->setPos(500, 300);
_scene->addItem(node);
}
|
Use new website macro instead | #include "command.h"
#include "../CommandHandler.h"
#include "../option.h"
/* full name of the command */
_CMDNAME("manual");
/* description of the command */
_CMDDESCR("view the lynxbot manual");
/* command usage synopsis */
_CMDUSAGE("$manual");
/* manual: view the lynxbot manual */
std::string CommandHandler::manual(char *out, struct command *c)
{
int opt;
static struct option long_opts[] = {
{ "help", NO_ARG, 'h' },
{ 0, 0, 0 }
};
opt_init();
while ((opt = getopt_long(c->argc, c->argv, "", long_opts)) != EOF) {
switch (opt) {
case 'h':
_HELPMSG(out, _CMDNAME, _CMDUSAGE, _CMDDESCR);
return "";
case '?':
_sprintf(out, MAX_MSG, "%s", opterr());
return "";
default:
return "";
}
}
if (optind != c->argc)
_USAGEMSG(out, _CMDNAME, _CMDUSAGE);
else
_sprintf(out, MAX_MSG, "[MANUAL] %s/manual/index.html",
BOT_WEBSITE);
return "";
}
| #include "command.h"
#include "../CommandHandler.h"
#include "../option.h"
/* full name of the command */
_CMDNAME("manual");
/* description of the command */
_CMDDESCR("view the lynxbot manual");
/* command usage synopsis */
_CMDUSAGE("$manual");
/* manual: view the lynxbot manual */
std::string CommandHandler::manual(char *out, struct command *c)
{
int opt;
static struct option long_opts[] = {
{ "help", NO_ARG, 'h' },
{ 0, 0, 0 }
};
opt_init();
while ((opt = getopt_long(c->argc, c->argv, "", long_opts)) != EOF) {
switch (opt) {
case 'h':
_HELPMSG(out, _CMDNAME, _CMDUSAGE, _CMDDESCR);
return "";
case '?':
_sprintf(out, MAX_MSG, "%s", opterr());
return "";
default:
return "";
}
}
if (optind != c->argc)
_USAGEMSG(out, _CMDNAME, _CMDUSAGE);
else
_sprintf(out, MAX_MSG, "[MANUAL] %s/manual/index.html",
_BOT_WEBSITE);
return "";
}
|
Use InMemory TagDatabase by default if none exists | #include "tag-database-factory.h"
#include "tag-database-in-memory.h"
#include "tag-database-sqlite.h"
#include <QFile>
TagDatabase *TagDatabaseFactory::Create(QString directory)
{
if (!directory.endsWith("/") && !directory.endsWith("\\"))
directory += "/";
QString typesFile = directory + "tag-types.txt";
if (QFile::exists(directory + "tags.txt"))
return new TagDatabaseInMemory(typesFile, directory + "tags.txt");
return new TagDatabaseSqlite(typesFile, directory + "tags.db");
}
| #include "tag-database-factory.h"
#include "tag-database-in-memory.h"
#include "tag-database-sqlite.h"
#include <QFile>
TagDatabase *TagDatabaseFactory::Create(QString directory)
{
if (!directory.endsWith("/") && !directory.endsWith("\\"))
directory += "/";
QString typesFile = directory + "tag-types.txt";
if (QFile::exists(directory + "tags.db"))
return new TagDatabaseSqlite(typesFile, directory + "tags.db");
return new TagDatabaseInMemory(typesFile, directory + "tags.txt");
}
|
Fix memory leak in float literal parsing Issue=93 | //
// Copyright (c) 2010 The ANGLE Project 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 <math.h>
#include <stdlib.h>
#include "util.h"
#ifdef _MSC_VER
#include <locale.h>
#else
#include <sstream>
#endif
double atof_dot(const char *str)
{
#ifdef _MSC_VER
return _atof_l(str, _create_locale(LC_NUMERIC, "C"));
#else
double result;
std::istringstream s(str);
std::locale l("C");
s.imbue(l);
s >> result;
return result;
#endif
}
| //
// Copyright (c) 2010 The ANGLE Project 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 <math.h>
#include <stdlib.h>
#include "util.h"
#ifdef _MSC_VER
#include <locale.h>
#else
#include <sstream>
#endif
double atof_dot(const char *str)
{
#ifdef _MSC_VER
_locale_t l = _create_locale(LC_NUMERIC, "C");
double result = _atof_l(str, l);
_free_locale(l);
return result;
#else
double result;
std::istringstream s(str);
std::locale l("C");
s.imbue(l);
s >> result;
return result;
#endif
}
|
Fix EncryptString call that should be a DecryptString call | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync/glue/chrome_encryptor.h"
#include "chrome/browser/password_manager/encryptor.h"
namespace browser_sync {
ChromeEncryptor::~ChromeEncryptor() {}
bool ChromeEncryptor::EncryptString(const std::string& plaintext,
std::string* ciphertext) {
return ::Encryptor::EncryptString(plaintext, ciphertext);
}
bool ChromeEncryptor::DecryptString(const std::string& ciphertext,
std::string* plaintext) {
return ::Encryptor::EncryptString(ciphertext, plaintext);
}
} // namespace browser_sync
| // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync/glue/chrome_encryptor.h"
#include "chrome/browser/password_manager/encryptor.h"
namespace browser_sync {
ChromeEncryptor::~ChromeEncryptor() {}
bool ChromeEncryptor::EncryptString(const std::string& plaintext,
std::string* ciphertext) {
return ::Encryptor::EncryptString(plaintext, ciphertext);
}
bool ChromeEncryptor::DecryptString(const std::string& ciphertext,
std::string* plaintext) {
return ::Encryptor::DecryptString(ciphertext, plaintext);
}
} // namespace browser_sync
|
Fix the CanvasKit viewer build | /*
* Copyright 2020 Google LLC
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <emscripten.h>
#include <emscripten/bind.h>
#include "tools/viewer/SampleSlide.h"
#include <string>
using namespace emscripten;
EMSCRIPTEN_BINDINGS(Viewer) {
function("MakeSlide", optional_override([](std::string name)->sk_sp<Slide> {
if (name == "WavyPathText") {
extern Sample* MakeWavyPathTextSample();
return sk_make_sp<SampleSlide>(MakeWavyPathTextSample);
}
return nullptr;
}));
class_<Slide>("Slide")
.smart_ptr<sk_sp<Slide>>("sk_sp<Slide>")
.function("load", &Slide::load)
.function("animate", &Slide::animate)
.function("draw", optional_override([](Slide& self, SkCanvas& canvas) {
self.draw(&canvas);
}));
}
| /*
* Copyright 2020 Google LLC
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <emscripten.h>
#include <emscripten/bind.h>
#include "include/core/SkCanvas.h"
#include "tools/viewer/SampleSlide.h"
#include <string>
using namespace emscripten;
EMSCRIPTEN_BINDINGS(Viewer) {
function("MakeSlide", optional_override([](std::string name)->sk_sp<Slide> {
if (name == "WavyPathText") {
extern Sample* MakeWavyPathTextSample();
return sk_make_sp<SampleSlide>(MakeWavyPathTextSample);
}
return nullptr;
}));
class_<Slide>("Slide")
.smart_ptr<sk_sp<Slide>>("sk_sp<Slide>")
.function("load", &Slide::load)
.function("animate", &Slide::animate)
.function("draw", optional_override([](Slide& self, SkCanvas& canvas) {
self.draw(&canvas);
}));
}
|
Make gui window a bit more responsive | #include "ofMain.h"
#include "ofApp.h"
#include "ofAppGLFWWindow.h"
int main() {
ofGLFWWindowSettings settings;
settings.width = 1280;
settings.height = 720;
settings.setPosition(ofVec2f(300,0));
settings.resizable = true;
shared_ptr<ofAppBaseWindow> mainWindow = ofCreateWindow(settings);
mainWindow->setFullscreen(true);
settings.width = 500;
settings.height = 900;
settings.setPosition(ofVec2f(0,0));
settings.shareContextWith = mainWindow;
shared_ptr<ofAppBaseWindow> guiWindow = ofCreateWindow(settings);
shared_ptr<ofApp> mainApp(new ofApp);
mainApp->setupGui();
ofAddListener(guiWindow->events().draw, mainApp.get(), &ofApp::drawGui);
ofAddListener(guiWindow->events().keyPressed, mainApp.get(), &ofApp::guiKeyPressed);
ofRunApp(mainWindow, mainApp);
ofRunMainLoop();
}
| #include "ofMain.h"
#include "ofApp.h"
#include "ofAppGLFWWindow.h"
int main() {
ofGLFWWindowSettings settings;
settings.width = 1280;
settings.height = 720;
settings.setPosition(ofVec2f(300,0));
settings.resizable = true;
shared_ptr<ofAppBaseWindow> mainWindow = ofCreateWindow(settings);
mainWindow->setFullscreen(true);
settings.width = 500;
settings.height = ofGetScreenHeight();
settings.setPosition(ofVec2f(0,0));
settings.shareContextWith = mainWindow;
shared_ptr<ofAppBaseWindow> guiWindow = ofCreateWindow(settings);
shared_ptr<ofApp> mainApp(new ofApp);
mainApp->setupGui();
ofAddListener(guiWindow->events().draw, mainApp.get(), &ofApp::drawGui);
ofAddListener(guiWindow->events().keyPressed, mainApp.get(), &ofApp::guiKeyPressed);
ofRunApp(mainWindow, mainApp);
ofRunMainLoop();
}
|
Append a size_t to a string in the correct way, using std::to_string. | #include "../kontsevich_graph_series.hpp"
#include <ginac/ginac.h>
#include <iostream>
using namespace std;
using namespace GiNaC;
size_t order = 2;
int main()
{
// Compute relevant primes
map< size_t, set<KontsevichGraph> > primes;
for (size_t n = 0; n <= order; ++n)
{
primes[n] = KontsevichGraph::graphs(n, 2, true, true,
[](KontsevichGraph g) -> bool
{
return g.positive_differential_order() && g.is_prime();
});
}
// Make a table of (symbolic) weights
map<KontsevichGraph, symbol> weights;
size_t weight_count = 0;
for (size_t n = 0; n <= order; ++n)
{
for (KontsevichGraph g : primes[n])
{
weights[g] = symbol("w_" + weight_count++);
}
}
KontsevichGraphSeries<symbol> star_product;
}
| #include "../kontsevich_graph_series.hpp"
#include <ginac/ginac.h>
#include <iostream>
using namespace std;
using namespace GiNaC;
size_t order = 2;
int main()
{
// Compute relevant primes
map< size_t, set<KontsevichGraph> > primes;
for (size_t n = 0; n <= order; ++n)
{
primes[n] = KontsevichGraph::graphs(n, 2, true, true,
[](KontsevichGraph g) -> bool
{
return g.positive_differential_order() && g.is_prime();
});
}
// Make a table of (symbolic) weights
map<KontsevichGraph, symbol> weights;
size_t weight_count = 0;
for (size_t n = 0; n <= order; ++n)
{
for (KontsevichGraph g : primes[n])
{
weights[g] = symbol("w_" + to_string(weight_count++));
}
}
KontsevichGraphSeries<symbol> star_product;
}
|
Fix license in settings example. | /* * This file is part of meego-im-framework *
*
* Copyright (C) 2012 Mattia Barbon <mattia@develer.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 "mainwindow.h"
#include <QApplication>
#if (defined(Q_WS_QPA) || defined(Q_WS_QWS)) && (QT_VERSION < 0x050000)
#include <QInputContextFactory>
#endif
int main(int argc, char **argv)
{
QApplication kit(argc, argv);
#if (defined(Q_WS_QPA) || defined(Q_WS_QWS)) && (QT_VERSION < 0x050000)
// Workaround for lighthouse Qt
kit.setInputContext(QInputContextFactory::create("Maliit", &kit));
#endif
MainWindow settings;
settings.show();
kit.exec();
}
| /* This file is part of Maliit framework
*
* Copyright (C) 2012 Mattia Barbon <mattia@develer.com>
*
* Contact: maliit-discuss@lists.maliit.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the licence, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#include "mainwindow.h"
#include <QApplication>
#if (defined(Q_WS_QPA) || defined(Q_WS_QWS)) && (QT_VERSION < 0x050000)
#include <QInputContextFactory>
#endif
int main(int argc, char **argv)
{
QApplication kit(argc, argv);
#if (defined(Q_WS_QPA) || defined(Q_WS_QWS)) && (QT_VERSION < 0x050000)
// Workaround for lighthouse Qt
kit.setInputContext(QInputContextFactory::create("Maliit", &kit));
#endif
MainWindow settings;
settings.show();
kit.exec();
}
|
Use random for software rendering demo | #define FPL_AUTO_NAMESPACE
#include <final_platform_layer.hpp>
int main(int argc, char **args) {
Settings settings = DefaultSettings();
CopyAnsiString("Software Rendering Example", settings.window.windowTitle, FPL_ARRAYCOUNT(settings.window.windowTitle) - 1);
settings.video.driverType = VideoDriverType::Software;
if (InitPlatform(InitFlags::Video, settings)) {
VideoBackBuffer *videoContext = GetVideoBackBuffer();
while (WindowUpdate()) {
uint32_t *p = videoContext->pixels;
for (uint32_t y = 0; y < videoContext->height; ++y) {
uint32_t color = 0xFFFF0000;
for (uint32_t x = 0; x < videoContext->width; ++x) {
*p++ = color;
}
}
WindowFlip();
}
ReleasePlatform();
}
return 0;
} | #define FPL_AUTO_NAMESPACE
#include <final_platform_layer.hpp>
struct RandomSeries {
uint16_t index;
};
static uint16_t RandomU16(RandomSeries &series) {
series.index ^= (series.index << 13);
series.index ^= (series.index >> 9);
series.index ^= (series.index << 7);
return (series.index);
}
static uint8_t RandomByte(RandomSeries &series) {
uint8_t result = RandomU16(series) % UINT8_MAX;
return(result);
}
int main(int argc, char **args) {
Settings settings = DefaultSettings();
CopyAnsiString("Software Rendering Example", settings.window.windowTitle, FPL_ARRAYCOUNT(settings.window.windowTitle) - 1);
settings.video.driverType = VideoDriverType::Software;
if (InitPlatform(InitFlags::Video, settings)) {
RandomSeries series = {1337};
VideoBackBuffer *videoContext = GetVideoBackBuffer();
while (WindowUpdate()) {
uint32_t *p = videoContext->pixels;
for (uint32_t y = 0; y < videoContext->height; ++y) {
for (uint32_t x = 0; x < videoContext->width; ++x) {
uint8_t r = RandomByte(series);
uint8_t g = RandomByte(series);
uint8_t b = RandomByte(series);
uint32_t color = (0xFF << 24) | (r << 16) | (g << 8) | b;
*p++ = color;
}
}
WindowFlip();
}
ReleasePlatform();
}
return 0;
} |
Remove unneeded include which is breaking build. | /*
* 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 "SkFontHost.h"
#include "SkTypeface.h"
#include "SkTypeface_win.h"
//static
void SkFontHost::EnsureTypefaceAccessible(const SkTypeface& typeface) {
//No sandbox, nothing to do.
}
| /*
* 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 "SkFontHost.h"
#include "SkTypeface.h"
//static
void SkFontHost::EnsureTypefaceAccessible(const SkTypeface& typeface) {
//No sandbox, nothing to do.
}
|
Remove duplicate brush color set in glyph paint cycle box. | #include "side_pane.hpp"
#include <cppurses/painter/color.hpp>
#include <cppurses/painter/glyph.hpp>
#include <cppurses/widget/widgets/text_display.hpp>
using namespace cppurses;
namespace demos {
namespace glyph_paint {
Side_pane::Side_pane() {
this->width_policy.fixed(16);
space1.wallpaper = L'─';
space2.wallpaper = L'─';
glyph_select.height_policy.preferred(6);
color_select_stack.height_policy.fixed(3);
for (auto& child : color_select_stack.top_row.children.get()) {
child->brush.set_background(Color::Light_gray);
child->brush.set_foreground(Color::Black);
}
show_glyph.height_policy.fixed(1);
show_glyph.set_alignment(Alignment::Center);
}
} // namespace glyph_paint
} // namespace demos
| #include "side_pane.hpp"
#include <cppurses/painter/color.hpp>
#include <cppurses/painter/glyph.hpp>
#include <cppurses/widget/widgets/text_display.hpp>
using namespace cppurses;
namespace demos {
namespace glyph_paint {
Side_pane::Side_pane() {
this->width_policy.fixed(16);
space1.wallpaper = L'─';
space2.wallpaper = L'─';
glyph_select.height_policy.preferred(6);
color_select_stack.height_policy.fixed(3);
show_glyph.height_policy.fixed(1);
show_glyph.set_alignment(Alignment::Center);
}
} // namespace glyph_paint
} // namespace demos
|
Remove unneeded include which is breaking build. | /*
* 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 "SkFontHost.h"
#include "SkTypeface.h"
#include "SkTypeface_win.h"
//static
void SkFontHost::EnsureTypefaceAccessible(const SkTypeface& typeface) {
//No sandbox, nothing to do.
}
| /*
* 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 "SkFontHost.h"
#include "SkTypeface.h"
//static
void SkFontHost::EnsureTypefaceAccessible(const SkTypeface& typeface) {
//No sandbox, nothing to do.
}
|
Fix an ASAN failure in //third_party/quic/core:tls_server_handshaker_test by always setting *cert_matched_sni in GetCertChain(). | // Copyright (c) 2017 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 "quic/test_tools/failing_proof_source.h"
#include "absl/strings/string_view.h"
namespace quic {
namespace test {
void FailingProofSource::GetProof(const QuicSocketAddress& /*server_address*/,
const QuicSocketAddress& /*client_address*/,
const std::string& /*hostname*/,
const std::string& /*server_config*/,
QuicTransportVersion /*transport_version*/,
absl::string_view /*chlo_hash*/,
std::unique_ptr<Callback> callback) {
callback->Run(false, nullptr, QuicCryptoProof(), nullptr);
}
QuicReferenceCountedPointer<ProofSource::Chain>
FailingProofSource::GetCertChain(const QuicSocketAddress& /*server_address*/,
const QuicSocketAddress& /*client_address*/,
const std::string& /*hostname*/,
bool* /*cert_matched_sni*/) {
return QuicReferenceCountedPointer<Chain>();
}
void FailingProofSource::ComputeTlsSignature(
const QuicSocketAddress& /*server_address*/,
const QuicSocketAddress& /*client_address*/,
const std::string& /*hostname*/,
uint16_t /*signature_algorithm*/,
absl::string_view /*in*/,
std::unique_ptr<SignatureCallback> callback) {
callback->Run(false, "", nullptr);
}
} // namespace test
} // namespace quic
| // Copyright (c) 2017 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 "quic/test_tools/failing_proof_source.h"
#include "absl/strings/string_view.h"
namespace quic {
namespace test {
void FailingProofSource::GetProof(const QuicSocketAddress& /*server_address*/,
const QuicSocketAddress& /*client_address*/,
const std::string& /*hostname*/,
const std::string& /*server_config*/,
QuicTransportVersion /*transport_version*/,
absl::string_view /*chlo_hash*/,
std::unique_ptr<Callback> callback) {
callback->Run(false, nullptr, QuicCryptoProof(), nullptr);
}
QuicReferenceCountedPointer<ProofSource::Chain>
FailingProofSource::GetCertChain(const QuicSocketAddress& /*server_address*/,
const QuicSocketAddress& /*client_address*/,
const std::string& /*hostname*/,
bool* cert_matched_sni) {
*cert_matched_sni = false;
return QuicReferenceCountedPointer<Chain>();
}
void FailingProofSource::ComputeTlsSignature(
const QuicSocketAddress& /*server_address*/,
const QuicSocketAddress& /*client_address*/,
const std::string& /*hostname*/,
uint16_t /*signature_algorithm*/,
absl::string_view /*in*/,
std::unique_ptr<SignatureCallback> callback) {
callback->Run(false, "", nullptr);
}
} // namespace test
} // namespace quic
|
Add tests for row vector and array | #include <test/unit/math/test_ad.hpp>
TEST(MathMixMatFun, reverse) {
auto f = [](const auto& x) { return stan::math::reverse(x); };
// 0 x 0
Eigen::VectorXd x0(0);
stan::test::expect_ad(f, x0);
// 1 x 1
Eigen::VectorXd x1(1);
x1 << 1;
stan::test::expect_ad(f, x1);
// 4 x 4
Eigen::VectorXd x(4);
x << 1, 3, 4, -5;
stan::test::expect_ad(f, x);
}
| #include <test/unit/math/test_ad.hpp>
#include <vector>
TEST(MathMixMatFun, reverse_vector) {
auto f = [](const auto& x) { return stan::math::reverse(x); };
// 0 x 0
Eigen::VectorXd x0(0);
stan::test::expect_ad(f, x0);
// 1 x 1
Eigen::VectorXd x1(1);
x1 << 1;
stan::test::expect_ad(f, x1);
// 4 x 4
Eigen::VectorXd x(4);
x << 1, 3, 4, -5;
stan::test::expect_ad(f, x);
}
TEST(MathMixMatFun, reverse_row_vector) {
auto f = [](const auto& x) { return stan::math::reverse(x); };
// 0 x 0
Eigen::RowVectorXd x0(0);
stan::test::expect_ad(f, x0);
// 1 x 1
Eigen::RowVectorXd x1(1);
x1 << 1;
stan::test::expect_ad(f, x1);
// 4 x 4
Eigen::RowVectorXd x(4);
x << 1, 3, 4, -5;
stan::test::expect_ad(f, x);
}
TEST(MathMixMatFun, reverse_array) {
auto f = [](const auto& x) { return stan::math::reverse(x); };
// 0 x 0
std::vector<double> x0(0);
stan::test::expect_ad(f, x0);
// 1 x 1
std::vector<double> x1{1};
stan::test::expect_ad(f, x1);
// 4 x 4
std::vector<double> x{1, 3, 4, -5};
stan::test::expect_ad(f, x);
}
|
Add extra date range widget tests | /*=========================================================================
Library: CTK
Copyright (c) 2010 Kitware Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.commontk.org/LICENSE
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.
=========================================================================*/
// Qt includes
#include <QApplication>
// CTK includes
#include "ctkDateRangeWidget.h"
// STD includes
#include <cstdlib>
#include <iostream>
//-----------------------------------------------------------------------------
int ctkDateRangeWidgetTest1(int argc, char * argv [] )
{
QApplication app(argc, argv);
ctkDateRangeWidget dateRange;
dateRange.show();
return EXIT_SUCCESS;
}
| /*=========================================================================
Library: CTK
Copyright (c) 2010 Kitware Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.commontk.org/LICENSE
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.
=========================================================================*/
// Qt includes
#include <QApplication>
#include <QTimer>
// CTK includes
#include "ctkDateRangeWidget.h"
// STD includes
#include <cstdlib>
#include <iostream>
//-----------------------------------------------------------------------------
int ctkDateRangeWidgetTest1(int argc, char * argv [] )
{
QApplication app(argc, argv);
ctkDateRangeWidget dateRange;
dateRange.show();
dateRange.onToday();
dateRange.onYesterday();
dateRange.onAnyDate();
dateRange.onLastMonth();
dateRange.onLastWeek();
dateRange.onSelectRange();
return EXIT_SUCCESS;
}
|
Fix building of the engine | #include <iostream>
#include "Crown.h"
#include "lua.hpp"
#include <unistd.h>
using namespace crown;
static void report_errors(lua_State* state, const int status)
{
if (status != 0)
{
std::cerr << "-- " << lua_tostring(state, -1) << std::endl;
lua_pop(state, 1);
}
}
int main(int argc, char** argv)
{
lua_State* lua_state;
Filesystem fs("/home/mikymod/test/res_compiled");
FileResourceArchive archive(fs);
MallocAllocator allocator;
ResourceManager res_manager(archive, allocator);
ResourceId script = res_manager.load("lua/hello.lua");
res_manager.flush();
while (1)
{
if (res_manager.is_loaded(script))
{
lua_state = luaL_newstate();
luaL_openlibs(lua_state);
ScriptResource* resource = (ScriptResource*)res_manager.data(script);
int s = luaL_loadbuffer(lua_state, (char*)resource->data(), 47, "");
if (s == 0)
{
s = lua_pcall(lua_state, 0, LUA_MULTRET, 0);
}
report_errors(lua_state, s);
break;
}
}
lua_close(lua_state);
return 0;
}
| #include <iostream>
#include "Crown.h"
#include "lua.hpp"
#include <unistd.h>
using namespace crown;
static void report_errors(lua_State* state, const int status)
{
if (status != 0)
{
std::cerr << "-- " << lua_tostring(state, -1) << std::endl;
lua_pop(state, 1);
}
}
int main(int argc, char** argv)
{
lua_State* lua_state;
Filesystem fs("/home/mikymod/test/res_compiled");
FileResourceArchive archive(fs);
ResourceManager res_manager(archive);
ResourceId script = res_manager.load("lua/hello.lua");
res_manager.flush();
while (1)
{
if (res_manager.is_loaded(script))
{
lua_state = luaL_newstate();
luaL_openlibs(lua_state);
ScriptResource* resource = (ScriptResource*)res_manager.data(script);
int s = luaL_loadbuffer(lua_state, (char*)resource->data(), 47, "");
if (s == 0)
{
s = lua_pcall(lua_state, 0, LUA_MULTRET, 0);
}
report_errors(lua_state, s);
break;
}
}
lua_close(lua_state);
return 0;
}
|
Disable SIMD in jpeg turbo as suggested to check if that fixes the uninitialised memory issue. | #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
| #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() {
// Disable SIMD in jpeg turbo.
(void) putenv(const_cast<char *>("JSIMD_FORCENONE=1"));
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
|
Use mdiArea directly as the window's central widget | #include "main_window.hpp"
#include <QVBoxLayout>
#include <QMessageBox>
#include "executable_viewer.hpp"
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
setWindowTitle(QString("Interactive Executable Mangler"));
mdiArea = new QMdiArea();
QVBoxLayout *layout = new QVBoxLayout();
layout->addWidget(mdiArea);
QMenu *file = menuBar()->addMenu(QString("File"));
QWidget *central = new QWidget(this);
central->setLayout(layout);
setCentralWidget(central);
createActions();
file->addAction(newAction);
file->addAction(aboutAction);
}
void MainWindow::createActions()
{
newAction = new QAction(QString("New"), this);
aboutAction = new QAction(QString("About"), this);
connect(newAction, SIGNAL(triggered()), this, SLOT(newFile()));
connect(aboutAction, SIGNAL(triggered()), this, SLOT(about()));
}
void MainWindow::newFile()
{
QString filename("hacker.out");
ExecutableViewer *viewer = new ExecutableViewer(filename, mdiArea);
mdiArea->addSubWindow(viewer);
viewer->show();
mdiArea->tileSubWindows();
}
void MainWindow::about()
{
QMessageBox::about(this, QString("About"),
QString("<p>Ștefan Mirea & Adrian Dobrică 2016.</p><p><a "
"href=\"https://github.com/stefanmirea/mangler\""
">Click!</a></p>"));
}
| #include "main_window.hpp"
#include <QMessageBox>
#include "executable_viewer.hpp"
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
setWindowTitle(QString("Interactive Executable Mangler"));
mdiArea = new QMdiArea();
QMenu *file = menuBar()->addMenu(QString("File"));
setCentralWidget(mdiArea);
createActions();
file->addAction(newAction);
file->addAction(aboutAction);
}
void MainWindow::createActions()
{
newAction = new QAction(QString("New"), this);
aboutAction = new QAction(QString("About"), this);
connect(newAction, SIGNAL(triggered()), this, SLOT(newFile()));
connect(aboutAction, SIGNAL(triggered()), this, SLOT(about()));
}
void MainWindow::newFile()
{
QString filename("hacker.out");
ExecutableViewer *viewer = new ExecutableViewer(filename, mdiArea);
mdiArea->addSubWindow(viewer);
viewer->show();
mdiArea->tileSubWindows();
}
void MainWindow::about()
{
QMessageBox::about(this, QString("About"),
QString("<p>Ștefan Mirea & Adrian Dobrică 2016.</p><p><a "
"href=\"https://github.com/stefanmirea/mangler\""
">Click!</a></p>"));
}
|
Support signed numbers in imul | #include "common.th"
// c <- multiplicand
// d <- multiplier
// b -> product
.global imul
imul:
pushall(h,i)
i <- d == 0
jnzrel(i, L_done)
L_top:
h <- d & 1
i <- h <> 0
i <- c & i
b <- b + i
c <- c << 1
d <- d >> 1
i <- d <> 0
jnzrel(i, L_top)
L_done:
popall(h,i)
ret
| #include "common.th"
// c <- multiplicand
// d <- multiplier
// b -> product
.global imul
imul:
pushall(h,i,j,k)
i <- d == 0
jnzrel(i, L_done)
h <- 1
b <- 0
j <- c >> 31 // save sign bit in j
j <- -j // convert sign to flag
c <- c ^ j // adjust multiplicand
c <- c - j
k <- d >> 31 // save sign bit in k
k <- -k // convert sign to flag
d <- d ^ k // adjust multiplier
d <- d - k
j <- j ^ k // final flip flag is in j
L_top:
// use constant 1 in h to combine instructions
i <- d & h - 1
i <- c &~ i
b <- b + i
c <- c << 1
d <- d >> 1
i <- d <> 0
jnzrel(i, L_top)
L_done:
b <- b ^ j // adjust product for signed math
b <- b - j
popall(h,i,j,k)
ret
|
Test cereal for loading a constant variable (using a const_cast) | #include "UnitTest++/UnitTest++.h"
#include <fstream>
#include <cereal/archives/binary.hpp>
SUITE( CerealTest )
{
TEST( basicSaveAndLoad )
{
const std::string saveFileName = "CerealTest";
const int expectedData = 42;
int actualData = 666;
{
std::ofstream file( saveFileName, std::ios::binary );
CHECK( !file.fail() );
cereal::BinaryOutputArchive archive( file );
archive( expectedData );
}
{
std::ifstream file( saveFileName, std::ios::binary );
CHECK( !file.fail() );
cereal::BinaryInputArchive archive( file );
archive( actualData );
}
CHECK_EQUAL( expectedData, actualData );
// Delete save file
CHECK( !remove( saveFileName.data() ) ) ;
}
}
| #include "UnitTest++/UnitTest++.h"
#include <fstream>
#include <cereal/archives/binary.hpp>
class Base
{
public:
Base() : someConstant(1)
{
}
private:
const int someConstant;
friend cereal::access;
template < class Archive >
void serialize( Archive & ar )
{
ar( const_cast< int & >( someConstant ) );
}
};
SUITE( CerealTest )
{
TEST( basicSaveAndLoad )
{
const std::string saveFileName = "CerealTest";
const int expectedData = 42;
int actualData = 666;
{
std::ofstream file( saveFileName, std::ios::binary );
CHECK( !file.fail() );
cereal::BinaryOutputArchive archive( file );
archive( expectedData );
}
{
std::ifstream file( saveFileName, std::ios::binary );
CHECK( !file.fail() );
cereal::BinaryInputArchive archive( file );
archive( actualData );
}
CHECK_EQUAL( expectedData, actualData );
// Delete save file
CHECK( !remove( saveFileName.data() ) ) ;
}
TEST( loadConstantVariable )
{
const std::string saveFileName = "CerealTest";
const int expectedData = 42;
const int actualData = 666;
{
std::ofstream file( saveFileName, std::ios::binary );
CHECK( !file.fail() );
cereal::BinaryOutputArchive archive( file );
archive( expectedData );
}
{
std::ifstream file( saveFileName, std::ios::binary );
CHECK( !file.fail() );
cereal::BinaryInputArchive archive( file );
archive( const_cast< int & >( actualData ) );
}
CHECK_EQUAL( expectedData, actualData );
// Delete save file
CHECK( !remove( saveFileName.data() ) ) ;
}
}
|
Print variable debug output to stdout | #include "variables.hpp"
#ifdef _VARS
std::ostream& var_defs_stream = cerr;
#endif
| #include "variables.hpp"
#ifdef _VARS
std::ostream& var_defs_stream = cout;
#endif
|
Add licence (yes, this means that editinterface.cpp has no licence) | #include "editinterfaceext.h"
#include "document.h"
using namespace KTextEditor;
uint EditInterfaceExt::globalEditInterfaceExtNumber = 0;
EditInterfaceExt::EditInterfaceExt()
: d(0L)
{
globalEditInterfaceExtNumber++;
myEditInterfaceExtNumber = globalEditInterfaceExtNumber;
}
EditInterfaceExt::~EditInterfaceExt()
{
}
uint EditInterfaceExt::editInterfaceExtNumber() const
{
return myEditInterfaceExtNumber;
}
EditInterfaceExt *KTextEditor::editInterfaceExt (Document *doc)
{
if (!doc)
return 0;
return static_cast<EditInterfaceExt*>(doc->qt_cast("KTextEditor::EditInterfaceExt"));
}
| /* This file is part of the KDE libraries
Copyright (C) 2003 Hamish Rodda <rodda@kde.org>
Copyright (C) 2001 Christoph Cullmann <cullmann@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 as published by the Free Software Foundation.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include "editinterfaceext.h"
#include "document.h"
using namespace KTextEditor;
uint EditInterfaceExt::globalEditInterfaceExtNumber = 0;
EditInterfaceExt::EditInterfaceExt()
: d(0L)
{
globalEditInterfaceExtNumber++;
myEditInterfaceExtNumber = globalEditInterfaceExtNumber;
}
EditInterfaceExt::~EditInterfaceExt()
{
}
uint EditInterfaceExt::editInterfaceExtNumber() const
{
return myEditInterfaceExtNumber;
}
EditInterfaceExt *KTextEditor::editInterfaceExt (Document *doc)
{
if (!doc)
return 0;
return static_cast<EditInterfaceExt*>(doc->qt_cast("KTextEditor::EditInterfaceExt"));
}
|
Add -nologo in nmake command lines. | #include "NMakefile.hpp"
#include <configure/Build.hpp>
#include <configure/Filesystem.hpp>
#include <configure/quote.hpp>
namespace configure { namespace generators {
std::string NMakefile::name() const
{ return "NMakefile"; }
bool NMakefile::is_available(Build& build) const
{
return build.fs().which("nmake") != boost::none;
}
void NMakefile::dump_command(
std::ostream& out,
std::vector<std::string> const& cmd) const
{
out << quote<CommandParser::nmake>(cmd);
}
std::vector<std::string>
NMakefile::build_command(Build& build, std::string const& target) const
{
return {
"nmake", "-f", (build.directory() / "Makefile").string(),
target.empty() ? "all" : target
};
}
}}
| #include "NMakefile.hpp"
#include <configure/Build.hpp>
#include <configure/Filesystem.hpp>
#include <configure/quote.hpp>
namespace configure { namespace generators {
std::string NMakefile::name() const
{ return "NMakefile"; }
bool NMakefile::is_available(Build& build) const
{
return build.fs().which("nmake") != boost::none;
}
void NMakefile::dump_command(
std::ostream& out,
std::vector<std::string> const& cmd) const
{
out << quote<CommandParser::nmake>(cmd);
}
std::vector<std::string>
NMakefile::build_command(Build& build, std::string const& target) const
{
return {
"nmake", "-nologo", "-f", (build.directory() / "Makefile").string(),
target.empty() ? "all" : target
};
}
}}
|
Add logging to analysis for profiling | #include "analyzer.h"
#include "dal.h"
#include "glog.h"
#include <iostream>
namespace holmes {
kj::Promise<bool> Analyzer::run(DAL *dal) {
std::vector<Holmes::Fact::Reader> searchedFacts;
auto ctxs = dal->getFacts(premises);
kj::Array<kj::Promise<bool>> analResults =
KJ_MAP(ctx, ctxs) {
if (cache.miss(ctx)) {
auto req = analysis.analyzeRequest();
auto ctxBuilder = req.initContext(ctx.size());
auto dex = 0;
for (auto&& val : ctx) {
ctxBuilder.setWithCaveats(dex++, val);
}
return req.send().then([this, dal, ctx = kj::mv(ctx)](Holmes::Analysis::AnalyzeResults::Reader res){
auto dfs = res.getDerived();
bool dirty = false;
if (dal->setFacts(dfs) != 0) {
dirty = true;
}
cache.add(ctx);
return dirty;
});
}
return kj::Promise<bool>(false);
};
return kj::joinPromises(kj::mv(analResults)).then([this](kj::Array<bool> x){
bool dirty = false;
for (auto v : x) {
dirty |= v;
}
return dirty;
});
}
}
| #include "analyzer.h"
#include "dal.h"
#include "glog.h"
#include <iostream>
namespace holmes {
kj::Promise<bool> Analyzer::run(DAL *dal) {
std::vector<Holmes::Fact::Reader> searchedFacts;
DLOG(INFO) << "Starting analysis " << name;
DLOG(INFO) << "Getting facts for " << name;
auto ctxs = dal->getFacts(premises);
DLOG(INFO) << "Got facts for " << name;
kj::Array<kj::Promise<bool>> analResults =
KJ_MAP(ctx, ctxs) {
if (cache.miss(ctx)) {
auto req = analysis.analyzeRequest();
auto ctxBuilder = req.initContext(ctx.size());
auto dex = 0;
for (auto&& val : ctx) {
ctxBuilder.setWithCaveats(dex++, val);
}
return req.send().then([this, dal, ctx = kj::mv(ctx)](Holmes::Analysis::AnalyzeResults::Reader res){
auto dfs = res.getDerived();
bool dirty = false;
if (dal->setFacts(dfs) != 0) {
dirty = true;
}
cache.add(ctx);
return dirty;
});
}
return kj::Promise<bool>(false);
};
return kj::joinPromises(kj::mv(analResults)).then([this](kj::Array<bool> x){
bool dirty = false;
for (auto v : x) {
dirty |= v;
}
DLOG(INFO) << "Finished analysis " << name;
return dirty;
});
}
}
|
Update example to be actually somewhat useful | #include <PIDController.h>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
PIDController* pid = new PIDController(1,0,0,-100,100);
pid->on();
pid->targetSetpoint(100);
pid->off();
cout << "Hello World!" << endl;
return 0;
}
| #include <PIDController.h>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
PIDController* pid = new PIDController(5,0.5,0.25,-100,100);
pid->on(); // Turn PID controller on
pid->targetSetpoint(10); // Change desired setpoint to 10
double t = 0; // Init with time t=0
double controlVariable = 0; // Init with zero actuation
double processVariable = 0; // Init with zero position
while(1) {
controlVariable = pid->calc(processVariable); // Calculate next controlVariable
processVariable += controlVariable/(20 + ((rand() % 11) - 5)); // Arbitrary function to simulate a plant
cout << "Time: " << t << ", Setpoint: " << pid->getSetpoint() << ", PV: " << processVariable << endl;
usleep(100000); // 100ms delay to simulate actuation time
t += 0.1; // Increment time variable by 100ms
}
return 0;
}
|
Initialize libsodium in the gtest suite. | #include "gtest/gtest.h"
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| #include "gtest/gtest.h"
#include "sodium.h"
int main(int argc, char **argv) {
assert(sodium_init() != -1);
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
Modify states methods to implement the game of life | #include "../../include/core/StateCell.hpp"
#include "../../include/core/Cell.hpp"
bool StateCell::isState(StateCell* state) const
{
return state == this; //All state are singletons, so if state has the same class as this, it is the same instance
}
EmptyCell::EmptyCell()
{}
EmptyCell* EmptyCell::instance = new EmptyCell();
EmptyCell* EmptyCell::emptyCell()
{
return instance;
}
std::string EmptyCell::toString() const
{
return "EmptyCell";
}
StateCell* EmptyCell::iterate(Cell const* cell)
{
return AliveCell::aliveCell();
}
AliveCell::AliveCell()
{}
AliveCell* AliveCell::instance = new AliveCell();
AliveCell* AliveCell::aliveCell()
{
return instance;
}
std::string AliveCell::toString() const
{
return "AliveCell";
}
StateCell* AliveCell::iterate(Cell const* cell)
{
return EmptyCell::emptyCell();
}
| #include "../../include/core/StateCell.hpp"
#include "../../include/core/Cell.hpp"
bool StateCell::isState(StateCell* state) const
{
return state == this; //All state are singletons, so if state has the same class as this, it is the same instance
}
EmptyCell::EmptyCell()
{}
EmptyCell* EmptyCell::instance = new EmptyCell();
EmptyCell* EmptyCell::emptyCell()
{
return instance;
}
std::string EmptyCell::toString() const
{
return "EmptyCell";
}
StateCell* EmptyCell::iterate(Cell const* cell)
{
int nbAliveNeighbors(0);
std::vector<Cell const*> neighbors = cell->getNeighbors();
for(int i = 0; i < neighbors.size(); i++)
{
if(neighbors[i]->isState(AliveCell::aliveCell()))
{
nbAliveNeighbors++;
}
}
if(nbAliveNeighbors > 2)
return AliveCell::aliveCell();
else
return EmptyCell::emptyCell();
}
AliveCell::AliveCell()
{}
AliveCell* AliveCell::instance = new AliveCell();
AliveCell* AliveCell::aliveCell()
{
return instance;
}
std::string AliveCell::toString() const
{
return "AliveCell";
}
StateCell* AliveCell::iterate(Cell const* cell)
{
int nbAliveNeighbors(0);
std::vector<Cell const*> neighbors = cell->getNeighbors();
for(int i = 0; i < neighbors.size(); i++)
{
if(neighbors[i]->isState(AliveCell::aliveCell()))
{
nbAliveNeighbors ++;
}
}
if(nbAliveNeighbors < 2) //Solitude
return EmptyCell::emptyCell();
else if(nbAliveNeighbors > 3) //Surpopulation
return EmptyCell::emptyCell();
else
return AliveCell::aliveCell();
}
|
Add test-case for a bug report | #include <QtCore/QList>
struct SmallType {
char a[8];
};
struct BigType {
char a[9];
};
void foo()
{
QList<BigType> bigT; // Warning
QList<SmallType> smallT; // OK
}
class A {
public:
void foo()
{
m_big.clear();
}
QList<BigType> m_big; // Warning
};
void foo1(QList<BigType> big2)
{
QList<BigType> bigt; // Warning
bigt = big2;
}
| #include <QtCore/QList>
struct SmallType {
char a[8];
};
struct BigType {
char a[9];
};
void foo()
{
QList<BigType> bigT; // Warning
QList<SmallType> smallT; // OK
}
class A {
public:
void foo()
{
m_big.clear();
}
QList<BigType> m_big; // Warning
};
void foo1(QList<BigType> big2)
{
QList<BigType> bigt; // Warning
bigt = big2;
}
void test_bug358740()
{
QList<int> list; // OK
int a, b;
}
|
Add shell includes to test project for searching purposes | // dllmain.cpp : Defines the entry point for the DLL application.
#include "stdafx.h"
#include "commctrl.h"
#include "accctrl.h"
BOOL APIENTRY DllMain(
HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
| // dllmain.cpp : Defines the entry point for the DLL application.
#include "stdafx.h"
#include "commctrl.h"
#include "accctrl.h"
#include "shellapi.h"
#include "shlobj.h"
BOOL APIENTRY DllMain(
HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
|
Disable ODR test on Android | // RUN: %clangxx_asan -fno-rtti -DBUILD_SO1 -fPIC -shared %s -o %t1.so
// RUN: %clangxx_asan -fno-rtti -DBUILD_SO2 -fPIC -shared %s -o %t2.so
// RUN: %clangxx_asan -fno-rtti %t1.so %t2.so %s -Wl,-R. -o %t
// RUN: %env_asan_opts=fast_unwind_on_malloc=0:detect_odr_violation=2 not %run %t 2>&1 | FileCheck %s
struct XYZ {
virtual void foo();
};
#if defined(BUILD_SO1)
void XYZ::foo() {}
#elif defined(BUILD_SO2)
void XYZ::foo() {}
#else
int main() {}
#endif
// CHECK: AddressSanitizer: odr-violation
// CHECK-NEXT: 'vtable for XYZ'
// CHECK-NEXT: 'vtable for XYZ'
| // FIXME: Same as test/asan/TestCases/Linux/odr-violation.cc ?
// XFAIL: android
// RUN: %clangxx_asan -fno-rtti -DBUILD_SO1 -fPIC -shared %s -o %t1.so
// RUN: %clangxx_asan -fno-rtti -DBUILD_SO2 -fPIC -shared %s -o %t2.so
// RUN: %clangxx_asan -fno-rtti %t1.so %t2.so %s -Wl,-R. -o %t
// RUN: %env_asan_opts=fast_unwind_on_malloc=0:detect_odr_violation=2 not %run %t 2>&1 | FileCheck %s
struct XYZ {
virtual void foo();
};
#if defined(BUILD_SO1)
void XYZ::foo() {}
#elif defined(BUILD_SO2)
void XYZ::foo() {}
#else
int main() {}
#endif
// CHECK: AddressSanitizer: odr-violation
// CHECK-NEXT: 'vtable for XYZ'
// CHECK-NEXT: 'vtable for XYZ'
|
Add thread to fix gcc | #include "PolarisBlock.h"
#include "Poco/Net/ServerSocket.h"
#include "Poco/Net/SocketReactor.h"
#include "Poco/Net/SocketAcceptor.h"
#include "PolarisConnection.h"
using Poco::Net::ServerSocket;
using Poco::Net::SocketReactor;
using Poco::Net::SocketAcceptor;
using Poco::Thread;
int main(int argc, char** argv) {
return PolarisBlockApp().run(argc, argv);
}
int PolarisBlockApp::main(const std::vector<std::string> &args) {
// Create + Bind socket
ServerSocket blockSocket(12201); // TODO Config file / Argument / Whatever
// Make the reactor
SocketReactor reactor;
// Assign the Connector
SocketAcceptor<PolarisConnection> acceptor(blockSocket, reactor);
Thread thread;
logger().information("Starting reactor...");
thread.start(reactor);
waitForTerminationRequest();
reactor.stop();
thread.join();
return Application::EXIT_OK;
} | #include "PolarisBlock.h"
#include "Poco/Net/ServerSocket.h"
#include "Poco/Net/SocketReactor.h"
#include "Poco/Net/SocketAcceptor.h"
#include "Poco/Thread.h"
#include "PolarisConnection.h"
using Poco::Net::ServerSocket;
using Poco::Net::SocketReactor;
using Poco::Net::SocketAcceptor;
using Poco::Thread;
int main(int argc, char** argv) {
return PolarisBlockApp().run(argc, argv);
}
int PolarisBlockApp::main(const std::vector<std::string> &args) {
// Create + Bind socket
ServerSocket blockSocket(12201); // TODO Config file / Argument / Whatever
// Make the reactor
SocketReactor reactor;
// Assign the Connector
SocketAcceptor<PolarisConnection> acceptor(blockSocket, reactor);
Thread thread;
logger().information("Starting reactor...");
thread.start(reactor);
waitForTerminationRequest();
reactor.stop();
thread.join();
return Application::EXIT_OK;
} |
Check properties changes before emitting notify signal | #include "quasigame.h"
#include "gamescene.h"
QuasiGame::QuasiGame(QQuickItem *parent)
: QQuickItem(parent)
, m_currentScene(0)
, m_fps(DEFAULT_FPS)
{
connect(&m_updateTimer, SIGNAL(timeout()), this, SLOT(onUpdate()));
m_gameTime.start();
m_updateTimer.start(1000 / m_fps);
}
GameScene *QuasiGame::currentScene() const {
return m_currentScene;
}
void QuasiGame::setCurrentScene(GameScene *currentScene) {
if (m_currentScene)
disconnect(SIGNAL(update(long)));
m_currentScene = currentScene;
if (m_currentScene)
connect(this, SIGNAL(update(long)), m_currentScene, SLOT(update(long)));
emit currentSceneChanged();
}
int QuasiGame::fps() const
{
return m_fps;
}
void QuasiGame::setFps(int fps)
{
m_fps = fps;
emit fpsChanged();
}
void QuasiGame::onUpdate()
{
long elapsedTime = m_gameTime.restart();
emit update(elapsedTime);
}
| #include "quasigame.h"
#include "gamescene.h"
QuasiGame::QuasiGame(QQuickItem *parent)
: QQuickItem(parent)
, m_currentScene(0)
, m_fps(DEFAULT_FPS)
{
connect(&m_updateTimer, SIGNAL(timeout()), this, SLOT(onUpdate()));
m_gameTime.start();
m_updateTimer.start(1000 / m_fps);
}
GameScene *QuasiGame::currentScene() const {
return m_currentScene;
}
void QuasiGame::setCurrentScene(GameScene *currentScene) {
if (m_currentScene != currentScene) {
if (m_currentScene)
disconnect(SIGNAL(update(long)));
m_currentScene = currentScene;
if (m_currentScene)
connect(this, SIGNAL(update(long)), m_currentScene, SLOT(update(long)));
emit currentSceneChanged();
}
}
int QuasiGame::fps() const
{
return m_fps;
}
void QuasiGame::setFps(int fps)
{
if (m_fps != fps) {
m_fps = fps;
emit fpsChanged();
}
}
void QuasiGame::onUpdate()
{
long elapsedTime = m_gameTime.restart();
emit update(elapsedTime);
}
|
Add alert when Google API key was not specified | #include "JNIRhodes.h"
#include "gapikey.h"
#include <common/rhoparams.h>
#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "MapView"
RHO_GLOBAL void mapview_create(rho_param *p)
{
#ifdef GOOGLE_API_KEY
jclass clsMapView = getJNIClass(RHODES_JAVA_CLASS_MAPVIEW);
if (!clsMapView) return;
jmethodID midCreate = getJNIClassStaticMethod(clsMapView, "create", "(Ljava/lang/String;Ljava/util/Map;)V");
if (!midCreate) return;
if (p->type != RHO_PARAM_HASH) {
RAWLOG_ERROR("create: wrong input parameter (expect Hash)");
return;
}
JNIEnv *env = jnienv();
jobject paramsObj = RhoValueConverter(env).createObject(p);
env->CallStaticVoidMethod(clsMapView, midCreate, env->NewStringUTF(GOOGLE_API_KEY), paramsObj);
#else
RHO_NOT_IMPLEMENTED;
#endif
}
| #include "JNIRhodes.h"
#include "gapikey.h"
#include <common/rhoparams.h>
#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "MapView"
extern "C" void alert_show_popup(char *);
RHO_GLOBAL void mapview_create(rho_param *p)
{
#ifdef GOOGLE_API_KEY
jclass clsMapView = getJNIClass(RHODES_JAVA_CLASS_MAPVIEW);
if (!clsMapView) return;
jmethodID midCreate = getJNIClassStaticMethod(clsMapView, "create", "(Ljava/lang/String;Ljava/util/Map;)V");
if (!midCreate) return;
if (p->type != RHO_PARAM_HASH) {
RAWLOG_ERROR("create: wrong input parameter (expect Hash)");
return;
}
JNIEnv *env = jnienv();
jobject paramsObj = RhoValueConverter(env).createObject(p);
env->CallStaticVoidMethod(clsMapView, midCreate, env->NewStringUTF(GOOGLE_API_KEY), paramsObj);
#else
alert_show_popup("Google API key problem");
#endif
}
|
Fix registration of Sinh GPU Eigen kernel | /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/cwise_ops_common.h"
namespace tensorflow {
REGISTER6(UnaryOp, CPU, "Sinh", functor::sinh, float, double, bfloat16,
Eigen::half, complex64, complex128);
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#if !defined(MLIR_GENERATED_GPU_KERNELS_ENABLED)
REGISTER3(UnaryOp, GPU, "Sinh", functor::sinh, float, double);
#endif
REGISTER(UnaryOp, GPU, "Sinh", functor::sinh, bfloat16)
#endif
} // namespace tensorflow
| /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/cwise_ops_common.h"
namespace tensorflow {
REGISTER6(UnaryOp, CPU, "Sinh", functor::sinh, float, double, bfloat16,
Eigen::half, complex64, complex128);
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#if !defined(MLIR_GENERATED_GPU_KERNELS_ENABLED)
REGISTER3(UnaryOp, GPU, "Sinh", functor::sinh, Eigen::half, float, double);
#endif
REGISTER(UnaryOp, GPU, "Sinh", functor::sinh, bfloat16)
#endif
} // namespace tensorflow
|
Make sure we shut down the app if SDL_main() returns instead of exiting. |
/* Include the SDL main definition header */
#include "SDL_main.h"
/*******************************************************************************
Functions called by JNI
*******************************************************************************/
#include <jni.h>
// Called before SDL_main() to initialize JNI bindings in SDL library
extern "C" void SDL_Android_Init(JNIEnv* env, jclass cls);
// Library init
extern "C" jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
return JNI_VERSION_1_4;
}
// Start up the SDL app
extern "C" void Java_org_libsdl_app_SDLActivity_nativeInit(JNIEnv* env, jclass cls, jobject obj)
{
/* This interface could expand with ABI negotiation, calbacks, etc. */
SDL_Android_Init(env, cls);
/* Run the application code! */
char *argv[2];
argv[0] = strdup("SDL_app");
argv[1] = NULL;
SDL_main(1, argv);
}
|
/* Include the SDL main definition header */
#include "SDL_main.h"
/*******************************************************************************
Functions called by JNI
*******************************************************************************/
#include <jni.h>
// Called before SDL_main() to initialize JNI bindings in SDL library
extern "C" void SDL_Android_Init(JNIEnv* env, jclass cls);
// Library init
extern "C" jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
return JNI_VERSION_1_4;
}
// Start up the SDL app
extern "C" void Java_org_libsdl_app_SDLActivity_nativeInit(JNIEnv* env, jclass cls, jobject obj)
{
/* This interface could expand with ABI negotiation, calbacks, etc. */
SDL_Android_Init(env, cls);
/* Run the application code! */
int status;
char *argv[2];
argv[0] = strdup("SDL_app");
argv[1] = NULL;
status = SDL_main(1, argv);
/* We exit here for consistency with other platforms. */
exit(status);
}
/* vi: set ts=4 sw=4 expandtab: */
|
Remove unneeded include which is breaking build. | /*
* 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 "SkFontHost.h"
#include "SkTypeface.h"
#include "SkTypeface_win.h"
//static
void SkFontHost::EnsureTypefaceAccessible(const SkTypeface& typeface) {
//No sandbox, nothing to do.
}
| /*
* 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 "SkFontHost.h"
#include "SkTypeface.h"
//static
void SkFontHost::EnsureTypefaceAccessible(const SkTypeface& typeface) {
//No sandbox, nothing to do.
}
|
Add includes to use debugging showCanvas | #include "Example1.h"
#include <string.h>
#include <GLES3/gl3.h>
#include <jni.h>
#include <iostream>
#include <glm/gtc/matrix_transform.hpp>
#include <shader_program.h>
using namespace std;
bool
Example1::Init() {
}
void
Example1::onDraw() {
}
void
Example1::onShutdown() {
}
std::shared_ptr<Example1> application;
void applicationMain(FWPlatformBase * platform) {
application = std::make_shared<Example1>(platform);
platform->setApplication(application.get());
}
| #include "Example1.h"
#include <string.h>
#include <GLES3/gl3.h>
#include <jni.h>
#include <iostream>
#include <glm/gtc/matrix_transform.hpp>
#include <shader_program.h>
#include <Context.h>
#include <AndroidPlatform.h>
#include <ContextAndroid.h>
using namespace std;
bool
Example1::Init() {
}
void
Example1::onDraw() {
}
void
Example1::onShutdown() {
}
std::shared_ptr<Example1> application;
void applicationMain(FWPlatformBase * platform) {
application = std::make_shared<Example1>(platform);
platform->setApplication(application.get());
}
|
Add try block for receive error on connection | #include<ros/ros.h>
#include<ics3/ics>
#include<servo_msgs/IdBased.h>
ics::ICS3* driver {nullptr};
ros::Publisher pub;
void move(const servo_msgs::IdBased::ConstPtr& msg) {
auto degree = ics::Angle::newDegree(msg->angle);
auto nowpos = driver->move(msg->id, degree);
servo_msgs::IdBased result;
result.id = msg->id;
result.angle = nowpos;
pub.publish(result);
}
int main(int argc, char** argv) {
ros::init(argc, argv, "servo_krs_node");
ros::NodeHandle n {};
ros::NodeHandle pn {"~"};
std::string path {"/dev/ttyUSB0"};
pn.param<std::string>("path", path, path);
try {
ics::ICS3 ics {path.c_str()};
driver = &ics;
} catch (std::runtime_error e) {
ROS_INFO("Error: Cannot make ICS3 instance [%s]", e.what());
ROS_INFO("I tried open [%s]", path.c_str());
return -1;
}
ros::Subscriber sub = n.subscribe("cmd_krs", 100, move);
pub = n.advertise<servo_msgs::IdBased>("pose_krs", 10);
ros::spin();
return 0;
}
| #include<ros/ros.h>
#include<ics3/ics>
#include<servo_msgs/IdBased.h>
ics::ICS3* driver {nullptr};
ros::Publisher pub;
void move(const servo_msgs::IdBased::ConstPtr& msg) {
auto degree = ics::Angle::newDegree(msg->angle);
try {
auto nowpos = driver->move(msg->id, degree);
servo_msgs::IdBased result;
result.id = msg->id;
result.angle = nowpos;
pub.publish(result);
} catch (std::runtime_error e) {
ROS_INFO("Communicate error: %s", e.what());
}
}
int main(int argc, char** argv) {
ros::init(argc, argv, "servo_krs_node");
ros::NodeHandle n {};
ros::NodeHandle pn {"~"};
std::string path {"/dev/ttyUSB0"};
pn.param<std::string>("path", path, path);
try {
ics::ICS3 ics {path.c_str()};
driver = &ics;
} catch (std::runtime_error e) {
ROS_INFO("Error: Cannot make ICS3 instance [%s]", e.what());
ROS_INFO("I tried open [%s]", path.c_str());
return -1;
}
ros::Subscriber sub = n.subscribe("cmd_krs", 100, move);
pub = n.advertise<servo_msgs::IdBased>("pose_krs", 10);
ros::spin();
return 0;
}
|
Fix 'virtual out of class' error | //
// Created by dar on 1/25/16.
//
#include "GuiButton.h"
GuiButton::GuiButton(int x, int y, int width, int height) {
this->x = x;
this->y = y;
this->width = width;
this->height = height;
}
bool virtual GuiButton::onClick(int action, float x, float y) {
if (onClickListener == NULL) return false;
return onClickListener(action, x, y);
}
void virtual GuiButton::setOnClickListener(std::function<bool(int, float, float)> onClickListener) {
this->onClickListener = onClickListener;
} | //
// Created by dar on 1/25/16.
//
#include "GuiButton.h"
GuiButton::GuiButton(int x, int y, int width, int height) {
this->x = x;
this->y = y;
this->width = width;
this->height = height;
}
bool GuiButton::onClick(int action, float x, float y) {
if (onClickListener == NULL) return false;
return onClickListener(action, x, y);
}
void GuiButton::setOnClickListener(std::function<bool(int, float, float)> onClickListener) {
this->onClickListener = onClickListener;
} |
Add regression test for PR37935. | // RUN: %clang_cc1 -fsyntax-only -verify -std=c++1z %s
namespace [[deprecated]] {} // expected-warning {{'deprecated' attribute on anonymous namespace ignored}}
namespace [[deprecated]] N { // expected-note 4{{'N' has been explicitly marked deprecated here}}
int X;
int Y = X; // Ok
int f();
}
int N::f() { // Ok
return Y; // Ok
}
void f() {
int Y = N::f(); // expected-warning {{'N' is deprecated}}
using N::X; // expected-warning {{'N' is deprecated}}
int Z = X; //Ok
}
void g() {
using namespace N; // expected-warning {{'N' is deprecated}}
int Z = Y; // Ok
}
namespace M = N; // expected-warning {{'N' is deprecated}}
| // RUN: %clang_cc1 -fsyntax-only -verify -std=c++1z %s
namespace [[deprecated]] {} // expected-warning {{'deprecated' attribute on anonymous namespace ignored}}
namespace [[deprecated]] N { // expected-note 4{{'N' has been explicitly marked deprecated here}}
int X;
int Y = X; // Ok
int f();
}
int N::f() { // Ok
return Y; // Ok
}
void f() {
int Y = N::f(); // expected-warning {{'N' is deprecated}}
using N::X; // expected-warning {{'N' is deprecated}}
int Z = X; //Ok
}
void g() {
using namespace N; // expected-warning {{'N' is deprecated}}
int Z = Y; // Ok
}
namespace M = N; // expected-warning {{'N' is deprecated}}
// Shouldn't diag:
[[nodiscard, deprecated("")]] int PR37935();
|
Allow unnamed function and their assigning to other values | #include "object/object.h"
#include "object/jsobject.h"
#include "object/function.h"
#include "parser/functionstatement.h"
#include "vm/instruction-builder.h"
#include "vm/instruction.h"
#include "vm/context.h"
#include "vm/vm.h"
namespace grok {
namespace parser {
using namespace grok::vm;
using namespace grok::obj;
/// emits code for function definition
/// We don't generate the code for the body now but defer it until
/// it is required i.e. when a call is placed to this function during
/// execution
void FunctionStatement::emit(std::shared_ptr<InstructionBuilder>)
{
std::string Name = proto_->GetName();
auto F = std::make_shared<Function>(std::move(body_), std::move(proto_));
auto VS = GetVStore(GetGlobalVMContext());
auto V = Value{};
V.O = std::make_shared<Object>(F);
VS->StoreValue(Name, V);
}
void FunctionPrototype::emit(std::shared_ptr<InstructionBuilder>)
{
// do nothing
}
} // parser
} // grok
| #include "object/object.h"
#include "object/jsobject.h"
#include "object/function.h"
#include "parser/functionstatement.h"
#include "vm/instruction-builder.h"
#include "vm/instruction.h"
#include "vm/context.h"
#include "vm/vm.h"
namespace grok {
namespace parser {
using namespace grok::vm;
using namespace grok::obj;
/// emits code for function definition
/// We don't generate the code for the body now but defer it until
/// it is required i.e. when a call is placed to this function during
/// execution
void FunctionStatement::emit(std::shared_ptr<InstructionBuilder> builder)
{
std::string Name = proto_->GetName();
auto F = std::make_shared<Function>(std::move(body_), std::move(proto_));
auto VS = GetVStore(GetGlobalVMContext());
if (Name.length()) {
auto V = Value{};
V.O = std::make_shared<Object>(F);
VS->StoreValue(Name, V);
}
auto instr = InstructionBuilder::Create<Instructions::push>();
instr->data_type_ = d_obj;
instr->data_ = std::make_shared<Object>(F);
builder->AddInstruction(std::move(instr));
}
void FunctionPrototype::emit(std::shared_ptr<InstructionBuilder>)
{
// do nothing
}
} // parser
} // grok
|
Store the query that is to be executed later. | //@author A0097630B
#include "stdafx.h"
#include "query_executor.h"
namespace You {
namespace Controller {
namespace Internal {
QueryExecutor::QueryExecutor(std::unique_ptr<You::QueryEngine::Query>&& query) {
}
Result QueryExecutor::execute() {
QueryEngine::Response response = QueryEngine::executeQuery(
std::move(query));
return processResponse(response);
}
} // namespace Internal
} // namespace Controller
} // namespace You
| //@author A0097630B
#include "stdafx.h"
#include "query_executor.h"
namespace You {
namespace Controller {
namespace Internal {
QueryExecutor::QueryExecutor(std::unique_ptr<You::QueryEngine::Query>&& query)
: query(std::move(query)) {
}
Result QueryExecutor::execute() {
QueryEngine::Response response = QueryEngine::executeQuery(
std::move(query));
return processResponse(response);
}
} // namespace Internal
} // namespace Controller
} // namespace You
|
Fix for missing Hovercards in Windows. Buddy: Mark | // Copyright eeGeo Ltd (2012-2015), All Rights Reserved
#include "WindowsInitialExperienceModule.h"
#include "WindowsInitialExperiencePreLoadModel.h"
#include "InitialExperienceIntroStep.h"
//#include "InitialExperienceSearchResultAttractModeModel.h"
namespace ExampleApp
{
namespace InitialExperience
{
namespace SdkModel
{
WindowsInitialExperienceModule::WindowsInitialExperienceModule(
WindowsNativeState& nativeState,
PersistentSettings::IPersistentSettingsModel& persistentSettings,
ExampleAppMessaging::TMessageBus& messageBus
)
: InitialExperienceModuleBase(persistentSettings)
, m_nativeState(nativeState)
, m_messageBus(messageBus)
//, m_pInitialExperienceSearchResultAttractModeModule(NULL)
{
}
WindowsInitialExperienceModule::~WindowsInitialExperienceModule()
{
//Eegeo_DELETE m_pInitialExperienceSearchResultAttractModeModule;
}
std::vector<IInitialExperienceStep*> WindowsInitialExperienceModule::CreateSteps(WorldAreaLoader::SdkModel::IWorldAreaLoaderModel &worldAreaLoaderModel)
{
std::vector<IInitialExperienceStep*> steps;
// TODO: Recreate MEA initial experience steps for windows...
return steps;
}
}
}
}
| // Copyright eeGeo Ltd (2012-2015), All Rights Reserved
#include "WindowsInitialExperienceModule.h"
#include "WindowsInitialExperiencePreLoadModel.h"
#include "InitialExperienceIntroStep.h"
//#include "InitialExperienceSearchResultAttractModeModel.h"
#include "WorldPinVisibility.h"
namespace ExampleApp
{
namespace InitialExperience
{
namespace SdkModel
{
WindowsInitialExperienceModule::WindowsInitialExperienceModule(
WindowsNativeState& nativeState,
PersistentSettings::IPersistentSettingsModel& persistentSettings,
ExampleAppMessaging::TMessageBus& messageBus
)
: InitialExperienceModuleBase(persistentSettings)
, m_nativeState(nativeState)
, m_messageBus(messageBus)
//, m_pInitialExperienceSearchResultAttractModeModule(NULL)
{
}
WindowsInitialExperienceModule::~WindowsInitialExperienceModule()
{
//Eegeo_DELETE m_pInitialExperienceSearchResultAttractModeModule;
}
std::vector<IInitialExperienceStep*> WindowsInitialExperienceModule::CreateSteps(WorldAreaLoader::SdkModel::IWorldAreaLoaderModel &worldAreaLoaderModel)
{
std::vector<IInitialExperienceStep*> steps;
// TODO: Recreate MEA initial experience steps for windows...
m_messageBus.Publish(WorldPins::WorldPinsVisibilityMessage(WorldPins::SdkModel::WorldPinVisibility::All));
return steps;
}
}
}
}
|
Fix last version writing in aboutWindow | #include "aboutwindow.h"
#include "ui_aboutwindow.h"
aboutWindow::aboutWindow(QString version, QWidget *parent) : QDialog(parent), ui(new Ui::aboutWindow)
{
ui->setupUi(this);
ui->labelCurrent->setText(version);
m_version = version.replace(".", "").toInt();
QNetworkAccessManager *m = new QNetworkAccessManager();
connect(m, SIGNAL(finished(QNetworkReply*)), this, SLOT(finished(QNetworkReply*)));
m->get(QNetworkRequest(QUrl("http://imgbrd-grabber.googlecode.com/svn/trunk/VERSION")));
setFixedSize(400, 170);
}
aboutWindow::~aboutWindow()
{
delete ui;
}
void aboutWindow::finished(QNetworkReply *r)
{
QString l = r->readAll();
int latest = l.replace(".", "").toInt();
if (latest <= m_version)
{ ui->labelMessage->setText("<p style=\"font-size:8pt; font-style:italic; color:#808080;\">"+tr("Grabber est jour")+"</p>"); }
else
{ ui->labelMessage->setText("<p style=\"font-size:8pt; font-style:italic; color:#808080;\">"+tr("Une nouvelle version est disponible : %1").arg(l)+"</p>"); }
}
| #include "aboutwindow.h"
#include "ui_aboutwindow.h"
aboutWindow::aboutWindow(QString version, QWidget *parent) : QDialog(parent), ui(new Ui::aboutWindow)
{
ui->setupUi(this);
ui->labelCurrent->setText(version);
m_version = version.replace(".", "").toInt();
QNetworkAccessManager *m = new QNetworkAccessManager();
connect(m, SIGNAL(finished(QNetworkReply*)), this, SLOT(finished(QNetworkReply*)));
m->get(QNetworkRequest(QUrl("http://imgbrd-grabber.googlecode.com/svn/trunk/VERSION")));
setFixedSize(400, 170);
}
aboutWindow::~aboutWindow()
{
delete ui;
}
void aboutWindow::finished(QNetworkReply *r)
{
QString l = r->readAll(), last = l;
int latest = last.replace(".", "").toInt();
if (latest <= m_version)
{ ui->labelMessage->setText("<p style=\"font-size:8pt; font-style:italic; color:#808080;\">"+tr("Grabber est jour")+"</p>"); }
else
{ ui->labelMessage->setText("<p style=\"font-size:8pt; font-style:italic; color:#808080;\">"+tr("Une nouvelle version est disponible : %1").arg(l)+"</p>"); }
}
|
Complete function for parsing epsilon-NFA -> .gv file. | #include "enfa.h"
#include <string>
namespace tinygrep {
namespace enfa {
std::string EpsilonNFA::to_graph() const {
return "";
}
} // namespace enfa
} // namespace tinygrep
| #include "enfa.h"
#include <string>
#include <sstream>
namespace tinygrep {
namespace enfa {
// The default scale of a generated graph.
const unsigned int DEFAULT_PNG_SIZE = 10;
const std::string LABEL_BEGIN = " [label=\"",
LABEL_END = "\"]",
EDGE_ARROW = " -> ",
STATE_PREFIX = "q",
ENDLINE = ";\n";
std::string EpsilonNFA::to_graph() const {
const unsigned int png_size = DEFAULT_PNG_SIZE;
std::stringstream output;
output << "digraph epsilon_nfa {\n"
<< "rankdir=LR; size=\""
<< png_size << "," << png_size << "\""
<< ENDLINE;
// add start state
output << "foo [style = invis]"
<< ENDLINE;
output << "node [shape = circle]; "
<< STATE_PREFIX << start_state_
<< ENDLINE;
output << "foo" << EDGE_ARROW
<< STATE_PREFIX << start_state_
<< LABEL_BEGIN << "start" << LABEL_END
<< ENDLINE;
// add accepting state
output << "node [shape = doublecircle]; "
<< STATE_PREFIX << accept_state_
<< ENDLINE;
// add remaining states
output << "node [shape = circle]"
<< ENDLINE;
// add transitions
for (state_type from = 0; from < state_count_; from++) {
// epsilon-transitions
for (state_type to : epsilon_transitions_[from]) {
output << STATE_PREFIX << from
<< EDGE_ARROW
<< STATE_PREFIX << to
<< LABEL_BEGIN << LABEL_END
<< ENDLINE;
}
// literal-transitions
for (Transition transition : literal_transitions_[from]) {
output << STATE_PREFIX << from
<< EDGE_ARROW
<< STATE_PREFIX << transition.target
<< LABEL_BEGIN << transition.literal << LABEL_END
<< ENDLINE;
}
}
output << "}\n";
return output.str();
}
} // namespace enfa
} // namespace tinygrep
|
Revert "Fixed command line macro's missing quotes" | #include <gtest/gtest.h>
#include <rapidxml_utils.hpp>
#include "llvm/compiler.hpp"
#include "parser/xmlParser.hpp"
class LLVMCompilerTest: public ::testing::Test {
protected:
XMLParser xpx = XMLParser();
inline rapidxml::file<> xmlFile(std::string path) {
#define Q(x) #x
#define QUOTE(x) Q(x)
path = QUOTE(DATA_PARENT_DIR) + ("/" + path);
#undef QUOTE
#undef Q
return rapidxml::file<>(path.c_str());
}
inline void noThrowOnCompile(std::string xmlFilePath) {
xpx.parse(xmlFile(xmlFilePath));
CompileVisitor::Link visitor = CompileVisitor::create(globalContext, xmlFilePath, xpx.getTree());
try {
visitor->visit();
} catch (InternalError& err) {
EXPECT_NO_THROW(throw InternalError(err));
println(err.what());
}
visitor->getModule()->dump();
}
};
TEST_F(LLVMCompilerTest, ExitCodes) {
noThrowOnCompile("data/llvm/exit_code.xml");
noThrowOnCompile("data/llvm/stored_return.xml");
}
TEST_F(LLVMCompilerTest, Declarations) {
noThrowOnCompile("data/llvm/primitive.xml");
}
TEST_F(LLVMCompilerTest, Branches) {
noThrowOnCompile("data/llvm/if.xml");
noThrowOnCompile("data/llvm/if-else.xml");
noThrowOnCompile("data/llvm/else-if.xml");
}
| #include <gtest/gtest.h>
#include <rapidxml_utils.hpp>
#include "llvm/compiler.hpp"
#include "parser/xmlParser.hpp"
class LLVMCompilerTest: public ::testing::Test {
protected:
XMLParser xpx = XMLParser();
inline rapidxml::file<> xmlFile(std::string path) {
path = DATA_PARENT_DIR + ("/" + path);
return rapidxml::file<>(path.c_str());
}
inline void noThrowOnCompile(std::string xmlFilePath) {
xpx.parse(xmlFile(xmlFilePath));
CompileVisitor::Link visitor = CompileVisitor::create(globalContext, xmlFilePath, xpx.getTree());
try {
visitor->visit();
} catch (InternalError& err) {
EXPECT_NO_THROW(throw InternalError(err));
println(err.what());
}
visitor->getModule()->dump();
}
};
TEST_F(LLVMCompilerTest, ExitCodes) {
noThrowOnCompile("data/llvm/exit_code.xml");
noThrowOnCompile("data/llvm/stored_return.xml");
}
TEST_F(LLVMCompilerTest, Declarations) {
noThrowOnCompile("data/llvm/primitive.xml");
}
TEST_F(LLVMCompilerTest, Branches) {
noThrowOnCompile("data/llvm/if.xml");
noThrowOnCompile("data/llvm/if-else.xml");
noThrowOnCompile("data/llvm/else-if.xml");
}
|
Add missing underscore - fix last commit | #include "Timer.hpp"
using namespace HomieInternals;
Timer::Timer()
: _initialTime(0)
, _interval(0)
, _tickAtBeginning(false) {
}
void Timer::setInterval(uint32_t interval, bool tickAtBeginning) {
_interval = interval;
_tickAtBeginning = tickAtBeginning;
this->reset();
}
bool Timer::check() const {
if (_tickAtBeginning && _initialTime == 0) return true;
if (millis() - _initialTime >= _interval) return true;
return false;
}
void Timer::reset() {
if (tickAtBeginning) {
_initialTime = 0;
} else {
this->tick();
}
}
void Timer::tick() {
_initialTime = millis();
}
| #include "Timer.hpp"
using namespace HomieInternals;
Timer::Timer()
: _initialTime(0)
, _interval(0)
, _tickAtBeginning(false) {
}
void Timer::setInterval(uint32_t interval, bool tickAtBeginning) {
_interval = interval;
_tickAtBeginning = tickAtBeginning;
this->reset();
}
bool Timer::check() const {
if (_tickAtBeginning && _initialTime == 0) return true;
if (millis() - _initialTime >= _interval) return true;
return false;
}
void Timer::reset() {
if (_tickAtBeginning) {
_initialTime = 0;
} else {
this->tick();
}
}
void Timer::tick() {
_initialTime = millis();
}
|
Fix a compile error on msvc7 | // Copyright (c) 2007-2009 Paul Hodge. All rights reserved.
#include "circa.h"
namespace circa {
namespace range_function {
void evaluate(Term* caller)
{
unsigned int max = as_int(caller->input(0));
Branch& branch = as_branch(caller);
resize_list(branch, max, INT_TYPE);
for (unsigned int i=0; i < max; i++)
as_int(branch[i]) = i;
}
void setup(Branch& kernel)
{
import_function(kernel, evaluate, "range(int) : List");
}
}
} // namespace circa
| // Copyright (c) 2007-2009 Paul Hodge. All rights reserved.
#include "circa.h"
namespace circa {
namespace range_function {
void evaluate(Term* caller)
{
int max = as_int(caller->input(0));
Branch& branch = as_branch(caller);
resize_list(branch, max, INT_TYPE);
for (int i=0; i < max; i++)
as_int(branch[i]) = i;
}
void setup(Branch& kernel)
{
import_function(kernel, evaluate, "range(int) : List");
}
}
} // namespace circa
|
Use helper function to get top left coordinates | #include "box2dbaseitem.h"
#include <Box2D/Box2D.h>
float Box2DBaseItem::m_scaleRatio = 32.0f;
Box2DBaseItem::Box2DBaseItem(GameScene *parent )
: GameItem(parent)
, m_initialized(false)
, m_synchronizing(false)
, m_synchronize(true)
{
}
bool Box2DBaseItem::initialized() const
{
return m_initialized;
}
/*
* Shamelessly stolen from qml-box2d project at gitorious
*
* https://gitorious.org/qml-box2d/qml-box2d
*/
void Box2DBaseItem::synchronize()
{
if (m_synchronize && m_initialized) {
m_synchronizing = true;
const b2Vec2 position = b2TransformOrigin();
const float32 angle = b2Angle();
const qreal newX = position.x * m_scaleRatio - width() / 2.0;
const qreal newY = -position.y * m_scaleRatio - height() / 2.0;
const qreal newRotation = -(angle * 360.0) / (2 * b2_pi);
if (!qFuzzyCompare(x(), newX) || !qFuzzyCompare(y(), newY))
setPos(QPointF(newX, newY));
if (!qFuzzyCompare(rotation(), newRotation))
setRotation(newRotation);
m_synchronizing = false;
}
}
| #include "box2dbaseitem.h"
#include "util.h"
#include <Box2D/Box2D.h>
float Box2DBaseItem::m_scaleRatio = 32.0f;
Box2DBaseItem::Box2DBaseItem(GameScene *parent )
: GameItem(parent)
, m_initialized(false)
, m_synchronizing(false)
, m_synchronize(true)
{
}
bool Box2DBaseItem::initialized() const
{
return m_initialized;
}
/*
* Shamelessly stolen from qml-box2d project at gitorious
*
* https://gitorious.org/qml-box2d/qml-box2d
*/
void Box2DBaseItem::synchronize()
{
if (m_synchronize && m_initialized) {
m_synchronizing = true;
const QPointF newPoint = b2Util::qTopLeft(b2TransformOrigin(), boundingRect(), m_scaleRatio);
const float32 angle = b2Angle();
const qreal newRotation = -(angle * 360.0) / (2 * b2_pi);
if (!qFuzzyCompare(x(), newPoint.x()) || !qFuzzyCompare(y(), newPoint.y()))
setPos(newPoint);
if (!qFuzzyCompare(rotation(), newRotation))
setRotation(newRotation);
m_synchronizing = false;
}
}
|
Use a pointer in getInstance instead of shared_ptr | #include "MediaSessionManager.h"
using namespace ::com::kurento::kms;
using namespace ::com::kurento::kms::api;
void task() {
}
MediaSessionManager::MediaSessionManager() {
}
MediaSessionManager::~MediaSessionManager() {
}
MediaSessionManager *MediaSessionManager::getInstance() {
static shared_ptr<MediaSessionManager> instance(new MediaSessionManager());
return instance.get();
}
void MediaSessionManager::releaseInstance(MediaSessionManager* manager) {
// As instance is a singleton no action is needed
}
MediaSession& MediaSessionManager::createMediaSession() {
MediaServerException exception;
exception.__set_description("Not implemented");
exception.__set_code(ErrorCode::UNEXPECTED);
throw exception;
}
void MediaSessionManager::deleteMediaSession(const MediaSession& session) {
MediaServerException exception;
exception.__set_description("Not implemented");
exception.__set_code(ErrorCode::UNEXPECTED);
throw exception;
}
| #include "MediaSessionManager.h"
using namespace ::com::kurento::kms;
using namespace ::com::kurento::kms::api;
void task() {
}
MediaSessionManager::MediaSessionManager() {
}
MediaSessionManager::~MediaSessionManager() {
}
MediaSessionManager *MediaSessionManager::getInstance() {
static MediaSessionManager *instance = new MediaSessionManager();
return instance;
}
void MediaSessionManager::releaseInstance(MediaSessionManager* manager) {
// As instance is a singleton no action is needed
}
MediaSession& MediaSessionManager::createMediaSession() {
MediaServerException exception;
exception.__set_description("Not implemented");
exception.__set_code(ErrorCode::UNEXPECTED);
throw exception;
}
void MediaSessionManager::deleteMediaSession(const MediaSession& session) {
MediaServerException exception;
exception.__set_description("Not implemented");
exception.__set_code(ErrorCode::UNEXPECTED);
throw exception;
}
|
Fix the Chrome Linux build by working around a compiler bug. | // Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ppapi/tests/test_case.h"
#include <sstream>
std::string TestCase::MakeFailureMessage(const char* file,
int line,
const char* cmd) {
std::ostringstream output;
output << "Failure in " << file << "(" << line << "): " << cmd;
return output.str();
}
| // Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ppapi/tests/test_case.h"
#include <sstream>
std::string TestCase::MakeFailureMessage(const char* file,
int line,
const char* cmd) {
// The mere presence of this local variable works around a gcc-4.2.4
// compiler bug in official Chrome Linux builds. If you remove it,
// confirm this compile command still works:
// GYP_DEFINES='branding=Chrome buildtype=Official target_arch=x64'
// gclient runhooks
// make -k -j4 BUILDTYPE=Release ppapi_tests
std::string s;
std::ostringstream output;
output << "Failure in " << file << "(" << line << "): " << cmd;
return output.str();
}
|
Add new line at the end of file | /* Copyright © 2001-2018, Canal TP and/or its affiliates. All rights reserved.
This file is part of Navitia,
the software to build cool stuff with public transport.
Hope you'll enjoy and contribute to this project,
powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
a non ending quest to the responsive locomotion way of traveling!
LICENCE: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/
#include "osm2ed.h"
int main(int argc, const char** argv) {
return ed::connectors::osm2ed(argc, argv);
} | /* Copyright © 2001-2018, Canal TP and/or its affiliates. All rights reserved.
This file is part of Navitia,
the software to build cool stuff with public transport.
Hope you'll enjoy and contribute to this project,
powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
a non ending quest to the responsive locomotion way of traveling!
LICENCE: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/
#include "osm2ed.h"
int main(int argc, const char** argv) {
return ed::connectors::osm2ed(argc, argv);
}
|
Use putenv for env variables | #include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <stdlib.h>
#include <QtGlobal>
int main(int argc, char *argv[])
{
//TODO: Run this on Qt versions which support it...
//QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QApplication app(argc, argv);
QQmlApplicationEngine engine;
setenv("PYTHONDONTWRITEBYTECODE", "1", 1);
QString frameworks = app.applicationDirPath() + "/../Frameworks";
setenv("DYLD_LIBRARY_PATH", frameworks.toUtf8().data(), 1);
engine.load(QUrl(QLatin1String("qrc:/main.qml")));
return app.exec();
}
| #include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <stdlib.h>
#include <QtGlobal>
int main(int argc, char *argv[])
{
//TODO: Run this on Qt versions which support it...
//QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QApplication app(argc, argv);
QQmlApplicationEngine engine;
QString pythonNoBytecode = "PYTHONDONTWRITEBYTECODE=1";
putenv(pythonNoBytecode.toUtf8().data());
QString frameworks = "DYLD_LIBRARY_PATH=" + app.applicationDirPath() + "/../Frameworks";
putenv(frameworks.toUtf8().data());
engine.load(QUrl(QLatin1String("qrc:/main.qml")));
return app.exec();
}
|
Set new frame timeout to 2 milliseconds (was 3 milliseconds) | #include "zg01_fsm.h"
// max time between ZG01 bits, until a new frame is assumed to have started
#define ZG01_MAX_MS 3
// all of the state of the FSM
typedef struct {
uint8_t *buffer;
int num_bits;
unsigned long prev_ms;
} fsm_t;
static fsm_t fsm;
static fsm_t *s = &fsm;
// resets the FSM
static void fsm_reset(void)
{
s->num_bits = 0;
}
void zg01_init(uint8_t buffer[5])
{
s->buffer = buffer;
fsm_reset();
}
bool zg01_process(unsigned long ms, bool data)
{
// check if a new message has started, based on time since previous bit
if ((ms - s->prev_ms) > ZG01_MAX_MS) {
fsm_reset();
}
s->prev_ms = ms;
// number of bits received is basically the "state"
if (s->num_bits < 40) {
// store it while it fits
int idx = s->num_bits / 8;
s->buffer[idx] = (s->buffer[idx] << 1) | (data ? 1 : 0);
// are we done yet?
s->num_bits++;
if (s->num_bits == 40) {
return true;
}
}
// else do nothing, wait until fsm is reset
return false;
}
| #include "zg01_fsm.h"
// max time between ZG01 bits, until a new frame is assumed to have started
#define ZG01_MAX_MS 2
// all of the state of the FSM
typedef struct {
uint8_t *buffer;
int num_bits;
unsigned long prev_ms;
} fsm_t;
static fsm_t fsm;
static fsm_t *s = &fsm;
// resets the FSM
static void fsm_reset(void)
{
s->num_bits = 0;
}
void zg01_init(uint8_t buffer[5])
{
s->buffer = buffer;
fsm_reset();
}
bool zg01_process(unsigned long ms, bool data)
{
// check if a new message has started, based on time since previous bit
if ((ms - s->prev_ms) > ZG01_MAX_MS) {
fsm_reset();
}
s->prev_ms = ms;
// number of bits received is basically the "state"
if (s->num_bits < 40) {
// store it while it fits
int idx = s->num_bits / 8;
s->buffer[idx] = (s->buffer[idx] << 1) | (data ? 1 : 0);
// are we done yet?
s->num_bits++;
if (s->num_bits == 40) {
return true;
}
}
// else do nothing, wait until fsm is reset
return false;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.