Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Use thread local storage for label counter | //=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include "Labels.hpp"
#include "Utils.hpp"
static int currentLabel = 0;
std::string eddic::newLabel(){
return "L" + toString(currentLabel++);
}
void eddic::resetNumbering(){
currentLabel = 0;
}
| //=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include "Labels.hpp"
#include "Utils.hpp"
__thread int currentLabel = 0;
std::string eddic::newLabel(){
return "L" + toString(currentLabel++);
}
void eddic::resetNumbering(){
currentLabel = 0;
}
|
Replace deprecated NanRawString with NanUtf8String | /*
** © 2014 by Philipp Dunkel <pip@pipobscure.com>
** Licensed under MIT License.
*/
void FSEvents::emitEvent(const char *path, UInt32 flags, UInt64 id) {
if (!handler) return;
NanScope();
v8::Local<v8::Value> argv[] = {
NanNew<v8::String>(path),
NanNew<v8::Number>(flags),
NanNew<v8::Number>(id)
};
handler->Call(3, argv);
}
NAN_METHOD(FSEvents::New) {
NanScope();
char* path = static_cast<char *>(NanRawString(args[0], Nan::UTF8, NULL, NULL, 0, v8::String::NO_OPTIONS));
NanCallback *callback = new NanCallback(args[1].As<v8::Function>());
FSEvents *fse = new FSEvents(path, callback);
fse->Wrap(args.This());
NanReturnValue(args.This());
}
NAN_METHOD(FSEvents::Stop) {
NanScope();
FSEvents* fse = node::ObjectWrap::Unwrap<FSEvents>(args.This());
fse->threadStop();
fse->asyncStop();
NanReturnValue(args.This());
}
NAN_METHOD(FSEvents::Start) {
NanScope();
FSEvents* fse = node::ObjectWrap::Unwrap<FSEvents>(args.This());
fse->asyncStart();
fse->threadStart();
NanReturnValue(args.This());
}
| /*
** © 2014 by Philipp Dunkel <pip@pipobscure.com>
** Licensed under MIT License.
*/
void FSEvents::emitEvent(const char *path, UInt32 flags, UInt64 id) {
if (!handler) return;
NanScope();
v8::Local<v8::Value> argv[] = {
NanNew<v8::String>(path),
NanNew<v8::Number>(flags),
NanNew<v8::Number>(id)
};
handler->Call(3, argv);
}
NAN_METHOD(FSEvents::New) {
NanScope();
char* path = static_cast<char *>(*NanUtf8String(args[0]));
NanCallback *callback = new NanCallback(args[1].As<v8::Function>());
FSEvents *fse = new FSEvents(path, callback);
fse->Wrap(args.This());
NanReturnValue(args.This());
}
NAN_METHOD(FSEvents::Stop) {
NanScope();
FSEvents* fse = node::ObjectWrap::Unwrap<FSEvents>(args.This());
fse->threadStop();
fse->asyncStop();
NanReturnValue(args.This());
}
NAN_METHOD(FSEvents::Start) {
NanScope();
FSEvents* fse = node::ObjectWrap::Unwrap<FSEvents>(args.This());
fse->asyncStart();
fse->threadStart();
NanReturnValue(args.This());
}
|
Include algorithm to get definition of std::find | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "free_list.h"
#include <cassert>
namespace vespalib::datastore {
FreeList::FreeList()
: _free_lists()
{
}
FreeList::~FreeList()
{
assert(_free_lists.empty());
}
void
FreeList::attach(BufferFreeList& buf_list)
{
_free_lists.push_back(&buf_list);
}
void
FreeList::detach(BufferFreeList& buf_list)
{
if (!_free_lists.empty() && (_free_lists.back() == &buf_list)) {
_free_lists.pop_back();
return;
}
auto itr = std::find(_free_lists.begin(), _free_lists.end(), &buf_list);
assert(itr != _free_lists.end());
_free_lists.erase(itr);
}
}
| // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "free_list.h"
#include <algorithm>
#include <cassert>
namespace vespalib::datastore {
FreeList::FreeList()
: _free_lists()
{
}
FreeList::~FreeList()
{
assert(_free_lists.empty());
}
void
FreeList::attach(BufferFreeList& buf_list)
{
_free_lists.push_back(&buf_list);
}
void
FreeList::detach(BufferFreeList& buf_list)
{
if (!_free_lists.empty() && (_free_lists.back() == &buf_list)) {
_free_lists.pop_back();
return;
}
auto itr = std::find(_free_lists.begin(), _free_lists.end(), &buf_list);
assert(itr != _free_lists.end());
_free_lists.erase(itr);
}
}
|
Remove unused variable in file finder, | #include "filefinder.h"
#if ! defined(_XOPEN_SOURCE) || _XOPEN_SOURCE < 600
#define _XOPEN_SOURCE 600 /* Get nftw() and S_IFSOCK declarations */
#endif
#include <ftw.h>
namespace{
std::vector<node> *nodes;
int dirTree(const char *pathname, const struct stat *sbuf, int type,
struct FTW *ftwb){
std::string filename(&pathname[ftwb->base]);
std::string location(pathname);
location = location.substr(0,location.size()-filename.size());
nodes->emplace_back(filename,location,ftwb->level, type == FTW_D);
return 0;
}
}
void find_files(std::vector<node>& ns){
nodes = &ns;
int flags = 0;
if(nftw(".",dirTree,10,flags)== -1){
}
}
| #include "filefinder.h"
#if ! defined(_XOPEN_SOURCE) || _XOPEN_SOURCE < 600
#define _XOPEN_SOURCE 600 /* Get nftw() and S_IFSOCK declarations */
#endif
#include <ftw.h>
namespace{
std::vector<node> *nodes;
int dirTree(const char *pathname, const struct stat *, int type,
struct FTW *ftwb){
std::string filename(&pathname[ftwb->base]);
std::string location(pathname);
location = location.substr(0,location.size()-filename.size());
nodes->emplace_back(filename,location,ftwb->level, type == FTW_D);
return 0;
}
}
void find_files(std::vector<node>& ns){
nodes = &ns;
int flags = 0;
if(nftw(".",dirTree,10,flags)== -1){
}
}
|
Use test fixture in GetUserName unit tests | #include <string>
#include <vector>
#include <unistd.h>
#include <gtest/gtest.h>
#include <scxcorelib/scxstrencodingconv.h>
#include "getusername.h"
TEST(GetUserName,simple)
{
// allocate a WCHAR_T buffer to receive username
DWORD lpnSize = L_cuserid;
WCHAR_T lpBuffer[lpnSize];
BOOL result = GetUserName(lpBuffer, &lpnSize);
// GetUserName returns 1 on success
ASSERT_EQ(1, result);
// get expected username
std::string username(getlogin());
// GetUserName sets lpnSize to length of username including null
ASSERT_EQ(username.size()+1, lpnSize);
// copy UTF-16 bytes (excluding null) from lpBuffer to vector for conversion
unsigned char *begin = reinterpret_cast<unsigned char *>(&lpBuffer[0]);
// -1 to skip null; *2 because UTF-16 encodes two bytes per character
unsigned char *end = begin + (lpnSize-1)*2;
std::vector<unsigned char> input(begin, end);
// convert to UTF-8 for assertion
std::string output;
SCXCoreLib::Utf16leToUtf8(input, output);
EXPECT_EQ(username, output);
}
| #include <string>
#include <vector>
#include <unistd.h>
#include <gtest/gtest.h>
#include <scxcorelib/scxstrencodingconv.h>
#include "getusername.h"
class GetUserNameTest : public ::testing::Test {
protected:
DWORD lpnSize;
std::vector<WCHAR_T> lpBuffer;
BOOL result;
std::string userName;
GetUserNameTest(): userName(std::string(getlogin())) {}
void GetUserNameWithSize(DWORD size) {
lpnSize = size;
// allocate a WCHAR_T buffer to receive username
lpBuffer.assign(lpnSize, '\0');
result = GetUserName(&lpBuffer[0], &lpnSize);
}
};
TEST_F(GetUserNameTest, NormalUse) {
GetUserNameWithSize(L_cuserid);
// GetUserName returns 1 on success
ASSERT_EQ(1, result);
// GetUserName sets lpnSize to length of username including null
ASSERT_EQ(userName.size()+1, lpnSize);
// copy UTF-16 bytes (excluding null) from lpBuffer to vector for conversion
unsigned char *begin = reinterpret_cast<unsigned char *>(&lpBuffer[0]);
// -1 to skip null; *2 because UTF-16 encodes two bytes per character
unsigned char *end = begin + (lpnSize-1)*2;
std::vector<unsigned char> input(begin, end);
// convert to UTF-8 for assertion
std::string output;
SCXCoreLib::Utf16leToUtf8(input, output);
EXPECT_EQ(userName, output);
}
|
Add import path to gamewindow example | #include <QGuiApplication>
#include <QQuickView>
int main(int argc, char *argv[]) {
QGuiApplication app(argc, argv);
QQuickView view;
view.setSource(QUrl::fromLocalFile("GameWindow.qml"));
view.show();
return app.exec();
}
| #include <QGuiApplication>
#include <QQuickView>
#include <QDeclarativeEngine>
#include <QDir>
int main(int argc, char *argv[]) {
QByteArray data = "1";
qputenv("QML_IMPORT_TRACE", data);
QGuiApplication app(argc, argv);
QQuickView view;
view.engine()->addImportPath("../../imports");
view.setSource(QUrl::fromLocalFile("GameWindow.qml"));
view.show();
return app.exec();
}
|
Fix template game by using default event listener | //Precompiled header are used in this project
#include "stdafx.h"
//Include Annwvyn Engine.
#include <Annwvyn.h>
//Every Annwvyn classes are in the Annwvyn namespace
using namespace Annwvyn;
//Include our level/stages here
#include "myLevel.hpp"
AnnMain() //The application entry point is "AnnMain()". return type int.
{
//Initialize the engine
new AnnEngine("A game using Annwvyn");
//Load your ressources here
AnnEngine::Instance()->initResources();
AnnEngine::Instance()->oculusInit();
//If the player has to folow the integrated physics scheme
AnnEngine::Instance()->initPlayerPhysics();
//Do the other initialization herttEventListener(); //Basic events
//Intentiate and register our basic level
AnnEngine::Instance()->getLevelManager()->addLevel(new MyLevel);
//This will make the game load and start the 1st we have registered
AnnEngine::Instance()->getLevelManager()->jumpToFirstLevel();
//This will recenter the facing direction of the player
//in the real world with the VR
AnnEngine::Instance()->resetOculusOrientation();
//The game is rendering here now:
AnnEngine::Instance()->startGameplayLoop();
//destroy the engine
delete AnnEngine::Instance();
return EXIT_SUCCESS;
}
| //Precompiled header are used in this project
#include "stdafx.h"
//Include Annwvyn Engine.
#include <Annwvyn.h>
//Every Annwvyn classes are in the Annwvyn namespace
using namespace Annwvyn;
//Include our level/stages here
#include "myLevel.hpp"
AnnMain() //The application entry point is "AnnMain()". return type int.
{
//Initialize the engine
AnnEngine::openConsole();
new AnnEngine("A game using Annwvyn");
//Load your ressources here
AnnEngine::Instance()->initResources();
AnnEngine::Instance()->oculusInit();
//If the player has to folow the integrated physics scheme
AnnEngine::Instance()->initPlayerPhysics();
//Do the other initialization herttEventListener(); //Basic events
//Intentiate and register our basic level
AnnEngine::Instance()->getLevelManager()->addLevel(new MyLevel);
//This will make the game load and start the 1st we have registered
AnnEngine::Instance()->getLevelManager()->jumpToFirstLevel();
//This will recenter the facing direction of the player
//in the real world with the VR
AnnEngine::Instance()->resetOculusOrientation();
//The game is rendering here now:
AnnEngine::Instance()->useDefaultEventListener();
AnnEngine::Instance()->startGameplayLoop();
//destroy the engine
delete AnnEngine::Instance();
return EXIT_SUCCESS;
}
|
Improve the file reading code to not be so buggy | #include <string>
#include <fstream>
#include <streambuf>
#include "exceptions.h"
#include "file_utils.h"
namespace file_utils {
std::vector<unicode> read_lines(const unicode& filename) {
unicode contents = read(filename);
return unicode(contents).split("\n");
}
unicode read(const unicode& filename) {
std::ifstream t(filename.encode().c_str());
if(!t) {
throw IOError(_u("Unable to load file") + filename);
}
std::string str((std::istreambuf_iterator<char>(t)),
std::istreambuf_iterator<char>());
return unicode(str);
}
}
| #include <string>
#include <fstream>
#include <streambuf>
#include "exceptions.h"
#include "file_utils.h"
namespace file_utils {
std::vector<unicode> read_lines(const unicode& filename) {
unicode contents = read(filename);
return unicode(contents).split("\n");
}
unicode read(const unicode& filename) {
std::ifstream in(filename.encode().c_str());
if(!in) {
throw IOError(_u("Unable to load file") + filename);
}
auto str = [&in]{
std::ostringstream ss{};
ss << in.rdbuf();
return ss.str();
}();
return unicode(str);
}
}
|
Make Mojo test more strict. | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ppapi/tests/mojo/test_mojo.h"
#include "third_party/mojo/src/mojo/public/cpp/system/message_pipe.h"
REGISTER_TEST_CASE(Mojo);
TestMojo::TestMojo(TestingInstance* instance) : TestCase(instance) { }
bool TestMojo::Init() {
return true;
}
void TestMojo::RunTests(const std::string& filter) {
RUN_TEST(CreateMessagePipe, filter);
}
std::string TestMojo::TestCreateMessagePipe() {
mojo::MessagePipe pipe;
PASS();
}
| // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ppapi/tests/mojo/test_mojo.h"
#include "third_party/mojo/src/mojo/public/cpp/system/message_pipe.h"
REGISTER_TEST_CASE(Mojo);
TestMojo::TestMojo(TestingInstance* instance) : TestCase(instance) { }
bool TestMojo::Init() {
return true;
}
void TestMojo::RunTests(const std::string& filter) {
RUN_TEST(CreateMessagePipe, filter);
}
std::string TestMojo::TestCreateMessagePipe() {
MojoHandle h0;
MojoHandle h1;
ASSERT_EQ(MOJO_RESULT_OK, MojoCreateMessagePipe(NULL, &h0, &h1));
PASS();
}
|
Fix type_name tests under Windows | #include <mettle.hpp>
using namespace mettle;
struct my_type {};
namespace my_namespace {
struct another_type {};
}
suite<> test_type_name("type_name()", [](auto &_) {
_.test("primitives", []() {
expect(type_name<int>(), equal_to("int"));
expect(type_name<int &>(), regex_match("int\\s*&"));
expect(type_name<int &&>(), regex_match("int\\s*&&"));
expect(type_name<const int>(), equal_to("const int"));
expect(type_name<volatile int>(), equal_to("volatile int"));
expect(type_name<const volatile int>(), equal_to("const volatile int"));
});
_.test("custom types", []() {
expect(type_name<my_type>(), equal_to("my_type"));
expect(type_name<my_namespace::another_type>(),
equal_to("my_namespace::another_type"));
});
});
| #include <mettle.hpp>
using namespace mettle;
struct my_type {};
namespace my_namespace {
struct another_type {};
}
suite<> test_type_name("type_name()", [](auto &_) {
_.test("primitives", []() {
expect(type_name<int>(), equal_to("int"));
expect(type_name<int &>(), regex_match("int\\s*&"));
expect(type_name<int &&>(), regex_match("int\\s*&&"));
expect(type_name<const int>(), equal_to("const int"));
expect(type_name<volatile int>(), equal_to("volatile int"));
expect(type_name<const volatile int>(), any(
equal_to("const volatile int"),
equal_to("volatile const int")
));
});
_.test("custom types", []() {
expect(type_name<my_type>(), regex_match("(struct )?my_type$"));
expect(type_name<my_namespace::another_type>(),
regex_match("(struct )?my_namespace::another_type$"));
});
});
|
Update about tab for Updater move | #include "About.h"
#include "../../3RVX/Updater.h"
#include "../resource.h"
void About::Initialize() {
INIT_CONTROL(LBL_TITLE, Label, _title);
std::wstring version = Updater::MainAppVersionString();
_title.Text(L"3RVX " + version);
}
void About::LoadSettings() {
}
void About::SaveSettings() {
}
| #include "About.h"
#include "../Updater.h"
#include "../resource.h"
void About::Initialize() {
INIT_CONTROL(LBL_TITLE, Label, _title);
std::wstring version = Updater::MainAppVersionString();
_title.Text(L"3RVX " + version);
}
void About::LoadSettings() {
}
void About::SaveSettings() {
}
|
Fix driver test so it doesn't fail if another oftr process is running. | // Copyright (c) 2015-2017 William W. Fisher (at gmail dot com)
// This file is distributed under the MIT License.
#include "ofp/driver.h"
#include "ofp/unittest.h"
using namespace ofp;
class MockChannelListener : public ChannelListener {
public:
void onChannelUp(Channel *channel) override {}
void onChannelDown(Channel *channel) override {}
void onMessage(const Message *message) override;
};
void MockChannelListener::onMessage(const Message *message) {}
TEST(driver, test) {
Driver driver;
// Test installing signal handlers more than once.
driver.installSignalHandlers();
driver.installSignalHandlers();
std::error_code err;
UInt64 connId = driver.listen(
ChannelOptions::FEATURES_REQ, 0, IPv6Endpoint{OFPGetDefaultPort()},
ProtocolVersions::All, [] { return new MockChannelListener; }, err);
EXPECT_NE(0, connId);
// Don't call driver.run(). This test just tests initialization.
// driver.run();
}
| // Copyright (c) 2015-2017 William W. Fisher (at gmail dot com)
// This file is distributed under the MIT License.
#include "ofp/driver.h"
#include "ofp/unittest.h"
using namespace ofp;
class MockChannelListener : public ChannelListener {
public:
void onChannelUp(Channel *channel) override {}
void onChannelDown(Channel *channel) override {}
void onMessage(const Message *message) override;
};
void MockChannelListener::onMessage(const Message *message) {}
TEST(driver, test) {
Driver driver;
// Test installing signal handlers more than once.
driver.installSignalHandlers();
driver.installSignalHandlers();
std::error_code err;
UInt16 listenPort = UInt16_narrow_cast(OFPGetDefaultPort() + 10000);
UInt64 connId = driver.listen(
ChannelOptions::FEATURES_REQ, 0, {"127.0.0.1", listenPort},
ProtocolVersions::All, [] { return new MockChannelListener; }, err);
EXPECT_NE(0, connId);
// Don't call driver.run(). This test just tests initialization.
// driver.run();
}
|
Implement the algorithm as described in the problem | #include "sieve.h"
#include <cmath>
namespace
{
bool is_prime(int n)
{
if (n % 2 == 0) {
return false;
}
const int max_factor = static_cast<int>(std::sqrt(n));
for (int probe = 2; probe <= max_factor; ++probe) {
if (n % probe == 0) {
return false;
}
}
return true;
}
}
namespace sieve
{
std::vector<int> primes(int n)
{
std::vector<int> result;
if (n >= 2) {
result.push_back(2);
}
for (int candidate = 3; candidate < n; ++candidate) {
if (is_prime(candidate)) {
result.push_back(candidate);
}
}
return result;
}
}
| #include "sieve.h"
#include <algorithm>
#include <list>
#include <numeric>
namespace sieve
{
std::vector<int> primes(int n)
{
std::vector<int> result;
std::list<int> candidates(n-1);
std::iota(candidates.begin(), candidates.end(), 2);
while (!candidates.empty()) {
const int next = candidates.front();
candidates.pop_front();
result.push_back(next);
candidates.remove_if([next](int n) { return n % next == 0; });
}
return result;
}
}
|
Change default background color to black |
#include <gloperate/painter/Painter.h>
namespace gloperate
{
Painter::Painter(const std::string & name, ResourceManager & resourceManager, const std::string & relDataPath)
: Object(name)
, m_resourceManager(resourceManager)
, m_relDataPath(relDataPath)
, m_backgroundColor(1.0, 1.0, 1.0)
{
}
Painter::~Painter()
{
for (auto & capability : m_capabilities)
{
delete capability;
}
}
void Painter::initialize()
{
onInitialize();
}
void Painter::paint()
{
onPaint();
}
glm::vec3 Painter::backgroundColor() const
{
return m_backgroundColor;
}
void Painter::setBackgroundColor(const glm::vec3 & color)
{
m_backgroundColor = color;
}
AbstractCapability * Painter::addCapability(AbstractCapability * capability)
{
m_capabilities.push_back(capability);
return capability;
}
} // namespace gloperate
|
#include <gloperate/painter/Painter.h>
namespace gloperate
{
Painter::Painter(const std::string & name, ResourceManager & resourceManager, const std::string & relDataPath)
: Object(name)
, m_resourceManager(resourceManager)
, m_relDataPath(relDataPath)
, m_backgroundColor(0.0, 0.0, 0.0)
{
}
Painter::~Painter()
{
for (auto & capability : m_capabilities)
{
delete capability;
}
}
void Painter::initialize()
{
onInitialize();
}
void Painter::paint()
{
onPaint();
}
glm::vec3 Painter::backgroundColor() const
{
return m_backgroundColor;
}
void Painter::setBackgroundColor(const glm::vec3 & color)
{
m_backgroundColor = color;
}
AbstractCapability * Painter::addCapability(AbstractCapability * capability)
{
m_capabilities.push_back(capability);
return capability;
}
} // namespace gloperate
|
Include SkTypes to fix Android frameworks build | /*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifdef SK_BUILD_FOR_ANDROID
#include "SkPicturePlayback.h"
#endif
#include "SkPictureRecorder.h"
SkCanvas* SkPictureRecorder::beginRecording(int width, int height,
SkBBHFactory* bbhFactory /* = NULL */,
uint32_t recordFlags /* = 0 */) {
fPicture.reset(SkNEW(SkPicture));
return fPicture->beginRecording(width, height, bbhFactory, recordFlags);
}
#ifdef SK_BUILD_FOR_ANDROID
void SkPictureRecorder::partialReplay(SkCanvas* canvas) {
if (NULL == fPicture.get() || NULL == canvas) {
// Not recording or nothing to replay into
return;
}
SkASSERT(NULL != fPicture->fRecord);
SkAutoTDelete<SkPicturePlayback> playback(SkPicture::FakeEndRecording(fPicture,
*fPicture->fRecord,
false));
playback->draw(*canvas, NULL);
}
#endif
| /*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
// Need to include SkTypes first, so that SK_BUILD_FOR_ANDROID is defined.
#include "SkTypes.h"
#ifdef SK_BUILD_FOR_ANDROID
#include "SkPicturePlayback.h"
#endif
#include "SkPictureRecorder.h"
SkCanvas* SkPictureRecorder::beginRecording(int width, int height,
SkBBHFactory* bbhFactory /* = NULL */,
uint32_t recordFlags /* = 0 */) {
fPicture.reset(SkNEW(SkPicture));
return fPicture->beginRecording(width, height, bbhFactory, recordFlags);
}
#ifdef SK_BUILD_FOR_ANDROID
void SkPictureRecorder::partialReplay(SkCanvas* canvas) {
if (NULL == fPicture.get() || NULL == canvas) {
// Not recording or nothing to replay into
return;
}
SkASSERT(NULL != fPicture->fRecord);
SkAutoTDelete<SkPicturePlayback> playback(SkPicture::FakeEndRecording(fPicture,
*fPicture->fRecord,
false));
playback->draw(*canvas, NULL);
}
#endif
|
Remove unistd.h inclusion for Windows | #include "blif_lexer.hpp"
#include "blif_lexer.gen.hpp" //For blifparse_lex_*()
extern YY_DECL; //For blifparse_lex()
namespace blifparse {
Lexer::Lexer(FILE* file, Callback& callback)
: callback_(callback) {
blifparse_lex_init(&state_);
blifparse_set_in(file, state_);
}
Lexer::~Lexer() {
blifparse_lex_destroy(state_);
}
Parser::symbol_type Lexer::next_token() {
return blifparse_lex(state_, callback_);
}
const char* Lexer::text() const {
return blifparse_get_text(state_);
}
int Lexer::lineno() const {
return blifparse_get_lineno(state_);
}
}
| #include "blif_lexer.hpp"
//Windows doesn't have unistd.h, so we set '%option nounistd'
//in blif_lexer.l, but flex still includes it in the generated
//header unless YY_NO_UNISTD_H is defined to 1
#define YY_NO_UNISTD_H 1
#include "blif_lexer.gen.hpp" //For blifparse_lex_*()
extern YY_DECL; //For blifparse_lex()
namespace blifparse {
Lexer::Lexer(FILE* file, Callback& callback)
: callback_(callback) {
blifparse_lex_init(&state_);
blifparse_set_in(file, state_);
}
Lexer::~Lexer() {
blifparse_lex_destroy(state_);
}
Parser::symbol_type Lexer::next_token() {
return blifparse_lex(state_, callback_);
}
const char* Lexer::text() const {
return blifparse_get_text(state_);
}
int Lexer::lineno() const {
return blifparse_get_lineno(state_);
}
}
|
Fix ``enter_replace_mode`` so that it works properly | #include <ncurses.h>
#include "../../../src/contents.hh"
#include "../../../src/key_aliases.hh"
#include "../../vick-move/src/move.hh"
void enter_insert_mode(contents& contents, boost::optional<int>) {
char ch;
contents.is_inserting = true;
while((ch = getch()) != _escape) {
contents.cont[contents.y].insert(contents.x, 1, ch);
mvf(contents);
if(get_contents().refresh) {
print_contents(get_contents());
}
}
contents.is_inserting = false;
}
void enter_replace_mode(contents& contents, boost::optional<int>) {
char ch;
contents.is_inserting = true;
while((ch = getch()) != _escape) {
if(contents.x >= contents.cont[contents.y].size()) {
contents.cont[contents.y].push_back(ch);
} else {
contents.cont[contents.y][contents.x] = ch;
}
if(get_contents().refresh) {
print_contents(get_contents());
}
}
contents.is_inserting = false;
}
| #include <ncurses.h>
#include "../../../src/contents.hh"
#include "../../../src/key_aliases.hh"
#include "../../vick-move/src/move.hh"
void enter_insert_mode(contents& contents, boost::optional<int>) {
char ch;
contents.is_inserting = true;
while((ch = getch()) != _escape) {
contents.cont[contents.y].insert(contents.x, 1, ch);
mvf(contents);
if(get_contents().refresh) {
print_contents(get_contents());
}
}
contents.is_inserting = false;
}
void enter_replace_mode(contents& contents, boost::optional<int>) {
char ch;
contents.is_inserting = true;
while((ch = getch()) != _escape) {
if(contents.x >= contents.cont[contents.y].size()) {
contents.cont[contents.y].push_back(ch);
contents.x = contents.cont[contents.y].size();
} else {
contents.cont[contents.y][contents.x] = ch;
contents.x++;
}
if(get_contents().refresh) {
print_contents(get_contents());
}
}
contents.is_inserting = false;
}
|
Fix compile error on penguin sample game | #include "Penguin.h"
void Penguin::processEvents(SDL_Event* a_event)
{
if (a_event->type == SDL_KEYDOWN)
{
switch (a_event->key.keysym.sym)
{
case SDLK_LEFT:
{
} break;
case SDLK_RIGHT:
{
} break;
}
}
}
void Penguin::update(float a_deltaT)
{
}
void Penguin::startJump()
{
if (m_onTheGround == true)
{
m_onTheGround = false;
}
}
void Peguin::endJump()
{
}
| #include "Penguin.h"
void Penguin::processEvents(SDL_Event* a_event)
{
if (a_event->type == SDL_KEYDOWN)
{
switch (a_event->key.keysym.sym)
{
case SDLK_LEFT:
{
} break;
case SDLK_RIGHT:
{
} break;
}
}
}
void Penguin::update(float a_deltaT)
{
}
void Penguin::startJump()
{
if (m_jumping == false)
{
m_jumping = true;
}
}
void Penguin::endJump()
{
}
|
Improve benchmarks by batching data. | // Copyright 2020 The Google Research Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "benchmark_utils.h"
#include <utility>
#include "benchmark/benchmark.h"
#include "sketch.h"
#include "utils.h"
namespace sketch {
void Add(benchmark::State& state, Sketch* sketch) {
for (auto _ : state) {
state.PauseTiming();
sketch->Reset();
auto data = sketch::CreateStream(state.range(0)).first;
state.ResumeTiming();
for (const auto& [item, freq] : data) {
sketch->Add(item, freq);
}
}
}
} // namespace sketch
| // Copyright 2020 The Google Research Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "benchmark_utils.h"
#include <utility>
#include "benchmark/benchmark.h"
#include "sketch.h"
#include "utils.h"
namespace sketch {
constexpr int kAddBatchSize = 32;
auto MakeAddStreams(int count) {
std::vector<std::vector<IntFloatPair>> streams(kAddBatchSize);
for (auto& stream : streams) {
stream = CreateStream(count).first;
}
return streams;
}
void Add(benchmark::State& state, Sketch* sketch) {
auto streams = MakeAddStreams(state.range(0));
while (state.KeepRunningBatch(kAddBatchSize)) {
for (const auto& stream : streams) {
for (const auto& [item, freq] : stream) {
sketch->Add(item, freq);
}
}
}
}
} // namespace sketch
|
Add Basic Message Recieve implementation | #include "msglistener.h"
#include <ei_connect.h>
namespace Mailbox {
MsgListener::MsgListener(int fd, QObject *parent) :
QThread(parent),
m_fd(fd)
{
}
void MsgListener::run()
{
}
} // namespace Mailbox
| #include "msglistener.h"
#include <ei_connect.h>
namespace Mailbox {
MsgListener::MsgListener(int fd, QObject *parent) :
QThread(parent),
m_fd(fd)
{
}
void MsgListener::run()
{
int length;
erlang_msg msg;
ei_x_buff buff;
ei_x_new(&buff);
length = ei_xreceive_msg_tmo(m_fd, &msg, &buff, 1000);
if (length > 0 && (msg.msgtype == ERL_SEND || msg.msgtype == ERL_REG_SEND))
emit messageRecieved();
ei_x_free(&buff);
}
} // namespace Mailbox
|
Improve error messages of the Profiler. | /* Copyright 2020 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/profiler/utils/errors.h"
namespace tensorflow {
namespace profiler {
const absl::string_view kErrorIncompleteStep =
"Visualization based on incomplete step. No step markers observed and "
"hence the step time is actually unknown. Instead, we use the trace "
"duration as the step time. This may happen if your profiling duration "
"is shorter than the step time. In that case, you may try to profile "
"longer.";
const absl::string_view kErrorNoStepMarker =
"Visualization contains on step based analysis. No step markers observed "
"and hence the step time is actually unknown. This may happen if your "
"profiling duration is shorter than the step time. In that case, you may "
"try to profile longer.";
} // namespace profiler
} // namespace tensorflow
| /* Copyright 2020 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/profiler/utils/errors.h"
namespace tensorflow {
namespace profiler {
const absl::string_view kErrorIncompleteStep =
"Incomplete step observed and hence the step time is unknown."
"Instead, we use the trace duration as the step time. This may happen"
" if your profiling duration is shorter than the step time. In this"
" case, you may try to profile longer.";
const absl::string_view kErrorNoStepMarker =
"No step marker observed and hence the step time is unknown."
" This may happen if (1) training steps are not instrumented (e.g., if"
" you are not using Keras) or (2) the profiling duration is shorter"
" than the step time. For (1), you need to add step instrumentation;"
" for (2), you may try to profile longer.";
} // namespace profiler
} // namespace tensorflow
|
Remove redundant escaping in allowed check. | #include <algorithm>
#include "url.h"
#include "agent.h"
#include "directive.h"
namespace Rep
{
Agent& Agent::allow(const std::string& query)
{
directives_.push_back(Directive(escape(query), true));
sorted_ = false;
return *this;
}
Agent& Agent::disallow(const std::string& query)
{
if (query.empty())
{
// Special case: "Disallow:" means "Allow: /"
directives_.push_back(Directive(query, true));
}
else
{
directives_.push_back(Directive(escape(query), false));
}
sorted_ = false;
return *this;
}
const std::vector<Directive>& Agent::directives() const
{
if (!sorted_)
{
std::sort(directives_.begin(), directives_.end(), [](const Directive& a, const Directive& b) {
return b.priority() < a.priority();
});
sorted_ = true;
}
return directives_;
}
bool Agent::allowed(const std::string& query) const
{
std::string path(escape(query));
if (path.compare("/robots.txt") == 0)
{
return true;
}
std::string escaped = escape(path);
for (auto directive : directives())
{
if (directive.match(escaped))
{
return directive.allowed();
}
}
return true;
}
std::string Agent::escape(const std::string& query)
{
return Url::Url(query).defrag().escape().fullpath();
}
}
| #include <algorithm>
#include "url.h"
#include "agent.h"
#include "directive.h"
namespace Rep
{
Agent& Agent::allow(const std::string& query)
{
directives_.push_back(Directive(escape(query), true));
sorted_ = false;
return *this;
}
Agent& Agent::disallow(const std::string& query)
{
if (query.empty())
{
// Special case: "Disallow:" means "Allow: /"
directives_.push_back(Directive(query, true));
}
else
{
directives_.push_back(Directive(escape(query), false));
}
sorted_ = false;
return *this;
}
const std::vector<Directive>& Agent::directives() const
{
if (!sorted_)
{
std::sort(directives_.begin(), directives_.end(), [](const Directive& a, const Directive& b) {
return b.priority() < a.priority();
});
sorted_ = true;
}
return directives_;
}
bool Agent::allowed(const std::string& query) const
{
std::string path(escape(query));
if (path.compare("/robots.txt") == 0)
{
return true;
}
for (auto directive : directives())
{
if (directive.match(path))
{
return directive.allowed();
}
}
return true;
}
std::string Agent::escape(const std::string& query)
{
return Url::Url(query).defrag().escape().fullpath();
}
}
|
Add blank name for loop syntax. | // Copyright 2015 Adam Grandquist
#include "./test.hpp"
#include "./ReQL.hpp"
void
consume(ReQL::Cursor<ReQL::Result> cursor) {
for (auto && : cursor) {}
}
| // Copyright 2015 Adam Grandquist
#include "./test.hpp"
#include "./ReQL.hpp"
void
consume(ReQL::Cursor<ReQL::Result> cursor) {
for (auto &&_ : cursor) {}
}
|
Fix forgetting generating interfaces for explorer | // AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from wallet.djinni
#include "CosmosConfigurationDefaults.hpp" // my header
namespace ledger { namespace core { namespace api {
std::string const CosmosConfigurationDefaults::COSMOS_DEFAULT_API_ENDPOINT = {"http://lite-client-0e27eefb-4031-4859-a88e-249fd241989d.cosmos.bison.run:1317"};
std::string const CosmosConfigurationDefaults::COSMOS_OBSERVER_WS_ENDPOINT = {""};
} } } // namespace ledger::core::api
| // AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from wallet.djinni
#include "CosmosConfigurationDefaults.hpp" // my header
namespace ledger { namespace core { namespace api {
std::string const CosmosConfigurationDefaults::COSMOS_DEFAULT_API_ENDPOINT = {"https://cosmos.coin.staging.aws.ledger.com"};
std::string const CosmosConfigurationDefaults::COSMOS_OBSERVER_WS_ENDPOINT = {""};
} } } // namespace ledger::core::api
|
Test commit EMAIL PROBLEM MEANS COMMITS DONT COUNT | //
// Created by Alex Gurung
//
#include "helper.h"
void testnums(unsigned long long int hail){
unsigned long long int orghail = hail;
while(hail!= 0){
hail = testHail(hail); //Within helper.h file, testHail returns the next hailstone number, or 0 if you get to 4
}
cout << orghail << endl;
}
int main(){
unsigned long long int counter = 10000;
for(unsigned long long int i = 5476377146882523136; i<18446744073709551615 ; i++){
//18446744073709551615 is the largest value available for an unsigned long long int, and 5476377146882523136 was the previous largest tested value
testnums(i);
}
return 0;
}
| //
// Created by Alex Gurung
//
#include "helper.h"
void testnums(unsigned long long int hail){
unsigned long long int orghail = hail;
while(hail!= 0){
hail = testHail(hail); //Within helper.h file, testHail returns the next hailstone number, or 0 if you get to 4
}
cout << orghail << endl; //This is a test commit
}
int main(){
unsigned long long int counter = 10000;
for(unsigned long long int i = 5476377146882523136; i<18446744073709551615 ; i++){
//18446744073709551615 is the largest value available for an unsigned long long int, and 5476377146882523136 was the previous largest tested value
testnums(i);
}
return 0;
}
|
Add sample code for PWM | /**
******************************************************************************
* @file main.c
* @author Ac6
* @version V1.0
* @date 01-December-2013
* @brief Default main function.
******************************************************************************
*/
#include "stm32f4xx.h"
#include "stm32f4xx_nucleo.h"
#include "stm32f4xx_hal.h"
extern "C" void initialise_monitor_handles(void);
int main(void)
{
HAL_Init();
initialise_monitor_handles();
for(;;);
}
| /**
******************************************************************************
* @file main.c
* @author Ac6
* @version V1.0
* @date 01-December-2013
* @brief Default main function.
******************************************************************************
*/
#include "stm32f4xx.h"
#include "stm32f4xx_nucleo.h"
#include "stm32f4xx_hal.h"
#include "PWM_Generator.h"
extern "C" void initialise_monitor_handles(void);
int main(void)
{
HAL_Init();
//initialise_monitor_handles();
PWM_Generator *pwm = PWM_Generator::Instance();
pwm->Init();
pwm->Arm(NULL);
pwm->SetPulse(1050, 1);
pwm->SetPulse(1050, 2);
pwm->SetPulse(1050, 3);
pwm->SetPulse(1050, 4);
for(;;);
}
|
Revert "use file based webkit cache in desktop mode" (was crashing when opening the history pane on linux) | /*
* DesktopNetworkAccessManager.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "DesktopNetworkAccessManager.hpp"
#include <QNetworkDiskCache>
#include <QDesktopServices>
#include <core/FilePath.hpp>
using namespace core;
NetworkAccessManager::NetworkAccessManager(QString secret, QObject *parent) :
QNetworkAccessManager(parent), secret_(secret)
{
setProxy(QNetworkProxy::NoProxy);
// initialize cache
QString cacheDir =
QDesktopServices::storageLocation(QDesktopServices::CacheLocation);
FilePath cachePath(cacheDir.toUtf8().constData());
FilePath browserCachePath = cachePath.complete("RStudioWebkit");
Error error = browserCachePath.ensureDirectory();
if (!error)
{
QNetworkDiskCache* pCache = new QNetworkDiskCache(parent);
QString browserCacheDir = QString::fromUtf8(
browserCachePath.absolutePath().c_str());
pCache->setCacheDirectory(browserCacheDir);
setCache(pCache);
}
else
{
LOG_ERROR(error);
}
}
QNetworkReply* NetworkAccessManager::createRequest(
Operation op,
const QNetworkRequest& req,
QIODevice* outgoingData)
{
QNetworkRequest req2 = req;
req2.setRawHeader("X-Shared-Secret",
secret_.toAscii());
return this->QNetworkAccessManager::createRequest(op, req2, outgoingData);
}
| /*
* DesktopNetworkAccessManager.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "DesktopNetworkAccessManager.hpp"
NetworkAccessManager::NetworkAccessManager(QString secret, QObject *parent) :
QNetworkAccessManager(parent), secret_(secret)
{
setProxy(QNetworkProxy::NoProxy);
}
QNetworkReply* NetworkAccessManager::createRequest(
Operation op,
const QNetworkRequest& req,
QIODevice* outgoingData)
{
QNetworkRequest req2 = req;
req2.setRawHeader("X-Shared-Secret",
secret_.toAscii());
return this->QNetworkAccessManager::createRequest(op, req2, outgoingData);
}
|
Update Floyd with input output | #include <iostream>
using namespace std;
int main() {
int a[100][100];
int d[100][100];
a = d;
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
d[i][j] = min(d[i][j], d[i][k] + d[k][j]);
}
}
}
} | #include <iostream>
using namespace std;
int main() {
int n = 4;
int a[n][n];
int d[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> a[i][j];
d[i][j] = a[i][j];
}
}
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
d[i][j] = min(d[i][j], d[i][k] + d[k][j]);
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << d[i][j] << ' ';
}
cout << endl;
}
} |
Fix integer casting issues in Mac OSS build | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "SimplifyCFG.h"
#include "ControlFlow.h"
#include "DexClass.h"
#include "IRCode.h"
#include "Walkers.h"
void SimplifyCFGPass::run_pass(DexStoresVector& stores,
ConfigFiles& /* unused */,
PassManager& mgr) {
const auto& scope = build_class_scope(stores);
auto total_insns_removed =
walk::parallel::reduce_methods<std::nullptr_t, int64_t, Scope>(
scope,
[](std::nullptr_t, DexMethod* m) {
auto code = m->get_code();
if (code == nullptr) {
return 0l;
}
int64_t before_insns = code->count_opcodes();
// build and linearize the CFG
code->build_cfg(/* editable */ true);
code->clear_cfg();
int64_t after_insns = code->count_opcodes();
return before_insns - after_insns;
},
[](int64_t a, int64_t b) { return a + b; },
[](int) { return nullptr; }, 0);
mgr.set_metric("insns_removed", total_insns_removed);
}
static SimplifyCFGPass s_pass;
| /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "SimplifyCFG.h"
#include "ControlFlow.h"
#include "DexClass.h"
#include "IRCode.h"
#include "Walkers.h"
void SimplifyCFGPass::run_pass(DexStoresVector& stores,
ConfigFiles& /* unused */,
PassManager& mgr) {
const auto& scope = build_class_scope(stores);
auto total_insns_removed =
walk::parallel::reduce_methods<std::nullptr_t, int64_t, Scope>(
scope,
[](std::nullptr_t, DexMethod* m) -> int64_t {
auto code = m->get_code();
if (code == nullptr) {
return 0;
}
int64_t before_insns = code->count_opcodes();
// build and linearize the CFG
code->build_cfg(/* editable */ true);
code->clear_cfg();
int64_t after_insns = code->count_opcodes();
return before_insns - after_insns;
},
[](int64_t a, int64_t b) { return a + b; },
[](int) { return nullptr; }, 0);
mgr.set_metric("insns_removed", total_insns_removed);
}
static SimplifyCFGPass s_pass;
|
Use a const_iterator in ClosedList::lookup. | /* -*- mode:linux -*- */
/**
* \file closed_list.cc
*
*
*
* \author Ethan Burns
* \date 2008-10-09
*/
#include <map>
#include "state.h"
#include "closed_list.h"
void ClosedList::add(const State *s)
{
m[s->hash()] = s;
}
const State *ClosedList::lookup(const State *c) const
{
// this is stupid: apparently you can't do an assignment with
// iterators, so instead we need to do two lookups.
if (m.find(c->hash()) == m.end())
return NULL;
return m.find(c->hash())->second;
}
/**
* Delete (free up the memory for) all states in the closed list.
*/
void ClosedList::delete_all_states(void)
{
map<int, const State *>::iterator iter;
for (iter = m.begin(); iter != m.end(); iter++)
delete iter->second;
}
| /* -*- mode:linux -*- */
/**
* \file closed_list.cc
*
*
*
* \author Ethan Burns
* \date 2008-10-09
*/
#include <map>
#include "state.h"
#include "closed_list.h"
void ClosedList::add(const State *s)
{
m[s->hash()] = s;
}
const State *ClosedList::lookup(const State *c) const
{
map<int, const State *>::const_iterator iter;
iter = m.find(c->hash());
if (iter == m.end())
return NULL;
return iter->second;
}
/**
* Delete (free up the memory for) all states in the closed list.
*/
void ClosedList::delete_all_states(void)
{
map<int, const State *>::iterator iter;
for (iter = m.begin(); iter != m.end(); iter++)
delete iter->second;
}
|
Add type hint for java codegen |
/**************************************************
* Source Code for the Original Compiler for the
* Programming Language Wake
*
* EarlyBailoutMethodInvecation.cpp
*
* Licensed under the MIT license
* See LICENSE.TXT for details
*
* Author: Michael Fairhurst
* Revised By:
*
**************************************************/
#include "ast/EarlyBailoutMethodInvocation.h"
#include "TypeError.h"
using namespace wake;
PureType<QUALIFIED>* ast::EarlyBailoutMethodInvocation::typeCheck(bool forceArrayIdentifier) {
PureType<QUALIFIED> subject = *auto_ptr<PureType<QUALIFIED> >(subjectExpr->typeCheck(false));
if(subject.type == TYPE_MATCHALL) {
return new PureType<QUALIFIED>(subject);
} else if(subject.type != TYPE_OPTIONAL) {
errors->addError(new SemanticError(OPTIONAL_USE_OF_NONOPTIONAL_TYPE, "using .? on a nonoptional", node));
return new PureType<QUALIFIED>(TYPE_MATCHALL);
} else {
PureType<QUALIFIED>* ret = new PureType<QUALIFIED>(TYPE_OPTIONAL);
PureType<QUALIFIED>* nonoptional = subject.typedata.optional.contained;
while(nonoptional->type == TYPE_OPTIONAL) {
nonoptional = nonoptional->typedata.optional.contained;
}
ret->typedata.optional.contained = typeCheckMethodInvocation(*nonoptional);
return ret;
}
}
|
/**************************************************
* Source Code for the Original Compiler for the
* Programming Language Wake
*
* EarlyBailoutMethodInvecation.cpp
*
* Licensed under the MIT license
* See LICENSE.TXT for details
*
* Author: Michael Fairhurst
* Revised By:
*
**************************************************/
#include "ast/EarlyBailoutMethodInvocation.h"
#include "TypeError.h"
using namespace wake;
PureType<QUALIFIED>* ast::EarlyBailoutMethodInvocation::typeCheck(bool forceArrayIdentifier) {
PureType<QUALIFIED> subject = *auto_ptr<PureType<QUALIFIED> >(subjectExpr->typeCheck(false));
addSubNode(node, makeNodeFromPureType((PureType<UNQUALIFIED>*) new PureType<QUALIFIED>(subject), node->loc));
if(subject.type == TYPE_MATCHALL) {
return new PureType<QUALIFIED>(subject);
} else if(subject.type != TYPE_OPTIONAL) {
errors->addError(new SemanticError(OPTIONAL_USE_OF_NONOPTIONAL_TYPE, "using .? on a nonoptional", node));
return new PureType<QUALIFIED>(TYPE_MATCHALL);
} else {
PureType<QUALIFIED>* ret = new PureType<QUALIFIED>(TYPE_OPTIONAL);
PureType<QUALIFIED>* nonoptional = subject.typedata.optional.contained;
while(nonoptional->type == TYPE_OPTIONAL) {
nonoptional = nonoptional->typedata.optional.contained;
}
ret->typedata.optional.contained = typeCheckMethodInvocation(*nonoptional);
return ret;
}
}
|
Fix cluster controller runtime not defining addBroadcast() | /*
* #%L
* %%
* Copyright (C) 2011 - 2013 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
#include "joynr/JoynrRuntime.h"
#include "JoynrClusterControllerRuntime.h"
#include "joynr/SettingsMerger.h"
namespace joynr
{
JoynrRuntime* JoynrRuntime::createRuntime(const QString& pathToLibjoynrSettings,
const QString& pathToMessagingSettings)
{
QSettings* settings = SettingsMerger::mergeSettings(pathToLibjoynrSettings);
SettingsMerger::mergeSettings(pathToMessagingSettings, settings);
return JoynrClusterControllerRuntime::create(settings);
}
} // namespace joynr
| /*
* #%L
* %%
* Copyright (C) 2011 - 2013 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
#include "joynr/JoynrRuntime.h"
#include "JoynrClusterControllerRuntime.h"
#include "joynr/SettingsMerger.h"
namespace joynr
{
JoynrRuntime* JoynrRuntime::createRuntime(const QString& pathToLibjoynrSettings,
const QString& pathToMessagingSettings)
{
QSettings* settings = SettingsMerger::mergeSettings(pathToLibjoynrSettings);
SettingsMerger::mergeSettings(pathToMessagingSettings, settings);
return JoynrClusterControllerRuntime::create(settings);
}
void JoynrRuntime::addBroadcastFilter(QSharedPointer<IBroadcastFilter> filter)
{
if (!publicationManager) {
throw JoynrException("Exception in JoynrRuntime: PublicationManager not created yet.");
}
publicationManager->addBroadcastFilter(filter);
}
} // namespace joynr
|
Fix typo in test's REQUIRES line | // REQUIRES: shell
// MSYS doesn't emulate umask.
// FIXME: Could we introduce another feature for it?
// REQUIRES: shell-preserves-root'
// RUN: umask 000
// RUN: %clang_cc1 -emit-llvm-bc %s -o %t
// RUN: ls -l %t | FileCheck --check-prefix=CHECK000 %s
// CHECK000: rw-rw-rw-
// RUN: umask 002
// RUN: %clang_cc1 -emit-llvm-bc %s -o %t
// RUN: ls -l %t | FileCheck --check-prefix=CHECK002 %s
// CHECK002: rw-rw-r--
| // REQUIRES: shell
// MSYS doesn't emulate umask.
// FIXME: Could we introduce another feature for it?
// REQUIRES: shell-preserves-root
// RUN: umask 000
// RUN: %clang_cc1 -emit-llvm-bc %s -o %t
// RUN: ls -l %t | FileCheck --check-prefix=CHECK000 %s
// CHECK000: rw-rw-rw-
// RUN: umask 002
// RUN: %clang_cc1 -emit-llvm-bc %s -o %t
// RUN: ls -l %t | FileCheck --check-prefix=CHECK002 %s
// CHECK002: rw-rw-r--
|
Fix warning treated as error | // Copyright 2019 The SwiftShader 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.
// This file contains LLVM stub functions - these are functions that are never
// called and are declared to satisfy the linker.
#include <assert.h>
#define STUB() assert(!"Stub function. Should not be called");
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
namespace llvm
{
void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) { STUB(); }
} // namespace llvm
| // Copyright 2019 The SwiftShader 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.
// This file contains LLVM stub functions - these are functions that are never
// called and are declared to satisfy the linker.
#include <assert.h>
#define STUB() assert(false); // Stub function. Should not be called
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
namespace llvm
{
void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) { STUB(); }
} // namespace llvm
|
Disable ExtensionApiTest.Tabs on Mac. TEST=no random redness on Mac OS X 10.6 bot BUG=37387 TBR=skerner@ | // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
// TODO(skerner): This test is flaky in chromeos. Figure out why and fix.
#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)
#define MAYBE_Tabs DISABLED_Tabs
#else
#define MAYBE_Tabs Tabs
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) {
StartHTTPServer();
// The test creates a tab and checks that the URL of the new tab
// is that of the new tab page. Make sure the pref that controls
// this is set.
browser()->profile()->GetPrefs()->SetBoolean(
prefs::kHomePageIsNewTabPage, true);
ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_;
}
| // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
// TODO(skerner): This test is flaky in chromeos and on Mac OS X 10.6. Figure
// out why and fix.
#if (defined(OS_LINUX) && defined(TOOLKIT_VIEWS)) || defined(OS_MACOSX)
#define MAYBE_Tabs DISABLED_Tabs
#else
#define MAYBE_Tabs Tabs
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) {
StartHTTPServer();
// The test creates a tab and checks that the URL of the new tab
// is that of the new tab page. Make sure the pref that controls
// this is set.
browser()->profile()->GetPrefs()->SetBoolean(
prefs::kHomePageIsNewTabPage, true);
ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_;
}
|
Add the disconnect command to the factory. | /**
* Copyright 2014 Truphone
*/
#include "XmppHarness.h"
#include "CommandFactory.h"
#include "XmppResourceStore.h"
#include "XmppHelpCommand.h"
#include "XmppPresenceCommand.h"
#include "XmppConnectCommand.h"
#include "XmppMessageCommand.h"
namespace truphone
{
namespace test
{
namespace cascades
{
XmppHarness::XmppHarness(QObject *parent) :
QObject(parent)
{
}
XmppHarness::~XmppHarness()
{
}
bool XmppHarness::installHarness()
{
XMPPResourceStore::initialiseStore(this);
CommandFactory::installCommand(
XMPPHelpCommand::getCmd(),
&XMPPHelpCommand::create);
CommandFactory::installCommand(
XMPPConnectCommand::getCmd(),
&XMPPConnectCommand::create);
CommandFactory::installCommand(
XMPPPresenceCommand::getCmd(),
&XMPPPresenceCommand::create);
CommandFactory::installCommand(
XMPPMessageCommand::getCmd(),
&XMPPMessageCommand::create);
return true;
}
} // namespace cascades
} // namespace test
} // namespace truphone
| /**
* Copyright 2014 Truphone
*/
#include "XmppHarness.h"
#include "CommandFactory.h"
#include "XmppResourceStore.h"
#include "XmppHelpCommand.h"
#include "XmppPresenceCommand.h"
#include "XmppConnectCommand.h"
#include "XmppMessageCommand.h"
#include "XmppDisconnectCommand.h"
namespace truphone
{
namespace test
{
namespace cascades
{
XmppHarness::XmppHarness(QObject *parent) :
QObject(parent)
{
}
XmppHarness::~XmppHarness()
{
}
bool XmppHarness::installHarness()
{
XMPPResourceStore::initialiseStore(this);
CommandFactory::installCommand(
XMPPHelpCommand::getCmd(),
&XMPPHelpCommand::create);
CommandFactory::installCommand(
XMPPConnectCommand::getCmd(),
&XMPPConnectCommand::create);
CommandFactory::installCommand(
XMPPPresenceCommand::getCmd(),
&XMPPPresenceCommand::create);
CommandFactory::installCommand(
XMPPMessageCommand::getCmd(),
&XMPPMessageCommand::create);
CommandFactory::installCommand(
XMPPDisconnectCommand::getCmd(),
&XMPPDisconnectCommand::create);
return true;
}
} // namespace cascades
} // namespace test
} // namespace truphone
|
Clean up MetricsService unit test. | // 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/metrics/metrics_service.h"
#include <string>
#include "base/base64.h"
#include "testing/gtest/include/gtest/gtest.h"
class MetricsServiceTest : public ::testing::Test {
};
// Ensure the ClientId is formatted as expected.
TEST(MetricsServiceTest, ClientIdCorrectlyFormatted) {
std::string clientid = MetricsService::GenerateClientID();
EXPECT_EQ(36U, clientid.length());
std::string hexchars = "0123456789ABCDEF";
for (uint32 i = 0; i < clientid.length(); i++) {
char current = clientid.at(i);
if (i == 8 || i == 13 || i == 18 || i == 23) {
EXPECT_EQ('-', current);
} else {
EXPECT_TRUE(std::string::npos != hexchars.find(current));
}
}
}
TEST(MetricsServiceTest, IsPluginProcess) {
EXPECT_TRUE(
MetricsService::IsPluginProcess(content::PROCESS_TYPE_PLUGIN));
EXPECT_TRUE(
MetricsService::IsPluginProcess(content::PROCESS_TYPE_PPAPI_PLUGIN));
EXPECT_FALSE(
MetricsService::IsPluginProcess(content::PROCESS_TYPE_GPU));
}
| // 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 <ctype.h>
#include <string>
#include "chrome/browser/metrics/metrics_service.h"
#include "testing/gtest/include/gtest/gtest.h"
// Ensure the ClientId is formatted as expected.
TEST(MetricsServiceTest, ClientIdCorrectlyFormatted) {
std::string clientid = MetricsService::GenerateClientID();
EXPECT_EQ(36U, clientid.length());
for (size_t i = 0; i < clientid.length(); ++i) {
char current = clientid[i];
if (i == 8 || i == 13 || i == 18 || i == 23)
EXPECT_EQ('-', current);
else
EXPECT_TRUE(isxdigit(current));
}
}
TEST(MetricsServiceTest, IsPluginProcess) {
EXPECT_TRUE(
MetricsService::IsPluginProcess(content::PROCESS_TYPE_PLUGIN));
EXPECT_TRUE(
MetricsService::IsPluginProcess(content::PROCESS_TYPE_PPAPI_PLUGIN));
EXPECT_FALSE(
MetricsService::IsPluginProcess(content::PROCESS_TYPE_GPU));
}
|
Use relational node handle for topic communicate | #include "main_action_planner_node.hpp"
int main(int argc, char** argv) {
ros::init(argc, argv, "test_action_planner_node");
ros::NodeHandle nh {"~"};
StateChecker status {nh};
while (ros::ok()) {
auto posture_key = status.getPostureKey();
RequestPosture* rp_p = RequestPostureFactory::get(posture_key[0], nh);
if (!rp_p) {
ROS_INFO("Error: get nullptr by RP Factory: arg is [%s]", posture_key[0].c_str());
return -1;
}
SendPosture* sp_p = SendPostureFactory::get(posture_key[1], nh);
if (!sp_p) {
ROS_INFO("Error: get nullptr by SP Factory: arg is [%s]", posture_key[1].c_str());
return -1;
}
std::vector<double> angles;
rp_p->requestPosture(angles);
sp_p->sendPosture(angles);
ros::spinOnce();
}
return 0;
}
| #include "main_action_planner_node.hpp"
int main(int argc, char** argv) {
ros::init(argc, argv, "test_action_planner_node");
ros::NodeHandle nh {};
StateChecker status {nh};
while (ros::ok()) {
auto posture_key = status.getPostureKey();
RequestPosture* rp_p = RequestPostureFactory::get(posture_key[0], nh);
if (!rp_p) {
ROS_INFO("Error: get nullptr by RP Factory: arg is [%s]", posture_key[0].c_str());
return -1;
}
SendPosture* sp_p = SendPostureFactory::get(posture_key[1], nh);
if (!sp_p) {
ROS_INFO("Error: get nullptr by SP Factory: arg is [%s]", posture_key[1].c_str());
return -1;
}
std::vector<double> angles;
rp_p->requestPosture(angles);
sp_p->sendPosture(angles);
ros::spinOnce();
}
return 0;
}
|
Call setQueue in setup function. | /*=========================================================================
Program: Converter Base Class
Language: C++
Copyright (c) Brigham and Women's Hospital. All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "rib_converter_base.h"
RIBConverterBase::RIBConverterBase()
{
this->nodeHandle = NULL;
}
RIBConverterBase::RIBConverterBase(ros::NodeHandle *nh)
{
this->setNodeHandle(nh);
}
RIBConverterBase::RIBConverterBase(const char* topicPublish, const char* topicSubscribe, ros::NodeHandle *nh)
{
this->topicPublish = topicPublish;
this->topicSubscribe = topicSubscribe;
this->setNodeHandle(nh);
}
RIBConverterBase::~RIBConverterBase()
{
}
void RIBConverterBase::setup(ros::NodeHandle* nh, uint32_t queuSize)
{
this->setNodeHandle(nh);
this->setQueueSize(queueSize);
}
//void RIBConverterBase::setup(ros::NodeHandle* nh, igtl::Socket * socket, const char* topicSubscribe, const char* topicPublish)
//{
// this->nodeHandle = nh;
// this->socket = socket;
// this->topicSubscribe = topicSubscribe;
// this->topicPublish = topicPublish;
//}
| /*=========================================================================
Program: Converter Base Class
Language: C++
Copyright (c) Brigham and Women's Hospital. All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "rib_converter_base.h"
RIBConverterBase::RIBConverterBase()
{
this->nodeHandle = NULL;
}
RIBConverterBase::RIBConverterBase(ros::NodeHandle *nh)
{
this->setNodeHandle(nh);
}
RIBConverterBase::RIBConverterBase(const char* topicPublish, const char* topicSubscribe, ros::NodeHandle *nh)
{
this->topicPublish = topicPublish;
this->topicSubscribe = topicSubscribe;
this->setNodeHandle(nh);
}
RIBConverterBase::~RIBConverterBase()
{
}
void RIBConverterBase::setup(ros::NodeHandle* nh, uint32_t queuSize)
{
this->setNodeHandle(nh);
this->setQueue(nh);
this->setQueueSize(queueSize);
}
//void RIBConverterBase::setup(ros::NodeHandle* nh, igtl::Socket * socket, const char* topicSubscribe, const char* topicPublish)
//{
// this->nodeHandle = nh;
// this->socket = socket;
// this->topicSubscribe = topicSubscribe;
// this->topicPublish = topicPublish;
//}
|
Exit menu action now works. | #include "robot_editor.h"
#include "robot_preview.h"
#include <cstdlib>
RobotEditor::RobotEditor()
{
main_window_ui_.setupUi(&main_window_);
robot_preview_ = new RobotPreview(main_window_ui_.rvizFrame);
QObject::connect(main_window_ui_.actionExit, SIGNAL(triggered()), this, SLOT(exitTrigger()));
QObject::connect(main_window_ui_.actionOpen, SIGNAL(triggered()), this, SLOT(openTrigger()));
QObject::connect(main_window_ui_.actionSave, SIGNAL(triggered()), this, SLOT(saveTrigger()));
QObject::connect(main_window_ui_.actionSave_As, SIGNAL(triggered()), this, SLOT(saveAsTrigger()));
}
RobotEditor::~RobotEditor()
{
delete robot_preview_;
}
void RobotEditor::show()
{
main_window_.show();
}
void RobotEditor::openTrigger() {
printf("Open selected\n");
}
void RobotEditor::saveTrigger() {
printf("Save selected\n");
}
void RobotEditor::saveAsTrigger() {
printf("Save as selected\n");
}
void RobotEditor::exitTrigger() {
printf("Exit selected\n");
}
| #include "robot_editor.h"
#include "robot_preview.h"
#include <cstdlib>
RobotEditor::RobotEditor()
{
main_window_ui_.setupUi(&main_window_);
robot_preview_ = new RobotPreview(main_window_ui_.rvizFrame);
QObject::connect(main_window_ui_.actionExit, SIGNAL(triggered()), this, SLOT(exitTrigger()));
QObject::connect(main_window_ui_.actionOpen, SIGNAL(triggered()), this, SLOT(openTrigger()));
QObject::connect(main_window_ui_.actionSave, SIGNAL(triggered()), this, SLOT(saveTrigger()));
QObject::connect(main_window_ui_.actionSave_As, SIGNAL(triggered()), this, SLOT(saveAsTrigger()));
}
RobotEditor::~RobotEditor()
{
delete robot_preview_;
}
void RobotEditor::show()
{
main_window_.show();
}
void RobotEditor::openTrigger() {
printf("Open selected\n");
}
void RobotEditor::saveTrigger() {
printf("Save selected\n");
}
void RobotEditor::saveAsTrigger() {
printf("Save as selected\n");
}
void RobotEditor::exitTrigger() {
// quit the application
exit(0);
}
|
Make loadTranslations() a static function. | #include <QtQuick>
#include <sailfishapp.h>
#include <QScopedPointer>
#include <QQuickView>
#include <QQmlEngine>
#include <QGuiApplication>
#include "factor.h"
void loadTranslations() {
QString langCode = QLocale::system().name().mid(0, 2);
const QString Prefix("sailfactor_");
if (QFile::exists(QString(":/lang/") + Prefix + langCode + ".qm")) {
QTranslator *translator = new QTranslator(QCoreApplication::instance());
translator->load(Prefix + langCode, ":/lang");
QCoreApplication::installTranslator(translator);
}
}
int main(int argc, char *argv[])
{
QScopedPointer<QGuiApplication> app(SailfishApp::application(argc, argv));
QScopedPointer<QQuickView> view(SailfishApp::createView());
loadTranslations();
Factorizer fact;
#ifdef QT_QML_DEBUG
runUnitTests();
#endif
view->engine()->rootContext()->setContextProperty("fact", &fact);
view->setSource(SailfishApp::pathTo("qml/main.qml"));
view->setTitle("Sailfactor");
app->setApplicationName("harbour-sailfactor");
app->setApplicationDisplayName("Sailfactor");
view->show();
return app->exec();
}
| #include <QtQuick>
#include <sailfishapp.h>
#include <QScopedPointer>
#include <QQuickView>
#include <QQmlEngine>
#include <QGuiApplication>
#include "factor.h"
static void loadTranslations() {
QString langCode = QLocale::system().name().mid(0, 2);
const QString Prefix("sailfactor_");
if (QFile::exists(QString(":/lang/") + Prefix + langCode + ".qm")) {
QTranslator *translator = new QTranslator(QCoreApplication::instance());
translator->load(Prefix + langCode, ":/lang");
QCoreApplication::installTranslator(translator);
}
}
int main(int argc, char *argv[])
{
QScopedPointer<QGuiApplication> app(SailfishApp::application(argc, argv));
QScopedPointer<QQuickView> view(SailfishApp::createView());
loadTranslations();
Factorizer fact;
#ifdef QT_QML_DEBUG
runUnitTests();
#endif
view->engine()->rootContext()->setContextProperty("fact", &fact);
view->setSource(SailfishApp::pathTo("qml/main.qml"));
view->setTitle("Sailfactor");
app->setApplicationName("harbour-sailfactor");
app->setApplicationDisplayName("Sailfactor");
view->show();
return app->exec();
}
|
Make quit tray menu option work | #include <functional>
#include <QApplication>
#include <QMenu>
#include <QObject>
#include <QSystemTrayIcon>
#include <QTranslator>
#include "piemenu.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
app.setQuitOnLastWindowClosed(false);
QTranslator translator;
translator.load(QLocale(), "", "i18n", ".qm");
app.installTranslator(&translator);
PieMenu pieMenu(qApp->applicationDirPath());
QSystemTrayIcon tray(QIcon(qApp->applicationDirPath() + "/icons/app.png"), &app);
QMenu trayMenu;
trayMenu.addAction(QObject::tr("Open menu"), std::bind(&PieMenu::open, &pieMenu));
trayMenu.addAction(QObject::tr("&Quit"));
tray.setContextMenu(&trayMenu);
tray.show();
return app.exec();
}
| #include <functional>
#include <QApplication>
#include <QMenu>
#include <QObject>
#include <QSystemTrayIcon>
#include <QTranslator>
#include "piemenu.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
app.setQuitOnLastWindowClosed(false);
QTranslator translator;
translator.load(QLocale(), "", "i18n", ".qm");
app.installTranslator(&translator);
PieMenu pieMenu(qApp->applicationDirPath());
QSystemTrayIcon tray(QIcon(qApp->applicationDirPath() + "/icons/app.png"), &app);
QMenu trayMenu;
trayMenu.addAction(QObject::tr("Open menu"), std::bind(&PieMenu::open, &pieMenu));
trayMenu.addAction(QObject::tr("&Quit"), qApp, &QApplication::quit);
tray.setContextMenu(&trayMenu);
tray.show();
return app.exec();
}
|
Stop deleting my includes clion | ShipBlockPacket::ShipBlockPacket(uint8_t ip1, uint8_t ip2, uint8_t ip3, uint8_t ip4, uint16_t port) {
static const uint8_t ipBits[] = { ip1, ip2, ip3, ip4};
memcpy(this->ipaddr, ipBits, sizeof(ipBits));
this->port = port;
}
ShipBlockPacket::~ShipBlockPacket() {
delete[] ipaddr;
}
PacketData ShipBlockPacket::build() {
PacketData data;
PacketHeader header(0x90, 0x11, 0x2C, 0x0, 0x0);
data.appendData(&header, sizeof(header));
// TODO fill in gap
// Offset 0x64
data.appendData(&ipaddr, 4);
// Offset 0x68
data.appendData(&port, 2);
// TODO fill in gap
return data;
} | #include <string.h>
#include "ShipBlockPacket.h"
ShipBlockPacket::ShipBlockPacket(uint8_t ip1, uint8_t ip2, uint8_t ip3, uint8_t ip4, uint16_t port) {
static const uint8_t ipBits[] = { ip1, ip2, ip3, ip4};
memcpy(this->ipaddr, ipBits, sizeof(ipBits));
this->port = port;
}
ShipBlockPacket::~ShipBlockPacket() {
delete[] ipaddr;
}
PacketData ShipBlockPacket::build() {
PacketData data;
PacketHeader header(0x90, 0x11, 0x2C, 0x0, 0x0);
data.appendData(&header, sizeof(header));
// TODO fill in gap
// Offset 0x64
data.appendData(&ipaddr, 4);
// Offset 0x68
data.appendData(&port, 2);
// TODO fill in gap
return data;
} |
Migrate to new MCAsmInfo CodePointerSize | //===-- AVRMCAsmInfo.cpp - AVR asm properties -----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declarations of the AVRMCAsmInfo properties.
//
//===----------------------------------------------------------------------===//
#include "AVRMCAsmInfo.h"
#include "llvm/ADT/Triple.h"
namespace llvm {
AVRMCAsmInfo::AVRMCAsmInfo(const Triple &TT) {
CodePointerSize = 2;
CalleeSaveStackSlotSize = 2;
CommentString = ";";
PrivateGlobalPrefix = ".L";
UsesELFSectionDirectiveForBSS = true;
UseIntegratedAssembler = true;
}
} // end of namespace llvm
| //===-- AVRMCAsmInfo.cpp - AVR asm properties -----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declarations of the AVRMCAsmInfo properties.
//
//===----------------------------------------------------------------------===//
#include "AVRMCAsmInfo.h"
#include "llvm/ADT/Triple.h"
namespace llvm {
AVRMCAsmInfo::AVRMCAsmInfo(const Triple &TT) {
CodePointerSize = 2;
CalleeSaveStackSlotSize = 2;
CommentString = ";";
PrivateGlobalPrefix = ".L";
UsesELFSectionDirectiveForBSS = true;
UseIntegratedAssembler = true;
}
} // end of namespace llvm
|
Fix MaxChannels test; 32 -> 100. | /*
* Copyright (c) 2011 The WebRTC 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 in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "voice_engine/test/auto_test/fixtures/before_initialization_fixture.h"
#include <cstdlib>
class VoeBaseMiscTest : public BeforeInitializationFixture {
};
using namespace testing;
TEST_F(VoeBaseMiscTest, MaxNumChannelsIs32) {
EXPECT_EQ(32, voe_base_->MaxNumOfChannels());
}
TEST_F(VoeBaseMiscTest, GetVersionPrintsSomeUsefulInformation) {
char char_buffer[1024];
memset(char_buffer, 0, sizeof(char_buffer));
EXPECT_EQ(0, voe_base_->GetVersion(char_buffer));
EXPECT_THAT(char_buffer, ContainsRegex("VoiceEngine"));
}
| /*
* Copyright (c) 2011 The WebRTC 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 in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "voice_engine/test/auto_test/fixtures/before_initialization_fixture.h"
#include <cstdlib>
class VoeBaseMiscTest : public BeforeInitializationFixture {
};
using namespace testing;
TEST_F(VoeBaseMiscTest, MaxNumChannelsIs100) {
EXPECT_EQ(100, voe_base_->MaxNumOfChannels());
}
TEST_F(VoeBaseMiscTest, GetVersionPrintsSomeUsefulInformation) {
char char_buffer[1024];
memset(char_buffer, 0, sizeof(char_buffer));
EXPECT_EQ(0, voe_base_->GetVersion(char_buffer));
EXPECT_THAT(char_buffer, ContainsRegex("VoiceEngine"));
}
|
Add additional check to assert call | #include "Flax/WindowsFiberImpl.h"
#include <cassert>
#include <Windows.h>
namespace flax {
WindowsFiberImpl::WindowsFiberImpl(Fiber* fiber, FiberMainFunction mainFunction, bool isMainFiber)
: address(nullptr), mainFiber(isMainFiber), fiberAndMain(fiber, mainFunction) {
assert(fiber && mainFunction);
if (mainFiber) {
address = ConvertThreadToFiber(this);
assert(address);
} else {
address = CreateFiber(0, [](LPVOID param) {
FiberAndMain* fiberAndMain = reinterpret_cast<FiberAndMain*>(param);
assert(fiberAndMain);
fiberAndMain->mainFunction(fiberAndMain->fiber);
}, &fiberAndMain);
}
}
WindowsFiberImpl::~WindowsFiberImpl() {
if (mainFiber) {
assert(address);
bool success = ConvertFiberToThread() != 0;
assert(success);
} else if (address) {
DeleteFiber(address);
}
address = nullptr;
}
void WindowsFiberImpl::swapTo(WindowsFiberImpl& lastFiberImpl) {
assert(address && GetCurrentFiber() != address && GetCurrentFiber() == lastFiberImpl.address);
SwitchToFiber(address);
}
} // namespace flax
| #include "Flax/WindowsFiberImpl.h"
#include <cassert>
#include <Windows.h>
namespace flax {
WindowsFiberImpl::WindowsFiberImpl(Fiber* fiber, FiberMainFunction mainFunction, bool isMainFiber)
: address(nullptr), mainFiber(isMainFiber), fiberAndMain(fiber, mainFunction) {
assert(fiber && mainFunction);
if (mainFiber) {
address = ConvertThreadToFiber(this);
assert(address);
} else {
address = CreateFiber(0, [](LPVOID param) {
FiberAndMain* fiberAndMain = reinterpret_cast<FiberAndMain*>(param);
assert(fiberAndMain);
fiberAndMain->mainFunction(fiberAndMain->fiber);
}, &fiberAndMain);
}
}
WindowsFiberImpl::~WindowsFiberImpl() {
if (mainFiber) {
assert(address);
bool success = ConvertFiberToThread() != 0;
assert(success);
} else if (address) {
DeleteFiber(address);
}
address = nullptr;
}
void WindowsFiberImpl::swapTo(WindowsFiberImpl& lastFiberImpl) {
assert(address && lastFiberImpl.address && GetCurrentFiber() != address && GetCurrentFiber() == lastFiberImpl.address);
SwitchToFiber(address);
}
} // namespace flax
|
Set mHandle to NULL after closing. | /*
* Copyright (c) 2007 Digital Bazaar, Inc. All rights reserved.
*/
#include <iostream>
#include "db/database/sqlite3/Sqlite3Connection.h"
#include "db/database/sqlite3/Sqlite3Statement.h"
using namespace std;
using namespace db::database;
using namespace db::database::sqlite3;
Sqlite3Connection::Sqlite3Connection(const char* params) :
Connection(params)
{
int ret;
mHandle = NULL;
if(mInitParams->getScheme() != "sqlite3")
{
// FIXME error handling
}
else
{
string dbFile = mInitParams->getSchemeSpecificPart();
ret = sqlite3_open(dbFile.c_str(), &mHandle);
if(ret != SQLITE_OK)
{
Sqlite3Connection::close();
// FIXME error handling
}
}
}
Sqlite3Connection::~Sqlite3Connection()
{
Sqlite3Connection::close();
}
void Sqlite3Connection::close()
{
if(mHandle != NULL)
{
sqlite3_close(mHandle);
}
}
void Sqlite3Connection::commit()
{
cout << "FIXME: commit" << endl;
}
void Sqlite3Connection::rollback()
{
cout << "FIXME: rollback" << endl;
}
Statement* Sqlite3Connection::createStatement(const char* sql)
{
return new Sqlite3Statement(this, sql);
}
| /*
* Copyright (c) 2007 Digital Bazaar, Inc. All rights reserved.
*/
#include <iostream>
#include "db/database/sqlite3/Sqlite3Connection.h"
#include "db/database/sqlite3/Sqlite3Statement.h"
using namespace std;
using namespace db::database;
using namespace db::database::sqlite3;
Sqlite3Connection::Sqlite3Connection(const char* params) :
Connection(params)
{
int ret;
mHandle = NULL;
if(mInitParams->getScheme() != "sqlite3")
{
// FIXME error handling
}
else
{
string dbFile = mInitParams->getSchemeSpecificPart();
ret = sqlite3_open(dbFile.c_str(), &mHandle);
if(ret != SQLITE_OK)
{
Sqlite3Connection::close();
// FIXME error handling
}
}
}
Sqlite3Connection::~Sqlite3Connection()
{
Sqlite3Connection::close();
}
void Sqlite3Connection::close()
{
if(mHandle != NULL)
{
sqlite3_close(mHandle);
mHandle = NULL;
}
}
void Sqlite3Connection::commit()
{
cout << "FIXME: commit" << endl;
}
void Sqlite3Connection::rollback()
{
cout << "FIXME: rollback" << endl;
}
Statement* Sqlite3Connection::createStatement(const char* sql)
{
return new Sqlite3Statement(this, sql);
}
|
Fix allocator OOM test on Windows. | // RUN: %clang_cl_asan -O0 %s -Fe%t
// RUN: not %run %t 2>&1 | FileCheck %s
// REQUIRES: asan-32-bits
#include <malloc.h>
int main() {
while (true) {
void *ptr = malloc(200 * 1024 * 1024); // 200MB
}
// CHECK: failed to allocate
}
| // RUN: %clang_cl_asan -O0 %s -Fe%t
// RUN: not %run %t 2>&1 | FileCheck %s
// REQUIRES: asan-32-bits
#include <malloc.h>
int main() {
while (true) {
void *ptr = malloc(200 * 1024 * 1024); // 200MB
}
// CHECK: allocator is terminating the process instead of returning 0
}
|
Fix DCHECK of AtExitManager failure | // Copyright (c) 2015 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "realsense/enhanced_photography/enhanced_photography_extension.h"
#include <string>
#include "realsense/enhanced_photography/enhanced_photography_instance.h"
xwalk::common::Extension* CreateExtension() {
return new realsense::enhanced_photography::EnhancedPhotographyExtension;
}
// This will be generated from common_api.js
extern const char kSource_common_api[];
// This will be generated from common_promise_api.js
extern const char kSource_common_promise_api[];
// This will be generated from enhanced_photography_api.js.
extern const char kSource_enhanced_photography_api[];
namespace realsense {
namespace enhanced_photography {
EnhancedPhotographyExtension::EnhancedPhotographyExtension() {
SetExtensionName("realsense.EnhancedPhotography");
std::string jsapi(kSource_common_api);
jsapi += kSource_common_promise_api;
jsapi += kSource_enhanced_photography_api;
SetJavaScriptAPI(jsapi.c_str());
}
EnhancedPhotographyExtension::~EnhancedPhotographyExtension() {}
xwalk::common::Instance* EnhancedPhotographyExtension::CreateInstance() {
return new EnhancedPhotographyInstance();
}
} // namespace enhanced_photography
} // namespace realsense
| // Copyright (c) 2015 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "realsense/enhanced_photography/enhanced_photography_extension.h"
#include <string>
#include "base/at_exit.h"
#include "realsense/enhanced_photography/enhanced_photography_instance.h"
base::AtExitManager exit_manager;
xwalk::common::Extension* CreateExtension() {
return new realsense::enhanced_photography::EnhancedPhotographyExtension;
}
// This will be generated from common_api.js
extern const char kSource_common_api[];
// This will be generated from common_promise_api.js
extern const char kSource_common_promise_api[];
// This will be generated from enhanced_photography_api.js.
extern const char kSource_enhanced_photography_api[];
namespace realsense {
namespace enhanced_photography {
EnhancedPhotographyExtension::EnhancedPhotographyExtension() {
SetExtensionName("realsense.EnhancedPhotography");
std::string jsapi(kSource_common_api);
jsapi += kSource_common_promise_api;
jsapi += kSource_enhanced_photography_api;
SetJavaScriptAPI(jsapi.c_str());
}
EnhancedPhotographyExtension::~EnhancedPhotographyExtension() {}
xwalk::common::Instance* EnhancedPhotographyExtension::CreateInstance() {
return new EnhancedPhotographyInstance();
}
} // namespace enhanced_photography
} // namespace realsense
|
Use __libc_malloc/__libc_free instead of malloc/free inside internal allocator on Linux (important for TSan) | //===-- sanitizer_allocator.cc --------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is shared between AddressSanitizer and ThreadSanitizer
// run-time libraries.
// This allocator that is used inside run-times.
//===----------------------------------------------------------------------===//
#include "sanitizer_common.h"
// FIXME: We should probably use more low-level allocator that would
// mmap some pages and split them into chunks to fulfill requests.
#include <stdlib.h>
namespace __sanitizer {
static const u64 kInternalAllocBlockMagic = 0x7A6CB03ABCEBC042ull;
void *InternalAlloc(uptr size) {
void *p = malloc(size + sizeof(u64));
((u64*)p)[0] = kInternalAllocBlockMagic;
return (char*)p + sizeof(u64);
}
void InternalFree(void *addr) {
if (!addr) return;
addr = (char*)addr - sizeof(u64);
CHECK_EQ(((u64*)addr)[0], kInternalAllocBlockMagic);
((u64*)addr)[0] = 0;
free(addr);
}
} // namespace __sanitizer
| //===-- sanitizer_allocator.cc --------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is shared between AddressSanitizer and ThreadSanitizer
// run-time libraries.
// This allocator that is used inside run-times.
//===----------------------------------------------------------------------===//
#include "sanitizer_common.h"
// FIXME: We should probably use more low-level allocator that would
// mmap some pages and split them into chunks to fulfill requests.
#ifdef __linux__
extern "C" void *__libc_malloc(__sanitizer::uptr size);
extern "C" void __libc_free(void *ptr);
# define LIBC_MALLOC __libc_malloc
# define LIBC_FREE __libc_free
#else // __linux__
# include <stdlib.h>
# define LIBC_MALLOC malloc
# define LIBC_FREE free
#endif // __linux__
namespace __sanitizer {
static const u64 kInternalAllocBlockMagic = 0x7A6CB03ABCEBC042ull;
void *InternalAlloc(uptr size) {
void *p = LIBC_MALLOC(size + sizeof(u64));
((u64*)p)[0] = kInternalAllocBlockMagic;
return (char*)p + sizeof(u64);
}
void InternalFree(void *addr) {
if (!addr) return;
addr = (char*)addr - sizeof(u64);
CHECK_EQ(((u64*)addr)[0], kInternalAllocBlockMagic);
((u64*)addr)[0] = 0;
LIBC_FREE(addr);
}
} // namespace __sanitizer
|
Fix building error of node | #include <ros/ros.h>
#include <geometry_msgs/Twist.h>
namespace quadrotor_obstacle_avoidance {
int main(int argc, char *argv[]){
ros::init(argc, argv, "quadrotor_obstacle_avoidance");
ros::NodeHandle node;
ros::Publisher cmd_pub = node.advertise<geometry_msgs::Twist>("cmd_vel", 10);
geometry_msgs::Twist cmd;
cmd.linear.z = 0.5;
cmd_pub.publish(cmd);
ros::Duration(5);
cmd.linear.z = 0.0;
cmd_pub.publish(cmd);
ros::Duration(5);
return 0;
}
};
| #include <ros/ros.h>
#include <geometry_msgs/Twist.h>
int main(int argc, char *argv[]){
ros::init(argc, argv, "quadrotor_obstacle_avoidance");
ros::NodeHandle node;
ros::Publisher cmd_pub = node.advertise<geometry_msgs::Twist>("cmd_vel", 10);
ros::Duration(1).sleep();
geometry_msgs::Twist cmd;
cmd.linear.z = 5;
cmd_pub.publish(cmd);
ros::Duration(5).sleep();
cmd.linear.z = 0.0;
cmd_pub.publish(cmd);
ros::Duration(5).sleep();
return 0;
}
|
Revert "Criando estruturas de dados" | #include <iostream>
#include <string>
using namespace std;
typedef struct {
String nome;
String cpf;
float saldo;
} Conta;
float get_saldo( Conta &conta ) {
return conta.saldo;
}
void set_saldo( Conta &conta ) {
conta.saldo;
}
int main() {
Conta conta;
init_conta( conta );
return 0;
}
| #include <iostream>
#include <string>
using namespace std;
typedef struct {
String nome;
String cpf;
float saldo;
} Conta;
int main() {
Conta conta;
init_conta( conta );
return 0;
}
|
Revert "Temporarily disable in-browser thumbnailing on Win and Mac." | // 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/common/thumbnail_support.h"
#include "base/command_line.h"
#include "chrome/common/chrome_switches.h"
#if defined(OS_WIN)
#include "base/win/windows_version.h"
#endif
bool ShouldEnableInBrowserThumbnailing() {
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableInBrowserThumbnailing))
return false;
#if defined(OS_CHROMEOS)
return true;
#else
return false;
#endif
}
| // 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/common/thumbnail_support.h"
#include "base/command_line.h"
#include "chrome/common/chrome_switches.h"
#if defined(OS_WIN)
#include "base/win/windows_version.h"
#endif
bool ShouldEnableInBrowserThumbnailing() {
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableInBrowserThumbnailing))
return false;
#if defined(OS_WIN)
// Disables in-browser thumbnailing on Windows XP where not supported yet.
if (base::win::GetVersion() < base::win::VERSION_VISTA)
return false;
return true;
#elif defined(OS_LINUX) && !defined(USE_AURA)
// Disables in-browser thumbnailing on non-Aura Linux where not supported yet.
return false;
#else
return true;
#endif
}
|
Fix num_calls initialized to 1 instead of 0 | // AMX profiler for SA-MP server: http://sa-mp.com
//
// Copyright (C) 2011-2012 Sergey Zolotarev
//
// 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 "function_info.h"
namespace amx_profiler {
FunctionInfo::FunctionInfo(const FunctionPtr &func)
: func_(func)
, num_calls_(1)
, total_time_(0)
, child_time_(0)
{
}
} // namespace amx_profiler
| // AMX profiler for SA-MP server: http://sa-mp.com
//
// Copyright (C) 2011-2012 Sergey Zolotarev
//
// 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 "function_info.h"
namespace amx_profiler {
FunctionInfo::FunctionInfo(const FunctionPtr &func)
: func_(func)
, num_calls_(0)
, total_time_(0)
, child_time_(0)
{
}
} // namespace amx_profiler
|
Include GrGLInterface.h instead of forward declaring, since we have to get NULL defined anyway. |
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
struct GrGLInterface;
const GrGLInterface* GrGLDefaultInterface() {
return NULL;
}
|
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrGLInterface.h"
const GrGLInterface* GrGLDefaultInterface() {
return NULL;
}
|
Use NSS for SSL encryption of XMPP connection on Windows. | // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "remoting/jingle_glue/ssl_adapter.h"
#if defined(OS_WIN)
#include "third_party/libjingle/source/talk/base/ssladapter.h"
#else
#include "remoting/jingle_glue/ssl_socket_adapter.h"
#endif
namespace remoting {
talk_base::SSLAdapter* CreateSSLAdapter(talk_base::AsyncSocket* socket) {
talk_base::SSLAdapter* ssl_adapter =
#if defined(OS_WIN)
talk_base::SSLAdapter::Create(socket);
#else
remoting::SSLSocketAdapter::Create(socket);
#endif
DCHECK(ssl_adapter);
return ssl_adapter;
}
} // namespace remoting
| // 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 "remoting/jingle_glue/ssl_adapter.h"
#if defined(OS_WIN)
#include "third_party/libjingle/source/talk/base/ssladapter.h"
#else
#include "remoting/jingle_glue/ssl_socket_adapter.h"
#endif
namespace remoting {
talk_base::SSLAdapter* CreateSSLAdapter(talk_base::AsyncSocket* socket) {
talk_base::SSLAdapter* ssl_adapter =
remoting::SSLSocketAdapter::Create(socket);
DCHECK(ssl_adapter);
return ssl_adapter;
}
} // namespace remoting
|
Add basic command line argument parsing. | #include "Emulator.hpp"
int main(const int argc, char* argv[]) {
Emulator emulator;
emulator.run();
} | #include <iostream>
#include <string>
#include <stdexcept>
#include <limits>
#include "Emulator.hpp"
void printHelpMessage() {
std::cout
<< "A NES emulator. Takes .nes files.\n\n"
<< "Usage: turbones [options] <path-to-rom-file>\n\n"
<< "Options:\n"
<< "\t-h --help\n"
<< "\t\tPrint this help text and exit."
<< std::endl;
}
void handleArguments(const int& argc, char* argv[], Emulator& emulator) {
for (int i = 1; i < argc; ++i) {
std::string arg = argv[i];
if (arg == "-h"
|| arg == "--help") {
printHelpMessage();
exit(EXIT_SUCCESS);
}
else if (i == argc - 1) {
emulator.rom_path = arg;
}
else {
std::cerr << "Unrecognized argument: " << arg << std::endl; }
}
}
int main(const int argc, char* argv[]) {
Emulator emulator;
handleArguments(argc, argv, emulator);
try {
emulator.run();
}
catch (const std::runtime_error& e) {
std::cerr << "\nFailed to run (" << e.what() << "). Shutting down." << std::endl;
// The pause here is to make sure the error can be read.
std::cout << "Press Enter to exit . . . ";
// Waits until Enter ('\n') is pressed. It turns out to be simpler
// to write this portably, if we wait for Enter, rather than "any key".
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
return EXIT_FAILURE;
}
} |
Add explicit instantiation of variants to be used in production. | // Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/fastos/fastos.h>
#include <vespa/log/log.h>
#include "multi_value_mapping2.h"
#include "multi_value_mapping2.hpp"
#include <vespa/vespalib/stllike/string.h>
LOG_SETUP(".searchlib.attribute.multivaluemapping2");
namespace search {
namespace attribute {
template class MultiValueMapping2<int32_t>;
} // namespace search::attribute
} // namespace search
| // Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/fastos/fastos.h>
#include <vespa/log/log.h>
#include "multi_value_mapping2.h"
#include "multi_value_mapping2.hpp"
#include <vespa/vespalib/stllike/string.h>
#include "multivalue.h"
#include "enumstorebase.h"
LOG_SETUP(".searchlib.attribute.multivaluemapping2");
using search::multivalue::Value;
using search::multivalue::WeightedValue;
namespace search {
namespace attribute {
template class MultiValueMapping2<Value<EnumStoreIndex>>;
template class MultiValueMapping2<WeightedValue<EnumStoreIndex>>;
template class MultiValueMapping2<Value<int8_t>>;
template class MultiValueMapping2<WeightedValue<int8_t>>;
template class MultiValueMapping2<Value<int16_t>>;
template class MultiValueMapping2<WeightedValue<int16_t>>;
template class MultiValueMapping2<Value<int32_t>>;
template class MultiValueMapping2<WeightedValue<int32_t>>;
template class MultiValueMapping2<Value<int64_t>>;
template class MultiValueMapping2<WeightedValue<int64_t>>;
template class MultiValueMapping2<Value<float>>;
template class MultiValueMapping2<WeightedValue<float>>;
template class MultiValueMapping2<Value<double>>;
template class MultiValueMapping2<WeightedValue<double>>;
} // namespace search::attribute
} // namespace search
|
Fix a build issue in Windows | #include <QString>
#include <QtTest>
#include <execinfo.h>
#include <signal.h>
#include <unistd.h>
#include <TestRunner>
#include <QtQuickTest/quicktest.h>
#include "aconcurrenttests.h"
#include "aconcurrent.h"
void dummy() {
// Dummy function. It is not called.
// It just prove it won't create any duplicated symbols
auto worker = [](int value) {
return value * value;
};
AConcurrent::blockingMapped(QThreadPool::globalInstance(), QList<int>(), worker);
}
void handleBacktrace(int sig) {
void *array[100];
size_t size;
// get void*'s for all entries on the stack
size = backtrace(array, 100);
// print out all the frames to stderr
fprintf(stderr, "Error: signal %d:\n", sig);
backtrace_symbols_fd(array, size, STDERR_FILENO);
exit(1);
}
namespace AutoTestRegister {
QUICK_TEST_MAIN(QuickTests)
}
int main(int argc, char *argv[])
{
signal(SIGSEGV, handleBacktrace);
QCoreApplication app(argc, argv);
TestRunner runner;
runner.addImportPath("qrc:///");
runner.add<AConcurrentTests>();
bool error = runner.exec(app.arguments());
if (!error) {
qDebug() << "All test cases passed!";
}
return error;
}
| #include <QString>
#include <QtTest>
#include <TestRunner>
#include <QtQuickTest/quicktest.h>
#include "aconcurrenttests.h"
#include "aconcurrent.h"
void dummy() {
// Dummy function. It is not called.
// It just prove it won't create any duplicated symbols
auto worker = [](int value) {
return value * value;
};
AConcurrent::blockingMapped(QThreadPool::globalInstance(), QList<int>(), worker);
}
#if defined(Q_OS_MAC) || defined(Q_OS_LINUX)
#include <execinfo.h>
#include <unistd.h>
#include <signal.h>
void handleBacktrace(int sig) {
void *array[100];
size_t size;
// get void*'s for all entries on the stack
size = backtrace(array, 100);
// print out all the frames to stderr
fprintf(stderr, "Error: signal %d:\n", sig);
backtrace_symbols_fd(array, size, STDERR_FILENO);
exit(1);
}
#endif
namespace AutoTestRegister {
QUICK_TEST_MAIN(QuickTests)
}
int main(int argc, char *argv[])
{
#if defined(Q_OS_MAC) || defined(Q_OS_LINUX)
signal(SIGSEGV, handleBacktrace);
#endif
QCoreApplication app(argc, argv);
TestRunner runner;
runner.addImportPath("qrc:///");
runner.add<AConcurrentTests>();
bool error = runner.exec(app.arguments());
if (!error) {
qDebug() << "All test cases passed!";
}
return error;
}
|
Add comment to make it clear | // This program is free software licenced under MIT Licence. You can
// find a copy of this licence in LICENCE.txt in the top directory of
// source code.
//
#include "../include/turing_machine.hpp"
using namespace turingmachine;
class do_nothing final: public tm_abstract_problem {
public:
const char *name() const override {
return "Empty";
}
void configure() override {
// Do nothing, tape should remain the same
}
void add_units() override {
ADD_UNIT_TEST(">#01#", ">#01#");
ADD_UNIT_TEST(">", ">");
ADD_UNIT_TEST(">9$1#", ">9$1#");
}
};
class dummy final: public tm_abstract_problem {
public:
const char *name() const override {
return "Dummy";
}
void configure() override {
ADD_TRANSITION(0, '#', 1, '0', GO_RIGHT);
}
void add_units() override {
ADD_UNIT_TEST(">#01#", ">001#");
}
};
int main() {
do_nothing{}.run();
dummy{}.run();
}
| // This program is free software licenced under MIT Licence. You can
// find a copy of this licence in LICENCE.txt in the top directory of
// source code.
//
#include "../include/turing_machine.hpp"
using namespace turingmachine;
class do_nothing final: public tm_abstract_problem {
public:
const char *name() const override {
return "Empty";
}
void configure() override {
// Do nothing, tape should remain the same
}
void add_units() override {
ADD_UNIT_TEST(">#01#", ">#01#");
ADD_UNIT_TEST(">", ">");
ADD_UNIT_TEST(">9$1#", ">9$1#");
}
};
class dummy final: public tm_abstract_problem {
public:
const char *name() const override {
return "Dummy";
}
void configure() override {
// Note that the last state is considered the final one.
ADD_TRANSITION(0, '#', 1, '0', GO_RIGHT);
}
void add_units() override {
ADD_UNIT_TEST(">#01#", ">001#");
}
};
int main() {
do_nothing{}.run();
dummy{}.run();
}
|
Put sock test in vprTest namespace | #include <CppUnit/framework/TestSuite.h>
#include <CppUnit/textui/TestRunner.h>
#include <TestCases/Socket/SocketTest.h>
#include <TestCases/Thread/ThreadTest.h>
#include <TestCases/IO/Socket/InetAddrTest.h>
using namespace vpr;
int main (int ac, char **av)
{
TestRunner runner;
//------------------------------------
// noninteractive
//------------------------------------
// create non-interactive test suite
TestSuite* noninteractive_suite = new TestSuite("NonInteractive");
// add tests to the suite
//suite_1->addTest( /* put your test here */ );
noninteractive_suite->addTest(vprTest::InetAddrTest::suite());
noninteractive_suite->addTest(SocketTest::suite());
// Add the test suite to the runner
runner.addTest( "noninteractive", noninteractive_suite );
// create test suite #2
TestSuite* suite_2 = new TestSuite("suite_2");
// add tests to the suite
//suite_2->addTest(gmtlTest::Vec3Test::suite());
//suite_2->addTest(gmtlTest::MatrixTest::suite());
//suite_2->addTest(gmtlTest::Point3Test::suite());
suite_2->addTest(ThreadTest::suite());
// Add the test suite to the runner
runner.addTest("suite_2_tests", suite_2);
// run all test suites
runner.run( ac, av );
return 0;
}
| #include <CppUnit/framework/TestSuite.h>
#include <CppUnit/textui/TestRunner.h>
#include <TestCases/Socket/SocketTest.h>
#include <TestCases/Thread/ThreadTest.h>
#include <TestCases/IO/Socket/InetAddrTest.h>
//using namespace vpr;
int main (int ac, char **av)
{
TestRunner runner;
//------------------------------------
// noninteractive
//------------------------------------
// create non-interactive test suite
TestSuite* noninteractive_suite = new TestSuite("NonInteractive");
// add tests to the suite
//suite_1->addTest( /* put your test here */ );
noninteractive_suite->addTest(vprTest::InetAddrTest::suite());
noninteractive_suite->addTest(vprTest::SocketTest::suite());
// Add the test suite to the runner
runner.addTest( "noninteractive", noninteractive_suite );
// create test suite #2
TestSuite* suite_2 = new TestSuite("suite_2");
// add tests to the suite
//suite_2->addTest(gmtlTest::Vec3Test::suite());
//suite_2->addTest(gmtlTest::MatrixTest::suite());
//suite_2->addTest(gmtlTest::Point3Test::suite());
suite_2->addTest(ThreadTest::suite());
// Add the test suite to the runner
runner.addTest("suite_2_tests", suite_2);
// run all test suites
runner.run( ac, av );
return 0;
}
|
Disable checking of sigprof on mac. | // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "platform/globals.h"
#if defined(HOST_OS_MACOS)
#include <errno.h> // NOLINT
#include <fcntl.h> // NOLINT
#include "bin/crypto.h"
#include "bin/fdutils.h"
#include "platform/signal_blocker.h"
namespace dart {
namespace bin {
bool Crypto::GetRandomBytes(intptr_t count, uint8_t* buffer) {
ThreadSignalBlocker signal_blocker(SIGPROF);
intptr_t fd = TEMP_FAILURE_RETRY_NO_SIGNAL_BLOCKER(
open("/dev/urandom", O_RDONLY | O_CLOEXEC));
if (fd < 0) {
return false;
}
intptr_t bytes_read = 0;
do {
int res = TEMP_FAILURE_RETRY_NO_SIGNAL_BLOCKER(
read(fd, buffer + bytes_read, count - bytes_read));
if (res < 0) {
int err = errno;
close(fd);
errno = err;
return false;
}
bytes_read += res;
} while (bytes_read < count);
close(fd);
return true;
}
} // namespace bin
} // namespace dart
#endif // defined(HOST_OS_MACOS)
| // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "platform/globals.h"
#if defined(HOST_OS_MACOS)
#include <errno.h> // NOLINT
#include <fcntl.h> // NOLINT
#include "bin/crypto.h"
#include "bin/fdutils.h"
#include "platform/signal_blocker.h"
namespace dart {
namespace bin {
bool Crypto::GetRandomBytes(intptr_t count, uint8_t* buffer) {
intptr_t fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC));
if (fd < 0) {
return false;
}
intptr_t bytes_read = 0;
do {
int res =
TEMP_FAILURE_RETRY(read(fd, buffer + bytes_read, count - bytes_read));
if (res < 0) {
int err = errno;
close(fd);
errno = err;
return false;
}
bytes_read += res;
} while (bytes_read < count);
close(fd);
return true;
}
} // namespace bin
} // namespace dart
#endif // defined(HOST_OS_MACOS)
|
Add string c constructor test. | #include "ReQL-test.hpp"
#include "catch.h"
using namespace ReQL;
TEST_CASE("Connection", "[c++][connect]") {
Connection conn = connect();
REQUIRE(conn.isOpen());
} | #include "ReQL-test.hpp"
#include "catch.h"
using namespace ReQL;
TEST_CASE("Connection", "[c++][connect]") {
Connection conn = connect();
REQUIRE(conn.isOpen());
}
TEST_CASE("Expr", "[c][expr]") {
SECTION("string") {
_ReQL_Op_t string;
const uint32_t size = 12;
uint8_t buf[size] = "Hello World";
std::string orig = std::string((char *)buf, size);
_reql_string_init(&string, buf, size, size);
CHECK(orig.compare(0, size, (char *)_reql_string_buf(&string), size) == 0);
CHECK(size == _reql_string_size(&string));
}
}
|
Use ANSI compatible __typeof__ instead of GNU's typeof | // Copyright (c) 2011 - 2019, GS Group, https://github.com/GSGroup
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
// provided that the above copyright notice and this permission notice appear in all copies.
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#include <stingraykit/log/Logger.h>
#include <stingraykit/diagnostics/Backtrace.h>
extern "C" typeof(abort) __real_abort;
extern "C" void __wrap_abort(ssize_t size)
{
using namespace stingray;
Logger::Error() << "Abort called: " << Backtrace().Get();
__real_abort();
}
| // Copyright (c) 2011 - 2019, GS Group, https://github.com/GSGroup
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
// provided that the above copyright notice and this permission notice appear in all copies.
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#include <stingraykit/log/Logger.h>
#include <stingraykit/diagnostics/Backtrace.h>
extern "C" __typeof__(abort) __real_abort;
extern "C" void __wrap_abort(ssize_t size)
{
using namespace stingray;
Logger::Error() << "Abort called: " << Backtrace().Get();
__real_abort();
}
|
Call free in OSX renderer's init | // Copyright (C) 2016 Elviss Strazdins
// This file is part of the Ouzel engine.
#include "RendererOGLOSX.h"
namespace ouzel
{
namespace graphics
{
bool RendererOGLOSX::init(const WindowPtr& window,
uint32_t newSampleCount,
TextureFiltering newTextureFiltering,
float newTargetFPS,
bool newVerticalSync)
{
return RendererOGL::init(window, newSampleCount, newTextureFiltering, newTargetFPS, newVerticalSync);
}
} // namespace graphics
} // namespace ouzel
| // Copyright (C) 2016 Elviss Strazdins
// This file is part of the Ouzel engine.
#include "RendererOGLOSX.h"
namespace ouzel
{
namespace graphics
{
bool RendererOGLOSX::init(const WindowPtr& window,
uint32_t newSampleCount,
TextureFiltering newTextureFiltering,
float newTargetFPS,
bool newVerticalSync)
{
free();
return RendererOGL::init(window, newSampleCount, newTextureFiltering, newTargetFPS, newVerticalSync);
}
} // namespace graphics
} // namespace ouzel
|
Test now outputs the log | #include "parsertest.h"
#include "fileast.h"
#include "scanner.h"
#include "myexception.h"
#include <QtTest/QtTest>
ParserTest::ParserTest(QObject *parent) : QObject(parent)
{
}
void ParserTest::initTestCase() {
}
void ParserTest::cleanupTestCase() {
}
void ParserTest::dummySuccess() {
}
Q_DECLARE_METATYPE(FileAST)
void ParserTest::expectedAST_data() {
QTest::addColumn<QString>("input"); //QRC file
//QTest::addColumn<FileAST>("expected");
QTest::newRow("Sample 1") << ":/sample_1_tokens.json";
}
void ParserTest::expectedAST() {
QFETCH(QString, input);
try {
QFile file(input);
QVERIFY(file.open(QFile::ReadOnly));
QByteArray data = file.readAll();
auto doc = QJsonDocument::fromJson(data);
auto tokens = Scanner::fromJson(doc);
//Now that we have the tokens, we can compare to expected AST (TODO)
qDebug() << "Number of tokens : " << tokens.tokens().size();
}
catch (MyException& e) {
QFAIL(QString("Exception catched in test : %1").arg(e.msg).toStdString().data());
}
}
| #include "parsertest.h"
#include "fileast.h"
#include "parser.h"
#include "scanner.h"
#include "myexception.h"
#include <QtTest/QtTest>
ParserTest::ParserTest(QObject *parent) : QObject(parent)
{
}
void ParserTest::initTestCase() {
}
void ParserTest::cleanupTestCase() {
}
void ParserTest::dummySuccess() {
}
Q_DECLARE_METATYPE(FileAST)
void ParserTest::expectedAST_data() {
QTest::addColumn<QString>("input"); //QRC file
//QTest::addColumn<FileAST>("expected");
QTest::newRow("Sample 1") << ":/sample_1_tokens.json";
}
void ParserTest::expectedAST() {
QFETCH(QString, input);
try {
QFile file(input);
QVERIFY(file.open(QFile::ReadOnly));
QByteArray data = file.readAll();
auto doc = QJsonDocument::fromJson(data);
auto scanner = Scanner::fromJson(doc);
auto tokens = scanner.tokens();
//Now that we have the tokens, we can parse then compare to expected AST (TODO)
Parser parser(tokens);
qDebug() << "Log of parser : " << parser.getLog();
}
catch (MyException& e) {
QFAIL(QString("Exception catched in test : %1").arg(e.msg).toStdString().data());
}
}
|
Rename columns to be compatible with sample_stats++ | #include <iostream>
#include <Sequence/variant_matrix/msformat.hpp>
#include <Sequence/summstats.hpp>
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cerr.tie(nullptr);
std::cout.setf(std::ios::fixed);
std::cout.precision(6);
std::cout << "pi\tS\tD\tthetaH\tH\n";
do {
const auto vm = Sequence::from_msformat(std::cin);
Sequence::AlleleCountMatrix ac(vm);
const double pi = Sequence::thetapi(ac);
const double tH = Sequence::thetah(ac, 0);
std::cout << pi << '\t'
<< Sequence::nvariable_sites(ac) << '\t'
<< Sequence::tajd(ac) << '\t'
<< tH << '\t'
<< pi - tH << '\n';
} while (!std::cin.eof());
return 0;
}
| #include <iostream>
#include <Sequence/variant_matrix/msformat.hpp>
#include <Sequence/summstats.hpp>
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cerr.tie(nullptr);
std::cout.setf(std::ios::fixed);
std::cout.precision(6);
std::cout << "pi\tS\tD\ttH\n";
do {
const auto vm = Sequence::from_msformat(std::cin);
Sequence::AlleleCountMatrix ac(vm);
std::cout << Sequence::thetapi(ac) << '\t'
<< Sequence::nvariable_sites(ac) << '\t'
<< Sequence::tajd(ac) << '\t'
<< Sequence::thetah(ac, 0) << '\n';
} while (!std::cin.eof());
return 0;
}
|
Fix problem with broken } | #include "casexponent.h"
// CasExpression CasExponent::getE(){
// return e;
}
| #include "casexponent.h"
// CasExpression CasExponent::getE(){
// return e;
//}
|
Test case fix: mode debug output, synchronization instead of sleep(). | // Regression test for http://llvm.org/bugs/show_bug.cgi?id=21621
// This test relies on timing between threads, so any failures will be flaky.
// RUN: %clangxx_lsan %s -o %t
// RUN: LSAN_OPTIONS="log_pointers=1:log_threads=1" %run %t
#include <assert.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
void *func(void *arg) {
sleep(1);
free(arg);
return 0;
}
void create_detached_thread() {
pthread_t thread_id;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
void *arg = malloc(1337);
assert(arg);
int res = pthread_create(&thread_id, &attr, func, arg);
assert(res == 0);
}
int main() {
create_detached_thread();
}
| // Regression test for http://llvm.org/bugs/show_bug.cgi?id=21621
// This test relies on timing between threads, so any failures will be flaky.
// RUN: %clangxx_lsan %s -o %t
// RUN: LSAN_OPTIONS="log_pointers=1:log_threads=1" %run %t
#include <assert.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
bool flag = false;
void *func(void *arg) {
// This mutex will never be grabbed.
fprintf(stderr, "entered func()\n");
pthread_mutex_lock(&mutex);
free(arg);
pthread_mutex_unlock(&mutex);
return 0;
}
void create_detached_thread() {
pthread_t thread_id;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
void *arg = malloc(1337);
assert(arg);
// This mutex is never unlocked by the main thread.
pthread_mutex_lock(&mutex);
int res = pthread_create(&thread_id, &attr, func, arg);
assert(res == 0);
}
int main() {
create_detached_thread();
}
|
Add a simple example of sniffer manager | #include <iostream>
#include <system_error>
#include "controllers/main/MainModule.hpp"
#include "network/bsdsocket/Manager.hpp"
#include "network/sniffer/SnifferManager.hpp"
int main()
{
tin::controllers::main::ControllerQueue ctrlQueue;
tin::network::bsdsocket::ManagerQueue netManagerQueue;
tin::controllers::main::MainModule mainCtrl(ctrlQueue, netManagerQueue);
tin::network::bsdsocket::Manager networkManager(netManagerQueue, ctrlQueue, 3333);
tin::network::sniffer::SnifferManager sniffManager(ctrlQueue, "lo", "src 127.0.0.1");
std::cout << "Hello agent!\n";
auto mainCtrlThread = mainCtrl.createThread();
auto netManager = networkManager.createThread();
try
{
mainCtrlThread.join();
netManager.join();
}
catch (std::system_error& e)
{
// Could not join one of the threads
}
return 0;
}
| #include <iostream>
#include <system_error>
#include "controllers/main/MainModule.hpp"
#include "network/bsdsocket/Manager.hpp"
#include "network/sniffer/Manager.hpp"
#include "network/sniffer/events/ChangeFilter.hpp"
int main()
{
tin::controllers::main::ControllerQueue ctrlQueue;
tin::network::bsdsocket::ManagerQueue netManagerQueue;
tin::network::sniffer::ManagerQueue snifferManagerQueue;
tin::controllers::main::MainModule mainCtrl(ctrlQueue, netManagerQueue);
tin::network::bsdsocket::Manager networkManager(netManagerQueue, ctrlQueue, 3333);
tin::network::sniffer::Manager sniffManager(
snifferManagerQueue,
ctrlQueue,
"lo",
"src 127.0.0.1"
);
std::cout << "Hello agent!\n";
auto mainCtrlThread = mainCtrl.createThread();
auto netManager = networkManager.createThread();
auto sniffThread = sniffManager.createThread();
std::this_thread::sleep_for (std::chrono::seconds(1));
snifferManagerQueue.push(
std::make_shared<tin::network::sniffer::events::ChangeFilter>(
"lo",
"src 127.0.0.1"
)
);
try
{
mainCtrlThread.join();
netManager.join();
sniffThread.join();
}
catch (std::system_error& e)
{
// Could not join one of the threads
}
return 0;
}
|
Change style of function display to match Debug.hpp | #include <lug/System/Exception.hpp>
#include <sstream>
lug::System::Exception::Exception(const char *typeName, const std::string &description, const char* file, const char* function, uint32_t line)
: _typeName{typeName}, _description{description}, _file{file}, _function{function}, _line{line} {}
const std::string& lug::System::Exception::getTypeName() const {
return _typeName;
}
const std::string& lug::System::Exception::getDescription() const {
return _description;
}
const std::string& lug::System::Exception::getFile() const {
return _file;
}
const std::string& lug::System::Exception::getFunction() const {
return _function;
}
const uint32_t lug::System::Exception::getLine() const {
return _line;
}
const char* lug::System::Exception::what() const noexcept {
std::stringstream msg;
msg << _typeName << ": " << _description << std::endl;
msg << "In " << _file;
msg << " at " << _function << " line " << _line;
_fullDesc = msg.str();
return _fullDesc.c_str();
}
| #include <lug/System/Exception.hpp>
#include <sstream>
lug::System::Exception::Exception(const char *typeName, const std::string &description, const char* file, const char* function, uint32_t line)
: _typeName{typeName}, _description{description}, _file{file}, _function{function}, _line{line} {}
const std::string& lug::System::Exception::getTypeName() const {
return _typeName;
}
const std::string& lug::System::Exception::getDescription() const {
return _description;
}
const std::string& lug::System::Exception::getFile() const {
return _file;
}
const std::string& lug::System::Exception::getFunction() const {
return _function;
}
const uint32_t lug::System::Exception::getLine() const {
return _line;
}
const char* lug::System::Exception::what() const noexcept {
std::stringstream msg;
msg << _typeName << ": " << _description << std::endl;
msg << "In " << _file;
msg << " at `" << _function << "` line " << _line;
_fullDesc = msg.str();
return _fullDesc.c_str();
}
|
FIx handling of image size | #include "imageprovider.h"
matrix::ImageProvider::ImageProvider() : QQuickImageProvider{QQuickImageProvider::Pixmap}
{
if (!default_image_.load(":/img/res/img/default.png")) {
default_image_ = QPixmap{256, 256};
default_image_.fill(QColor{"#ff00ff"});
}
}
QPixmap matrix::ImageProvider::requestPixmap(const QString& id, QSize* size,
[[maybe_unused]] const QSize& requested_size)
{
if (size)
*size = QSize(32, 32);
QPixmap p;
if (images_.contains(id)) {
return images_[id];
}
return default_image_;
}
| #include "imageprovider.h"
matrix::ImageProvider::ImageProvider() : QQuickImageProvider{QQuickImageProvider::Pixmap}
{
if (!default_image_.load(":/img/res/img/default.png")) {
default_image_ = QPixmap{256, 256};
default_image_.fill(QColor{"#ff00ff"});
}
}
QPixmap matrix::ImageProvider::requestPixmap(const QString& id, QSize* size,
[[maybe_unused]] const QSize& requested_size)
{
if (images_.contains(id)) {
const auto& p = images_[id];
if (size)
*size = QSize{p.size()};
return p;
}
if (size)
*size = QSize{default_image_.size()};
return default_image_;
}
|
Disable direct write by default. | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "config.h"
FNET_Config::FNET_Config()
: _minEventTimeOut(0),
_pingInterval(0),
_iocTimeOut(0),
_maxInputBufferSize(0x10000),
_maxOutputBufferSize(0x10000),
_tcpNoDelay(true),
_logStats(false),
_directWrite(true)
{ }
| // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "config.h"
FNET_Config::FNET_Config()
: _minEventTimeOut(0),
_pingInterval(0),
_iocTimeOut(0),
_maxInputBufferSize(0x10000),
_maxOutputBufferSize(0x10000),
_tcpNoDelay(true),
_logStats(false),
_directWrite(false)
{ }
|
Split apart effect interface and implementations. | #include "map.h"
#include "screen.h"
#include <sstream>
Map CreateMap(int seed)
{
return GenerateRandomMap(std::mt19937(seed));
}
int GameMain()
{
SetTitle("Map test");
int seed = 1;
Map map = CreateMap(seed);
Screen screen;
while(true)
{
screen.Clear();
std::ostringstream ss;
ss << "Seed = " << seed;
screen.PutString({0,0}, Color::White, ss.str());
for(int y=0; y<MAP_HEIGHT; ++y)
{
for(int x=0; x<MAP_WIDTH; ++x)
{
screen.PutGlyph({x+MAP_OFFSET_X,y+MAP_OFFSET_Y}, map.GetTile({x,y}).GetGlyph());
}
}
WriteOutput(screen.glyphs, {7,0});
switch(ReadInput())
{
case 'Q': return 0;
case '4': map = CreateMap(--seed); break;
case '6': map = CreateMap(++seed); break;
case '2': map = CreateMap(seed -= 10); break;
case '8': map = CreateMap(seed += 10); break;
}
}
} | #include "map.h"
#include "screen.h"
#include <sstream>
Map CreateMap(int seed)
{
return GenerateRandomMap(std::mt19937(seed));
}
int GameMain()
{
SetTitle("Map test");
int seed = 1;
Map map = CreateMap(seed);
Screen screen;
while(true)
{
screen.Clear();
std::ostringstream ss;
ss << "Seed = " << seed;
screen.PutString({0,0}, Color::White, ss.str());
for(int y=0; y<MAP_HEIGHT; ++y)
{
for(int x=0; x<MAP_WIDTH; ++x)
{
for(int dir=0; dir<9; ++dir)
{
if(map.GetTile(int2(x,y) + (Direction)dir).IsWalkable())
{
screen.PutGlyph({x+MAP_OFFSET_X,y+MAP_OFFSET_Y}, map.GetTile({x,y}).GetGlyph());
break;
}
}
}
}
WriteOutput(screen.glyphs, {7,0});
switch(ReadInput())
{
case 'Q': return 0;
case '4': map = CreateMap(--seed); break;
case '6': map = CreateMap(++seed); break;
case '2': map = CreateMap(seed -= 10); break;
case '8': map = CreateMap(seed += 10); break;
}
}
} |
Create a simple example of file tokenization | #include "Interpreter.hpp"
#include "modules/error-handler/ErrorHandler.hpp"
tkom::Interpreter::Interpreter(const std::vector<std::string>& arguments)
{
try
{
modules::ErrorHandler::error("Hello world!");
}
catch (std::exception& e)
{}
modules::ErrorHandler::warning("Hello world!");
modules::ErrorHandler::notice("Hello world!");
// Main program body
}
| #include "Interpreter.hpp"
#include "modules/error-handler/ErrorHandler.hpp"
#include "modules/lexer/Lexer.hpp"
#include <iostream>
using Interpreter = tkom::Interpreter;
using ErrorHandler = tkom::modules::ErrorHandler;
using Lexer = tkom::modules::Lexer;
Interpreter::Interpreter(const std::vector<std::string>& arguments)
{
try
{
if (arguments.size() < 1)
{
ErrorHandler::error("No input file specified");
}
Lexer lexer(arguments.at(0));
Token token;
do
{
token = lexer.nextToken();
std::cout << tkom::modules::utils::getTokenTypeName(token.type) << " = " << token.value << std::endl;
}
while(token.type != TokenType::Invalid && token.type != TokenType::EndOfFile);
}
catch(ErrorHandler::Exception &e)
{
ErrorHandler::error("Terminating...", true);
}
}
|
Remove the 'alarm' script which isn't present on OS X by default. The test may hang now if a regression occurs. | #include <stdio.h>
// Make sure ASan doesn't hang in an exec loop if DYLD_INSERT_LIBRARIES is set.
// This is a regression test for
// https://code.google.com/p/address-sanitizer/issues/detail?id=159
// RUN: %clangxx_asan -m64 %s -o %t
// RUN: %clangxx -m64 %p/../SharedLibs/darwin-dummy-shared-lib-so.cc \
// RUN: -dynamiclib -o darwin-dummy-shared-lib-so.dylib
// If the test hangs, kill it after 15 seconds.
// RUN: DYLD_INSERT_LIBRARIES=darwin-dummy-shared-lib-so.dylib \
// RUN: alarm 15 %t 2>&1 | FileCheck %s || exit 1
#include <stdlib.h>
int main() {
const char kEnvName[] = "DYLD_INSERT_LIBRARIES";
printf("%s=%s\n", kEnvName, getenv(kEnvName));
// CHECK: {{DYLD_INSERT_LIBRARIES=.*darwin-dummy-shared-lib-so.dylib.*}}
return 0;
}
| #include <stdio.h>
// Make sure ASan doesn't hang in an exec loop if DYLD_INSERT_LIBRARIES is set.
// This is a regression test for
// https://code.google.com/p/address-sanitizer/issues/detail?id=159
// RUN: %clangxx_asan -m64 %s -o %t
// RUN: %clangxx -m64 %p/../SharedLibs/darwin-dummy-shared-lib-so.cc \
// RUN: -dynamiclib -o darwin-dummy-shared-lib-so.dylib
// FIXME: the following command line may hang in the case of a regression.
// RUN: DYLD_INSERT_LIBRARIES=darwin-dummy-shared-lib-so.dylib \
// RUN: %t 2>&1 | FileCheck %s || exit 1
#include <stdlib.h>
int main() {
const char kEnvName[] = "DYLD_INSERT_LIBRARIES";
printf("%s=%s\n", kEnvName, getenv(kEnvName));
// CHECK: {{DYLD_INSERT_LIBRARIES=.*darwin-dummy-shared-lib-so.dylib.*}}
return 0;
}
|
Implement getClientHostId with uname() under Linux by default. | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 <thrift/lib/cpp2/async/ClientChannel.h>
#include <thrift/lib/cpp2/PluggableFunction.h>
namespace apache {
namespace thrift {
namespace {
THRIFT_PLUGGABLE_FUNC_REGISTER(std::optional<std::string>, getClientHostId) {
return {};
}
} // namespace
/* static */ const std::optional<std::string>& ClientChannel::getHostId() {
static const auto& hostId =
*new std::optional<std::string>{THRIFT_PLUGGABLE_FUNC(getClientHostId)()};
return hostId;
}
} // namespace thrift
} // namespace apache
| /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 <thrift/lib/cpp2/async/ClientChannel.h>
#ifdef __linux__
#include <sys/utsname.h>
#endif
#include <thrift/lib/cpp2/PluggableFunction.h>
namespace apache {
namespace thrift {
namespace {
THRIFT_PLUGGABLE_FUNC_REGISTER(std::optional<std::string>, getClientHostId) {
#ifdef __linux__
struct utsname bufs;
::uname(&bufs);
return bufs.nodename;
#else
return {};
#endif
}
} // namespace
/* static */ const std::optional<std::string>& ClientChannel::getHostId() {
static const auto& hostId =
*new std::optional<std::string>{THRIFT_PLUGGABLE_FUNC(getClientHostId)()};
return hostId;
}
} // namespace thrift
} // namespace apache
|
Use the generated oneo proto enum |
#include <boost/assert.hpp>
#include "worker.h"
#include "requests.pb.h"
bool traffic::MessageWorker::process(std::string &result, void *data, size_t size)
{
(void) result;
request::Request request;
request.ParseFromArray(data, size);
if (request.has_statistic())
return process_statistics();
else if (request.has_summary())
return process_summary();
BOOST_ASSERT(false && "Unknown message type");
return false;
}
|
#include <boost/assert.hpp>
#include "worker.h"
#include "requests.pb.h"
bool traffic::MessageWorker::process(std::string &result, void *data, size_t size)
{
(void) result;
request::Request request;
request.ParseFromArray(data, size);
switch (request.Payload_case()) {
case request::Request::kStatistic:
return process_statistics();
case request::Request::kSummary:
return process_summary();
case request::Request::PAYLOAD_NOT_SET:
return false;
}
BOOST_ASSERT(false && "Message parsing failed!");
return false;
}
|
Test file for dynamic regression model. | #include "gtest/gtest.h"
#include "Models/ChisqModel.hpp"
#include "Models/PosteriorSamplers/ZeroMeanGaussianConjSampler.hpp"
#include "Models/StateSpace/DynamicRegression.hpp"
#include "Models/StateSpace/StateModels/LocalLevelStateModel.hpp"
#include "Models/StateSpace/StateModels/SeasonalStateModel.hpp"
#include "Models/StateSpace/StateSpaceModel.hpp"
#include "Models/MvnGivenScalarSigma.hpp"
#include "Models/Glm/PosteriorSamplers/BregVsSampler.hpp"
#include "Models/Glm/VariableSelectionPrior.hpp"
#include "distributions.hpp"
#include "test_utils/test_utils.hpp"
#include "Models/StateSpace/tests/state_space_test_utils.hpp"
#include "stats/AsciiDistributionCompare.hpp"
#include <fstream>
namespace {
using namespace BOOM;
using namespace BOOM::StateSpace;
using std::endl;
using std::cout;
class RegressionDataTimePointTest : public ::testing::Test {
protected:
};
TEST_F(RegressionDataTimePointTest, blah) {
NEW(RegressionDataTimePoint, dp)();
EXPECT_EQ(0, dp->sample_size());
EXPECT_FALSE(dp->using_suf());
}
class DynamicRegressionModelTest : public ::testing::Test {
protected:
};
} // namespace
| #include "gtest/gtest.h"
#include "Models/ChisqModel.hpp"
#include "Models/PosteriorSamplers/ZeroMeanGaussianConjSampler.hpp"
#include "Models/StateSpace/DynamicRegression.hpp"
#include "Models/StateSpace/StateModels/LocalLevelStateModel.hpp"
#include "Models/StateSpace/StateModels/SeasonalStateModel.hpp"
#include "Models/StateSpace/StateSpaceModel.hpp"
#include "Models/MvnGivenScalarSigma.hpp"
#include "Models/Glm/PosteriorSamplers/BregVsSampler.hpp"
#include "Models/Glm/VariableSelectionPrior.hpp"
#include "distributions.hpp"
#include "test_utils/test_utils.hpp"
#include "Models/StateSpace/tests/state_space_test_utils.hpp"
#include "stats/AsciiDistributionCompare.hpp"
#include <fstream>
namespace {
using namespace BOOM;
using namespace BOOM::StateSpace;
using std::endl;
using std::cout;
class RegressionDataTimePointTest : public ::testing::Test {
protected:
RegressionDataTimePointTest() {}
};
TEST_F(RegressionDataTimePointTest, blah) {
NEW(RegressionDataTimePoint, dp)();
EXPECT_EQ(0, dp->sample_size());
EXPECT_FALSE(dp->using_suf());
}
class DynamicRegressionModelTest : public ::testing::Test {
protected:
};
} // namespace
|
Add exception management on Unix | #include "UnixExecutablePathValidator.h"
using namespace clt::filesystem::entities;
using namespace clt::filesystem::entities::validators;
bool
UnixExecutablePathValidator::isPathValid(const Path& path, std::vector<ValidatorBrokenRules> & brokenRules) const {
//TODO: must be a file with executable right
return path.exists()
&& !path.isDirectory()
&& path.isExecutable();
} | #include "UnixExecutablePathValidator.h"
using namespace clt::filesystem::entities;
using namespace clt::filesystem::entities::validators;
bool
UnixExecutablePathValidator::isPathValid(const Path& path, std::vector<ValidatorBrokenRules> & brokenRules) const {
if (!path.exists()) {
brokenRules.push_back(ValidatorBrokenRules("Path does not exist"));
return false;
}
if (path.isDirectory()) {
brokenRules.push_back(ValidatorBrokenRules("The path is not a file"));
return false;
}
if (!path.isExecutable()) {
brokenRules.push_back(ValidatorBrokenRules("File at path is not executable"));
return false;
}
return true;
} |
Add the contributor of the method | #include <iostream>
/* This program computes fibo using
* and optimization of the matrix way
*/
/*REFERENCES
* https://en.wikipedia.org/wiki/Fibonacci_number#Matrix_form
* http://www.geeksforgeeks.org/program-for-nth-fibonacci-number/
*/
using namespace std;
const int MAX = 1000;
int f[MAX] = {0};
int fib(int n){
if (n == 0) return 0;
if (n == 1 || n == 2) return (f[n] = 1);
if (f[n]) return f[n];
//pretty good way to know if a number is odd or even
int k = (n & 1)? (n+1)/2 : n/2;
f[n] = (n & 1) ? ( fib(k) * fib(k) + fib(k-1) * fib(k-1) )
: (2*fib(k-1) + fib(k))*fib(k);
return f[n];
}
int main(){
int n = 9;
cout<< fib(n);
return 0;
}
| #include <iostream>
/* This program computes fibo using
* and optimization of the matrix way
*/
/*REFERENCES
* This method is contributed by Chirag Agarwal.
* https://en.wikipedia.org/wiki/Fibonacci_number#Matrix_form
* http://www.geeksforgeeks.org/program-for-nth-fibonacci-number/
*/
using namespace std;
const int MAX = 1000;
int f[MAX] = {0};
int fib(int n){
if (n == 0) return 0;
if (n == 1 || n == 2) return (f[n] = 1);
if (f[n]) return f[n];
//pretty good way to know if a number is odd or even
int k = (n & 1)? (n+1)/2 : n/2;
f[n] = (n & 1) ? ( fib(k) * fib(k) + fib(k-1) * fib(k-1) )
: (2*fib(k-1) + fib(k))*fib(k);
return f[n];
}
int main(){
int n = 9;
cout<< fib(n);
return 0;
}
|
Update coshx_eq_expy, make the return value pure real or pure imaginary. | #include "math_container.h"
using std::complex;
/******************************************************/
/*solve the equation cosh(x)=exp(y), input y, return x*/
/******************************************************/
complex<double> coshx_eq_expy(double y)
{
complex<double> ey={exp(y),0};
return log(ey-sqrt(ey*ey-1.0));
}
| #include "math_container.h"
using std::complex;
/******************************************************/
/*solve the equation cosh(x)=exp(y), input y, return x*/
/******************************************************/
complex<double> coshx_eq_expy(double y)
{
complex<double> ey={exp(y),0};
complex<double> gamma=log(ey-sqrt(ey*ey-1.0));
//Since gamma is pure real or pure imaginary, set it:
if( abs( gamma.real() ) < abs( gamma.imag() ) ) gamma=complex<double>( 0, gamma.imag() );
else gamma=complex<double>( gamma.real(), 0 );
return gamma;
}
|
Use the normal panel-frame until there's a touch-friendly version. | // 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/views/frame/browser_non_client_frame_view.h"
#include "chrome/browser/ui/touch/frame/touch_browser_frame_view.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/frame/popup_non_client_frame_view.h"
namespace browser {
BrowserNonClientFrameView* CreateBrowserNonClientFrameView(
BrowserFrame* frame, BrowserView* browser_view) {
if (browser_view->IsBrowserTypePopup() ||
browser_view->IsBrowserTypePanel()) {
// TODO(anicolao): implement popups for touch
NOTIMPLEMENTED();
return new PopupNonClientFrameView(frame);
} else {
return new TouchBrowserFrameView(frame, browser_view);
}
}
} // browser
| // 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/views/frame/browser_non_client_frame_view.h"
#include "base/command_line.h"
#include "chrome/browser/ui/panels/panel_browser_frame_view.h"
#include "chrome/browser/ui/panels/panel_browser_view.h"
#include "chrome/browser/ui/touch/frame/touch_browser_frame_view.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/frame/popup_non_client_frame_view.h"
#include "chrome/common/chrome_switches.h"
namespace browser {
BrowserNonClientFrameView* CreateBrowserNonClientFrameView(
BrowserFrame* frame, BrowserView* browser_view) {
Browser::Type type = browser_view->browser()->type();
switch (type) {
case Browser::TYPE_PANEL:
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnablePanels)) {
return new PanelBrowserFrameView(
frame, static_cast<PanelBrowserView*>(browser_view));
} // else, fall-through and treat as popup
case Browser::TYPE_POPUP:
// TODO(anicolao): implement popups for touch
NOTIMPLEMENTED();
return new PopupNonClientFrameView(frame);
default:
return new TouchBrowserFrameView(frame, browser_view);
}
}
} // browser
|
Remove force creation of "Adwaita-Dark" style | /*
* Copyright 2017
*
* Made by vincent leroy
* Mail <vincent.54.leroy@gmail.com>
*/
// Project includes ------------------------------------------------------------
#include "MainWindow.hpp"
// Qt includes -----------------------------------------------------------------
#include <QApplication>
#include <QWidget>
#include <QStyleFactory>
#include <QFileInfo>
// C++ standard library includes -----------------------------------------------
#include <csignal>
namespace
{
constexpr const auto styleName = "Adwaita-Dark";
}
int main(int ac, char * av[])
{
std::signal(SIGINT, [](int){ qApp->quit(); });
std::signal(SIGTERM, [](int){ qApp->quit(); });
QApplication app(ac, av);
QApplication::setOrganizationDomain("vivoka.com");
QApplication::setOrganizationName("vivoka");
QApplication::setApplicationName(QFileInfo(av[0]).baseName());
QApplication::setApplicationVersion("1.6");
if (QStyleFactory::keys().contains(styleName))
QApplication::setStyle(QStyleFactory::create(styleName));
MainWindow w;
w.restoreState();
return app.exec();
}
| /*
* Copyright 2017
*
* Made by vincent leroy
* Mail <vincent.54.leroy@gmail.com>
*/
// Project includes ------------------------------------------------------------
#include "MainWindow.hpp"
// Qt includes -----------------------------------------------------------------
#include <QApplication>
#include <QFileInfo>
// C++ standard library includes -----------------------------------------------
#include <csignal>
int main(int ac, char * av[])
{
std::signal(SIGINT, [](int){ qApp->quit(); });
std::signal(SIGTERM, [](int){ qApp->quit(); });
QApplication app(ac, av);
QApplication::setOrganizationDomain("vivoka.com");
QApplication::setOrganizationName("vivoka");
QApplication::setApplicationName(QFileInfo(av[0]).baseName());
QApplication::setApplicationVersion("1.6");
MainWindow w;
w.restoreState();
return app.exec();
}
|
Revert "Guia 2 - Particionar Merval: No setear la semilla aleatoria; no estamos" | #include "../guia1/particionar.cpp"
#include "../config.hpp"
#include <boost/filesystem.hpp>
int main()
{
vec datos;
datos.load(config::sourceDir + "/guia2/datos/merval.csv");
mat tuplas(datos.n_elem - 5, 6);
for (unsigned int i = 0; i < datos.n_rows - 5; ++i) {
tuplas.row(i) = datos.rows(span(i, i + 5)).t();
}
// FIXME: ¿Hay que randomizar el orden de las tuplas?
tuplas.save(config::sourceDir + "/guia2/datos/mervalTuplas.csv", csv_ascii);
vector<ic::Particion> particiones = ic::leaveKOut(tuplas, 47);
boost::filesystem::create_directory(config::sourceDir + "/guia2/datos/particionesMerval/");
ic::guardarParticiones(particiones, config::sourceDir + "/guia2/datos/particionesMerval/");
return 0;
}
| #include "../guia1/particionar.cpp"
#include "../config.hpp"
#include <boost/filesystem.hpp>
int main()
{
arma_rng::set_seed_random();
vec datos;
datos.load(config::sourceDir + "/guia2/datos/merval.csv");
mat tuplas(datos.n_elem - 5, 6);
for (unsigned int i = 0; i < datos.n_rows - 5; ++i) {
tuplas.row(i) = datos.rows(span(i, i + 5)).t();
}
// FIXME: ¿Hay que randomizar el orden de las tuplas?
tuplas.save(config::sourceDir + "/guia2/datos/mervalTuplas.csv", csv_ascii);
vector<ic::Particion> particiones = ic::leaveKOut(tuplas, 47);
boost::filesystem::create_directory(config::sourceDir + "/guia2/datos/particionesMerval/");
ic::guardarParticiones(particiones, config::sourceDir + "/guia2/datos/particionesMerval/");
return 0;
}
|
Set SO_REUSEADDR in listening sockets | #include <fcntl.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <glog/logging.h>
namespace {
const uint32_t k_listen_backlog = 100;
}
int create_tcp_listen_socket(int port) {
struct sockaddr_in addr;
int socket_fd = socket(PF_INET, SOCK_STREAM, 0);
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = INADDR_ANY;
if (bind(socket_fd, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
LOG(FATAL) << "bind error: " << strerror(errno);
exit(1);
}
fcntl(socket_fd, F_SETFL, fcntl(socket_fd, F_GETFL, 0) | O_NONBLOCK);
listen(socket_fd, k_listen_backlog);
return socket_fd;
}
| #include <fcntl.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <glog/logging.h>
namespace {
const uint32_t k_listen_backlog = 100;
}
int create_tcp_listen_socket(int port) {
struct sockaddr_in addr;
int socket_fd = socket(PF_INET, SOCK_STREAM, 0);
int reuse_addr = 1;
if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &reuse_addr,
sizeof(reuse_addr)) != 0)
{
LOG(ERROR) << "failed to set SO_REUSEADDR in socket";
}
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = INADDR_ANY;
if (bind(socket_fd, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
LOG(FATAL) << "bind error: " << strerror(errno);
exit(1);
}
fcntl(socket_fd, F_SETFL, fcntl(socket_fd, F_GETFL, 0) | O_NONBLOCK);
listen(socket_fd, k_listen_backlog);
return socket_fd;
}
|
Use localhost by default in our test network client | #include <stdio.h>
#include "wcl/network/TCPSocket.h"
int main(void)
{
char buffer[4096];
try{
TCPSocket s("10.220.99.84", 55555);
s.read((char *)buffer, 4096);
printf("Client: Server Said: %s\n", buffer);
s.close();
}
catch( SocketException* e )
{
fprintf( stderr, e->getReason().c_str() );
}
return 0;
}
| #include <stdio.h>
#include "wcl/network/TCPSocket.h"
int main(void)
{
char buffer[4096];
try{
TCPSocket s("127.0.0.1", 55555);
s.read((char *)buffer, 4096);
printf("Client: Server Said: %s\n", buffer);
s.close();
}
catch( SocketException* e )
{
fprintf( stderr, e->getReason().c_str() );
}
return 0;
}
|
Add test suite to Analyser | #include "gtest/gtest.h"
#include "Token.hpp"
class SemanticAnalyser
{
public:
bool analyse(const Tokens& tokens)
{
return tokens.empty();
}
};
constexpr Token createTokenWithZeroValue(TokenType type)
{
return {type, 0};
}
TEST(SemanticAnalyserTest, ShouldAcceptEmptyTokens)
{
SemanticAnalyser analyser;
Tokens tokens{};
ASSERT_TRUE(analyser.analyse(tokens));
}
TEST(SemanticAnalyserTest, ShouldNotAcceptInvalidInstructionSet)
{
SemanticAnalyser analyser;
Tokens tokens{createTokenWithZeroValue(TokenType::Ld)};
ASSERT_FALSE(analyser.analyse(tokens));
} | #include "gtest/gtest.h"
#include "Token.hpp"
class SemanticAnalyser
{
public:
bool analyse(const Tokens& tokens)
{
return tokens.empty();
}
};
using namespace ::testing;
struct SemanticAnalyserTest : public Test
{
SemanticAnalyser analyser;
static constexpr Token createTokenWithZeroValue(TokenType type)
{
return
{ type, 0};
}
};
TEST_F(SemanticAnalyserTest, ShouldAcceptEmptyTokens)
{
Tokens tokens{};
ASSERT_TRUE(analyser.analyse(tokens));
}
TEST_F(SemanticAnalyserTest, ShouldNotAcceptInvalidInstructionSet)
{
Tokens tokens{createTokenWithZeroValue(TokenType::Ld)};
ASSERT_FALSE(analyser.analyse(tokens));
} |
Use "using namespace llvm" like the rest of ELF lld. | //===- Error.cpp ----------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Error.h"
#include "Config.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/raw_ostream.h"
namespace lld {
namespace elf {
bool HasError;
llvm::raw_ostream *ErrorOS;
void log(const Twine &Msg) {
if (Config->Verbose)
llvm::outs() << Msg << "\n";
}
void warning(const Twine &Msg) {
if (Config->FatalWarnings)
error(Msg);
else
llvm::errs() << Msg << "\n";
}
void error(const Twine &Msg) {
*ErrorOS << Msg << "\n";
HasError = true;
}
void error(std::error_code EC, const Twine &Prefix) {
if (EC)
error(Prefix + ": " + EC.message());
}
void fatal(const Twine &Msg) {
llvm::errs() << Msg << "\n";
exit(1);
}
void fatal(const Twine &Msg, const Twine &Prefix) {
fatal(Prefix + ": " + Msg);
}
void check(std::error_code EC) {
if (EC)
fatal(EC.message());
}
} // namespace elf
} // namespace lld
| //===- Error.cpp ----------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Error.h"
#include "Config.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
namespace lld {
namespace elf {
bool HasError;
raw_ostream *ErrorOS;
void log(const Twine &Msg) {
if (Config->Verbose)
outs() << Msg << "\n";
}
void warning(const Twine &Msg) {
if (Config->FatalWarnings)
error(Msg);
else
errs() << Msg << "\n";
}
void error(const Twine &Msg) {
*ErrorOS << Msg << "\n";
HasError = true;
}
void error(std::error_code EC, const Twine &Prefix) {
if (EC)
error(Prefix + ": " + EC.message());
}
void fatal(const Twine &Msg) {
errs() << Msg << "\n";
exit(1);
}
void fatal(const Twine &Msg, const Twine &Prefix) {
fatal(Prefix + ": " + Msg);
}
void check(std::error_code EC) {
if (EC)
fatal(EC.message());
}
} // namespace elf
} // namespace lld
|
Expand the PIC test case for XRay | // Test to check if we handle pic code properly.
// RUN: %clangxx_xray -fxray-instrument -std=c++11 -fpic %s -o %t
// RUN: XRAY_OPTIONS="patch_premain=true verbosity=1 xray_logfile_base=pic-test-logging-" %run %t 2>&1 | FileCheck %s
// After all that, clean up the output xray log.
//
// RUN: rm pic-test-logging-*
#include <cstdio>
[[clang::xray_always_instrument]]
unsigned short foo (unsigned b);
[[clang::xray_always_instrument]]
unsigned short bar (unsigned short a)
{
printf("bar() is always instrumented!\n");
return foo(a);
}
unsigned short foo (unsigned b)
{
printf("foo() is always instrumented!\n");
return b + b + 5;
}
int main ()
{
// CHECK: XRay: Log file in 'pic-test-logging-{{.*}}'
bar(10);
// CHECK: bar() is always instrumented!
// CHECK-NEXT: foo() is always instrumented!
}
| // Test to check if we handle pic code properly.
// RUN: %clangxx_xray -fxray-instrument -std=c++11 -ffunction-sections \
// RUN: -fdata-sections -fpic -fpie -Wl,--gc-sections %s -o %t
// RUN: XRAY_OPTIONS="patch_premain=true verbosity=1 xray_logfile_base=pic-test-logging-" %run %t 2>&1 | FileCheck %s
// After all that, clean up the output xray log.
//
// RUN: rm pic-test-logging-*
#include <cstdio>
[[clang::xray_always_instrument]]
unsigned short foo (unsigned b);
[[clang::xray_always_instrument]]
unsigned short bar (unsigned short a)
{
printf("bar() is always instrumented!\n");
return foo(a);
}
unsigned short foo (unsigned b)
{
printf("foo() is always instrumented!\n");
return b + b + 5;
}
int main ()
{
// CHECK: XRay: Log file in 'pic-test-logging-{{.*}}'
bar(10);
// CHECK: bar() is always instrumented!
// CHECK-NEXT: foo() is always instrumented!
}
|
Remove unnecessary use of heap allocation |
#if defined(WIN32) && !defined(_DEBUG)
#pragma comment(linker, "/SUBSYSTEM:WINDOWS /entry:mainCRTStartup")
#endif
#include "Application.h"
#include <memory>
#include <gloperate-qtapplication/Viewer.h>
#include <widgetzeug/dark_fusion_style.hpp>
int main(int argc, char * argv[])
{
Application app(argc, argv);
widgetzeug::enableDarkFusionStyle();
std::unique_ptr<gloperate_qtapplication::Viewer> viewer(new gloperate_qtapplication::Viewer()); // make_unique is C++14
viewer->show();
return app.exec();
}
|
#if defined(WIN32) && !defined(_DEBUG)
#pragma comment(linker, "/SUBSYSTEM:WINDOWS /entry:mainCRTStartup")
#endif
#include "Application.h"
#include <memory>
#include <gloperate-qtapplication/Viewer.h>
#include <widgetzeug/dark_fusion_style.hpp>
int main(int argc, char * argv[])
{
Application app(argc, argv);
widgetzeug::enableDarkFusionStyle();
gloperate_qtapplication::Viewer viewer;
viewer.show();
return app.exec();
}
|
Fix grammar in highlight error message | #include "highlighter.hh"
#include "buffer_utils.hh"
namespace Kakoune
{
void Highlighter::highlight(HighlightContext context, DisplayBuffer& display_buffer, BufferRange range)
{
if (context.pass & m_passes) try
{
do_highlight(context, display_buffer, range);
}
catch (runtime_error& error)
{
write_to_debug_buffer(format("Error while highlighting: {}", error.what()));
}
}
void Highlighter::compute_display_setup(HighlightContext context, DisplaySetup& setup) const
{
if (context.pass & m_passes)
do_compute_display_setup(context, setup);
}
bool Highlighter::has_children() const
{
return false;
}
Highlighter& Highlighter::get_child(StringView path)
{
throw runtime_error("this highlighter do not hold children");
}
void Highlighter::add_child(HighlighterAndId&& hl)
{
throw runtime_error("this highlighter do not hold children");
}
void Highlighter::remove_child(StringView id)
{
throw runtime_error("this highlighter do not hold children");
}
Completions Highlighter::complete_child(StringView path, ByteCount cursor_pos, bool group) const
{
throw runtime_error("this highlighter do not hold children");
}
void Highlighter::fill_unique_ids(Vector<StringView>& unique_ids) const
{}
}
| #include "highlighter.hh"
#include "buffer_utils.hh"
namespace Kakoune
{
void Highlighter::highlight(HighlightContext context, DisplayBuffer& display_buffer, BufferRange range)
{
if (context.pass & m_passes) try
{
do_highlight(context, display_buffer, range);
}
catch (runtime_error& error)
{
write_to_debug_buffer(format("Error while highlighting: {}", error.what()));
}
}
void Highlighter::compute_display_setup(HighlightContext context, DisplaySetup& setup) const
{
if (context.pass & m_passes)
do_compute_display_setup(context, setup);
}
bool Highlighter::has_children() const
{
return false;
}
Highlighter& Highlighter::get_child(StringView path)
{
throw runtime_error("this highlighter does not hold children");
}
void Highlighter::add_child(HighlighterAndId&& hl)
{
throw runtime_error("this highlighter does not hold children");
}
void Highlighter::remove_child(StringView id)
{
throw runtime_error("this highlighter does not hold children");
}
Completions Highlighter::complete_child(StringView path, ByteCount cursor_pos, bool group) const
{
throw runtime_error("this highlighter does not hold children");
}
void Highlighter::fill_unique_ids(Vector<StringView>& unique_ids) const
{}
}
|
Fix incorrect move of shared session pointer. | #include <bonefish/wamp_dealer.hpp>
#include <bonefish/wamp_session.hpp>
#include <iostream>
namespace bonefish {
wamp_dealer::wamp_dealer()
: m_sessions()
{
}
wamp_dealer::~wamp_dealer()
{
}
bool wamp_dealer::attach_session(const std::shared_ptr<wamp_session>& session)
{
std::cerr << "attach session: " << session->get_session_id() << std::endl;
auto result = m_sessions.insert(
std::make_pair(session->get_session_id(), std::move(session)));
return result.second;
}
bool wamp_dealer::detach_session(const wamp_session_id& session_id)
{
std::cerr << "detach session:" << session_id << std::endl;
return m_sessions.erase(session_id) == 1;
}
} // namespace bonefish
| #include <bonefish/wamp_dealer.hpp>
#include <bonefish/wamp_session.hpp>
#include <iostream>
namespace bonefish {
wamp_dealer::wamp_dealer()
: m_sessions()
{
}
wamp_dealer::~wamp_dealer()
{
}
bool wamp_dealer::attach_session(const std::shared_ptr<wamp_session>& session)
{
std::cerr << "attach session: " << session->get_session_id() << std::endl;
auto result = m_sessions.insert(std::make_pair(session->get_session_id(), session));
return result.second;
}
bool wamp_dealer::detach_session(const wamp_session_id& session_id)
{
std::cerr << "detach session:" << session_id << std::endl;
return m_sessions.erase(session_id) == 1;
}
} // namespace bonefish
|
Use PCG32 instead of table for rand_5_k. | #include <random>
#include <vector>
#include <algorithm>
#include "Statistic.hpp"
#include <cstdlib>
namespace cctag {
namespace numerical {
static constexpr size_t MAX_POINTS = 1000;
static constexpr size_t MAX_RANDOMNESS = 10000000;
struct Randomness : public std::vector<unsigned short>
{
Randomness();
};
static Randomness randomness;
Randomness::Randomness() : std::vector<unsigned short>(MAX_RANDOMNESS)
{
std::ranlux24 engine;
engine.seed(2718282);
std::uniform_int_distribution<int> dist(0, MAX_POINTS);
for (size_t i = 0; i < MAX_RANDOMNESS; ++i)
randomness[i] = dist(engine);
}
void rand_5_k(std::array<int, 5>& perm, size_t N)
{
static thread_local int sourceIndex = 0;
auto it = perm.begin();
int r;
for (int i = 0; i < 5; ++i) {
retry:
do {
if (sourceIndex >= MAX_RANDOMNESS) sourceIndex = 0;
r = randomness[sourceIndex++];
} while (r >= N);
if (std::find(perm.begin(), it, r) != it)
goto retry;
*it++ = r;
}
}
}
} | #include <algorithm>
#include "Statistic.hpp"
#include "utils/pcg_random.hpp"
namespace cctag {
namespace numerical {
void rand_5_k(std::array<int, 5>& perm, size_t N)
{
static thread_local pcg32 rng(271828);
auto it = perm.begin();
int r;
for (int i = 0; i < 5; ++i) {
do {
r = rng(N);
} while (std::find(perm.begin(), it, r) != it);
*it++ = r;
}
}
}
} |
Add test case in main() | #include <stdio.h>
#include <stdlib.h>
int *list;
int size;
int sum;
int main(void)
{
size = 9;
sum = 15;
list = (int *)malloc(sizeof(int) * size);
list[0] = 1;
list[1] = 5;
list[2] = 8;
list[3] = 3;
list[4] = 7;
list[5] = 12;
list[6] = 11;
list[7] = 2;
list[8] = 6;
func(size - 1);
free(list);
return 0;
}
| |
Use sleep instead of a busy-wait while loop to retain the output. | #include <omp.h>
#include "proctor/detector.h"
#include "proctor/proctor.h"
#include "proctor/scanning_model_source.h"
using pcl::proctor::Detector;
//using pcl::proctor::ProctorMPI;
using pcl::proctor::Proctor;
using pcl::proctor::ScanningModelSource;
Detector detector;
Proctor proctor;
int main(int argc, char **argv) {
unsigned int model_seed = 2;
unsigned int test_seed = 0; //time(NULL);
if (argc >= 2) model_seed = atoi(argv[1]);
if (argc >= 3) test_seed = atoi(argv[2]);
ScanningModelSource model_source("Princeton", "/home/justin/Documents/benchmark/db");
model_source.loadModels();
//detector.enableVisualization();
proctor.setModelSource(&model_source);
proctor.train(detector);
proctor.test(detector, test_seed);
proctor.printResults(detector);
while (true) {}
return 0;
}
| #include <omp.h>
#include "proctor/detector.h"
#include "proctor/proctor.h"
#include "proctor/scanning_model_source.h"
using pcl::proctor::Detector;
//using pcl::proctor::ProctorMPI;
using pcl::proctor::Proctor;
using pcl::proctor::ScanningModelSource;
Detector detector;
Proctor proctor;
int main(int argc, char **argv) {
unsigned int model_seed = 2;
unsigned int test_seed = 0; //time(NULL);
if (argc >= 2) model_seed = atoi(argv[1]);
if (argc >= 3) test_seed = atoi(argv[2]);
ScanningModelSource model_source("Princeton", "/home/justin/Documents/benchmark/db");
model_source.loadModels();
//detector.enableVisualization();
proctor.setModelSource(&model_source);
proctor.train(detector);
proctor.test(detector, test_seed);
proctor.printResults(detector);
sleep(100000);
return 0;
}
|
Add newline to end of another debug message. | #include "canwrite.h"
#include "canutil_pic32.h"
#include "bitfield.h"
#include "log.h"
void copyToMessageBuffer(uint64_t source, uint8_t* destination) {
for(int i = 0; i < 8; i++) {
destination[i] = ((uint8_t*)&source)[i];
}
}
bool sendCanMessage(CanBus* bus, CanMessage request) {
CAN::TxMessageBuffer* message = CAN_CONTROLLER(bus)->getTxMessageBuffer(
CAN::CHANNEL0);
if (message != NULL) {
message->messageWord[0] = 0;
message->messageWord[1] = 0;
message->messageWord[2] = 0;
message->messageWord[3] = 0;
message->msgSID.SID = request.id;
message->msgEID.IDE = 0;
message->msgEID.DLC = 8;
memset(message->data, 0, 8);
copyToMessageBuffer(request.data, message->data);
// Mark message as ready to be processed
CAN_CONTROLLER(bus)->updateChannel(CAN::CHANNEL0);
CAN_CONTROLLER(bus)->flushTxChannel(CAN::CHANNEL0);
return true;
} else {
debug("Unable to get TX message area");
}
return false;
}
| #include "canwrite.h"
#include "canutil_pic32.h"
#include "bitfield.h"
#include "log.h"
void copyToMessageBuffer(uint64_t source, uint8_t* destination) {
for(int i = 0; i < 8; i++) {
destination[i] = ((uint8_t*)&source)[i];
}
}
bool sendCanMessage(CanBus* bus, CanMessage request) {
CAN::TxMessageBuffer* message = CAN_CONTROLLER(bus)->getTxMessageBuffer(
CAN::CHANNEL0);
if (message != NULL) {
message->messageWord[0] = 0;
message->messageWord[1] = 0;
message->messageWord[2] = 0;
message->messageWord[3] = 0;
message->msgSID.SID = request.id;
message->msgEID.IDE = 0;
message->msgEID.DLC = 8;
memset(message->data, 0, 8);
copyToMessageBuffer(request.data, message->data);
// Mark message as ready to be processed
CAN_CONTROLLER(bus)->updateChannel(CAN::CHANNEL0);
CAN_CONTROLLER(bus)->flushTxChannel(CAN::CHANNEL0);
return true;
} else {
debug("Unable to get TX message area\r\n");
}
return false;
}
|
Fix a prevent issue - Resource leak | /*
* Copyright (c) 2014 Samsung Electronics Co., Ltd.
*
* 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.
*
*/
// CLASS HEADER
#include <adaptor-impl.h>
// EXTERNAL INCLUDES
#ifdef OVER_TIZEN_SDK_2_2
#include <app.h>
#endif
namespace Dali
{
namespace Internal
{
namespace Adaptor
{
void Adaptor::GetDataStoragePath( std::string& path)
{
path = "";
#ifdef OVER_TIZEN_SDK_2_2
char *pathInt = app_get_data_path();
if ( pathInt )
{
path = pathInt;
}
#endif
}
} // namespace Adaptor
} // namespace Internal
} // namespace Dali
| /*
* Copyright (c) 2014 Samsung Electronics Co., Ltd.
*
* 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.
*
*/
// CLASS HEADER
#include <adaptor-impl.h>
// EXTERNAL INCLUDES
#ifdef OVER_TIZEN_SDK_2_2
#include <app.h>
#endif
namespace Dali
{
namespace Internal
{
namespace Adaptor
{
void Adaptor::GetDataStoragePath( std::string& path)
{
path = "";
#ifdef OVER_TIZEN_SDK_2_2
char *pathInt = app_get_data_path();
if ( pathInt )
{
path = pathInt;
free( pathInt );
}
#endif
}
} // namespace Adaptor
} // namespace Internal
} // namespace Dali
|
Fix regression where we didn't ever start watching for network address changes on Windows. | // 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 "net/base/network_change_notifier_win.h"
#include <iphlpapi.h>
#include <winsock2.h>
#pragma comment(lib, "iphlpapi.lib")
namespace net {
NetworkChangeNotifierWin::NetworkChangeNotifierWin() {
memset(&addr_overlapped_, 0, sizeof addr_overlapped_);
addr_overlapped_.hEvent = WSACreateEvent();
}
NetworkChangeNotifierWin::~NetworkChangeNotifierWin() {
CancelIPChangeNotify(&addr_overlapped_);
addr_watcher_.StopWatching();
WSACloseEvent(addr_overlapped_.hEvent);
}
void NetworkChangeNotifierWin::OnObjectSignaled(HANDLE object) {
NotifyObserversOfIPAddressChange();
// Start watching for the next address change.
WatchForAddressChange();
}
void NetworkChangeNotifierWin::WatchForAddressChange() {
HANDLE handle = NULL;
DWORD ret = NotifyAddrChange(&handle, &addr_overlapped_);
CHECK(ret == ERROR_IO_PENDING);
addr_watcher_.StartWatching(addr_overlapped_.hEvent, this);
}
} // namespace net
| // 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 "net/base/network_change_notifier_win.h"
#include <iphlpapi.h>
#include <winsock2.h>
#pragma comment(lib, "iphlpapi.lib")
namespace net {
NetworkChangeNotifierWin::NetworkChangeNotifierWin() {
memset(&addr_overlapped_, 0, sizeof addr_overlapped_);
addr_overlapped_.hEvent = WSACreateEvent();
WatchForAddressChange();
}
NetworkChangeNotifierWin::~NetworkChangeNotifierWin() {
CancelIPChangeNotify(&addr_overlapped_);
addr_watcher_.StopWatching();
WSACloseEvent(addr_overlapped_.hEvent);
}
void NetworkChangeNotifierWin::OnObjectSignaled(HANDLE object) {
NotifyObserversOfIPAddressChange();
// Start watching for the next address change.
WatchForAddressChange();
}
void NetworkChangeNotifierWin::WatchForAddressChange() {
HANDLE handle = NULL;
DWORD ret = NotifyAddrChange(&handle, &addr_overlapped_);
CHECK(ret == ERROR_IO_PENDING);
addr_watcher_.StartWatching(addr_overlapped_.hEvent, this);
}
} // namespace net
|
Fix DeleteCache on POSIX. It wasn't successfully deleting before. | // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/disk_cache/cache_util.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/string_util.h"
namespace disk_cache {
bool MoveCache(const std::wstring& from_path, const std::wstring& to_path) {
// Just use the version from base.
return file_util::Move(from_path.c_str(), to_path.c_str());
}
void DeleteCache(const std::wstring& path, bool remove_folder) {
if (remove_folder) {
file_util::Delete(path, false);
} else {
std::wstring name(path);
// TODO(rvargas): Fix this after file_util::delete is fixed.
// file_util::AppendToPath(&name, L"*");
file_util::Delete(name, true);
}
}
bool DeleteCacheFile(const std::wstring& name) {
return file_util::Delete(name, false);
}
void WaitForPendingIO(int* num_pending_io) {
if (*num_pending_io) {
NOTIMPLEMENTED();
}
}
} // namespace disk_cache
| // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/disk_cache/cache_util.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/string_util.h"
namespace disk_cache {
bool MoveCache(const std::wstring& from_path, const std::wstring& to_path) {
// Just use the version from base.
return file_util::Move(from_path.c_str(), to_path.c_str());
}
void DeleteCache(const std::wstring& path, bool remove_folder) {
file_util::FileEnumerator iter(path, /* recursive */ false,
file_util::FileEnumerator::FILES);
for (std::wstring file = iter.Next(); !file.empty(); file = iter.Next()) {
if (!file_util::Delete(file, /* recursive */ false))
NOTREACHED();
}
if (remove_folder) {
if (!file_util::Delete(path, /* recursive */ false))
NOTREACHED();
}
}
bool DeleteCacheFile(const std::wstring& name) {
return file_util::Delete(name, false);
}
void WaitForPendingIO(int* num_pending_io) {
if (*num_pending_io) {
NOTIMPLEMENTED();
}
}
} // namespace disk_cache
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.