Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Add progress for the night | #include "../lib/shared_mem.hpp"
#include <iostream>
std::shared_ptr<cs477::shm_pool> pool;
std::shared_ptr<cs477::bounded_queue<cs477::message, 1024>> rq_queue;
std::shared_ptr<cs477::bounded_queue<cs477::message, 1024>> rp_queue;
int main(int argc, char **argv) {
pool = std::make_shared<cs477::shm_pool>();
pool->create("primes-pool", 4096, 16384);
rq_queue = std::make_shared<cs477::bounded_queue<cs477::message, 1024>>();
rq_queue->create("primes-rq-queue");
rp_queue = std::make_shared<cs477::bounded_queue<cs477::message, 1024>>();
rp_queue->create("primes-rp-queue");
std::cout << "test" << std::endl;
std::cin.get();
return 0;
}
| #include "../lib/shared_mem.hpp"
#include <iostream>
const int PROCESS_COUNT = 3;
std::shared_ptr<cs477::shm_pool> pool;
std::shared_ptr<cs477::bounded_queue<cs477::message, 1024>> rq_queue;
std::shared_ptr<cs477::bounded_queue<cs477::message, 1024>> rp_queue;
int main(int argc, char **argv) {
pool = std::make_shared<cs477::shm_pool>();
pool->create("primes-pool", 4096, 16384);
rq_queue = std::make_shared<cs477::bounded_queue<cs477::message, 1024>>();
rq_queue->create("primes-rq-queue");
rp_queue = std::make_shared<cs477::bounded_queue<cs477::message, 1024>>();
rp_queue->create("primes-rp-queue");
for (auto i = 0; i < PROCESS_COUNT; ++i) {
cs477::buffer prime_block{pool};
prime_block.allocate(4);
rq_queue->write(prime_block.make_message());
}
std::cout << "test" << std::endl;
std::cin.get();
return 0;
}
|
Move some prototypes to prototypes.h. | /* RTcmix - Copyright (C) 2000 The RTcmix Development Team
See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for
the license to this software and for a DISCLAIMER OF ALL WARRANTIES.
*/
#include "../sys/mixerr.h"
extern "C" double checkInsts(char*, double*, short);
extern "C" {
double rtdispatch(char *fname, double *pp, short n_args)
{
double rv;
rv = checkInsts(fname, pp, n_args);
return rv;
}
}
| /* RTcmix - Copyright (C) 2000 The RTcmix Development Team
See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for
the license to this software and for a DISCLAIMER OF ALL WARRANTIES.
*/
#include <prototypes.h>
#include "../sys/mixerr.h"
extern "C" {
double rtdispatch(char *fname, double *pp, short n_args)
{
double rv;
rv = checkInsts(fname, pp, n_args);
return rv;
}
}
|
Add tests for sto() and replace() | #include <wtl/string.hpp>
#include <wtl/exception.hpp>
#include <iostream>
int main() {
std::cout << "__cplusplus: " << __cplusplus << std::endl;
WTL_ASSERT((wtl::split("a b\tc") == std::vector<std::string>{"a", "b", "c"}));
WTL_ASSERT((wtl::split<int>("1 2\t3") == std::vector<int>{1, 2, 3}));
WTL_ASSERT(wtl::strip(" str ") == "str");
WTL_ASSERT(wtl::startswith("prefix", "pre"));
WTL_ASSERT(!wtl::startswith("prefix", "post"));
WTL_ASSERT(wtl::endswith("suffix", "fix"));
WTL_ASSERT(!wtl::endswith("suffix", "suf"));
return 0;
}
| #include <wtl/string.hpp>
#include <wtl/exception.hpp>
#include <iostream>
void test_sto() {
WTL_ASSERT(wtl::sto<bool>("1"));
WTL_ASSERT(wtl::sto<int>("42") == 42);
WTL_ASSERT(wtl::sto<long>("1729") == 1729l);
WTL_ASSERT(wtl::sto<long long>("24601") == 24601ll);
WTL_ASSERT(wtl::sto<unsigned>("42") == 42u);
WTL_ASSERT(wtl::sto<unsigned long>("1729") == 1729ul);
WTL_ASSERT(wtl::sto<unsigned long long>("24601") == 24601ull);
WTL_ASSERT(wtl::sto<double>("3.14") - 3.14 < 1e-9);
}
int main() {
std::cout << "__cplusplus: " << __cplusplus << std::endl;
test_sto();
WTL_ASSERT((wtl::split("a b\tc") == std::vector<std::string>{"a", "b", "c"}));
WTL_ASSERT((wtl::split<int>("1 2\t3") == std::vector<int>{1, 2, 3}));
WTL_ASSERT(wtl::strip(" str ") == "str");
WTL_ASSERT(wtl::startswith("abracadabra", "abr"));
WTL_ASSERT(!wtl::startswith("abracadabra", "bra"));
WTL_ASSERT(wtl::endswith("abracadabra", "bra"));
WTL_ASSERT(!wtl::endswith("abracadabra", "abr"));
WTL_ASSERT(wtl::replace("abracadabra", "br", "_") == "a_acada_a");
return 0;
}
|
Fix segfault with foreign function mappings | #include "llvm/runner.hpp"
Runner::Runner(CompileVisitor::Link v): v(v) {
llvm::InitializeNativeTarget();
llvm::InitializeNativeTargetAsmPrinter();
llvm::InitializeNativeTargetAsmParser();
std::string onError = "";
auto eb = new llvm::EngineBuilder(std::unique_ptr<llvm::Module>(v->getModule()));
engine = eb
->setErrorStr(&onError)
.setEngineKind(llvm::EngineKind::JIT)
.create();
for (const auto& pair : nameToFunPtr) {
engine->addGlobalMapping(v->getModule()->getFunction(pair.first), pair.second);
}
engine->finalizeObject();
if (onError != "") throw InternalError("ExecutionEngine error", {
METADATA_PAIRS,
{"supplied error string", onError}
});
}
int Runner::run() {
return engine->runFunctionAsMain(v->getEntryPoint(), {}, {});
}
ProgramResult Runner::runAndCapture() {
// Capture stdout
char buf[8192];
std::fflush(stdout);
std::freopen("/dev/null", "a", stdout);
std::setbuf(stdout, buf);
// Run program
int exitCode = run();
// Stop capturing stdout
std::freopen("/dev/tty", "a", stdout);
return {exitCode, buf};
}
| #include "llvm/runner.hpp"
Runner::Runner(CompileVisitor::Link v): v(v) {
llvm::InitializeNativeTarget();
llvm::InitializeNativeTargetAsmPrinter();
llvm::InitializeNativeTargetAsmParser();
std::string onError = "";
auto eb = new llvm::EngineBuilder(std::unique_ptr<llvm::Module>(v->getModule()));
engine = eb
->setErrorStr(&onError)
.setEngineKind(llvm::EngineKind::JIT)
.create();
for (const auto& pair : nameToFunPtr) {
auto funPtr = v->getModule()->getFunction(pair.first);
if (funPtr == nullptr) continue; // Function not used
engine->addGlobalMapping(funPtr, pair.second);
}
engine->finalizeObject();
if (onError != "") throw InternalError("ExecutionEngine error", {
METADATA_PAIRS,
{"supplied error string", onError}
});
}
int Runner::run() {
return engine->runFunctionAsMain(v->getEntryPoint(), {}, {});
}
ProgramResult Runner::runAndCapture() {
// Capture stdout
char buf[8192];
std::fflush(stdout);
std::freopen("/dev/null", "a", stdout);
std::setbuf(stdout, buf);
// Run program
int exitCode = run();
// Stop capturing stdout
std::freopen("/dev/tty", "a", stdout);
return {exitCode, buf};
}
|
Fix typo in debug log text | /*
* ModSecurity, http://www.modsecurity.org/
* Copyright (c) 2015 - 2021 Trustwave Holdings, Inc. (http://www.trustwave.com/)
*
* 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
*
* If any of the files related to licensing are missing or if you have any
* other questions related to licensing please contact Trustwave Holdings, Inc.
* directly using the email address security@modsecurity.org.
*
*/
#include "src/actions/set_env.h"
#include <iostream>
#include <string>
#include "modsecurity/transaction.h"
#include "modsecurity/rule.h"
#include "src/utils/string.h"
namespace modsecurity {
namespace actions {
bool SetENV::init(std::string *error) {
return true;
}
bool SetENV::evaluate(RuleWithActions *rule, Transaction *t) {
std::string colNameExpanded(m_string->evaluate(t));
auto pair = utils::string::ssplit_pair(colNameExpanded, '=');
ms_dbg_a(t, 8, "Setting envoriment variable: "
+ pair.first + " to " + pair.second);
setenv(pair.first.c_str(), pair.second.c_str(), /*overwrite*/ 1);
return true;
}
} // namespace actions
} // namespace modsecurity
| /*
* ModSecurity, http://www.modsecurity.org/
* Copyright (c) 2015 - 2021 Trustwave Holdings, Inc. (http://www.trustwave.com/)
*
* 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
*
* If any of the files related to licensing are missing or if you have any
* other questions related to licensing please contact Trustwave Holdings, Inc.
* directly using the email address security@modsecurity.org.
*
*/
#include "src/actions/set_env.h"
#include <iostream>
#include <string>
#include "modsecurity/transaction.h"
#include "modsecurity/rule.h"
#include "src/utils/string.h"
namespace modsecurity {
namespace actions {
bool SetENV::init(std::string *error) {
return true;
}
bool SetENV::evaluate(RuleWithActions *rule, Transaction *t) {
std::string colNameExpanded(m_string->evaluate(t));
auto pair = utils::string::ssplit_pair(colNameExpanded, '=');
ms_dbg_a(t, 8, "Setting environment variable: "
+ pair.first + " to " + pair.second);
setenv(pair.first.c_str(), pair.second.c_str(), /*overwrite*/ 1);
return true;
}
} // namespace actions
} // namespace modsecurity
|
Use SIGHUP instead of SIGUSR1 in test. | // Check that stores in signal handlers are not recorded in origin history.
// This is, in fact, undesired behavior caused by our chained origins
// implementation being not async-signal-safe.
// RUN: %clangxx_msan -fsanitize-memory-track-origins=2 -m64 -O3 %s -o %t && \
// RUN: not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out
// RUN: %clangxx_msan -mllvm -msan-instrumentation-with-call-threshold=0 -fsanitize-memory-track-origins=2 -m64 -O3 %s -o %t && \
// RUN: not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out
#include <signal.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
volatile int x, y;
void SignalHandler(int signo) {
y = x;
}
int main(int argc, char *argv[]) {
int volatile z;
x = z;
signal(SIGUSR1, SignalHandler);
kill(getpid(), SIGUSR1);
signal(SIGUSR1, SIG_DFL);
return y;
}
// CHECK: WARNING: MemorySanitizer: use-of-uninitialized-value
// CHECK-NOT: in SignalHandler
| // Check that stores in signal handlers are not recorded in origin history.
// This is, in fact, undesired behavior caused by our chained origins
// implementation being not async-signal-safe.
// RUN: %clangxx_msan -fsanitize-memory-track-origins=2 -m64 -O3 %s -o %t && \
// RUN: not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out
// RUN: %clangxx_msan -mllvm -msan-instrumentation-with-call-threshold=0 -fsanitize-memory-track-origins=2 -m64 -O3 %s -o %t && \
// RUN: not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out
#include <signal.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
volatile int x, y;
void SignalHandler(int signo) {
y = x;
}
int main(int argc, char *argv[]) {
int volatile z;
x = z;
signal(SIGHUP, SignalHandler);
kill(getpid(), SIGHUP);
signal(SIGHUP, SIG_DFL);
return y;
}
// CHECK: WARNING: MemorySanitizer: use-of-uninitialized-value
// CHECK-NOT: in SignalHandler
|
Increase the base font size for touch ui | // Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "views/controls/menu/menu_config.h"
#include "grit/app_resources.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/base/resource/resource_bundle.h"
namespace views {
// static
MenuConfig* MenuConfig::Create() {
MenuConfig* config = new MenuConfig();
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
config->font = rb.GetFont(ResourceBundle::BaseFont);
config->arrow_width = rb.GetBitmapNamed(IDR_MENU_ARROW)->width();
// Add 4 to force some padding between check and label.
config->check_width = rb.GetBitmapNamed(IDR_MENU_CHECK)->width() + 4;
config->check_height = rb.GetBitmapNamed(IDR_MENU_CHECK)->height();
return config;
}
} // namespace views
| // Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "views/controls/menu/menu_config.h"
#include "grit/app_resources.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/base/resource/resource_bundle.h"
namespace views {
// static
MenuConfig* MenuConfig::Create() {
MenuConfig* config = new MenuConfig();
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
#if defined(TOUCH_UI)
config->font = rb.GetFont(ResourceBundle::LargeFont);
#else
config->font = rb.GetFont(ResourceBundle::BaseFont);
#endif
config->arrow_width = rb.GetBitmapNamed(IDR_MENU_ARROW)->width();
// Add 4 to force some padding between check and label.
config->check_width = rb.GetBitmapNamed(IDR_MENU_CHECK)->width() + 4;
config->check_height = rb.GetBitmapNamed(IDR_MENU_CHECK)->height();
return config;
}
} // namespace views
|
Make use of range based for loop | /*
* SimNetworkFunctions.cpp
*
* Created on: 18.04.2016
* Author: Marc Hartung
*/
#include "../../include/network_impl/SimNetworkFunctions.hpp"
#include <iostream>
namespace NetOff
{
std::string createStringFromData(const char * data)
{
size_t num = getIntegralFromData<size_t>(data);
const char * start = shift<size_t>(data);
std::string res(start, num);
return res;
}
size_t getStringDataSize(const std::string & str)
{
return sizeof(size_t) + sizeof(char) * (str.size() + 1); // first is for saving how many chars will be there
}
size_t saveStringInData(const std::string & str, char * data)
{
char * p = saveShiftIntegralInData<size_t>(str.size(),data);
for (size_t i = 0; i < str.size(); ++i)
{
*p = str[i];
++p;
}
return getStringDataSize(str);
}
}
| /*
* SimNetworkFunctions.cpp
*
* Created on: 18.04.2016
* Author: Marc Hartung
*/
#include "network_impl/SimNetworkFunctions.hpp"
#include <iostream>
namespace NetOff
{
std::string createStringFromData(const char * data)
{
size_t num = getIntegralFromData<size_t>(data);
const char * start = shift<size_t>(data);
std::string res(start, num);
return res;
}
size_t getStringDataSize(const std::string & str)
{
return sizeof(size_t) + sizeof(char) * (str.size() + 1); // first is for saving how many chars will be there
}
size_t saveStringInData(const std::string & str, char * data)
{
char * p = saveShiftIntegralInData<size_t>(str.size(), data);
for (auto& elem : str)
{
*p = elem;
++p;
}
return getStringDataSize(str);
}
} /* End namespace NetOff */
|
Fix CrOS Official build from options2 copy. | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/options2/chromeos/stats_options_handler.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "content/public/browser/user_metrics.h"
namespace chromeos {
StatsOptionsHandler::StatsOptionsHandler() {
}
// OptionsPageUIHandler implementation.
void StatsOptionsHandler::GetLocalizedValues(
DictionaryValue* localized_strings) {
}
void StatsOptionsHandler::Initialize() {
}
// WebUIMessageHandler implementation.
void StatsOptionsHandler::RegisterMessages() {
web_ui_->RegisterMessageCallback("metricsReportingCheckboxAction",
base::Bind(&StatsOptionsHandler::HandleMetricsReportingCheckbox,
base::Unretained(this)));
}
void StatsOptionsHandler::HandleMetricsReportingCheckbox(
const ListValue* args) {
#if defined(GOOGLE_CHROME_BUILD)
const std::string checked_str = UTF16ToUTF8(ExtractStringValue(args));
const bool enabled = (checked_str == "true");
UserMetrics::RecordAction(
enabled ?
UserMetricsAction("Options_MetricsReportingCheckbox_Enable") :
UserMetricsAction("Options_MetricsReportingCheckbox_Disable"));
#endif
}
} // namespace chromeos
| // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/options2/chromeos/stats_options_handler.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "content/public/browser/user_metrics.h"
using content::UserMetricsAction;
namespace chromeos {
StatsOptionsHandler::StatsOptionsHandler() {
}
// OptionsPageUIHandler implementation.
void StatsOptionsHandler::GetLocalizedValues(
DictionaryValue* localized_strings) {
}
void StatsOptionsHandler::Initialize() {
}
// WebUIMessageHandler implementation.
void StatsOptionsHandler::RegisterMessages() {
web_ui_->RegisterMessageCallback("metricsReportingCheckboxAction",
base::Bind(&StatsOptionsHandler::HandleMetricsReportingCheckbox,
base::Unretained(this)));
}
void StatsOptionsHandler::HandleMetricsReportingCheckbox(
const ListValue* args) {
#if defined(GOOGLE_CHROME_BUILD)
const std::string checked_str = UTF16ToUTF8(ExtractStringValue(args));
const bool enabled = (checked_str == "true");
content::RecordAction(
enabled ?
UserMetricsAction("Options_MetricsReportingCheckbox_Enable") :
UserMetricsAction("Options_MetricsReportingCheckbox_Disable"));
#endif
}
} // namespace chromeos
|
Fix final condition in test | #include "Limiter.h"
#include "Testing.h"
#include <iostream>
auto TestWithPeakLoadInTheBeginning(int maxAllowedRps)
{
const auto startTime = std::chrono::steady_clock::now();
int sentRequestsCount = 0;
Limiter limiter(maxAllowedRps, 100);
for (; sentRequestsCount < maxAllowedRps; ++sentRequestsCount)
{
ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok);
}
if (std::chrono::steady_clock::now() < startTime + std::chrono::seconds())
{
ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests);
}
}
namespace LimiterSpecs
{
static constexpr int minRPS = 1;
static constexpr int maxRPS = 100'000;
};
int main()
{
try
{
TestWithPeakLoadInTheBeginning(LimiterSpecs::maxRPS);
std::cout << "All Tests passed successfully\n";
}
catch (AssertionException& e)
{
std::cout << "One or more of tests failed: " << e.what() << '\n';
}
system("pause");
return 0;
}
| #include "Limiter.h"
#include "Testing.h"
#include <iostream>
auto TestWithPeakLoadInTheBeginning(int maxAllowedRps)
{
const auto startTime = std::chrono::steady_clock::now();
int sentRequestsCount = 0;
Limiter limiter(maxAllowedRps, 10000);
for (; sentRequestsCount < maxAllowedRps; ++sentRequestsCount)
{
ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok);
}
auto expectedEndResult = std::chrono::steady_clock::now() < startTime + std::chrono::milliseconds(500)
? HttpResult::Code::Ok
: HttpResult::Code::TooManyRequests;
while (std::chrono::steady_clock::now() < startTime + std::chrono::seconds(1))
{
ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests);
}
ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests);
std::this_thread::sleep_until(startTime + std::chrono::milliseconds(1500));
ASSERT_EQUAL(limiter.ValidateRequest(), expectedEndResult);
}
namespace LimiterSpecs
{
static constexpr int minRPS = 1;
static constexpr int maxRPS = 100'000;
};
int main()
{
try
{
TestWithPeakLoadInTheBeginning(LimiterSpecs::maxRPS);
std::cout << "All Tests passed successfully\n";
}
catch (AssertionException& e)
{
std::cout << "One or more of tests failed: " << e.what() << '\n';
}
system("pause");
return 0;
}
|
Add comment about linking place | #include<iostream>
#include<boost/filesystem.hpp>
using namespace boost::filesystem;
//bool CopyDir(path const & source_path, path const & destination_path);
int main(int argc, char *argv[])
{
if(argc < 3)
{
std::cout << "USAGE " << argv[0] << " source destination" << std::endl;
return 1;
}
else
{
path source_path = argv[1];
path destination_path = argv[2];
if(exists(source_path))
{
if(is_regular_file(source_path) == true)
{
copy_file(source_path, destination_path);
std::cout << "File has been copied" << std::endl;
}
else if(is_directory(source_path) == true)
{
copy_directory(source_path, destination_path);
std::cout << "Directory has been copied" << std::endl;
}
else
{
std::cerr << "It seems like the specified directory does not exist." << std::endl;
}
}
else
{
std::cerr << "The specified directory could not be found" << std::endl;
}
}
return 0;
}
| #include<iostream>
#include<boost/filesystem.hpp>
using namespace boost::filesystem;
//bool CopyDir(path const & source_path, path const & destination_path);
int main(int argc, char *argv[])
{
if(argc < 3)
{
std::cout << "USAGE " << argv[0] << " source destination" << std::endl;
return 1;
}
else
{
path source_path = argv[1];
path destination_path = argv[2];
if(exists(source_path))
{
if(is_regular_file(source_path) == true)
{
copy_file(source_path, destination_path); //Link dest path to buffer
std::cout << "File has been copied" << std::endl;
}
else if(is_directory(source_path) == true)
{
copy_directory(source_path, destination_path);
std::cout << "Directory has been copied" << std::endl;
}
else
{
std::cerr << "It seems like the specified directory does not exist." << std::endl;
}
}
else
{
std::cerr << "The specified directory could not be found" << std::endl;
}
}
return 0;
}
|
Add the missing FileCheck invocation to this testcase. | // RUN: %clang_cc1 %s -triple i386-pc-windows-msvc19.0.0 -emit-obj \
// RUN: -debug-info-kind=line-tables-only -fms-extensions
class __declspec(dllexport) A {
A(int * = new int) {}
};
// CHECK: define {{.*}}void @"\01??_FA@@AAEXXZ"
// CHECK-SAME: !dbg ![[SP:[0-9]+]]
// CHECK-NOT: {{ret }}
// CHECK: call x86_thiscallcc %class.A* @"\01??0A@@AAE@PAH@Z"(%class.A* %this1, i32* %0)
// CHECK-SAME: !dbg ![[DBG:[0-9]+]]
// CHECK: ret void, !dbg ![[DBG]]
//
// CHECK: ![[SP]] = distinct !DISubprogram(
// CHECK-SAME: line: 3
// CHECK-SAME: isDefinition: true
// CHECK-SAME: DIFlagArtificial
// CHECK-SAME: ){{$}}
//
// CHECK: ![[DBG]] = !DILocation(line: 0
| // RUN: %clang_cc1 %s -triple i386-pc-windows-msvc19.0.0 -emit-llvm \
// RUN: -debug-info-kind=line-tables-only -fms-extensions -o - | FileCheck %s
class __declspec(dllexport) A {
A(int * = new int) {}
};
// CHECK: define {{.*}}void @"\01??_FA@@AAEXXZ"
// CHECK-SAME: !dbg ![[SP:[0-9]+]]
// CHECK-NOT: {{ret }}
// CHECK: call x86_thiscallcc %class.A* @"\01??0A@@AAE@PAH@Z"(%class.A* %this1, i32* %0)
// CHECK-SAME: !dbg ![[DBG:[0-9]+]]
// CHECK: ret void, !dbg ![[DBG1:[0-9]+]]
//
// CHECK: ![[SP]] = distinct !DISubprogram(
// CHECK-SAME: line: 4
// CHECK-SAME: isDefinition: true
// CHECK-SAME: DIFlagArtificial
// CHECK-SAME: ){{$}}
//
// CHECK: ![[DBG1]] = !DILocation(line: 0
// CHECK: ![[DBG]] = !DILocation(line: 0
|
Add a special condition so that static analyzers could write the exact condition when problem happens |
int main()
{
int *a;
int *n = a;
a = n;
*n = 5;
return 0;
} | #include <stdio.h>
int main()
{
int input;
if (scanf("%d", &input) == 1)
{
if (input == 2)
{
int *a;
int *n = a;
a = n;
*n = 5;
}
else
{
printf("OK\n");
}
}
return 0;
} |
Test empty and non-empty queue. | extern "C"
{
#include "packet_queue.h"
#include "error.h"
#include "nrf51.h"
#include "nrf51_bitfields.h"
}
#include "CppUTest/TestHarness.h"
TEST_GROUP(packet_queue)
{
void setup(void)
{
}
void teardown(void)
{
}
};
TEST(packet_queue, test_packet_queue_init_succeed)
{
packet_queue_t queue;
LONGS_EQUAL(SUCCESS, packet_queue_init(&queue));
}
| 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));
}
|
Remove pragma from source file |
#pragma once
#include <threadingzeug/parallelfor.h>
namespace threadingzeug
{
int getNumberOfThreads()
{
return std::max(static_cast<size_t>(2), static_cast<size_t>(std::thread::hardware_concurrency()));
}
} // namespace threadingzeug
|
#include <threadingzeug/parallelfor.h>
namespace threadingzeug
{
int getNumberOfThreads()
{
return std::max(static_cast<size_t>(2), static_cast<size_t>(std::thread::hardware_concurrency()));
}
} // namespace threadingzeug
|
Fix registration for Neg kernel. | /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/kernels/mlir_generated/unranked_op_gpu_base.h"
namespace tensorflow {
GENERATE_AND_REGISTER_UNARY_KERNEL(Neg, f16, DT_HALF, Eigen::half);
GENERATE_AND_REGISTER_UNARY_KERNEL(Neg, f32, DT_FLOAT, float);
GENERATE_AND_REGISTER_UNARY_KERNEL(Neg, f64, DT_DOUBLE, double);
GENERATE_AND_REGISTER_UNARY_KERNEL(Neg, i8, DT_INT8, int8);
GENERATE_AND_REGISTER_UNARY_KERNEL(Neg, i16, DT_DOUBLE, int16);
// TODO(b/25387198): We cannot use a regular GPU kernel for int32.
GENERATE_AND_REGISTER_UNARY_KERNEL(Neg, i64, DT_DOUBLE, int64);
} // namespace tensorflow
| /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/kernels/mlir_generated/unranked_op_gpu_base.h"
namespace tensorflow {
GENERATE_AND_REGISTER_UNARY_KERNEL(Neg, f16, DT_HALF, Eigen::half);
GENERATE_AND_REGISTER_UNARY_KERNEL(Neg, f32, DT_FLOAT, float);
GENERATE_AND_REGISTER_UNARY_KERNEL(Neg, f64, DT_DOUBLE, double);
GENERATE_AND_REGISTER_UNARY_KERNEL(Neg, i8, DT_INT8, int8);
GENERATE_AND_REGISTER_UNARY_KERNEL(Neg, i16, DT_INT16, int16);
// TODO(b/25387198): We cannot use a regular GPU kernel for int32.
GENERATE_AND_REGISTER_UNARY_KERNEL(Neg, i64, DT_INT64, int64);
} // namespace tensorflow
|
Add an XFAIL for Newlib's missing uchar.h | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// XFAIL: apple-darwin
// <uchar.h>
#include <uchar.h>
int main()
{
}
| //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// XFAIL: apple-darwin
// XFAIL: newlib
// <uchar.h>
#include <uchar.h>
int main()
{
}
|
Add line break before "Failures:" | #include <iostream>
#include <ccspec/core/formatters/text_formatter.h>
namespace ccspec {
namespace core {
namespace formatters {
using std::endl;
using std::exception;
using std::exception_ptr;
using std::list;
using std::ostream;
using std::rethrow_exception;
// Public methods.
void TextFormatter::afterEachHookFailed(exception_ptr failure) const {
output_ << "An error occurred in an `after(:example)` hook" << endl;
outputException(failure);
}
void TextFormatter::afterAllHookFailed(exception_ptr failure) const {
output_ << "An error occurred in an `after(:context)` hook" << endl;
outputException(failure);
}
void TextFormatter::aroundHookFailed(exception_ptr failure) const {
output_ << "An error occurred in an `around(:example)` hook" << endl;
outputException(failure);
}
void TextFormatter::dumpFailures(const list<exception_ptr>& failures) const {
if (failures.empty())
return;
output_ << "Failures:" << endl;
for (auto failure : failures)
outputException(failure);
}
// Protected methods.
TextFormatter::TextFormatter(ostream& output) : Formatter(output) {}
// Private methods.
void TextFormatter::outputException(exception_ptr failure) const {
try {
rethrow_exception(failure);
} catch (const exception& e) {
output_ << e.what() << endl;
}
}
} // namespace formatters
} // namespace core
} // namespace ccspec
| #include <iostream>
#include <ccspec/core/formatters/text_formatter.h>
namespace ccspec {
namespace core {
namespace formatters {
using std::endl;
using std::exception;
using std::exception_ptr;
using std::list;
using std::ostream;
using std::rethrow_exception;
// Public methods.
void TextFormatter::afterEachHookFailed(exception_ptr failure) const {
output_ << "An error occurred in an `after(:example)` hook" << endl;
outputException(failure);
}
void TextFormatter::afterAllHookFailed(exception_ptr failure) const {
output_ << "An error occurred in an `after(:context)` hook" << endl;
outputException(failure);
}
void TextFormatter::aroundHookFailed(exception_ptr failure) const {
output_ << "An error occurred in an `around(:example)` hook" << endl;
outputException(failure);
}
void TextFormatter::dumpFailures(const list<exception_ptr>& failures) const {
if (failures.empty())
return;
output_ << endl << "Failures:" << endl;
for (auto failure : failures)
outputException(failure);
}
// Protected methods.
TextFormatter::TextFormatter(ostream& output) : Formatter(output) {}
// Private methods.
void TextFormatter::outputException(exception_ptr failure) const {
try {
rethrow_exception(failure);
} catch (const exception& e) {
output_ << e.what() << endl;
}
}
} // namespace formatters
} // namespace core
} // namespace ccspec
|
Mark SessionRestoureApis as flaky on chromium os | // 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_apitest.h"
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, SessionRestoreApis) {
ASSERT_TRUE(RunExtensionSubtest("session_restore",
"session_restore.html")) << message_;
}
| // 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_apitest.h"
// Flaky on ChromeOS http://crbug.com/251199
#if defined(OS_CHROMEOS)
#define MAYBE_SessionRestoreApis DISABLED_SessionRestoreApis
#else
#define MAYBE_SessionRestoreApis SessionRestoreApis
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_SessionRestoreApis) {
ASSERT_TRUE(RunExtensionSubtest("session_restore",
"session_restore.html")) << message_;
}
|
Fix compilation warning when checking for writable directory | // Copyright 2004-present Facebook. All Rights Reserved.
#include "ApkManager.h"
#include <boost/filesystem.hpp>
#include <iostream>
#include <sstream>
namespace {
bool check_directory(std::string& apkdir) {
if (!boost::filesystem::is_directory(apkdir.c_str())) {
std::cerr << "error: apkdir is not a writable directory: " << apkdir
<< std::endl;
exit(EXIT_FAILURE);
}
}
}
FILE* ApkManager::new_asset_file(const char* filename) {
check_directory(m_apk_dir);
std::ostringstream path;
path << m_apk_dir << "/assets/";
if (!boost::filesystem::is_directory(path.str().c_str())) {
std::cerr << "error: assets dir is not a writable directory: " << path.str()
<< std::endl;
exit(EXIT_FAILURE);
}
path << filename;
FILE* fd = fopen(path.str().c_str(), "w");
if (fd != nullptr) {
m_files.emplace_back(fd);
} else {
perror("Error creating new asset file");
}
return fd;
}
| // Copyright 2004-present Facebook. All Rights Reserved.
#include "ApkManager.h"
#include <boost/filesystem.hpp>
#include <iostream>
#include <sstream>
namespace {
void check_directory(std::string& dir) {
if (!boost::filesystem::is_directory(dir.c_str())) {
std::cerr << "error: not a writable directory: " << dir
<< std::endl;
exit(EXIT_FAILURE);
}
}
}
FILE* ApkManager::new_asset_file(const char* filename) {
check_directory(m_apk_dir);
std::ostringstream path;
path << m_apk_dir << "/assets/";
std::string assets_dir = path.str();
check_directory(assets_dir);
path << filename;
FILE* fd = fopen(path.str().c_str(), "w");
if (fd != nullptr) {
m_files.emplace_back(fd);
} else {
perror("Error creating new asset file");
}
return fd;
}
|
Read commands from stdin "forever" | #include <iostream>
#include <string>
std::string parse_command(const std::string& input) {
return input.substr(0, input.find(' '));
}
int main() {
std::cout << "PUCRS FAT16 SHELL\n";
std::cout << "$ ";
std::string cmd;
getline (std::cin, cmd);
std::cout << "-> Will execute: " << parse_command(cmd) << "\n";
}
| #include <iostream>
#include <string>
std::string parse_command(const std::string& input) {
return input.substr(0, input.find(' '));
}
int main() {
std::cout << "PUCRS FAT16 SHELL\n";
while (true) {
std::cout << "$ ";
std::string cmd;
getline (std::cin, cmd);
std::cout << "-> Will execute: " << parse_command(cmd) << "\n";
}
}
|
Check if we have enough arguments | #include <dns_sd.h>
#include <ev++.h>
int main(int argc, char *argv[]) {
(void)argc;
(void)argv;
return 0;
}
| #include <iostream>
#include <dns_sd.h>
#include <ev++.h>
#include "build_version.h"
int main(int argc, char *argv[]) {
if (2 != argc) {
std::cerr << argv[0] << " <announce file>" << std::endl;
std::cerr << "Version: " << VERSION << std::endl;
return -1;
}
return 0;
}
|
Comment out test, need to refactor | #include "Assignment.h"
#include "Course.h"
#include <cstdio>
#include <iostream>
using namespace std;
int main() {
if (remove("test-0.sqlite") != 0) {
cout << "Error with deletion of database file\n";
} else {
cout << "Database file successfully deleted\n";
}
// test instantiation of a Course object.
cout << "Testing instantiation of a Course object:" << endl;
Course course("test-0");
cout << "Created " << course.getName() << endl;
cout << "All Assignments: " << course.assignments.size() << endl;
cout << "All Categories: " << course.categories.size() << endl;
cout << "All Students: " << course.students.size() << endl;
cout << "All Submitted: " << course.submitted.size() << endl;
// Test adding items to the db
Category c1(0, "Homework", 20, course.getDb());
Category c2(0, "Labs", 30, course.getDb());
Category c3(0, "Exams", 50, course.getDb());
c1.insert();
c2.insert();
c3.insert();
course.categories[c1.getId()] = &c1;
course.categories[c2.getId()] = &c2;
course.categories[c3.getId()] = &c3;
for (auto it : course.categories) {
cout << it.first << " " << it.second->getName() << endl;
}
}
| #include "Assignment.h"
#include "Course.h"
#include <cstdio>
#include <iostream>
using namespace std;
int main() {
if (remove("test-0.sqlite") != 0) {
cout << "Error with deletion of database file\n";
} else {
cout << "Database file successfully deleted\n";
}
// test instantiation of a Course object.
cout << "Testing instantiation of a Course object:" << endl;
Course course("test-0");
cout << "Created " << course.getName() << endl;
// cout << "All Assignments: " << course.assignments.size() << endl;
// cout << "All Categories: " << course.categories.size() << endl;
// cout << "All Students: " << course.students.size() << endl;
// cout << "All Submitted: " << course.submitted.size() << endl;
// // Test adding items to the db
// Category c1(0, "Homework", 20, course.getDb());
// Category c2(0, "Labs", 30, course.getDb());
// Category c3(0, "Exams", 50, course.getDb());
// c1.insert();
// c2.insert();
// c3.insert();
// course.categories[c1.getId()] = &c1;
// course.categories[c2.getId()] = &c2;
// course.categories[c3.getId()] = &c3;
// for (auto it : course.categories) {
// cout << it.first << " " << it.second->getName() << endl;
// }
}
|
Add setup/cleanup for bundle test unit | /* ***** BEGIN LICENSE BLOCK *****
* Sconspiracy - Copyright (C) IRCAD, 2004-2010.
* Distributed under the terms of the BSD Licence as
* published by the Open Source Initiative.
* ****** END LICENSE BLOCK ****** */
MiniLauncher::MiniLauncher( ::boost::filesystem::path profilePath )
{
::boost::filesystem::path cwd = ::boost::filesystem::current_path();
::boost::filesystem::path bundlePath = cwd / "Bundles";
::fwRuntime::addBundles(bundlePath);
if (!::boost::filesystem::exists( profilePath ))
{
profilePath = cwd / profilePath;
}
if (!::boost::filesystem::exists( profilePath ))
{
throw (std::invalid_argument("<" + profilePath.string() + "> not found." ));
}
m_profile = ::fwRuntime::io::ProfileReader::createProfile(profilePath);
::fwRuntime::profile::setCurrentProfile(m_profile);
m_profile->setParams(0, NULL);
m_profile->start();
// m_profile->run();
}
MiniLauncher::~MiniLauncher()
{
m_profile->stop();
m_profile.reset();
::fwRuntime::profile::setCurrentProfile(m_profile);
}
| /* ***** BEGIN LICENSE BLOCK *****
* Sconspiracy - Copyright (C) IRCAD, 2004-2010.
* Distributed under the terms of the BSD Licence as
* published by the Open Source Initiative.
* ****** END LICENSE BLOCK ****** */
MiniLauncher::MiniLauncher( ::boost::filesystem::path profilePath )
{
::boost::filesystem::path cwd = ::boost::filesystem::current_path();
::boost::filesystem::path bundlePath = cwd / "Bundles";
::fwRuntime::addBundles(bundlePath);
if (!::boost::filesystem::exists( profilePath ))
{
profilePath = cwd / profilePath;
}
if (!::boost::filesystem::exists( profilePath ))
{
throw (std::invalid_argument("<" + profilePath.string() + "> not found." ));
}
m_profile = ::fwRuntime::io::ProfileReader::createProfile(profilePath);
::fwRuntime::profile::setCurrentProfile(m_profile);
m_profile->setParams(0, NULL);
m_profile->start();
::fwRuntime::profile::getCurrentProfile()->setup();
// m_profile->run();
}
MiniLauncher::~MiniLauncher()
{
::fwRuntime::profile::getCurrentProfile()->cleanup();
m_profile->stop();
m_profile.reset();
::fwRuntime::profile::setCurrentProfile(m_profile);
}
|
Initialize seed for better random numbers. | #include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "System/management.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
// Create management object and register it as context property
Management *man = new Management();
engine.rootContext()->setContextProperty("management", man);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
QObject *canvas = engine.rootObjects().first()->findChild<QObject*>("canvas");
man->initialize(&engine, canvas);
return app.exec();
}
| #include <ctime>
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "System/management.h"
int main(int argc, char *argv[]) {
srand((unsigned)time(NULL));
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
// Create management object and register it as context property
Management *man = new Management();
engine.rootContext()->setContextProperty("management", man);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
QObject *canvas = engine.rootObjects().first()->findChild<QObject*>("canvas");
man->initialize(&engine, canvas);
return app.exec();
}
|
Allow logger to use STDERR | #include <iomanip>
#include <iostream>
#include <boost/log/trivial.hpp>
#include <boost/log/utility/setup/console.hpp>
static void color_fmt(boost::log::record_view const& rec, boost::log::formatting_ostream& strm) {
auto severity = rec[boost::log::trivial::severity];
bool color = false;
if (severity) {
switch (severity.get()) {
case boost::log::trivial::warning:
strm << "\033[33m";
color = true;
break;
case boost::log::trivial::error:
case boost::log::trivial::fatal:
strm << "\033[31m";
color = true;
break;
default:
break;
}
}
// setw(7) = the longest log level. eg "warning"
strm << std::setw(7) << std::setfill(' ') << severity << ": " << rec[boost::log::expressions::smessage];
if (color) {
strm << "\033[0m";
}
}
void logger_init_sink(bool use_colors = false) {
auto sink = boost::log::add_console_log(std::cout, boost::log::keywords::format = "%Message%",
boost::log::keywords::auto_flush = true);
if (use_colors) {
sink->set_formatter(&color_fmt);
}
}
| #include <iomanip>
#include <iostream>
#include <boost/log/trivial.hpp>
#include <boost/log/utility/setup/console.hpp>
static void color_fmt(boost::log::record_view const& rec, boost::log::formatting_ostream& strm) {
auto severity = rec[boost::log::trivial::severity];
bool color = false;
if (severity) {
switch (severity.get()) {
case boost::log::trivial::warning:
strm << "\033[33m";
color = true;
break;
case boost::log::trivial::error:
case boost::log::trivial::fatal:
strm << "\033[31m";
color = true;
break;
default:
break;
}
}
// setw(7) = the longest log level. eg "warning"
strm << std::setw(7) << std::setfill(' ') << severity << ": " << rec[boost::log::expressions::smessage];
if (color) {
strm << "\033[0m";
}
}
void logger_init_sink(bool use_colors = false) {
auto stream = &std::cerr;
if (getenv("LOG_STDERR") == nullptr) {
stream = &std::cout;
}
auto sink = boost::log::add_console_log(*stream, boost::log::keywords::format = "%Message%",
boost::log::keywords::auto_flush = true);
if (use_colors) {
sink->set_formatter(&color_fmt);
}
}
|
Throw standard exception on illegal row access | ////////////////////////////////////////////////////////////////////////////
//
// 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.hpp>
#include "error_handling.hpp"
#include "marshalling.hpp"
#include "realm_export_decls.hpp"
using namespace realm;
using namespace realm::binding;
extern "C" {
REALM_EXPORT void row_destroy(Row* row_ptr)
{
handle_errors([&]() {
delete row_ptr;
});
}
REALM_EXPORT size_t row_get_row_index(const Row* row_ptr)
{
return handle_errors([&]() {
return row_ptr->get_index();
});
}
REALM_EXPORT size_t row_get_is_attached(const Row* row_ptr)
{
return handle_errors([&]() {
return bool_to_size_t(row_ptr->is_attached());
});
}
} // extern "C"
| ////////////////////////////////////////////////////////////////////////////
//
// 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.hpp>
#include "error_handling.hpp"
#include "marshalling.hpp"
#include "realm_export_decls.hpp"
using namespace realm;
using namespace realm::binding;
extern "C" {
REALM_EXPORT void row_destroy(Row* row_ptr)
{
handle_errors([&]() {
delete row_ptr;
});
}
REALM_EXPORT size_t row_get_row_index(const Row* row_ptr)
{
return handle_errors([&]() {
if (!row_ptr->is_attached())
throw std::exception();
return row_ptr->get_index();
});
}
REALM_EXPORT size_t row_get_is_attached(const Row* row_ptr)
{
return handle_errors([&]() {
return bool_to_size_t(row_ptr->is_attached());
});
}
} // extern "C"
|
Use FFmpeg mp4 codec for output | #include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main() {
VideoCapture cap(0);
if (!cap.isOpened()) {
cout << "Error opening webcam" << endl;
return -1;
}
int frame_width = cap.get(CV_CAP_PROP_FRAME_WIDTH);
int frame_height = cap.get(CV_CAP_PROP_FRAME_HEIGHT);
VideoWriter video("out.avi", CV_FOURCC('M', 'J', 'P', 'G'), 10, Size(frame_width, frame_height), true);
for (;;) {
Mat frame;
cap >> frame;
video.write(frame);
// imshow("Frame", frame);
if (waitKey(1) == 27) {
break;
}
}
return 0;
}
| #include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main() {
VideoCapture cap(0);
if (!cap.isOpened()) {
cout << "Error opening webcam" << endl;
return -1;
}
int frame_width = cap.get(CV_CAP_PROP_FRAME_WIDTH);
int frame_height = cap.get(CV_CAP_PROP_FRAME_HEIGHT);
int four_cc = CV_FOURCC('F', 'M', 'P', '4');
VideoWriter video("out.avi", four_cc, 10, Size(frame_width, frame_height), true);
for (;;) {
Mat frame;
cap >> frame;
video.write(frame);
// imshow("Frame", frame);
if (waitKey(1) == 27) {
break;
}
}
return 0;
}
|
Include the header for safety. | /*
* msg - user messages - implementation
* Copyright(c) 2004 of wave++ (Yuri D'Elia) <wavexx@users.sf.net>
* Distributed under GNU LGPL without ANY warranty.
*/
// c system headers
#include <stdarg.h>
#include <cstdio>
using std::vfprintf;
using std::fprintf;
// data
const char* prg;
bool verbose = false;
// implementation
void
err(const char* fmt, ...)
{
va_list params;
fprintf(stderr, "%s: ", prg);
va_start(params, fmt);
vfprintf(stderr, fmt, params);
va_end(params);
fprintf(stderr, "\n");
}
void
msg(const char* fmt, ...)
{
if(!verbose)
return;
va_list params;
fprintf(stderr, "%s: ", prg);
va_start(params, fmt);
vfprintf(stderr, fmt, params);
va_end(params);
fprintf(stderr, "\n");
}
| /*
* msg - user messages - implementation
* Copyright(c) 2004 of wave++ (Yuri D'Elia) <wavexx@users.sf.net>
* Distributed under GNU LGPL without ANY warranty.
*/
// local headers
#include "msg.hh"
// c system headers
#include <stdarg.h>
#include <cstdio>
using std::vfprintf;
using std::fprintf;
// data
const char* prg;
bool verbose = false;
// implementation
void
err(const char* fmt, ...)
{
va_list params;
fprintf(stderr, "%s: ", prg);
va_start(params, fmt);
vfprintf(stderr, fmt, params);
va_end(params);
fprintf(stderr, "\n");
}
void
msg(const char* fmt, ...)
{
if(!verbose)
return;
va_list params;
fprintf(stderr, "%s: ", prg);
va_start(params, fmt);
vfprintf(stderr, fmt, params);
va_end(params);
fprintf(stderr, "\n");
}
|
Add new functions and finished module Graph.h | #include "Graph.h"
| #include "Graph.h"
#include <fstream>
using namespace std;
void main()
{
setlocale(LC_ALL, "Russian");
ifstream inputFile("inputfile.txt");
int numberOfCountries = 0;
List **mapOfWorld = creatingCoutries(inputFile);
printMap(mapOfWorld);
deleteMap(mapOfWorld);
system("pause");
} |
Comment out broken tests for now | //
// Created by Konstantin Gredeskoul on 1/23/16.
//
#include "gtest/gtest.h"
#include "macros_color_test.h"
TEST(rgb_pixel, set_color) {
pixel.setColor(purple);
EXPECT_EQ_COLORS(pixel.getColor(), purple);
wait_for(10);
EXPECT_EQ_COLORS(pixel.getColor(), purple);
}
TEST(rgb_pixel, fade_same_colors) {
pixel.fade(purple, purple, 100);
EXPECT_EQ_COLORS(pixel.getColor(), purple);
wait_for(90);
EXPECT_EQ_COLORS(pixel.getColor(), purple);
}
TEST(rgb_pixel, tick_100ms) {
pixel.fade(purple, orange, 200);
wait_for(100);
RGBColor dark_grey = (orange - purple) / 2;
EXPECT_EQ_COLORS(dark_grey, pixel.getColor());
}
| //
// Created by Konstantin Gredeskoul on 1/23/16.
//
#include "gtest/gtest.h"
#include "macros_color_test.h"
TEST(rgb_pixel, set_color) {
pixel.setColor(purple);
EXPECT_EQ_COLORS(pixel.getColor(), purple);
wait_for(10);
EXPECT_EQ_COLORS(pixel.getColor(), purple);
}
//TEST(rgb_pixel, fade_same_colors) {
// pixel.fade(purple, purple, 100);
// EXPECT_EQ_COLORS(pixel.getColor(), purple);
// wait_for(90);
// EXPECT_EQ_COLORS(pixel.getColor(), purple);
//}
//
//TEST(rgb_pixel, tick_100ms) {
// pixel.fade(purple, orange, 200);
// wait_for(100);
// RGBColor dark_grey = (orange - purple) / 2;
// EXPECT_EQ_COLORS(dark_grey, pixel.getColor());
//}
|
Include missing headers & own header as first | /*
googletalkcalldialog.cpp - Google Talk and Google libjingle support
Copyright (c) 2009 by Pali Rohár <pali.rohar@gmail.com>
*************************************************************************
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
*************************************************************************
*/
#include <QCloseEvent>
#include "googletalkcalldialog.h"
GoogleTalkCallDialog::GoogleTalkCallDialog(QWidget *parent): QDialog(parent) {
setupUi(this);
}
void GoogleTalkCallDialog::closeEvent(QCloseEvent * e) {
e->ignore();
emit(closed());
}
#include "googletalkcalldialog.moc"
| /*
googletalkcalldialog.cpp - Google Talk and Google libjingle support
Copyright (c) 2009 by Pali Rohár <pali.rohar@gmail.com>
*************************************************************************
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
*************************************************************************
*/
#include "googletalkcalldialog.h"
#include <QCloseEvent>
GoogleTalkCallDialog::GoogleTalkCallDialog(QWidget *parent): QDialog(parent) {
setupUi(this);
}
void GoogleTalkCallDialog::closeEvent(QCloseEvent * e) {
e->ignore();
emit(closed());
}
#include "googletalkcalldialog.moc"
|
Tweak lit tests to avoid false negatives | // RUN: grep -Ev "// *[A-Z-]+:" %s > %t.cpp
// RUN: not cpp11-migrate -format-style=FOO -use-auto %t.cpp -- -std=c++11
// RUN: not cpp11-migrate -format-style=/tmp/ -use-auto %t.cpp -- -std=c++11
// RUN: cpp11-migrate -format-style=LLVM -use-auto %t.cpp -- -std=c++11
// RUN: FileCheck --strict-whitespace -input-file=%t.cpp %s
class MyType012345678901234567890123456789 {};
int f() {
MyType012345678901234567890123456789 *a =
new MyType012345678901234567890123456789();
// CHECK: {{^\ \ auto\ a\ \=\ new\ MyType012345678901234567890123456789\(\);}}
delete a;
}
| // RUN: grep -Ev "// *[A-Z-]+:" %s > %t.cpp
// RUN: not cpp11-migrate -format-style=non_existent_file.yaml -use-auto %t.cpp -- -std=c++11
// RUN: touch %T/non_format_config.yaml
// RUN: not cpp11-migrate -format-style=%T/non_format_config.yaml -use-auto %t.cpp -- -std=c++11
// RUN: cpp11-migrate -format-style=LLVM -use-auto %t.cpp -- -std=c++11
// RUN: FileCheck --strict-whitespace -input-file=%t.cpp %s
class MyType012345678901234567890123456789 {};
int f() {
MyType012345678901234567890123456789 *a =
new MyType012345678901234567890123456789();
// CHECK: {{^\ \ auto\ a\ \=\ new\ MyType012345678901234567890123456789\(\);}}
delete a;
}
|
Patch from Achtelik Markus to fix compile error on 32bit builds. | #include "cvd/colourspace.h"
namespace CVD {
namespace ColourSpace {
inline void yuv420p_to_rgb_c(const unsigned char* y, const unsigned char* u, const unsigned char* v, unsigned char* rgb, unsigned int width, unsigned int height);
extern "C"{
void cvd_asm_yuv420p_to_rgb(const unsigned char*, unsigned char*, int);
}
void yuv420p_to_rgb(const unsigned char* y, const unsigned char* u, const unsigned char* v, unsigned char* rgb, unsigned int width, unsigned int height) {
if (is_aligned<8>(y) && (u == y + width*height) && is_aligned<8>(u) && (v == u + width*height/4) && is_aligned<8>(v) &&
is_aligned<8>(rgb) && ((width&4) == 0) && ((height&1)==0))
cvd_asm_yuv420p_to_rgb(y,rgb,width,height);
else
yuv420p_to_rgb_c(y, u, v, rgb, width, height);
}
}
}
| #include "cvd/colourspace.h"
#include "cvd/utility.h"
namespace CVD {
namespace ColourSpace {
inline void yuv420p_to_rgb_c(const unsigned char* y, const unsigned char* u, const unsigned char* v, unsigned char* rgb, unsigned int width, unsigned int height);
extern "C"{
void cvd_asm_yuv420p_to_rgb(const unsigned char*, unsigned char*, int, int);
}
void yuv420p_to_rgb(const unsigned char* y, const unsigned char* u, const unsigned char* v, unsigned char* rgb, unsigned int width, unsigned int height) {
if (is_aligned<8>(y) && (u == y + width*height) && is_aligned<8>(u) && (v == u + width*height/4) && is_aligned<8>(v) &&
is_aligned<8>(rgb) && ((width&4) == 0) && ((height&1)==0))
cvd_asm_yuv420p_to_rgb(y,rgb,width,height);
else
yuv420p_to_rgb_c(y, u, v, rgb, width, height);
}
}
}
|
Use real distribution for random float generator | //
// MathsUtilities.cpp
// TimGameLib
//
// Created by Tim Brier on 10/04/2015.
// Copyright (c) 2015 tbrier. All rights reserved.
//
#include "MathsUtilities.hpp"
#include <random>
#include <functional>
namespace MathsUtilities
{
std::function<int()> GetRandomGeneratorFunctionForRange(int min, int max)
{
std::random_device device;
std::default_random_engine generator(device());
std::uniform_int_distribution<int> distribution(min, max);
auto result = std::bind(distribution, generator);
return result;
}
std::function<float()> GetRandomGeneratorFunctionForRange(float min, float max)
{
std::random_device device;
std::default_random_engine generator(device());
std::uniform_int_distribution<float> distribution(min, max);
auto result = std::bind(distribution, generator);
return result;
}
} // namespace MathsUtilities | //
// MathsUtilities.cpp
// TimGameLib
//
// Created by Tim Brier on 10/04/2015.
// Copyright (c) 2015 tbrier. All rights reserved.
//
#include "MathsUtilities.hpp"
#include <random>
#include <functional>
namespace MathsUtilities
{
std::function<int()> GetRandomGeneratorFunctionForRange(int min, int max)
{
std::random_device device;
std::default_random_engine generator(device());
std::uniform_int_distribution<int> distribution(min, max);
auto result = std::bind(distribution, generator);
return result;
}
std::function<float()> GetRandomGeneratorFunctionForRange(float min, float max)
{
std::random_device device;
std::default_random_engine generator(device());
std::uniform_real_distribution<float> distribution(min, max);
auto result = std::bind(distribution, generator);
return result;
}
} // namespace MathsUtilities |
Use Win32 function instead of rolling our own | #include "Control.h"
#include <sstream>
Control::Control() {
}
Control::Control(int id, HWND parent) :
_id(id),
_parent(parent) {
_hWnd = GetDlgItem(parent, id);
}
Control::~Control() {
}
bool Control::Text(std::wstring text) {
return SetDlgItemText(_parent, _id, text.c_str()) == TRUE;
}
bool Control::Text(int value) {
return Text(std::to_wstring(value));
}
std::wstring Control::Text() {
wchar_t text[MAX_EDITSTR];
GetDlgItemText(_parent, _id, text, MAX_EDITSTR);
return std::wstring(text);
}
int Control::TextAsInt() {
std::wstring str = Text();
int num;
std::wistringstream wistr(str);
wistr >> num;
return num;
}
void Control::AddWindowExStyle(long exStyle) {
long exs = GetWindowLongPtr(_hWnd, GWL_EXSTYLE);
exs |= exStyle;
SetWindowLongPtr(_hWnd, GWL_EXSTYLE, exs);
}
RECT Control::Dimensions() {
RECT r;
GetWindowRect(_hWnd, &r);
return r;
} | #include "Control.h"
#include <sstream>
Control::Control() {
}
Control::Control(int id, HWND parent) :
_id(id),
_parent(parent) {
_hWnd = GetDlgItem(parent, id);
}
Control::~Control() {
}
bool Control::Text(std::wstring text) {
return SetDlgItemText(_parent, _id, text.c_str()) == TRUE;
}
bool Control::Text(int value) {
return SetDlgItemInt(_parent, _id, value, TRUE) == TRUE;
}
std::wstring Control::Text() {
wchar_t text[MAX_EDITSTR];
GetDlgItemText(_parent, _id, text, MAX_EDITSTR);
return std::wstring(text);
}
int Control::TextAsInt() {
std::wstring str = Text();
int num;
std::wistringstream wistr(str);
wistr >> num;
return num;
}
void Control::AddWindowExStyle(long exStyle) {
long exs = GetWindowLongPtr(_hWnd, GWL_EXSTYLE);
exs |= exStyle;
SetWindowLongPtr(_hWnd, GWL_EXSTYLE, exs);
}
RECT Control::Dimensions() {
RECT r;
GetWindowRect(_hWnd, &r);
return r;
} |
Update clang to match llvm r250901. OptTable constructor now takes an ArrayRef. NFC | //===--- DriverOptions.cpp - Driver Options Table -------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/Driver/Options.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Option/OptTable.h"
#include "llvm/Option/Option.h"
using namespace clang::driver;
using namespace clang::driver::options;
using namespace llvm::opt;
#define PREFIX(NAME, VALUE) static const char *const NAME[] = VALUE;
#include "clang/Driver/Options.inc"
#undef PREFIX
static const OptTable::Info InfoTable[] = {
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
HELPTEXT, METAVAR) \
{ PREFIX, NAME, HELPTEXT, METAVAR, OPT_##ID, Option::KIND##Class, PARAM, \
FLAGS, OPT_##GROUP, OPT_##ALIAS, ALIASARGS },
#include "clang/Driver/Options.inc"
#undef OPTION
};
namespace {
class DriverOptTable : public OptTable {
public:
DriverOptTable()
: OptTable(InfoTable, llvm::array_lengthof(InfoTable)) {}
};
}
OptTable *clang::driver::createDriverOptTable() {
return new DriverOptTable();
}
| //===--- DriverOptions.cpp - Driver Options Table -------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/Driver/Options.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Option/OptTable.h"
#include "llvm/Option/Option.h"
using namespace clang::driver;
using namespace clang::driver::options;
using namespace llvm::opt;
#define PREFIX(NAME, VALUE) static const char *const NAME[] = VALUE;
#include "clang/Driver/Options.inc"
#undef PREFIX
static const OptTable::Info InfoTable[] = {
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
HELPTEXT, METAVAR) \
{ PREFIX, NAME, HELPTEXT, METAVAR, OPT_##ID, Option::KIND##Class, PARAM, \
FLAGS, OPT_##GROUP, OPT_##ALIAS, ALIASARGS },
#include "clang/Driver/Options.inc"
#undef OPTION
};
namespace {
class DriverOptTable : public OptTable {
public:
DriverOptTable()
: OptTable(InfoTable) {}
};
}
OptTable *clang::driver::createDriverOptTable() {
return new DriverOptTable();
}
|
Fix to make the behavior of TextfieldWithMargin consistent with Textfield | // Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/textfield_with_margin.h"
#include "chrome/browser/chromeos/login/helper.h"
#include "ui/base/keycodes/keyboard_codes.h"
namespace {
// Holds ratio of the margin to the preferred text height.
const double kTextMarginRate = 0.33;
// Size of each vertical margin (top, bottom).
const int kVerticalMargin = 3;
} // namespace
namespace chromeos {
TextfieldWithMargin::TextfieldWithMargin() {
CorrectTextfieldFontSize(this);
}
TextfieldWithMargin::TextfieldWithMargin(views::Textfield::StyleFlags style)
: Textfield(style) {
CorrectTextfieldFontSize(this);
}
void TextfieldWithMargin::Layout() {
int margin = GetPreferredSize().height() * kTextMarginRate;
SetHorizontalMargins(margin, margin);
SetVerticalMargins(kVerticalMargin, kVerticalMargin);
views::Textfield::Layout();
}
bool TextfieldWithMargin::OnKeyPressed(const views::KeyEvent& e) {
if (e.key_code() == ui::VKEY_ESCAPE && !text().empty()) {
SetText(string16());
return true;
}
return false;
}
} // namespace chromeos
| // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/textfield_with_margin.h"
#include "chrome/browser/chromeos/login/helper.h"
#include "ui/base/keycodes/keyboard_codes.h"
namespace {
// Holds ratio of the margin to the preferred text height.
const double kTextMarginRate = 0.33;
// Size of each vertical margin (top, bottom).
const int kVerticalMargin = 3;
} // namespace
namespace chromeos {
TextfieldWithMargin::TextfieldWithMargin() {
CorrectTextfieldFontSize(this);
}
TextfieldWithMargin::TextfieldWithMargin(views::Textfield::StyleFlags style)
: Textfield(style) {
CorrectTextfieldFontSize(this);
}
void TextfieldWithMargin::Layout() {
int margin = GetPreferredSize().height() * kTextMarginRate;
SetHorizontalMargins(margin, margin);
SetVerticalMargins(kVerticalMargin, kVerticalMargin);
views::Textfield::Layout();
}
bool TextfieldWithMargin::OnKeyPressed(const views::KeyEvent& e) {
if (e.key_code() == ui::VKEY_ESCAPE && !text().empty()) {
SetText(string16());
return true;
}
return views::Textfield::OnKeyPressed(e);
}
} // namespace chromeos
|
Remove confusing transpose() in setLinSpaced() docs. | VectorXf v;
v.setLinSpaced(5,0.5f,1.5f).transpose();
cout << v << endl;
| VectorXf v;
v.setLinSpaced(5,0.5f,1.5f);
cout << v << endl;
|
Fix line length in caller.cc | // Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/common/api/event_emitter_caller.h"
#include "atom/common/api/locker.h"
#include "atom/common/node_includes.h"
namespace mate {
namespace internal {
v8::Local<v8::Value> CallMethodWithArgs(v8::Isolate* isolate,
v8::Local<v8::Object> obj,
const char* method,
ValueVector* args) {
// Perform microtask checkpoint after running JavaScript.
v8::MicrotasksScope script_scope(isolate,
v8::MicrotasksScope::kRunMicrotasks);
// Use node::MakeCallback to call the callback, and it will also run pending
// tasks in Node.js.
v8::MaybeLocal<v8::Value> ret = node::MakeCallback(isolate, obj, method, args->size(), &args->front(),
{0, 0});
if (ret.IsEmpty()) {
return v8::Boolean::New(isolate, false);
}
return ret.ToLocalChecked();
}
} // namespace internal
} // namespace mate
| // Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/common/api/event_emitter_caller.h"
#include "atom/common/api/locker.h"
#include "atom/common/node_includes.h"
namespace mate {
namespace internal {
v8::Local<v8::Value> CallMethodWithArgs(v8::Isolate* isolate,
v8::Local<v8::Object> obj,
const char* method,
ValueVector* args) {
// Perform microtask checkpoint after running JavaScript.
v8::MicrotasksScope script_scope(isolate,
v8::MicrotasksScope::kRunMicrotasks);
// Use node::MakeCallback to call the callback, and it will also run pending
// tasks in Node.js.
v8::MaybeLocal<v8::Value> ret = node::MakeCallback(isolate, obj, method,
args->size(),
&args->front(), {0, 0});
if (ret.IsEmpty()) {
return v8::Boolean::New(isolate, false);
}
return ret.ToLocalChecked();
}
} // namespace internal
} // namespace mate
|
Disable stack exhaustion test on NetBSD, where either the detection or recovery mechanism does not appear to work. | // RUN: %clang_cc1 -verify %s
// REQUIRES: thread_support
// expected-warning@* 0-1{{stack nearly exhausted}}
// expected-note@* 0+{{}}
template<int N> struct X : X<N-1> {};
template<> struct X<0> {};
X<1000> x;
template<typename ...T> struct tuple {};
template<typename ...T> auto f(tuple<T...> t) -> decltype(f(tuple<T...>(t))) {} // expected-error {{exceeded maximum depth}}
void g() { f(tuple<int, int>()); }
int f(X<0>);
template<int N> auto f(X<N>) -> f(X<N-1>());
int k = f(X<1000>());
| // RUN: %clang_cc1 -verify %s
// REQUIRES: thread_support
// FIXME: Detection of, or recovery from, stack exhaustion does not work on
// NetBSD at the moment. Since this is a best-effort mitigation for exceeding
// implementation limits, just disable the test.
// UNSUPPORTED: system-netbsd
// expected-warning@* 0-1{{stack nearly exhausted}}
// expected-note@* 0+{{}}
template<int N> struct X : X<N-1> {};
template<> struct X<0> {};
X<1000> x;
template<typename ...T> struct tuple {};
template<typename ...T> auto f(tuple<T...> t) -> decltype(f(tuple<T...>(t))) {} // expected-error {{exceeded maximum depth}}
void g() { f(tuple<int, int>()); }
int f(X<0>);
template<int N> auto f(X<N>) -> f(X<N-1>());
int k = f(X<1000>());
|
Set active_dialog_ before showing it, since showing a dialog can sometimes actually move to the next one in the queue instead. | // 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 "chrome/browser/app_modal_dialog_queue.h"
#include "chrome/browser/browser_list.h"
void AppModalDialogQueue::AddDialog(AppModalDialog* dialog) {
if (!active_dialog_) {
ShowModalDialog(dialog);
return;
}
app_modal_dialog_queue_.push(dialog);
}
void AppModalDialogQueue::ShowNextDialog() {
if (!app_modal_dialog_queue_.empty()) {
AppModalDialog* dialog = app_modal_dialog_queue_.front();
app_modal_dialog_queue_.pop();
ShowModalDialog(dialog);
} else {
active_dialog_ = NULL;
}
}
void AppModalDialogQueue::ActivateModalDialog() {
if (active_dialog_)
active_dialog_->ActivateModalDialog();
}
void AppModalDialogQueue::ShowModalDialog(AppModalDialog* dialog) {
dialog->ShowModalDialog();
active_dialog_ = dialog;
}
| // 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 "chrome/browser/app_modal_dialog_queue.h"
#include "chrome/browser/browser_list.h"
void AppModalDialogQueue::AddDialog(AppModalDialog* dialog) {
if (!active_dialog_) {
ShowModalDialog(dialog);
return;
}
app_modal_dialog_queue_.push(dialog);
}
void AppModalDialogQueue::ShowNextDialog() {
if (!app_modal_dialog_queue_.empty()) {
AppModalDialog* dialog = app_modal_dialog_queue_.front();
app_modal_dialog_queue_.pop();
ShowModalDialog(dialog);
} else {
active_dialog_ = NULL;
}
}
void AppModalDialogQueue::ActivateModalDialog() {
if (active_dialog_)
active_dialog_->ActivateModalDialog();
}
void AppModalDialogQueue::ShowModalDialog(AppModalDialog* dialog) {
// Set active_dialog_ before showing it, because ShowModalDialog can wind up
// calling ShowNextDialog in some cases, which will change active_dialog_.
active_dialog_ = dialog;
dialog->ShowModalDialog();
}
|
Remove wrong parameter from ECSignatureCreator's constructor in openssl implement. | // 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 "crypto/ec_signature_creator.h"
#include "base/logging.h"
namespace crypto {
// static
ECSignatureCreator* ECSignatureCreator::Create(ECPrivateKey* key) {
NOTIMPLEMENTED();
return NULL;
}
ECSignatureCreator::ECSignatureCreator(ECPrivateKey* key,
HASH_HashType hash_type)
: key_(key),
hash_type_(hash_type) {
NOTIMPLEMENTED();
}
ECSignatureCreator::~ECSignatureCreator() { }
bool ECSignatureCreator::Sign(const uint8* data,
int data_len,
std::vector<uint8>* signature) {
NOTIMPLEMENTED();
return false;
}
} // namespace crypto
| // 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 "crypto/ec_signature_creator.h"
#include "base/logging.h"
namespace crypto {
// static
ECSignatureCreator* ECSignatureCreator::Create(ECPrivateKey* key) {
NOTIMPLEMENTED();
return NULL;
}
ECSignatureCreator::ECSignatureCreator(ECPrivateKey* key)
: key_(key) {
NOTIMPLEMENTED();
}
ECSignatureCreator::~ECSignatureCreator() { }
bool ECSignatureCreator::Sign(const uint8* data,
int data_len,
std::vector<uint8>* signature) {
NOTIMPLEMENTED();
return false;
}
} // namespace crypto
|
Add coin serialize deserialize priv coin | #include "../Coin.h"
#include "../Params.h"
#include "../../../streams.h"
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_SUITE(sigma_coin_tests)
BOOST_AUTO_TEST_CASE(pubcoin_serialization)
{
secp_primitives::GroupElement coin;
coin.randomize();
sigma::PublicCoinV3 pubcoin(coin, sigma::ZQ_GOLDWASSER);
CDataStream serialized(SER_NETWORK, PROTOCOL_VERSION);
serialized << pubcoin;
sigma::PublicCoinV3 deserialized;
serialized >> deserialized;
BOOST_CHECK(pubcoin == deserialized);
}
BOOST_AUTO_TEST_CASE(pubcoin_validate)
{
auto params = sigma::ParamsV3::get_default();
sigma::PrivateCoinV3 privcoin(params);
auto& pubcoin = privcoin.getPublicCoin();
BOOST_CHECK(pubcoin.validate());
}
BOOST_AUTO_TEST_SUITE_END()
| #include "../Coin.h"
#include "../Params.h"
#include "../../../streams.h"
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_SUITE(sigma_coin_tests)
BOOST_AUTO_TEST_CASE(pubcoin_serialization)
{
secp_primitives::GroupElement coin;
coin.randomize();
sigma::PublicCoinV3 pubcoin(coin, sigma::ZQ_GOLDWASSER);
CDataStream serialized(SER_NETWORK, PROTOCOL_VERSION);
serialized << pubcoin;
sigma::PublicCoinV3 deserialized;
serialized >> deserialized;
BOOST_CHECK(pubcoin == deserialized);
}
BOOST_AUTO_TEST_CASE(pubcoin_validate)
{
auto params = sigma::ParamsV3::get_default();
sigma::PrivateCoinV3 privcoin(params);
auto& pubcoin = privcoin.getPublicCoin();
BOOST_CHECK(pubcoin.validate());
}
BOOST_AUTO_TEST_CASE(getter_setter_priv)
{
auto params = sigma::ParamsV3::get_default();
sigma::PrivateCoinV3 privcoin(params);
sigma::PrivateCoinV3 new_privcoin(params);
BOOST_CHECK(privcoin.getPublicCoin() != new_privcoin.getPublicCoin());
BOOST_CHECK(privcoin.getSerialNumber() != new_privcoin.getSerialNumber());
BOOST_CHECK(privcoin.getRandomness() != new_privcoin.getRandomness());
BOOST_CHECK(privcoin.getVersion() == new_privcoin.getVersion());
new_privcoin.setPublicCoin(privcoin.getPublicCoin());
new_privcoin.setRandomness(privcoin.getRandomness());
new_privcoin.setSerialNumber(privcoin.getSerialNumber());
new_privcoin.setVersion(2);
BOOST_CHECK(privcoin.getPublicCoin() == new_privcoin.getPublicCoin());
BOOST_CHECK(privcoin.getSerialNumber() == new_privcoin.getSerialNumber());
BOOST_CHECK(privcoin.getRandomness() == new_privcoin.getRandomness());
BOOST_CHECK(new_privcoin.getVersion() == 2);
}
BOOST_AUTO_TEST_SUITE_END()
|
Apply same fix to apple | /******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2016-2017 Baldur Karlsson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
#include "os/posix/posix_hook.h"
#include <dlfcn.h>
void PosixHookInit()
{
}
bool PosixHookDetect(const char *identifier)
{
return dlsym(RTLD_DEFAULT, identifier) != NULL;
}
void PosixHookLibrary(const char *name, dlopenCallback cb)
{
} | /******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2016-2017 Baldur Karlsson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
#include "os/posix/posix_hook.h"
#include <dlfcn.h>
#include <stddef.h>
void PosixHookInit()
{
}
bool PosixHookDetect(const char *identifier)
{
return dlsym(RTLD_DEFAULT, identifier) != NULL;
}
void PosixHookLibrary(const char *name, dlopenCallback cb)
{
}
|
Add two tests to demo 'override' specifier. | // ep1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <gtest\gtest.h>
int _tmain(int argc, _TCHAR* argv[])
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| // ep1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <memory>
#include <gtest\gtest.h>
using namespace std;
struct Foo {
virtual int Plus(int left, int right)
{
return 2;
}
};
struct Bar : public Foo {
virtual int Plus(int left, short right)
{
return 4;
}
};
TEST(Episode1, OverrideTest_CallParent)
{
unique_ptr<Foo> op(new Foo());
EXPECT_EQ(2, op->Plus(1, 1));
}
TEST(Episode1, OverrideTest_CallDerived)
{
unique_ptr<Foo> op(new Bar());
EXPECT_EQ(4, op->Plus(1, 1));
}
int _tmain(int argc, _TCHAR* argv[])
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
Add the sanity test for libsodium. | // Copyright (c) 2012-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "compat/sanity.h"
#include "key.h"
#include "test/test_bitcoin.h"
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(sanity_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(basic_sanity)
{
BOOST_CHECK_MESSAGE(glibc_sanity_test() == true, "libc sanity test");
BOOST_CHECK_MESSAGE(glibcxx_sanity_test() == true, "stdlib sanity test");
BOOST_CHECK_MESSAGE(ECC_InitSanityCheck() == true, "openssl ECC test");
}
BOOST_AUTO_TEST_SUITE_END()
| // Copyright (c) 2012-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "compat/sanity.h"
#include "key.h"
#include "test/test_bitcoin.h"
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(sanity_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(basic_sanity)
{
BOOST_CHECK_MESSAGE(glibc_sanity_test() == true, "libc sanity test");
BOOST_CHECK_MESSAGE(glibcxx_sanity_test() == true, "stdlib sanity test");
BOOST_CHECK_MESSAGE(ECC_InitSanityCheck() == true, "openssl ECC test");
BOOST_CHECK_MESSAGE(init_and_check_sodium() == 0, "libsodium sanity test");
}
BOOST_AUTO_TEST_SUITE_END()
|
Fix failing test due to missing checkerboard constructor param. | /*
* Unit tests for the checkerboard.
* Author: Dino Wernli
*/
#include <gtest/gtest.h>
#include "scene/texture/checkerboard.h"
#include "test/test_util.h"
namespace {
static IntersectionData DataWithCoords(Scalar ss, Scalar tt) {
Ray r(Point3(0, 0, 0), Vector3(0, 0, 1));
IntersectionData data(r);
data.texture_coordinate.s = ss;
data.texture_coordinate.t = tt;
return data;
}
TEST(Checkerboard, IsChanging) {
Color3 blue(0, 0, 1);
Color3 red(1, 0, 0);
Checkerboard cb(blue, red);
EXPECT_TRUE(TestUtil::ColorsEqual(blue, cb.Evaluate(DataWithCoords(0, 0))));
EXPECT_TRUE(TestUtil::ColorsEqual(red, cb.Evaluate(DataWithCoords(0, 0.1))));
}
}
| /*
* Unit tests for the checkerboard.
* Author: Dino Wernli
*/
#include <gtest/gtest.h>
#include "scene/texture/checkerboard.h"
#include "test/test_util.h"
namespace {
static IntersectionData DataWithCoords(Scalar ss, Scalar tt) {
Ray r(Point3(0, 0, 0), Vector3(0, 0, 1));
IntersectionData data(r);
data.texture_coordinate.s = ss;
data.texture_coordinate.t = tt;
return data;
}
TEST(Checkerboard, IsChanging) {
Color3 blue(0, 0, 1);
Color3 red(1, 0, 0);
Checkerboard cb(blue, red, 5 /* length */);
EXPECT_TRUE(TestUtil::ColorsEqual(blue, cb.Evaluate(DataWithCoords(0, 0))));
EXPECT_TRUE(TestUtil::ColorsEqual(red, cb.Evaluate(DataWithCoords(0, 0.1))));
}
}
|
Fix msvc14 64-bit release mode linker error | // Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "auto_id.h"
using namespace autowiring;
// Index that will be given to the next auto_id instance. Zero is reserved.
static int s_index = 1;
const auto_id_block auto_id_t<void>::s_block{
0,
&typeid(void),
&typeid(s<void>),
0,
0,
nullptr,
nullptr
};
int autowiring::CreateIndex(void) {
return s_index++;
}
std::shared_ptr<CoreObject> auto_id_block::NullToObj(const std::shared_ptr<void>&) AUTO_NOEXCEPT
{
return nullptr;
}
std::shared_ptr<void> auto_id_block::NullFromObj(const std::shared_ptr<CoreObject>&) AUTO_NOEXCEPT
{
return nullptr;
}
| // Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "auto_id.h"
using namespace autowiring;
// Index that will be given to the next auto_id instance. Zero is reserved.
static int s_index = 1;
const auto_id_block auto_id_t<void>::s_block{
0,
&typeid(void),
&typeid(s<void>),
0,
0,
nullptr,
nullptr
};
const auto_id_t_init<void, true> auto_id_t_init<void, true>::init;
const auto_id_t_init<void, false> auto_id_t_init<void, false>::init;
int autowiring::CreateIndex(void) {
return s_index++;
}
std::shared_ptr<CoreObject> auto_id_block::NullToObj(const std::shared_ptr<void>&) AUTO_NOEXCEPT
{
return nullptr;
}
std::shared_ptr<void> auto_id_block::NullFromObj(const std::shared_ptr<CoreObject>&) AUTO_NOEXCEPT
{
return nullptr;
}
|
Fix obsolete structure init in CodeArea::GetCenter() | #include "codearea.h"
#include <algorithm>
namespace openlocationcode {
const double kLatitudeMaxDegrees = 90;
const double kLongitudeMaxDegrees = 180;
CodeArea::CodeArea(double latitude_lo, double longitude_lo, double latitude_hi,
double longitude_hi, size_t code_length) {
latitude_lo_ = latitude_lo;
longitude_lo_ = longitude_lo;
latitude_hi_ = latitude_hi;
longitude_hi_ = longitude_hi;
code_length_ = code_length;
}
double CodeArea::GetLatitudeLo() const{
return latitude_lo_;
}
double CodeArea::GetLongitudeLo() const {
return longitude_lo_;
}
double CodeArea::GetLatitudeHi() const {
return latitude_hi_;
}
double CodeArea::GetLongitudeHi() const {
return longitude_hi_;
}
size_t CodeArea::GetCodeLength() const { return code_length_; }
LatLng CodeArea::GetCenter() const {
double latitude_center = std::min(latitude_lo_ + (latitude_hi_ - latitude_lo_) / 2, kLatitudeMaxDegrees);
double longitude_center = std::min(longitude_lo_ + (longitude_hi_ - longitude_lo_) / 2, kLongitudeMaxDegrees);
LatLng center = {latitude: latitude_center, longitude: longitude_center};
return center;
}
} // namespace openlocationcode | #include "codearea.h"
#include <algorithm>
namespace openlocationcode {
const double kLatitudeMaxDegrees = 90;
const double kLongitudeMaxDegrees = 180;
CodeArea::CodeArea(double latitude_lo, double longitude_lo, double latitude_hi,
double longitude_hi, size_t code_length) {
latitude_lo_ = latitude_lo;
longitude_lo_ = longitude_lo;
latitude_hi_ = latitude_hi;
longitude_hi_ = longitude_hi;
code_length_ = code_length;
}
double CodeArea::GetLatitudeLo() const{
return latitude_lo_;
}
double CodeArea::GetLongitudeLo() const {
return longitude_lo_;
}
double CodeArea::GetLatitudeHi() const {
return latitude_hi_;
}
double CodeArea::GetLongitudeHi() const {
return longitude_hi_;
}
size_t CodeArea::GetCodeLength() const { return code_length_; }
LatLng CodeArea::GetCenter() const {
const double latitude_center = std::min(
latitude_lo_ + (latitude_hi_ - latitude_lo_) / 2, kLatitudeMaxDegrees);
const double longitude_center =
std::min(longitude_lo_ + (longitude_hi_ - longitude_lo_) / 2,
kLongitudeMaxDegrees);
const LatLng center = {latitude_center, longitude_center};
return center;
}
} // namespace openlocationcode
|
Add code to implement querying CPU time for each processor on Mac for systemInfo.cpu API. | // 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/api/system_info_cpu/cpu_info_provider.h"
namespace extensions {
bool CpuInfoProvider::QueryCpuTimePerProcessor(std::vector<CpuTime>* times) {
// TODO(hongbo): Query the cpu time.
return false;
}
} // namespace extensions
| // 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/api/system_info_cpu/cpu_info_provider.h"
#include <mach/mach_host.h>
#include "base/mac/scoped_mach_port.h"
namespace extensions {
bool CpuInfoProvider::QueryCpuTimePerProcessor(std::vector<CpuTime>* times) {
natural_t num_of_processors;
base::mac::ScopedMachPort host(mach_host_self());
mach_msg_type_number_t type;
processor_cpu_load_info_data_t* cpu_infos;
if (host_processor_info(host.get(),
PROCESSOR_CPU_LOAD_INFO,
&num_of_processors,
reinterpret_cast<processor_info_array_t*>(&cpu_infos),
&type) == KERN_SUCCESS) {
std::vector<CpuTime> results;
int64 user = 0, nice = 0, sys = 0, idle = 0;
for (natural_t i = 0; i < num_of_processors; ++i) {
CpuTime time;
user = static_cast<int64>(cpu_infos[i].cpu_ticks[CPU_STATE_USER]);
sys = static_cast<int64>(cpu_infos[i].cpu_ticks[CPU_STATE_SYSTEM]);
nice = static_cast<int64>(cpu_infos[i].cpu_ticks[CPU_STATE_NICE]);
idle = static_cast<int64>(cpu_infos[i].cpu_ticks[CPU_STATE_IDLE]);
time.kernel = sys;
time.user = user + nice;
time.idle = idle;
results.push_back(time);
}
vm_deallocate(mach_task_self(),
reinterpret_cast<vm_address_t>(cpu_infos),
num_of_processors * sizeof(processor_cpu_load_info));
times->swap(results);
return true;
}
return false;
}
} // namespace extensions
|
Use the canvas-based SkPaintFilterCanvas ctor in OpacityFilterCanvas | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "skia/ext/opacity_filter_canvas.h"
#include "third_party/skia/include/core/SkPaint.h"
#include "third_party/skia/include/core/SkTLazy.h"
namespace skia {
OpacityFilterCanvas::OpacityFilterCanvas(SkCanvas* canvas,
float opacity,
bool disable_image_filtering)
: INHERITED(canvas->imageInfo().width(), canvas->imageInfo().height()),
alpha_(SkScalarRoundToInt(opacity * 255)),
disable_image_filtering_(disable_image_filtering) {
this->addCanvas(canvas);
}
void OpacityFilterCanvas::onFilterPaint(SkPaint* paint, Type) const {
if (alpha_ < 255)
paint->setAlpha(alpha_);
if (disable_image_filtering_)
paint->setFilterQuality(kNone_SkFilterQuality);
}
void OpacityFilterCanvas::onDrawPicture(const SkPicture* picture,
const SkMatrix* matrix,
const SkPaint* paint) {
SkTLazy<SkPaint> filteredPaint;
if (paint) {
this->onFilterPaint(filteredPaint.set(*paint), kPicture_Type);
}
// Unfurl pictures in order to filter nested paints.
this->SkCanvas::onDrawPicture(picture, matrix, filteredPaint.getMaybeNull());
}
} // namespace skia
| // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "skia/ext/opacity_filter_canvas.h"
#include "third_party/skia/include/core/SkPaint.h"
#include "third_party/skia/include/core/SkTLazy.h"
namespace skia {
OpacityFilterCanvas::OpacityFilterCanvas(SkCanvas* canvas,
float opacity,
bool disable_image_filtering)
: INHERITED(canvas),
alpha_(SkScalarRoundToInt(opacity * 255)),
disable_image_filtering_(disable_image_filtering) { }
void OpacityFilterCanvas::onFilterPaint(SkPaint* paint, Type) const {
if (alpha_ < 255)
paint->setAlpha(alpha_);
if (disable_image_filtering_)
paint->setFilterQuality(kNone_SkFilterQuality);
}
void OpacityFilterCanvas::onDrawPicture(const SkPicture* picture,
const SkMatrix* matrix,
const SkPaint* paint) {
SkTLazy<SkPaint> filteredPaint;
if (paint) {
this->onFilterPaint(filteredPaint.set(*paint), kPicture_Type);
}
// Unfurl pictures in order to filter nested paints.
this->SkCanvas::onDrawPicture(picture, matrix, filteredPaint.getMaybeNull());
}
} // namespace skia
|
Update for new rect tracking | #include "SliderKnob.h"
SliderKnob::SliderKnob(std::wstring bitmapName,
int x, int y, int width, int height) :
Meter(bitmapName, x, y, 1),
_track(x, y, width, height) {
_units = _track.Width - _rect.Width;
}
Gdiplus::Rect SliderKnob::Location() {
return _rect;
}
void SliderKnob::Draw(Gdiplus::Bitmap *buffer, Gdiplus::Graphics *graphics) {
graphics->DrawImage(_bitmap, _rect,
0, 0, _rect.Width, _track.Height, Gdiplus::UnitPixel);
}
void SliderKnob::Value(float value) {
Meter::Value(value);
X(_trackX + CalcUnits());
}
int SliderKnob::TrackX() const {
return _trackX;
}
int SliderKnob::TrackY() const {
return _trackY;
}
int SliderKnob::TrackWidth() const {
return _trackWidth;
}
int SliderKnob::TrackHeight() const {
return _trackHeight;
}
int SliderKnob::X() const {
return Meter::X();
}
int SliderKnob::Y() const {
return Meter::Y();
}
void SliderKnob::X(int x) {
_rect.X = x;
}
void SliderKnob::Y(int y) {
_rect.Y = y;
} | #include "SliderKnob.h"
SliderKnob::SliderKnob(std::wstring bitmapName,
int x, int y, int width, int height) :
Meter(bitmapName, x, y, 1),
_track(x, y, width, height) {
_units = _track.Width - _rect.Width;
}
Gdiplus::Rect SliderKnob::Location() {
return _rect;
}
void SliderKnob::Draw(Gdiplus::Bitmap *buffer, Gdiplus::Graphics *graphics) {
graphics->DrawImage(_bitmap, _rect,
0, 0, _rect.Width, _track.Height, Gdiplus::UnitPixel);
}
void SliderKnob::Value(float value) {
Meter::Value(value);
X(TrackX() + CalcUnits());
}
int SliderKnob::TrackX() const {
return _track.X;
}
int SliderKnob::TrackY() const {
return _track.Y;
}
int SliderKnob::TrackWidth() const {
return _track.Width;
}
int SliderKnob::TrackHeight() const {
return _track.Height;
}
int SliderKnob::X() const {
return _rect.X;
}
int SliderKnob::Y() const {
return _rect.Y;
}
void SliderKnob::X(int x) {
_rect.X = x;
}
void SliderKnob::Y(int y) {
_rect.Y = y;
}
int SliderKnob::Width() const {
return _rect.Width;
}
int SliderKnob::Height() const {
return _rect.Height;
} |
Make sure Im using Boost libraries, not just headers. | /*=============================================================================
MYPROJECT: A software package for whatever.
Copyright (c) University College London (UCL). All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
See LICENSE.txt in the top level directory for details.
=============================================================================*/
#include <mpMyFunctions.h>
#include <iostream>
#ifdef BUILD_Eigen
#include <Eigen/Dense>
#endif
#ifdef BUILD_Boost
#include <boost/math/special_functions/round.hpp>
#endif
#ifdef BUILD_OpenCV
#include <cv.h>
#endif
int main(int argc, char** argv)
{
#ifdef BUILD_Eigen
Eigen::MatrixXd m(2,2);
std::cout << "Printing 2x2 matrix ..." << m << std::endl;
#endif
#ifdef BUILD_Boost
std::cout << "Rounding to ... " << boost::math::round(0.123) << std::endl;
#endif
#ifdef BUILD_OpenCV
cv::Matx44d matrix = cv::Matx44d::eye();
std::cout << "Printing 4x4 matrix ..." << matrix << std::endl;
#endif
std::cout << "Calculating ... " << mp::MyFirstFunction(1) << std::endl;
return 0;
}
| /*=============================================================================
MYPROJECT: A software package for whatever.
Copyright (c) University College London (UCL). All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
See LICENSE.txt in the top level directory for details.
=============================================================================*/
#include <mpMyFunctions.h>
#include <iostream>
#ifdef BUILD_Eigen
#include <Eigen/Dense>
#endif
#ifdef BUILD_Boost
#include <boost/math/special_functions/round.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/filesystem/path.hpp>
#endif
#ifdef BUILD_OpenCV
#include <cv.h>
#endif
int main(int argc, char** argv)
{
#ifdef BUILD_Eigen
Eigen::MatrixXd m(2,2);
std::cout << "Printing 2x2 matrix ..." << m << std::endl;
#endif
#ifdef BUILD_Boost
std::cout << "Rounding to ... " << boost::math::round(0.123) << std::endl;
boost::posix_time::ptime startTime = boost::posix_time::second_clock::local_time();
boost::filesystem::path pathname( "/tmp/tmp.txt" );
#endif
#ifdef BUILD_OpenCV
cv::Matx44d matrix = cv::Matx44d::eye();
std::cout << "Printing 4x4 matrix ..." << matrix << std::endl;
#endif
std::cout << "Calculating ... " << mp::MyFirstFunction(1) << std::endl;
return 0;
}
|
Handle another fade effect corner case when colour is black | #include "fade_effect.h"
unsigned int FadeEffect::maxDelay()
{
return -1;
}
void FadeEffect::init()
{
// Handle a corner case in which the update just increments
// a color and overflows the byte
if( R() == 255 ) R(254);
if( G() == 255 ) G(254);
if( B() == 255 ) R(254);
stage = 0;
renderTime = 0;
}
void FadeEffect::update()
{
if( millis() < renderTime ) return;
switch(stage)
{
case 0:
if( G( G()+1 ) == 255 ) ++stage;
break;
case 1:
if( R( R()-1 ) == 0 ) ++stage;
break;
case 2:
if( B( B()+1 ) == 255 ) ++stage;
break;
case 3:
if( G( G()-1 ) == 0 ) ++stage;
break;
case 4:
if( R( R()+1 ) == 255 ) ++stage;
break;
case 5:
if( B( B()-1 ) == 0 ) ++stage;
break;
}
if( stage == 6 )
stage = 0;
renderTime += ceil((float)m_duration / 1536);
}
| #include "fade_effect.h"
unsigned int FadeEffect::maxDelay()
{
return -1;
}
void FadeEffect::init()
{
// Handle a corner case in which the update just increments
// a color and overflows the byte
if( R() == 255 ) R(254);
if( G() == 255 ) G(254);
if( B() == 255 ) R(254);
if( R() == 0 ) R(1);
if( G() == 0 ) G(1);
if( B() == 0 ) R(1);
stage = 0;
renderTime = 0;
}
void FadeEffect::update()
{
if( millis() < renderTime ) return;
switch(stage)
{
case 0:
if( G( G()+1 ) == 255 ) ++stage;
break;
case 1:
if( R( R()-1 ) == 0 ) ++stage;
break;
case 2:
if( B( B()+1 ) == 255 ) ++stage;
break;
case 3:
if( G( G()-1 ) == 0 ) ++stage;
break;
case 4:
if( R( R()+1 ) == 255 ) ++stage;
break;
case 5:
if( B( B()-1 ) == 0 ) ++stage;
break;
}
if( stage == 6 )
stage = 0;
renderTime += ceil((float)m_duration / 1536);
}
|
Use strtol instead of atol; verify conversion. | // Nikita Kouevda
// 2013/11/01
#include <iostream>
#include "prime.hpp"
using namespace std;
int main(int argc, char *argv[]) {
if (argc < 2) {
cerr << "Usage: prime number ..." << endl;
return 1;
}
for (int i = 1; i < argc; ++i) {
cout << argv[i] << " is";
if (!isPrime(atol(argv[i]))) {
cout << " not";
}
cout << " prime" << endl;
}
return 0;
}
| // Nikita Kouevda
// 2013/11/04
#include <iostream>
#include "prime.hpp"
using namespace std;
int main(int argc, char *argv[]) {
int i, n;
char *endptr;
if (argc < 2) {
cerr << "usage: prime number ..." << endl;
return 1;
}
for (i = 1; i < argc; ++i) {
n = strtol(argv[i], &endptr, 10);
if (*endptr) {
cerr << "prime: illegal argument: " << argv[i] << endl;
continue;
}
cout << argv[i] << " is";
if (!isPrime(n)) {
cout << " not";
}
cout << " prime" << endl;
}
return 0;
}
|
Add basic log on MediaService | #include "MediaServiceHandler.h"
using namespace ::com::kurento::kms::api;
namespace com { namespace kurento { namespace kms {
MediaServerServiceHandler::MediaServerServiceHandler()
{
manager = MediaSessionManager::getInstance();
}
MediaServerServiceHandler::~MediaServerServiceHandler() {
MediaSessionManager::releaseInstance(manager);
}
void MediaServerServiceHandler::createMediaSession(MediaSession& _return) {
_return = manager->createMediaSession();
}
void MediaServerServiceHandler::deleteMediaSession(const MediaSession& session) {
manager->deleteMediaSession(session);
}
}}} // com::kurento::kms
| #include "MediaServiceHandler.h"
#include "log.h"
using namespace ::com::kurento::kms::api;
using ::com::kurento::log::Log;
static Log l("MediaServiceHandler");
#define d(...) aux_debug(l, __VA_ARGS__);
#define i(...) aux_info(l, __VA_ARGS__);
namespace com { namespace kurento { namespace kms {
MediaServerServiceHandler::MediaServerServiceHandler()
{
manager = MediaSessionManager::getInstance();
}
MediaServerServiceHandler::~MediaServerServiceHandler() {
MediaSessionManager::releaseInstance(manager);
}
void MediaServerServiceHandler::createMediaSession(MediaSession& _return) {
i("createMediaSession");
_return = manager->createMediaSession();
}
void MediaServerServiceHandler::deleteMediaSession(const MediaSession& session) {
i("deleteMediaSession");
manager->deleteMediaSession(session);
}
}}} // com::kurento::kms
|
Mark this test as Darwin only. Patch by Bill Wendling. | // Insure __block_holder_tmp is allocated on the stack.
// RUN: %llvmgxx %s -S -O2 -o - | egrep {__block_holder_tmp.*alloca}
// <rdar://problem/5865221>
extern void fubar_dispatch_sync(void (^PP)(void));
void fubar() {
__block void *voodoo;
fubar_dispatch_sync(^(void){voodoo=0;});
}
| // Insure __block_holder_tmp is allocated on the stack. Darwin only.
// RUN: %llvmgxx %s -S -O2 -o - | egrep {__block_holder_tmp.*alloca}
// XFAIL: *
// XTARGET: darwin
// <rdar://problem/5865221>
// END.
extern void fubar_dispatch_sync(void (^PP)(void));
void fubar() {
__block void *voodoo;
fubar_dispatch_sync(^(void){voodoo=0;});
}
|
Make ConstraintType::stringToEnum not case sensitive | #include <constrained_ik/enum_types.h>
#include <ros/console.h>
using namespace constrained_ik::constraint_types;
const std::string ConstraintType::names_[] = {"Primary", "Auxiliary", "Inactive"};
const std::map<std::string, ConstraintTypes> ConstraintType::name_to_enum_map_ = boost::assign::map_list_of ("Primary", Primary) ("Auxiliary", Auxiliary) ("Inactive", Inactive);
ConstraintTypes ConstraintType::stringToEnum(std::string constraint_type_name)
{
std::map<std::string, ConstraintTypes>::const_iterator it;
it = name_to_enum_map_.find(constraint_type_name);
if (it != name_to_enum_map_.end())
return it->second;
else
ROS_ERROR("No enumerator named %s. Valid names: Primary, Auxiliary, Inactive", constraint_type_name.c_str());
}
| #include <constrained_ik/enum_types.h>
#include <ros/console.h>
using namespace constrained_ik::constraint_types;
const std::string ConstraintType::names_[] = {"Primary", "Auxiliary", "Inactive"};
const std::map<std::string, ConstraintTypes> ConstraintType::name_to_enum_map_ = boost::assign::map_list_of ("primary", Primary) ("auxiliary", Auxiliary) ("inactive", Inactive);
ConstraintTypes ConstraintType::stringToEnum(std::string constraint_type_name)
{
std::map<std::string, ConstraintTypes>::const_iterator it;
std::transform(constraint_type_name.begin(), constraint_type_name.end(), constraint_type_name.begin(), ::tolower);
it = name_to_enum_map_.find(constraint_type_name);
if (it != name_to_enum_map_.end())
return it->second;
else
ROS_ERROR("No enumerator named %s. Valid names (Not case sensitive): Primary, Auxiliary, Inactive", constraint_type_name.c_str());
}
|
Document what is expected from UART example | #include <xpcc/architecture.hpp>
#include "../stm32f4_discovery.hpp"
// ----------------------------------------------------------------------------
MAIN_FUNCTION
{
defaultSystemClock::enable();
LedOrange::setOutput(xpcc::Gpio::High);
LedGreen::setOutput(xpcc::Gpio::Low);
LedRed::setOutput(xpcc::Gpio::High);
LedBlue::setOutput(xpcc::Gpio::High);
// Enable USART 2
GpioOutputA2::connect(Usart2::Tx);
GpioInputA3::connect(Usart2::Rx, Gpio::InputType::PullUp);
Usart2::initialize<defaultSystemClock, 9600>(12);
while (1)
{
static uint8_t c = 'A';
LedRed::toggle();
LedGreen::toggle();
Usart2::write(c);
++c;
if (c == 'Z' + 1) {
c = 'A';
}
xpcc::delay_ms(500);
}
return 0;
}
| #include <xpcc/architecture.hpp>
#include "../stm32f4_discovery.hpp"
// ----------------------------------------------------------------------------
/**
* Very basic example of USART usage.
* The ASCII sequence 'A', 'B', 'C, ... , 'Z', 'A', 'B', 'C', ...
* is printed with 9600 baud, 8N1 at pin PA3.
*/
MAIN_FUNCTION
{
defaultSystemClock::enable();
LedOrange::setOutput(xpcc::Gpio::High);
LedGreen::setOutput(xpcc::Gpio::Low);
LedRed::setOutput(xpcc::Gpio::High);
LedBlue::setOutput(xpcc::Gpio::High);
// Enable USART 2
GpioOutputA2::connect(Usart2::Tx);
GpioInputA3::connect(Usart2::Rx, Gpio::InputType::PullUp);
Usart2::initialize<defaultSystemClock, 9600>(12);
while (1)
{
static uint8_t c = 'A';
LedRed::toggle();
LedGreen::toggle();
Usart2::write(c);
++c;
if (c > 'Z') {
c = 'A';
}
xpcc::delay_ms(500);
}
return 0;
}
|
Fix cropped hapticsquare buttons on devices | #include "hapticbutton.h"
#include <QPainter>
HapticButton::HapticButton(const QString &label) :
QWidget(0), m_label(label), m_checked(false), m_checkable(false)
{
setMinimumSize(100, 100);
}
void HapticButton::mousePressEvent(QMouseEvent *)
{
if (m_checkable) {
m_checked = !m_checked;
emit toggled(m_checked);
} else {
emit clicked();
}
}
void HapticButton::paintEvent(QPaintEvent *)
{
QPainter paint(this);
QRect r(0, 0, width()-1, height()-1);
paint.drawRoundedRect(r, 10, 10);
paint.drawText(r, Qt::AlignCenter, m_label);
}
| #include "hapticbutton.h"
#include <QPainter>
HapticButton::HapticButton(const QString &label) :
QWidget(0), m_label(label), m_checked(false), m_checkable(false)
{
setMinimumSize(100, 100);
}
void HapticButton::mousePressEvent(QMouseEvent *)
{
if (m_checkable) {
m_checked = !m_checked;
emit toggled(m_checked);
} else {
emit clicked();
}
}
void HapticButton::paintEvent(QPaintEvent *)
{
QPainter paint(this);
QRect r(1, 1, width()-2, height()-2);
paint.drawRoundedRect(r, 10, 10);
paint.drawText(r, Qt::AlignCenter, m_label);
}
|
Remove formal parameters to avoid complier warning | #include <ccspec/core/formatter.h>
namespace ccspec {
namespace core {
using std::exception_ptr;
using std::list;
using std::ostream;
// public methods.
void Formatter::examplePassed(const ExecutionResult& execution_result) const {
(void) execution_result;
}
void Formatter::exampleFailed(const ExecutionResult& execution_result) const {
(void) execution_result;
}
void Formatter::afterEachHookFailed(exception_ptr failure) const {
(void) failure;
}
void Formatter::aroundHookFailed(exception_ptr failure) const {
(void) failure;
}
void Formatter::startDump() const {}
void Formatter::dumpFailures(const list<exception_ptr>& failures) const {
(void) failures;
}
// Protected methods.
Formatter::Formatter(ostream& output) : output_(output) {}
} // namespace core
} // namespace ccspec
| #include <ccspec/core/formatter.h>
namespace ccspec {
namespace core {
using std::exception_ptr;
using std::list;
using std::ostream;
// public methods.
void Formatter::examplePassed(const ExecutionResult&) const {}
void Formatter::exampleFailed(const ExecutionResult&) const {}
void Formatter::afterEachHookFailed(exception_ptr) const {}
void Formatter::aroundHookFailed(exception_ptr) const {}
void Formatter::startDump() const {}
void Formatter::dumpFailures(const list<exception_ptr>&) const {}
// Protected methods.
Formatter::Formatter(ostream& output) : output_(output) {}
} // namespace core
} // namespace ccspec
|
Remove deprecated set_unexpected and set_terminate | #include <exception>
#include <iostream>
#include <cstdlib>
#include "IMPL/LCIOExceptionHandler.h"
namespace IMPL {
// create one globale instance of the handler
LCIOExceptionHandler* LCIOExceptionHandler::_me = 0 ;
/** Method catches any std::exception, prints the message to stdout
* and then exits the program.
*/
void lcio_unexpected(){
try{
throw ;
}catch( std::exception& e){
std::cout << " A runtime error has occured : "
<< e.what()
<< std::endl
<< " the program will have to be terminated - sorry." << std::endl ;
exit(1) ;
}
}
LCIOExceptionHandler::LCIOExceptionHandler(){
std::set_unexpected( lcio_unexpected ) ;
std::set_terminate( lcio_unexpected ) ;
}
LCIOExceptionHandler* LCIOExceptionHandler::createInstance(){
if( ! _me ){
_me = new LCIOExceptionHandler ;
}
return _me ;
}
}
| #include <exception>
#include <iostream>
#include <cstdlib>
#include "IMPL/LCIOExceptionHandler.h"
namespace IMPL {
// create one globale instance of the handler
LCIOExceptionHandler* LCIOExceptionHandler::_me = 0 ;
/** Method catches any std::exception, prints the message to stdout
* and then exits the program.
*/
void lcio_unexpected(){
try{
throw ;
}catch( std::exception& e){
std::cout << " A runtime error has occured : "
<< e.what()
<< std::endl
<< " the program will have to be terminated - sorry." << std::endl ;
exit(1) ;
}
}
LCIOExceptionHandler::LCIOExceptionHandler(){}
LCIOExceptionHandler* LCIOExceptionHandler::createInstance(){
if( ! _me ){
_me = new LCIOExceptionHandler ;
}
return _me ;
}
}
|
Use the error_type field to check for errors | #include "./compile.h"
#include "tree_sitter/compiler.h"
namespace node_tree_sitter_compiler {
using namespace v8;
NAN_METHOD(Compile) {
String::Utf8Value grammar_json(info[0]);
TSCompileResult compile_result = ts_compile_grammar(*grammar_json);
if (compile_result.error_message) {
Local<Value> error = Nan::Error(compile_result.error_message);
Local<Object>::Cast(error)->Set(Nan::New("isGrammarError").ToLocalChecked(), Nan::True());
Nan::ThrowError(error);
} else {
info.GetReturnValue().Set(Nan::New(compile_result.code).ToLocalChecked());
}
}
} // namespace node_tree_sitter_compiler
| #include "./compile.h"
#include "tree_sitter/compiler.h"
namespace node_tree_sitter_compiler {
using namespace v8;
NAN_METHOD(Compile) {
String::Utf8Value grammar_json(info[0]);
TSCompileResult compile_result = ts_compile_grammar(*grammar_json);
if (compile_result.error_type != TSCompileErrorTypeNone) {
Local<Value> error = Nan::Error(compile_result.error_message);
Local<Object>::Cast(error)->Set(Nan::New("isGrammarError").ToLocalChecked(), Nan::True());
Nan::ThrowError(error);
} else {
info.GetReturnValue().Set(Nan::New(compile_result.code).ToLocalChecked());
}
}
} // namespace node_tree_sitter_compiler
|
Install ISR on PIC32 with updated build script. | #include "platform/platform.h"
#include "WProgram.h"
void openxc::platform::initialize() {
// this is required to initialize the Wiring library from MPIDE's toolchain
// (inspired by Arduino)
init();
}
| #include "platform/platform.h"
#include "WProgram.h"
extern "C" {
extern void __use_isr_install(void);
__attribute__((section(".comment"))) void (*__use_force_isr_install)(void) = &__use_isr_install;
}
void openxc::platform::initialize() {
// this is required to initialize the Wiring library from MPIDE's toolchain
// (inspired by Arduino)
init();
}
|
Test case B is updated to work for 32-bit and 64-bit platforms | // RUN: %clang_cc1 -emit-llvm-only -triple %itanium_abi_triple -fdump-record-layouts %s 2>/dev/null \
// RUN: | FileCheck %s
union A {
int f1: 3;
A();
};
A::A() {}
union B {
int f1: 69;
B();
};
B::B() {}
// CHECK:*** Dumping AST Record Layout
// CHECK-NEXT: 0 | union A
// CHECK-NEXT: 0 | int f1
// CHECK-NEXT: | [sizeof=4, dsize=1, align=4
// CHECK-NEXT: | nvsize=1, nvalign=4]
// CHECK:*** Dumping AST Record Layout
// CHECK-NEXT: 0 | union B
// CHECK-NEXT: 0 | int f1
// CHECK-NEXT: | [{{sizeof=16, dsize=9, align=8|sizeof=12, dsize=9, align=4}}
// CHECK-NEXT: | {{nvsize=9, nvalign=8|nvsize=9, nvalign=4}}]
| // RUN: %clang_cc1 -emit-llvm-only -triple %itanium_abi_triple -fdump-record-layouts %s 2>/dev/null \
// RUN: | FileCheck %s
union A {
int f1: 3;
A();
};
A::A() {}
union B {
char f1: 35;
B();
};
B::B() {}
// CHECK:*** Dumping AST Record Layout
// CHECK-NEXT: 0 | union A
// CHECK-NEXT: 0 | int f1
// CHECK-NEXT: | [sizeof=4, dsize=1, align=4
// CHECK-NEXT: | nvsize=1, nvalign=4]
// CHECK:*** Dumping AST Record Layout
// CHECK-NEXT: 0 | union B
// CHECK-NEXT: 0 | int f1
// CHECK-NEXT: | [sizeof=8, dsize=5, align=4
// CHECK-NEXT: | nvsize=5, nvalign=4]
|
Use full tag for buildings if available | #include "utils.h"
#include <nlohmann/json.hpp>
using json = nlohmann::json;
std::string get_with_def(const std::map<std::string, std::string> &m, const std::string &key,
const std::string &defval)
{
auto it = m.find(key);
if (it == m.end())
return defval;
return it->second;
}
std::map<std::string, std::string> parse_to_map(const std::string &js)
{
std::map<std::string, std::string> m;
if (js.size())
{
json j = json::parse(js);
for (auto v : j.items())
m[v.key()] = v.value();
}
return m;
}
std::string geocoder_type(const std::string &t_class, const std::string &t_value)
{
if (t_class == "building" || t_value == "yes")
return t_class;
return t_class + "_" + t_value;
} | #include "utils.h"
#include <nlohmann/json.hpp>
using json = nlohmann::json;
std::string get_with_def(const std::map<std::string, std::string> &m, const std::string &key,
const std::string &defval)
{
auto it = m.find(key);
if (it == m.end())
return defval;
return it->second;
}
std::map<std::string, std::string> parse_to_map(const std::string &js)
{
std::map<std::string, std::string> m;
if (js.size())
{
json j = json::parse(js);
for (auto v : j.items())
m[v.key()] = v.value();
}
return m;
}
std::string geocoder_type(const std::string &t_class, const std::string &t_value)
{
if (t_value == "yes")
return t_class;
return t_class + "_" + t_value;
} |
Debug which version is build with test-package. | #include "utils/LinearAlg2D.h"
int main(int argc, char** argv)
{
// Pick a function that's not defined in the header.
const float angle =
cura::LinearAlg2D::getAngleLeft
(
cura::Point(1.0, 1.0),
cura::Point(1.0, 2.0),
cura::Point(3.0, 3.0)
);
return (angle != 0.f) ? 0 : 1;
}
| #include "settings/Settings.h" // For the default definition of 'CURA_ENGINE_VERSION' if none is given.
#include "utils/LinearAlg2D.h" // For testing calling a simple non-header function.
#include <cstdio>
int main(int argc, char** argv)
{
// Test which version do we have here?
std::fprintf(stdout, "test-package called for version: %s\n", CURA_ENGINE_VERSION);
// Pick a function that's not defined in the header.
const float angle =
cura::LinearAlg2D::getAngleLeft
(
cura::Point(1.0, 1.0),
cura::Point(1.0, 2.0),
cura::Point(3.0, 3.0)
);
return (angle != 0.f) ? 0 : 1;
}
|
Set the code to MIT license | #include <thread>
#include <mutex>
struct Complex {
std::mutex mutex;
int i;
Complex() : i(0) {}
void mul(int x){
std::lock_guard<std::mutex> lock(mutex);
i *= x;
}
void div(int x){
std::lock_guard<std::mutex> lock(mutex);
i /= x;
}
void both(int x, int y){
std::lock_guard<std::mutex> lock(mutex);
mul(x);
div(y);
}
};
int main(){
Complex complex;
complex.both(32, 23);
return 0;
}
| //=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <thread>
#include <mutex>
struct Complex {
std::mutex mutex;
int i;
Complex() : i(0) {}
void mul(int x){
std::lock_guard<std::mutex> lock(mutex);
i *= x;
}
void div(int x){
std::lock_guard<std::mutex> lock(mutex);
i /= x;
}
void both(int x, int y){
std::lock_guard<std::mutex> lock(mutex);
mul(x);
div(y);
}
};
int main(){
Complex complex;
complex.both(32, 23);
return 0;
}
|
Test that we correctly handle reversion of line splicing etc in raw string literals. As suggested by Sean Silva. | // RUN: %clang_cc1 -fsyntax-only -std=c++11 -verify %s
int a<::> = { 1, 2, 3 };
int b = a<:::a<:0:>:>;
bool c = a<:0:><::b;
template<int &n> void f() {}
template void f<::b>();
#define x a<:: ## : b :>
int d = x; // expected-error {{pasting formed ':::', an invalid preprocessing token}} expected-error {{expected unqualified-id}}
| // RUN: %clang_cc1 -fsyntax-only -std=c++11 -verify %s
int a<::> = { 1, 2, 3 };
int b = a<:::a<:0:>:>;
bool c = a<:0:><::b;
template<int &n> void f() {}
template void f<::b>();
#define x a<:: ## : b :>
int d = x; // expected-error {{pasting formed ':::', an invalid preprocessing token}} expected-error {{expected unqualified-id}}
const char xs[] = R"(\
??=\U0000)";
static_assert(sizeof(xs) == 12, "did not revert all changes");
|
Convert sequence tests to Boost UTF | #include "unit_tests/tests.hpp"
#include "grune/non_terminal.hpp"
using namespace grune;
class sequence_tests : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE(sequence_tests);
CPPUNIT_TEST(test_to_string);
CPPUNIT_TEST_SUITE_END();
public:
void test_to_string()
{
non_terminal A("A");
non_terminal B("B");
symbol c("c");
sequence s { A, B, c };
std::string expected = "A, B, \"c\"";
CPPUNIT_ASSERT_EQUAL(expected, to_string(s));
expected = "\"\"";
CPPUNIT_ASSERT_EQUAL(expected, to_string(sequence()));
sequence_list sl { s, { A, c, B } };
expected = "A, B, \"c\" | A, \"c\", B";
CPPUNIT_ASSERT_EQUAL(expected, to_string(sl));
expected = "\"\"";
CPPUNIT_ASSERT_EQUAL(expected, to_string(sequence_list()));
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(sequence_tests);
| #include "unit_tests/tests.hpp"
#include "grune/non_terminal.hpp"
using namespace grune;
BOOST_AUTO_TEST_SUITE(sequence_tests)
void test_to_string()
{
non_terminal A("A");
non_terminal B("B");
symbol c("c");
sequence s { A, B, c };
std::string expected = "A, B, \"c\"";
BOOST_CHECK_EQUAL(expected, to_string(s));
expected = "\"\"";
BOOST_CHECK_EQUAL(expected, to_string(sequence()));
sequence_list sl { s, { A, c, B } };
expected = "A, B, \"c\" | A, \"c\", B";
BOOST_CHECK_EQUAL(expected, to_string(sl));
expected = "\"\"";
BOOST_CHECK_EQUAL(expected, to_string(sequence_list()));
}
BOOST_AUTO_TEST_SUITE_END()
|
Fix encoding of data in HTTP POST login | #include "login/http-post-login.h"
#include <QNetworkRequest>
#include <QUrlQuery>
#include "models/site.h"
#include "network/network-manager.h"
HttpPostLogin::HttpPostLogin(HttpAuth *auth, Site *site, NetworkManager *manager, MixedSettings *settings)
: HttpLogin("post", auth, site, manager, settings)
{}
NetworkReply *HttpPostLogin::getReply(const QUrl &url, const QUrlQuery &query) const
{
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
return m_manager->post(request, query.query(QUrl::FullyEncoded).toUtf8());
}
| #include "login/http-post-login.h"
#include <QNetworkRequest>
#include <QUrlQuery>
#include "models/site.h"
#include "network/network-manager.h"
HttpPostLogin::HttpPostLogin(HttpAuth *auth, Site *site, NetworkManager *manager, MixedSettings *settings)
: HttpLogin("post", auth, site, manager, settings)
{}
NetworkReply *HttpPostLogin::getReply(const QUrl &url, const QUrlQuery &query) const
{
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
QString data = query.query(QUrl::FullyEncoded)
.replace('+', "%2B")
.replace("%20", "+");
return m_manager->post(request, data.toUtf8());
}
|
Fix illegal access to member | #include <ros/ros.h>
#include <nav_msgs/OccupancyGrid.h>
int main(int argc, char *argv[]){
ros::init(argc, argv, "local_map_2d_publisher");
ros::NodeHandle node;
ros::Publisher map_lc_pub = node.advertise<nav_msgs::OccupancyGrid>("local_map", 1);
const int size = 5;
nav_msgs::OccupancyGrid map_lc;
map_lc.resolution = 2;
map_lc.frame_id = "/world";
map_lc.info.origin.position.x = -size/2;
map_lc.info.origin.position.y = -size/2;
map_lc.header.stamp = ros::Time::now();
map_lc.info.width = size;
map_lc.info.height = size;
map_lc.data.resize(size * size);
for(int row=0; row < size; row++){
for(int col=0; col < size; col++){
map_lc.data[(row*map_lc.info.width)+col] = 0;
}
}
map_lc_pub.publish(map_lc);
ros::spin();
}
| #include <ros/ros.h>
#include <nav_msgs/OccupancyGrid.h>
int main(int argc, char *argv[]){
ros::init(argc, argv, "local_map_2d_publisher");
ros::NodeHandle node;
ros::Publisher map_lc_pub = node.advertise<nav_msgs::OccupancyGrid>("local_map", 1);
const int size = 5;
nav_msgs::OccupancyGrid map_lc;
map_lc.info.resolution = 2;
map_lc.header.frame_id = "/world";
map_lc.header.stamp = ros::Time::now();
map_lc.info.origin.position.x = -size/2;
map_lc.info.origin.position.y = -size/2;
map_lc.info.width = size;
map_lc.info.height = size;
map_lc.data.resize(size * size);
for(int row=0; row < size; row++){
for(int col=0; col < size; col++){
map_lc.data[(row*map_lc.info.width)+col] = 0;
}
}
map_lc_pub.publish(map_lc);
ros::spin();
}
|
Update Problem 4 test case | #include "catch.hpp"
#include "MedianOfTwoSortedArrays.hpp"
TEST_CASE("Median Of Two Sorted Arrays") {
Solution s;
SECTION("Two nums are empty") {
vector<int> nums1;
vector<int> nums2;
REQUIRE(s.findMedianSortedArrays(nums1, nums2) == 0.0);
}
SECTION("Two nums do not overlap") {
vector<int> nums1 {1, 2, 3};
vector<int> nums2 {4, 5, 6};
REQUIRE(s.findMedianSortedArrays(nums1, nums2) == 3.5);
}
}
| #include "catch.hpp"
#include "MedianOfTwoSortedArrays.hpp"
TEST_CASE("Median Of Two Sorted Arrays") {
Solution s;
SECTION("Two nums are empty") {
vector<int> nums1;
vector<int> nums2;
REQUIRE(s.findMedianSortedArrays(nums1, nums2) == 0.0);
}
SECTION("Two nums do not overlap (even case)") {
vector<int> nums1 {1, 2, 3};
vector<int> nums2 {4, 5, 6};
REQUIRE(s.findMedianSortedArrays(nums1, nums2) == 3.5);
}
SECTION("Two overlapped nums (even case)") {
vector<int> nums1 {1, 2, 7};
vector<int> nums2 {4, 5, 6};
REQUIRE(s.findMedianSortedArrays(nums1, nums2) == 4.5);
}
SECTION("Two nums do not overlap (odd case)") {
vector<int> nums1 {1, 2};
vector<int> nums2 {4, 5, 6};
REQUIRE(s.findMedianSortedArrays(nums1, nums2) == 4.0);
}
SECTION("Two overlapped nums (odd case)") {
vector<int> nums1 {1, 7};
vector<int> nums2 {4, 5, 6};
REQUIRE(s.findMedianSortedArrays(nums1, nums2) == 5.0);
}
}
|
Use resize to specify the size of the central widget | #include "../src/engine.h"
#include "drawdevice.h"
#include <QtGui>
int main(int argc, char *argv[])
{
Engine *eng = new Engine;
if (!eng->loadWorldFromFile("world.rooms"))
{
eng->getLogger()->write("ERROR: cannot load world.rooms!", Log::ERROR);
delete eng;
return 1;
}
QApplication qt_app(argc, argv);
QFile file("style.qss");
if (file.exists())
{
file.open(QFile::ReadOnly);
QString styleSheet = QLatin1String(file.readAll());
qt_app.setStyleSheet(styleSheet);
}
QMainWindow qt_wnd;
RoomsManager *man = eng->getRoomsManager();
qt_wnd.setBaseSize(man->width(), man->height());
qt_wnd.setWindowTitle(man->worldName().c_str());
DrawDevice qt_draw_device(eng, &qt_wnd);
qt_draw_device.initialize();
qt_wnd.setCentralWidget(&qt_draw_device);
qt_wnd.show();
int r = qt_app.exec();
delete eng;
return r;
}
| #include "../src/engine.h"
#include "drawdevice.h"
#include <QtGui>
int main(int argc, char *argv[])
{
Engine *eng = new Engine;
if (!eng->loadWorldFromFile("world.rooms"))
{
eng->getLogger()->write("ERROR: cannot load world.rooms!", Log::ERROR);
delete eng;
return 1;
}
QApplication qt_app(argc, argv);
QFile file("style.qss");
if (file.exists())
{
file.open(QFile::ReadOnly);
QString styleSheet = QLatin1String(file.readAll());
qt_app.setStyleSheet(styleSheet);
}
QMainWindow qt_wnd;
RoomsManager *man = eng->getRoomsManager();
qt_wnd.resize(man->width(), man->height());
qt_wnd.setWindowTitle(man->worldName().c_str());
DrawDevice qt_draw_device(eng, &qt_wnd);
qt_draw_device.initialize();
qt_wnd.setCentralWidget(&qt_draw_device);
qt_wnd.show();
int r = qt_app.exec();
delete eng;
return r;
}
|
Fix for High DPI Screens | #include "EpsilonDashboard.h"
#include <QApplication>
#include <QLockFile>
#include <QDebug>
#include <QDir>
int main(int argc, char* argv[])
{
QString tmpDir = QDir::tempPath();
QLockFile lockFile(tmpDir + "/epsilonDashboard.lock");
/* Trying to close the Lock File, if the attempt is unsuccessful for 100 milliseconds,
* then there is a Lock File already created by another process.
* Therefore, we issue a warning and close the program
*/
if (!lockFile.tryLock(100))
{
qDebug() << "An instance of dashboard already exists.";
qDebug() << "If you are sure you only have one instance of dashboard running, please delete the file /tmp/epsilonDashboard.lock as root.";
qDebug() << "Quitting...";
return 1;
}
else
{
qDebug() << "No other instance of dashboard exists.";
qDebug() << "Launching dashboard...";
}
QScopedPointer<EpsilonDashboard> app;
app.reset(new EpsilonDashboard(argc, argv));
return app->exec();
}
| #include "EpsilonDashboard.h"
#include <QApplication>
#include <QLockFile>
#include <QDebug>
#include <QDir>
int main(int argc, char* argv[])
{
#if QT_VERSION >= 0x050600
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
QString tmpDir = QDir::tempPath();
QLockFile lockFile(tmpDir + "/epsilonDashboard.lock");
/* Trying to close the Lock File, if the attempt is unsuccessful for 100 milliseconds,
* then there is a Lock File already created by another process.
* Therefore, we issue a warning and close the program
*/
if (!lockFile.tryLock(100))
{
qDebug() << "An instance of dashboard already exists.";
qDebug() << "If you are sure you only have one instance of dashboard running, please delete the file /tmp/epsilonDashboard.lock as root.";
qDebug() << "Quitting...";
return 1;
}
else
{
qDebug() << "No other instance of dashboard exists.";
qDebug() << "Launching dashboard...";
}
QScopedPointer<EpsilonDashboard> app;
app.reset(new EpsilonDashboard(argc, argv));
return app->exec();
}
|
Use mergeable strings sections on sparc | //===-- SparcTargetAsmInfo.cpp - Sparc asm properties -----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declarations of the SparcTargetAsmInfo properties.
//
//===----------------------------------------------------------------------===//
#include "SparcTargetAsmInfo.h"
using namespace llvm;
SparcELFTargetAsmInfo::SparcELFTargetAsmInfo(const TargetMachine &TM):
ELFTargetAsmInfo(TM) {
Data16bitsDirective = "\t.half\t";
Data32bitsDirective = "\t.word\t";
Data64bitsDirective = 0; // .xword is only supported by V9.
ZeroDirective = "\t.skip\t";
CommentString = "!";
ConstantPoolSection = "\t.section \".rodata\",#alloc\n";
COMMDirectiveTakesAlignment = true;
}
std::string SparcELFTargetAsmInfo::PrintSectionFlags(unsigned flags) const {
std::string Flags = ",";
if (flags & SectionFlags::Mergeable)
return ELFTargetAsmInfo::PrintSectionFlags(flags);
if (!(flags & SectionFlags::Debug))
Flags += "#alloc";
if (flags & SectionFlags::Code)
Flags += "#execinstr";
if (flags & SectionFlags::Writeable)
Flags += "#write";
if (flags & SectionFlags::TLS)
Flags += "#tls";
return Flags;
}
| //===-- SparcTargetAsmInfo.cpp - Sparc asm properties -----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declarations of the SparcTargetAsmInfo properties.
//
//===----------------------------------------------------------------------===//
#include "SparcTargetAsmInfo.h"
using namespace llvm;
SparcELFTargetAsmInfo::SparcELFTargetAsmInfo(const TargetMachine &TM):
ELFTargetAsmInfo(TM) {
Data16bitsDirective = "\t.half\t";
Data32bitsDirective = "\t.word\t";
Data64bitsDirective = 0; // .xword is only supported by V9.
ZeroDirective = "\t.skip\t";
CommentString = "!";
ConstantPoolSection = "\t.section \".rodata\",#alloc\n";
COMMDirectiveTakesAlignment = true;
CStringSection=".rodata.str";
}
std::string SparcELFTargetAsmInfo::PrintSectionFlags(unsigned flags) const {
std::string Flags = ",";
if (flags & SectionFlags::Mergeable)
return ELFTargetAsmInfo::PrintSectionFlags(flags);
if (!(flags & SectionFlags::Debug))
Flags += "#alloc";
if (flags & SectionFlags::Code)
Flags += "#execinstr";
if (flags & SectionFlags::Writeable)
Flags += "#write";
if (flags & SectionFlags::TLS)
Flags += "#tls";
return Flags;
}
|
Add bindings for parse_result hints. | #include <emscripten/bind.h>
#include "checksieve.h"
using namespace emscripten;
EMSCRIPTEN_BINDINGS(sieve) {
value_object<yy::position>("position")
.field("column", &yy::position::column)
.field("line", &yy::position::line)
;
value_object<yy::location>("location")
.field("begin", &yy::location::begin)
.field("end", &yy::location::end)
;
value_object<sieve::parse_result>("parse_result")
.field("location", &sieve::parse_result::location)
.field("status", &sieve::parse_result::status)
.field("error", &sieve::parse_result::error)
;
class_<sieve::parse_options>("parse_options")
.constructor<>()
;
function("version", optional_override(
[](){
return std::string(sieve::version());
}));
function("sieve_parse_string", optional_override(
[](const std::string s, struct sieve::parse_options o) {
return sieve_parse_string(s.c_str(), o);
}));
}
| #include <emscripten/bind.h>
#include "checksieve.h"
using namespace emscripten;
EMSCRIPTEN_BINDINGS(sieve) {
value_object<yy::position>("position")
.field("column", &yy::position::column)
.field("line", &yy::position::line)
;
value_object<yy::location>("location")
.field("begin", &yy::location::begin)
.field("end", &yy::location::end)
;
value_object<sieve::parse_result>("parse_result")
.field("location", &sieve::parse_result::location)
.field("status", &sieve::parse_result::status)
.field("error", &sieve::parse_result::error)
.field("hint", &sieve::parse_result::hint)
;
class_<sieve::parse_options>("parse_options")
.constructor<>()
;
function("version", optional_override(
[](){
return std::string(sieve::version());
}));
function("sieve_parse_string", optional_override(
[](const std::string s, struct sieve::parse_options o) {
return sieve_parse_string(s.c_str(), o);
}));
}
|
Enable DW2 unwind helper on MacOS. | #include <qv4unwindhelper.h>
#include <wtf/Platform.h>
#if CPU(X86_64) && OS(LINUX)
# define USE_DW2_HELPER
#elif CPU(X86) && OS(LINUX)
# define USE_DW2_HELPER
#elif OS(WINDOWS)
// SJLJ will unwind on Windows
# define USE_NULL_HELPER
#elif OS(IOS)
// SJLJ will unwind on iOS
# define USE_NULL_HELPER
#elif OS(ANDROID)
# warning "TODO!"
# define USE_NULL_HELPER
#else
# warning "Unsupported/untested platform!"
# define USE_NULL_HELPER
#endif
#ifdef USE_DW2_HELPER
# include <qv4unwindhelper_p-dw2.h>
#endif // USE_DW2_HELPER
#ifdef USE_NULL_HELPER
using namespace QQmlJS::VM;
UnwindHelper *UnwindHelper::create() { return 0; }
UnwindHelper::UnwindHelper() {}
UnwindHelper::~UnwindHelper() {}
void UnwindHelper::registerFunction(Function *function) {Q_UNUSED(function);}
void UnwindHelper::registerFunctions(QVector<Function *> functions) {Q_UNUSED(functions);}
void UnwindHelper::deregisterFunction(Function *function) {Q_UNUSED(function);}
void UnwindHelper::deregisterFunctions(QVector<Function *> functions) {Q_UNUSED(functions);}
#endif // USE_NULL_HELPER
| #include <qv4unwindhelper.h>
#include <wtf/Platform.h>
#if CPU(X86_64) && (OS(LINUX) || OS(MAC_OS_X))
# define USE_DW2_HELPER
#elif CPU(X86) && OS(LINUX)
# define USE_DW2_HELPER
#elif OS(WINDOWS)
// SJLJ will unwind on Windows
# define USE_NULL_HELPER
#elif OS(IOS)
// SJLJ will unwind on iOS
# define USE_NULL_HELPER
#elif OS(ANDROID)
# warning "TODO!"
# define USE_NULL_HELPER
#else
# warning "Unsupported/untested platform!"
# define USE_NULL_HELPER
#endif
#ifdef USE_DW2_HELPER
# include <qv4unwindhelper_p-dw2.h>
#endif // USE_DW2_HELPER
#ifdef USE_NULL_HELPER
using namespace QQmlJS::VM;
UnwindHelper *UnwindHelper::create() { return 0; }
UnwindHelper::UnwindHelper() {}
UnwindHelper::~UnwindHelper() {}
void UnwindHelper::registerFunction(Function *function) {Q_UNUSED(function);}
void UnwindHelper::registerFunctions(QVector<Function *> functions) {Q_UNUSED(functions);}
void UnwindHelper::deregisterFunction(Function *function) {Q_UNUSED(function);}
void UnwindHelper::deregisterFunctions(QVector<Function *> functions) {Q_UNUSED(functions);}
#endif // USE_NULL_HELPER
|
Add a basic implementation for __cxa_pure_virtual | #include <cstdlib>
extern "C" void __cxa_pure_virtual()
{
}
void* operator new(size_t size)
{
return malloc(size);
}
void* operator new[](size_t size)
{
return malloc(size);
}
void operator delete(void *ptr)
{
free(ptr);
}
void operator delete[](void *ptr)
{
free(ptr);
}
| #include <os/Board.h>
#include <cstdio>
#include <cstdlib>
extern "C" void __cxa_pure_virtual()
{
printf("__cxa_pure_virtual() called. Probably a bad build.\n");
os::board::shutdown();
}
void* operator new(size_t size)
{
return malloc(size);
}
void* operator new[](size_t size)
{
return malloc(size);
}
void operator delete(void *ptr)
{
free(ptr);
}
void operator delete[](void *ptr)
{
free(ptr);
}
|
Add started and ended timestamps | #include <GL/glew.h>
#include "editor.h"
#include <util.h>
#include <QtWidgets/QApplication>
int main(int argc, char *argv[]) {
freopen(util::savePath("editor_log.txt").c_str(), "a", stderr);
QApplication a(argc, argv);
Editor w;
w.show();
return a.exec();
}
| #include <GL/glew.h>
#include "editor.h"
#include <util.h>
#include <QtWidgets/QApplication>
int main(int argc, char *argv[]) {
freopen(util::savePath("editor_log.txt").c_str(), "a", stderr);
util::logWithTime("Editor started");
QApplication a(argc, argv);
Editor w;
w.show();
int result = a.exec();
util::logWithTime("Editor ended");
return result;
}
|
Use initializer list syntax to construct the vector of strings | #include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
int main(int argc, char* argv[])
{
using namespace std;
vector<string> cmdlineargs(argv+1, argv+argc);
for(auto rbiterv=cmdlineargs.rbegin(); rbiterv != cmdlineargs.rend(); ++rbiterv) {
auto& arg = *rbiterv;
for(auto rbiterarg = arg.rbegin(); rbiterarg != arg.rend(); ++rbiterarg) {
cout << *rbiterarg;
}
cout << endl;
}
return EXIT_SUCCESS;
}
| #include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
int main(int argc, char* argv[])
{
using namespace std;
vector<string> cmdlineargs {argv+1, argv+argc};
for(auto rbiterv=cmdlineargs.rbegin(); rbiterv != cmdlineargs.rend(); ++rbiterv) {
auto& arg = *rbiterv;
for(auto rbiterarg = arg.rbegin(); rbiterarg != arg.rend(); ++rbiterarg) {
cout << *rbiterarg;
}
cout << endl;
}
return EXIT_SUCCESS;
}
|
Fix |started_| variable for Device Motion Android data fetcher. | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "data_fetcher_shared_memory.h"
#include "base/logging.h"
#include "data_fetcher_impl_android.h"
namespace content {
DataFetcherSharedMemory::~DataFetcherSharedMemory() {
if (started_)
StopFetchingDeviceMotionData();
}
bool DataFetcherSharedMemory::NeedsPolling() {
return false;
}
bool DataFetcherSharedMemory::FetchDeviceMotionDataIntoBuffer() {
NOTREACHED();
return false;
}
bool DataFetcherSharedMemory::StartFetchingDeviceMotionData(
DeviceMotionHardwareBuffer* buffer) {
DCHECK(buffer);
device_motion_buffer_ = buffer;
return DataFetcherImplAndroid::GetInstance()->
StartFetchingDeviceMotionData(buffer);
started_ = true;
}
void DataFetcherSharedMemory::StopFetchingDeviceMotionData() {
DataFetcherImplAndroid::GetInstance()->StopFetchingDeviceMotionData();
started_ = false;
}
} // namespace content
| // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "data_fetcher_shared_memory.h"
#include "base/logging.h"
#include "data_fetcher_impl_android.h"
namespace content {
DataFetcherSharedMemory::~DataFetcherSharedMemory() {
if (started_)
StopFetchingDeviceMotionData();
}
bool DataFetcherSharedMemory::NeedsPolling() {
return false;
}
bool DataFetcherSharedMemory::FetchDeviceMotionDataIntoBuffer() {
NOTREACHED();
return false;
}
bool DataFetcherSharedMemory::StartFetchingDeviceMotionData(
DeviceMotionHardwareBuffer* buffer) {
DCHECK(buffer);
device_motion_buffer_ = buffer;
started_ = DataFetcherImplAndroid::GetInstance()->
StartFetchingDeviceMotionData(buffer);
return started_;
}
void DataFetcherSharedMemory::StopFetchingDeviceMotionData() {
DataFetcherImplAndroid::GetInstance()->StopFetchingDeviceMotionData();
started_ = false;
}
} // namespace content
|
Stop the source before exit | #include <chrono>
#include <thread>
#include "AudioSubsystem.h"
#include "AudioSubsystem_OpenAL.h"
#include "Decoders/iWaveDataProvider.h"
#include "Decoders/WAV/WAVDataProvider.h"
#include "Utils.h"
int main( int argc, char* argv[] )
{
const char* FileName = ( argc > 1 ) ? argv[1] : "test.wav";
auto AudioSubsystem = CreateAudioSubsystem_OpenAL();
AudioSubsystem->Start();
auto TestBlob = ReadFileAsBlob( FileName );
auto Provider = CreateWaveDataProvider( FileName, TestBlob );
auto Source = AudioSubsystem->CreateAudioSource();
Source->BindDataProvider( Provider );
Source->Play();
while ( Source->IsPlaying() && !IsKeyPressed() );
std::this_thread::sleep_for( std::chrono::milliseconds(300) );
Source = nullptr;
AudioSubsystem->Stop();
return 0;
};
| #include <chrono>
#include <thread>
#include "AudioSubsystem.h"
#include "AudioSubsystem_OpenAL.h"
#include "Decoders/iWaveDataProvider.h"
#include "Decoders/WAV/WAVDataProvider.h"
#include "Utils.h"
int main( int argc, char* argv[] )
{
const char* FileName = ( argc > 1 ) ? argv[1] : "test.wav";
auto AudioSubsystem = CreateAudioSubsystem_OpenAL();
AudioSubsystem->Start();
auto TestBlob = ReadFileAsBlob( FileName );
auto Provider = CreateWaveDataProvider( FileName, TestBlob );
auto Source = AudioSubsystem->CreateAudioSource();
Source->BindDataProvider( Provider );
Source->Play();
while ( Source->IsPlaying() && !IsKeyPressed() );
std::this_thread::sleep_for( std::chrono::milliseconds(300) );
Source->Stop();
Source = nullptr;
AudioSubsystem->Stop();
return 0;
};
|
Fix warning about unused parameter | #include "qmljscodestylesettingsfactory.h"
#include "qmljscodestylesettingspage.h"
#include "qmljstoolsconstants.h"
#include <texteditor/tabpreferences.h>
#include <texteditor/tabsettings.h>
#include <QtGui/QLayout>
using namespace QmlJSTools;
QmlJSCodeStylePreferencesFactory::QmlJSCodeStylePreferencesFactory()
{
}
QString QmlJSCodeStylePreferencesFactory::languageId()
{
return Constants::QML_JS_SETTINGS_ID;
}
QString QmlJSCodeStylePreferencesFactory::displayName()
{
return Constants::QML_JS_SETTINGS_NAME;
}
TextEditor::IFallbackPreferences *QmlJSCodeStylePreferencesFactory::createPreferences(
const QList<TextEditor::IFallbackPreferences *> &fallbacks) const
{
return 0;
}
QWidget *QmlJSCodeStylePreferencesFactory::createEditor(TextEditor::IFallbackPreferences *preferences,
TextEditor::TabPreferences *tabPreferences,
QWidget *parent) const
{
Q_UNUSED(preferences)
Internal::QmlJSCodeStylePreferencesWidget *widget = new Internal::QmlJSCodeStylePreferencesWidget(parent);
widget->layout()->setMargin(0);
widget->setTabPreferences(tabPreferences);
return widget;
}
| #include "qmljscodestylesettingsfactory.h"
#include "qmljscodestylesettingspage.h"
#include "qmljstoolsconstants.h"
#include <texteditor/tabpreferences.h>
#include <texteditor/tabsettings.h>
#include <QtGui/QLayout>
using namespace QmlJSTools;
QmlJSCodeStylePreferencesFactory::QmlJSCodeStylePreferencesFactory()
{
}
QString QmlJSCodeStylePreferencesFactory::languageId()
{
return Constants::QML_JS_SETTINGS_ID;
}
QString QmlJSCodeStylePreferencesFactory::displayName()
{
return Constants::QML_JS_SETTINGS_NAME;
}
TextEditor::IFallbackPreferences *QmlJSCodeStylePreferencesFactory::createPreferences(
const QList<TextEditor::IFallbackPreferences *> &fallbacks) const
{
Q_UNUSED(fallbacks);
return 0;
}
QWidget *QmlJSCodeStylePreferencesFactory::createEditor(TextEditor::IFallbackPreferences *preferences,
TextEditor::TabPreferences *tabPreferences,
QWidget *parent) const
{
Q_UNUSED(preferences)
Internal::QmlJSCodeStylePreferencesWidget *widget = new Internal::QmlJSCodeStylePreferencesWidget(parent);
widget->layout()->setMargin(0);
widget->setTabPreferences(tabPreferences);
return widget;
}
|
Make walls draw what they actually do | #include "Wall.h"
Wall::Wall(Vector b, Vector t) :
b_(b),
t_(t)
{
}
bool Wall::OnLeft(Vector p) {
return (p.i < b_.i);
}
bool Wall::Between(Vector p) {
return (p.j < t_.j) && (p.j > b_.j);
}
float Wall::Left() {
return b_.i - 0.1;
}
float Wall::Right() {
return b_.i + 0.1;
}
void Wall::Draw() {
glColor3f(0, 0, 0);
glBegin(GL_LINES);
glVertex2f(b_.i, b_.j);
glVertex2f(t_.i, t_.j);
glEnd();
}
| #include "Wall.h"
Wall::Wall(Vector b, Vector t) :
b_(b),
t_(t)
{
}
bool Wall::OnLeft(Vector p) {
return (p.i < b_.i);
}
bool Wall::Between(Vector p) {
return (p.j < t_.j) && (p.j > b_.j);
}
float Wall::Left() {
return b_.i - 0.1;
}
float Wall::Right() {
return b_.i + 0.1;
}
void Wall::Draw() {
glColor3f(0, 0, 0);
glBegin(GL_LINES);
glVertex2f(b_.i, b_.j);
glVertex2f(b_.i, t_.j);
glEnd();
}
|
Add more commenting to serial echo example | #include "board.h"
#include <aery32/all.h>
using namespace aery;
#define UART0_PINMASK ((1 << 0) | (1 << 1))
int main(void)
{
init_board();
gpio_init_pins(porta, UART0_PINMASK, GPIO_FUNCTION_A);
gpio_set_pin_high(LED);
/*
* Initializes USART0 in async mode with 8 data bits, 1 stop bit
* and no parity. After then sets up baud rate to 115200 bit/s
* (error 0.8%) and enables rx/tx.
*/
usart_init_serial(usart0);
usart_setup_speed(usart0, USART_CLK_PBA, 71);
usart_enable_rx(usart0);
usart_enable_tx(usart0);
#define BUFSIZE 100
char buf[BUFSIZE] = "";
for(;;) {
usart_puts(usart0, "in: ");
usart_gets(usart0, buf, BUFSIZE);
usart_puts(usart0, "\r\nout: ");
usart_puts(usart0, buf);
usart_puts(usart0, "\r\n\n");
}
return 0;
}
| #include "board.h"
#include <aery32/all.h>
using namespace aery;
int main(void)
{
init_board();
/*
* In UC3A:
* PA00 => RXD
* PA01 => TXD
*/
#define UART0_SERIAL_PINMASK (0x1)
gpio_init_pins(porta, UART0_SERIAL_PINMASK, GPIO_FUNCTION_A);
/*
* Initializes USART0 in async mode with 8 data bits, 1 stop bit
* and no parity. After then sets up baud rate to 115200 bit/s
* (error 0.8%) and enables rx/tx.
*
* Baud rate divider has been selected in assumption that
* F_PBA is 66 MHz.
*/
usart_init_serial(usart0);
usart_setup_speed(usart0, USART_CLK_PBA, 71);
usart_enable_rx(usart0);
usart_enable_tx(usart0);
gpio_set_pin_high(LED);
#define BUFSIZE 100
char buf[BUFSIZE] = "";
for(;;) {
usart_puts(usart0, "in: ");
usart_gets(usart0, buf, BUFSIZE);
usart_puts(usart0, "\r\nout: ");
usart_puts(usart0, buf);
usart_puts(usart0, "\r\n\n");
}
return 0;
}
|
Use QQuickView instead of QQmlEngine. | #include <QGuiApplication>
#include <QQmlEngine>
#include <QQmlContext>
#include <QQmlComponent>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlEngine engine;
QQmlContext *objectContext = new QQmlContext(engine.rootContext());
QQmlComponent component(&engine, "main.qml");
QObject *object = component.create(objectContext);
// ... delete object and objectContext when necessary
return app.exec();
}
| #include <QGuiApplication>
#include <QQuickView>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQuickView view;
view.setSource(QUrl::fromLocalFile("main.qml"));
view.show();
return app.exec();
}
|
Add basic x3 parsing demo test | #include <catch.hpp>
#include "../wold.hpp"
namespace wold {
TEST_CASE("foo", "[]") {
REQUIRE(foo() == 42);
}
} // namespace wold
| #include <catch.hpp>
#include "../wold.hpp"
#include <boost/spirit/home/x3.hpp>
#include <iostream>
namespace wold {
TEST_CASE("foo", "[]") {
REQUIRE(foo() == 42);
}
TEST_CASE("parsing", "[]") {
using boost::spirit::x3::double_;
using boost::spirit::x3::ascii::space;
auto text = std::string(" val 12.3 ");
double result;
auto success = boost::spirit::x3::phrase_parse(
text.begin(), text.end(),
"val" >> double_,
space,
result);
REQUIRE(success);
std::cout << result << "\n";
}
} // namespace wold
|
Clear image after GPU upload. | #include "graphics/texture.h"
#include "graphics/opengl.h"
namespace sp {
void BasicTexture::setRepeated(bool)
{
}
void BasicTexture::setSmooth(bool value)
{
smooth = value;
}
void BasicTexture::loadFromImage(Image&& image)
{
this->image = std::move(image);
}
void BasicTexture::bind()
{
if (handle == 0)
{
glGenTextures(1, &handle);
glBindTexture(GL_TEXTURE_2D, handle);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, smooth ? GL_LINEAR : GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, smooth ? GL_LINEAR : GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.getSize().x, image.getSize().y, 0, GL_RGBA, GL_UNSIGNED_BYTE, image.getPtr());
}
glBindTexture(GL_TEXTURE_2D, handle);
}
}
| #include "graphics/texture.h"
#include "graphics/opengl.h"
namespace sp {
void BasicTexture::setRepeated(bool)
{
}
void BasicTexture::setSmooth(bool value)
{
smooth = value;
}
void BasicTexture::loadFromImage(Image&& image)
{
this->image = std::move(image);
}
void BasicTexture::bind()
{
if (handle == 0)
{
glGenTextures(1, &handle);
glBindTexture(GL_TEXTURE_2D, handle);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, smooth ? GL_LINEAR : GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, smooth ? GL_LINEAR : GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.getSize().x, image.getSize().y, 0, GL_RGBA, GL_UNSIGNED_BYTE, image.getPtr());
image = {};
}
glBindTexture(GL_TEXTURE_2D, handle);
}
}
|
Correct the set thread name macro | /*
* AvanceDB - an in-memory database similar to Apache CouchDB
* Copyright (C) 2015-2017 Ripcord Software
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "set_thread_name.h"
#if __GNUG__ && not defined(__clang__)
#include <pthread.h>
bool SetThreadName::Set(std::thread& thread, const char* name) {
auto status = ::pthread_setname_np(thread.native_handle(), name) == 0;
return status;
}
bool SetThreadName::Set(const char* name) {
auto status = pthread_setname_np(::pthread_self(), name) == 0;
return status;
}
#else
bool SetThreadName::Set(std::thread&, const char*) {
return false;
}
bool SetThreadName::Set(const char*) {
return false;
}
#endif | /*
* AvanceDB - an in-memory database similar to Apache CouchDB
* Copyright (C) 2015-2017 Ripcord Software
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "set_thread_name.h"
#if __GNUG__ && !defined(__clang__)
#include <pthread.h>
bool SetThreadName::Set(std::thread& thread, const char* name) {
auto status = ::pthread_setname_np(thread.native_handle(), name) == 0;
return status;
}
bool SetThreadName::Set(const char* name) {
auto status = pthread_setname_np(::pthread_self(), name) == 0;
return status;
}
#else
bool SetThreadName::Set(std::thread&, const char*) {
return false;
}
bool SetThreadName::Set(const char*) {
return false;
}
#endif |
Fix warning in test - missing exception specifier for overload of operator new | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <locale>
// template <> class ctype<char>
// ~ctype();
#include <locale>
#include <cassert>
#include <new>
unsigned delete_called = 0;
void* operator new[](size_t sz)
{
return operator new(sz);
}
void operator delete[](void* p) throw()
{
operator delete(p);
++delete_called;
}
int main()
{
{
delete_called = 0;
std::locale l(std::locale::classic(), new std::ctype<char>);
assert(delete_called == 0);
}
assert(delete_called == 0);
{
std::ctype<char>::mask table[256];
delete_called = 0;
std::locale l(std::locale::classic(), new std::ctype<char>(table));
assert(delete_called == 0);
}
assert(delete_called == 0);
{
delete_called = 0;
std::locale l(std::locale::classic(),
new std::ctype<char>(new std::ctype<char>::mask[256], true));
assert(delete_called == 0);
}
assert(delete_called == 1);
}
| //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <locale>
// template <> class ctype<char>
// ~ctype();
#include <locale>
#include <cassert>
#include <new>
unsigned delete_called = 0;
void* operator new[](size_t sz) throw(std::bad_alloc)
{
return operator new(sz);
}
void operator delete[](void* p) throw()
{
operator delete(p);
++delete_called;
}
int main()
{
{
delete_called = 0;
std::locale l(std::locale::classic(), new std::ctype<char>);
assert(delete_called == 0);
}
assert(delete_called == 0);
{
std::ctype<char>::mask table[256];
delete_called = 0;
std::locale l(std::locale::classic(), new std::ctype<char>(table));
assert(delete_called == 0);
}
assert(delete_called == 0);
{
delete_called = 0;
std::locale l(std::locale::classic(),
new std::ctype<char>(new std::ctype<char>::mask[256], true));
assert(delete_called == 0);
}
assert(delete_called == 1);
}
|
Move direction reader from console. | #include <iostream>
int main() {
std::cout << "hello world" << std::endl;
return 0;
}
| #include <iostream>
//#include <stdio.h>
enum MoveDirection { LEFT, UP, RIGHT, DOWN };
class ConsoleMoveDirectionReader {
public:
MoveDirection next() {
while (true) {
int keyCode = std::cin.get();
if (keyCode == 97) {
return MoveDirection::LEFT;
break;
}
else if (keyCode == 115) {
return MoveDirection::DOWN;
break;
}
else if (keyCode == 100) {
return MoveDirection::RIGHT;
break;
}
else if (keyCode == 119) {
return MoveDirection::UP;
break;
}
}
}
};
int main() {
std::cout << "hello world" << std::endl;
ConsoleMoveDirectionReader directionReader;
MoveDirection direction = directionReader.next();
std::cout << (int)direction << std::endl;
return 0;
}
|
Make message size check return true to not break tests | #include "wav_embedding_agent.hh"
void WAV_embedding_agent::embed() {
// TODO: implement
}
void WAV_embedding_agent::save() const {
// TODO: implement
}
std::vector<unsigned> WAV_embedding_agent::message_to_masks(const std::string& msg, Mask_type mask_type) {
// TODO: implement
// do fun things until we implement function for real
std::move(msg);
std::move(mask_type);
return std::vector<unsigned>();
}
bool WAV_embedding_agent::check_msg_media_capacity(const std::string& msg) {
// TODO: implement
// do fun things until we implement function for real
std::move(msg);
return false;
}
| #include "wav_embedding_agent.hh"
void WAV_embedding_agent::embed() {
// TODO: implement
}
void WAV_embedding_agent::save() const {
// TODO: implement
}
std::vector<unsigned> WAV_embedding_agent::message_to_masks(const std::string& msg, Mask_type mask_type) {
// TODO: implement
// do fun things until we implement function for real
std::move(msg);
std::move(mask_type);
return std::vector<unsigned>();
}
bool WAV_embedding_agent::check_msg_media_capacity(const std::string& msg) {
// TODO: implement
// do fun things until we implement function for real
std::move(msg);
return true;
}
|
Fix duplicate symbol in memory tracker. | /*
* Copyright (C) 2019 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 "core/vulkan/vk_memory_tracker_layer/cc/layer.h"
namespace memory_tracker {
VkResult vkCreateDevice(PFN_vkCreateDevice fn, VkPhysicalDevice physicalDevice,
const VkDeviceCreateInfo* pCreateInfo,
AllocationCallbacks pAllocator, VkDevice* pDevice) {
return fn(physicalDevice, pCreateInfo, pAllocator, pDevice);
}
void vkCmdDraw(PFN_vkCmdDraw fn, VkCommandBuffer commandBuffer,
uint32_t vertexCount, uint32_t instanceCount,
uint32_t firstVertex, uint32_t firstInstance) {
return fn(commandBuffer, vertexCount, instanceCount, firstVertex,
firstInstance);
}
VkResult vkQueueSubmit(PFN_vkQueueSubmit fn, VkQueue queue,
uint32_t submitCount, const VkSubmitInfo* pSubmits,
VkFence fence) {
return fn(queue, submitCount, pSubmits, fence);
}
VkResult vkCreateInstance(PFN_vkCreateInstance fn,
const VkInstanceCreateInfo* pCreateInfo,
AllocationCallbacks pAllocator,
VkInstance* pInstance) {
return fn(pCreateInfo, pAllocator, pInstance);
}
} // namespace memory_tracker | /*
* Copyright (C) 2019 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 "core/vulkan/vk_memory_tracker_layer/cc/layer.h"
namespace memory_tracker {
void vkCmdDraw(PFN_vkCmdDraw fn, VkCommandBuffer commandBuffer,
uint32_t vertexCount, uint32_t instanceCount,
uint32_t firstVertex, uint32_t firstInstance) {
return fn(commandBuffer, vertexCount, instanceCount, firstVertex,
firstInstance);
}
VkResult vkQueueSubmit(PFN_vkQueueSubmit fn, VkQueue queue,
uint32_t submitCount, const VkSubmitInfo* pSubmits,
VkFence fence) {
return fn(queue, submitCount, pSubmits, fence);
}
} // namespace memory_tracker |
Use helper function to get the new rotation | #include "box2dbaseitem.h"
#include "util.h"
#include <Box2D/Box2D.h>
float Box2DBaseItem::m_scaleRatio = 32.0f;
Box2DBaseItem::Box2DBaseItem(GameScene *parent )
: GameItem(parent)
, m_initialized(false)
, m_synchronizing(false)
, m_synchronize(true)
{
}
bool Box2DBaseItem::initialized() const
{
return m_initialized;
}
/*
* Shamelessly stolen from qml-box2d project at gitorious
*
* https://gitorious.org/qml-box2d/qml-box2d
*/
void Box2DBaseItem::synchronize()
{
if (m_synchronize && m_initialized) {
m_synchronizing = true;
const QPointF newPoint = b2Util::qTopLeft(b2TransformOrigin(), boundingRect(), m_scaleRatio);
const float32 angle = b2Angle();
const qreal newRotation = -(angle * 360.0) / (2 * b2_pi);
if (!qFuzzyCompare(x(), newPoint.x()) || !qFuzzyCompare(y(), newPoint.y()))
setPos(newPoint);
if (!qFuzzyCompare(rotation(), newRotation))
setRotation(newRotation);
m_synchronizing = false;
}
}
| #include "box2dbaseitem.h"
#include "util.h"
#include <Box2D/Box2D.h>
float Box2DBaseItem::m_scaleRatio = 32.0f;
Box2DBaseItem::Box2DBaseItem(GameScene *parent )
: GameItem(parent)
, m_initialized(false)
, m_synchronizing(false)
, m_synchronize(true)
{
}
bool Box2DBaseItem::initialized() const
{
return m_initialized;
}
/*
* Shamelessly stolen from qml-box2d project at gitorious
*
* https://gitorious.org/qml-box2d/qml-box2d
*/
void Box2DBaseItem::synchronize()
{
if (m_synchronize && m_initialized) {
m_synchronizing = true;
const QPointF newPoint = b2Util::qTopLeft(b2TransformOrigin(), boundingRect(), m_scaleRatio);
const qreal newRotation = b2Util::qAngle(b2Angle());
if (!qFuzzyCompare(x(), newPoint.x()) || !qFuzzyCompare(y(), newPoint.y()))
setPos(newPoint);
if (!qFuzzyCompare(rotation(), newRotation))
setRotation(newRotation);
m_synchronizing = false;
}
}
|
Set font size correctly on Mac and non-Mac. | /*
* Qumulus UML editor
* Author: Frank Erens
*
*/
#include "Diagram.h"
#include "Style.h"
QUML_BEGIN_NAMESPACE_UD
Diagram::Diagram(QString name, double resolution) :
mName(name),
mResolution(resolution) {
auto s = new Style;
setLocalStyle(s);
s->setFontName("sans-serif");
s->setFontSize(12.0);
}
Diagram::Diagram(const Diagram& d) :
Shape(d) {
}
QUML_END_NAMESPACE_UD
| /*
* Qumulus UML editor
* Author: Frank Erens
*
*/
#include "Diagram.h"
#include "Style.h"
QUML_BEGIN_NAMESPACE_UD
constexpr static float kFontSize =
#ifdef Q_OS_MAC
12.0;
#else
10.0;
#endif
Diagram::Diagram(QString name, double resolution) :
mName(name),
mResolution(resolution) {
auto s = new Style;
setLocalStyle(s);
s->setFontName("sans-serif");
s->setFontSize(kFontSize);
}
Diagram::Diagram(const Diagram& d) :
Shape(d) {
}
QUML_END_NAMESPACE_UD
|
Patch to support MSVC, contributed by Morten Ofstad | //===-- IsInf.cpp ---------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Platform-independent wrapper around C99 isinf().
//
//===----------------------------------------------------------------------===//
#include "llvm/Config/config.h"
#if HAVE_ISINF_IN_MATH_H
# include <math.h>
#elif HAVE_ISINF_IN_CMATH
# include <cmath>
#elif HAVE_STD_ISINF_IN_CMATH
# include <cmath>
using std::isinf;
#elif HAVE_FINITE_IN_IEEEFP_H
// A handy workaround I found at http://www.unixguide.net/sun/faq ...
// apparently this has been a problem with Solaris for years.
# include <ieeefp.h>
static int isinf(double x) { return !finite(x) && x==x; }
#else
# error "Don't know how to get isinf()"
#endif
namespace llvm {
int IsInf (float f) { return isinf (f); }
int IsInf (double d) { return isinf (d); }
}; // end namespace llvm;
| //===-- IsInf.cpp ---------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Platform-independent wrapper around C99 isinf().
//
//===----------------------------------------------------------------------===//
#include "llvm/Config/config.h"
#if HAVE_ISINF_IN_MATH_H
# include <math.h>
#elif HAVE_ISINF_IN_CMATH
# include <cmath>
#elif HAVE_STD_ISINF_IN_CMATH
# include <cmath>
using std::isinf;
#elif HAVE_FINITE_IN_IEEEFP_H
// A handy workaround I found at http://www.unixguide.net/sun/faq ...
// apparently this has been a problem with Solaris for years.
# include <ieeefp.h>
static int isinf(double x) { return !finite(x) && x==x; }
#elif defined(_MSC_VER)
#include <float.h>
#define isinf(X) (!_finite(X))
#else
# error "Don't know how to get isinf()"
#endif
namespace llvm {
int IsInf (float f) { return isinf (f); }
int IsInf (double d) { return isinf (d); }
}; // end namespace llvm;
|
Make the lazy TLS pointer to UtilityThread into a LeakyLazyInstance. | // 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/public/utility/utility_thread.h"
#include "base/lazy_instance.h"
#include "base/threading/thread_local.h"
namespace content {
// Keep the global UtilityThread in a TLS slot so it is impossible to access
// incorrectly from the wrong thread.
static base::LazyInstance<base::ThreadLocalPointer<UtilityThread> > lazy_tls =
LAZY_INSTANCE_INITIALIZER;
UtilityThread* UtilityThread::Get() {
return lazy_tls.Pointer()->Get();
}
UtilityThread::UtilityThread() {
lazy_tls.Pointer()->Set(this);
}
UtilityThread::~UtilityThread() {
lazy_tls.Pointer()->Set(NULL);
}
} // 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/public/utility/utility_thread.h"
#include "base/lazy_instance.h"
#include "base/threading/thread_local.h"
namespace content {
// Keep the global UtilityThread in a TLS slot so it is impossible to access
// incorrectly from the wrong thread.
static base::LazyInstance<base::ThreadLocalPointer<UtilityThread> >::Leaky
lazy_tls = LAZY_INSTANCE_INITIALIZER;
UtilityThread* UtilityThread::Get() {
return lazy_tls.Pointer()->Get();
}
UtilityThread::UtilityThread() {
lazy_tls.Pointer()->Set(this);
}
UtilityThread::~UtilityThread() {
lazy_tls.Pointer()->Set(NULL);
}
} // namespace content
|
Change connected components to assign component ids starting at 0 | /*
* ConnectedComponents.cpp
*
* Created on: Dec 16, 2013
* Author: cls
*/
#include <set>
#include "ConnectedComponents.h"
#include "../structures/Partition.h"
#include "../auxiliary/Log.h"
namespace NetworKit {
ConnectedComponents::ConnectedComponents(const Graph& G) : G(G), numComponents(0) {
}
void ConnectedComponents::run() {
DEBUG("initializing labels");
component = Partition(G.upperNodeIdBound(), none);
numComponents = 0;
// perform breadth-first searches
G.forNodes([&](node u) {
if (component[u] == none) {
component.toSingleton(u);
index c = component[u];
assert (component[u] != none);
G.BFSfrom(u, [&](node v, count dist) {
component[v] = c;
});
++numComponents;
}
});
}
Partition ConnectedComponents::getPartition() {
return this->component;
}
std::map<index, count> ConnectedComponents::getComponentSizes() {
return this->component.subsetSizeMap();
}
}
| /*
* ConnectedComponents.cpp
*
* Created on: Dec 16, 2013
* Author: cls
*/
#include <set>
#include "ConnectedComponents.h"
#include "../structures/Partition.h"
#include "../auxiliary/Log.h"
namespace NetworKit {
ConnectedComponents::ConnectedComponents(const Graph& G) : G(G), numComponents(0) {
}
void ConnectedComponents::run() {
DEBUG("initializing labels");
component = Partition(G.upperNodeIdBound(), none);
numComponents = 0;
// perform breadth-first searches
G.forNodes([&](node u) {
if (component[u] == none) {
component.setUpperBound(numComponents+1);
index c = numComponents;
G.BFSfrom(u, [&](node v, count dist) {
component[v] = c;
});
assert (component[u] != none);
++numComponents;
}
});
}
Partition ConnectedComponents::getPartition() {
return this->component;
}
std::map<index, count> ConnectedComponents::getComponentSizes() {
return this->component.subsetSizeMap();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.