Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Normalize tested for vector2. vector2 tested fully | // Copyright (c) 2017 Pierre Fourgeaud
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include <bandit/bandit.h>
#include "core/math/vector2.h"
using namespace bandit;
using namespace snowhouse;
using namespace CodeHero;
go_bandit([]() {
describe("Vector2", []() {
describe("Constructor", []() {
it("should initialize vector with 0s if no arguments", [] {
Vector2 test;
AssertThat(test.x(), Equals(0.0f));
});
it("should initialize vector with correct x and y if provided", [] {
float x = 1.5f;
float y = 1.5f;
Vector2 test(x, y);
AssertThat(test.x(), Equals(x));
AssertThat(test.y(), Equals(y));
});
});
describe("::Length", [] {
it("should compute the proper length", [] {
float x = 2.0f;
float y = 2.0f;
Vector2 test(x, y);
float res = 2.8284271247461903f;
AssertThat(test.Length(), Equals(res));
});
});
});
}); | // Copyright (c) 2017 Pierre Fourgeaud
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include <bandit/bandit.h>
#include "core/math/vector2.h"
using namespace bandit;
using namespace snowhouse;
using namespace CodeHero;
go_bandit([]() {
describe("Vector2", []() {
describe("Constructor", []() {
it("should initialize vector with 0s if no arguments", [] {
Vector2 test;
AssertThat(test.x(), Equals(0.0f));
});
it("should initialize vector with correct x and y if provided", [] {
float x = 1.5f;
float y = 1.5f;
Vector2 test(x, y);
AssertThat(test.x(), Equals(x));
AssertThat(test.y(), Equals(y));
});
});
describe("::Length", [] {
it("should compute the proper length", [] {
float x = 2.0f;
float y = 2.0f;
Vector2 test(x, y);
float res = 2.8284271247461903f;
AssertThat(test.Length(), Equals(res));
});
});
describe("::Normalize", [] {
it("should compute the normalized vector", [] {
Vector2 test(1.0f, 1.0f);
float res = 0.70710678118f;
test.Normalize();
AssertThat(test.x(), Equals(res));
AssertThat(test.y(), Equals(res));
});
});
});
}); |
Add test for first problem solution | #include <iostream>
using namespace std;
const int MAX = 100;
struct Person {
string firstName;
string lastName;
void input() {
cout << "Enter person's first and last names separated by a space: ";
cin >> firstName >> lastName;
}
void print() {
cout << firstName << ' ' << lastName << '\n';
}
};
struct Client {
Person person;
double account;
void input() {
person.input();
cout << "Enter account: ";
cin >> account;
}
void print() {
person.print();
cout << "Account: " << account << '\n';
};
};
void inputClients(int n) {
Client clients[MAX];
for (int i = 0; i < n; ++i) {
clients[i].input();
}
}
void printClients(Client clients[], int n) {
for (int i = 0; i < n; ++i) {
clients[i].print();
}
}
double sumAccounts(Client clients[], int n) {
double sum = 0;
for (int i = 0; i < n; ++i) {
sum += clients[i].account;
}
return sum;
}
int main() {
return 0;
}
| #include <iostream>
using namespace std;
const int MAX = 100;
struct Person {
string firstName;
string lastName;
void input() {
cout << "Enter person's first and last names separated by a space: ";
cin >> firstName >> lastName;
}
void print() {
cout << firstName << ' ' << lastName << '\n';
}
};
struct Client {
Person person;
double account;
void input() {
person.input();
cout << "Enter account: ";
cin >> account;
}
void print() {
person.print();
cout << "Account: " << account << '\n';
};
};
void inputClients(Client clients[], int n) {
for (int i = 0; i < n; ++i) {
clients[i].input();
}
}
void printClients(Client clients[], int n) {
for (int i = 0; i < n; ++i) {
clients[i].print();
}
}
double sumAccounts(Client clients[], int n) {
double sum = 0;
for (int i = 0; i < n; ++i) {
sum += clients[i].account;
}
return sum;
}
int main() {
Client clients[MAX];
int clientsCount = 3;
inputClients(clients, clientsCount);
printClients(clients, clientsCount);
cout << sumAccounts(clients, clientsCount) << '\n';
return 0;
}
|
Make the father walk straight | //
// Created by dar on 2/21/16.
//
#include "EntityFather.h"
EntityFather::EntityFather(Map *map) : EntityMoving(map, 0.25, 0.25) {
b2PolygonShape shape;
shape.SetAsBox(0.25, 0.25);
b2FixtureDef fixDef;
fixDef.shape = &shape;
fixDef.density = 6.0f;
fixDef.friction = 0.1f;
this->body->CreateFixture(&fixDef);
}
void EntityFather::update() {
EntityMoving::update();
this->applyImpulse(1.0f * this->getSpeed(), 0.0f);
}
double EntityFather::getSpeed() {
return 0.5f;
} | //
// Created by dar on 2/21/16.
//
#include "EntityFather.h"
EntityFather::EntityFather(Map *map) : EntityMoving(map, 0.25, 0.25) {
b2PolygonShape shape;
shape.SetAsBox(0.25, 0.25);
b2FixtureDef fixDef;
fixDef.shape = &shape;
fixDef.density = 6.0f;
fixDef.friction = 0.1f;
this->body->CreateFixture(&fixDef);
}
void EntityFather::update() {
EntityMoving::update();
this->applyImpulse(1.0f * this->getSpeed() * cos(this->getAngle()), 1.0f * this->getSpeed() * sin(this->getAngle()));
}
double EntityFather::getSpeed() {
return 0.5f;
} |
Fix bug for parsing google test flags | /*
* main.cc
*
* Copyright (c) 2015 Masatoshi Hanai
*
* This software is released under MIT License.
* See LICENSE.
*
*/
#include "glog/logging.h"
#include "gflags/gflags.h"
#include "gtest/gtest.h"
#include "leveldb/db.h"
#include "leveldb/options.h"
/* test files */
#include "medium/com_test.cc"
#include "medium/db_via_lp_test.cc"
#include "medium/gvt_test.cc"
#include "medium/logical_process_test.cc"
#include "small/db_test.cc"
#include "small/io_test.cc"
#include "small/thread_test.cc"
#include "small/util_test.cc"
int main(int argc, char** argv) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(*argv);
google::InstallFailureSignalHandler();
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| /*
* main.cc
*
* Copyright (c) 2015 Masatoshi Hanai
*
* This software is released under MIT License.
* See LICENSE.
*
*/
#include "glog/logging.h"
#include "gflags/gflags.h"
#include "gtest/gtest.h"
#include "leveldb/db.h"
#include "leveldb/options.h"
/* test files */
#include "medium/com_test.cc"
#include "medium/db_via_lp_test.cc"
#include "medium/gvt_test.cc"
#include "medium/logical_process_test.cc"
#include "small/db_test.cc"
#include "small/io_test.cc"
#include "small/thread_test.cc"
#include "small/util_test.cc"
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
gflags::ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(*argv);
google::InstallFailureSignalHandler();
return RUN_ALL_TESTS();
}
|
Increase timeout of Crash test. | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "perfetto/base/watchdog.h"
#include "gtest/gtest.h"
#include <time.h>
namespace perfetto {
namespace base {
namespace {
TEST(WatchDogTest, Crash) {
EXPECT_DEATH(
{
WatchDog watchdog(1);
usleep(2000000);
},
"");
}
TEST(WatchDogTest, NoCrash) {
WatchDog watchdog(100000);
usleep(5000);
}
} // namespace
} // namespace base
} // namespace perfetto
| /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "perfetto/base/watchdog.h"
#include "perfetto/base/logging.h"
#include "gtest/gtest.h"
#include <time.h>
namespace perfetto {
namespace base {
namespace {
TEST(WatchDogTest, Crash) {
EXPECT_DEATH(
{
WatchDog watchdog(1);
int sleep_s = 20;
while (sleep_s != 0) {
sleep_s = sleep(sleep_s);
}
},
"");
}
TEST(WatchDogTest, NoCrash) {
WatchDog watchdog(100000);
PERFETTO_CHECK(usleep(5000) != -1);
}
} // namespace
} // namespace base
} // namespace perfetto
|
Secure this test against slightly different number formatters. | // RUN: %clang_cc1 -verify -triple x86_64-apple-darwin -emit-llvm -o - %s | FileCheck %s
// CHECK: @a = global i32 10
int a = 10;
// CHECK: @ar = constant i32* @a
int &ar = a;
void f();
// CHECK: @fr = constant void ()* @_Z1fv
void (&fr)() = f;
struct S { int& a; };
// CHECK: @s = global %0 { i32* @a }
S s = { a };
// PR5581
namespace PR5581 {
class C {
public:
enum { e0, e1 };
unsigned f;
};
// CHECK: @_ZN6PR55812g0E = global %1 { i32 1 }
C g0 = { C::e1 };
}
namespace test2 {
struct A {
static const double d = 1.0;
static const float f = d / 2;
};
// CHECK: @_ZN5test22t0E = global double 1.000000e+00, align 8
// CHECK: @_ZN5test22t1E = global [2 x double] [double 1.000000e+00, double 5.000000e-01], align 16
double t0 = A::d;
double t1[] = { A::d, A::f };
}
| // RUN: %clang_cc1 -verify -triple x86_64-apple-darwin -emit-llvm -o - %s | FileCheck %s
// CHECK: @a = global i32 10
int a = 10;
// CHECK: @ar = constant i32* @a
int &ar = a;
void f();
// CHECK: @fr = constant void ()* @_Z1fv
void (&fr)() = f;
struct S { int& a; };
// CHECK: @s = global %0 { i32* @a }
S s = { a };
// PR5581
namespace PR5581 {
class C {
public:
enum { e0, e1 };
unsigned f;
};
// CHECK: @_ZN6PR55812g0E = global %1 { i32 1 }
C g0 = { C::e1 };
}
namespace test2 {
struct A {
static const double d = 1.0;
static const float f = d / 2;
};
// CHECK: @_ZN5test22t0E = global double {{1\.0+e\+0+}}, align 8
// CHECK: @_ZN5test22t1E = global [2 x double] [double {{1\.0+e\+0+}}, double {{5\.0+e-0*}}1], align 16
double t0 = A::d;
double t1[] = { A::d, A::f };
}
|
Fix for MPLY-9036. Guard against null region values from IA. Buddy: Jordan | // Copyright eeGeo Ltd (2012-2017), All Rights Reserved
#include <jni.h>
#include "AndroidAppThreadAssertionMacros.h"
#include "IndoorAtlasLocationManager.h"
#include "IndoorAtlasLocationManagerJni.h"
extern "C"
{
JNIEXPORT void JNICALL Java_com_eegeo_interiorsposition_indooratlas_IndoorAtlasLocationManagerJniMethods_DidUpdateLocation(
JNIEnv *jenv, jclass jobj,
jlong nativeObjectPtr,
jdouble latitude,
jdouble longitude,
jstring floorId)
{
const char* chars = jenv->GetStringUTFChars(floorId, 0);
std::string floorIdString = chars;
jenv->ReleaseStringUTFChars(floorId, chars);
using ExampleApp::InteriorsPosition::SdkModel::IndoorAtlas::IndoorAtlasLocationManager;
reinterpret_cast<IndoorAtlasLocationManager *>(nativeObjectPtr)->DidUpdateLocation(latitude,
longitude,
floorIdString);
}
JNIEXPORT void JNICALL Java_com_eegeo_interiorsposition_indooratlas_IndoorAtlasLocationManagerJniMethods_SetIsAuthorized(
JNIEnv *jenv, jclass obj,
jlong nativeObjectPtr,
jboolean isAuthorized)
{
using ExampleApp::InteriorsPosition::SdkModel::IndoorAtlas::IndoorAtlasLocationManager;
reinterpret_cast<IndoorAtlasLocationManager *>(nativeObjectPtr)->SetIsAuthorized(isAuthorized);
}
}
| // Copyright eeGeo Ltd (2012-2017), All Rights Reserved
#include <jni.h>
#include "AndroidAppThreadAssertionMacros.h"
#include "IndoorAtlasLocationManager.h"
#include "IndoorAtlasLocationManagerJni.h"
extern "C"
{
JNIEXPORT void JNICALL Java_com_eegeo_interiorsposition_indooratlas_IndoorAtlasLocationManagerJniMethods_DidUpdateLocation(
JNIEnv *jenv, jclass jobj,
jlong nativeObjectPtr,
jdouble latitude,
jdouble longitude,
jstring floorId)
{
std::string floorIdString = "";
if(floorId != NULL)
{
const char *chars = jenv->GetStringUTFChars(floorId, 0);
floorIdString = chars;
jenv->ReleaseStringUTFChars(floorId, chars);
}
using ExampleApp::InteriorsPosition::SdkModel::IndoorAtlas::IndoorAtlasLocationManager;
reinterpret_cast<IndoorAtlasLocationManager *>(nativeObjectPtr)->DidUpdateLocation(latitude,
longitude,
floorIdString);
}
JNIEXPORT void JNICALL Java_com_eegeo_interiorsposition_indooratlas_IndoorAtlasLocationManagerJniMethods_SetIsAuthorized(
JNIEnv *jenv, jclass obj,
jlong nativeObjectPtr,
jboolean isAuthorized)
{
using ExampleApp::InteriorsPosition::SdkModel::IndoorAtlas::IndoorAtlasLocationManager;
reinterpret_cast<IndoorAtlasLocationManager *>(nativeObjectPtr)->SetIsAuthorized(isAuthorized);
}
}
|
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"));
}
|
Read in input and freq.txt | #include <iostream>
#include <cstdlib>
#include <vector>
#include <bitset>
#include <cstring>
#include <string>
#include "rand.h"
using namespace std;
int main() {
string cipher;
getline(cin, cipher);
cout << cipher << endl;
}
| #include <iostream>
#include <cstdlib>
#include <vector>
#include <bitset>
#include <cstring>
#include <string>
#include <fstream>
#include "rand.h"
using namespace std;
int main() {
string cipher, tmp;
while( getline( cin, tmp ) )
{
cipher.append( tmp );
}
// cout << cipher << endl;
ifstream freq;
freq.open( "freq.txt", ios::in );
string freqletter[488];
int freqnumber[488];
if( freq.is_open() ) {
for(int i = 0; i < 488; i++ ) {
freq >> freqletter[i];
freq >> freqnumber[i];
}
}
freq.close();
// for(int i = 0; i < 488; i++ ) {
// cout << freqletter[i] << " " << freqnumber[i] << endl;
// }
}
|
Update getMetadataKindOf for +0 parameters. | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/Runtime/Config.h"
#include "swift/Runtime/Metadata.h"
using namespace swift;
SWIFT_CC(swift) LLVM_LIBRARY_VISIBILITY extern "C"
uint32_t getMetadataKindOf(
OpaqueValue *value,
const Metadata *type
) {
auto result = uint32_t(type->getKind());
type->vw_destroy(value);
return result;
}
| //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/Runtime/Config.h"
#include "swift/Runtime/Metadata.h"
using namespace swift;
SWIFT_CC(swift) LLVM_LIBRARY_VISIBILITY extern "C"
uint32_t getMetadataKindOf(
OpaqueValue *value,
const Metadata *type
) {
auto result = uint32_t(type->getKind());
SWIFT_CC_PLUSONE_GUARD(type->vw_destroy(value));
return result;
}
|
Add space after switch keyword | #include <iostream>
using std::cin;
using std::cout;
int main() {
char operation;
cout << "Choose an operation (+, -, *, /): ";
cin >> operation;
double first_operand;
double second_operand;
cout << "Enter your operands: ";
cin >> first_operand >> second_operand;
double result;
switch(operation) {
case '+':
result = first_operand + second_operand;
break;
case '-':
result = first_operand - second_operand;
break;
case '*':
result = first_operand * second_operand;
break;
case '/':
result = first_operand / second_operand;
break;
default:
cout << "Unknown operation " << operation << '\n';
return 1;
}
cout << first_operand << ' '
<< operation << ' '
<< second_operand << " = "
<< result << '\n';
return 0;
}
| #include <iostream>
using std::cin;
using std::cout;
int main() {
char operation;
cout << "Choose an operation (+, -, *, /): ";
cin >> operation;
double first_operand;
double second_operand;
cout << "Enter your operands: ";
cin >> first_operand >> second_operand;
double result;
switch (operation) {
case '+':
result = first_operand + second_operand;
break;
case '-':
result = first_operand - second_operand;
break;
case '*':
result = first_operand * second_operand;
break;
case '/':
result = first_operand / second_operand;
break;
default:
cout << "Unknown operation " << operation << '\n';
return 1;
}
cout << first_operand << ' '
<< operation << ' '
<< second_operand << " = "
<< result << '\n';
return 0;
}
|
Add format string to gtk_message_dialog_new() | #include <boxer/boxer.h>
#include <gtk/gtk.h>
namespace boxer {
void show(const char *message, const char *title) {
gtk_init(0, NULL);
GtkWidget *dialog = gtk_message_dialog_new(NULL,
GTK_DIALOG_MODAL,
GTK_MESSAGE_INFO,
GTK_BUTTONS_OK,
message);
gtk_window_set_title(GTK_WINDOW(dialog), title);
gtk_dialog_run(GTK_DIALOG(dialog));
gtk_widget_destroy(GTK_WIDGET(dialog));
while (g_main_context_iteration(NULL, false));
}
} // namespace boxer
| #include <boxer/boxer.h>
#include <gtk/gtk.h>
namespace boxer {
void show(const char *message, const char *title) {
gtk_init(0, NULL);
GtkWidget *dialog = gtk_message_dialog_new(NULL,
GTK_DIALOG_MODAL,
GTK_MESSAGE_INFO,
GTK_BUTTONS_OK,
"%s",
message);
gtk_window_set_title(GTK_WINDOW(dialog), title);
gtk_dialog_run(GTK_DIALOG(dialog));
gtk_widget_destroy(GTK_WIDGET(dialog));
while (g_main_context_iteration(NULL, false));
}
} // namespace boxer
|
Add first cpu unit test | #include <gtest/gtest.h>
#include "../../include/Cpu.h"
// The fixture for testing class Foo.
class CpuTest : public ::testing::Test
{
protected:
CpuTest()
{
}
~CpuTest() override
{
}
void SetUp() override
{
}
void TearDown() override
{
}
Cpu cpu;
};
TEST_F(CpuTest, instruction1test)
{
} | #include <gtest/gtest.h>
#include "../../include/Cpu.h"
// The fixture for testing class Foo.
class CpuTest : public Cpu, public ::testing::Test
{
protected:
CpuTest()
{
}
~CpuTest() override
{
}
void SetUp() override
{
}
void TearDown() override
{
}
};
TEST_F(CpuTest, pcNop)
{
runOpcode(0x01);
EXPECT_EQ(getPC(), 3);
} |
Reorganize empty and full tests. | extern "C"
{
#include "packet_queue.h"
#include "error.h"
#include "nrf51.h"
#include "nrf51_bitfields.h"
}
#include "CppUTest/TestHarness.h"
TEST_GROUP(packet_queue)
{
packet_queue_t queue;
void setup(void)
{
packet_queue_init(&queue);
}
void teardown(void)
{
}
};
TEST(packet_queue, test_queue_init_succeed)
{
packet_queue_t queue;
LONGS_EQUAL(SUCCESS, packet_queue_init(&queue));
}
TEST(packet_queue, test_queue_new_queue_is_empty)
{
LONGS_EQUAL(true, packet_queue_is_empty(&queue));
}
TEST(packet_queue, test_queue_add_queue_is_not_empty)
{
radio_packet_t packet;
packet_queue_add(&queue, &packet);
LONGS_EQUAL(false, packet_queue_is_empty(&queue));
}
| extern "C"
{
#include "packet_queue.h"
#include "error.h"
#include "nrf51.h"
#include "nrf51_bitfields.h"
}
#include "CppUTest/TestHarness.h"
#include <limits.h>
#include <string.h>
TEST_GROUP(packet_queue)
{
packet_queue_t queue;
void setup(void)
{
packet_queue_init(&queue);
}
void teardown(void)
{
}
};
TEST(packet_queue, test_queue_init_succeed)
{
packet_queue_t queue;
LONGS_EQUAL(SUCCESS, packet_queue_init(&queue));
}
TEST(packet_queue, test_queue_new_queue_is_empty)
{
LONGS_EQUAL(true, packet_queue_is_empty(&queue));
radio_packet_t packet;
packet_queue_add(&queue, &packet);
LONGS_EQUAL(false, packet_queue_is_empty(&queue));
}
TEST(packet_queue, test_queue_full_queue_is_full)
{
LONGS_EQUAL(false, packet_queue_is_full(&queue));
for (int i = 0; i < PACKET_QUEUE_SIZE; i++)
{
radio_packet_t packet;
packet_queue_add(&queue, &packet);
}
LONGS_EQUAL(true, packet_queue_is_full(&queue));
}
|
Fix types in iterator async | #include <assert.h>
#include <leveldb/iterator.h>
#include <node.h>
#include <v8.h>
#include "iterator.h"
namespace node_leveldb {
async_rtn JIterator::After(uv_work_t* req) {
Params *data = (Params*) req->data;
data->callback->Call(data->self->handle_, 0, NULL);
delete data;
RETURN_ASYNC_AFTER;
}
async_rtn JIterator::Seek(uv_work_t* req) {
SeekParams *data = (SeekParams*) req->data;
data->self->it_->Seek(data->key);
RETURN_ASYNC;
}
async_rtn JIterator::First(uv_work_t* req) {
SeekParams *data = (SeekParams*) req->data;
data->self->it_->SeekToFirst();
RETURN_ASYNC;
}
async_rtn JIterator::Last(uv_work_t* req) {
SeekParams *data = (SeekParams*) req->data;
data->self->it_->SeekToLast();
RETURN_ASYNC;
}
async_rtn JIterator::Next(uv_work_t* req) {
SeekParams *data = (SeekParams*) req->data;
data->self->it_->Next();
RETURN_ASYNC;
}
async_rtn JIterator::Prev(uv_work_t* req) {
SeekParams *data = (SeekParams*) req->data;
data->self->it_->Prev();
RETURN_ASYNC;
}
} // node_leveldb
| #include <assert.h>
#include <leveldb/iterator.h>
#include <node.h>
#include <v8.h>
#include "iterator.h"
namespace node_leveldb {
async_rtn JIterator::After(uv_work_t* req) {
Params *data = (Params*) req->data;
data->callback->Call(data->self->handle_, 0, NULL);
delete data;
RETURN_ASYNC_AFTER;
}
async_rtn JIterator::Seek(uv_work_t* req) {
SeekParams *data = (SeekParams*) req->data;
data->self->it_->Seek(data->key);
RETURN_ASYNC;
}
async_rtn JIterator::First(uv_work_t* req) {
Params *data = (Params*) req->data;
data->self->it_->SeekToFirst();
RETURN_ASYNC;
}
async_rtn JIterator::Last(uv_work_t* req) {
Params *data = (Params*) req->data;
data->self->it_->SeekToLast();
RETURN_ASYNC;
}
async_rtn JIterator::Next(uv_work_t* req) {
Params *data = (Params*) req->data;
data->self->it_->Next();
RETURN_ASYNC;
}
async_rtn JIterator::Prev(uv_work_t* req) {
Params *data = (Params*) req->data;
data->self->it_->Prev();
RETURN_ASYNC;
}
} // node_leveldb
|
Use log(X)/log(2.0) instead of log2() function |
// Qt includes
//#include <QHash>
//#include <QVariant>
// Visomics includes
#include "voLog2.h"
// VTK includes
#include <vtkDoubleArray.h>
#include <vtkMath.h>
#include <vtkTable.h>
namespace Normalization
{
//------------------------------------------------------------------------------
bool applyLog2(vtkTable * dataTable, const QHash<int, QVariant>& settings)
{
Q_UNUSED(settings);
if (!dataTable)
{
return false;
}
for (int cid = 0; cid < dataTable->GetNumberOfColumns(); ++cid)
{
vtkDoubleArray * column = vtkDoubleArray::SafeDownCast(dataTable->GetColumn(cid));
if (!column)
{
continue;
}
for (int rid = 0; rid < column->GetNumberOfTuples() * column->GetNumberOfComponents(); ++rid)
{
column->SetValue(rid, log2(column->GetValue(rid)));
}
}
dataTable->Modified();
return true;
}
} // end of Normalization namespace
|
// Qt includes
//#include <QHash>
//#include <QVariant>
// Visomics includes
#include "voLog2.h"
// VTK includes
#include <vtkDoubleArray.h>
#include <vtkTable.h>
// STD includes
#include <cmath>
namespace Normalization
{
//------------------------------------------------------------------------------
bool applyLog2(vtkTable * dataTable, const QHash<int, QVariant>& settings)
{
Q_UNUSED(settings);
if (!dataTable)
{
return false;
}
for (int cid = 0; cid < dataTable->GetNumberOfColumns(); ++cid)
{
vtkDoubleArray * column = vtkDoubleArray::SafeDownCast(dataTable->GetColumn(cid));
if (!column)
{
continue;
}
for (int rid = 0; rid < column->GetNumberOfTuples() * column->GetNumberOfComponents(); ++rid)
{
column->SetValue(rid, std::log(column->GetValue(rid)) / log(2.0));
}
}
dataTable->Modified();
return true;
}
} // end of Normalization namespace
|
Create app dir if not exists (linux) | #include "mainwindowcontroller.h"
#include "ui_mainwindowcontroller.h"
#include <QErrorMessage>
#include <QStandardPaths>
#include <QDir>
#include <QCoreApplication>
#include "kopsik_api.h"
MainWindowController::MainWindowController(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindowController)
{
ui->setupUi(this);
QString version = QCoreApplication::applicationVersion();
ctx_ = kopsik_context_init("linux_native_app", version.toUtf8().constData());
QString appDirPath =
QStandardPaths::writableLocation(QStandardPaths::DataLocation);
QDir appDir = QDir(appDirPath);
QString logPath = appDir.filePath("kopsik.log");
kopsik_set_log_path(logPath.toUtf8().constData());
QString dbPath = appDir.filePath("kopsik.db");
kopsik_set_db_path(ctx_, dbPath.toUtf8().constData());
QString executablePath = QCoreApplication::applicationDirPath();
QDir executableDir = QDir(executablePath);
QString cacertPath = executableDir.filePath("cacert.pem");
kopsik_set_cacert_path(ctx_, cacertPath.toUtf8().constData());
if (!kopsik_context_start_events(ctx_)) {
}
}
MainWindowController::~MainWindowController()
{
kopsik_context_clear(ctx_);
delete ui;
}
| #include "mainwindowcontroller.h"
#include "ui_mainwindowcontroller.h"
#include <QErrorMessage>
#include <QStandardPaths>
#include <QDir>
#include <QCoreApplication>
#include "kopsik_api.h"
MainWindowController::MainWindowController(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindowController)
{
ui->setupUi(this);
QString version = QCoreApplication::applicationVersion();
ctx_ = kopsik_context_init("linux_native_app", version.toUtf8().constData());
QString appDirPath =
QStandardPaths::writableLocation(QStandardPaths::DataLocation);
QDir appDir = QDir(appDirPath);
if (!appDir.exists()) {
appDir.mkpath(".");
}
QString logPath = appDir.filePath("kopsik.log");
kopsik_set_log_path(logPath.toUtf8().constData());
QString dbPath = appDir.filePath("kopsik.db");
kopsik_set_db_path(ctx_, dbPath.toUtf8().constData());
QString executablePath = QCoreApplication::applicationDirPath();
QDir executableDir = QDir(executablePath);
QString cacertPath = executableDir.filePath("cacert.pem");
kopsik_set_cacert_path(ctx_, cacertPath.toUtf8().constData());
if (!kopsik_context_start_events(ctx_)) {
}
}
MainWindowController::~MainWindowController()
{
kopsik_context_clear(ctx_);
delete ui;
}
|
Fix ball bouncing before graphic touched borders. | #include "Ball.h"
void Ball::reset()
{
float resetX, resetY;
resetX = displayW / 2.0;
resetY = rand() % displayH;
randomDirection();
setPosition(resetX, resetY);
}
void Ball::update()
{
checkForCollisions();
x += accelX;
y += accelY;
if (testBit(DEAD))
{
reset();
clearBit(DEAD);
}
calcCenter();
}
void Ball::randomDirection()
{
if (rand() % 2)
{
accelX *= -1;
}
if (rand() % 2)
{
accelY *= -1;
}
}
void Ball::getDisplayData()
{
ALLEGRO_DISPLAY *display = al_get_current_display();
displayW = al_get_display_width(display);
displayH = al_get_display_height(display);
}
void Ball::checkForCollisions()
{
if (x < 0 || x > displayW)
{
accelX *= -1;
}
if (y < 0 || y > displayH)
{
accelY *= -1;
}
} | #include "Ball.h"
void Ball::reset()
{
float resetX, resetY;
resetX = displayW / 2.0;
resetY = rand() % displayH;
randomDirection();
setPosition(resetX, resetY);
}
void Ball::update()
{
checkForCollisions();
x += accelX;
y += accelY;
if (testBit(DEAD))
{
reset();
clearBit(DEAD);
}
calcCenter();
}
void Ball::randomDirection()
{
if (rand() % 2)
{
accelX *= -1;
}
if (rand() % 2)
{
accelY *= -1;
}
}
void Ball::getDisplayData()
{
ALLEGRO_DISPLAY *display = al_get_current_display();
displayW = al_get_display_width(display);
displayH = al_get_display_height(display);
}
void Ball::checkForCollisions()
{
if (x - w / 2.0 < 0 || x + w / 2.0 > displayW)
{
accelX *= -1;
}
if (y - h / 2.0 < 0 || y + h / 2.0> displayH)
{
accelY *= -1;
}
} |
Make the minimum stack size depend on the default stack size. | #include <kernel/config.h>
#include <kernel/kernconf.hh>
USDK_API kernconf_type kernconf = {
// Default is large enough until we enable a mechanism to dynamically
// reallocate task space on demand.
/* .default_stack_size = */ URBI_KERNEL_STACK_SIZE * 1024,
/* .minimum_stack_size = */ 4 * 1024
};
| #include <kernel/config.h>
#include <kernel/kernconf.hh>
USDK_API kernconf_type kernconf = {
// Default is large enough until we enable a mechanism to dynamically
// reallocate task space on demand.
/* .default_stack_size = */ URBI_KERNEL_STACK_SIZE * 1024,
/* .minimum_stack_size = */ URBI_KERNEL_STACK_SIZE * 1024 / 8
};
|
Fix warning on Ubuntu Bionic. | #include "config.h"
#include <stdint.h>
#include <stdlib.h>
#include <sys/types.h>
#ifdef RBX_WINDOWS
#include <winsock2.h>
#else
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <netdb.h>
#endif
#include <sys/stat.h>
#include <errno.h>
#include <time.h>
#include <math.h>
#include "windows_compat.h"
#include "ffi_util.hpp"
#ifdef __APPLE__
#include <crt_externs.h>
#endif
extern "C" {
extern char** environ;
int ffi_errno() { return errno; }
char** ffi_environ() {
#ifdef __APPLE__
return *_NSGetEnviron();
#else
return environ;
#endif
}
void ffi_set_errno(int n) {
errno = n;
}
#ifndef major
#define major(x) x
#endif
#ifndef minor
#define minor(x) 0
#endif
long ffi_major(dev_t n) {
return major(n);
}
long ffi_minor(dev_t n) {
return minor(n);
}
}
| #include "config.h"
#include <stdint.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/sysmacros.h>
#ifdef RBX_WINDOWS
#include <winsock2.h>
#else
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <netdb.h>
#endif
#include <sys/stat.h>
#include <errno.h>
#include <time.h>
#include <math.h>
#include "windows_compat.h"
#include "ffi_util.hpp"
#ifdef __APPLE__
#include <crt_externs.h>
#endif
extern "C" {
extern char** environ;
int ffi_errno() { return errno; }
char** ffi_environ() {
#ifdef __APPLE__
return *_NSGetEnviron();
#else
return environ;
#endif
}
void ffi_set_errno(int n) {
errno = n;
}
#ifndef major
#define major(x) x
#endif
#ifndef minor
#define minor(x) 0
#endif
long ffi_major(dev_t n) {
return major(n);
}
long ffi_minor(dev_t n) {
return minor(n);
}
}
|
Remove console-in ignore in main source. | // Native C++ Libraries
#include <iostream>
#include <string>
// C++ Interpreter Libraries
#include <Console.h>
using namespace std;
int main()
{
RESTART:
string input = "";
getline(cin, input);
cin.ignore();
goto RESTART;
}
| // Native C++ Libraries
#include <iostream>
#include <string>
// C++ Interpreter Libraries
#include <Console.h>
using namespace std;
int main()
{
RESTART:
string input = "";
getline(cin, input);
goto RESTART;
}
|
Fix high dpi icon sizes | #include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QtQml>
#include "applications.h"
#include "iconprovider.h"
#include "process.h"
/**
* @todo: Config file in ~/.config/qmldmenu/
* @todo: SHIFT(ENTER) for sudo
* @todo: TAB For command (term /{usr}/bin/) / app (.desktop) mode
*/
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QLoggingCategory::setFilterRules("qt.svg.warning=false"); // Hide buggy SVG icon warnings
QQmlApplicationEngine engine;
qmlRegisterType<Process>("Process", 1, 0, "Process");
qmlRegisterType<Applications>("Applications", 1, 0, "Applications");
engine.addImageProvider(QLatin1String("appicon"), new IconProvider);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
| #include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QtQml>
#include "applications.h"
#include "iconprovider.h"
#include "process.h"
/**
* @todo: Config file in ~/.config/qmldmenu/
* @todo: SHIFT(ENTER) for sudo
* @todo: TAB For command (term /{usr}/bin/) / app (.desktop) mode
*/
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QLoggingCategory::setFilterRules("qt.svg.warning=false"); // Hide buggy SVG icon warnings
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QQmlApplicationEngine engine;
qmlRegisterType<Process>("Process", 1, 0, "Process");
qmlRegisterType<Applications>("Applications", 1, 0, "Applications");
engine.addImageProvider(QLatin1String("appicon"), new IconProvider);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
|
Fix typo in previous patch. | /*
* Copyright (C) 2008-2010, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
// This file *must* remain with absolutely no run-time dependency.
#include <urbi/urbi-root.hh>
#include <sdk/config.hh>
int main(int argc, char* argv[])
{
UrbiRoot urbi_root(argv[0],
#ifdef STATIC_BUILD
true
#else
false
#endif
);
return urbi_root.urbi_launch(argc, argv);
}
| /*
* Copyright (C) 2008-2010, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
// This file *must* remain with absolutely no run-time dependency.
#include <urbi/urbi-root.hh>
#include <sdk/config.h>
int main(int argc, char* argv[])
{
UrbiRoot urbi_root(argv[0],
#ifdef STATIC_BUILD
true
#else
false
#endif
);
return urbi_root.urbi_launch(argc, argv);
}
|
Test array with 2 elements | /*
* Arduino JSON library
* Benoit Blanchon 2014 - MIT License
*/
#include "CppUnitTest.h"
#include "IndentedPrintDecorator.h"
#include "StringBuilder.h"
using namespace ArduinoJson::Internals;
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace JsonGeneratorTests
{
TEST_CLASS(Indented_Array_Tests)
{
char buffer[1024];
size_t returnValue;
public:
TEST_METHOD(EmptyArray)
{
whenInputIs("[]");
outputMustBe("[]");
}
TEST_METHOD(OneElement)
{
whenInputIs("[1]");
outputMustBe(
"[\n"
" 1\n"
"]");
}
private:
void whenInputIs(const char input[])
{
StringBuilder sb(buffer, sizeof(buffer));
IndentedPrintDecorator decorator(sb);
returnValue = decorator.print(input);
}
void outputMustBe(const char* expected)
{
Assert::AreEqual(expected, buffer);
Assert::AreEqual(strlen(expected), returnValue);
}
};
} | /*
* Arduino JSON library
* Benoit Blanchon 2014 - MIT License
*/
#include "CppUnitTest.h"
#include "IndentedPrintDecorator.h"
#include "StringBuilder.h"
using namespace ArduinoJson::Internals;
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace JsonGeneratorTests
{
TEST_CLASS(Indented_Array_Tests)
{
char buffer[1024];
size_t returnValue;
public:
TEST_METHOD(EmptyArray)
{
whenInputIs("[]");
outputMustBe("[]");
}
TEST_METHOD(OneElement)
{
whenInputIs("[1]");
outputMustBe(
"[\n"
" 1\n"
"]");
}
TEST_METHOD(TwoElements)
{
whenInputIs("[1,2]");
outputMustBe(
"[\n"
" 1,\n"
" 2\n"
"]");
}
private:
void whenInputIs(const char input[])
{
StringBuilder sb(buffer, sizeof(buffer));
IndentedPrintDecorator decorator(sb);
returnValue = decorator.print(input);
}
void outputMustBe(const char* expected)
{
Assert::AreEqual(expected, buffer);
Assert::AreEqual(strlen(expected), returnValue);
}
};
} |
Use 50 ms for key typing time in the card reader test instead of something based on the card reader limit constant, in order to detect that the card reader constant is mis-set. | #include "cardreader-t.h"
#include <QSignalSpy>
const QString TEST_CARDNUMBER = "1234_testcard";
void CardReaderTest::initTestCase()
{
widget.installEventFilter(&cardReader);
}
void CardReaderTest::simulateRFIDReader()
{
QSignalSpy spy(&cardReader, SIGNAL(newCardNumber(QString)));
QVERIFY(spy.isValid());
QTest::keyClicks(&widget, TEST_CARDNUMBER);
QTest::keyClick(&widget, Qt::Key_Return);
QCOMPARE(spy.count(), 1);
QList<QVariant> arguments = spy.takeFirst();
QCOMPARE(arguments.at(0).toString(), TEST_CARDNUMBER);
}
void CardReaderTest::simulateKeyboardInput()
{
QSignalSpy spy(&cardReader, SIGNAL(newCardNumber(QString)));
QVERIFY(spy.isValid());
int keyTypingTime = CARDREADER_TIME_LIMIT_MS*1.0/((TEST_CARDNUMBER.size())*1.0);
QTest::keyClicks(&widget, TEST_CARDNUMBER, Qt::NoModifier, keyTypingTime);
QTest::keyClick(&widget, Qt::Key_Return);
QCOMPARE(spy.count(), 0);
}
void CardReaderTest::simulateSecondRFIDReader()
{
simulateRFIDReader();
}
QTEST_MAIN(CardReaderTest)
| #include "cardreader-t.h"
#include <QSignalSpy>
const QString TEST_CARDNUMBER = "1234_testcard";
void CardReaderTest::initTestCase()
{
widget.installEventFilter(&cardReader);
}
void CardReaderTest::simulateRFIDReader()
{
QSignalSpy spy(&cardReader, SIGNAL(newCardNumber(QString)));
QVERIFY(spy.isValid());
QTest::keyClicks(&widget, TEST_CARDNUMBER);
QTest::keyClick(&widget, Qt::Key_Return);
QCOMPARE(spy.count(), 1);
QList<QVariant> arguments = spy.takeFirst();
QCOMPARE(arguments.at(0).toString(), TEST_CARDNUMBER);
}
void CardReaderTest::simulateKeyboardInput()
{
QSignalSpy spy(&cardReader, SIGNAL(newCardNumber(QString)));
QVERIFY(spy.isValid());
int keyTypingTime = 50;
QTest::keyClicks(&widget, TEST_CARDNUMBER, Qt::NoModifier, keyTypingTime);
QTest::keyClick(&widget, Qt::Key_Return);
QCOMPARE(spy.count(), 0);
}
void CardReaderTest::simulateSecondRFIDReader()
{
simulateRFIDReader();
}
QTEST_MAIN(CardReaderTest)
|
Rewrite return multiple values sample | // Return multiple values
#include <tuple>
#include <string>
std::tuple<int, bool, std::string> foo()
{
return {128, true, "hello"};
}
int main()
{
int obj1;
bool obj2;
std::string obj3;
std::tie(obj1, obj2, obj3) = foo();
}
// Return multiple values of different types from a function.
//
// The `foo` function on [6-9] returns a
// [`std::tuple`](cpp/utility/tuple) representing multiple values
// of different types.
//
// On [17], the [`std::tie`](cpp/utility/tuple/tie) helper function
// ensures that each of the return values is assigned to each of the
// given objects. This approach only works if it is reasonable to
// declare the objects earlier.
//
// When we cannot use `std::tie`, we can simply
// store the resulting `std::tuple` object and use
// [`std::get`](cpp/utility/tuple/get) to get the values from it.
| // Return multiple values
#include <tuple>
std::tuple<int, bool, float> foo()
{
return {128, true, 1.5f};
}
int main()
{
int obj1;
bool obj2;
float obj3;
std::tie(obj1, obj2, obj3) = foo();
}
// Return multiple values of different types from a function.
//
// The `foo` function on [5-8] returns a
// [`std::tuple`](cpp/utility/tuple) representing multiple values
// of different types.
//
// On [16], we call this function and use [`std::tie`](cpp/utility/tuple/tie)
// to assign the return values to each of the given objects.
// If we cannot create the objects prior to this call, we can
// alternatively store the resulting `std::tuple` object and use
// [`std::get`](cpp/utility/tuple/get) to get the values from it.
//
// If the values are closely and logically related, consider composing
// them into a `struct` or `class`.
|
Use ASSERT_EQ rather than ASSERT_TRUE for better unit test failures. | //===- llvm/unittest/DebugInfo/DWARFFormValueTest.cpp ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "../lib/CodeGen/AsmPrinter/DIE.h"
#include "../lib/CodeGen/AsmPrinter/DIEHash.h"
#include "llvm/Support/Dwarf.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Format.h"
#include "gtest/gtest.h"
namespace {
using namespace llvm;
TEST(DIEHashData1Test, DIEHash) {
DIEHash Hash;
DIE Die(dwarf::DW_TAG_base_type);
DIEInteger Size(4);
Die.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &Size);
uint64_t MD5Res = Hash.computeTypeSignature(&Die);
ASSERT_TRUE(MD5Res == 0x540e9ff30ade3e4aULL);
}
}
| //===- llvm/unittest/DebugInfo/DWARFFormValueTest.cpp ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "../lib/CodeGen/AsmPrinter/DIE.h"
#include "../lib/CodeGen/AsmPrinter/DIEHash.h"
#include "llvm/Support/Dwarf.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Format.h"
#include "gtest/gtest.h"
using namespace llvm;
namespace {
TEST(DIEHashData1Test, DIEHash) {
DIEHash Hash;
DIE Die(dwarf::DW_TAG_base_type);
DIEInteger Size(4);
Die.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &Size);
uint64_t MD5Res = Hash.computeTypeSignature(&Die);
ASSERT_EQ(MD5Res, 0x540e9ff30ade3e4aULL);
}
}
|
Disable the default plugin for aura | // 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/common/default_plugin.h"
#include "chrome/default_plugin/plugin_main.h"
#include "webkit/plugins/npapi/plugin_list.h"
namespace chrome {
void RegisterInternalDefaultPlugin() {
#if defined(OS_WIN)
// TODO(bauerb): On Windows the default plug-in can download and install
// missing plug-ins, which we don't support in the browser yet, so keep
// using the default plug-in on Windows until we do.
const webkit::npapi::PluginEntryPoints entry_points = {
#if !defined(OS_POSIX) || defined(OS_MACOSX)
default_plugin::NP_GetEntryPoints,
#endif
default_plugin::NP_Initialize,
default_plugin::NP_Shutdown
};
webkit::npapi::PluginList::Singleton()->RegisterInternalPlugin(
FilePath(webkit::npapi::kDefaultPluginLibraryName),
"Default Plug-in",
"Provides functionality for installing third-party plug-ins",
"*",
entry_points);
#endif // defined OS(WIN)
}
} // namespace chrome
| // 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/common/default_plugin.h"
#include "chrome/default_plugin/plugin_main.h"
#include "webkit/plugins/npapi/plugin_list.h"
namespace chrome {
void RegisterInternalDefaultPlugin() {
#if defined(OS_WIN) && !defined(USE_AURA)
// TODO(bauerb): On Windows the default plug-in can download and install
// missing plug-ins, which we don't support in the browser yet, so keep
// using the default plug-in on Windows until we do.
// Aura isn't going to support NPAPI plugins.
const webkit::npapi::PluginEntryPoints entry_points = {
#if !defined(OS_POSIX) || defined(OS_MACOSX)
default_plugin::NP_GetEntryPoints,
#endif
default_plugin::NP_Initialize,
default_plugin::NP_Shutdown
};
webkit::npapi::PluginList::Singleton()->RegisterInternalPlugin(
FilePath(webkit::npapi::kDefaultPluginLibraryName),
"Default Plug-in",
"Provides functionality for installing third-party plug-ins",
"*",
entry_points);
#endif
}
} // namespace chrome
|
Make sure to not compare signed with unsigned. | // Copyright 2017-2020 The Verible 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 "common/strings/display_utils.h"
#include <iostream>
namespace verible {
static constexpr absl::string_view kEllipses = "...";
std::ostream& operator<<(std::ostream& stream, const AutoTruncate& trunc) {
const auto text = trunc.text;
const auto length = text.length();
if (length <= trunc.max_chars) return stream << text;
const auto context_length = trunc.max_chars - kEllipses.length();
const auto tail_length = context_length / 2;
const auto head_length = context_length - tail_length;
const auto tail_start = length - tail_length;
return stream << text.substr(0, head_length) << kEllipses
<< text.substr(tail_start, tail_length);
}
} // namespace verible
| // Copyright 2017-2020 The Verible 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 "common/strings/display_utils.h"
#include <iostream>
namespace verible {
static constexpr absl::string_view kEllipses = "...";
std::ostream& operator<<(std::ostream& stream, const AutoTruncate& trunc) {
const auto text = trunc.text;
const int length = text.length();
if (length <= trunc.max_chars) return stream << text;
const auto context_length = trunc.max_chars - kEllipses.length();
const auto tail_length = context_length / 2;
const auto head_length = context_length - tail_length;
const auto tail_start = length - tail_length;
return stream << text.substr(0, head_length) << kEllipses
<< text.substr(tail_start, tail_length);
}
} // namespace verible
|
Fix compilation error in the focus manager by returning NULL from unimplemented function. | // Copyright (c) 2006-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 "views/focus/focus_manager.h"
#include "base/logging.h"
namespace views {
void FocusManager::ClearNativeFocus() {
NOTIMPLEMENTED();
}
void FocusManager::FocusNativeView(gfx::NativeView native_view) {
NOTIMPLEMENTED();
}
// static
FocusManager* FocusManager::GetFocusManagerForNativeView(
gfx::NativeView native_view) {
NOTIMPLEMENTED();
}
} // namespace views
| // Copyright (c) 2006-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 "views/focus/focus_manager.h"
#include "base/logging.h"
namespace views {
void FocusManager::ClearNativeFocus() {
NOTIMPLEMENTED();
}
void FocusManager::FocusNativeView(gfx::NativeView native_view) {
NOTIMPLEMENTED();
}
// static
FocusManager* FocusManager::GetFocusManagerForNativeView(
gfx::NativeView native_view) {
NOTIMPLEMENTED();
return NULL;
}
} // namespace views
|
Remove the execution of InitRunfilesDir from InitXls. The InitXLS assumes that an executable has Runfiles and is a Runfile marker. Moreover, as XLS moves to a bazel toolchain implementation, toolchain executables are not a runfile or a runfile marker. | // Copyright 2020 The XLS 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 "xls/common/init_xls.h"
#include "absl/flags/parse.h"
#include "xls/common/file/get_runfile_path.h"
#include "xls/common/logging/logging.h"
namespace xls {
std::vector<absl::string_view> InitXls(absl::string_view usage, int argc,
char* argv[]) {
// Copy the argv array to ensure this method doesn't clobber argv.
std::vector<char*> arguments(argv, argv + argc);
std::vector<char*> remaining = absl::ParseCommandLine(argc, argv);
XLS_CHECK_GE(argc, 1);
XLS_CHECK_OK(InitRunfilesDir(argv[0]));
return std::vector<absl::string_view>(remaining.begin() + 1, remaining.end());
}
} // namespace xls
| // Copyright 2020 The XLS 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 "xls/common/init_xls.h"
#include "absl/flags/parse.h"
#include "xls/common/file/get_runfile_path.h"
#include "xls/common/logging/logging.h"
namespace xls {
std::vector<absl::string_view> InitXls(absl::string_view usage, int argc,
char* argv[]) {
// Copy the argv array to ensure this method doesn't clobber argv.
std::vector<char*> arguments(argv, argv + argc);
std::vector<char*> remaining = absl::ParseCommandLine(argc, argv);
XLS_CHECK_GE(argc, 1);
return std::vector<absl::string_view>(remaining.begin() + 1, remaining.end());
}
} // namespace xls
|
Adjust compiler options used to build Mac executables. | #########################################################
# Local Compiler Rules #
#########################################################
#--objectrule--# $(CXX) $(CFLAGS) $(CDEFS) $(CINCS) -o $@ -c
#--objectsuffix--# $B
#--targetsuffix--# $B
#--tarulesuffix--# $B
#--buildtargets--# targets
.SUFFIXES :
B =
%-dbg : B = -dbg
D =
%-dbg : D = /dbg
CDEFS = -DVisionBuild
CINCS =
CBASE = -fexceptions -frtti -Wno-trigraphs -Wno-undefined-bool-conversion
CDBG = -g
CREL = -O2
CVER = ${CREL}
CFLAGS = ${CVER} ${CBASE}
LINKER = VLINK-CC
LBASE =
LIBASE = ${LOCALLIBS} -lpthread
LIBS = ${LBASE} -c -L../lib$D ${LIBASE}
release : targets
debug : targets-dbg
targets-dbg :
@$(MAKE) B=-dbg D=/dbg CVER=${CDBG} targets
clean-dbg :
@$(MAKE) B=-dbg D=/dbg clean
clean-all : clean clean-dbg
| #########################################################
# Local Compiler Rules #
#########################################################
#--objectrule--# $(CXX) $(CFLAGS) $(CDEFS) $(CINCS) -o $@ -c
#--objectsuffix--# $B
#--targetsuffix--# $B
#--tarulesuffix--# $B
#--buildtargets--# targets
.SUFFIXES :
B =
%-dbg : B = -dbg
D =
%-dbg : D = /dbg
CDEFS = -DVisionBuild
CINCS =
CBASE = -fexceptions -frtti -Wno-trigraphs -Wno-undefined-bool-conversion -Wno-format -Wno-logical-op-parentheses -Wno-switch -Wno-shift-op-parentheses -Wno-shift-negative-value -Wno-parentheses
CDBG = -g
CREL = -O2
CVER = ${CREL}
CFLAGS = ${CVER} ${CBASE}
LINKER = VLINK-CC
LBASE =
LIBASE = ${LOCALLIBS} -lpthread
LIBS = ${LBASE} -L../lib$D ${LIBASE}
release : targets
debug : targets-dbg
targets-dbg :
@$(MAKE) B=-dbg D=/dbg CVER=${CDBG} targets
clean-dbg :
@$(MAKE) B=-dbg D=/dbg clean
clean-all : clean clean-dbg
|
Add some simple tests to check whether the operation-queue works | #include "AppViewController.h"
namespace mural
{
AppViewController::~AppViewController()
{
delete this->view;
}
void AppViewController::initWithScriptAtPath(const char *path, int width, int height, const char *title)
{
this->view = new JavaScriptView(width, height, title);
this->view->loadScriptAtPath(path);
this->view->startRunning();
}
}
| #include "AppViewController.h"
// #include <thread>
namespace mural
{
AppViewController::~AppViewController()
{
delete this->view;
}
void AppViewController::initWithScriptAtPath(const char *path, int width, int height, const char *title)
{
this->view = new JavaScriptView(width, height, title);
this->view->loadScriptAtPath(path);
// Test MuOperationQueue
// this->view->backgroundQueue.addOperation([] {
// printf("[Test]: Operation 'A' starts running, this should be long (1000ms)\n");
// std::this_thread::sleep_for(std::chrono::milliseconds(1000));
// printf("[Test]: Operation 'A' finished\n");
// });
// this->view->backgroundQueue.addOperation([] {
// printf("[Test]: Operation 'B' just fired\n");
// });
this->view->startRunning();
}
}
|
Check IR in this test. | // REQUIRES: x86-registered-target,x86-64-registered-target
// RUN: %clang_cc1 -triple x86_64-apple-darwin -std=c++11 -S %s -o %t-64.s
// RUN: FileCheck -check-prefix CHECK-LP64 --input-file=%t-64.s %s
// RUN: %clang_cc1 -triple i386-apple-darwin -std=c++11 -S %s -o %t-32.s
// RUN: FileCheck -check-prefix CHECK-LP32 --input-file=%t-32.s %s
struct A {
A(int);
};
struct B {
B(A);
};
int main () {
(B)10;
B(10);
static_cast<B>(10);
}
// CHECK-LP64: callq __ZN1AC1Ei
// CHECK-LP64: callq __ZN1BC1E1A
// CHECK-LP64: callq __ZN1AC1Ei
// CHECK-LP64: callq __ZN1BC1E1A
// CHECK-LP64: callq __ZN1AC1Ei
// CHECK-LP64: callq __ZN1BC1E1A
// CHECK-LP32: calll L__ZN1AC1Ei
// CHECK-LP32: calll L__ZN1BC1E1A
// CHECK-LP32: calll L__ZN1AC1Ei
// CHECK-LP32: calll L__ZN1BC1E1A
// CHECK-LP32: calll L__ZN1AC1Ei
// CHECK-LP32: calll L__ZN1BC1E1A
| // RUN: %clang_cc1 -triple x86_64-apple-darwin -std=c++11 -emit-llvm %s -o - | \
// RUN: FileCheck %s
// RUN: %clang_cc1 -triple i386-apple-darwin -std=c++11 -emit-llvm %s -o - | \
// RUN: FileCheck %s
struct A {
A(int);
};
struct B {
B(A);
};
int main () {
(B)10;
B(10);
static_cast<B>(10);
}
// CHECK: call void @_ZN1AC1Ei
// CHECK: call void @_ZN1BC1E1A
// CHECK: call void @_ZN1AC1Ei
// CHECK: call void @_ZN1BC1E1A
// CHECK: call void @_ZN1AC1Ei
// CHECK: call void @_ZN1BC1E1A
|
Fix compiler warning in smoketest | /*
* Copyright (C) 2016 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Game.h"
#include "Shell.h"
#if (defined(_MSC_VER) && _MSC_VER < 1900 /*vs2015*/) || \
defined MINGW_HAS_SECURE_API
#include <basetsd.h>
#define snprintf sprintf_s
#endif
void Game::print_stats() {
// Output frame count and measured elapsed time
auto now = std::chrono::system_clock::now();
auto elapsed = now - start_time;
auto elapsed_millis =
std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).count();
char msg[256];
snprintf(msg, 255, "frames:%d, elapsedms:%ld", frame_count, elapsed_millis);
shell_->log(Shell::LogPriority::LOG_INFO, msg);
}
void Game::quit() {
print_stats();
shell_->quit();
}
| /*
* Copyright (C) 2016 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <sstream>
#include "Game.h"
#include "Shell.h"
void Game::print_stats() {
// Output frame count and measured elapsed time
auto now = std::chrono::system_clock::now();
auto elapsed = now - start_time;
auto elapsed_millis =
std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).count();
std::stringstream ss;
ss << "frames:" << frame_count << ", elapsedms:" << elapsed_millis;
shell_->log(Shell::LogPriority::LOG_INFO, ss.str().c_str());
}
void Game::quit() {
print_stats();
shell_->quit();
}
|
Adjust string directly instead of using index of the array | #include <stdio.h>
#include <string.h>
#include <stdbool.h>
#define MAX_INPUT_SIZE 100
bool is_palindrome(const char *string, const int begin = 0, int end = -1)
{
/* initialise parameter */
if(end == -1) end = strlen(string) - 1;
/* base case */
if(string[begin] != string[end]) return false;
if(begin >= end) return true;
/* recursive case */
return is_palindrome(string, begin + 1, end - 1);
}
int main(void)
{
printf("palindrome checker\n");
char word[MAX_INPUT_SIZE];
printf("Enter word= "); scanf("%s", word);
printf("%s is %spalindrome.\n", word, is_palindrome(word) ? "" : "not " );
return 0;
}
| #include <stdio.h>
#include <string.h>
#include <stdbool.h>
#define MAX_INPUT_SIZE 100
bool is_palindrome(const char *word)
{
int length = strlen(word);
char string[length]; /* Should not modify the value of ptr arg. */
strcpy(string, word);
/* base case */
if(length <= 1) return true;
if(string[0] != string[length - 1]) return false;
/* recursive case */
string[length - 1] = '\0';
return is_palindrome(string + 1);
}
int main(void)
{
printf("palindrome checker\n");
char word[MAX_INPUT_SIZE];
printf("Enter word= "); scanf("%s", word);
printf("%s is %spalindrome.\n", word, is_palindrome(word) ? "" : "not " );
return 0;
}
|
Support for putting entries onto queue | #include "host-interface.hpp"
namespace phosphor
{
namespace host
{
void Host::execute(Command command)
{
// Future commits to build on
return;
}
} // namespace host
} // namepsace phosphor
| #include <queue>
#include <phosphor-logging/log.hpp>
#include "host-interface.hpp"
namespace phosphor
{
namespace host
{
using namespace phosphor::logging;
// When you see base:: you know we're referencing our base class
namespace base = sdbusplus::xyz::openbmc_project::Control::server;
std::queue<base::Host::Command> workQueue{};
void Host::execute(base::Host::Command command)
{
log<level::INFO>("Pushing cmd on to queue",
entry("CONTROL_HOST_CMD=%s",
convertForMessage(command)));
workQueue.push(command);
return;
}
} // namespace host
} // namepsace phosphor
|
Fix a test to test what the name suggest. | // RUN: %clang_cc1 -fsyntax-only -Wno-dangling -Wreturn-stack-address -verify %s
struct [[gsl::Owner(int)]] MyIntOwner {
MyIntOwner();
int &operator*();
};
struct [[gsl::Pointer(int)]] MyIntPointer {
MyIntPointer(int *p = nullptr);
MyIntPointer(const MyIntOwner &);
int &operator*();
MyIntOwner toOwner();
};
int &f() {
int i;
return i; // expected-warning {{reference to stack memory associated with local variable 'i' returned}}
}
MyIntPointer g() {
MyIntOwner o;
return o; // No warning, it is disabled.
}
| // RUN: %clang_cc1 -fsyntax-only -Wno-dangling-gsl -Wreturn-stack-address -verify %s
struct [[gsl::Owner(int)]] MyIntOwner {
MyIntOwner();
int &operator*();
};
struct [[gsl::Pointer(int)]] MyIntPointer {
MyIntPointer(int *p = nullptr);
MyIntPointer(const MyIntOwner &);
int &operator*();
MyIntOwner toOwner();
};
int &f() {
int i;
return i; // expected-warning {{reference to stack memory associated with local variable 'i' returned}}
}
MyIntPointer g() {
MyIntOwner o;
return o; // No warning, it is disabled.
}
|
Add missing include and change existing include | /**
** \file libport/perror.cc
** \brief perror: implements file libport/perror.hh
*/
#include <stdio.h>
#include "libport/cstring"
namespace libport
{
void
perror (const char* s)
{
#ifndef WIN32
::perror(s);
#else
int errnum;
const char* errstring;
const char* colon;
errnum = WSAGetLastError();
errstring = strerror(errnum);
if (s == NULL || *s == '\0')
s = colon = "";
else
colon = ": ";
std::cerr << s << colon << errstring << std::endl;
#endif
}
}
| /**
** \file libport/perror.cc
** \brief perror: implements file libport/perror.hh
*/
#include <cstdio>
#include <iostream>
#include "libport/cstring"
namespace libport
{
void
perror (const char* s)
{
#ifndef WIN32
::perror(s);
#else
int errnum;
const char* errstring;
const char* colon;
errnum = WSAGetLastError();
errstring = strerror(errnum);
if (s == NULL || *s == '\0')
s = colon = "";
else
colon = ": ";
std::cerr << s << colon << errstring << std::endl;
#endif
}
}
|
Fix failure of the Timer unit test. | #include "Timer.h"
#define BOOST_TEST_MODULE TimerTest
#include <boost/test/unit_test.hpp>
#include <string>
#include <iostream>
BOOST_AUTO_TEST_CASE(timer_basic_test) {
Timer timer;
timer.start();
BOOST_REQUIRE(timer.is_running());
BOOST_REQUIRE(timer.get_elapsed_cpu_time() > 0.0);
BOOST_REQUIRE(timer.get_elapsed_cpu_time_microseconds() > 0);
BOOST_REQUIRE(timer.get_elapsed_wall_time() > 0.0);
BOOST_REQUIRE(timer.get_elapsed_wall_time_microseconds() > 0);
timer.restart();
BOOST_REQUIRE(timer.is_running());
BOOST_REQUIRE(timer.get_elapsed_cpu_time() > 0.0);
BOOST_REQUIRE(timer.get_elapsed_cpu_time_microseconds() > 0);
BOOST_REQUIRE(timer.get_elapsed_wall_time() > 0.0);
BOOST_REQUIRE(timer.get_elapsed_wall_time_microseconds() > 0);
const std::string s = timer.ToString();
BOOST_REQUIRE(!s.empty());
}
| #include "Timer.h"
#define BOOST_TEST_MODULE TimerTest
#include <boost/test/unit_test.hpp>
#include <string>
#include <iostream>
#include <unistd.h>
BOOST_AUTO_TEST_CASE(timer_basic_test) {
Timer timer;
const int sleep_time_microsec = 40; // ad-hoc microseconds to pass unit tests.
timer.start();
BOOST_REQUIRE(timer.is_running());
BOOST_REQUIRE(usleep(sleep_time_microsec) == 0);
BOOST_CHECK(timer.get_elapsed_cpu_time() > 0.0);
BOOST_CHECK(timer.get_elapsed_cpu_time_microseconds() > 0);
BOOST_CHECK(timer.get_elapsed_wall_time() > 0.0);
BOOST_CHECK(timer.get_elapsed_wall_time_microseconds() > 0);
timer.restart();
BOOST_REQUIRE(timer.is_running());
BOOST_REQUIRE(usleep(sleep_time_microsec) == 0);
BOOST_CHECK(timer.get_elapsed_cpu_time() > 0.0);
BOOST_CHECK(timer.get_elapsed_cpu_time_microseconds() > 0);
BOOST_CHECK(timer.get_elapsed_wall_time() > 0.0);
BOOST_CHECK(timer.get_elapsed_wall_time_microseconds() > 0);
const std::string s = timer.ToString();
BOOST_CHECK(!s.empty());
}
|
Put the using namespace std in the cpp files | #include <iostream>
#include "../src/tisys.hpp"
int main(int argc, char** argv){
cout << "Example" <<endl;
Filesystem fs;
if ( argc == 1 )
fs.listdir(".");
else
fs.listdir( argv[1] );
cout << fs;
return 0;
}
| #include <iostream>
#include "../src/tisys.hpp"
using namespace std;
int main(int argc, char** argv){
cout << "Example" <<endl;
Filesystem fs;
if ( argc == 1 )
fs.listdir(".");
else
fs.listdir( argv[1] );
cout << fs;
return 0;
}
|
Fix compiling of DTSC version branch. | /// \file Connector_RAW/main.cpp
/// Contains the main code for the RAW connector.
#include <iostream>
#include "../util/socket.h"
/// Contains the main code for the RAW connector.
/// Expects a single commandline argument telling it which stream to connect to,
/// then outputs the raw stream to stdout.
int main(int argc, char ** argv) {
if (argc < 2){
std::cout << "Usage: " << argv[0] << " stream_name" << std::endl;
return 1;
}
std::string input = "/tmp/shared_socket_";
input += argv[1];
//connect to the proper stream
Socket::Connection S(input);
if (!S.connected()){
std::cout << "Could not open stream " << argv[1] << std::endl;
return 1;
}
//transport ~50kb at a time
//this is a nice tradeoff between CPU usage and speed
char buffer[50000];
while(std::cout.good() && S.read(buffer,50000)){std::cout.write(buffer,50000);}
S.close();
return 0;
}
| /// \file Connector_RAW/main.cpp
/// Contains the main code for the RAW connector.
#include <iostream>
#include "../util/socket.h"
/// Contains the main code for the RAW connector.
/// Expects a single commandline argument telling it which stream to connect to,
/// then outputs the raw stream to stdout.
int main(int argc, char ** argv) {
if (argc < 2){
std::cout << "Usage: " << argv[0] << " stream_name" << std::endl;
return 1;
}
std::string input = "/tmp/shared_socket_";
input += argv[1];
//connect to the proper stream
Socket::Connection S(input);
if (!S.connected()){
std::cout << "Could not open stream " << argv[1] << std::endl;
return 1;
}
//transport ~50kb at a time
//this is a nice tradeoff between CPU usage and speed
const char buffer[50000] = {0};
while(std::cout.good() && S.read(buffer,50000)){std::cout.write(buffer,50000);}
S.close();
return 0;
}
|
Use Qt based file system in App. |
// Includes.
#include "UI/mainwindow.h"
#include "App/App.h"
#include "App/Factories/AdditionNFDelegate.h"
#include "App/Factories/ConstantNFDelegate.h"
#include "App/Factories/PrinterNFDelegate.h"
#include "App/Factories/TextFileNFDelegate.h"
// Qt.
#include <QApplication>
QString titleString()
{
QString name = QString::fromStdString(App::appName());
QString version = QString::fromStdString(App::appVersion());
return QString("%1 - v%2").arg(name).arg(version);
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
App app;
app.addNodeFactory(new AdditionNFDelegate);
app.addNodeFactory(new ConstantNFDelegate);
app.addNodeFactory(new PrinterNFDelegate);
app.addNodeFactory(new TextFileNFDelegate);
MainWindow w(&app);
w.setWindowTitle(titleString());
w.setMinimumSize(800, 600);
w.show();
app.setUI(&w);
app.setDelegate(&w);
return a.exec();
}
|
// Includes.
#include "UI/mainwindow.h"
#include "App/App.h"
#include "App/Factories/AdditionNFDelegate.h"
#include "App/Factories/ConstantNFDelegate.h"
#include "App/Factories/PrinterNFDelegate.h"
#include "App/Factories/TextFileNFDelegate.h"
#include "System/QtBasedFileSystem.h"
// Qt.
#include <QApplication>
QString titleString()
{
QString name = QString::fromStdString(App::appName());
QString version = QString::fromStdString(App::appVersion());
return QString("%1 - v%2").arg(name).arg(version);
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QtBasedFileSystem file_system;
App app(&file_system);
app.addNodeFactory(new AdditionNFDelegate);
app.addNodeFactory(new ConstantNFDelegate);
app.addNodeFactory(new PrinterNFDelegate);
app.addNodeFactory(new TextFileNFDelegate);
MainWindow w(&app);
w.setWindowTitle(titleString());
w.setMinimumSize(800, 600);
w.show();
app.setUI(&w);
app.setDelegate(&w);
return a.exec();
}
|
Set numeric locale to C for proper tesseract-orc-* packages work on linux. | #include <QApplication>
#include <QTranslator>
#include <qtsingleapplication.h>
#include <Manager.h>
#include <Settings.h>
int main (int argc, char *argv[]) {
QtSingleApplication a (argc, argv);
if (a.sendMessage (QString ())) {
return 0;
}
a.setQuitOnLastWindowClosed (false);
a.setApplicationName (settings_values::appName);
a.setOrganizationName (settings_values::companyName);
QTranslator translator;
// Set default to english.
if (translator.load (QLocale::system (), "translation", "_", ":/translations") ||
translator.load (":/translations/translation_en")) {
a.installTranslator (&translator);
}
Manager manager;
return a.exec ();
}
| #ifdef Q_OS_LINUX
# include <locale.h>
#endif
#include <QApplication>
#include <QTranslator>
#include <qtsingleapplication.h>
#include <Manager.h>
#include <Settings.h>
int main (int argc, char *argv[]) {
QtSingleApplication a (argc, argv);
if (a.sendMessage (QString ())) {
return 0;
}
#ifdef Q_OS_LINUX
setlocale (LC_NUMERIC, "C");
#endif
a.setQuitOnLastWindowClosed (false);
a.setApplicationName (settings_values::appName);
a.setOrganizationName (settings_values::companyName);
QTranslator translator;
// Set default to english.
if (translator.load (QLocale::system (), "translation", "_", ":/translations") ||
translator.load (":/translations/translation_en")) {
a.installTranslator (&translator);
}
Manager manager;
return a.exec ();
}
|
Remove PrinterNFDelegate, has become redundant due to logger Lua node. |
// Includes.
#include "UI/mainwindow.h"
#include "App/App.h"
#include "App/Factories/PrinterNFDelegate.h"
#include "App/Factories/TextFileNFDelegate.h"
#include "System/QtBasedFileSystem.h"
// Qt.
#include <QApplication>
QString titleString()
{
QString name = QString::fromStdString(App::appName());
QString version = QString::fromStdString(App::appVersion());
return QString("%1 - v%2").arg(name).arg(version);
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QtBasedFileSystem file_system;
App app(&file_system);
app.addNodeFactory(new PrinterNFDelegate);
app.addNodeFactory(new TextFileNFDelegate);
app.loadScriptNodes("Nodin/NodeScripts/Lua");
MainWindow w(&app);
w.setWindowTitle(titleString());
w.setMinimumSize(800, 600);
w.show();
app.setUI(&w);
app.setDelegate(&w);
return a.exec();
}
|
// Includes.
#include "UI/mainwindow.h"
#include "App/App.h"
#include "App/Factories/TextFileNFDelegate.h"
#include "System/QtBasedFileSystem.h"
// Qt.
#include <QApplication>
QString titleString()
{
QString name = QString::fromStdString(App::appName());
QString version = QString::fromStdString(App::appVersion());
return QString("%1 - v%2").arg(name).arg(version);
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QtBasedFileSystem file_system;
App app(&file_system);
app.addNodeFactory(new TextFileNFDelegate);
app.loadScriptNodes("Nodin/NodeScripts/Lua");
MainWindow w(&app);
w.setWindowTitle(titleString());
w.setMinimumSize(800, 600);
w.show();
app.setUI(&w);
app.setDelegate(&w);
return a.exec();
}
|
Enable function and arrow keys | #include <ncurses.h>
#include "ev3dev.h"
using namespace ev3dev;
int main() {
int inputKey;
const int KEY_A = 97;
const int KEY_S = 115;
const int KEY_D = 100;
const int KEY_F = 102;
const int KEY_Q = 113;
const int KEY_R = 114;
initscr();
raw();
mvprintw(1,2,"Hello world :) Press Q to quit. ");
noecho();
inputKey = getch();
while(inputKey != KEY_Q) {
printw("[KEY #%i PRESSED] ", inputKey);
if (inputKey == KEY_R) {
sound::beep();
}else if (inputKey == KEY_A) {
sound::tone(262,180);
}else if (inputKey == KEY_S) {
sound::tone(392,180);
}else if (inputKey == KEY_D) {
sound::tone(440,180);
}else if (inputKey == KEY_F) {
sound::tone(262,400);
}
inputKey = getch();
}
endwin();
return 0;
}
| #include <ncurses.h>
#include "ev3dev.h"
using namespace ev3dev;
int main() {
int inputKey;
const int KEY_A = 97;
const int KEY_S = 115;
const int KEY_D = 100;
const int KEY_F = 102;
const int KEY_Q = 113;
const int KEY_R = 114;
initscr();
raw();
keypad(stdscr, TRUE);
mvprintw(1,2,"Hello world :) Press Q to quit. ");
noecho();
inputKey = getch();
while(inputKey != KEY_Q) {
printw("[KEY #%i PRESSED] ", inputKey);
if (inputKey == KEY_R) {
sound::beep();
}else if (inputKey == KEY_A) {
sound::tone(262,180);
}else if (inputKey == KEY_S) {
sound::tone(392,180);
}else if (inputKey == KEY_D) {
sound::tone(440,180);
}else if (inputKey == KEY_F) {
sound::tone(262,400);
}
inputKey = getch();
}
endwin();
return 0;
}
|
Add basic skeleton for command line arguments parsing mechanism | /*
* Copyright 2013 Kamil Michalak <kmichalak8@gmail.com>
*
* 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 <stdlib.h>
#include <iostream>
using namespace std;
int main(int argc, char **argv)
{
char* home_dir = getenv("HOME");
cout << home_dir << endl;
return 0;
}
| /*
* Copyright 2013 Kamil Michalak <kmichalak8@gmail.com>
*
* 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 <iostream>
#include <getopt.h>
int main(int argc, char **argv)
{
int arg_char;
static struct option long_options[] = {
{"config", 1, 0, 'c'},
{"query", 0, 0, 'q'},
{NULL, 0, NULL, 0}
};
int option_index = 0;
while ((arg_char = getopt_long(argc, argv, "c:", long_options, &option_index)) != -1)
switch (arg_char)
{
case 0:
std::cout << long_options[option_index].name << std::endl;
case 'c':
std::cout << "configuration" << std::endl;
if (optarg)
std::cout << " with arguments: " << optarg << std::endl;
std::cout << argv[optind] << std::endl;
break;
case 'q':
std::cout << "query" << std::endl;
break;
default:
std::cout << arg_char << std::endl;
if (optarg)
std::cout << " with arguments: " << optarg << std::endl;
}
return 0;
}
|
Add workaround for QT Lighthouse to example. | /* * This file is part of meego-im-framework *
*
* Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* Contact: Nokia Corporation (directui@nokia.com)
*
* If you have questions regarding the use of this file, please contact
* Nokia at directui@nokia.com.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation
* and appearing in the file LICENSE.LGPL included in the packaging
* of this file.
*/
#include "mainwindow.h"
#include <QtCore>
#include <QtGui>
#include <cstdlib>
int main(int argc, char** argv)
{
// Set input method to MInputContext
#ifdef HAVE_LEGACY_NAMES
setenv("QT_IM_MODULE", "MInputContext", 1);
#else
setenv("QT_IM_MODULE", "Maliit", 1);
#endif
QApplication kit(argc, argv);
MainWindow window;
return kit.exec();
}
| /* * This file is part of meego-im-framework *
*
* Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* Contact: Nokia Corporation (directui@nokia.com)
*
* If you have questions regarding the use of this file, please contact
* Nokia at directui@nokia.com.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation
* and appearing in the file LICENSE.LGPL included in the packaging
* of this file.
*/
#include "mainwindow.h"
#include <QtCore>
#include <QtGui>
#include <cstdlib>
int main(int argc, char** argv)
{
// Set input method to MInputContext
#ifdef HAVE_LEGACY_NAMES
setenv("QT_IM_MODULE", "MInputContext", 1);
#else
setenv("QT_IM_MODULE", "Maliit", 1);
#endif
QApplication kit(argc, argv);
#ifdef Q_WS_QPA
// Workaround for lighthouse Qt
kit.setInputContext(QInputContextFactory::create("Maliit", &kit));
#endif
MainWindow window;
return kit.exec();
}
|
Initialize sequence_number field for MESSAGESENT messages! | # include "broker2broker.hpp"
# include <sstream>
#include <sys/socket.h>
/**
* @brief Initialize an outgoing message of SNDMSG type.
*/
MessageForB2B::MessageForB2B(const chattp::ChattpMessage& mesg, const string& channel_id)
{
message_buffer.set_sequence_number(b2b_counter.get());
*(message_buffer.mutable_mesg()) = mesg;
message_buffer.set_channel_id(channel_id);
message_buffer.set_type(B2BMessage::SENDMESSAGE);
}
/**
* @brief Initialize an outgoing message of MSGSNT type.
*/
MessageForB2B::MessageForB2B(sequence_t seq_num, bool status)
{
message_buffer.set_type(B2BMessage::MESSAGESENT);
message_buffer.set_status(status);
}
B2BIncoming::B2BIncoming(const char* buffer, size_t length, const string& origin_b)
: origin_broker(origin_b)
{
message_buffer.ParseFromArray(buffer,length);
}
| # include "broker2broker.hpp"
# include <sstream>
#include <sys/socket.h>
/**
* @brief Initialize an outgoing message of SNDMSG type.
*/
MessageForB2B::MessageForB2B(const chattp::ChattpMessage& mesg, const string& channel_id)
{
message_buffer.set_sequence_number(b2b_counter.get());
*(message_buffer.mutable_mesg()) = mesg;
message_buffer.set_channel_id(channel_id);
message_buffer.set_type(B2BMessage::SENDMESSAGE);
}
/**
* @brief Initialize an outgoing message of MSGSNT type.
*/
MessageForB2B::MessageForB2B(sequence_t seq_num, bool status)
{
message_buffer.set_sequence_number(seq_num);
message_buffer.set_type(B2BMessage::MESSAGESENT);
message_buffer.set_status(status);
}
B2BIncoming::B2BIncoming(const char* buffer, size_t length, const string& origin_b)
: origin_broker(origin_b)
{
message_buffer.ParseFromArray(buffer,length);
}
|
Fix qt translation files path on Windows | #include <QApplication>
#include <QSettings>
#include <QLocale>
#include <QTranslator>
#include <QLibraryInfo>
#include "trayicon.h"
int main(int argc, char **argv)
{
QApplication app(argc, argv);
QApplication::setOrganizationName("Restnotifier");
app.setQuitOnLastWindowClosed(false);
// Set language
QSettings settings;
QString lang;
QTranslator translator, qtTranslator;
if (settings.contains("lang"))
lang = settings.value("lang").toString();
else
lang = QLocale::languageToString(QLocale::system().language());
if (lang == "ru")
{
QLocale::setDefault(QLocale("ru_RU"));
// install qt translator
qtTranslator.load("qt_" + QLocale().name(),
QLibraryInfo::location(QLibraryInfo::TranslationsPath));
app.installTranslator(&qtTranslator);
// install app translator
translator.load("restnotifier_ru_RU");
app.installTranslator(&translator);
}
TrayIcon *trayIcon = new TrayIcon();
trayIcon->show();
QObject::connect(trayIcon, SIGNAL(quitScheduled()), &app, SLOT(quit()));
int code = app.exec();
delete trayIcon;
return code;
}
| #include <QApplication>
#include <QSettings>
#include <QLocale>
#include <QTranslator>
#include <QLibraryInfo>
#include "trayicon.h"
int main(int argc, char **argv)
{
QApplication app(argc, argv);
QApplication::setOrganizationName("Restnotifier");
app.setQuitOnLastWindowClosed(false);
// Set language
QSettings settings;
QString lang;
QTranslator translator, qtTranslator;
if (settings.contains("lang"))
lang = settings.value("lang").toString();
else
lang = QLocale::languageToString(QLocale::system().language());
if (lang == "ru")
{
QLocale::setDefault(QLocale("ru_RU"));
// install qt translator
#if defined Q_WS_X11
const QString loc = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
#elif defined Q_WS_WIN
const QString loc();
#endif
qtTranslator.load("qt_" + QLocale().name(), loc);
app.installTranslator(&qtTranslator);
// install app translator
translator.load("restnotifier_ru_RU");
app.installTranslator(&translator);
}
TrayIcon *trayIcon = new TrayIcon();
trayIcon->show();
QObject::connect(trayIcon, SIGNAL(quitScheduled()), &app, SLOT(quit()));
int code = app.exec();
delete trayIcon;
return code;
}
|
Load gradient as floats and create float texture. | #include "./transfer_function.h"
#include <QLoggingCategory>
#include <stdexcept>
#include "./texture_manager.h"
#include "../utils/gradient_utils.h"
namespace Graphics
{
// QLoggingCategory tfChan("Graphics.TransferFunction");
TransferFunction::TransferFunction(
std::shared_ptr<TextureManager> textureManager, std::string path)
: textureManager(textureManager)
{
auto image =
GradientUtils::loadGradientAsImage(QString(path.c_str()), QSize(512, 1));
texture = textureManager->addTexture(&image);
}
TransferFunction::~TransferFunction()
{
}
} // namespace Graphics
| #include "./transfer_function.h"
#include <QLoggingCategory>
#include <stdexcept>
#include "./texture_manager.h"
#include "../utils/gradient_utils.h"
namespace Graphics
{
// QLoggingCategory tfChan("Graphics.TransferFunction");
TransferFunction::TransferFunction(
std::shared_ptr<TextureManager> textureManager, std::string path)
: textureManager(textureManager)
{
auto vector = GradientUtils::loadGradientAsFloats(QString(path.c_str()), 512);
texture = textureManager->addTexture(vector.data(), 512, 1);
}
TransferFunction::~TransferFunction()
{
}
} // namespace Graphics
|
Add inverse of frequency type | #include <strong_types.hpp>
namespace st = strong_types;
// Create a type that counts number of cycles
struct cycle_count : st::type<cycle_count, int> {
// inherit the base class's constructors
using type::type;
};
// Create a type that counts number of instructions
struct instruction_count : st::type<instruction_count, int> {
using type::type;
};
// Create a type for frequencies (hertz)
struct frequency : st::type<frequency, double> {
using type::type;
};
int main() {
cycle_count cycles(50);
instruction_count instructions(10000);
frequency clock_rate(2.6);
return 0;
}
| #include <strong_types.hpp>
namespace st = strong_types;
// Create a type that counts number of cycles
struct cycle_count : st::type<cycle_count, int> {
// inherit the base class's constructors
using type::type;
};
// Create a type that counts number of instructions
struct instruction_count : st::type<instruction_count, int> {
using type::type;
};
// Create a type for frequencies (hertz)
struct frequency : st::type<frequency, double> {
using type::type;
};
// Create a type for periods (inverse of frequency)
struct period : st::type<period, double> {
using type::type;
};
// Calculate the period given a frequency
constexpr period inverse(frequency const & hertz)
{
return period(1.0 / static_cast<double>(hertz));
}
int main() {
cycle_count cycles(50);
instruction_count instructions(10000);
frequency clock_rate(2.6);
period p = inverse(clock_rate);
return 0;
}
|
Correct area and diameter calculations. | #include "fisx_detector.h"
#include <math.h>
#include <stdexcept>
Detector::Detector(const std::string & name, const double & density, const double & thickness, \
const double & funnyFactor): Layer(name, density, thickness, funnyFactor)
{
this->diameter = 0.0;
this->distance = 10.0;
}
double Detector::getActiveArea() const
{
double pi;
pi = acos(-1.0);
return (0.5 * pi) * (this->diameter * this->diameter);
}
void Detector::setActiveArea(const double & area)
{
double pi;
pi = acos(-1.0);
if (area < 0)
{
throw std::invalid_argument("Negative detector area");
}
this->diameter = sqrt(area/(0.5 * pi));
}
void Detector::setDiameter(const double & diameter)
{
if (diameter < 0)
{
throw std::invalid_argument("Negative detector diameter");
}
this->diameter = diameter;
}
void Detector::setDistance(const double & distance)
{
if (distance <= 0)
{
throw std::invalid_argument("Negative detector distance");
}
this->distance = distance;
}
const double & Detector::getDiameter() const
{
return this->diameter;
}
const double & Detector::getDistance() const
{
return this->distance;
}
| #include "fisx_detector.h"
#include <math.h>
#include <stdexcept>
Detector::Detector(const std::string & name, const double & density, const double & thickness, \
const double & funnyFactor): Layer(name, density, thickness, funnyFactor)
{
this->diameter = 0.0;
this->distance = 10.0;
}
double Detector::getActiveArea() const
{
double pi;
pi = acos(-1.0);
return (0.25 * pi) * (this->diameter * this->diameter);
}
void Detector::setActiveArea(const double & area)
{
double pi;
pi = acos(-1.0);
if (area < 0)
{
throw std::invalid_argument("Negative detector area");
}
this->diameter = 2.0 * sqrt(area/pi);
}
void Detector::setDiameter(const double & diameter)
{
if (diameter < 0)
{
throw std::invalid_argument("Negative detector diameter");
}
this->diameter = diameter;
}
void Detector::setDistance(const double & distance)
{
if (distance <= 0)
{
throw std::invalid_argument("Negative detector distance");
}
this->distance = distance;
}
const double & Detector::getDiameter() const
{
return this->diameter;
}
const double & Detector::getDistance() const
{
return this->distance;
}
|
Return false if the size does not match | #include <mantella_bits/helper/unorderedContainer.hpp>
// C++ standard library
#include <functional>
namespace mant {
arma::uword Hash::operator()(
const arma::Col<double>& key) const {
// Start with the hash of the first value ...
arma::uword hashedKey = std::hash<double>()(key(0));
// ... and add the hash value of all following values to it.
// Note: This is adapted from the Boost library (boost::hash_combine).
for (const auto& value : key) {
hashedKey ^= std::hash<double>()(value) + 0x9e3779b9 + (hashedKey << 6) + (hashedKey >> 2);
}
return hashedKey;
}
bool IsEqual::operator()(
const arma::Col<double>& firstKey,
const arma::Col<double>& secondKey) const {
// TODO Add exception
return arma::all(firstKey == secondKey);
}
}
| #include <mantella_bits/helper/unorderedContainer.hpp>
// C++ standard library
#include <functional>
namespace mant {
arma::uword Hash::operator()(
const arma::Col<double>& key) const {
// Start with the hash of the first value ...
arma::uword hashedKey = std::hash<double>()(key(0));
// ... and add the hash value of all following values to it.
// Note: This is adapted from the Boost library (boost::hash_combine).
for (const auto& value : key) {
hashedKey ^= std::hash<double>()(value) + 0x9e3779b9 + (hashedKey << 6) + (hashedKey >> 2);
}
return hashedKey;
}
bool IsEqual::operator()(
const arma::Col<double>& firstKey,
const arma::Col<double>& secondKey) const {
if (firstKey.n_elem != secondKey.n_elem) {
return false;
}
return arma::all(firstKey == secondKey);
}
}
|
Update docs on double to float | /*
C++ working draft
7.9.1
If the source value is between two adjacent destination values, the result
of the conversion is an implementation-defined choice of either of those
values. Otherwise, the behavior is undefined.
*/
#include <cstdlib>
#include <iostream>
int main() {
static constexpr double kLargeDouble = 1e100;
std::cout << static_cast<float>(kLargeDouble) << std::endl;
return 0;
}
| /*
http://eel.is/c++draft/conv.double#1
7 Expressions [expr]
7.3 Standard conversions [conv]
7.3.9 Floating-point conversions [conv.double]
1 A prvalue of floating-point type can be converted to a prvalue of another floating-point type.
If the source value can be exactly represented in the destination type, the result of the conversion is that exact representation.
If the source value is between two adjacent destination values, the result of the conversion is an implementation-defined choice of either of those values.
Otherwise, the behavior is undefined.
https://docs.microsoft.com/en-us/cpp/c-language/conversions-from-floating-point-types?view=vs-2019
Represent as a float. If double value can't be represented exactly as float, loss of precision occurs. If value is too large to be represented as float, the result is undefined.
*/
#include <cstdlib>
#include <iostream>
int main() {
static constexpr double kLargeDouble = 1e100;
std::cout << static_cast<float>(kLargeDouble) << std::endl;
return 0;
}
|
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
|
Revert "Remove extra call to create_directories" | #include "OptionsManager.h"
#include <fstream>
#include <iostream>
#include <boost/filesystem.hpp>
#include <spotify/json.hpp>
#include "codecs/OptionsCodec.h"
#include "logging/Logging.h"
OptionsManager::OptionsManager(std::string optionsFilename)
{
loadOptions(optionsFilename);
}
void OptionsManager::loadOptions(std::string optionsFilename)
{
std::ifstream ifs(optionsFilename);
if (!ifs.good())
{
throw std::runtime_error("Could not open options file");
}
std::string str{std::istreambuf_iterator<char>(ifs),
std::istreambuf_iterator<char>()};
try
{
mOptions = spotify::json::decode<Options>(str.c_str());
}
catch (const spotify::json::decode_exception& e)
{
logError() << "spotify::json::decode_exception encountered at "
<< e.offset()
<< ": "
<< e.what();
throw;
}
mOptions.paths.initialise(optionsFilename);
createOutputDirectory();
}
void OptionsManager::createOutputDirectory()
{
// TODO(hryniuk): move it elsewhere
boost::filesystem::path p(mOptions.paths.directory);
p.append(mOptions.outputDirectory);
auto relativeOutputDirectory = p.string();
mOptions.relativeOutputDirectory = relativeOutputDirectory;
}
const Options& OptionsManager::getOptions() const
{
return mOptions;
}
| #include "OptionsManager.h"
#include <fstream>
#include <iostream>
#include <boost/filesystem.hpp>
#include <spotify/json.hpp>
#include "codecs/OptionsCodec.h"
#include "logging/Logging.h"
OptionsManager::OptionsManager(std::string optionsFilename)
{
loadOptions(optionsFilename);
}
void OptionsManager::loadOptions(std::string optionsFilename)
{
std::ifstream ifs(optionsFilename);
if (!ifs.good())
{
throw std::runtime_error("Could not open options file");
}
std::string str{std::istreambuf_iterator<char>(ifs),
std::istreambuf_iterator<char>()};
try
{
mOptions = spotify::json::decode<Options>(str.c_str());
}
catch (const spotify::json::decode_exception& e)
{
logError() << "spotify::json::decode_exception encountered at "
<< e.offset()
<< ": "
<< e.what();
throw;
}
mOptions.paths.initialise(optionsFilename);
createOutputDirectory();
}
void OptionsManager::createOutputDirectory()
{
// TODO(hryniuk): move it elsewhere
boost::filesystem::path p(mOptions.paths.directory);
p.append(mOptions.outputDirectory);
boost::filesystem::create_directories(p);
auto relativeOutputDirectory = p.string();
mOptions.relativeOutputDirectory = relativeOutputDirectory;
}
const Options& OptionsManager::getOptions() const
{
return mOptions;
}
|
Fix nasty bug introduced due to naming glitch. | #include "vast/detail/cppa_type_info.h"
#include <cppa/announce.hpp>
#include "vast/chunk.h"
#include "vast/event.h"
#include "vast/expression.h"
#include "vast/schema.h"
#include "vast/segment.h"
#include "vast/to_string.h"
#include "vast/uuid.h"
namespace vast {
namespace detail {
template <typename T>
void cppa_announce()
{
cppa::announce(typeid(T), new cppa_type_info<T>);
}
void cppa_announce_types()
{
cppa_announce<uuid>();
cppa_announce<event>();
cppa_announce<chunk<event>>();
cppa_announce<expression>();
cppa_announce<segment>();
cppa_announce<schema>();
cppa::announce<std::vector<uuid>>();
cppa::announce<std::vector<event>>();
}
} // namespace detail
} // namespace vast
| #include "vast/detail/cppa_type_info.h"
#include <cppa/announce.hpp>
#include "vast/chunk.h"
#include "vast/event.h"
#include "vast/expression.h"
#include "vast/schema.h"
#include "vast/segment.h"
#include "vast/to_string.h"
#include "vast/uuid.h"
namespace vast {
namespace detail {
template <typename T>
void cppa_announce()
{
cppa::announce(typeid(T), new cppa_type_info<T>);
}
void cppa_announce_types()
{
cppa_announce<uuid>();
cppa_announce<event>();
cppa_announce<chunk<event>>();
cppa_announce<expression>();
cppa_announce<segment>();
cppa_announce<schema>();
cppa_announce<std::vector<uuid>>();
cppa_announce<std::vector<event>>();
}
} // namespace detail
} // namespace vast
|
Fix test broken by r335644 | // RUN: %clangxx -g -DSHARED_LIB %s -fPIC -shared -o %dynamiclib %ld_flags_rpath_so
// RUN: %clangxx_cfi_diag -g %s -o %t %ld_flags_rpath_exe
// RUN: %run %t 2>&1 | FileCheck %s
// REQUIRES: cxxabi
// UNSUPPORTED: win32
#include <stdio.h>
#include <string.h>
struct A {
virtual void f();
};
void *create_B();
#ifdef SHARED_LIB
struct B {
virtual void f();
};
void B::f() {}
void *create_B() {
return (void *)(new B());
}
#else
void A::f() {}
int main(int argc, char *argv[]) {
void *p = create_B();
// CHECK: runtime error: control flow integrity check for type 'A' failed during cast to unrelated type
// CHECK: invalid vtable in module {{.*}}libtarget_uninstrumented.cpp.dynamic.so
A *a = (A *)p;
memset(p, 0, sizeof(A));
// CHECK: runtime error: control flow integrity check for type 'A' failed during cast to unrelated type
// CHECK-NOT: invalid vtable in module
// CHECK: invalid vtable
a = (A *)p;
// CHECK: done
fprintf(stderr, "done %p\n", a);
}
#endif
| // RUN: %clangxx -g -DSHARED_LIB %s -fPIC -shared -o %dynamiclib %ld_flags_rpath_so
// RUN: %clangxx_cfi_diag -g %s -o %t %ld_flags_rpath_exe
// RUN: %run %t 2>&1 | FileCheck %s
// REQUIRES: cxxabi
// UNSUPPORTED: win32
#include <stdio.h>
#include <string.h>
struct A {
virtual void f();
};
void *create_B();
#ifdef SHARED_LIB
struct B {
virtual void f();
};
void B::f() {}
void *create_B() {
return (void *)(new B());
}
#else
void A::f() {}
int main(int argc, char *argv[]) {
void *p = create_B();
// CHECK: runtime error: control flow integrity check for type 'A' failed during cast to unrelated type
// CHECK: invalid vtable
// CHECK: check failed in {{.*}}, vtable located in {{.*}}libtarget_uninstrumented.cpp.dynamic.so
A *a = (A *)p;
memset(p, 0, sizeof(A));
// CHECK: runtime error: control flow integrity check for type 'A' failed during cast to unrelated type
// CHECK: invalid vtable
// CHECK: check failed in {{.*}}, vtable located in (unknown)
a = (A *)p;
// CHECK: done
fprintf(stderr, "done %p\n", a);
}
#endif
|
Test pow with scalar double exponent and integer exponent. | #include <iostream>
using namespace std;
#include "numvec.hpp"
template<typename T>
void f1(T &res, const T &x)
{
T u,y = 2*x;
y = 7*x;
y -= 1.2;
u = x + y;
y = y/x;
u = 3/x;
u += -y;
u += 1.1*x;
y = sin(u);
res = pow(x,y);
}
void test_correctness()
{
const int len = 4;
numvec<double, len> inp, out;
for (int i=0;i<len;i++)
inp[i] = i+0.1;
f1(out,inp);
double sumres = 0;
for (int i=0;i<len;i++)
{
double outd;
f1(outd,inp[i]);
sumres += fabs(out[i] - outd);
cout << outd << " " << out[i] << endl;
}
cout.precision(15);
cout << "Sum of absolute differences " << sumres << endl;
}
int main(int argc, const char *argv[])
{
test_correctness();
return 0;
}
| #include <iostream>
using namespace std;
#include "numvec.hpp"
template<typename T>
void f1(T &res, const T &x)
{
T u,y = 2*x;
y = 7*x;
y -= 1.2;
u = x + y;
y = y/x;
u = 3/x;
u += -y;
u += 1.1*x;
y = sin(u);
res = pow(x,y);
y = pow(res,1.2);
res = pow(y,3);
}
void test_correctness()
{
const int len = 4;
numvec<double, len> inp, out;
for (int i=0;i<len;i++)
inp[i] = i+0.1;
f1(out,inp);
double sumres = 0;
for (int i=0;i<len;i++)
{
double outd;
f1(outd,inp[i]);
sumres += fabs(out[i] - outd);
}
cout.precision(15);
cout << "Sum of absolute differences " << sumres << endl;
}
int main(int argc, const char *argv[])
{
test_correctness();
return 0;
}
|
Remove space (major changes here, people) | // Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)
#include "HorizontalTile.h"
HorizontalTile::HorizontalTile(std::wstring bitmapName,
int x, int y, int units, bool reverse) :
Meter(bitmapName, x, y, units),
_reverse(reverse) {
_rect.Width = _bitmap->GetWidth();
_rect.Height = _bitmap->GetHeight();
_texture = new Gdiplus::TextureBrush(_bitmap, Gdiplus::WrapModeTile,
0, 0, _rect.Width, _rect.Height);
_shiftMat = new Gdiplus::Matrix(1, 0, 0, 1,
(float) _rect.X, (float) _rect.Y);
_texture->SetTransform(_shiftMat);
}
HorizontalTile::~HorizontalTile() {
delete _texture;
delete _shiftMat;
}
void HorizontalTile::Draw(
Gdiplus::Bitmap *buffer, Gdiplus::Graphics *graphics) {
int width = _rect.Width * CalcUnits();
if (_reverse == false) {
graphics->FillRectangle(_texture,
_rect.X, _rect.Y, width, _rect.Height);
} else {
int xShift = _rect.Width * Units() - width;
graphics->FillRectangle(_texture,
_rect.X + xShift, _rect.Y, width, _rect.Height);
}
UpdateDrawnValues();
} | // Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)
#include "HorizontalTile.h"
HorizontalTile::HorizontalTile(std::wstring bitmapName,
int x, int y, int units, bool reverse) :
Meter(bitmapName, x, y, units),
_reverse(reverse) {
_rect.Width = _bitmap->GetWidth();
_rect.Height = _bitmap->GetHeight();
_texture = new Gdiplus::TextureBrush(_bitmap, Gdiplus::WrapModeTile,
0, 0, _rect.Width, _rect.Height);
_shiftMat = new Gdiplus::Matrix(1, 0, 0, 1,
(float) _rect.X, (float) _rect.Y);
_texture->SetTransform(_shiftMat);
}
HorizontalTile::~HorizontalTile() {
delete _texture;
delete _shiftMat;
}
void HorizontalTile::Draw(
Gdiplus::Bitmap *buffer, Gdiplus::Graphics *graphics) {
int width = _rect.Width * CalcUnits();
if (_reverse == false) {
graphics->FillRectangle(_texture,
_rect.X, _rect.Y, width, _rect.Height);
} else {
int xShift = _rect.Width * Units() - width;
graphics->FillRectangle(_texture,
_rect.X + xShift, _rect.Y, width, _rect.Height);
}
UpdateDrawnValues();
} |
Correct the way the module is defined. | #include <Python.h>
#include "Quantuccia/ql/time/calendars/unitedstates.hpp"
static PyObject*
get_holiday_date(PyObject *self, PyObject *args)
{
return NULL;
}
static PyMethodDef QuantucciaMethods[] = {
{"get_holiday_date", (PyCFunction)get_holiday_date, METH_VARARGS, NULL},
{NULL, NULL} /* Sentinel */
};
PyObject* PyInit_pyQuantuccia(void){
PyObject *m;
m = PyCreate_Module("quantuccia", QuantucciaMethods);
return m;
}
| #include <Python.h>
#include "Quantuccia/ql/time/calendars/unitedstates.hpp"
static PyObject*
get_holiday_date(PyObject *self, PyObject *args)
{
return NULL;
}
static PyMethodDef QuantucciaMethods[] = {
{"get_holiday_date", (PyCFunction)get_holiday_date, METH_VARARGS, NULL},
{NULL, NULL} /* Sentinel */
};
static struct PyModuleDef quantuccia_module_def = {
PyModuleDef_HEAD_INIT,
"quantuccia",
NULL,
-1,
QuantucciaMethods,
};
PyObject* PyInit_pyQuantuccia(void){
PyObject *m;
m = PyCreate_Module(&quantuccia_module_def);
return m;
}
|
Add exit check for setup call | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
#include <signal.h>
#include <iostream>
#include "verilated_toplevel.h"
#include "verilator_sim_ctrl.h"
ibex_riscv_compliance *top;
VerilatorSimCtrl *simctrl;
int main(int argc, char **argv) {
int retcode;
top = new ibex_riscv_compliance;
simctrl = new VerilatorSimCtrl(top, top->IO_CLK, top->IO_RST_N,
VerilatorSimCtrlFlags::ResetPolarityNegative);
// Setup simctrl
retcode = simctrl->SetupSimulation(argc, argv);
// Initialize RAM
simctrl->InitRam("TOP.ibex_riscv_compliance.u_ram");
// Run the simulation
simctrl->RunSimulation();
delete top;
delete simctrl;
return retcode;
}
| // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
#include <signal.h>
#include <iostream>
#include "verilated_toplevel.h"
#include "verilator_sim_ctrl.h"
ibex_riscv_compliance *top;
VerilatorSimCtrl *simctrl;
int main(int argc, char **argv) {
int retcode;
top = new ibex_riscv_compliance;
simctrl = new VerilatorSimCtrl(top, top->IO_CLK, top->IO_RST_N,
VerilatorSimCtrlFlags::ResetPolarityNegative);
// Setup simctrl
retcode = simctrl->SetupSimulation(argc, argv);
if (retcode != 0) {
goto free_return;
}
// Initialize RAM
simctrl->InitRam("TOP.ibex_riscv_compliance.u_ram");
// Run the simulation
simctrl->RunSimulation();
free_return:
delete top;
delete simctrl;
return retcode;
}
|
Add name for bit hacks | /**
* Author: Václav Volhejn
* Source: KACTL notebook (various/chapter.tex)
* Status: Tested manually, forAllSubsetMasks tested at Ptz
* Description: Various bit manipulation functions/snippets.
*/
#include "../base.hpp"
int lowestSetBit(int x) { return x & -x }
void forAllSubsetMasks(int m) { // Including m itself
for (int x = m; x; --x &= m) { /* ... */ }
}
int nextWithSamePopcount(int x) { // 3->5->6->9->10->12->17...
int c = x&-x, r = x+c;
return (((r^x) >> 2)/c) | r;
}
// For each mask, compute sum of values D[1<<i] of its set bits i
void sumsOfSubsets() {
int K = 3;
vector<int> D(1<<K, 0);
D[1] = 4; D[2] = 3; D[4] = 8;
rep(b,0,K) rep(i,0,(1 << K)) if (i & 1 << b) D[i] += D[i^(1 << b)];
}
| /**
* Name: Bit hacks
* Author: Václav Volhejn
* Source: KACTL notebook (various/chapter.tex)
* Status: Tested manually, forAllSubsetMasks tested at Ptz
* Description: Various bit manipulation functions/snippets.
*/
#include "../base.hpp"
int lowestSetBit(int x) { return x & -x }
void forAllSubsetMasks(int m) { // Including m itself
for (int x = m; x; --x &= m) { /* ... */ }
}
int nextWithSamePopcount(int x) { // 3->5->6->9->10->12->17...
int c = x&-x, r = x+c;
return (((r^x) >> 2)/c) | r;
}
// For each mask, compute sum of values D[1<<i] of its set bits i
void sumsOfSubsets() {
int K = 3;
vector<int> D(1<<K, 0);
D[1] = 4; D[2] = 3; D[4] = 8;
rep(b,0,K) rep(i,0,(1 << K)) if (i & 1 << b) D[i] += D[i^(1 << b)];
}
|
Change declarative expression to get context and scopre from script | #include "gameitem.h"
#include <QDeclarativeExpression>
GameItem::GameItem(QQuickItem *parent)
: QQuickItem(parent),
m_expression(0)
{
}
void GameItem::update(long delta)
{
if (m_expression)
m_expression->evaluate();
}
QDeclarativeScriptString GameItem::updateScript() const
{
return m_updateScript;
}
void GameItem::setUpdateScript(QDeclarativeScriptString updateScript)
{
m_updateScript = updateScript;
if (m_expression)
delete m_expression;
m_expression = new QDeclarativeExpression(m_updateScript);
emit updateScriptChanged();
}
| #include "gameitem.h"
#include <QDeclarativeExpression>
GameItem::GameItem(QQuickItem *parent)
: QQuickItem(parent),
m_expression(0)
{
}
void GameItem::update(long delta)
{
if (m_expression)
m_expression->evaluate();
}
QDeclarativeScriptString GameItem::updateScript() const
{
return m_updateScript;
}
void GameItem::setUpdateScript(QDeclarativeScriptString updateScript)
{
m_updateScript = updateScript;
if (m_expression)
delete m_expression;
m_expression = new QDeclarativeExpression(m_updateScript.context(), m_updateScript.scopeObject(), m_updateScript.script());
emit updateScriptChanged();
}
|
Use Chrome's user agent string for content_shell, since some sites (i.e. Gmail) give a degraded experience otherwise. | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/shell/shell_content_client.h"
#include "base/string_piece.h"
namespace content {
ShellContentClient::~ShellContentClient() {
}
void ShellContentClient::SetActiveURL(const GURL& url) {
}
void ShellContentClient::SetGpuInfo(const GPUInfo& gpu_info) {
}
void ShellContentClient::AddPepperPlugins(
std::vector<PepperPluginInfo>* plugins) {
}
bool ShellContentClient::CanSendWhileSwappedOut(const IPC::Message* msg) {
return false;
}
bool ShellContentClient::CanHandleWhileSwappedOut(const IPC::Message& msg) {
return false;
}
std::string ShellContentClient::GetUserAgent(bool mimic_windows) const {
return std::string();
}
string16 ShellContentClient::GetLocalizedString(int message_id) const {
return string16();
}
base::StringPiece ShellContentClient::GetDataResource(int resource_id) const {
return base::StringPiece();
}
#if defined(OS_WIN)
bool ShellContentClient::SandboxPlugin(CommandLine* command_line,
sandbox::TargetPolicy* policy) {
return false;
}
#endif
} // namespace content
| // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/shell/shell_content_client.h"
#include "base/string_piece.h"
#include "webkit/glue/user_agent.h"
namespace content {
ShellContentClient::~ShellContentClient() {
}
void ShellContentClient::SetActiveURL(const GURL& url) {
}
void ShellContentClient::SetGpuInfo(const GPUInfo& gpu_info) {
}
void ShellContentClient::AddPepperPlugins(
std::vector<PepperPluginInfo>* plugins) {
}
bool ShellContentClient::CanSendWhileSwappedOut(const IPC::Message* msg) {
return false;
}
bool ShellContentClient::CanHandleWhileSwappedOut(const IPC::Message& msg) {
return false;
}
std::string ShellContentClient::GetUserAgent(bool mimic_windows) const {
return webkit_glue::BuildUserAgentHelper(mimic_windows, "Chrome/15.16.17.18");
}
string16 ShellContentClient::GetLocalizedString(int message_id) const {
return string16();
}
base::StringPiece ShellContentClient::GetDataResource(int resource_id) const {
return base::StringPiece();
}
#if defined(OS_WIN)
bool ShellContentClient::SandboxPlugin(CommandLine* command_line,
sandbox::TargetPolicy* policy) {
return false;
}
#endif
} // namespace content
|
Add symbols for sized allocation | #include <MemoryManager.hh>
#include <cstddef>
#include <new>
void *operator new(std::size_t size)
{
return MemoryManager::get().allocate(size);
}
void *operator new[](std::size_t size)
{
return MemoryManager::get().allocate(size);
}
void operator delete(void* p)
{
MemoryManager::get().deallocate(p);
}
void operator delete[](void* p)
{
MemoryManager::get().deallocate(p);
}
| #include <MemoryManager.hh>
#include <cstddef>
#include <new>
void *operator new(std::size_t size)
{
return MemoryManager::get().allocate(size);
}
void *operator new[](std::size_t size)
{
return MemoryManager::get().allocate(size);
}
void operator delete(void* p)
{
MemoryManager::get().deallocate(p);
}
void operator delete[](void* p)
{
MemoryManager::get().deallocate(p);
}
void operator delete(void* p, std::size_t)
{
MemoryManager::get().deallocate(p);
}
void operator delete[](void* p, std::size_t)
{
MemoryManager::get().deallocate(p);
}
|
Fix invalid write in RenderViewHostObserver. | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/render_view_host_observer.h"
#include "content/browser/renderer_host/render_view_host.h"
RenderViewHostObserver::RenderViewHostObserver(RenderViewHost* render_view_host)
: render_view_host_(render_view_host),
routing_id_(render_view_host->routing_id()) {
render_view_host_->AddObserver(this);
}
RenderViewHostObserver::~RenderViewHostObserver() {
if (render_view_host_)
render_view_host_->RemoveObserver(this);
}
void RenderViewHostObserver::RenderViewHostDestroyed() {
delete this;
}
bool RenderViewHostObserver::OnMessageReceived(const IPC::Message& message) {
return false;
}
bool RenderViewHostObserver::Send(IPC::Message* message) {
if (!render_view_host_) {
delete message;
return false;
}
return render_view_host_->Send(message);
}
void RenderViewHostObserver::RenderViewHostDestruction() {
render_view_host_->RemoveObserver(this);
RenderViewHostDestroyed();
render_view_host_ = NULL;
}
| // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/render_view_host_observer.h"
#include "content/browser/renderer_host/render_view_host.h"
RenderViewHostObserver::RenderViewHostObserver(RenderViewHost* render_view_host)
: render_view_host_(render_view_host),
routing_id_(render_view_host->routing_id()) {
render_view_host_->AddObserver(this);
}
RenderViewHostObserver::~RenderViewHostObserver() {
if (render_view_host_)
render_view_host_->RemoveObserver(this);
}
void RenderViewHostObserver::RenderViewHostDestroyed() {
delete this;
}
bool RenderViewHostObserver::OnMessageReceived(const IPC::Message& message) {
return false;
}
bool RenderViewHostObserver::Send(IPC::Message* message) {
if (!render_view_host_) {
delete message;
return false;
}
return render_view_host_->Send(message);
}
void RenderViewHostObserver::RenderViewHostDestruction() {
render_view_host_->RemoveObserver(this);
render_view_host_ = NULL;
RenderViewHostDestroyed();
}
|
Add content to second test | #include <QtPlugin>
#include "test_video_annotator.h"
#include "fish_detector/video_annotator/mainwindow.h"
#ifdef _WIN32
Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin)
#endif
void TestVideoAnnotator::testLoadVideo() {
fish_detector::video_annotator::MainWindow mainwin;
mainwin.player_->loadVideo("slow_motion_drop.mp4");
}
void TestVideoAnnotator::testSaveAnnotationsNoFish() {
}
QTEST_MAIN(TestVideoAnnotator)
#include "test_video_annotator.moc"
| #include <QtPlugin>
#include "test_video_annotator.h"
#include "fish_detector/video_annotator/mainwindow.h"
#ifdef _WIN32
Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin)
#endif
void TestVideoAnnotator::testLoadVideo() {
fish_detector::video_annotator::MainWindow mainwin;
std::string name = "C:/local/FishDetector/test/video_annotator/slow_motion_drop.mp4";
QVERIFY(mainwin.player_->loadVideo(name));
}
void TestVideoAnnotator::testSaveAnnotationsNoFish() {
fish_detector::video_annotator::MainWindow mainwin;
std::string filename = "slow_motion_drop.mp4";
QVERIFY(mainwin.player_->loadVideo(filename));
mainwin.onLoadVideoSuccess(QString::fromUtf8(filename.c_str()));
}
QTEST_MAIN(TestVideoAnnotator)
#include "test_video_annotator.moc"
|
Fix a build error when OS_CHROMEOS is not defined. | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_input_method_api.h"
#include "base/values.h"
#include "chrome/browser/chromeos/input_method/input_method_manager.h"
#include "chrome/browser/chromeos/extensions/input_method_event_router.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
GetInputMethodFunction::GetInputMethodFunction() {
}
GetInputMethodFunction::~GetInputMethodFunction() {
}
bool GetInputMethodFunction::RunImpl() {
#if !defined(OS_CHROMEOS)
NOTREACHED();
#else
chromeos::ExtensionInputMethodEventRouter* router =
profile_->GetExtensionService()->input_method_event_router();
chromeos::input_method::InputMethodManager* manager =
chromeos::input_method::InputMethodManager::GetInstance();
const std::string input_method =
router->GetInputMethodForXkb(manager->current_input_method().id());
result_.reset(Value::CreateStringValue(input_method));
return true;
#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/browser/extensions/extension_input_method_api.h"
#include "base/values.h"
#include "chrome/browser/chromeos/input_method/input_method_manager.h"
#include "chrome/browser/chromeos/extensions/input_method_event_router.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
GetInputMethodFunction::GetInputMethodFunction() {
}
GetInputMethodFunction::~GetInputMethodFunction() {
}
bool GetInputMethodFunction::RunImpl() {
#if !defined(OS_CHROMEOS)
NOTREACHED();
return false;
#else
chromeos::ExtensionInputMethodEventRouter* router =
profile_->GetExtensionService()->input_method_event_router();
chromeos::input_method::InputMethodManager* manager =
chromeos::input_method::InputMethodManager::GetInstance();
const std::string input_method =
router->GetInputMethodForXkb(manager->current_input_method().id());
result_.reset(Value::CreateStringValue(input_method));
return true;
#endif
}
|
Check vs Remove - not so not so clear | #include <vector>
#include <iostream>
#include <algorithm>
#ifndef REMOVE_VALUES
#ifndef CHECK_VALUES
#error "define one of REMOVE_VALUES or CHECK_VALUES"
#endif
#endif
#ifdef REMOVE_VALUES
#ifdef CHECK_VALUES
#error "define either REMOVE_VALUES or CHECK_VALUES"
#endif
#endif
int main()
{
std::vector<int> myValues;
for ( long int i=0L; i<100000000L; ++i )
myValues.push_back(i%3);
int iOriginalSize = myValues.size();
#ifdef REMOVE_VALUES
myValues.erase(std::remove_if(myValues.begin(),myValues.end(),[](int i) { return i == 2; }),myValues.end());
#endif
int sum = 0;
for ( unsigned int i=0; i<myValues.size(); ++i )
{
#ifdef CHECK_VALUES
if ( myValues[i] != 2 )
{
#endif
sum += myValues[i];
#ifdef CHECK_VALUES
}
#endif
}
}
| #include <vector>
#include <iostream>
#include <algorithm>
#ifndef REMOVE_VALUES
#ifndef CHECK_VALUES
#error "define one of REMOVE_VALUES or CHECK_VALUES"
#endif
#endif
#ifdef REMOVE_VALUES
#ifdef CHECK_VALUES
#error "define either REMOVE_VALUES or CHECK_VALUES"
#endif
#endif
int main()
{
std::vector<int> myValues;
for ( long int i=0L; i<10000000L; ++i )
myValues.push_back(i%3);
int iOriginalSize = myValues.size();
#ifdef REMOVE_VALUES
myValues.erase(std::remove_if(myValues.begin(),myValues.end(),[](int i) { return i == 2; }),myValues.end());
#endif
const int iterations = 100;
for ( int iteration=0; iteration < iterations; ++iteration )
{
int sum = 0;
for ( unsigned int i=0; i<myValues.size(); ++i )
{
#ifdef CHECK_VALUES
if ( myValues[i] != 2 )
{
#endif
sum += myValues[i];
#ifdef CHECK_VALUES
}
#endif
}
}
}
|
Add test for JSON dumping | #include "Test.h"
TEST_CASE("Nets") {
auto tree = SyntaxTree::fromText(R"(
module Top;
wire logic f = 1;
endmodule
)");
Compilation compilation;
compilation.addSyntaxTree(tree);
NO_COMPILATION_ERRORS;
}
TEST_CASE("Continuous Assignments") {
auto tree = SyntaxTree::fromText(R"(
module Top;
wire foo;
assign foo = 1, foo = 'z;
logic bar;
assign bar = 1;
endmodule
)");
Compilation compilation;
compilation.addSyntaxTree(tree);
NO_COMPILATION_ERRORS;
} | #include "Test.h"
#include <nlohmann/json.hpp>
TEST_CASE("Nets") {
auto tree = SyntaxTree::fromText(R"(
module Top;
wire logic f = 1;
endmodule
)");
Compilation compilation;
compilation.addSyntaxTree(tree);
NO_COMPILATION_ERRORS;
}
TEST_CASE("Continuous Assignments") {
auto tree = SyntaxTree::fromText(R"(
module Top;
wire foo;
assign foo = 1, foo = 'z;
logic bar;
assign bar = 1;
endmodule
)");
Compilation compilation;
compilation.addSyntaxTree(tree);
NO_COMPILATION_ERRORS;
}
TEST_CASE("JSON dump") {
auto tree = SyntaxTree::fromText(R"(
interface I;
modport m();
endinterface
package p1;
parameter int BLAH = 1;
endpackage
module Top;
wire foo;
assign foo = 1;
I array [3] ();
always_comb begin
end
if (1) begin
end
for (genvar i = 0; i < 10; i++) begin
end
import p1::BLAH;
import p1::*;
logic f;
I stuff();
Child child(.i(stuff), .f);
function logic func(logic bar);
endfunction
endmodule
module Child(I.m i, input logic f = 1);
endmodule
)");
Compilation compilation;
compilation.addSyntaxTree(tree);
NO_COMPILATION_ERRORS;
// This basic test just makes sure that JSON dumping doesn't crash.
json output = compilation.getRoot();
output.dump();
} |
Update blink_modular.ino: changed blinkrate argument to uint32_t | #include <Automaton.h>
#include "Atm_blink.h"
Atm_blink & Atm_blink::begin( int attached_pin, int blinkrate )
{
const static state_t state_table[] PROGMEM = {
/* ON_ENTER ON_LOOP ON_EXIT EVT_TIMER ELSE */
/* LED_ON */ ACT_ON, -1, -1, LED_OFF, -1,
/* LED_OFF */ ACT_OFF, -1, -1, LED_ON, -1 };
Machine::begin( state_table, ELSE );
pin = attached_pin;
timer.begin( this, blinkrate );
pinMode( pin, OUTPUT );
return *this;
}
int Atm_blink::event( int id )
{
switch ( id ) {
case EVT_TIMER :
return timer.expired();
}
return 0;
}
void Atm_blink::action( int id )
{
switch ( id ) {
case ACT_ON :
digitalWrite( pin, HIGH );
return;
case ACT_OFF :
digitalWrite( pin, LOW );
return;
}
}
Atm_blink & Atm_blink::onSwitch( swcb_sym_t switch_callback ) {
Machine::onSwitch( switch_callback, "LED_ON\0LED_OFF", "EVT_TIMER\0ELSE" );
return *this;
}
| #include <Automaton.h>
#include "Atm_blink.h"
Atm_blink & Atm_blink::begin( int attached_pin, uint32_t blinkrate )
{
const static state_t state_table[] PROGMEM = {
/* ON_ENTER ON_LOOP ON_EXIT EVT_TIMER ELSE */
/* LED_ON */ ACT_ON, -1, -1, LED_OFF, -1,
/* LED_OFF */ ACT_OFF, -1, -1, LED_ON, -1 };
Machine::begin( state_table, ELSE );
pin = attached_pin;
timer.begin( this, blinkrate );
pinMode( pin, OUTPUT );
return *this;
}
int Atm_blink::event( int id )
{
switch ( id ) {
case EVT_TIMER :
return timer.expired();
}
return 0;
}
void Atm_blink::action( int id )
{
switch ( id ) {
case ACT_ON :
digitalWrite( pin, HIGH );
return;
case ACT_OFF :
digitalWrite( pin, LOW );
return;
}
}
Atm_blink & Atm_blink::onSwitch( swcb_sym_t switch_callback ) {
Machine::onSwitch( switch_callback, "LED_ON\0LED_OFF", "EVT_TIMER\0ELSE" );
return *this;
}
|
Change to initilizer list construction | #include <iostream>
using namespace std;
class Complex {
double re, im;
public:
Complex(double r, double i) : re {r}, im {i} {}
Complex operator+(Complex);
Complex operator*(Complex);
friend ostream &operator<<(ostream &os, Complex c);
};
ostream &operator<<(ostream &os, Complex c) {
os << c.re;
os << ((c.im >= 0) ? "+" : "-");
os << c.im << "*i";
return os;
}
Complex Complex::operator+(Complex c) {
return Complex{this->re+c.re, this->im+c.im};
}
Complex Complex::operator*(Complex c) {
double r = this->re*c.re - this->im*c.im;
double i = this->im*c.re + this->re*c.im;
// This is OK, probably because this is considered
// as initializer
return {r, i};
}
void f() {
Complex a = Complex{1, 3.1};
cout << a << endl;
Complex b {1.2, 2};
cout << b << endl;
Complex c {b};
cout << c << endl;
cout << b+c << endl;
cout << a*b + Complex{1, 2} << endl;
}
int main() {
Complex c0 {0, 0};
f();
return 0;
}
| #include <iostream>
using namespace std;
class Complex {
double re, im;
public:
Complex(double r, double i) : re {r}, im {i} {}
Complex operator+(Complex);
Complex operator*(Complex);
friend ostream &operator<<(ostream &os, Complex c);
};
ostream &operator<<(ostream &os, Complex c) {
os << c.re;
os << ((c.im >= 0) ? "+" : "-");
os << c.im << "*i";
return os;
}
Complex Complex::operator+(Complex c) {
return Complex{this->re+c.re, this->im+c.im};
}
Complex Complex::operator*(Complex c) {
double r = this->re*c.re - this->im*c.im;
double i = this->im*c.re + this->re*c.im;
// This is OK, probably because this is considered
// as initializer
return {r, i};
}
void f() {
Complex a = {1, 3.1};
cout << a << endl;
Complex b {1.2, 2};
cout << b << endl;
Complex c {b};
cout << c << endl;
cout << b+c << endl;
cout << a*b + Complex{1, 2} << endl;
}
int main() {
Complex c0 {0, 0};
f();
return 0;
}
|
Use the new atom types module macro | /**
* atom_types_init.cc
*
* Link Grammar Atom Types used during Viterbi parsing.
*
* Copyright (c) 2009 Linas Vepstas <linasvepstas@gmail.com>
*/
#include "opencog/viterbi/atom_types.definitions"
using namespace opencog;
// library initialization
#if defined(WIN32) && defined(_DLL)
namespace win {
#include <windows.h>
}
win::BOOL APIENTRY DllMain(win::HINSTANCE hinstDLL, // handle to DLL module
win::DWORD fdwReason, // reason for calling function
win::LPVOID lpvReserved) // reserved
{
System::setModuleHandle(hinstDLL);
switch (fdwReason) {
case DLL_PROCESS_ATTACH:
#include "opencog/viterbi/atom_types.inheritance"
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
#elif __GNUC__
static __attribute__ ((constructor)) void viterbi_init(void)
{
#include "opencog/viterbi/atom_types.inheritance"
}
static __attribute__ ((destructor)) void viterbi_fini(void)
{
}
#endif
| /**
* atom_types_init.cc
*
* Link Grammar Atom Types used during Viterbi parsing.
*
* Copyright (c) 2009, 2013 Linas Vepstas <linasvepstas@gmail.com>
*/
#include <opencog/server/Module.h>
#include "opencog/viterbi/atom_types.definitions"
using namespace opencog;
// library initialization
#if defined(WIN32) && defined(_DLL)
namespace win {
#include <windows.h>
}
win::BOOL APIENTRY DllMain(win::HINSTANCE hinstDLL, // handle to DLL module
win::DWORD fdwReason, // reason for calling function
win::LPVOID lpvReserved) // reserved
{
System::setModuleHandle(hinstDLL);
switch (fdwReason) {
case DLL_PROCESS_ATTACH:
#include "opencog/viterbi/atom_types.inheritance"
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
#elif __GNUC__
static __attribute__ ((constructor)) void viterbi_init(void)
{
#include "opencog/viterbi/atom_types.inheritance"
}
static __attribute__ ((destructor)) void viterbi_fini(void)
{
}
#endif
TRIVIAL_MODULE(ViterbiTypesModule)
DECLARE_MODULE(ViterbiTypesModule)
|
Make snippet run successfully again: the snippet for 'eval' was taking m=m.transpose() as an example of code that needs an explicit call to eval(), but that doesn't work anymore now that we have the clever assert detecting aliasing issues. | Matrix2f M = Matrix2f::Random();
Matrix2f m;
m = M;
cout << "Here is the matrix m:" << endl << m << endl;
cout << "Now we want to replace m by its own transpose." << endl;
cout << "If we do m = m.transpose(), then m becomes:" << endl;
m = m.transpose() * 1;
cout << m << endl << "which is wrong!" << endl;
cout << "Now let us instead do m = m.transpose().eval(). Then m becomes" << endl;
m = M;
m = m.transpose().eval();
cout << m << endl << "which is right." << endl;
| Matrix2f M = Matrix2f::Random();
Matrix2f m;
m = M;
cout << "Here is the matrix m:" << endl << m << endl;
cout << "Now we want to copy a column into a row." << endl;
cout << "If we do m.col(1) = m.row(0), then m becomes:" << endl;
m.col(1) = m.row(0);
cout << m << endl << "which is wrong!" << endl;
cout << "Now let us instead do m.col(1) = m.row(0).eval(). Then m becomes" << endl;
m = M;
m.col(1) = m.row(0).eval();
cout << m << endl << "which is right." << endl;
|
Add TimeValue.Win32FILETIME, corresponding to r186374. | //===- llvm/unittest/Support/TimeValueTest.cpp - Time Value tests ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "gtest/gtest.h"
#include "llvm/Support/TimeValue.h"
#include <time.h>
using namespace llvm;
namespace {
TEST(TimeValue, time_t) {
sys::TimeValue now = sys::TimeValue::now();
time_t now_t = time(NULL);
EXPECT_TRUE(abs(static_cast<long>(now_t - now.toEpochTime())) < 2);
}
}
| //===- llvm/unittest/Support/TimeValueTest.cpp - Time Value tests ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "gtest/gtest.h"
#include "llvm/Support/TimeValue.h"
#include <time.h>
using namespace llvm;
namespace {
TEST(TimeValue, time_t) {
sys::TimeValue now = sys::TimeValue::now();
time_t now_t = time(NULL);
EXPECT_TRUE(abs(static_cast<long>(now_t - now.toEpochTime())) < 2);
}
TEST(TimeValue, Win32FILETIME) {
uint64_t epoch_as_filetime = 0x19DB1DED53E8000ULL;
uint32_t ns = 765432100;
sys::TimeValue epoch;
// FILETIME has 100ns of intervals.
uint64_t ft1970 = epoch_as_filetime + ns / 100;
epoch.fromWin32Time(ft1970);
// The "seconds" part in Posix time may be expected as zero.
EXPECT_EQ(ns / 100, epoch.toPosixTime());
// Confirm it reversible.
EXPECT_EQ(ft1970, epoch.toWin32Time());
}
}
|
Add exception if GLEW fails to initialize. |
#include "GLPlatform.hpp"
void glPlatformInit()
{
#ifdef GL_PLATFORM_USING_WIN
glewInit();
#endif
}
|
#include "GLPlatform.hpp"
#include <stdexcept>
void glPlatformInit()
{
#ifdef GL_PLATFORM_USING_WIN
GLenum err = glewInit();
if (GLEW_OK != err)
{
throw std::runtime_error("GLEW failed to initialize.");
}
#endif
}
|
Add executable path on Windows |
#error Still to implement
string executable_path()
{
char buffer[16 * 1024];
int bytes = GetModuleFileName(NULL, buffer, sizeof(buffer));
if (bytes == 0)
{
throw unable_to_find_executable_path{};
}
buffer[bytes] = '\0';
string executable_path{buffer};
return std::string{executable_path.cbegin(),
executable_path.cbegin() +
executable_path.find_last_of('/')};
}
| #include <sdl_cpp/widgets/executable_path.h>
#include <string>
#include "Windows.h"
//#error Still to implement
using namespace ::std;
string executable_path()
{
char buffer[16 * 1024];
int bytes = GetModuleFileName(nullptr, buffer, sizeof(buffer));
if (bytes == 0)
{
throw unable_to_find_executable_path{};
}
buffer[bytes] = '\0';
string executable_path{buffer};
return std::string{executable_path.cbegin(),
executable_path.cbegin() +
executable_path.find_last_of('\\')};
}
|
Fix the names of variables in the tests. | /**
* @file BStringTests.cpp
* @copyright (c) 2014 by Petr Zemek (s3rvac@gmail.com) and contributors
* @license BSD, see the @c LICENSE file for more details
* @brief Tests for the BString class.
*/
#include <gtest/gtest.h>
#include "BString.h"
namespace bencoding {
namespace tests {
using namespace testing;
class BStringTests: public Test {};
TEST_F(BStringTests,
ValueReturnsCorrectValueAfterCreation) {
auto i = BString::create("test");
EXPECT_EQ("test", i->value());
}
TEST_F(BStringTests,
ValueReturnsCorrectValueAfterSet) {
auto i = BString::create("test");
i->setValue("other");
EXPECT_EQ("other", i->value());
}
TEST_F(BStringTests,
LengthReturnsCorrectValue) {
auto i = BString::create("test");
EXPECT_EQ(4, i->length());
}
} // namespace tests
} // namespace bencoding
| /**
* @file BStringTests.cpp
* @copyright (c) 2014 by Petr Zemek (s3rvac@gmail.com) and contributors
* @license BSD, see the @c LICENSE file for more details
* @brief Tests for the BString class.
*/
#include <gtest/gtest.h>
#include "BString.h"
namespace bencoding {
namespace tests {
using namespace testing;
class BStringTests: public Test {};
TEST_F(BStringTests,
ValueReturnsCorrectValueAfterCreation) {
auto s = BString::create("test");
EXPECT_EQ("test", s->value());
}
TEST_F(BStringTests,
ValueReturnsCorrectValueAfterSet) {
auto s = BString::create("test");
s->setValue("other");
EXPECT_EQ("other", s->value());
}
TEST_F(BStringTests,
LengthReturnsCorrectValue) {
auto s = BString::create("test");
EXPECT_EQ(4, s->length());
}
} // namespace tests
} // namespace bencoding
|
Comment out unused mocks to save build time | // Copyright 2015 http://switchdevice.com
#include "Arduino.cc"
#include "EEPROM.cc"
#include "Serial.cc"
#include "SoftwareSerial.cc"
#include "serialHelper.cc"
#include "Spark.cc"
#include "WiFi.cc"
#include "Wire.cc"
#include "SPI.cc"
#include "OneWire.cc"
#include "IRremote.cc"
| // Copyright 2015 http://switchdevice.com
#include "Arduino.cc"
#include "Serial.cc"
#include "serialHelper.cc"
#include "OneWire.cc"
#include "SoftwareSerial.cc"
/* At WiTraC we don't make use of any of the following mocks. They are therefore
* commented out to save precious build time
*/
//#include "EEPROM.cc"
//#include "Spark.cc"
//#include "WiFi.cc"
//#include "Wire.cc"
//#include "SPI.cc"
//#include "IRremote.cc"
|
Add placeholder font code for Windows | #include "rastertext.hpp"
bool RasterText::loadTexture()
{
return true;
}
| #include "rastertext.hpp"
// FIXME: unimplemented
Font::Font(Font const &f)
{ }
Font::~Font()
{ }
Font &Font::operator=(Font const &f)
{
return *this;
}
bool RasterText::loadTexture()
{
return true;
}
|
Update header in recently added file. | /*************************************************************************
*
* REALM CONFIDENTIAL
* __________________
*
* [2011] - [2016] Realm Inc
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Realm Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Realm Incorporated
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Realm Incorporated.
*
**************************************************************************/
#include <realm/util/interprocess_mutex.hpp>
#ifdef REALM_ROBUST_MUTEX_EMULATION
using namespace realm::util;
std::map<File::UniqueID, std::weak_ptr<InterprocessMutex::LockInfo>> InterprocessMutex::s_info_map;
Mutex InterprocessMutex::s_mutex;
#endif
| /*************************************************************************
*
* Copyright 2016 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**************************************************************************/
#include <realm/util/interprocess_mutex.hpp>
#ifdef REALM_ROBUST_MUTEX_EMULATION
using namespace realm::util;
std::map<File::UniqueID, std::weak_ptr<InterprocessMutex::LockInfo>> InterprocessMutex::s_info_map;
Mutex InterprocessMutex::s_mutex;
#endif
|
Update bug reference link in ExtensionApiTest.Toolstrip | // 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"
// Disabled, http://crbug.com/30151.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Toolstrip) {
ASSERT_TRUE(RunExtensionTest("toolstrip")) << 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"
// Disabled, http://crbug.com/30151 (Linux and ChromeOS),
// http://crbug.com/35034 (others).
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Toolstrip) {
ASSERT_TRUE(RunExtensionTest("toolstrip")) << message_;
}
|
Fix broken builds - stubs not stubby enough. | /** @file
@brief Implementation
@date 2014
@author
Ryan Pavlik
<ryan@sensics.com>
<http://sensics.com>
*/
// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)
// Internal Includes
#include <ogvr/PluginKit/DeviceToken.h>
// Library/third-party includes
// - none
// Standard includes
// - none
namespace ogvr {
DeviceToken::DeviceToken(std::string const& name);
DeviceToken::~DeviceToken() {}
AsyncDeviceToken * DeviceToken::asAsyncDevice() {
return NULL;
}
SyncDeviceToken * DeviceToken::asSyncDevice() {
return NULL;
}
} | /** @file
@brief Implementation
@date 2014
@author
Ryan Pavlik
<ryan@sensics.com>
<http://sensics.com>
*/
// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)
// Internal Includes
#include <ogvr/PluginKit/DeviceToken.h>
// Library/third-party includes
// - none
// Standard includes
// - none
namespace ogvr {
DeviceToken::DeviceToken(std::string const &name) : m_name(name) {}
DeviceToken::~DeviceToken() {}
AsyncDeviceToken * DeviceToken::asAsyncDevice() {
return NULL;
}
SyncDeviceToken * DeviceToken::asSyncDevice() {
return NULL;
}
} |
Use range for instead of for | /***************************************************************************
* @file main.cpp
* @author Alan.W
* @date 02 Feb 2014
* 13 Oct 2014
* @remark This code is for the exercises from C++ Primer 5th Edition
* @note
***************************************************************************/
//!
//! Exercise 16.5:
//! Write a template version of the print function from § 6.2.4 (p. 217) that
//! takes a reference to an array and can handle arrays of any size and any
//! element type.
//!
#include <iostream>
#include <string>
/** @note
* 1 any array is essentially a pointer, so the &ref here is a reference to pointer.
* 2 size must be captured here to manage the loop.
*/
template<typename T, unsigned size>
void print(const T(&ref)[size])
{
for (unsigned i = 0; i != size; ++i)
std::cout << ref[i] << std::endl;
}
int main()
{
std::string p[] = {"ssss","aaa","ssssss"};
char c[] = {'a','b','c','d'};
int i[] = {1};
print(i);
print(c);
print(p);
std::cout << "\nexit normally\n";
return 0;
}
| /***************************************************************************
* @file main.cpp
* @author Alan.W
* @date 02 Feb 2014
* 13 Oct 2014
* @remark This code is for the exercises from C++ Primer 5th Edition
* @note
***************************************************************************/
//!
//! Exercise 16.5:
//! Write a template version of the print function from § 6.2.4 (p. 217) that
//! takes a reference to an array and can handle arrays of any size and any
//! element type.
//!
#include <iostream>
#include <string>
template<typename Arr>
void print(const Arr& a)
{
for(const auto& elem : a)
std::cout << elem << std::endl;
}
int main()
{
std::string p[] = {"ssss","aaa","ssssss"};
char c[] = {'a','b','c','d'};
int i[] = {1};
print(i);
print(c);
print(p);
std::cout << "\nexit normally\n";
return 0;
}
|
Remove implementation of pure virtual function. | #include "Renderer.hpp"
#include "../OpenGL/OpenGLRenderer.hpp"
#include "../Vulkan/VulkanRenderer.hpp"
Renderer::~Renderer() {
}
Renderer* Renderer::makeRenderer(BACKEND backend, Window & window){
// Create and return backend.
if(backend == BACKEND::OpenGL)
return new OpenGLRenderer(window);
else if(backend == BACKEND::Vulkan)
return new VulkanRenderer(window);
return nullptr;
}
void Renderer::render() {
}
| #include "Renderer.hpp"
#include "../OpenGL/OpenGLRenderer.hpp"
#include "../Vulkan/VulkanRenderer.hpp"
Renderer::~Renderer() {
}
Renderer* Renderer::makeRenderer(BACKEND backend, Window & window){
// Create and return backend.
if(backend == BACKEND::OpenGL)
return new OpenGLRenderer(window);
else if(backend == BACKEND::Vulkan)
return new VulkanRenderer(window);
return nullptr;
}
|
Make sure to include QDesktopWidget | #include "WindowMaximize.h"
#include "WebPage.h"
#include "WebPageManager.h"
WindowMaximize::WindowMaximize(WebPageManager *manager, QStringList &arguments, QObject *parent) : WindowCommand(manager, arguments, parent) {
}
void WindowMaximize::windowFound(WebPage *page) {
QDesktopWidget *desktop = QApplication::desktop();
QRect area = desktop->availableGeometry();
page->resize(area.width(), area.height());
finish(true);
}
| #include <QDesktopWidget>
#include "WindowMaximize.h"
#include "WebPage.h"
#include "WebPageManager.h"
WindowMaximize::WindowMaximize(WebPageManager *manager, QStringList &arguments, QObject *parent) : WindowCommand(manager, arguments, parent) {
}
void WindowMaximize::windowFound(WebPage *page) {
QDesktopWidget *desktop = QApplication::desktop();
QRect area = desktop->availableGeometry();
page->resize(area.width(), area.height());
finish(true);
}
|
Simplify and fix the partition reader | /*
* PartitionReader.cpp
*
* Created on: 15.02.2013
* Author: Christian Staudt (christian.staudt@kit.edu)
*/
#include "PartitionReader.h"
namespace NetworKit {
Partition PartitionReader::read(std::string path) {
std::ifstream file(path);
// check if file readable
if (!file) {
throw std::runtime_error("invalid clustering file");
}
std::vector<index> temp;
// push all cluster ids into vector in order of appearance
std::string line;
while(std::getline(file, line)) {
index c = std::atoi(line.c_str());
temp.push_back(c);
}
count n = temp.size();
Partition zeta(n);
#pragma omp parallel for
for (node u = 0; u < n; ++u) {
zeta[u] = temp[u];
}
return zeta;
}
} /* namespace NetworKit */
| /*
* PartitionReader.cpp
*
* Created on: 15.02.2013
* Author: Christian Staudt (christian.staudt@kit.edu)
*/
#include "PartitionReader.h"
namespace NetworKit {
Partition PartitionReader::read(std::string path) {
std::ifstream file(path);
// check if file readable
if (!file) {
throw std::runtime_error("invalid clustering file");
}
Partition zeta(0);
std::string line;
index omega = 0;
while(std::getline(file, line)) {
index c = std::atoi(line.c_str());
// extend the partition by one entry and store the cluster id
zeta[zeta.extend()] = c;
omega = std::max(c, omega);
}
zeta.setUpperBound(omega+1);
return zeta;
}
} /* namespace NetworKit */
|
Change default Z-order for packages. | /*
* Qumulus UML editor
* Author: Frank Erens
* Author: Randy Thiemann
*
*/
#include "PackageShape.h"
#include <QtGui/QBrush>
QUML_BEGIN_NAMESPACE_UD
PackageShape::PackageShape(QuUK::Element* e,
DiagramElement* p) :
SelectableShape(e, p),
mTabItem(new QGraphicsRectItem(0, 0, 30, 10, this)),
mBodyItem(new QGraphicsRectItem(0, 10, 100, 50, this)) {
mTabItem->setBrush(QBrush(Qt::white));
mBodyItem->setBrush(QBrush(Qt::white));
addToGroup(mTabItem);
addToGroup(mBodyItem);
}
PackageShape::PackageShape(const PackageShape& c) :
SelectableShape(c) {
}
void PackageShape::resize(double w, double h) {
if(minimumSize().isValid()) {
w = std::max(w, minimumSize().width());
h = std::max(h, minimumSize().height());
}
mBodyItem->setRect(0, 10, w, h - 10);
setSize({w, h});
}
QUML_END_NAMESPACE_UD
| /*
* Qumulus UML editor
* Author: Frank Erens
* Author: Randy Thiemann
*
*/
#include "PackageShape.h"
#include <QtGui/QBrush>
QUML_BEGIN_NAMESPACE_UD
PackageShape::PackageShape(QuUK::Element* e,
DiagramElement* p) :
SelectableShape(e, p),
mTabItem(new QGraphicsRectItem(0, 0, 30, 10, this)),
mBodyItem(new QGraphicsRectItem(0, 10, 100, 50, this)) {
constexpr int kPackageZOrdering = -2;
mTabItem->setBrush(QBrush(Qt::white));
mBodyItem->setBrush(QBrush(Qt::white));
addToGroup(mTabItem);
addToGroup(mBodyItem);
setZValue(kPackageZOrdering);
}
PackageShape::PackageShape(const PackageShape& c) :
SelectableShape(c) {}
void PackageShape::resize(double w, double h) {
if(minimumSize().isValid()) {
w = std::max(w, minimumSize().width());
h = std::max(h, minimumSize().height());
}
mBodyItem->setRect(0, 10, w, h - 10);
setSize({w, h});
}
QUML_END_NAMESPACE_UD
|
Update example for openFrameworks 0.11.0 | #include "ofMain.h"
#include "ofApp.h"
//========================================================================
int main( ){
ofGLWindowSettings settings;
settings.setGLVersion(3, 2); // Using programmable renderer. Comment out this line to use the 'standard' GL renderer.
settings.width = 1024;
settings.height = 768;
ofCreateWindow(settings);
ofRunApp(new ofApp());
}
| #include "ofMain.h"
#include "ofApp.h"
//========================================================================
int main( ){
ofWindowSettings winSettings;
winSettings.setSize(1024, 768);
ofGLWindowSettings glSettings(winSettings);
glSettings.setGLVersion(3, 2); // Using programmable renderer. Comment out this line to use the 'standard' GL renderer.
ofCreateWindow(glSettings);
ofRunApp(new ofApp());
}
|
Fix length calc based on m444x's suggestion. | /* Copyright (c) 2006, NIF File Format Library and Tools
All rights reserved. Please see niflib.h for licence. */
#include "SkinPartition.h"
using namespace Niflib;
//Constructor
SkinPartition::SkinPartition() : numVertices((ushort)0), numTriangles((ushort)0), numBones((ushort)0), numStrips((ushort)0), numWeightsPerVertex((ushort)0), hasVertexMap(false), hasVertexWeights(false), hasStrips(false), hasBoneIndices(false) {};
//Destructor
SkinPartition::~SkinPartition() {};
// needs to be moved elsewhere but this will work for now
ushort SkinPartition::CalcNumTriangles() const {
ushort size = 0;
if (stripLengths.empty()) {
size = (ushort)triangles.size();
} else {
for (size_t i=0; i<stripLengths.size(); ++i)
size += (ushort)stripLengths[i];
size -= 2;
}
return size;
} | /* Copyright (c) 2006, NIF File Format Library and Tools
All rights reserved. Please see niflib.h for licence. */
#include "SkinPartition.h"
using namespace Niflib;
//Constructor
SkinPartition::SkinPartition() : numVertices((ushort)0), numTriangles((ushort)0), numBones((ushort)0), numStrips((ushort)0), numWeightsPerVertex((ushort)0), hasVertexMap(false), hasVertexWeights(false), hasStrips(false), hasBoneIndices(false) {};
//Destructor
SkinPartition::~SkinPartition() {};
// needs to be moved elsewhere but this will work for now
ushort SkinPartition::CalcNumTriangles() const {
ushort size = 0;
if (stripLengths.empty()) {
size = (ushort)triangles.size();
} else {
for (size_t i=0; i<stripLengths.size(); ++i)
size += ((ushort)stripLengths[i] - 2);
}
return size;
} |
Disable shared memory test for OpenCL until bugginess is resolved. | #include <stdio.h>
#include <Halide.h>
using namespace Halide;
int main(int argc, char **argv) {
Var x, y;
Var xo, xi, yo, yi;
Func f, g;
printf("Defining function...\n");
f(x, y) = cast<float>(x);
g(x, y) = f(x+1, y) + f(x-1, y);
Target target = get_jit_target_from_environment();
if (target.has_gpu_feature()) {
Var xi, yi;
g.gpu_tile(x, y, 8, 8, GPU_DEFAULT);
f.compute_at(g, Var("blockidx")).gpu_threads(x, y, GPU_DEFAULT);
}
printf("Realizing function...\n");
Image<float> im = g.realize(32, 32, target);
for (int i = 0; i < 32; i++) {
for (int j = 0; j < 32; j++) {
if (im(i,j) != 2*i) {
printf("im[%d, %d] = %f\n", i, j, im(i,j));
return -1;
}
}
}
printf("Success!\n");
return 0;
}
| #include <stdio.h>
#include <Halide.h>
using namespace Halide;
int main(int argc, char **argv) {
Var x, y;
Var xo, xi, yo, yi;
Func f, g;
printf("Defining function...\n");
f(x, y) = cast<float>(x);
g(x, y) = f(x+1, y) + f(x-1, y);
Target target = get_jit_target_from_environment();
// shared memory not currently working in OpenCL
if (target.features & Target::CUDA) {
Var xi, yi;
g.gpu_tile(x, y, 8, 8, GPU_CUDA);
f.compute_at(g, Var("blockidx")).gpu_threads(x, y, GPU_CUDA);
}
printf("Realizing function...\n");
Image<float> im = g.realize(32, 32, target);
for (int i = 0; i < 32; i++) {
for (int j = 0; j < 32; j++) {
if (im(i,j) != 2*i) {
printf("im[%d, %d] = %f\n", i, j, im(i,j));
return -1;
}
}
}
printf("Success!\n");
return 0;
}
|
Use s prefix for static class vars | /*
* Copyright (c) 2007 Digital Bazaar, Inc. All rights reserved.
*/
#include <iostream>
#include "db/io/OStreamOutputStream.h"
using namespace std;
using namespace db::io;
using namespace db::rt;
OStreamOutputStream* OStreamOutputStream::mStdoutStream =
new OStreamOutputStream(&cout);
OStreamOutputStream::OStreamOutputStream(ostream* stream)
{
// store ostream
mStream = stream;
}
OStreamOutputStream::~OStreamOutputStream()
{
}
bool OStreamOutputStream::write(const char* b, int length)
{
bool rval = false;
// do write
mStream->write(b, length);
// see if a failure has occurred
if(mStream->fail())
{
Exception::setLast(new IOException("Could not write to ostream!"));
}
else
{
rval = true;
}
return rval;
}
OStreamOutputStream* OStreamOutputStream::getStdoutStream()
{
return sStdoutStream;
}
| /*
* Copyright (c) 2007 Digital Bazaar, Inc. All rights reserved.
*/
#include <iostream>
#include "db/io/OStreamOutputStream.h"
using namespace std;
using namespace db::io;
using namespace db::rt;
OStreamOutputStream* OStreamOutputStream::sStdoutStream =
new OStreamOutputStream(&cout);
OStreamOutputStream::OStreamOutputStream(ostream* stream)
{
// store ostream
mStream = stream;
}
OStreamOutputStream::~OStreamOutputStream()
{
}
bool OStreamOutputStream::write(const char* b, int length)
{
bool rval = false;
// do write
mStream->write(b, length);
// see if a failure has occurred
if(mStream->fail())
{
Exception::setLast(new IOException("Could not write to ostream!"));
}
else
{
rval = true;
}
return rval;
}
OStreamOutputStream* OStreamOutputStream::getStdoutStream()
{
return sStdoutStream;
}
|
Fix params passed to i2c.init() to include DEVICE_ADDRESS in the first position. Otherwise SDA becomes SCL_PIN and SCL becomes Default. | #include <esp_log.h>
#include <FreeRTOS.h>
#include <string>
#include <Task.h>
#include <I2C.h>
#include "sdkconfig.h"
#define SDA_PIN 25
#define SCL_PIN 26
//static char tag[] = "task_cpp_utils";
class I2CScanner: public Task {
void run(void *data) override {
I2C i2c;
i2c.init((gpio_num_t)SDA_PIN, (gpio_num_t)SCL_PIN);
i2c.scan();
} // End run
};
static I2CScanner i2cScanner = I2CScanner();
void task_i2c_scanner(void *ignore) {
i2cScanner.start();
FreeRTOS::deleteTask();
}
| #include <esp_log.h>
#include <FreeRTOS.h>
#include <string>
#include <Task.h>
#include <I2C.h>
#include "sdkconfig.h"
#define DEVICE_ADDRESS 0
#define SDA_PIN 25
#define SCL_PIN 26
//static char tag[] = "task_cpp_utils";
class I2CScanner: public Task {
void run(void *data) override {
I2C i2c;
i2c.init((uint8_t)DEVICE_ADDRESS, (gpio_num_t)SDA_PIN, (gpio_num_t)SCL_PIN);
i2c.scan();
} // End run
};
static I2CScanner i2cScanner = I2CScanner();
void task_i2c_scanner(void *ignore) {
i2cScanner.start();
FreeRTOS::deleteTask();
}
|
Fix bug when deletig phone | #include "phonevalidator.h"
PhoneValidator::PhoneValidator(QObject *parent) :
QValidator(parent)
{
}
QValidator::State PhoneValidator::validate(QString &input, int &pos) const
{
//DDD
QRegExp ddd("(\\d{2})+");
if (ddd.exactMatch(input))
{
input.insert(input.length(), ") ");
input.insert(0, "(");
pos = input.length();
}
//Slash
QRegExp slash("\\(\\d{2}\\)\\s*\\d{4}");
if (slash.exactMatch(input))
{
input.insert(input.length(), "-");
pos = input.length();
}
//Separator
QRegExp sep("[\\(]{0,1}[\\d]\{0,2}[\\)]{0,1}\\s*\\d*[\\-]{0,1}\\d*");
if (sep.exactMatch(input))
return QValidator::Acceptable;
return QValidator::Invalid;
}
bool PhoneValidator::isValid(QString str)
{
QRegExp sep("[\\(]{0,1}[\\d]\{0,2}[\\)]{0,1}\\s*\\d*[\\-]{0,1}\\d*");
return sep.exactMatch(str);
}
| #include "phonevalidator.h"
PhoneValidator::PhoneValidator(QObject *parent) :
QValidator(parent)
{
}
QValidator::State PhoneValidator::validate(QString &input, int &pos) const
{
//DDD
QRegExp ddd("(\\d{2})+");
if (ddd.exactMatch(input))
{
input.insert(input.length(), ") ");
input.insert(0, "(");
pos = input.length();
}
//Slash
QRegExp slash("\\(\\d{2}\\)\\s{0,1}\\d{5}");
if (slash.exactMatch(input))
{
input.insert(input.length()-1, "-");
pos = input.length();
}
//Separator
QRegExp sep("[\\(]{0,1}[\\d]\{0,2}[\\)]{0,1}\\s{0,1}\\d*-{0,1}\\d*");
if (sep.exactMatch(input))
return QValidator::Acceptable;
return QValidator::Invalid;
}
bool PhoneValidator::isValid(QString str)
{
QRegExp sep("[\\(]{0,1}[\\d]\{0,2}[\\)]{0,1}\\s*\\d*[\\-]{0,1}\\d*");
return sep.exactMatch(str);
}
|
Update Test Thread to show that wait() and kill() are not working as expected |
/* Test program to test the thread callbacks
*/
#include <iostream>
#include "SDL.hh"
using namespace RAGE;
Logger testlog("testThread");
class ObjectWithThreadCall
{
public:
int threadcall(void* args)
{
testlog << nl << " --- Thread " << SDL::getCurrentThreadID() << "called --- " << std::endl;
return 0;
}
};
int main(int argc, char *argv[])
{
testlog.enableFileLog("testThread.log");
testlog << nl<<"SDL init...";
SDL::App::getInstance();
testlog << nl<<"Creating instance";
ObjectWithThreadCall obj;
testlog << nl<<"Creating instance timer";
SDL::Thread<ObjectWithThreadCall> thread;
thread.setThreadCall(&obj,&ObjectWithThreadCall::threadcall,(void*)NULL);
thread.run();
testlog << nl<<"Waiting for thread to finish" << std::endl;
thread.wait();
return 0;
}
|
/* Test program to test the thread callbacks
*/
#include <iostream>
#include "SDL.hh"
using namespace RAGE;
Logger testlog("testThread");
class ObjectWithThreadCall
{
public:
ObjectWithThreadCall() {}
int threadcall(void* args)
{
testlog << nl << " --- Thread " << SDL::getCurrentThreadID() << "called. Counting from 0 to 20000 --- " << std::endl;
for (int i = 0; i < 20000; i++)
{
testlog << nl << "Iteration N" << i << std::endl;
}
return 0;
}
};
int main(int argc, char *argv[])
{
testlog.enableFileLog("testThread.log");
testlog << nl<<"SDL init...";
SDL::App::getInstance();
testlog << nl<<"Creating instance";
ObjectWithThreadCall * obj = new ObjectWithThreadCall();
testlog << nl<<"Creating instance timer";
SDL::Thread<ObjectWithThreadCall>* thread = new SDL::Thread<ObjectWithThreadCall>();
thread->setThreadCall(obj,&ObjectWithThreadCall::threadcall,(void*)NULL);
thread->run();
testlog << nl<<"Waiting for thread" << std::endl;
thread->wait();
SDL::Delay(3000);
testlog << nl <<"Killing thread: After That No Iteration Should Be Present" << std::endl;
thread->kill();
SDL::Delay(3000);
return 0;
}
|
Fix progress bar rounding issue | #include "utils/progressBar.h"
#include <iostream>
#include <glog/logging.h>
using namespace std;
const std::string ProgressBar::BEGINNING = "[";
const std::string ProgressBar::END = "]";
const std::string ProgressBar::FILLER = "-";
const size_t ProgressBar::LENGTH = 50;
ProgressBar::ProgressBar()
: mProgress(0)
{}
void ProgressBar::setProgress(float progress) {
mProgress = progress;
}
void ProgressBar::print() const {
cout << "\r" << BEGINNING;
const int amountOfFiller = static_cast<int>(mProgress * LENGTH);
for (size_t i = 0; i < amountOfFiller; i++) {
cout << FILLER;
}
LOG_IF(ERROR, amountOfFiller > LENGTH) << "Bad size";
const int remaningSpace = LENGTH - amountOfFiller;
for (size_t i = 0; i < remaningSpace; i++) {
cout << " ";
}
cout << END
<< static_cast<int>(mProgress * 100) << "%"
<< flush;
}
| #include "utils/progressBar.h"
#include <iostream>
#include <cmath>
#include <glog/logging.h>
using namespace std;
const std::string ProgressBar::BEGINNING = "[";
const std::string ProgressBar::END = "]";
const std::string ProgressBar::FILLER = "-";
const size_t ProgressBar::LENGTH = 50;
ProgressBar::ProgressBar()
: mProgress(0)
{}
void ProgressBar::setProgress(float progress) {
mProgress = progress;
}
void ProgressBar::print() const {
cout << "\r" << BEGINNING;
const int amountOfFiller = static_cast<int>(mProgress * LENGTH);
for (size_t i = 0; i < amountOfFiller; i++) {
cout << FILLER;
}
LOG_IF(ERROR, amountOfFiller > LENGTH) << "Bad size";
const int remaningSpace = LENGTH - amountOfFiller;
for (size_t i = 0; i < remaningSpace; i++) {
cout << " ";
}
cout << END
<< round(mProgress * 100) << "%"
<< flush;
}
|
Remove unused reference to threads | #include "framework/applicationcontext.hh"
#include "framework/clientcode.hh"
using Framework::ApplicationContext;
using Framework::ClientCode;
using Framework::LoadClientCode;
using System::thread;
int applicationMain()
{
ClientCode clientCode = LoadClientCode();
ApplicationContext applicationContext;
clientCode.ApplicationThreadEntry(&applicationContext);
return 0;
}
| #include "framework/applicationcontext.hh"
#include "framework/clientcode.hh"
using Framework::ApplicationContext;
using Framework::ClientCode;
using Framework::LoadClientCode;
int applicationMain()
{
ClientCode clientCode = LoadClientCode();
ApplicationContext applicationContext;
clientCode.ApplicationThreadEntry(&applicationContext);
return 0;
}
|
Make sure the env variables are set | #include <QActiveResource.h>
#include <QDebug>
int main()
{
qDebug() << getenv("AR_BASE");
QActiveResource::Resource resource(QUrl(getenv("AR_BASE")), getenv("AR_RESOURCE"));
const QString field = getenv("AR_FIELD");
for(int i = 0; i < 100; i++)
{
qDebug() << i;
foreach(QActiveResource::Record record, resource.find())
{
qDebug() << record[field].toString();
}
}
return 0;
}
| #include <QActiveResource.h>
#include <QDebug>
int main()
{
Q_ASSERT(getenv("AR_BASE") && getenv("AR_RESOURCE") && getenv("AR_FIELD"));
qDebug() << getenv("AR_BASE");
QActiveResource::Resource resource(QUrl(getenv("AR_BASE")), getenv("AR_RESOURCE"));
const QString field = getenv("AR_FIELD");
for(int i = 0; i < 100; i++)
{
qDebug() << i;
foreach(QActiveResource::Record record, resource.find())
{
qDebug() << record[field].toString();
}
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.