Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Add ability to read arguments from the command line | // This is the starting point
//
#include <iostream>
#include <fstream>
#include <sstream>
int main() {
std::string first_input;
std::string second_input;
std::cout << "Enter the first string" << std::endl;
std::cin >> first_input;
std::cout << "Enter the second string" << std::endl;
std::cin >> second_input;
if (first_input == second_input) {
std::cout << "Match!" << std::endl;
}
std::string fileName;
std::cout << "Enter a filename in which to look for the string" << std::endl;
std::cin >> fileName;
std::ifstream file_input_stream(fileName);
std::string line;
if (file_input_stream.is_open()) {
std::cout << "Successfully opened " << fileName << std::endl;
while(true) {
if (file_input_stream.fail()) {
std::cout << "The file input stream went into an error state" << std::endl;
break;
}
getline(file_input_stream, line);
std::cout << line << std::endl;
if (first_input == line) {
std::cout << "Match!" << std::endl;
}
}
} else {
std::cout << "Could not open file for reading" << std::endl;
}
return 0;
}
| // This is the starting point
//
#include <iostream>
#include <fstream>
#include <sstream>
int main(int argc, char * argv[]) {
std::cout << "You supplied " << argc << " arguments, which were: " << std::endl;
for (size_t i = 0; i < argc; ++i) {
std::cout << argv[i] << std::endl;
}
std::string first_input;
std::string second_input;
std::cout << "Enter the first string" << std::endl;
std::cin >> first_input;
std::cout << "Enter the second string" << std::endl;
std::cin >> second_input;
if (first_input == second_input) {
std::cout << "Match!" << std::endl;
}
std::string fileName;
std::cout << "Enter a filename in which to look for the string" << std::endl;
std::cin >> fileName;
std::ifstream file_input_stream(fileName);
std::string line;
if (file_input_stream.is_open()) {
std::cout << "Successfully opened " << fileName << std::endl;
while(true) {
if (file_input_stream.fail()) {
std::cout << "The file input stream went into an error state" << std::endl;
break;
}
getline(file_input_stream, line);
std::cout << line << std::endl;
if (first_input == line) {
std::cout << "Match!" << std::endl;
}
}
} else {
std::cout << "Could not open file for reading" << std::endl;
}
return 0;
}
|
Replace tab with space to separate game result | #include "Game/Game_Result.h"
#include <string>
#include "Game/Color.h"
#include "Utility.h"
Game_Result::Game_Result() : victor(NONE), cause()
{
}
Game_Result::Game_Result(Color winner,
const std::string& reason) :
victor(winner),
cause(reason)
{
}
bool Game_Result::game_has_ended() const
{
return ! cause.empty();
}
Color Game_Result::winner() const
{
return victor;
}
std::string Game_Result::ending_reason() const
{
return cause;
}
std::string Game_Result::game_ending_annotation() const
{
switch(winner())
{
case WHITE:
return "1-0";
case BLACK:
return "0-1";
default:
return game_has_ended() ? "1/2-1/2" : "";
}
}
std::string Game_Result::game_record_annotation() const
{
if(game_has_ended())
{
std::string prefix = "\t";
if(String::ends_with(cause, "mates"))
{
prefix = "#" + prefix;
}
return prefix + game_ending_annotation();
}
else
{
return {};
}
}
| #include "Game/Game_Result.h"
#include <string>
#include "Game/Color.h"
#include "Utility.h"
Game_Result::Game_Result() : victor(NONE), cause()
{
}
Game_Result::Game_Result(Color winner,
const std::string& reason) :
victor(winner),
cause(reason)
{
}
bool Game_Result::game_has_ended() const
{
return ! cause.empty();
}
Color Game_Result::winner() const
{
return victor;
}
std::string Game_Result::ending_reason() const
{
return cause;
}
std::string Game_Result::game_ending_annotation() const
{
switch(winner())
{
case WHITE:
return "1-0";
case BLACK:
return "0-1";
default:
return game_has_ended() ? "1/2-1/2" : "";
}
}
std::string Game_Result::game_record_annotation() const
{
if(game_has_ended())
{
std::string prefix = " ";
if(String::ends_with(cause, "mates"))
{
prefix = "#" + prefix;
}
return prefix + game_ending_annotation();
}
else
{
return {};
}
}
|
Fix a test bug where dllexport qualifier was missing. | unsigned __int32 Ret_Int(unsigned __int32 argVal){
unsigned __int32 retVal = (unsigned __int32)argVal;
return retVal;
}
unsigned __int32 Ret_Ptr(void *argVal){
unsigned __int32 retVal = (unsigned __int32)argVal;
return retVal;
}
void Set_Val(__int32 *argVal, __int32 val){
*argVal = val;;
}
void Mul_Val(__int32 *arg1,__int32 *arg2,__int32 *arg3){
*arg3 = (*arg1)*(*arg2);
}
| #if defined(_MSC_VER)
#define EXPORT_API extern "C" __declspec(dllexport)
#else
#define EXPORT_API extern "C" __attribute__((visibility("default")))
#endif
EXPORT_API unsigned __int32 Ret_Int(unsigned __int32 argVal){
unsigned __int32 retVal = (unsigned __int32)argVal;
return retVal;
}
EXPORT_API unsigned __int32 Ret_Ptr(void *argVal){
unsigned __int32 retVal = (unsigned __int32)argVal;
return retVal;
}
EXPORT_API void Set_Val(__int32 *argVal, __int32 val){
*argVal = val;;
}
EXPORT_API void Mul_Val(__int32 *arg1,__int32 *arg2,__int32 *arg3){
*arg3 = (*arg1)*(*arg2);
}
|
Update proto fuzzer example for r375453. | //===-- ExampleClangProtoFuzzer.cpp - Fuzz Clang --------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
///
/// \file
/// This file implements a function that runs Clang on a single
/// input and uses libprotobuf-mutator to find new inputs. This function is
/// then linked into the Fuzzer library.
///
//===----------------------------------------------------------------------===//
#include "cxx_proto.pb.h"
#include "handle-cxx/handle_cxx.h"
#include "proto-to-cxx/proto_to_cxx.h"
#include "fuzzer-initialize/fuzzer_initialize.h"
#include "src/libfuzzer/libfuzzer_macro.h"
using namespace clang_fuzzer;
DEFINE_BINARY_PROTO_FUZZER(const Function& input) {
auto S = FunctionToString(input);
HandleCXX(S, GetCLArgs());
}
| //===-- ExampleClangProtoFuzzer.cpp - Fuzz Clang --------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
///
/// \file
/// This file implements a function that runs Clang on a single
/// input and uses libprotobuf-mutator to find new inputs. This function is
/// then linked into the Fuzzer library.
///
//===----------------------------------------------------------------------===//
#include "cxx_proto.pb.h"
#include "handle-cxx/handle_cxx.h"
#include "proto-to-cxx/proto_to_cxx.h"
#include "fuzzer-initialize/fuzzer_initialize.h"
#include "src/libfuzzer/libfuzzer_macro.h"
using namespace clang_fuzzer;
DEFINE_BINARY_PROTO_FUZZER(const Function& input) {
auto S = FunctionToString(input);
HandleCXX(S, "./test.cc", GetCLArgs());
}
|
Disable testPathFinder. Does not terminate! | #include "gtest/gtest.h"
#include "maze.h"
#include "mazereader.h"
#include "mazeflooder.h"
#include "mazepathfinder.h"
#include "mazeprinter.h"
TEST(PathFinder,test){
MazeResetData();
ReadMAZFile("mazefiles/empty.maz");
FloodMazeClassic(DefaultGoal());
ASSERT_EQ(0xFE,MazeGetWalls(Home()));
int pathLength = IsolatePath(Home(),Goal());
PrintMaze(DIRS);
ASSERT_EQ(12,pathLength);
} | #include "gtest/gtest.h"
#include "maze.h"
#include "mazereader.h"
#include "mazeflooder.h"
#include "mazepathfinder.h"
#include "mazeprinter.h"
TEST(PathFinder,test){
MazeResetData();
ReadMAZFile("mazefiles/empty.maz");
FloodMazeClassic(DefaultGoal());
ASSERT_EQ(0xFE,MazeGetWalls(Home()));
// int pathLength = IsolatePath(Home(),Goal());
// PrintMaze(DIRS);
// ASSERT_EQ(12,pathLength);
} |
Make GUI window a bit taller | #include "ofMain.h"
#include "ofApp.h"
#include "ofAppGLFWWindow.h"
int main() {
ofGLFWWindowSettings settings;
settings.width = 1280;
settings.height = 720;
settings.setPosition(ofVec2f(300,0));
settings.resizable = true;
shared_ptr<ofAppBaseWindow> mainWindow = ofCreateWindow(settings);
mainWindow->setFullscreen(true);
settings.width = 500;
settings.height = 800;
settings.setPosition(ofVec2f(0,0));
shared_ptr<ofAppBaseWindow> guiWindow = ofCreateWindow(settings);
shared_ptr<ofApp> mainApp(new ofApp);
mainApp->setupGui();
ofAddListener(guiWindow->events().draw, mainApp.get(), &ofApp::drawGui);
ofRunApp(mainWindow, mainApp);
ofRunMainLoop();
}
| #include "ofMain.h"
#include "ofApp.h"
#include "ofAppGLFWWindow.h"
int main() {
ofGLFWWindowSettings settings;
settings.width = 1280;
settings.height = 720;
settings.setPosition(ofVec2f(300,0));
settings.resizable = true;
shared_ptr<ofAppBaseWindow> mainWindow = ofCreateWindow(settings);
mainWindow->setFullscreen(true);
settings.width = 500;
settings.height = 900;
settings.setPosition(ofVec2f(0,0));
shared_ptr<ofAppBaseWindow> guiWindow = ofCreateWindow(settings);
shared_ptr<ofApp> mainApp(new ofApp);
mainApp->setupGui();
ofAddListener(guiWindow->events().draw, mainApp.get(), &ofApp::drawGui);
ofRunApp(mainWindow, mainApp);
ofRunMainLoop();
}
|
Add another solution for week 3, task 13 | /*
Author: vpetrigo
Task:
,
.
.
, 0.
.
,
0 ( 0 ,
).
.
Sample Input:
1
2
1
2
1
0
Sample Output:
2
*/
#include <iostream>
using namespace std;
int main() {
int prev = -1;
int cur = -1;
bool prev_gr = false;
int cnt = 0;
while (cin >> cur && cur != 0) {
if (prev != -1) {
if (prev < cur && !prev_gr) {
prev_gr = true;
}
else if (prev_gr) {
if (cur < prev) {
++cnt;
prev_gr = false;
}
else if (cur == prev) {
prev_gr = false;
}
}
else {
prev_gr = false;
}
}
prev = cur;
}
cout << cnt;
return 0;
} | /*
Author: vpetrigo
Task:
,
.
.
, 0.
.
,
0 ( 0 ,
).
.
Sample Input:
1
2
1
2
1
0
Sample Output:
2
*/
#include <iostream>
using namespace std;
int main() {
int prev = -1;
int cur = -1;
bool prev_gr = false;
int cnt = 0;
// Option 1
while (cin >> cur && cur != 0) {
if (prev != -1) {
if (prev < cur && !prev_gr) {
prev_gr = true;
}
else if (prev_gr) {
if (cur < prev) {
++cnt;
prev_gr = false;
}
else if (cur == prev) {
prev_gr = false;
}
}
else {
prev_gr = false;
}
}
prev = cur;
}
// Option 2
int next;
if (cin >> prev && prev != 0) {
if (cin >> cur && cur != 0) {
if (cin >> next) {
while (next != 0) {
if (prev < cur && cur > next) {
++cnt;
}
prev = cur;
cur = next;
cin >> next;
}
}
}
}
cout << cnt;
return 0;
} |
Add test case for rdar://11293995 | // RUN: %clang_cc1 -fsyntax-only -verify %s
class X {};
void test() {
X x;
x.int; // expected-error{{expected unqualified-id}}
x.~int(); // expected-error{{expected a class name}}
x.operator; // expected-error{{expected a type}}
x.operator typedef; // expected-error{{expected a type}} expected-error{{type name does not allow storage class}}
}
void test2() {
X *x;
x->int; // expected-error{{expected unqualified-id}}
x->~int(); // expected-error{{expected a class name}}
x->operator; // expected-error{{expected a type}}
x->operator typedef; // expected-error{{expected a type}} expected-error{{type name does not allow storage class}}
}
// PR6327
namespace test3 {
template <class A, class B> struct pair {};
void test0() {
pair<int, int> z = minmax({}); // expected-error {{expected expression}}
}
struct string {
class iterator {};
};
void test1() {
string s;
string::iterator i = s.foo(); // expected-error {{no member named 'foo'}}
}
}
| // RUN: %clang_cc1 -fsyntax-only -verify %s
class X {};
void test() {
X x;
x.int; // expected-error{{expected unqualified-id}}
x.~int(); // expected-error{{expected a class name}}
x.operator; // expected-error{{expected a type}}
x.operator typedef; // expected-error{{expected a type}} expected-error{{type name does not allow storage class}}
}
void test2() {
X *x;
x->int; // expected-error{{expected unqualified-id}}
x->~int(); // expected-error{{expected a class name}}
x->operator; // expected-error{{expected a type}}
x->operator typedef; // expected-error{{expected a type}} expected-error{{type name does not allow storage class}}
}
// PR6327
namespace test3 {
template <class A, class B> struct pair {};
void test0() {
pair<int, int> z = minmax({}); // expected-error {{expected expression}}
}
struct string {
class iterator {};
};
void test1() {
string s;
string::iterator i = s.foo(); // expected-error {{no member named 'foo'}}
}
}
// Make sure we don't crash.
namespace rdar11293995 {
struct Length {
explicit Length(PassRefPtr<CalculationValue>); // expected-error {{unknown type name}} \
expected-error {{expected ')'}} \
expected-note {{to match this '('}}
};
struct LengthSize {
Length m_width;
Length m_height;
};
enum EFillSizeType { Contain, Cover, SizeLength, SizeNone };
struct FillSize {
EFillSizeType type;
LengthSize size;
};
class FillLayer {
public:
void setSize(FillSize f) { m_sizeType = f.type;}
private:
unsigned m_sizeType : 2;
};
}
|
Fix aura bustage on linux. | // 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 "ui/aura/toplevel_window_container.h"
#include "base/utf_string_conversions.h"
#include "ui/aura/toplevel_window_event_filter.h"
namespace aura {
ToplevelWindowContainer::ToplevelWindowContainer()
: Window(NULL) {
set_name("ToplevelWindowContainer");
SetEventFilter(new ToplevelWindowEventFilter(this));
}
ToplevelWindowContainer::~ToplevelWindowContainer() {
}
Window* ToplevelWindowContainer::GetTopmostWindowToActivate(
Window* ignore) const {
for (Window::Windows::const_reverse_iterator i = children().rbegin();
i != children().rend(); ++i) {
Window* w = *i;
if (*i != ignore && (*i)->CanActivate())
return *i;
}
return NULL;
}
ToplevelWindowContainer* ToplevelWindowContainer::AsToplevelWindowContainer() {
return this;
}
const ToplevelWindowContainer*
ToplevelWindowContainer::AsToplevelWindowContainer() const {
return this;
}
} // namespace aura
| // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/aura/toplevel_window_container.h"
#include "base/utf_string_conversions.h"
#include "ui/aura/toplevel_window_event_filter.h"
namespace aura {
ToplevelWindowContainer::ToplevelWindowContainer()
: Window(NULL) {
set_name("ToplevelWindowContainer");
SetEventFilter(new ToplevelWindowEventFilter(this));
}
ToplevelWindowContainer::~ToplevelWindowContainer() {
}
Window* ToplevelWindowContainer::GetTopmostWindowToActivate(
Window* ignore) const {
for (Window::Windows::const_reverse_iterator i = children().rbegin();
i != children().rend(); ++i) {
if (*i != ignore && (*i)->CanActivate())
return *i;
}
return NULL;
}
ToplevelWindowContainer* ToplevelWindowContainer::AsToplevelWindowContainer() {
return this;
}
const ToplevelWindowContainer*
ToplevelWindowContainer::AsToplevelWindowContainer() const {
return this;
}
} // namespace aura
|
Use the data/ directory in the Mac app bundle. | #include "ofMain.h"
#include "ofApp.h"
int main( ){
ofSetupOpenGL(1024, 768, OF_WINDOW);
ofxDatGui::setAssetPath("./");
// this kicks off the running of my app
// can be OF_WINDOW or OF_FULLSCREEN
// pass in width and height too:
ofRunApp(new ofApp());
}
| #include "ofMain.h"
#include "ofApp.h"
int main( ){
ofSetupOpenGL(1024, 768, OF_WINDOW);
ofSetDataPathRoot("../Resources/data/");
ofxDatGui::setAssetPath("./");
// this kicks off the running of my app
// can be OF_WINDOW or OF_FULLSCREEN
// pass in width and height too:
ofRunApp(new ofApp());
}
|
Fix excepion name for linux platform. | #include "Config.hpp"
#include "Calculator.hpp"
Calculator::Calculator()
{
ready = false;
}
Calculator::Calculator(int a, int b)
{
ready = false;
create(a, b);
}
Calculator::~Calculator()
{
if (valid())
{
destroy();
}
}
bool Calculator::create(int a, int b)
{
if (valid())
{
throw std::exception("Calculator object is initialised!");
}
this->a = a;
this->b = b;
ready = !ready;
return true;
}
bool Calculator::valid()
{
return ready;
}
void Calculator::destroy()
{
if (!valid())
{
throw std::exception("Calculator object is not initialised!");
}
a = b = 0;
ready = !ready;
}
int Calculator::sum()
{
return a + b;
}
int Calculator::mul()
{
return a * b;
}
int Calculator::diff()
{
return a - b;
}
int Calculator::div()
{
if (!a)
{
return 0;
}
return a / b;
}
| #include "Config.hpp"
#include "Calculator.hpp"
Calculator::Calculator()
{
ready = false;
}
Calculator::Calculator(int a, int b)
{
ready = false;
create(a, b);
}
Calculator::~Calculator()
{
if (valid())
{
destroy();
}
}
bool Calculator::create(int a, int b)
{
if (valid())
{
throw std::runtime_error("Calculator object is initialised!");
}
this->a = a;
this->b = b;
ready = !ready;
return true;
}
bool Calculator::valid()
{
return ready;
}
void Calculator::destroy()
{
if (!valid())
{
throw std::runtime_error("Calculator object is not initialised!");
}
a = b = 0;
ready = !ready;
}
int Calculator::sum()
{
return a + b;
}
int Calculator::mul()
{
return a * b;
}
int Calculator::diff()
{
return a - b;
}
int Calculator::div()
{
if (!a)
{
return 0;
}
return a / b;
}
|
Add utilty function for checking errors | #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;
}
| #include <iostream>
#include <dns_sd.h>
#include <ev++.h>
#include "build_version.h"
inline void check_dnsservice_errors(DNSServiceErrorType& e, const std::string& func_name) {
std::string error(func_name);
error += ": ";
switch (e) {
case kDNSServiceErr_NoError:
return;
case kDNSServiceErr_NameConflict:
error += "Name in use, please choose another";
break;
case kDNSServiceErr_Invalid:
error += "An invalid index or character was passed";
break;
case kDNSServiceErr_BadReference:
error += "Bad reference";
break;
case kDNSServiceErr_BadParam:
error += "Bad parameter value passed to function.";
break;
default:
error += "Unknown error code... ";
error += std::to_string(e);
}
throw std::runtime_error(error.c_str());
}
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;
}
|
Fix mouse move item bug | #include "CanvasView.h"
#include <QMouseEvent>
CanvasView::CanvasView(QWidget* parent)
: QGraphicsView(parent)
{
}
CanvasView::~CanvasView()
{
}
void CanvasView::mouseReleaseEvent(QMouseEvent *event)
{
QPointF localPos = QGraphicsView::mapToScene(event->pos());
emit signalMouseReleaseEvent(localPos);
}
| #include "CanvasView.h"
#include <QMouseEvent>
CanvasView::CanvasView(QWidget* parent)
: QGraphicsView(parent)
{
}
CanvasView::~CanvasView()
{
}
void CanvasView::mouseReleaseEvent(QMouseEvent *event)
{
QGraphicsView::mouseReleaseEvent(event);
QPointF localPos = QGraphicsView::mapToScene(event->pos());
emit signalMouseReleaseEvent(localPos);
}
|
Disable test failing since r29947. | // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Storage) {
ASSERT_TRUE(RunExtensionTest("storage")) << message_;
}
| // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
// Started failing with r29947. WebKit merge 49961:49992.
IN_PROC_BROWSER_TEST_F(DISABLED_ExtensionApiTest, Storage) {
ASSERT_TRUE(RunExtensionTest("storage")) << message_;
}
|
Implement the block version of the Vanka smoother. | /* $Id$ */
#include <lac/sparse_vanka.templates.h>
// explicit instantiations
template class SparseVanka<float>;
template class SparseVanka<double>;
template void SparseVanka<double>::operator () (Vector<float> &dst,
const Vector<float> &src) const;
template void SparseVanka<double>::operator () (Vector<double> &dst,
const Vector<double> &src) const;
| /* $Id$ */
#include <lac/sparse_vanka.templates.h>
// explicit instantiations
template class SparseVanka<float>;
template class SparseVanka<double>;
template void SparseVanka<double>::operator () (Vector<float> &dst,
const Vector<float> &src) const;
template void SparseVanka<double>::operator () (Vector<double> &dst,
const Vector<double> &src) const;
template class SparseBlockVanka<float>;
template class SparseBlockVanka<double>;
template void SparseBlockVanka<double>::operator () (Vector<float> &dst,
const Vector<float> &src) const;
template void SparseBlockVanka<double>::operator () (Vector<double> &dst,
const Vector<double> &src) const;
|
Fix Binary Tree DOT print | #include "binarytree.h"
#include <iostream>
using namespace std;
template <class T>
void dotPrint(ostream& out, typename BinaryTree<T>::Inspector treeInspector, size_t id)
{
out << id << "[label=\"" << treeInspector.getData() << "\"];" << endl;
if (treeInspector.hasLeft())
{
out << id << " -> " << id + 1 << ";" << endl;
treeInspector.goLeft();
dotPrint<T>(out, treeInspector, id + 1);
treeInspector.goToParent();
}
if (treeInspector.hasRight())
{
out << id << " -> " << id + 2 << ";" << endl;
treeInspector.goRight();
dotPrint<T>(out, treeInspector, id + 2);
treeInspector.goToParent();
}
}
template <class T>
void dotPrint(ostream& out, const BinaryTree<T>& tree)
{
out << "digraph G\n{\n";
dotPrint<T>(out, tree.getInspector(), 0);
out << "}\n";
}
int main()
{
BinaryTree<int> tree;
BinaryTree<int>::Transformer tr = tree.getTransformer();
tr.addData(5);
tr.goLeft();
tr.addData(2);
tr.goToParent();
tr.goRight();
tr.addData(3);
dotPrint(cout, tree);
return 0;
}
| #include "binarytree.h"
#include <iostream>
using namespace std;
template <class T>
void dotPrint(ostream& out, typename BinaryTree<T>::Inspector treeInspector, size_t id)
{
if (treeInspector.isEmpty())
{
out << id << "[label=\"NULL\" shape=point];" << endl;
return;
}
out << id << "[label=\"" << treeInspector.getData() << "\"];" << endl;
out << id << " -> " << 2*id + 1 << ";" << endl;
dotPrint<T>(out, treeInspector.left(), 2*id + 1);
out << id << " -> " << 2*id + 2 << ";" << endl;
dotPrint<T>(out, treeInspector.right(), 2*id + 2);
}
template <class T>
void dotPrint(ostream& out, const BinaryTree<T>& tree)
{
out << "digraph G\n{\n";
dotPrint<T>(out, tree.getInspector(), 0);
out << "}\n";
}
int main()
{
BinaryTree<int> tree;
BinaryTree<int>::Transformer tr = tree.getTransformer();
tr.addData(5);
tr.goLeft();
tr.addData(2);
tr.goToParent();
tr.goRight();
tr.addData(3);
dotPrint(cout, tree);
return 0;
}
|
Fix hidden broken floating-point test | #include "TestData.h"
TEST(DataObjectTests, ScalarDataObjectHasCorrectProperties) {
float scalarValue = 5.0;
DataObject five(scalarValue);
EXPECT_EQ(five.Dim(), 0);
std::vector<int64_t> expectedShape;
EXPECT_EQ(five.Shape(), expectedShape);
EXPECT_EQ(five.GetKind(), DataKind::SCALAR);
}
TEST(DataObjectTests, MatrixDataObjectHasCorrectProperties) {
Eigen::MatrixXf m(3, 2);
DataObject matrix(m);
EXPECT_EQ(matrix.Dim(), 2);
std::vector<int64_t> expectedShape({3, 2});
EXPECT_EQ(matrix.Shape(), expectedShape);
EXPECT_EQ(matrix.GetKind(), DataKind::MATRIX);
}
TEST(DataObjectTests, ScalarDataObjectGivesCorrectScalarConversion) {
DataObject five = Scalar(5.0);
EXPECT_FLOAT_EQ(five.ToScalar(), 5.0);
bool comparatorWorks = five == 5.0;
EXPECT_EQ(comparatorWorks, true);
}
TEST(DataObjectTests, MatrixDataObjectGivesCorrectMatrixConversion) {
Eigen::MatrixXf m(3, 2);
DataObject matrix = Mat(m);
EXPECT_EQ(matrix.ToMatrix(), m);
bool comparatorWorks = matrix == m;
EXPECT_EQ(comparatorWorks, true);
}
| #include "TestData.h"
TEST(DataObjectTests, ScalarDataObjectHasCorrectProperties) {
float scalarValue = 5.0;
DataObject five(scalarValue);
EXPECT_EQ(five.Dim(), 0);
std::vector<int64_t> expectedShape;
EXPECT_EQ(five.Shape(), expectedShape);
EXPECT_EQ(five.GetKind(), DataKind::SCALAR);
}
TEST(DataObjectTests, MatrixDataObjectHasCorrectProperties) {
Eigen::MatrixXf m(3, 2);
DataObject matrix(m);
EXPECT_EQ(matrix.Dim(), 2);
std::vector<int64_t> expectedShape({3, 2});
EXPECT_EQ(matrix.Shape(), expectedShape);
EXPECT_EQ(matrix.GetKind(), DataKind::MATRIX);
}
TEST(DataObjectTests, ScalarDataObjectGivesCorrectScalarConversion) {
DataObject five = Scalar(5.0);
EXPECT_FLOAT_EQ(five.ToScalar(), 5.0);
bool comparatorWorks = five == 5.0;
EXPECT_EQ(comparatorWorks, true);
}
TEST(DataObjectTests, MatrixDataObjectGivesCorrectMatrixConversion) {
Eigen::MatrixXf m = Eigen::MatrixXf::Zero(3, 2);
DataObject matrix = Mat(m);
EXPECT_EQ(matrix.ToMatrix(), m);
bool comparatorWorks = matrix == m;
EXPECT_EQ(comparatorWorks, true);
}
|
Use must<>, added required analyze_t for custom rule | // Copyright (c) 2014-2015 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/
#include <pegtl.hh>
namespace modulus
{
template< unsigned M, unsigned R = 0 >
struct my_rule
{
static_assert( M > 1, "Modulus must be greater than 1" );
static_assert( R < M, "Remainder must be less than modulus" );
template< typename Input >
static bool match( Input & in )
{
if ( in.size() ) {
if ( ( ( * in.begin() ) % M ) == R ) {
in.bump( 1 );
return true;
}
}
return false;
}
};
struct grammar
: pegtl::until< pegtl::eolf, my_rule< 3 > > {};
}
int main( int argc, char * argv[] )
{
if ( argc > 1 ) {
pegtl::parse< modulus::grammar >( 1, argv );
}
return 0;
}
| // Copyright (c) 2014-2015 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/
#include <pegtl.hh>
namespace modulus
{
template< unsigned M, unsigned R = 0 >
struct my_rule
{
using analyze_t = pegtl::analysis::generic< pegtl::analysis::rule_type::ANY >;
static_assert( M > 1, "Modulus must be greater than 1" );
static_assert( R < M, "Remainder must be less than modulus" );
template< typename Input >
static bool match( Input & in )
{
if ( in.size() ) {
if ( ( ( * in.begin() ) % M ) == R ) {
in.bump( 1 );
return true;
}
}
return false;
}
};
struct grammar
: pegtl::until< pegtl::eolf, pegtl::must< my_rule< 3 > > > {};
}
int main( int argc, char * argv[] )
{
if ( argc > 1 ) {
pegtl::parse< modulus::grammar >( 1, argv );
}
return 0;
}
|
Return value based on test run status | /*
This file is part of the Geometry library.
Copyright (C) 2010-2013 Benjamin Eikel <benjamin@eikel.org>
This library is subject to the terms of the Mozilla Public License, v. 2.0.
You should have received a copy of the MPL along with this library; see the
file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <cppunit/BriefTestProgressListener.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>
#include <cppunit/TestRunner.h>
#include <cppunit/TextOutputter.h>
#include <cppunit/XmlOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <fstream>
int main(int /*argc*/, char ** /*argv*/) {
CppUnit::TestResult controller;
CppUnit::TestResultCollector result;
controller.addListener(&result);
CppUnit::BriefTestProgressListener progress;
controller.addListener(&progress);
CppUnit::TestRunner runner;
runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest());
runner.run(controller);
std::ofstream fileStream("cppunit_results.xml");
CppUnit::XmlOutputter xmlOutput(&result, fileStream, "UTF-8");
xmlOutput.write();
CppUnit::TextOutputter textOutput(&result, std::cout);
textOutput.write();
return 0;
}
| /*
This file is part of the Geometry library.
Copyright (C) 2010-2013 Benjamin Eikel <benjamin@eikel.org>
This library is subject to the terms of the Mozilla Public License, v. 2.0.
You should have received a copy of the MPL along with this library; see the
file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <cppunit/BriefTestProgressListener.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>
#include <cppunit/TestRunner.h>
#include <cppunit/TextOutputter.h>
#include <cppunit/XmlOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <fstream>
int main(int /*argc*/, char ** /*argv*/) {
CppUnit::TestResult controller;
CppUnit::TestResultCollector result;
controller.addListener(&result);
CppUnit::BriefTestProgressListener progress;
controller.addListener(&progress);
CppUnit::TestRunner runner;
runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest());
runner.run(controller);
std::ofstream fileStream("cppunit_results.xml");
CppUnit::XmlOutputter xmlOutput(&result, fileStream, "UTF-8");
xmlOutput.write();
CppUnit::TextOutputter textOutput(&result, std::cout);
textOutput.write();
return result.wasSuccessful() ? 0 : 1;
}
|
Fix function name which does not match with header file | #include <stdlib.h>
#include <time.h>
#include "make_random_data.hpp"
int *make_data(const int size)
{
return make_data(size, RAND_MAX);
}
int *make_data(const int size, const int max)
{
srand(time(NULL)); /* Set a seed */
int *data = (int *)malloc(sizeof(int) * size);
for(int i = 0; i < size; i++)
data[i] = rand() % (max + 1);
return data;
}
void free_data(int *data)
{
free(data);
}
| #include <stdlib.h>
#include <time.h>
#include "make_random_data.hpp"
int *make_random_data(const int size)
{
return make_random_data(size, RAND_MAX);
}
int *make_random_data(const int size, const int max)
{
srand(time(NULL)); /* Set a seed */
int *data = (int *)malloc(sizeof(int) * size);
for(int i = 0; i < size; i++)
data[i] = rand() % (max + 1);
return data;
}
void free_random_data(int *data)
{
free(data);
}
|
Fix username tests by checking for null | //! @file test-getusername.cpp
//! @author Andrew Schwartzmeyer <andschwa@microsoft.com>
//! @brief Unit tests for GetUserName
#include <string>
#include <vector>
#include <unistd.h>
#include <gtest/gtest.h>
#include <unicode/unistr.h>
#include <pwd.h>
#include "getusername.h"
//! Test fixture for GetUserName
class GetUserNameTest : public ::testing::Test
{
protected:
std::string UserName;
GetUserNameTest(): UserName(std::string(getpwuid(geteuid())->pw_name))
{
}
};
TEST_F(GetUserNameTest, Success)
{
ASSERT_EQ(GetUserName(), UserName);
}
| //! @file test-getusername.cpp
//! @author Andrew Schwartzmeyer <andschwa@microsoft.com>
//! @brief Unit tests for GetUserName
#include <string>
#include <vector>
#include <unistd.h>
#include <gtest/gtest.h>
#include <unicode/unistr.h>
#include <pwd.h>
#include "getusername.h"
TEST(GetUserName, Success)
{
char* expected = getpwuid(geteuid())->pw_name;
ASSERT_TRUE(expected != NULL);
ASSERT_EQ(GetUserName(), std::string(expected));
}
|
Fix tests after cache tweaks | #define BOOST_TEST_MODULE Bitcoin Test Suite
#include <boost/test/unit_test.hpp>
#include "db.h"
#include "txdb.h"
#include "main.h"
#include "wallet.h"
CWallet* pwalletMain;
CClientUIInterface uiInterface;
extern bool fPrintToConsole;
extern void noui_connect();
struct TestingSetup {
CCoinsViewDB *pcoinsdbview;
TestingSetup() {
fPrintToDebugger = true; // don't want to write to debug.log file
noui_connect();
bitdb.MakeMock();
pblocktree = new CBlockTreeDB(true);
pcoinsdbview = new CCoinsViewDB(true);
pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
LoadBlockIndex();
bool fFirstRun;
pwalletMain = new CWallet("wallet.dat");
pwalletMain->LoadWallet(fFirstRun);
RegisterWallet(pwalletMain);
}
~TestingSetup()
{
delete pwalletMain;
pwalletMain = NULL;
delete pcoinsTip;
delete pcoinsdbview;
delete pblocktree;
bitdb.Flush(true);
}
};
BOOST_GLOBAL_FIXTURE(TestingSetup);
void Shutdown(void* parg)
{
exit(0);
}
void StartShutdown()
{
exit(0);
}
| #define BOOST_TEST_MODULE Bitcoin Test Suite
#include <boost/test/unit_test.hpp>
#include "db.h"
#include "txdb.h"
#include "main.h"
#include "wallet.h"
CWallet* pwalletMain;
CClientUIInterface uiInterface;
extern bool fPrintToConsole;
extern void noui_connect();
struct TestingSetup {
CCoinsViewDB *pcoinsdbview;
TestingSetup() {
fPrintToDebugger = true; // don't want to write to debug.log file
noui_connect();
bitdb.MakeMock();
pblocktree = new CBlockTreeDB(1 << 20, true);
pcoinsdbview = new CCoinsViewDB(1 << 23, true);
pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
LoadBlockIndex();
bool fFirstRun;
pwalletMain = new CWallet("wallet.dat");
pwalletMain->LoadWallet(fFirstRun);
RegisterWallet(pwalletMain);
}
~TestingSetup()
{
delete pwalletMain;
pwalletMain = NULL;
delete pcoinsTip;
delete pcoinsdbview;
delete pblocktree;
bitdb.Flush(true);
}
};
BOOST_GLOBAL_FIXTURE(TestingSetup);
void Shutdown(void* parg)
{
exit(0);
}
void StartShutdown()
{
exit(0);
}
|
Add licence header to ScopeReaderExample | #include <TString.h>
#include <DBHandler/HeaderFiles/DBHandler.h>
#include <JPetManager/JPetManager.h>
using namespace std;
int main(int argc, char* argv[])
{
DB::SERVICES::DBHandler::createDBConnection("../DBConfig/configDB.cfg");
JPetManager& manager = JPetManager::getManager();
manager.parseCmdLine(argc, argv);
manager.run();
}
| /**
* @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may find a copy of the License in the LICENCE file.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @file main.cpp
*/
#include <TString.h>
#include <DBHandler/HeaderFiles/DBHandler.h>
#include <JPetManager/JPetManager.h>
using namespace std;
int main(int argc, char* argv[])
{
DB::SERVICES::DBHandler::createDBConnection("../DBConfig/configDB.cfg");
JPetManager& manager = JPetManager::getManager();
manager.parseCmdLine(argc, argv);
manager.run();
}
|
Fix nullptr access in article class | //! \file Article.cpp
#include "Article.h"
#include <algorithm>
#include "WalkerException.h"
namespace WikiWalker
{
size_t Article::countLinks() const
{
if(!analyzed_ && links_.empty()) {
throw WalkerException("Article not analyzed yet!");
}
return links_.size();
}
Article::ArticleLinkConstIterator Article::linkBegin() const
{
return links_.cbegin();
}
Article::ArticleLinkConstIterator Article::linkEnd() const
{
return links_.cend();
}
bool Article::addLink(const std::weak_ptr<const Article> article)
{
auto newTitle = article.lock()->title();
// check for duplicates using title
//! \todo Or rather compare pointers again?
bool isNewLink =
std::none_of(links_.cbegin(),
links_.cend(),
[&newTitle](const std::weak_ptr<const Article> x) {
return x.lock()->title() == newTitle;
});
if(isNewLink) {
links_.push_back(article);
analyzed_ = true;
}
return isNewLink;
}
void Article::analyzed(bool analyzed)
{
analyzed_ = analyzed;
}
bool Article::analyzed() const
{
return analyzed_;
}
void Article::marked(bool marked)
{
marked_ = marked;
}
bool Article::marked() const
{
return marked_;
}
} // namespace WikiWalker | //! \file Article.cpp
#include "Article.h"
#include <algorithm>
#include "WalkerException.h"
namespace WikiWalker
{
size_t Article::countLinks() const
{
if(!analyzed_ && links_.empty()) {
throw WalkerException("Article not analyzed yet!");
}
return links_.size();
}
Article::ArticleLinkConstIterator Article::linkBegin() const
{
return links_.cbegin();
}
Article::ArticleLinkConstIterator Article::linkEnd() const
{
return links_.cend();
}
bool Article::addLink(const std::weak_ptr<const Article> article)
{
auto newTitle = article.lock()->title();
// check for duplicates using title
//! \todo Or rather compare pointers again?
bool isNewLink =
std::none_of(links_.cbegin(),
links_.cend(),
[&newTitle](const std::weak_ptr<const Article> x) {
auto p = x.lock();
return p == nullptr ? false : p->title() == newTitle;
});
if(isNewLink) {
links_.push_back(article);
analyzed_ = true;
}
return isNewLink;
}
void Article::analyzed(bool analyzed)
{
analyzed_ = analyzed;
}
bool Article::analyzed() const
{
return analyzed_;
}
void Article::marked(bool marked)
{
marked_ = marked;
}
bool Article::marked() const
{
return marked_;
}
} // namespace WikiWalker |
Set the output code page UTF-8.(Windows) | //
// Copyright(c) 2016-2017 benikabocha.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#include "Log.h"
#include "UnicodeUtil.h"
#include <iostream>
#if _WIN32
#include <Windows.h>
#endif // _WIN32
namespace saba
{
DefaultSink::DefaultSink()
{
m_defaultLogger = spdlog::stdout_color_mt("default");
}
void DefaultSink::log(const spdlog::details::log_msg & msg)
{
#if _WIN32
auto utf8Message = msg.raw.str();
std::wstring wMessage;
if (!TryToWString(utf8Message, wMessage))
{
m_defaultLogger->log(msg.level, "Failed to convert message.");
return;
}
int chCount = WideCharToMultiByte(
CP_OEMCP,
0,
wMessage.c_str(),
(int)wMessage.size(),
nullptr,
0,
0,
FALSE
);
std::string oemMessage(chCount, '\0');
WideCharToMultiByte(
CP_OEMCP,
0,
wMessage.c_str(),
(int)wMessage.size(),
&oemMessage[0],
chCount,
0,
FALSE
);
m_defaultLogger->log(msg.level, oemMessage);
#else // _WIN32
m_defaultLogger->log(msg.level, msg.raw.c_str());
#endif // _WIN32
}
void DefaultSink::flush()
{
m_defaultLogger->flush();
}
}
| //
// Copyright(c) 2016-2017 benikabocha.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#include "Log.h"
#include "UnicodeUtil.h"
#include <iostream>
#if _WIN32
#include <Windows.h>
#endif // _WIN32
namespace saba
{
DefaultSink::DefaultSink()
{
m_defaultLogger = spdlog::stdout_color_mt("default");
#if _WIN32
SetConsoleOutputCP(CP_UTF8);
#endif // _WIN32
}
void DefaultSink::log(const spdlog::details::log_msg & msg)
{
m_defaultLogger->log(msg.level, msg.raw.c_str());
}
void DefaultSink::flush()
{
m_defaultLogger->flush();
}
}
|
Fix bug for parsing google test flags | /*
* main.cc
*
* Copyright (c) 2015 Masatoshi Hanai
*
* This software is released under MIT License.
* See LICENSE.
*
*/
#include "glog/logging.h"
#include "gflags/gflags.h"
#include "gtest/gtest.h"
#include "leveldb/db.h"
#include "leveldb/options.h"
/* test files */
#include "medium/com_test.cc"
#include "medium/db_via_lp_test.cc"
#include "medium/gvt_test.cc"
#include "medium/logical_process_test.cc"
#include "small/db_test.cc"
#include "small/io_test.cc"
#include "small/thread_test.cc"
#include "small/util_test.cc"
int main(int argc, char** argv) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(*argv);
google::InstallFailureSignalHandler();
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| /*
* main.cc
*
* Copyright (c) 2015 Masatoshi Hanai
*
* This software is released under MIT License.
* See LICENSE.
*
*/
#include "glog/logging.h"
#include "gflags/gflags.h"
#include "gtest/gtest.h"
#include "leveldb/db.h"
#include "leveldb/options.h"
/* test files */
#include "medium/com_test.cc"
#include "medium/db_via_lp_test.cc"
#include "medium/gvt_test.cc"
#include "medium/logical_process_test.cc"
#include "small/db_test.cc"
#include "small/io_test.cc"
#include "small/thread_test.cc"
#include "small/util_test.cc"
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
gflags::ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(*argv);
google::InstallFailureSignalHandler();
return RUN_ALL_TESTS();
}
|
Use = default for default constructor. | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "search_session.h"
#include "match_tools.h"
#include "match_context.h"
namespace proton::matching {
SearchSession::SearchSession(const SessionId &id, fastos::TimeStamp time_of_doom,
std::unique_ptr<MatchToolsFactory> match_tools_factory,
OwnershipBundle &&owned_objects)
: _session_id(id),
_create_time(fastos::ClockSystem::now()),
_time_of_doom(time_of_doom),
_owned_objects(std::move(owned_objects)),
_match_tools_factory(std::move(match_tools_factory))
{
}
void
SearchSession::releaseEnumGuards() {
_owned_objects.context->releaseEnumGuards();
}
SearchSession::~SearchSession() { }
SearchSession::OwnershipBundle::OwnershipBundle() { }
SearchSession::OwnershipBundle::~OwnershipBundle() { }
}
| // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "search_session.h"
#include "match_tools.h"
#include "match_context.h"
namespace proton::matching {
SearchSession::SearchSession(const SessionId &id, fastos::TimeStamp time_of_doom,
std::unique_ptr<MatchToolsFactory> match_tools_factory,
OwnershipBundle &&owned_objects)
: _session_id(id),
_create_time(fastos::ClockSystem::now()),
_time_of_doom(time_of_doom),
_owned_objects(std::move(owned_objects)),
_match_tools_factory(std::move(match_tools_factory))
{
}
void
SearchSession::releaseEnumGuards() {
_owned_objects.context->releaseEnumGuards();
}
SearchSession::~SearchSession() { }
SearchSession::OwnershipBundle::OwnershipBundle() = default;
SearchSession::OwnershipBundle::~OwnershipBundle() { }
}
|
Fix strdup behavior on nullptr. | #include "BaseString.hpp"
// Apparently, strdup isn't a standard function, and isn't in <cstring>
char* strdup(const char *s) throw () {
auto n = strlen(s);
auto d = new char[n + 1];
return static_cast<char*>(memcpy(d, s, n + 1));
}
namespace K3 {
template<>
std::size_t hash_value<K3::base_string>(const K3::base_string& s) {
std::size_t seed = 0;
for (auto& i: s) {
boost::hash_combine(seed, i);
}
return seed;
}
}
| #include "BaseString.hpp"
// Apparently, strdup isn't a standard function, and isn't in <cstring>
char* strdup(const char *s) throw () {
if (!s) {
return nullptr;
}
auto n = strlen(s);
auto d = new char[n + 1];
return static_cast<char*>(memcpy(d, s, n + 1));
}
namespace K3 {
template<>
std::size_t hash_value<K3::base_string>(const K3::base_string& s) {
std::size_t seed = 0;
for (auto& i: s) {
boost::hash_combine(seed, i);
}
return seed;
}
}
|
Fix bug: visitor to IndexQueue may have side effects on first/second. | // index_queue.cc
// Copyright (c) 2014 Jinglei Ren <jinglei@ren.systems>
#include "index_queue.h"
void IndexQueue::Remove(int i) {
assert(i >= 0);
const int prev = array_[i].first;
const int next = array_[i].second;
if (prev == -EINVAL) {
assert(Front() == i);
SetFront(next);
} else {
array_[prev].second = next;
}
if (next == -EINVAL) {
assert(Back() == i);
SetBack(prev);
} else {
array_[next].first = prev;
}
array_[i].first = -EINVAL;
array_[i].second = -EINVAL;
--length_;
}
void IndexQueue::PushBack(int i) {
if (Empty()) {
array_[i].first = array_[i].second = -EINVAL;
SetFront(i);
SetBack(i);
} else {
array_[i].first = Back();
array_[i].second = -EINVAL;
BackNode().second = i;
SetBack(i);
}
++length_;
}
void IndexQueue::Accept(QueueVisitor* visitor) {
int i = Front();
while (i != -EINVAL) {
visitor->Visit(i);
i = array_[i].second;
}
}
| // index_queue.cc
// Copyright (c) 2014 Jinglei Ren <jinglei@ren.systems>
#include "index_queue.h"
using namespace std;
void IndexQueue::Remove(int i) {
assert(i >= 0);
const int prev = array_[i].first;
const int next = array_[i].second;
if (prev == -EINVAL) {
assert(Front() == i);
SetFront(next);
} else {
array_[prev].second = next;
}
if (next == -EINVAL) {
assert(Back() == i);
SetBack(prev);
} else {
array_[next].first = prev;
}
array_[i].first = -EINVAL;
array_[i].second = -EINVAL;
--length_;
}
void IndexQueue::PushBack(int i) {
if (Empty()) {
array_[i].first = array_[i].second = -EINVAL;
SetFront(i);
SetBack(i);
} else {
array_[i].first = Back();
array_[i].second = -EINVAL;
BackNode().second = i;
SetBack(i);
}
++length_;
}
void IndexQueue::Accept(QueueVisitor* visitor) {
int i = Front();
int tmp;
while (i != -EINVAL) {
tmp = array_[i].second;
visitor->Visit(i);
i = tmp;
}
}
|
Test epsilon in direct tree | #include "gtest/gtest.h"
#include "test/support.hpp"
namespace fgt {
TEST(DirectTree, MatchesDirect) {
auto source = load_ascii_test_matrix("X.txt");
auto target = load_ascii_test_matrix("Y.txt");
auto expected = direct(source, target, 0.5);
auto actual = direct_tree(source, target, 0.5, 1e-4);
EXPECT_TRUE(actual.isApprox(expected, 1e-4));
}
TEST(DirectTree, WithWeights) {
auto source = load_ascii_test_matrix("X.txt");
auto target = load_ascii_test_matrix("Y.txt");
Vector weights = Vector::LinSpaced(source.rows(), 0.1, 0.9);
auto expected = direct(source, target, 0.5, weights);
auto actual = direct_tree(source, target, 0.5, 1e-4, weights);
EXPECT_TRUE(expected.isApprox(actual));
}
TEST(DirectTree, ClassBased) {
auto source = load_ascii_test_matrix("X.txt");
auto target = load_ascii_test_matrix("Y.txt");
auto expected = direct(source, target, 0.5);
auto actual = DirectTree(source, 0.5, 1e-4).compute(target);
EXPECT_TRUE(actual.isApprox(expected, 1e-4));
}
}
| #include "gtest/gtest.h"
#include "test/support.hpp"
namespace fgt {
TEST(DirectTree, MatchesDirect) {
auto source = load_ascii_test_matrix("X.txt");
auto target = load_ascii_test_matrix("Y.txt");
double bandwidth = 0.5;
auto expected = direct(source, target, bandwidth);
double epsilon = 1e-4;
auto actual = direct_tree(source, target, bandwidth, epsilon);
EXPECT_LT((expected - actual).array().abs().maxCoeff() / actual.size(), epsilon);
}
TEST(DirectTree, WithWeights) {
auto source = load_ascii_test_matrix("X.txt");
auto target = load_ascii_test_matrix("Y.txt");
Vector weights = Vector::LinSpaced(source.rows(), 0.1, 0.9);
double bandwidth = 0.5;
auto expected = direct(source, target, bandwidth, weights);
double epsilon = 1e-4;
auto actual = direct_tree(source, target, bandwidth, epsilon, weights);
EXPECT_LT((expected - actual).array().abs().maxCoeff() / weights.sum(), epsilon);
}
TEST(DirectTree, ClassBased) {
auto source = load_ascii_test_matrix("X.txt");
auto target = load_ascii_test_matrix("Y.txt");
double bandwidth = 0.5;
auto expected = direct(source, target, bandwidth);
double epsilon = 1e-4;
auto actual = DirectTree(source, bandwidth, epsilon).compute(target);
EXPECT_LT((expected - actual).array().abs().maxCoeff() / actual.size(), epsilon);
}
}
|
Switch to using EXPECT_TRUE instead of EXPECT_EQ | #include "gtest/gtest.h"
#include "Ant.h"
TEST(AntTest, NewAntIsAlive)
{
Ant a1;
EXPECT_EQ(true, a1.isAlive());
}
TEST(AntTest, NewAntIsAgeZero)
{
Ant a1;
EXPECT_EQ(0, a1.getAge());
}
TEST(AntTest, AntAgesAfterUpdate)
{
Ant a1;
a1.update();
EXPECT_EQ(1, a1.getAge());
}
TEST(AntTest, AntDiesAfterMaxAge)
{
Ant a1;
for(int i=0; i < Ant::MAX_AGE; ++i)
{
a1.update();
}
EXPECT_FALSE(a1.isAlive());
}
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| #include "gtest/gtest.h"
#include "Ant.h"
TEST(AntTest, NewAntIsAlive)
{
Ant a1;
EXPECT_TRUE(a1.isAlive());
}
TEST(AntTest, NewAntIsAgeZero)
{
Ant a1;
EXPECT_EQ(0, a1.getAge());
}
TEST(AntTest, AntAgesAfterUpdate)
{
Ant a1;
a1.update();
EXPECT_EQ(1, a1.getAge());
}
TEST(AntTest, AntDiesAfterMaxAge)
{
Ant a1;
for(int i=0; i < Ant::MAX_AGE; ++i)
{
a1.update();
}
EXPECT_FALSE(a1.isAlive());
}
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
Fix typo in pseudocode comment | // An Homage to Vera Molnar's "An Homange to Durer"
SquareSize = [[Square Size]]
gridHeight = [[Grid Height]]
gridWidth = [[Grid Width]]
columnCounter = [[shiftCounter]]
rowCounter = [[rowCounter]]
if(columnCounter < [[gridWidth]]) {
drawVeraLines([[columnCounter]], [[rowCounter]])
columnCounter++;
} else if ([[rowCounter]] < [[gridHeight]]) {
columnCounter = 0;
rowCounter++;
} else {
rowCounter = 0;
columnCounter = 0;
} | // An homage to Vera Molnar's "Hommage a Durer"
SquareSize = [[Square Size]]
gridHeight = [[Grid Height]]
gridWidth = [[Grid Width]]
columnCounter = [[shiftCounter]]
rowCounter = [[rowCounter]]
if(columnCounter < [[gridWidth]]) {
drawVeraLines([[columnCounter]], [[rowCounter]])
columnCounter++;
} else if ([[rowCounter]] < [[gridHeight]]) {
columnCounter = 0;
rowCounter++;
} else {
rowCounter = 0;
columnCounter = 0;
} |
Fix to compile on MacOSX | #include "TextureAtlas.h"
TextureAtlas::TextureAtlas(const std::string& textureFileName)
{
sf::Image i;
if (!i.loadFromFile("Res/Textures/" + textureFileName + ".png"))
{
throw std::runtime_error("Unable to open image: " + textureFileName);
}
loadFromImage(i);
m_imageSize = 256;
m_individualTextureSize = 16;
}
std::array<GLfloat, 8> TextureAtlas::getTexture(const sf::Vector2i& coords)
{
static const GLfloat TEX_PER_ROW = (GLfloat)m_imageSize / (GLfloat)m_individualTextureSize;
static const GLfloat INDV_TEX_SIZE = 1.0f / TEX_PER_ROW;
static const GLfloat PIXEL_SIZE = 1.0f / (float)m_imageSize;
GLfloat xMin = (coords.x * INDV_TEX_SIZE) + 0.5 * PIXEL_SIZE;
GLfloat yMin = (coords.y * INDV_TEX_SIZE) + 0.5 * PIXEL_SIZE;
GLfloat xMax = (xMin + INDV_TEX_SIZE) - 0.5 * PIXEL_SIZE;
GLfloat yMax = (yMin + INDV_TEX_SIZE) - 0.5 * PIXEL_SIZE;
return
{
xMax, yMax,
xMin, yMax,
xMin, yMin,
xMax, yMin
};
}
| #include "TextureAtlas.h"
#include <array>
TextureAtlas::TextureAtlas(const std::string& textureFileName)
{
sf::Image i;
if (!i.loadFromFile("Res/Textures/" + textureFileName + ".png"))
{
throw std::runtime_error("Unable to open image: " + textureFileName);
}
loadFromImage(i);
m_imageSize = 256;
m_individualTextureSize = 16;
}
std::array<GLfloat, 8> TextureAtlas::getTexture(const sf::Vector2i& coords)
{
static const GLfloat TEX_PER_ROW = (GLfloat)m_imageSize / (GLfloat)m_individualTextureSize;
static const GLfloat INDV_TEX_SIZE = 1.0f / TEX_PER_ROW;
static const GLfloat PIXEL_SIZE = 1.0f / (float)m_imageSize;
GLfloat xMin = (coords.x * INDV_TEX_SIZE) + 0.5 * PIXEL_SIZE;
GLfloat yMin = (coords.y * INDV_TEX_SIZE) + 0.5 * PIXEL_SIZE;
GLfloat xMax = (xMin + INDV_TEX_SIZE) - 0.5 * PIXEL_SIZE;
GLfloat yMax = (yMin + INDV_TEX_SIZE) - 0.5 * PIXEL_SIZE;
return
{
xMax, yMax,
xMin, yMax,
xMin, yMin,
xMax, yMin
};
}
|
Delete qApp instance on exit. | #include <QApplication>
#include <QDeclarativeView>
#include <QUrl>
#include <qplatformdefs.h>
#include <LunaWebView.h>
#if defined(MEEGO_EDITION_HARMATTAN)
#include <MDeclarativeCache>
#define NEW_QAPPLICATION(x, y) MDeclarativeCache::qApplication((x), (y))
Q_DECL_EXPORT
#else
#define NEW_QAPPLICATION(x, y) new QApplication((x), (y))
#endif
int main(int argc, char** argv)
{
QApplication* app = NEW_QAPPLICATION(argc, argv);
qmlRegisterType<LunaWebView>("Luna", 1, 0, "LunaWebView");
QDeclarativeView viewer;
#if defined(MEEGO_EDITION_HARMATTAN)
viewer.setSource(QUrl("qrc:/qml/main-harmattan.qml"));
viewer.showFullScreen();
#else
viewer.setSource(QUrl("qrc:/qml/main-desktop.qml"));
viewer.show();
#endif
return app->exec();
}
| #include <QApplication>
#include <QDeclarativeView>
#include <QUrl>
#include <QScopedPointer>
#include <qplatformdefs.h>
#include <LunaWebView.h>
#if defined(MEEGO_EDITION_HARMATTAN)
#include <MDeclarativeCache>
#define NEW_QAPPLICATION(x, y) MDeclarativeCache::qApplication((x), (y))
Q_DECL_EXPORT
#else
#define NEW_QAPPLICATION(x, y) new QApplication((x), (y))
#endif
int main(int argc, char** argv)
{
QScopedPointer<QApplication> app(NEW_QAPPLICATION(argc, argv));
qmlRegisterType<LunaWebView>("Luna", 1, 0, "LunaWebView");
QDeclarativeView viewer;
#if defined(MEEGO_EDITION_HARMATTAN)
viewer.setSource(QUrl("qrc:/qml/main-harmattan.qml"));
viewer.showFullScreen();
#else
viewer.setSource(QUrl("qrc:/qml/main-desktop.qml"));
viewer.show();
#endif
return app->exec();
}
|
Define a simple hello method for scratch testing | // File: btBoostWrapper.cpp
#ifndef _btBoostWrapper_cpp
#define _btBoostWrapper_cpp
#pragma GCC diagnostic ignored "-Wunused-variable"
#pragma GCC diagnostic ignored "-Wreorder"
#include <boost/python.hpp>
#include <btBoost/btBoostLinearMath.hpp>
#include <btBoost/btBoostDynamics.hpp>
using namespace boost::python;
BOOST_PYTHON_MODULE(bullet)
{
defineLinearMath();
defineDynamics();
}
#endif // _btBoostWrapper_cpp
| // File: btBoostWrapper.cpp
#ifndef _btBoostWrapper_cpp
#define _btBoostWrapper_cpp
#pragma GCC diagnostic ignored "-Wunused-variable"
#pragma GCC diagnostic ignored "-Wreorder"
#include <boost/python.hpp>
#include <btBoost/btBoostLinearMath.hpp>
#include <btBoost/btBoostDynamics.hpp>
#include <btBoost/btBoostHello.hpp>
using namespace boost::python;
BOOST_PYTHON_MODULE(bullet)
{
defineHello();
defineLinearMath();
defineDynamics();
}
#endif // _btBoostWrapper_cpp
|
Fix error [FATAL:at_exit.cc(40)] Check failed: false. Tried to RegisterCallback without an AtExitManager in (possibly unused) binary perf_tests | // 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 "base/message_loop.h"
#include "base/perf_test_suite.h"
#include "chrome/common/chrome_paths.cc"
int main(int argc, char **argv) {
chrome::RegisterPathProvider();
MessageLoop main_message_loop;
return PerfTestSuite(argc, argv).Run();
}
| // 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 "base/message_loop.h"
#include "base/perf_test_suite.h"
#include "chrome/common/chrome_paths.cc"
int main(int argc, char **argv) {
PerfTestSuite suite(argc, argv);
chrome::RegisterPathProvider();
MessageLoop main_message_loop;
return suite.Run();
}
|
Change generic external commit helper to just be commented out for now | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 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 "impl/external_commit_helper.hpp"
#include "impl/realm_coordinator.hpp"
#include <realm/commit_log.hpp>
#include <realm/replication.hpp>
using namespace realm;
using namespace realm::_impl;
ExternalCommitHelper::ExternalCommitHelper(RealmCoordinator& parent)
{
}
ExternalCommitHelper::~ExternalCommitHelper()
{
}
| ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 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 "impl/external_commit_helper.hpp"
#include "impl/realm_coordinator.hpp"
#include <realm/commit_log.hpp>
#include <realm/replication.hpp>
using namespace realm;
using namespace realm::_impl;
ExternalCommitHelper::ExternalCommitHelper(RealmCoordinator& parent)
//: m_parent(parent)
//, m_history(realm::make_client_history(parent.get_path(), parent.get_encryption_key().data()))
//, m_sg(*m_history, parent.is_in_memory() ? SharedGroup::durability_MemOnly : SharedGroup::durability_Full,
// parent.get_encryption_key().data())
//, m_thread(std::async(std::launch::async, [=] {
// m_sg.begin_read();
// while (m_sg.wait_for_change()) {
// m_sg.end_read();
// m_sg.begin_read();
// m_parent.on_change();
// }
//}))
{
}
ExternalCommitHelper::~ExternalCommitHelper()
{
//m_sg.wait_for_change_release();
//m_thread.wait(); // Wait for the thread to exit
}
|
Add trylock in Windows implementation of mutex. | #include "Thread/Win/MutexImpl.hh"
#include "Thread/ThreadException.hh"
namespace LilWrapper
{
MutexImpl::MutexImpl()
{
InitializeCriticalSection(&this->_mutex);
}
MutexImpl::~MutexImpl()
{
DeleteCriticalSection(&this->_mutex);
}
void MutexImpl::lock()
{
EnterCriticalSection(&this->_mutex);
}
void MutexImpl::unlock()
{
LeaveCriticalSection(&this->_mutex);
}
bool MutexImpl::trylock()
{
}
}
| #include "Thread/Win/MutexImpl.hh"
#include "Thread/ThreadException.hh"
namespace LilWrapper
{
MutexImpl::MutexImpl()
{
InitializeCriticalSection(&this->_mutex);
}
MutexImpl::~MutexImpl()
{
DeleteCriticalSection(&this->_mutex);
}
void MutexImpl::lock()
{
EnterCriticalSection(&this->_mutex);
}
void MutexImpl::unlock()
{
LeaveCriticalSection(&this->_mutex);
}
bool MutexImpl::trylock()
{
return (TryEnterCriticalSection(&this->_mutex) != 0);
}
}
|
Disable test failing since r29947. | // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Storage) {
ASSERT_TRUE(RunExtensionTest("storage")) << message_;
}
| // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
// Started failing with r29947. WebKit merge 49961:49992.
IN_PROC_BROWSER_TEST_F(DISABLED_ExtensionApiTest, Storage) {
ASSERT_TRUE(RunExtensionTest("storage")) << message_;
}
|
Use qreal instead of int for painting. | #include "histogram.h"
#include <QPainter>
#include <QDebug>
Histogram::Histogram(QWidget* p) :QWidget(p) {
}
void
Histogram::setData(const QList<QPair<QString,quint32> >& d) {
data = d;
update();
}
typedef QPair<QString, quint32> StringUIntPair;
void
Histogram::paintEvent(QPaintEvent *) {
if (data.size() == 0) return;
int w = width();
int h = height();
int m = 5;
int bw = (w-m*(data.size()-1))/data.size();
uint max = 0;
foreach (const StringUIntPair& p, data) {
if (p.second > max) max = p.second;
}
QPainter painter(this);
painter.setPen(palette().highlightedText().color());
int offset = 0;
painter.rotate(-90);
painter.translate(-h, 0);
foreach (const StringUIntPair& p, data) {
int bh = p.second*h/max;
painter.fillRect(0, offset, bh, bw, palette().highlight());
painter.drawText(QRect(m, offset, bh-m, bw), Qt::AlignVCenter,
p.first);
offset += bw + m;
}
}
| #include "histogram.h"
#include <QPainter>
#include <QDebug>
Histogram::Histogram(QWidget* p) :QWidget(p) {
}
void
Histogram::setData(const QList<QPair<QString,quint32> >& d) {
data = d;
update();
}
typedef QPair<QString, quint32> StringUIntPair;
void
Histogram::paintEvent(QPaintEvent *) {
if (data.size() == 0) return;
int w = width();
int h = height();
int m = 5;
int bw = (w-m*(data.size()-1))/data.size();
uint max = 0;
foreach (const StringUIntPair& p, data) {
if (p.second > max) max = p.second;
}
QPainter painter(this);
painter.setPen(palette().highlightedText().color());
qreal offset = 0;
painter.rotate(-90);
painter.translate(-h, 0);
foreach (const StringUIntPair& p, data) {
qreal bh = p.second*h/(qreal)max;
painter.fillRect(QRectF(0, offset, bh, bw), palette().highlight());
painter.drawText(QRectF(m, offset, bh-m, bw), Qt::AlignVCenter,
p.first);
offset += bw + m;
}
}
|
Revert "TransportServerDummy: no log on close" | /*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#include <iostream>
#include <qi/log.hpp>
#include <qimessaging/session.hpp>
#include <qimessaging/url.hpp>
#include "transportserver_p.hpp"
#include "transportserverdummy_p.hpp"
namespace qi
{
bool TransportServerDummyPrivate::listen()
{
qiLogWarning("TransportServer") << "listen: You are currently running on dummy"
<< " TransportServer!";
return true;
}
void TransportServerDummyPrivate::close()
{
}
TransportServerDummyPrivate::TransportServerDummyPrivate(TransportServer* self,
const qi::Url &url,
EventLoop* ctx)
: TransportServerPrivate(self, url, ctx)
{
}
void TransportServerDummyPrivate::destroy()
{
delete this;
}
TransportServerDummyPrivate::~TransportServerDummyPrivate()
{
}
}
| /*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#include <iostream>
#include <qi/log.hpp>
#include <qimessaging/session.hpp>
#include <qimessaging/url.hpp>
#include "transportserver_p.hpp"
#include "transportserverdummy_p.hpp"
namespace qi
{
bool TransportServerDummyPrivate::listen()
{
qiLogWarning("TransportServer") << "listen: You are currently running on dummy"
<< " TransportServer!";
return true;
}
void TransportServerDummyPrivate::close()
{
qiLogVerbose("TransportServer") << "close: You are currently running on dummy"
<< " TransportServer!";
}
TransportServerDummyPrivate::TransportServerDummyPrivate(TransportServer* self,
const qi::Url &url,
EventLoop* ctx)
: TransportServerPrivate(self, url, ctx)
{
}
void TransportServerDummyPrivate::destroy()
{
delete this;
}
TransportServerDummyPrivate::~TransportServerDummyPrivate()
{
}
}
|
Disable array cookie test on ARM, enable on Android/x86. | // Test that we do not poison the array cookie if the operator new is defined
// inside the class.
// RUN: %clangxx_asan %s -o %t && %run %t
//
// XFAIL: android
// XFAIL: armv7l-unknown-linux-gnueabihf
#include <new>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <assert.h>
struct Foo {
void *operator new(size_t s) { return Allocate(s); }
void *operator new[] (size_t s) { return Allocate(s); }
~Foo();
static void *allocated;
static void *Allocate(size_t s) {
assert(!allocated);
return allocated = ::new char[s];
}
};
Foo::~Foo() {}
void *Foo::allocated;
Foo *getFoo(size_t n) {
return new Foo[n];
}
int main() {
Foo *foo = getFoo(10);
fprintf(stderr, "foo : %p\n", foo);
fprintf(stderr, "alloc: %p\n", Foo::allocated);
assert(reinterpret_cast<uintptr_t>(foo) ==
reinterpret_cast<uintptr_t>(Foo::allocated) + sizeof(void*));
*reinterpret_cast<uintptr_t*>(Foo::allocated) = 42;
return 0;
}
| // Test that we do not poison the array cookie if the operator new is defined
// inside the class.
// RUN: %clangxx_asan %s -o %t && %run %t
//
// XFAIL: arm
#include <new>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <assert.h>
struct Foo {
void *operator new(size_t s) { return Allocate(s); }
void *operator new[] (size_t s) { return Allocate(s); }
~Foo();
static void *allocated;
static void *Allocate(size_t s) {
assert(!allocated);
return allocated = ::new char[s];
}
};
Foo::~Foo() {}
void *Foo::allocated;
Foo *getFoo(size_t n) {
return new Foo[n];
}
int main() {
Foo *foo = getFoo(10);
fprintf(stderr, "foo : %p\n", foo);
fprintf(stderr, "alloc: %p\n", Foo::allocated);
assert(reinterpret_cast<uintptr_t>(foo) ==
reinterpret_cast<uintptr_t>(Foo::allocated) + sizeof(void*));
*reinterpret_cast<uintptr_t*>(Foo::allocated) = 42;
return 0;
}
|
Test that MatcherException::what() returns non-empty string | #include "matcherexception.h"
#include "3rd-party/catch.hpp"
using namespace newsboat;
extern "C" {
MatcherErrorFfi rs_get_test_attr_unavail_error();
MatcherErrorFfi rs_get_test_invalid_regex_error();
}
TEST_CASE("Can be constructed from Rust error returned over FFI",
"[MatcherException]")
{
SECTION("Attribute unavailable") {
const auto e = MatcherException::from_rust_error(
rs_get_test_attr_unavail_error());
REQUIRE(e.type() == MatcherException::Type::ATTRIB_UNAVAIL);
REQUIRE(e.info() == "test_attribute");
REQUIRE(e.info2().empty());
}
SECTION("Invalid regex") {
const auto e = MatcherException::from_rust_error(
rs_get_test_invalid_regex_error());
REQUIRE(e.type() == MatcherException::Type::INVALID_REGEX);
REQUIRE(e.info() == "?!");
REQUIRE(e.info2() == "inconceivable happened!");
}
}
| #include "matcherexception.h"
#include "3rd-party/catch.hpp"
#include <cstring>
using namespace newsboat;
extern "C" {
MatcherErrorFfi rs_get_test_attr_unavail_error();
MatcherErrorFfi rs_get_test_invalid_regex_error();
}
TEST_CASE("Can be constructed from Rust error returned over FFI",
"[MatcherException]")
{
SECTION("Attribute unavailable") {
const auto e = MatcherException::from_rust_error(
rs_get_test_attr_unavail_error());
REQUIRE(e.type() == MatcherException::Type::ATTRIB_UNAVAIL);
REQUIRE(e.info() == "test_attribute");
REQUIRE(e.info2().empty());
REQUIRE_FALSE(strlen(e.what()) == 0);
}
SECTION("Invalid regex") {
const auto e = MatcherException::from_rust_error(
rs_get_test_invalid_regex_error());
REQUIRE(e.type() == MatcherException::Type::INVALID_REGEX);
REQUIRE(e.info() == "?!");
REQUIRE(e.info2() == "inconceivable happened!");
REQUIRE_FALSE(strlen(e.what()) == 0);
}
}
|
Allow this file to compile on Darwin. | //===- Darwin/MappedFile.cpp - Darwin MappedFile Implementation -*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Reid Spencer and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provides the Darwin specific implementation of the MappedFile
// concept.
//
//===----------------------------------------------------------------------===//
// Include the generic unix implementation
#include "../Unix/MappedFile.cpp"
// vim: sw=2 smartindent smarttab tw=80 autoindent expandtab
| //===- Darwin/MappedFile.cpp - Darwin MappedFile Implementation -*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Reid Spencer and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provides the Darwin specific implementation of the MappedFile
// concept.
//
//===----------------------------------------------------------------------===//
// Include the generic unix implementation
#include <sys/stat.h>
#include "../Unix/MappedFile.cpp"
// vim: sw=2 smartindent smarttab tw=80 autoindent expandtab
|
Make independent of initializer list support. | // Check if trailing return types are supported
#include <algorithm>
#include <vector>
void fun() {
int val = 0;
std::vector<int> v{0, 1, 2, 4, 8};
std::sort(v.begin(), v.end(),
[&](int i, int j)->bool{ val++; return i < j && val++ < i; });
}
| // Check if trailing return types are supported
#include <algorithm>
#include <vector>
void fun() {
int val = 0;
std::vector<int> v(5);
std::sort(v.begin(), v.end(),
[&](int i, int j)->bool{ val++; return i < j && val++ < i; });
}
|
Fix test for LLVM change r203619 | // REQUIRES: x86-registered-target
// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -g -fstandalone-debug -S -mllvm -generate-dwarf-pub-sections=Enable %s -o - | FileCheck %s
// FIXME: This testcase shouldn't rely on assembly emission.
//CHECK: Lpubtypes_begin[[SECNUM:[0-9]:]]
//CHECK: .asciz "G"
//CHECK-NEXT: .long 0
//CHECK-NEXT: Lpubtypes_end[[SECNUM]]
class G {
public:
void foo();
};
void G::foo() {
}
| // REQUIRES: x86-registered-target
// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -g -fstandalone-debug -S -mllvm -generate-dwarf-pub-sections=Enable %s -o - | FileCheck %s
// FIXME: This testcase shouldn't rely on assembly emission.
//CHECK: LpubTypes_begin[[SECNUM:[0-9]:]]
//CHECK: .asciz "G"
//CHECK-NEXT: .long 0
//CHECK-NEXT: LpubTypes_end[[SECNUM]]
class G {
public:
void foo();
};
void G::foo() {
}
|
Correct usage line, no need to include .py in module name. | #include <iostream>
#include <Python.h>
#include "character.h"
using namespace std;
static int error(const std::string & message){
std::cout << message << std::endl;
//PyErr_Print();
return -1;
}
int main(int argc, char ** argv){
if (argc > 1){
Py_Initialize();
/* NOTE need to make sure we are trying to load in the same directory (is there a work around?) */
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
try {
Character * character = new Character(argv[1]);
character->addAttribute("name", Character::String);
std::cout << "Character Name: " << character->getStringValue("name") << std::endl;
delete character;
} catch (const PyException & ex){
error("Problem loading module! Reason: " + ex.getReason());
}
Py_Finalize();
return 0;
}
std::cout << "Usage: ./test character.py" << std::endl;
return 0;
}
| #include <iostream>
#include <Python.h>
#include "character.h"
using namespace std;
static int error(const std::string & message){
std::cout << message << std::endl;
//PyErr_Print();
return -1;
}
int main(int argc, char ** argv){
if (argc > 1){
Py_Initialize();
/* NOTE need to make sure we are trying to load in the same directory (is there a work around?) */
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
try {
Character * character = new Character(argv[1]);
character->addAttribute("name", Character::String);
std::cout << "Character Name: " << character->getStringValue("name") << std::endl;
delete character;
} catch (const PyException & ex){
error("Problem loading module! Reason: " + ex.getReason());
}
Py_Finalize();
return 0;
}
std::cout << "Usage: ./test character_module_name" << std::endl;
return 0;
}
|
Make realm-tests switch to test directory upon start | /*************************************************************************
*
* 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 "test_all.hpp"
int main(int argc, char* argv[])
{
return test_all(argc, argv);
}
| /*************************************************************************
*
* 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 "test_all.hpp"
#ifdef _MSC_VER
#include <Shlwapi.h>
#pragma comment(lib, "Shlwapi.lib")
#else
#include <unistd.h>
#include <libgen.h>
#endif
int main(int argc, char* argv[])
{
#ifdef _MSC_VER
char path[MAX_PATH];
if (GetModuleFileNameA(NULL, path, sizeof(path)) == 0) {
fprintf(stderr, "Failed to retrieve path to exectuable.\n");
return 1;
}
PathRemoveFileSpecA(path);
SetCurrentDirectoryA(path);
#else
char executable[PATH_MAX];
realpath(argv[0], executable);
const char* directory = dirname(executable);
chdir(directory);
#endif
return test_all(argc, argv);
}
|
Stop uploading unrecoverable errors to breakpad in preparation for beta. | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"
#include "base/rand_util.h"
#include "build/build_config.h"
#if defined(OS_WIN)
#include <windows.h>
#endif
#include "chrome/common/chrome_constants.h"
namespace browser_sync {
static const double kErrorUploadRatio = 0.15;
void ChromeReportUnrecoverableError() {
// TODO(lipalani): Add this for other platforms as well.
#if defined(OS_WIN)
// We only want to upload |kErrorUploadRatio| ratio of errors.
double random_number = base::RandDouble();
if (random_number > kErrorUploadRatio)
return;
// Get the breakpad pointer from chrome.exe
typedef void (__cdecl *DumpProcessFunction)();
DumpProcessFunction DumpProcess = reinterpret_cast<DumpProcessFunction>(
::GetProcAddress(::GetModuleHandle(
chrome::kBrowserProcessExecutableName),
"DumpProcessWithoutCrash"));
if (DumpProcess)
DumpProcess();
#endif // OS_WIN
}
} // namespace browser_sync
| // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"
#include "base/rand_util.h"
#include "build/build_config.h"
#if defined(OS_WIN)
#include <windows.h>
#endif
#include "chrome/common/chrome_constants.h"
namespace browser_sync {
static const double kErrorUploadRatio = 0.0;
void ChromeReportUnrecoverableError() {
// TODO(lipalani): Add this for other platforms as well.
#if defined(OS_WIN)
// We only want to upload |kErrorUploadRatio| ratio of errors.
if (kErrorUploadRatio <= 0.0)
return; // We are not allowed to upload errors.
double random_number = base::RandDouble();
if (random_number > kErrorUploadRatio)
return;
// Get the breakpad pointer from chrome.exe
typedef void (__cdecl *DumpProcessFunction)();
DumpProcessFunction DumpProcess = reinterpret_cast<DumpProcessFunction>(
::GetProcAddress(::GetModuleHandle(
chrome::kBrowserProcessExecutableName),
"DumpProcessWithoutCrash"));
if (DumpProcess)
DumpProcess();
#endif // OS_WIN
}
} // namespace browser_sync
|
Use FileCheck instead of [. | // FIXME: https://code.google.com/p/address-sanitizer/issues/detail?id=316
// XFAIL: android
//
// RUN: %clangxx_asan -fsanitize-coverage=func %s -o %t
// RUN: rm -rf %T/coverage-maybe-open-file
// RUN: mkdir -p %T/coverage-maybe-open-file && cd %T/coverage-maybe-open-file
// RUN: %env_asan_opts=coverage=1 %run %t | FileCheck %s --check-prefix=CHECK-success
// RUN: %env_asan_opts=coverage=0 %run %t | FileCheck %s --check-prefix=CHECK-fail
// RUN: [ "$(cat test.sancov.packed)" == "test" ]
// RUN: cd .. && rm -rf %T/coverage-maybe-open-file
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sanitizer/coverage_interface.h>
// FIXME: the code below might not work on Windows.
int main(int argc, char **argv) {
int fd = __sanitizer_maybe_open_cov_file("test");
if (fd > 0) {
printf("SUCCESS\n");
const char s[] = "test\n";
write(fd, s, strlen(s));
close(fd);
} else {
printf("FAIL\n");
}
}
// CHECK-success: SUCCESS
// CHECK-fail: FAIL
| // FIXME: https://code.google.com/p/address-sanitizer/issues/detail?id=316
// XFAIL: android
//
// RUN: %clangxx_asan -fsanitize-coverage=func %s -o %t
// RUN: rm -rf %T/coverage-maybe-open-file
// RUN: mkdir -p %T/coverage-maybe-open-file && cd %T/coverage-maybe-open-file
// RUN: %env_asan_opts=coverage=1 %run %t | FileCheck %s --check-prefix=CHECK-success
// RUN: %env_asan_opts=coverage=0 %run %t | FileCheck %s --check-prefix=CHECK-fail
// RUN: FileCheck %s < test.sancov.packed -implicit-check-not={{.}} --check-prefix=CHECK-test
// RUN: cd .. && rm -rf %T/coverage-maybe-open-file
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sanitizer/coverage_interface.h>
// FIXME: the code below might not work on Windows.
int main(int argc, char **argv) {
int fd = __sanitizer_maybe_open_cov_file("test");
if (fd > 0) {
printf("SUCCESS\n");
const char s[] = "test\n";
write(fd, s, strlen(s));
close(fd);
} else {
printf("FAIL\n");
}
}
// CHECK-success: SUCCESS
// CHECK-fail: FAIL
// CHECK-test: {{^}}test{{$}}
|
Remove CHECK line for kernel32.dll | // RUN: %clang_cl_asan -O0 %s -Fe%t
// RUN: not %run %t 2>&1 | FileCheck %s
#include <stdio.h>
char bigchunk[1 << 30];
int main() {
printf("Hello, world!\n");
scanf("%s", bigchunk);
// CHECK-NOT: Hello, world!
// CHECK: Shadow memory range interleaves with an existing memory mapping.
// CHECK: ASan shadow was supposed to be located in the [0x2fff0000-0x{{.*}}ffff] range.
// CHECK: Dumping process modules:
// CHECK-DAG: 0x{{[0-9a-f]*}}-0x{{[0-9a-f]*}} {{.*}}shadow_mapping_failure
// CHECK-DAG: 0x{{[0-9a-f]*}}-0x{{[0-9a-f]*}} {{.*}}kernel32.dll
// CHECK-DAG: 0x{{[0-9a-f]*}}-0x{{[0-9a-f]*}} {{.*}}ntdll.dll
}
| // RUN: %clang_cl_asan -O0 %s -Fe%t
// RUN: not %run %t 2>&1 | FileCheck %s
#include <stdio.h>
char bigchunk[1 << 30];
int main() {
printf("Hello, world!\n");
scanf("%s", bigchunk);
// CHECK-NOT: Hello, world!
// CHECK: Shadow memory range interleaves with an existing memory mapping.
// CHECK: ASan shadow was supposed to be located in the [0x2fff0000-0x{{.*}}ffff] range.
// CHECK: Dumping process modules:
// CHECK-DAG: 0x{{[0-9a-f]*}}-0x{{[0-9a-f]*}} {{.*}}shadow_mapping_failure
// CHECK-DAG: 0x{{[0-9a-f]*}}-0x{{[0-9a-f]*}} {{.*}}ntdll.dll
}
|
Revert ":lipstick: for the beforeunload handler." | // Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "browser/atom_javascript_dialog_manager.h"
#include "base/utf_string_conversions.h"
namespace atom {
void AtomJavaScriptDialogManager::RunBeforeUnloadDialog(
content::WebContents* web_contents,
const string16& message_text,
bool is_reload,
const DialogClosedCallback& callback) {
bool prevent_reload = !message_text.empty() ||
message_text == ASCIIToUTF16("false");
callback.Run(!prevent_reload, message_text);
}
} // namespace atom
| // Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "browser/atom_javascript_dialog_manager.h"
#include "base/utf_string_conversions.h"
namespace atom {
void AtomJavaScriptDialogManager::RunBeforeUnloadDialog(
content::WebContents* web_contents,
const string16& message_text,
bool is_reload,
const DialogClosedCallback& callback) {
bool prevent_reload = message_text.empty() ||
message_text == ASCIIToUTF16("false");
callback.Run(!prevent_reload, message_text);
}
} // namespace atom
|
Fix mistaken local variable name. | #include "game.hpp"
#include "window.hpp"
#include "clock.hpp"
#include "events.hpp"
#include <iostream>
// "Game" specific data
namespace {
bool gIsRunning = false;
class GameEventEar : public EventEar {
public:
void onWindowClose()
{
Game::stop();
}
};
GameEventEar gEar;
}
void Game::run()
{
// Don't run it twice.
if (gIsRunning)
return;
// Initialize the basics
Window::open(800, 600);
Clock::setTime(0.0);
Events::addEar(&gEar);
// Run the game loop
gIsRunning = true;
Clock::Timer frameCapTimer;
while (gIsRunning)
{
// Poll for new events
Events::poll();
// Perform drawing, logic, etc...
// Cap the framerate at 60
Clock::sleepFor((1.0 / 60.0) - dt.get());
frameCapTimer.set(0.0);
}
// Close the basics
Events::removeEar(&gEar);
Window::close();
}
void Game::stop()
{
gIsRunning = false;
}
| #include "game.hpp"
#include "window.hpp"
#include "clock.hpp"
#include "events.hpp"
#include <iostream>
// "Game" specific data
namespace {
bool gIsRunning = false;
class GameEventEar : public EventEar {
public:
void onWindowClose()
{
Game::stop();
}
};
GameEventEar gEar;
}
void Game::run()
{
// Don't run it twice.
if (gIsRunning)
return;
// Initialize the basics
Window::open(800, 600);
Clock::setTime(0.0);
Events::addEar(&gEar);
// Run the game loop
gIsRunning = true;
Clock::Timer frameCapTimer;
while (gIsRunning)
{
// Poll for new events
Events::poll();
// Perform drawing, logic, etc...
// Cap the framerate at 60
Clock::sleepFor((1.0 / 60.0) - frameCapTimer.get());
frameCapTimer.set(0.0);
}
// Close the basics
Events::removeEar(&gEar);
Window::close();
}
void Game::stop()
{
gIsRunning = false;
}
|
Use the NAN module init. | #include <nan.h>
#include "input.h"
#include "output.h"
Nan::Persistent<v8::FunctionTemplate> NodeMidiInput::s_ct;
Nan::Persistent<v8::FunctionTemplate> NodeMidiOutput::s_ct;
extern "C" {
void init (v8::Local<v8::Object> target)
{
NodeMidiOutput::Init(target);
NodeMidiInput::Init(target);
}
NODE_MODULE(midi, init)
}
| #include <nan.h>
#include "input.h"
#include "output.h"
Nan::Persistent<v8::FunctionTemplate> NodeMidiInput::s_ct;
Nan::Persistent<v8::FunctionTemplate> NodeMidiOutput::s_ct;
NAN_MODULE_INIT(InitAll) {
NodeMidiOutput::Init(target);
NodeMidiInput::Init(target);
}
NODE_MODULE(midi, InitAll)
|
Make print vector as auto function | #include <iostream>
#include <vector>
#include "MuMaterial.h"
#include "rhythm.hpp"
using namespace std;
void PrintVector (vector<float> v, string message);
int main ()
{
MuInit();
Rhythm rhythm(4, 4, 60);
rhythm.GenerateBaseRhythm(2);
vector<float> base_rhythm = rhythm.base_rhythm;
PrintVector(rhythm.base_rhythm, "base_rhythm");
cout << endl << "Ok!" << endl;
return 0;
}
void PrintVector (vector<float> v, string message)
{
cout << message << ": ";
for (unsigned int index = 0; index < v.size(); index++)
{
cout << v[index] << " ";
}
cout << endl;
}
| #include <iostream>
#include <vector>
#include "MuMaterial.h"
#include "rhythm.hpp"
using namespace std;
void PrintVector (auto const v, string message);
int main ()
{
MuInit();
Rhythm rhythm(4, 4, 60);
rhythm.GenerateBaseRhythm(2);
vector<float> base_rhythm = rhythm.base_rhythm;
PrintVector(rhythm.base_rhythm, "base_rhythm");
cout << endl << "Ok!" << endl;
return 0;
}
void PrintVector (auto const v, string message)
{
cout << message << ": ";
for (unsigned int index = 0; index < v.size(); index++)
{
cout << v[index] << " ";
}
cout << endl;
}
|
Complete header comment of Chapter 16, exercise 10 | // Function grapher: user can choose among a set of functions (e.g., sin() and
// log(), provide parameters for those functions and then graph them
#include "Simple_window.h"
#include "Graph.h"
int main()
try {
Point tl(400,150);
Fgraph_window fwin(tl,800,605,"Function Grapher");
return gui_main();
}
catch (exception& e) {
cerr << "exception: " << e.what() << endl;
keep_window_open();
}
catch (...) {
cerr << "exception\n";
keep_window_open();
} | // Chapter 16, exercise 10: function grapher: user can choose among a set of
// functions (e.g., sin() and log(), provide parameters for those functions and
// then graph them
#include "Simple_window.h"
#include "Graph.h"
int main()
try {
Point tl(400,150);
Fgraph_window fwin(tl,800,605,"Function Grapher");
return gui_main();
}
catch (exception& e) {
cerr << "exception: " << e.what() << endl;
keep_window_open();
}
catch (...) {
cerr << "exception\n";
keep_window_open();
}
|
Add tabs & CR sanity check | //
// Parser.cpp
// snowcrash
//
// Created by Zdenek Nemec on 4/8/13.
// Copyright (c) 2013 Apiary.io. All rights reserved.
//
#include <exception>
#include <sstream>
#include "Parser.h"
#include "MarkdownParser.h"
#include "BlueprintParser.h"
using namespace snowcrash;
const int SourceAnnotation::OK;
void Parser::parse(const SourceData& source, Result& result, Blueprint& blueprint)
{
try {
// Parse Markdown
MarkdownBlock::Stack markdown;
MarkdownParser markdownParser;
markdownParser.parse(source, result, markdown);
if (result.error.code != Error::OK)
return;
// Parse Blueprint
BlueprintParser::Parse(source, markdown, result, blueprint);
}
catch (const std::exception& e) {
std::stringstream ss;
ss << "parser exception: '" << e.what() << "'";
result.error = Error(ss.str(), 1);
}
catch (...) {
result.error = Error("parser exception has occured", 1);
}
}
| //
// Parser.cpp
// snowcrash
//
// Created by Zdenek Nemec on 4/8/13.
// Copyright (c) 2013 Apiary.io. All rights reserved.
//
#include <exception>
#include <sstream>
#include "Parser.h"
#include "MarkdownParser.h"
#include "BlueprintParser.h"
using namespace snowcrash;
const int SourceAnnotation::OK;
// Check source for unsupported character \t & \r
// Returns true if passed (not found), false otherwise
static bool CheckSource(const SourceData& source, Result& result)
{
std::string::size_type pos = source.find("\t");
if (pos != std::string::npos) {
result.error = Error("the use of tab(s) `\\t` in source data isn't currently supported, please contact makers", 2);
return false;
}
pos = source.find("\r");
if (pos != std::string::npos) {
result.error = Error("the use of carriage return(s) `\\r` in source data isn't currently supported, please contact makers", 2);
return false;
}
return true;
}
void Parser::parse(const SourceData& source, Result& result, Blueprint& blueprint)
{
try {
// Sanity Check
if (!CheckSource(source, result))
return;
// Parse Markdown
MarkdownBlock::Stack markdown;
MarkdownParser markdownParser;
markdownParser.parse(source, result, markdown);
if (result.error.code != Error::OK)
return;
// Parse Blueprint
BlueprintParser::Parse(source, markdown, result, blueprint);
}
catch (const std::exception& e) {
std::stringstream ss;
ss << "parser exception: '" << e.what() << "'";
result.error = Error(ss.str(), 1);
}
catch (...) {
result.error = Error("parser exception has occured", 1);
}
}
|
Add debug timestamp for log output. | #include <QApplication>
#include "qkeymapper.h"
#ifdef DEBUG_LOGOUT_ON
//#include "vld.h"
#endif
int main(int argc, char *argv[])
{
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
QApplication a(argc, argv);
QApplication::setStyle(QStyleFactory::create("Fusion"));
#ifdef ADJUST_PRIVILEGES
// BOOL adjustresult = QKeyMapper::AdjustPrivileges();
// qDebug() << "AdjustPrivileges Result:" << adjustresult;
BOOL adjustresult = QKeyMapper::EnableDebugPrivilege();
qDebug() << "EnableDebugPrivilege Result:" << adjustresult;
#endif
QKeyMapper w;
// Remove "?" Button from QDialog
Qt::WindowFlags flags = Qt::Dialog;
flags |= Qt::WindowMinimizeButtonHint;
flags |= Qt::WindowCloseButtonHint;
w.setWindowFlags(flags);
w.show();
return a.exec();
}
| #include <QApplication>
#include "qkeymapper.h"
#ifdef DEBUG_LOGOUT_ON
//#include "vld.h"
#endif
int main(int argc, char *argv[])
{
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
QApplication a(argc, argv);
QApplication::setStyle(QStyleFactory::create("Fusion"));
#ifdef DEBUG_LOGOUT_ON
qSetMessagePattern("%{time [hh:mm:ss.zzz]} Message:%{message}");
#endif
#ifdef ADJUST_PRIVILEGES
// BOOL adjustresult = QKeyMapper::AdjustPrivileges();
// qDebug() << "AdjustPrivileges Result:" << adjustresult;
BOOL adjustresult = QKeyMapper::EnableDebugPrivilege();
qDebug() << "EnableDebugPrivilege Result:" << adjustresult;
#endif
QKeyMapper w;
// Remove "?" Button from QDialog
Qt::WindowFlags flags = Qt::Dialog;
flags |= Qt::WindowMinimizeButtonHint;
flags |= Qt::WindowCloseButtonHint;
w.setWindowFlags(flags);
w.show();
return a.exec();
}
|
Fix build error on OSX | #include "SuffixTree\SuffixTreeBuilder.h"
#include <iostream>
#include <string>
#include <cassert>
#include <ctime>
using namespace std;
int main()
{
unsigned int length = 100000;
char* source = new char[length + 1];
for (unsigned int i = 0; i < length; i++)
{
source[i] = rand() % 26 + 'A';
}
source[length] = 0;
string s = source;
clock_t s_time = clock();
SuffixTreeBuilder builder(s);
SuffixTree suffixTree;
builder.BuildSuffixTree(&suffixTree);
clock_t e_time = clock();
cout << e_time - s_time << endl;
// cout << suffixTree.Show(s, &builder) << endl;
return 0;
}
| #include "SuffixTree/SuffixTreeBuilder.h"
#include <iostream>
#include <string>
#include <cassert>
#include <ctime>
using namespace std;
int main()
{
unsigned int length = 100000;
char* source = new char[length + 1];
for (unsigned int i = 0; i < length; i++)
{
source[i] = rand() % 26 + 'A';
}
source[length] = 0;
string s = source;
clock_t s_time = clock();
SuffixTreeBuilder builder(s);
SuffixTree suffixTree;
builder.BuildSuffixTree(&suffixTree);
clock_t e_time = clock();
cout << e_time - s_time << endl;
// cout << suffixTree.Show(s, &builder) << endl;
return 0;
}
|
Set the default scale to 100 | #include "glTFForUE4EdPrivatePCH.h"
#include "glTFImportOptions.h"
FglTFImportOptions::FglTFImportOptions()
: FilePathInOS(TEXT(""))
, FilePathInEngine(TEXT(""))
, MeshScaleRatio(1.0f)
, bInvertNormal(false)
, bImportMaterial(true)
, bRecomputeNormals(true)
, bRecomputeTangents(true)
{
//
}
const FglTFImportOptions FglTFImportOptions::Default;
FglTFImportOptions FglTFImportOptions::Current;
| #include "glTFForUE4EdPrivatePCH.h"
#include "glTFImportOptions.h"
FglTFImportOptions::FglTFImportOptions()
: FilePathInOS(TEXT(""))
, FilePathInEngine(TEXT(""))
, MeshScaleRatio(100.0f)
, bInvertNormal(false)
, bImportMaterial(true)
, bRecomputeNormals(true)
, bRecomputeTangents(true)
{
//
}
const FglTFImportOptions FglTFImportOptions::Default;
FglTFImportOptions FglTFImportOptions::Current;
|
Fix compiler warning about member initializer order | #include <cucumber-cpp/internal/connectors/wire/WireServer.hpp>
namespace cucumber {
namespace internal {
SocketServer::SocketServer(const ProtocolHandler *protocolHandler) :
ios(),
acceptor(ios),
protocolHandler(protocolHandler) {
}
void SocketServer::listen(const port_type port) {
tcp::endpoint endpoint(tcp::v4(), port);
acceptor.open(endpoint.protocol());
acceptor.set_option(tcp::acceptor::reuse_address(true));
acceptor.bind(endpoint);
acceptor.listen(1);
}
void SocketServer::acceptOnce() {
tcp::iostream stream;
acceptor.accept(*stream.rdbuf());
processStream(stream);
}
void SocketServer::processStream(tcp::iostream &stream) {
std::string request;
while (getline(stream, request)) {
stream << protocolHandler->handle(request) << std::endl << std::flush;
}
}
}
}
| #include <cucumber-cpp/internal/connectors/wire/WireServer.hpp>
namespace cucumber {
namespace internal {
SocketServer::SocketServer(const ProtocolHandler *protocolHandler) :
protocolHandler(protocolHandler),
ios(),
acceptor(ios) {
}
void SocketServer::listen(const port_type port) {
tcp::endpoint endpoint(tcp::v4(), port);
acceptor.open(endpoint.protocol());
acceptor.set_option(tcp::acceptor::reuse_address(true));
acceptor.bind(endpoint);
acceptor.listen(1);
}
void SocketServer::acceptOnce() {
tcp::iostream stream;
acceptor.accept(*stream.rdbuf());
processStream(stream);
}
void SocketServer::processStream(tcp::iostream &stream) {
std::string request;
while (getline(stream, request)) {
stream << protocolHandler->handle(request) << std::endl << std::flush;
}
}
}
}
|
Add missing header for windows. | /**
** \file libport/perror.cc
** \brief perror: implements file libport/perror.hh
*/
#include <cstdio>
#include <iostream>
#include "libport/cstring"
namespace libport
{
void
perror (const char* s)
{
#ifndef WIN32
::perror(s);
#else
int errnum;
const char* errstring;
const char* colon;
errnum = WSAGetLastError();
errstring = strerror(errnum);
if (s == NULL || *s == '\0')
s = colon = "";
else
colon = ": ";
std::cerr << s << colon << errstring << std::endl;
#endif
}
}
| /**
** \file libport/perror.cc
** \brief perror: implements file libport/perror.hh
*/
#include <cstdio>
#include <iostream>
#include "libport/windows.hh"
#include "libport/cstring"
namespace libport
{
void
perror (const char* s)
{
#ifndef WIN32
::perror(s);
#else
int errnum;
const char* errstring;
const char* colon;
errnum = WSAGetLastError();
errstring = strerror(errnum);
if (s == NULL || *s == '\0')
s = colon = "";
else
colon = ": ";
std::cerr << s << colon << errstring << std::endl;
#endif
}
}
|
Fix "inifiniteLoop" test for Qt 4. | #include <QThread>
int main()
{
QThread::sleep(60);
}
| #include <QThread>
class MyThread : public QThread
{
public:
static void mySleep(unsigned long secs) { sleep(secs); } // sleep() is protected in Qt 4.
};
int main()
{
MyThread::mySleep(60);
}
|
Fix formatting for matrix output | #include <miniMAT/util/PrintResult.hpp>
#include <iostream>
#include <iomanip>
namespace miniMAT {
namespace util {
void PrintResult(std::string varname, Matrix m, bool suppressed) {
if (!suppressed) {
// Print a row at a time (default precision is 4)
std::cout << varname << " =" << std::endl << std::endl;
for (int i = 0; i < m.rows(); i++) {
std::cout << " ";
for (int j = 0; j < m.cols(); j++)
std::cout << std::fixed << std::showpoint << std::setprecision(4) << m(i,j) << " ";
std::cout << std::endl;
}
std::cout << std::endl;
}
}
}
} | #include <miniMAT/util/PrintResult.hpp>
#include <iostream>
#include <iomanip>
#include <cmath>
namespace miniMAT {
namespace util {
void PrintResult(std::string varname, Matrix m, bool suppressed) {
if (!suppressed) {
using namespace std;
int maxdigits = log10(m.maxCoeff()) + 1; // Get number of digits of max element
int precision = 4;
int space = 1, dot = 1;
// Print a row at a time (default precision is 4)
cout << varname << " =" << endl << endl;
for (int i = 0; i < m.rows(); i++) {
cout << " ";
for (int j = 0; j < m.cols(); j++)
cout << right
<< fixed
<< showpoint
<< setprecision(precision)
<< setw(maxdigits + precision + dot + space)
<< m(i,j);
cout << endl;
}
cout << endl;
}
}
}
} |
Change status codes for debugging | /**
* @file Connection.cpp
* @brief
* @author Travis Lane
* @version 0.0.1
* @date 2016-01-05
*/
#include "Connection.h"
Connection::Connection(Bluetooth &new_bt, int id) : bt(new_bt)
{
this->id = id;
}
int Connection::write(int percent)
{
int rc = 0;
StaticJsonBuffer<200> buffer;
JsonObject& object = buffer.createObject();
if (!bt.connected()) {
return -1;
}
object["id"] = this->id;
object["throttle"] = percent;
/* Don't pretty print, I deliminate on \n */
rc = object.printTo(bt);
bt.write('\n');
return rc;
}
int Connection::read(int *out_percent)
{
int rc = 0;
char buff[200];
StaticJsonBuffer<200> buffer;
if (!bt.connected()) {
return -1;
}
rc = bt.readBytesUntil('\n', buff, sizeof(buff));
if (rc <= 0) {
return -1;
}
/* Set last char to NULL */
buff[rc] = '\0';
JsonObject& object = buffer.parseObject(buff);
if (!object.success()) {
return -1;
}
if (object["id"] != id) {
/* The ID doesn't match... We should ignore this message */
return -1;
}
*out_percent = object["throttle"];
return rc;
}
| /**
* @file Connection.cpp
* @brief
* @author Travis Lane
* @version 0.0.1
* @date 2016-01-05
*/
#include "Connection.h"
Connection::Connection(Bluetooth &new_bt, int id) : bt(new_bt)
{
this->id = id;
}
int Connection::write(int percent)
{
int rc = 0;
StaticJsonBuffer<200> buffer;
JsonObject& object = buffer.createObject();
if (!bt.connected()) {
return -1;
}
object["id"] = this->id;
object["throttle"] = percent;
/* Don't pretty print, I deliminate on \n */
rc = object.printTo(bt);
bt.write('\n');
return rc;
}
int Connection::read(int *out_percent)
{
int rc = 0;
char buff[200];
StaticJsonBuffer<200> buffer;
if (!bt.connected()) {
return -1;
}
rc = bt.readBytesUntil('\n', buff, sizeof(buff));
if (rc <= 0) {
return -2;
}
/* Set last char to NULL */
buff[rc] = '\0';
JsonObject& object = buffer.parseObject(buff);
if (!object.success()) {
return -3;
}
if (object["id"] != id) {
/* The ID doesn't match... We should ignore this message */
return -4;
}
*out_percent = object["throttle"];
return rc;
}
|
Fix static assertion of exception safety of move assignment | /*
* This file is part of Peli - universal JSON interaction library
* Copyright (C) 2014 Alexey Chernov <4ernov@gmail.com>
*
* Peli is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see <http://www.gnu.org/licenses/>.
*
*/
#include <cassert>
#include "peli/json/value.h"
using namespace std;
using namespace peli;
int main(int, char**)
{
json::value v1(json::make_value<json::object>());
json::object& obj1(v1);
obj1["test"] = json::value(52);
json::value v2;
static_assert(noexcept(json::value() = std::move(v2)), "Move assignment isn't noexcept");
v2 = std::move(v1);
json::object& obj2(v2);
obj2["tost"] = json::value(false);
return 0;
}
| /*
* This file is part of Peli - universal JSON interaction library
* Copyright (C) 2014 Alexey Chernov <4ernov@gmail.com>
*
* Peli is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see <http://www.gnu.org/licenses/>.
*
*/
#include <cassert>
#include "peli/json/value.h"
using namespace std;
using namespace peli;
int main(int, char**)
{
json::value v1(json::make_value<json::object>());
json::object& obj1(v1);
obj1["test"] = json::value(52);
json::value v2;
static_assert(noexcept(declval<json::value>().operator=(std::move(v2))), "Move assignment isn't noexcept");
v2 = std::move(v1);
json::object& obj2(v2);
obj2["tost"] = json::value(false);
return 0;
}
|
Fix flashing in WebContents we create | #include "browser/inspectable_web_contents.h"
#include "browser/inspectable_web_contents_impl.h"
namespace brightray {
InspectableWebContents* InspectableWebContents::Create(const content::WebContents::CreateParams& create_params) {
return Create(content::WebContents::Create(create_params));
}
InspectableWebContents* InspectableWebContents::Create(content::WebContents* web_contents) {
return new InspectableWebContentsImpl(web_contents);
}
}
| #include "browser/inspectable_web_contents.h"
#include "browser/inspectable_web_contents_impl.h"
#include "content/public/browser/web_contents_view.h"
namespace brightray {
InspectableWebContents* InspectableWebContents::Create(const content::WebContents::CreateParams& create_params) {
auto contents = content::WebContents::Create(create_params);
#if defined(OS_MACOSX)
// Work around http://crbug.com/279472.
contents->GetView()->SetAllowOverlappingViews(true);
#endif
return Create(contents);
}
InspectableWebContents* InspectableWebContents::Create(content::WebContents* web_contents) {
return new InspectableWebContentsImpl(web_contents);
}
}
|
Add orbfile write code to checkpoint file writing | /*
* Copyright 2009-2018 The VOTCA Development Team (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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.
*
*/
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE test_hdf5
#include <boost/test/unit_test.hpp>
#include <votca/xtp/checkpoint.h>
BOOST_AUTO_TEST_SUITE(test_hdf5)
BOOST_AUTO_TEST_CASE(constructor_test) {
votca::xtp::CheckpointFile cpf("xtp_testing.hdf5"); }
BOOST_AUTO_TEST_SUITE_END()
| /*
* Copyright 2009-2018 The VOTCA Development Team (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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.
*
*/
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE test_hdf5
#include <boost/test/unit_test.hpp>
#include <votca/xtp/checkpoint.h>
BOOST_AUTO_TEST_SUITE(test_hdf5)
BOOST_AUTO_TEST_CASE(checkpoint_file_test) {
votca::xtp::CheckpointFile cpf("xtp_testing.hdf5");
// Write orbitals
votca::xtp::Orbitals orbWrite;
orbWrite.setBasisSetSize(17);
orbWrite.setNumberOfLevels(4,13);
Eigen::VectorXd moeTest = Eigen::VectorXd::Zero(17);
Eigen::MatrixXd mocTest = Eigen::MatrixXd::Zero(17,17);
orbWrite.MOEnergies()=moeTest;
orbWrite.MOCoefficients()=mocTest;
cpf.WriteOrbitals(orbWrite, "Test Orb");
// Read Orbitals
votca::xtp::Orbitals orbRead;
}
BOOST_AUTO_TEST_SUITE_END()
|
Trim the fat off SkPMFloat bench. | #include "Benchmark.h"
#include "SkPMFloat.h"
#include "SkRandom.h"
struct PMFloatBench : public Benchmark {
explicit PMFloatBench(bool clamp) : fClamp(clamp) {}
const char* onGetName() SK_OVERRIDE { return fClamp ? "SkPMFloat_clamp" : "SkPMFloat_get"; }
bool isSuitableFor(Backend backend) SK_OVERRIDE { return backend == kNonRendering_Backend; }
void onDraw(const int loops, SkCanvas* canvas) SK_OVERRIDE {
SkRandom rand;
for (int i = 0; i < loops; i++) {
SkPMColor c = SkPreMultiplyColor(rand.nextU());
SkPMFloat pmf;
pmf.set(c);
SkPMColor back = fClamp ? pmf.clamped() : pmf.get();
if (c != back) { SkFAIL("no joy"); } // This conditional makes this not compile away.
}
}
bool fClamp;
};
DEF_BENCH(return new PMFloatBench( true);)
DEF_BENCH(return new PMFloatBench(false);)
| #include "Benchmark.h"
#include "SkPMFloat.h"
// Used to prevent the compiler from optimizing away the whole loop.
volatile uint32_t blackhole = 0;
// Not a great random number generator, but it's very fast.
// The code we're measuring is quite fast, so low overhead is essential.
static uint32_t lcg_rand(uint32_t* seed) {
*seed *= 1664525;
*seed += 1013904223;
return *seed;
}
struct PMFloatBench : public Benchmark {
explicit PMFloatBench(bool clamp) : fClamp(clamp) {}
const char* onGetName() SK_OVERRIDE { return fClamp ? "SkPMFloat_clamp" : "SkPMFloat_get"; }
bool isSuitableFor(Backend backend) SK_OVERRIDE { return backend == kNonRendering_Backend; }
void onDraw(const int loops, SkCanvas* canvas) SK_OVERRIDE {
// Unlike blackhole, junk can and probably will be a register.
uint32_t junk = 0;
uint32_t seed = 0;
for (int i = 0; i < loops; i++) {
#ifdef SK_DEBUG
// Our SkASSERTs will remind us that it's technically required that we premultiply.
SkPMColor c = SkPreMultiplyColor(lcg_rand(&seed));
#else
// But it's a lot faster not to, and this code won't really mind the non-PM colors.
SkPMColor c = lcg_rand(&seed);
#endif
SkPMFloat pmf;
pmf.set(c);
SkPMColor back = fClamp ? pmf.clamped() : pmf.get();
junk ^= back;
}
blackhole ^= junk;
}
bool fClamp;
};
DEF_BENCH(return new PMFloatBench( true);)
DEF_BENCH(return new PMFloatBench(false);)
|
Make this test check a few more cases which didn't work correctly before r110526. | // RUN: %clang_cc1 -fsyntax-only -verify %s
// PR7800
class NoDestroy { ~NoDestroy(); }; // expected-note {{declared private here}}
struct A {
virtual ~A();
};
struct B : public virtual A {
NoDestroy x; // expected-error {{field of type 'NoDestroy' has private destructor}}
};
struct D : public virtual B {
virtual void foo();
~D();
};
void D::foo() { // expected-note {{implicit default destructor for 'B' first required here}}
}
| // RUN: %clang_cc1 -fsyntax-only -verify %s
// PR7800
class NoDestroy { ~NoDestroy(); }; // expected-note 3 {{declared private here}}
struct A {
virtual ~A();
};
struct B : public virtual A {
NoDestroy x; // expected-error {{field of type 'NoDestroy' has private destructor}}
};
struct D : public virtual B {
virtual void foo();
~D();
};
void D::foo() { // expected-note {{implicit default destructor for 'B' first required here}}
}
struct E : public virtual A {
NoDestroy x; // expected-error {{field of type 'NoDestroy' has private destructor}}
};
struct F : public E { // expected-note {{implicit default destructor for 'E' first required here}}
};
struct G : public virtual F {
virtual void foo();
~G();
};
void G::foo() { // expected-note {{implicit default destructor for 'F' first required here}}
}
struct H : public virtual A {
NoDestroy x; // expected-error {{field of type 'NoDestroy' has private destructor}}
};
struct I : public virtual H {
~I();
};
struct J : public I {
virtual void foo();
~J();
};
void J::foo() { // expected-note {{implicit default destructor for 'H' first required here}}
}
|
Fix potential issue with Diagnostics_Debugger::Break | //
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
#include "CorLib.h"
HRESULT Library_corlib_native_System_Diagnostics_Debugger::get_IsAttached___STATIC__BOOLEAN( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)
stack.SetResult_Boolean( CLR_EE_DBG_IS( SourceLevelDebugging ));
#else
stack.SetResult_Boolean( false );
#endif
NANOCLR_NOCLEANUP_NOLABEL();
}
HRESULT Library_corlib_native_System_Diagnostics_Debugger::Break___STATIC__VOID( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)
if(stack.m_customState == 0)
{
stack.m_customState++;
g_CLR_RT_ExecutionEngine.Breakpoint_StackFrame_Break( &stack );
hr = CLR_E_RESCHEDULE; NANOCLR_LEAVE();
}
NANOCLR_NOCLEANUP();
#else
NANOCLR_NOCLEANUP_NOLABEL();
#endif
}
| //
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
#include "CorLib.h"
HRESULT Library_corlib_native_System_Diagnostics_Debugger::get_IsAttached___STATIC__BOOLEAN( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)
stack.SetResult_Boolean( CLR_EE_DBG_IS( SourceLevelDebugging ));
#else
stack.SetResult_Boolean( false );
#endif
NANOCLR_NOCLEANUP_NOLABEL();
}
HRESULT Library_corlib_native_System_Diagnostics_Debugger::Break___STATIC__VOID( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)
if(stack.m_customState == 0)
{
stack.m_customState++;
g_CLR_RT_ExecutionEngine.Breakpoint_StackFrame_Break( &stack );
hr = CLR_E_RESCHEDULE; NANOCLR_LEAVE();
}
NANOCLR_NOCLEANUP();
#else
(void)stack;
NANOCLR_NOCLEANUP_NOLABEL();
#endif
}
|
Throw exception on fatal error | #include <polar/core/log.h>
#include <polar/fs/local.h>
#include <polar/util/sdl.h>
namespace polar::core {
std::shared_ptr<logger> logger::instance;
void logger::msgbox(std::string title, std::string msg) {
#if defined(_WIN32)
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, title.data(), msg.data(), NULL);
#endif
std::cerr << title << ": " << msg << std::endl;
}
logger::logger(priority_t priority)
: file((fs::local::app_dir() / "log.txt").str(), std::ios::out | std::ios::binary | std::ios::trunc),
priority(priority) {}
}
| #include <polar/core/log.h>
#include <polar/fs/local.h>
#include <polar/util/sdl.h>
namespace polar::core {
std::shared_ptr<logger> logger::instance;
void logger::msgbox(std::string title, std::string msg) {
#if defined(_WIN32)
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, title.data(), msg.data(), NULL);
#endif
std::cerr << title << ": " << msg << std::endl;
throw std::runtime_error("fatal error");
}
logger::logger(priority_t priority)
: file((fs::local::app_dir() / "log.txt").str(), std::ios::out | std::ios::binary | std::ios::trunc),
priority(priority) {}
}
|
Fix Windows build after directory library changes. | // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "bin/directory.h"
bool Directory::Open(const char* path, intptr_t* dir) {
UNIMPLEMENTED();
return false;
}
bool Directory::Close(intptr_t dir) {
UNIMPLEMENTED();
return false;
}
void Directory::List(intptr_t dir,
bool recursive,
Dart_Port dir_handler,
Dart_Port file_handler,
Dart_Port done_handler,
Dart_Port dir_error_handler) {
UNIMPLEMENTED();
}
| // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "bin/directory.h"
bool Directory::Open(const char* path, intptr_t* dir) {
UNIMPLEMENTED();
return false;
}
bool Directory::Close(intptr_t dir) {
UNIMPLEMENTED();
return false;
}
void Directory::List(const char* path,
intptr_t dir,
bool recursive,
Dart_Port dir_handler,
Dart_Port file_handler,
Dart_Port done_handler,
Dart_Port dir_error_handler) {
UNIMPLEMENTED();
}
|
Add Problem's command-line options tests | #include "gtest/gtest.h"
#include "tcframe_test_commons.cpp"
#include "tcframe/problem.hpp"
using tcframe::BaseProblem;
class MyProblem : public BaseProblem {
protected:
void Config() {
setSlug("foo");
setTimeLimit(2);
setMemoryLimit(256);
}
void InputFormat() { }
void OutputFormat() { }
};
TEST(ProblemTest, DefaultOptions) {
BaseProblem* problem = new DefaultProblem();
EXPECT_EQ("problem", problem->getSlug());
EXPECT_EQ(0, problem->getTimeLimit());
EXPECT_EQ(0, problem->getMemoryLimit());
}
TEST(ProblemTest, MyOptions) {
BaseProblem* problem = new MyProblem();
problem->applyProblemConfiguration();
EXPECT_EQ("foo", problem->getSlug());
EXPECT_EQ(2, problem->getTimeLimit());
EXPECT_EQ(256, problem->getMemoryLimit());
}
| #include "gtest/gtest.h"
#include "tcframe_test_commons.cpp"
#include "tcframe/problem.hpp"
using tcframe::BaseProblem;
class MyProblem : public BaseProblem {
protected:
void Config() {
setSlug("foo");
setTimeLimit(2);
setMemoryLimit(256);
}
void InputFormat() { }
void OutputFormat() { }
};
TEST(ProblemTest, DefaultOptions) {
BaseProblem* problem = new DefaultProblem();
EXPECT_EQ("problem", problem->getSlug());
EXPECT_EQ(0, problem->getTimeLimit());
EXPECT_EQ(0, problem->getMemoryLimit());
}
TEST(ProblemTest, MyOptions) {
BaseProblem* problem = new MyProblem();
problem->applyProblemConfiguration();
EXPECT_EQ("foo", problem->getSlug());
EXPECT_EQ(2, problem->getTimeLimit());
EXPECT_EQ(256, problem->getMemoryLimit());
}
TEST(ProblemTest, CommandLineOptions) {
char* argv[] = {(char*) "<runner>", (char*)"--slug=bar", (char*)"--time-limit=3", (char*)"--memory-limit=64"};
BaseProblem* problem = new MyProblem();
problem->applyProblemConfiguration();
problem->applyProblemCommandLineOptions(4, argv);
EXPECT_EQ("bar", problem->getSlug());
EXPECT_EQ(3, problem->getTimeLimit());
EXPECT_EQ(64, problem->getMemoryLimit());
}
TEST(ProblemTest, CommandLineOptionsWithNos) {
char* argv[] = {(char*) "<runner>", (char*)"--no-time-limit", (char*)"--no-memory-limit"};
BaseProblem* problem = new MyProblem();
problem->applyProblemConfiguration();
problem->applyProblemCommandLineOptions(3, argv);
EXPECT_EQ("foo", problem->getSlug());
EXPECT_EQ(0, problem->getTimeLimit());
EXPECT_EQ(0, problem->getMemoryLimit());
}
|
Add the iteration function for the fractals | #include <iostream>
int main() {
std::cout << "Fractalogy!\n";
return 0;
}
| #include <iostream>
#include <complex>
using std::cout;
using std::complex;
using std::exp;
using std::norm;
/// returns -1 on failing to escape
int iteration(complex<double> c, int limit = 1000) {
int i = 0;
double n;
complex<double> z(0, 0);
while ((n = norm(z)) < 4 && i < limit) {
z = exp(z) - c;
++i;
}
if (n < 4)
return -1;
else
return i;
}
int main() {
std::cout << "Fractalogy!\n";
double lower = -2, upper = 2;
int width = 100, height = 100;
for (int i = 0; i <= width; ++i) {
for (int j = 0; j <= height; ++j) {
complex<double> t;
t = complex<double>(lower + (upper - lower) * i / width, lower + (upper - lower) * j / height);
cout << iteration(t) << " ";
}
cout << std::endl;
}
return 0;
}
|
Make sure that we assume pixels are in block stream order when accessing. | #include "ImageWriter.h"
uint32 ImageWriter::GetChannelForPixel(uint32 x, uint32 y, uint32 ch) {
uint32 bytesPerRow = GetWidth() * 4;
uint32 byteLocation = y * bytesPerRow + x*4 + ch;
return m_PixelData[byteLocation];
}
| #include "ImageWriter.h"
uint32 ImageWriter::GetChannelForPixel(uint32 x, uint32 y, uint32 ch) {
// Assume pixels are in block stream order, hence we would need to first find
// the block that contains pixel (x, y) and then find the byte location for it.
const uint32 blocksPerRow = GetWidth() / 4;
const uint32 blockIdxX = x / 4;
const uint32 blockIdxY = y / 4;
const uint32 blockIdx = blockIdxY * blocksPerRow + blockIdxX;
// Now we find the offset in the block
const uint32 blockOffsetX = x % 4;
const uint32 blockOffsetY = y % 4;
const uint32 pixelOffset = blockOffsetY * 4 + blockOffsetX;
// There are 16 pixels per block and bytes per pixel...
uint32 dataOffset = blockIdx * 4 * 16;
dataOffset += 4 * pixelOffset;
dataOffset += ch;
return m_PixelData[dataOffset];
}
|
Use 'nextStep' instead of 'step' and call ProcessNextStep() | // This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
#include <Rosetta/Games/Game.hpp>
#include <Rosetta/Models/Player.hpp>
#include <Rosetta/Tasks/PlayerTasks/EndTurnTask.hpp>
namespace RosettaStone::PlayerTasks
{
TaskID EndTurnTask::GetTaskID() const
{
return TaskID::END_TURN;
}
TaskStatus EndTurnTask::Impl(Player& player)
{
player.GetGame()->step = Step::MAIN_END;
player.GetGame()->MainEnd();
return TaskStatus::COMPLETE;
}
} // namespace RosettaStone::PlayerTasks
| // This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
#include <Rosetta/Games/Game.hpp>
#include <Rosetta/Games/GameManager.hpp>
#include <Rosetta/Models/Player.hpp>
#include <Rosetta/Tasks/PlayerTasks/EndTurnTask.hpp>
namespace RosettaStone::PlayerTasks
{
TaskID EndTurnTask::GetTaskID() const
{
return TaskID::END_TURN;
}
TaskStatus EndTurnTask::Impl(Player& player)
{
auto game = player.GetGame();
game->nextStep = Step::MAIN_END;
GameManager::ProcessNextStep(*game, game->nextStep);
return TaskStatus::COMPLETE;
}
} // namespace RosettaStone::PlayerTasks
|
Remove no longer necessary assimp import flag | /*
* This file is part of ATLAS. It is subject to the license terms in
* the LICENSE file found in the top-level directory of this distribution.
* (Also avialable at http://www.apache.org/licenses/LICENSE-2.0.txt)
* You may not use this file except in compliance with the License.
*/
#include <iostream>
#include <assimp/postprocess.h>
#include <assimp/scene.h>
#include "AssimpImporter.hpp"
namespace AssimpWorker {
AssimpImporter::AssimpImporter() :
importer()
{
return;
}
AssimpImporter::~AssimpImporter(){
return;
}
const aiScene* AssimpImporter::importSceneFromFile(std::string fileName, Log& log){
importer.SetPropertyBool(AI_CONFIG_PP_FD_REMOVE, true); //remove degenerate polys
importer.SetPropertyBool(AI_CONFIG_IMPORT_NO_SKELETON_MESHES, true); //do not import skeletons
importer.SetPropertyBool(AI_CONFIG_IMPORT_COLLADA_IGNORE_UP_DIRECTION, true);
importer.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_LINE | aiPrimitiveType_POINT); //Drop all primitives that aren't triangles
const aiScene* scene = importer.ReadFile(fileName, aiProcessPreset_TargetRealtime_Quality);
if (!scene) {
log.error("Scene not imported: "+fileName);
}
log.error(importer.GetErrorString());
return scene;
}
}
| /*
* This file is part of ATLAS. It is subject to the license terms in
* the LICENSE file found in the top-level directory of this distribution.
* (Also avialable at http://www.apache.org/licenses/LICENSE-2.0.txt)
* You may not use this file except in compliance with the License.
*/
#include <iostream>
#include <assimp/postprocess.h>
#include <assimp/scene.h>
#include "AssimpImporter.hpp"
namespace AssimpWorker {
AssimpImporter::AssimpImporter() :
importer()
{
return;
}
AssimpImporter::~AssimpImporter(){
return;
}
const aiScene* AssimpImporter::importSceneFromFile(std::string fileName, Log& log){
importer.SetPropertyBool(AI_CONFIG_PP_FD_REMOVE, true); //remove degenerate polys
importer.SetPropertyBool(AI_CONFIG_IMPORT_NO_SKELETON_MESHES, true); //do not import skeletons
importer.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_LINE | aiPrimitiveType_POINT); //Drop all primitives that aren't triangles
const aiScene* scene = importer.ReadFile(fileName, aiProcessPreset_TargetRealtime_Quality);
if (!scene) {
log.error("Scene not imported: "+fileName);
}
log.error(importer.GetErrorString());
return scene;
}
}
|
Set auto card in show(0) as const. | /*
* CardDeck.cpp
*
* Created on: 2014年10月25日
* Author: nemo
*/
#include "CardDeck.h"
#include <iostream>
CardDeck::CardDeck()
{
LOG_TRACE("Construct CardDeck.")
}
CardDeck::~CardDeck()
{
// TODO Auto-generated destructor stub
}
/// Insert card into card deck.
/**
* @brief Insert card into card deck.
*
* @param card Input card pointer.
*/
void CardDeck::push_back(Card *card)
{
_card.push_back(card);
}
/// Show all card in card deck.
void CardDeck::show()
{
for(auto card :_card)
{
card->show();
}
}
| /*
* CardDeck.cpp
*
* Created on: 2014年10月25日
* Author: nemo
*/
#include "CardDeck.h"
#include <iostream>
CardDeck::CardDeck()
{
LOG_TRACE("Construct CardDeck.")
}
CardDeck::~CardDeck()
{
// TODO Auto-generated destructor stub
}
/// Insert card into card deck.
/**
* @brief Insert card into card deck.
*
* @param card Input card pointer.
*/
void CardDeck::push_back(Card *card)
{
_card.push_back(card);
}
/// Show all card in card deck.
void CardDeck::show()
{
for(const auto card :_card)
{
card->show();
}
}
|
Resolve the valgrind memory leak problem | /* This file is part of VoltDB.
* Copyright (C) 2008-2012 VoltDB Inc.
*
* VoltDB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* VoltDB is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <sstream>
#include "tablecountnode.h"
#include "common/common.h"
#include "expressions/abstractexpression.h"
#include "storage/table.h"
namespace voltdb {
TableCountPlanNode::~TableCountPlanNode() {
}
std::string TableCountPlanNode::debugInfo(const std::string &spacer) const {
std::ostringstream buffer;
buffer << this->AbstractScanPlanNode::debugInfo(spacer);
assert(m_predicate == NULL);
buffer << spacer << "TABLE COUNT Expression: <NULL>";
return (buffer.str());
}
}
| /* This file is part of VoltDB.
* Copyright (C) 2008-2012 VoltDB Inc.
*
* VoltDB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* VoltDB is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <sstream>
#include "tablecountnode.h"
#include "common/common.h"
#include "expressions/abstractexpression.h"
#include "storage/table.h"
namespace voltdb {
TableCountPlanNode::~TableCountPlanNode() {
delete getOutputTable();
setOutputTable(NULL);
}
std::string TableCountPlanNode::debugInfo(const std::string &spacer) const {
std::ostringstream buffer;
buffer << this->AbstractScanPlanNode::debugInfo(spacer);
assert(m_predicate == NULL);
buffer << spacer << "TABLE COUNT Expression: <NULL>";
return (buffer.str());
}
}
|
Revert 112083 - Try a different library for Crc32. | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "courgette/crc.h"
#ifdef OS_CHROMEOS
# include "zlib.h"
#else
extern "C" {
# include "third_party/lzma_sdk/7zCrc.h"
}
#endif
#include "base/basictypes.h"
namespace courgette {
uint32 CalculateCrc(const uint8* buffer, size_t size) {
uint32 crc;
#ifdef OS_CHROMEOS
// Calculate Crc by calling CRC method in zlib
crc = crc32(0, buffer, size);
#else
// Calculate Crc by calling CRC method in LZMA SDK
CrcGenerateTable();
crc = CrcCalc(buffer, size);
#endif
return ~crc;
}
} // namespace
| // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Calculate Crc by calling CRC method in LZMA SDK
#include "courgette/crc.h"
extern "C" {
#include "third_party/lzma_sdk/7zCrc.h"
}
namespace courgette {
uint32 CalculateCrc(const uint8* buffer, size_t size) {
CrcGenerateTable();
uint32 crc = 0xffffffffL;
crc = ~CrcCalc(buffer, size);
return crc;
}
} // namespace
|
Use `*.h` headers rather than `c*` | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <ncurses.h>
#include <csignal>
#include <cstdlib>
#include "signals.hh"
extern "C" {
static void myexit(int i) {
endwin();
SIG_DFL(i);
}
}
namespace vick {
void setup_signal_handling() {
signal(SIGABRT, myexit);
signal(SIGFPE, myexit);
signal(SIGILL, myexit);
signal(SIGINT, myexit);
signal(SIGSEGV, myexit);
signal(SIGTERM, myexit);
}
}
| /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <ncurses.h>
#include <signal.h>
#include <stdlib.h>
#include "signals.hh"
extern "C" {
static void myexit(int i) {
endwin();
SIG_DFL(i);
}
}
namespace vick {
void setup_signal_handling() {
signal(SIGABRT, myexit);
signal(SIGFPE, myexit);
signal(SIGILL, myexit);
signal(SIGINT, myexit);
signal(SIGSEGV, myexit);
signal(SIGTERM, myexit);
}
}
|
Enable using PrintException even when no MGSystem is present. | #include "commands.h"
#include "sim/except.h"
#include <iostream>
using namespace std;
void PrintException(Simulator::MGSystem *sys, ostream& out, const exception& e)
{
out << endl << e.what() << endl;
auto se = dynamic_cast<const Simulator::SimulationException*>(&e);
if (se != NULL)
{
// SimulationExceptions hold more information, print it
for (auto& p : se->GetDetails())
out << p << endl;
auto te = dynamic_cast<const Simulator::ProgramTerminationException*>(se);
if (te == NULL && se->GetPC() != 0)
{
// We avoid printing the backtrace when receiving an exception
// for normal program termination.
assert(sys != NULL);
sys->Disassemble(se->GetPC());
}
}
}
| #include "commands.h"
#include "sim/except.h"
#include <iostream>
using namespace std;
void PrintException(Simulator::MGSystem *sys, ostream& out, const exception& e)
{
out << endl << e.what() << endl;
auto se = dynamic_cast<const Simulator::SimulationException*>(&e);
if (se != NULL)
{
// SimulationExceptions hold more information, print it
for (auto& p : se->GetDetails())
out << p << endl;
auto te = dynamic_cast<const Simulator::ProgramTerminationException*>(se);
if (te == NULL && se->GetPC() != 0)
{
// We avoid printing the backtrace when receiving an exception
// for normal program termination.
if (sys != NULL)
// Only disassemble if there is a system to do so.
sys->Disassemble(se->GetPC());
}
}
}
|
Add basic retriggering to input | /*############################################################################################
Garden System
Wireless controller for watering electropumps
Author: Daniele Colanardi
License: BSD, see LICENSE file
############################################################################################*/
#include <Wire.h>
#include "input.h"
LightMPR121 touch;
void init_buttons() {
Wire.begin();
touch.begin();
}
bool update_buttons() {
touch.update();
}
bool is_pressed(uint8_t i) { return touch.touched(i); }
bool released(uint8_t i) { return true; }
| /*############################################################################################
Garden System
Wireless controller for watering electropumps
Author: Daniele Colanardi
License: BSD, see LICENSE file
############################################################################################*/
#include <Wire.h>
#include "input.h"
LightMPR121 touch;
int last_status;
long repeat_timer;
bool changed;
void init_buttons() {
Wire.begin();
touch.begin();
}
bool update_buttons() {
int new_status = touch.update();
changed = new_status != last_status;
last_status = new_status;
if (changed || millis() - repeat_timer > 150) {
repeat_timer = millis();
if(!changed) changed = true;
}
}
bool is_pressed(uint8_t i) { return touch.touched(i) && changed; }
bool released(uint8_t i) { return true; }
|
Use a shared ptr and uncomment unit tests | //
// Created by Sam on 11/18/2017.
//
#include "../../../build/catch-src/include/catch.hpp"
#include "../../../include/Game/Python/Factory.h"
TEST_CASE("Create factory")
{
auto* factory = new Factory();
delete factory;
//
// SECTION("Verify creation")
// {
// REQUIRE_FALSE(factory == nullptr);
// }
//
// SECTION("Verify minimum python version")
// {
// std::string minimumVersion = "2.7";
// bool versionCheck = Version(minimumVersion) < factory->version;
// REQUIRE(versionCheck);
// }
//
// SECTION("Verify expected python version")
// {
// std::string expectedVersion = "3.6.3";
// bool versionCheck = Version(expectedVersion) == factory->version;
//
// if (!versionCheck)
// {
// FAIL_CHECK("Unexpected python version, expected " + expectedVersion +
// " but factory's interpreter is running " + factory->version.toString());
// }
// }
} | //
// Created by Sam on 11/18/2017.
//
#include "../../../build/catch-src/include/catch.hpp"
#include "../../../include/Game/Python/Factory.h"
TEST_CASE("Create factory")
{
std::shared_ptr<Factory> factory = std::make_shared<Factory>();
SECTION("Verify creation")
{
REQUIRE_FALSE(factory == nullptr);
}
SECTION("Verify minimum python version")
{
std::string minimumVersion = "2.7";
bool versionCheck = Version(minimumVersion) < factory->version;
REQUIRE(versionCheck);
}
SECTION("Verify expected python version")
{
std::string expectedVersion = "3.6.3";
bool versionCheck = Version(expectedVersion) == factory->version;
if (!versionCheck)
{
FAIL_CHECK("Unexpected python version, expected " + expectedVersion +
" but factory's interpreter is running " + factory->version.toString());
}
}
} |
Update the halfspaces test to also test `long` input/output | #include "zonotope_halfspaces.hpp"
#include <gmpxx.h>
#include <iostream>
int main() {
using namespace std;
typedef mpz_class NT;
int n_tests;
cin >> n_tests;
for ( int t = 0; t < n_tests; ++t ) {
int n, d;
cin >> n >> d;
vector<vector<NT> > generators ( n, vector<NT> ( d ) );
for ( int i = 0; i < n; ++i ) {
for ( int j = 0; j < d; ++j ) {
cin >> generators[i][j];
}
}
set<Hyperplane<NT> > halfspaces = zonotope_halfspaces<NT> (generators);
cout << "n=" << n << " "
<< "d=" << d << " "
<< "ieqs=" << halfspaces.size() << "\n";
}
return 0;
}
| #include "zonotope_halfspaces.hpp"
#include <gmpxx.h>
#include <iostream>
int main() {
using namespace std;
int n_tests;
cin >> n_tests;
for ( int t = 0; t < n_tests; ++t ) {
int n, d;
cin >> n >> d;
vector<vector<mpz_class> >
generators_mpz ( n, vector<mpz_class> ( d ) );
vector<vector<long> >
generators_long ( n, vector<long> ( d ) );
for ( int k = 0; k < n; ++k ) {
for ( int i = 0; i < d; ++i ) {
cin >> generators_long[k][i];
generators_mpz[k][i] = generators_long[k][i];
}
}
set<Hyperplane<mpz_class> > halfspaces_mpz;
zonotope_halfspaces<mpz_class> (generators_mpz, halfspaces_mpz);
set<Hyperplane<long> > halfspaces_long;
zonotope_halfspaces<long> (generators_long, halfspaces_long);
cout << "n=" << n << " "
<< "d=" << d << " "
<< "ieqs=" << halfspaces_mpz.size() << " "
<< "ieqs_long=" << halfspaces_long.size() << "\n";
}
return 0;
}
|
Add resource to client settings in hello example | #include <iostream>
#include <talk/base/cryptstring.h>
#include <talk/base/logging.h>
#include <talk/xmpp/xmppclientsettings.h>
#include "xmppthread.h"
int main(int argc, char* argv[]) {
talk_base::LogMessage::LogToDebug(talk_base::LS_SENSITIVE);
talk_base::InsecureCryptStringImpl ipass;
ipass.password() = "test";
talk_base::CryptString password = talk_base::CryptString(ipass);
// Start xmpp on a different thread
XmppThread thread;
thread.Start();
// Create client settings
buzz::XmppClientSettings xcs;
xcs.set_user("test");
xcs.set_pass(password);
xcs.set_host("example.org");
xcs.set_use_tls(true);
xcs.set_server(talk_base::SocketAddress("example.org", 5222));
thread.Login(xcs);
// Use main thread for console input
std::string line;
while (std::getline(std::cin, line)) {
if (line == "quit")
break;
}
return 0;
}
| #include <iostream>
#include <talk/base/cryptstring.h>
#include <talk/base/logging.h>
#include <talk/xmpp/xmppclientsettings.h>
#include "xmppthread.h"
int main(int argc, char* argv[]) {
talk_base::LogMessage::LogToDebug(talk_base::LS_SENSITIVE);
talk_base::InsecureCryptStringImpl ipass;
ipass.password() = "test";
talk_base::CryptString password = talk_base::CryptString(ipass);
// Start xmpp on a different thread
XmppThread thread;
thread.Start();
// Create client settings
buzz::XmppClientSettings xcs;
xcs.set_user("test");
xcs.set_pass(password);
xcs.set_host("example.org");
xcs.set_resource("resource");
xcs.set_use_tls(true);
xcs.set_server(talk_base::SocketAddress("example.org", 5222));
thread.Login(xcs);
// Use main thread for console input
std::string line;
while (std::getline(std::cin, line)) {
if (line == "quit")
break;
}
return 0;
}
|
Disable ExtensionApiTest.JavaScriptURLPermissions, it flakily hits an assertion. | // 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/extensions/extension_apitest.h"
#include "net/base/mock_host_resolver.h"
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, JavaScriptURLPermissions) {
host_resolver()->AddRule("a.com", "127.0.0.1");
host_resolver()->AddRule("b.com", "127.0.0.1");
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionTest("tabs/javascript_url_permissions")) << message_;
}
| // 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/extensions/extension_apitest.h"
#include "net/base/mock_host_resolver.h"
// Disabled, http://crbug.com/63589.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_JavaScriptURLPermissions) {
host_resolver()->AddRule("a.com", "127.0.0.1");
host_resolver()->AddRule("b.com", "127.0.0.1");
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionTest("tabs/javascript_url_permissions")) << message_;
}
|
Disable ExtensionApiTest.JavaScriptURLPermissions, it flakily hits an assertion. | // 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/extensions/extension_apitest.h"
#include "net/base/mock_host_resolver.h"
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, JavaScriptURLPermissions) {
host_resolver()->AddRule("a.com", "127.0.0.1");
host_resolver()->AddRule("b.com", "127.0.0.1");
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionTest("tabs/javascript_url_permissions")) << message_;
}
| // 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/extensions/extension_apitest.h"
#include "net/base/mock_host_resolver.h"
// Disabled, http://crbug.com/63589.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_JavaScriptURLPermissions) {
host_resolver()->AddRule("a.com", "127.0.0.1");
host_resolver()->AddRule("b.com", "127.0.0.1");
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionTest("tabs/javascript_url_permissions")) << message_;
}
|
Make insert instruction return something | #include "Table.h"
// int insertInstruction(int state, int symbol, int newState, int newSymbol,
// char instruction);
// void removeInstruction(int id);
// machineAction_t getAction(int state, int symbol);
// TODO: implement Table methods
int Table::insertInstruction(int state, int symbol, int newState, int newSymbol,
char instruction)
{
machineState_t mStat;
mStat.state = state;
mStat.symbol = symbol;
machineAction_t mAct;
mAct.newState = newState;
mAct.newSymbol = newSymbol;
mAct.instruction = instruction;
machineInstruction_t mInst;
mInst.state = mStat;
mInst.action = mAct;
mInst.id = 0; // TODO: figure out something to do with ID's or remove them
this.table.push_back(mInst);
}
| #include "Table.h"
// int insertInstruction(int state, int symbol, int newState, int newSymbol,
// char instruction);
// void removeInstruction(int id);
// machineAction_t getAction(int state, int symbol);
// TODO: implement Table methods
int Table::insertInstruction(int state, int symbol, int newState, int newSymbol,
char instruction)
{
machineState_t mStat;
mStat.state = state;
mStat.symbol = symbol;
machineAction_t mAct;
mAct.newState = newState;
mAct.newSymbol = newSymbol;
mAct.instruction = instruction;
machineInstruction_t mInst;
mInst.state = mStat;
mInst.action = mAct;
mInst.id = 0; // TODO: figure out something to do with ID's or remove them
this.table.push_back(mInst);
return 0; //TODO: Figure out something to do with id's
}
|
Add include to support SAMD core | #include <avr/pgmspace.h>
#include <stdlib.h>
char *to_print;
char *pgmStrToRAM(PROGMEM char *theString) {
free(to_print);
to_print=(char *) malloc(strlen_P(theString) + 1);
strcpy_P(to_print, theString);
return (to_print);
} | #include <avr/pgmspace.h>
#include <stdlib.h>
#include <string.h>
char *to_print;
char *pgmStrToRAM(PROGMEM char *theString) {
free(to_print);
to_print=(char *) malloc(strlen_P(theString) + 1);
strcpy_P(to_print, theString);
return (to_print);
} |
Initialize target_message_loop_ in the constructor. | // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/icon_loader.h"
#include "base/message_loop.h"
#include "base/mime_util.h"
#include "base/thread.h"
#include "chrome/browser/browser_process.h"
#include "third_party/skia/include/core/SkBitmap.h"
IconLoader::IconLoader(const IconGroupID& group, IconSize size,
Delegate* delegate)
: group_(group),
icon_size_(size),
bitmap_(NULL),
delegate_(delegate) {
}
IconLoader::~IconLoader() {
delete bitmap_;
}
void IconLoader::Start() {
target_message_loop_ = MessageLoop::current();
#if defined(OS_LINUX)
// This call must happen on the UI thread before we can start loading icons.
mime_util::DetectGtkTheme();
#endif
g_browser_process->file_thread()->message_loop()->PostTask(FROM_HERE,
NewRunnableMethod(this, &IconLoader::ReadIcon));
}
void IconLoader::NotifyDelegate() {
if (delegate_->OnBitmapLoaded(this, bitmap_))
bitmap_ = NULL;
}
| // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/icon_loader.h"
#include "base/message_loop.h"
#include "base/mime_util.h"
#include "base/thread.h"
#include "chrome/browser/browser_process.h"
#include "third_party/skia/include/core/SkBitmap.h"
IconLoader::IconLoader(const IconGroupID& group, IconSize size,
Delegate* delegate)
: target_message_loop_(NULL),
group_(group),
icon_size_(size),
bitmap_(NULL),
delegate_(delegate) {
}
IconLoader::~IconLoader() {
delete bitmap_;
}
void IconLoader::Start() {
target_message_loop_ = MessageLoop::current();
#if defined(OS_LINUX)
// This call must happen on the UI thread before we can start loading icons.
mime_util::DetectGtkTheme();
#endif
g_browser_process->file_thread()->message_loop()->PostTask(FROM_HERE,
NewRunnableMethod(this, &IconLoader::ReadIcon));
}
void IconLoader::NotifyDelegate() {
if (delegate_->OnBitmapLoaded(this, bitmap_))
bitmap_ = NULL;
}
|
Enable Android executables (like skia_launcher) to redirect SkDebugf output to stdout as well as the system logs. |
/*
* Copyright 2006 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkTypes.h"
static const size_t kBufferSize = 256;
#define LOG_TAG "skia"
#include <android/log.h>
void SkDebugf(const char format[], ...) {
va_list args;
va_start(args, format);
__android_log_vprint(ANDROID_LOG_DEBUG, LOG_TAG, format, args);
va_end(args);
}
|
/*
* Copyright 2006 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkTypes.h"
static const size_t kBufferSize = 256;
#define LOG_TAG "skia"
#include <android/log.h>
static bool gSkDebugToStdOut = false;
extern "C" void AndroidSkDebugToStdOut(bool debugToStdOut) {
gSkDebugToStdOut = debugToStdOut;
}
void SkDebugf(const char format[], ...) {
va_list args;
va_start(args, format);
__android_log_vprint(ANDROID_LOG_DEBUG, LOG_TAG, format, args);
// Print debug output to stdout as well. This is useful for command
// line applications (e.g. skia_launcher)
if (gSkDebugToStdOut) {
vprintf(format, args);
}
va_end(args);
}
|
Rename a variable due to using a different service. | #include <3ds.h>
#include <stdio.h>
void shutdown3DS()
{
Handle ptmSysmHandle = 0;
Result result = srvGetServiceHandle(&ptmSysmHandle, "ns:s");
if (result != 0)
return;
// http://3dbrew.org/wiki/NSS:ShutdownAsync
u32 *commandBuffer = getThreadCommandBuffer();
commandBuffer[0] = 0x000E0000;
svcSendSyncRequest(ptmSysmHandle);
svcCloseHandle(ptmSysmHandle);
}
int main(int argc, char **argv) {
hidScanInput();
#ifndef ALWAYS_SHUTDOWN
// If any key is pressed, cancel the shutdown.
if (hidKeysDown() != 0)
goto done;
#endif
shutdown3DS();
done:
// Hack: the 3ds crashes ("An error has occcurred.") for some reason
// without one iteration of the main loop.
aptMainLoop();
return 0;
}
| #include <3ds.h>
#include <stdio.h>
void shutdown3DS()
{
Handle nssHandle = 0;
Result result = srvGetServiceHandle(&nssHandle, "ns:s");
if (result != 0)
return;
// http://3dbrew.org/wiki/NSS:ShutdownAsync
u32 *commandBuffer = getThreadCommandBuffer();
commandBuffer[0] = 0x000E0000;
svcSendSyncRequest(nssHandle);
svcCloseHandle(nssHandle);
}
int main(int argc, char **argv) {
hidScanInput();
#ifndef ALWAYS_SHUTDOWN
// If any key is pressed, cancel the shutdown.
if (hidKeysDown() != 0)
goto done;
#endif
shutdown3DS();
done:
// Hack: the 3ds crashes ("An error has occcurred.") for some reason
// without one iteration of the main loop.
aptMainLoop();
return 0;
}
|
Fix to prevent crashing if file couldn't be opened. | // Copyright 2015 FMAW
#include <iostream>
#include <fstream>
#include "./grid.h"
#include "./gridmap.h"
#include <fat.h>
#include <nds.h>
namespace GridMap{
void loadDefaultGridMap( Grid &g ) { loadGridMap("defaultMap", g); }
void loadGridMap( const char* mapName, Grid &g ){
FILE* test = fopen ("./defaultMap", "r");
int rows, cols, aux;
fscanf( test, "%d %d\n", &rows, &cols );
for( int row = 0; row < rows; row++ ){
for( int col = 0; col < cols; col++ ){
if(col < cols-1) fscanf( test, "%d ", &aux );
else fscanf( test, "%d\n", &aux );
IndexPath path {row, col};
g.cellAtIndexPath(path)->setBackgroundType(
static_cast<CellBackgroundType>(aux)
);
g.cellAtIndexPath(path)->renderBackground();
}
}
fclose(test);
}
}
| // Copyright 2015 FMAW
#include <fat.h>
#include <nds.h>
#include <iostream>
#include <fstream>
#include "./grid.h"
#include "./gridmap.h"
namespace GridMap {
void loadDefaultGridMap(Grid &g) {
loadGridMap("defaultMap", g);
}
void loadGridMap(const char *mapName, Grid &g) {
FILE *test = fopen("./defaultMap", "r");
if (test != NULL) {
int rows, cols, aux;
fscanf(test, "%d %d\n", &rows, &cols);
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
if (col < cols - 1) {
fscanf(test, "%d ", &aux);
} else {
fscanf(test, "%d\n", &aux);
}
IndexPath path {row, col};
g.cellAtIndexPath(path)->setBackgroundType(
static_cast<CellBackgroundType>(aux));
g.cellAtIndexPath(path)->renderBackground();
}
}
fclose(test);
}
}
} // namespace GridMap
|
Add missing GL_ prefixes to previously removed constants | #include <glow/memory.h>
#include <glow/global.h>
#include <glow/Extension.h>
namespace {
GLint getMemoryInformation(GLenum pname)
{
if (!glow::hasExtension("NVX_gpu_memory_info"))
return -1;
return glow::getInteger(pname);
}
}
namespace glow
{
namespace memory
{
GLint total()
{
return getMemoryInformation(GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX);
}
GLint dedicated()
{
return getMemoryInformation(GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX);
}
GLint available()
{
return getMemoryInformation(GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX);
}
GLint evicted()
{
return getMemoryInformation(GPU_MEMORY_INFO_EVICTED_MEMORY_NVX);
}
GLint evictionCount()
{
return getMemoryInformation(GPU_MEMORY_INFO_EVICTION_COUNT_NVX);
}
}
}
| #include <glow/memory.h>
#include <glow/global.h>
#include <glow/Extension.h>
namespace {
GLint getMemoryInformation(GLenum pname)
{
if (!glow::hasExtension("NVX_gpu_memory_info"))
return -1;
return glow::getInteger(pname);
}
}
namespace glow
{
namespace memory
{
GLint total()
{
return getMemoryInformation(GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX);
}
GLint dedicated()
{
return getMemoryInformation(GL_GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX);
}
GLint available()
{
return getMemoryInformation(GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX);
}
GLint evicted()
{
return getMemoryInformation(GL_GPU_MEMORY_INFO_EVICTED_MEMORY_NVX);
}
GLint evictionCount()
{
return getMemoryInformation(GL_GPU_MEMORY_INFO_EVICTION_COUNT_NVX);
}
}
}
|
Test commit: Reverting whitespace changes | // -*- C++ -*-
//===----------------------------------------------------------------------===//
//
// 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.
//
//===----------------------------------------------------------------------===//
int main()
{
}
| // -*- C++ -*-
//===----------------------------------------------------------------------===//
//
// 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.
//
//===----------------------------------------------------------------------===//
int main()
{
}
|
Remove accidentally added "include "" | // For conditions of distribution and use, see copyright notice in license.txt
/**
* @file InventoryAsset.cpp
* @brief A class representing asset in inventory.
*/
#include "
#include "StableHeaders.h"
#include "InventoryAsset.h"
#include "InventoryFolder.h"
namespace Inventory
{
InventoryAsset::InventoryAsset(const QString &id, const QString &asset_reference,const QString &name, InventoryFolder *parent) :
AbstractInventoryItem(id, name, parent), itemType_(AbstractInventoryItem::Type_Asset), assetReference_(asset_reference),
libraryAsset_(false)
{
}
// virtual
InventoryAsset::~InventoryAsset()
{
}
bool InventoryAsset::IsDescendentOf(AbstractInventoryItem *searchFolder)
{
forever
{
AbstractInventoryItem *parent = GetParent();
if (parent)
{
if (parent == searchFolder)
return true;
else
return parent->IsDescendentOf(searchFolder);
}
return false;
}
}
/*
int InventoryAsset::ColumnCount() const
{
return itemData_.count();
}
int InventoryAsset::Row() const
{
if (GetParent())
return GetParent()->Children().indexOf(const_cast<InventoryAsset *>(this));
return 0;
}
*/
}
| // For conditions of distribution and use, see copyright notice in license.txt
/**
* @file InventoryAsset.cpp
* @brief A class representing asset in inventory.
*/
#include "StableHeaders.h"
#include "InventoryAsset.h"
#include "InventoryFolder.h"
namespace Inventory
{
InventoryAsset::InventoryAsset(const QString &id, const QString &asset_reference,const QString &name, InventoryFolder *parent) :
AbstractInventoryItem(id, name, parent), itemType_(AbstractInventoryItem::Type_Asset), assetReference_(asset_reference),
libraryAsset_(false)
{
}
// virtual
InventoryAsset::~InventoryAsset()
{
}
bool InventoryAsset::IsDescendentOf(AbstractInventoryItem *searchFolder)
{
forever
{
AbstractInventoryItem *parent = GetParent();
if (parent)
{
if (parent == searchFolder)
return true;
else
return parent->IsDescendentOf(searchFolder);
}
return false;
}
}
/*
int InventoryAsset::ColumnCount() const
{
return itemData_.count();
}
int InventoryAsset::Row() const
{
if (GetParent())
return GetParent()->Children().indexOf(const_cast<InventoryAsset *>(this));
return 0;
}
*/
}
|
Add Spark function and variables | #include "application.h"
#include "Adafruit_LEDBackpack.h"
Adafruit_8x8matrix matrix1;
Adafruit_8x8matrix matrix2;
Adafruit_8x8matrix matrix3;
static const uint8_t smile[] = {
0b00111100,
0b01000010,
0b10100101,
0b10000001,
0b10100101,
0b10011001,
0b01000010,
0b00111100
};
void setup()
{
Wire.begin();
matrix1.begin(0x70);
matrix2.begin(0x71);
matrix3.begin(0x72);
}
void loop()
{
matrix1.clear();
delay(500);
matrix1.drawBitmap(0, 0, smile, 8, 8, LED_ON);
matrix1.writeDisplay();
delay(500);
}
| #include "application.h"
#include "Adafruit_LEDBackpack.h"
Adafruit_8x8matrix matrix1;
Adafruit_8x8matrix matrix2;
Adafruit_8x8matrix matrix3;
static const uint8_t smile[] = {
0b00111100,
0b01000010,
0b10100101,
0b10000001,
0b10100101,
0b10011001,
0b01000010,
0b00111100
};
int currentTemperature = 0;
int desiredTemperature = 0;
bool isHeatOn = false;
bool isFanOn = false;
int setTemperature(String t)
{
return 1;
}
void setup()
{
Wire.begin();
matrix1.begin(0x70);
matrix2.begin(0x71);
matrix3.begin(0x72);
Spark.function("set_temp", setTemperature);
Spark.variable("current_temp", ¤tTemperature, INT);
Spark.variable("desired_temp", &desiredTemperature, INT);
Spark.variable("is_heat_on", &isHeatOn, BOOLEAN);
Spark.variable("is_fan_on", &isFanOn, BOOLEAN);
}
void loop()
{
matrix3.clear();
matrix3.drawBitmap(0, 0, smile, 8, 8, LED_ON);
matrix3.writeDisplay();
delay(500);
}
|
Fix code to string conversion. | #include "../../include/base/ErrorInfo.hpp"
namespace cutehmi {
namespace base {
QString ErrorInfo::toString() const
{
QString result = str;
result += "\n[error class: ";
result += errClass;
result += " code: ";
result += code;
result += "]";
return result;
}
}
}
//(c)MP: Copyright © 2017, Michal Policht. All rights reserved.
//(c)MP: This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
| #include "../../include/base/ErrorInfo.hpp"
namespace cutehmi {
namespace base {
QString ErrorInfo::toString() const
{
QString result = str;
result += "\n[error class: ";
result += errClass;
result += " code: ";
result += QString::number(code);
result += "]";
return result;
}
}
}
//(c)MP: Copyright © 2017, Michal Policht. All rights reserved.
//(c)MP: This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.