Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Remove unnecessary dependency on ~~driver_node.cpp | /******************************************************
* This is CIR-KIT 3rd robot control driver.
* Author : Arita Yuta(Kyutech)
******************************************************/
#include <ros/ros.h>
#include <geometry_msgs/Twist.h> // cmd_vel
#include <nav_msgs/Odometry.h> // odom
#include <tf/transform_broadcaster.h>
#include <iostream>
#include <string>
#include <boost/thread.hpp>
#include "third_robot_driver.hpp"
int main(int argc, char** argv)
{
ros::init(argc, argv, "Third_robot_driver_node");
ROS_INFO("Third robot driver for ROS.");
ros::NodeHandle nh;
cirkit::ThirdRobotDriver driver(nh);
driver.run();
return 0;
}
| /******************************************************
* This is CIR-KIT 3rd robot control driver.
* Author : Arita Yuta(Kyutech)
******************************************************/
#include "third_robot_driver.hpp"
int main(int argc, char** argv)
{
ros::init(argc, argv, "Third_robot_driver_node");
ROS_INFO("Third robot driver for ROS.");
ros::NodeHandle nh;
cirkit::ThirdRobotDriver driver(nh);
driver.run();
return 0;
}
|
Add solution for Day 11 part two | // Day11.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "Password.h"
int main()
{
Password<8> SantasPassword(std::string("hepxcrrq"));
std::cout << SantasPassword << std::endl;
++SantasPassword;
std::cout << SantasPassword << std::endl;
system("pause");
return 0;
} | // Day11.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "Password.h"
int main()
{
Password<8> SantasPassword(std::string("hepxcrrq"));
std::cout << SantasPassword << std::endl;
++SantasPassword;
std::cout << SantasPassword << std::endl;
++SantasPassword;
std::cout << SantasPassword << std::endl;
system("pause");
return 0;
} |
Update Parameter for init data to impossible | #include "ics3/parameter.hpp"
ics::Parameter ics::Parameter::stretch() noexcept {
static const Parameter STRETCH(0x01, 1, 127);
return STRETCH;
}
ics::Parameter ics::Parameter::speed() noexcept {
static const Parameter SPEED(0x02, 1, 127);
return SPEED;
}
ics::Parameter ics::Parameter::current() noexcept {
static const Parameter CURRENT(0x03, 0, 63);
return CURRENT;
}
ics::Parameter ics::Parameter::temperature() noexcept {
static const Parameter TEMPERATURE(0x04, 1, 127);
return TEMPERATURE;
}
unsigned char ics::Parameter::get() const noexcept {
return data;
}
void ics::Parameter::set(unsigned char input) throw(std::invalid_argument) {
if (input < min) throw std::invalid_argument("Too small value");
if (max < input) throw std::invalid_argument("Too big value");
data = input;
}
ics::Parameter::Parameter(unsigned char sc, unsigned char min, unsigned char max) noexcept
: sc(sc),
min(min),
max(max)
{}
| #include "ics3/parameter.hpp"
ics::Parameter ics::Parameter::stretch() noexcept {
static const Parameter STRETCH(0x01, 1, 127);
return STRETCH;
}
ics::Parameter ics::Parameter::speed() noexcept {
static const Parameter SPEED(0x02, 1, 127);
return SPEED;
}
ics::Parameter ics::Parameter::current() noexcept {
static const Parameter CURRENT(0x03, 0, 63);
return CURRENT;
}
ics::Parameter ics::Parameter::temperature() noexcept {
static const Parameter TEMPERATURE(0x04, 1, 127);
return TEMPERATURE;
}
unsigned char ics::Parameter::get() const noexcept {
return data;
}
void ics::Parameter::set(unsigned char input) throw(std::invalid_argument) {
if (input < min) throw std::invalid_argument("Too small value");
if (max < input) throw std::invalid_argument("Too big value");
data = input;
}
ics::Parameter::Parameter(unsigned char sc, unsigned char min, unsigned char max) noexcept
: sc(sc),
min(min),
max(max),
data(-1)
{}
|
Fix creating new object of incomplete type |
#include <LCDDisplay.h>
int main(int argc, char **argv)
{
std::cout << "testing display";
LCDDisplay *display = new Display();
display->refresh();
display->setMenuString("test string");
display->refresh();
display->setMenuString("new string");
display->setTrackInfoString("track string");
display->refresh();
delete display;
printf("Done");
return 0;
}
|
#include <stdio.h>
#include <LCDDisplay.h>
int main(int argc, char **argv)
{
printf("testing display");
LCDDisplay *display = new LCDDisplay();
display->refresh();
display->setMenuString("test string");
display->refresh();
display->setMenuString("new string");
display->setTrackInfoString("track string");
display->refresh();
delete display;
printf("Done");
return 0;
}
|
Disable WebKitThreadTest.ExposedInChromeThread, due to subsequent assert. | // 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/in_process_webkit/webkit_thread.h"
#include "testing/gtest/include/gtest/gtest.h"
TEST(WebKitThreadTest, ExposedInChromeThread) {
int* null = NULL; // Help the template system out.
EXPECT_FALSE(ChromeThread::DeleteSoon(ChromeThread::WEBKIT, FROM_HERE, null));
{
WebKitThread thread;
EXPECT_FALSE(ChromeThread::DeleteSoon(ChromeThread::WEBKIT,
FROM_HERE, null));
thread.Initialize();
EXPECT_TRUE(ChromeThread::DeleteSoon(ChromeThread::WEBKIT,
FROM_HERE, null));
}
EXPECT_FALSE(ChromeThread::DeleteSoon(ChromeThread::WEBKIT,
FROM_HERE, 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/in_process_webkit/webkit_thread.h"
#include "testing/gtest/include/gtest/gtest.h"
TEST(WebKitThreadTest, DISABLED_ExposedInChromeThread) {
int* null = NULL; // Help the template system out.
EXPECT_FALSE(ChromeThread::DeleteSoon(ChromeThread::WEBKIT, FROM_HERE, null));
{
WebKitThread thread;
EXPECT_FALSE(ChromeThread::DeleteSoon(ChromeThread::WEBKIT,
FROM_HERE, null));
thread.Initialize();
EXPECT_TRUE(ChromeThread::DeleteSoon(ChromeThread::WEBKIT,
FROM_HERE, null));
}
EXPECT_FALSE(ChromeThread::DeleteSoon(ChromeThread::WEBKIT,
FROM_HERE, null));
}
|
Update Problem 33. Search in Rotated Sorted Array | #include "SearchInRotatedSortedArray.hpp"
int SearchInRotatedSortedArray::search(vector<int>& nums, int target)
{
if (nums.empty()) return -1;
int p = 0;
while (p + 1 < nums.size() && nums[p] < nums[p + 1])
p++;
if (p + 1 == nums.size())
return partialSearch(nums, 0, nums.size() - 1, target);
if (target <= nums[nums.size() - 1])
return partialSearch(nums, p + 1, nums.size() - 1, target);
else
return partialSearch(nums, 0, p, target);
}
int SearchInRotatedSortedArray::partialSearch(vector<int>& nums, int p, int q, int target)
{
while (p < q) {
int m = (p + q) / 2;
if (nums[m] == target)
return m;
else if (nums[m] < target)
p = m + 1;
else
q = m;
}
return (nums[p] == target) ? p : -1;
}
| #include "SearchInRotatedSortedArray.hpp"
int SearchInRotatedSortedArray::search(vector<int>& nums, int target)
{
if (nums.empty()) return -1;
return partialSearch(nums, 0, nums.size() - 1, target);
}
int SearchInRotatedSortedArray::partialSearch(vector<int>& nums, int p, int q, int target)
{
if (p > q) return -1;
int m = (p + q) / 2;
if (nums[m] == target) return m;
if (nums[p] > nums[q]) {
int left = partialSearch(nums, p, m - 1, target);
if (left != -1) return left;
else return partialSearch(nums, m + 1, q, target);
} else {
if (nums[m] < target) return partialSearch(nums, m + 1, q, target);
else return partialSearch(nums, p, m - 1, target);
}
} |
Check if collider or one of it's inner objects has a controller to award a badge. | // This file is part of SWGANH which is released under the MIT license.
// See file LICENSE or go to http://swganh.com/LICENSE
#include <swganh_core/badge/badge_region.h>
#include <swganh_core/connection/connection_client_interface.h>
#include <swganh_core/messages/chat_system_message.h>
#include <swganh_core/messages/play_music_message.h>
#include <swganh_core/messages/out_of_band.h>
#include <swganh_core/messages/system_message.h>
#include "badge_service.h"
using namespace swganh::badge;
using namespace swganh::messages;
BadgeRegion::BadgeRegion(std::string badge_name, BadgeService* service)
: badge_service_(service)
, badge_name_(badge_name)
{
SetCollidable(true);
}
BadgeRegion::~BadgeRegion(void)
{
}
void BadgeRegion::OnCollisionEnter(std::shared_ptr<swganh::object::Object> collider)
{
badge_service_->GiveBadge(collider, badge_name_);
} | // This file is part of SWGANH which is released under the MIT license.
// See file LICENSE or go to http://swganh.com/LICENSE
#include <swganh_core/badge/badge_region.h>
#include <swganh_core/connection/connection_client_interface.h>
#include <swganh_core/messages/chat_system_message.h>
#include <swganh_core/messages/play_music_message.h>
#include <swganh_core/messages/out_of_band.h>
#include <swganh_core/messages/system_message.h>
#include "badge_service.h"
using namespace swganh::badge;
using namespace swganh::messages;
using swganh::object::Object;
BadgeRegion::BadgeRegion(std::string badge_name, BadgeService* service)
: badge_service_(service)
, badge_name_(badge_name)
{
SetCollidable(true);
SetDatabasePersisted(false);
SetInSnapshot(true);
}
BadgeRegion::~BadgeRegion(void)
{
}
void BadgeRegion::OnCollisionEnter(std::shared_ptr<Object> collider)
{
if(collider->HasController())
{
badge_service_->GiveBadge(collider, badge_name_);
} else {
collider->ViewObjects(nullptr, 0, true, [this] (const std::shared_ptr<Object>& inner)
{
if(inner->HasController())
{
badge_service_->GiveBadge(inner, badge_name_);
}
});
}
} |
Disable ExtensionApiTest.WebSocket instead of marked as FAILS_ | // 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 "base/logging.h"
#include "base/path_service.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/base/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"
// http://crbug.com/111165
#if defined(OS_WIN)
#define MAYBE_WebSocket FAILS_WebSocket
#else
#define MAYBE_WebSocket WebSocket
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_WebSocket) {
FilePath websocket_root_dir;
ASSERT_TRUE(PathService::Get(chrome::DIR_LAYOUT_TESTS, &websocket_root_dir));
// TODO(toyoshim): Remove following logging after a bug investigation.
// http://crbug.com/107836 .
LOG(INFO) << "Assume LayoutTests in " << websocket_root_dir.MaybeAsASCII();
ui_test_utils::TestWebSocketServer server;
ASSERT_TRUE(server.Start(websocket_root_dir));
ASSERT_TRUE(RunExtensionTest("websocket")) << message_;
}
| // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/logging.h"
#include "base/path_service.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/base/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"
// http://crbug.com/111165
#if defined(OS_WIN)
#define MAYBE_WebSocket DISABLED_WebSocket
#else
#define MAYBE_WebSocket WebSocket
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_WebSocket) {
FilePath websocket_root_dir;
ASSERT_TRUE(PathService::Get(chrome::DIR_LAYOUT_TESTS, &websocket_root_dir));
// TODO(toyoshim): Remove following logging after a bug investigation.
// http://crbug.com/107836 .
LOG(INFO) << "Assume LayoutTests in " << websocket_root_dir.MaybeAsASCII();
ui_test_utils::TestWebSocketServer server;
ASSERT_TRUE(server.Start(websocket_root_dir));
ASSERT_TRUE(RunExtensionTest("websocket")) << message_;
}
|
Make DllMain hang onto the HINSTANCE passed to it | // dllmain.cpp : Implementation of DllMain.
#include "stdafx.h"
#include "resource.h"
#include "WordPerfectIndexer_i.h"
#include "dllmain.h"
CWordPerfectIndexerModule _AtlModule;
// DLL Entry Point
extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
{
hInstance;
return _AtlModule.DllMain(dwReason, lpReserved);
}
| // dllmain.cpp : Implementation of DllMain.
#include "stdafx.h"
#include "resource.h"
#include "WordPerfectIndexer_i.h"
#include "dllmain.h"
CWordPerfectIndexerModule _AtlModule;
HINSTANCE _AtlModuleInstance;
// DLL Entry Point
extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
{
_AtlModuleInstance = hInstance;
return _AtlModule.DllMain(dwReason, lpReserved);
}
|
Make header include compat with std. | #include <iostream>
#include <zlib.h>
#include <string>
#include "mszreader.h"
using namespace std;
using namespace iomsz;
int main( int argc, char* argv[] ) {
if ( argc <= 1 ) exit(-1);
unsigned int nbSolvers, nbFeatures, nbInstances, timeOut;
string* solversNames, *featuresNames, *instancesNames;
double** matrix;
char * inputFileName=argv[1];
gzFile in=(inputFileName==NULL? gzdopen(0,"rb"): gzopen(inputFileName,"rb"));
if (in==NULL) {
cerr<<"Error: Could not open file: "
<<(inputFileName==NULL? "<stdin>": inputFileName)
<<endl;
exit(1);
}
parse_DIMACS(in, nbSolvers, nbFeatures, nbInstances, timeOut, solversNames, featuresNames, instancesNames, matrix);
return 0;
}
| #include <iostream>
#include <zlib.h>
#include <string>
#include "mszreader.hh"
using namespace std;
using namespace iomsz;
int main( int argc, char* argv[] ) {
if ( argc <= 1 ) exit(-1);
unsigned int nbSolvers, nbFeatures, nbInstances, timeOut;
string* solversNames, *featuresNames, *instancesNames;
double** matrix;
char * inputFileName=argv[1];
gzFile in=(inputFileName==NULL? gzdopen(0,"rb"): gzopen(inputFileName,"rb"));
if (in==NULL) {
cerr<<"Error: Could not open file: "
<<(inputFileName==NULL? "<stdin>": inputFileName)
<<endl;
exit(1);
}
parse_DIMACS(in, nbSolvers, nbFeatures, nbInstances, timeOut, solversNames, featuresNames, instancesNames, matrix);
return 0;
}
|
Revert 64157 - Marking ExtensionApiTest.Infobars as FAILS until 10.5 issue is resolved. Reverting in order to create a proper CL for it. BUG=60990 | // 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 "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"
#if defined(TOOLKIT_VIEWS)
#define MAYBE_Infobars Infobars
#elif defined(OS_MACOSX)
// Temporarily marking as FAILS. See http://crbug.com/60990 for details.
#define MAYBE_Infobars FAILS_Infobars
#else
// Need to finish port to Linux. See http://crbug.com/39916 for details.
#define MAYBE_Infobars DISABLED_Infobars
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) {
// TODO(finnur): Remove once infobars are no longer experimental (bug 39511).
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionTest("infobars")) << 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 "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"
#if defined(TOOLKIT_VIEWS) || defined(OS_MACOSX)
#define MAYBE_Infobars Infobars
#else
// Need to finish port to Linux. See http://crbug.com/39916 for details.
#define MAYBE_Infobars DISABLED_Infobars
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) {
// TODO(finnur): Remove once infobars are no longer experimental (bug 39511).
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionTest("infobars")) << message_;
}
|
Disable ExtensionApiTest.Storage because it crashes the browser_tests too. | // 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"
// This test is disabled. See bug 25746
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Storage) {
ASSERT_TRUE(RunExtensionTest("storage")) << message_;
}
|
Revert "Fix boolean expectation from strcmp." | /*
* Copyright 2004-2014 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is 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 <cstdio>
#include "driver.h"
#include "version.h"
#include "version_num.h"
void
get_version(char *v) {
v += sprintf(v, "%d.%s.%s", MAJOR_VERSION, MINOR_VERSION, UPDATE_VERSION);
if (!strcmp(BUILD_VERSION, "") || developer)
sprintf(v, ".%s", BUILD_VERSION);
}
| /*
* Copyright 2004-2014 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is 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 <cstdio>
#include "driver.h"
#include "version.h"
#include "version_num.h"
void
get_version(char *v) {
v += sprintf(v, "%d.%s.%s", MAJOR_VERSION, MINOR_VERSION, UPDATE_VERSION);
if (strcmp(BUILD_VERSION, "") || developer)
sprintf(v, ".%s", BUILD_VERSION);
}
|
Implement adding of torrents over the commandline | #include <memory>
#include "client/event_system.h"
#include "client/client_interface.h"
#include "events/connection_receiver.h"
#include "events/hub.h"
int main( int argc, char** argv )
{
auto connection = std::make_shared < events::Connection_receiver > ( "localhost", 31005 );
events::Hub::get_filter ( "Send_message_event" ).subscribe ( connection );
client::Event_system::initialize ( connection.get () );
connection->start ();
client::Interface::run ( connection.get () );
std::exit ( 0 );
}
| #include <memory>
#include <iostream>
#include <cstring>
#include "client/event_system.h"
#include "client/client_interface.h"
#include "client/events/events.h"
#include "events/connection_receiver.h"
#include "events/hub.h"
bool parse_args ( int argc, char** argv )
{
if ( argc > 1 )
{
if ( ( !strcmp ( argv [ 1 ], "--url" ) ) && argc > 2 )
{
for ( int i = 2; i < argc; i++ )
{
auto add_torrent_event = std::make_shared < client::Add_torrent_event > ( client::Add_torrent_event::Method::URL, argv [ i ] );
events::Hub::send ( add_torrent_event );
std::cout << "Added: " << argv [ i ] << std::endl;
}
}
else
{
for ( int i = 1; i < argc; i++ )
{
auto add_torrent_event = std::make_shared < client::Add_torrent_event > ( client::Add_torrent_event::Method::FILE, argv [ i ] );
events::Hub::send ( add_torrent_event );
std::cout << "Added: " << argv [ i ] << std::endl;
}
}
return false;
}
else
return true;
}
int main ( int argc, char** argv )
{
auto connection = std::make_shared < events::Connection_receiver > ( "localhost", 31005 );
events::Hub::get_filter ( "Send_message_event" ).subscribe ( connection );
client::Event_system::initialize ( connection.get () );
connection->start ();
if ( parse_args ( argc, argv ) )
client::Interface::run ( connection.get () );
std::exit ( 0 );
}
|
Fix compilation error in logger test | #include <boost/timer/timer.hpp>
#include <iostream>
#include <string>
#include <vector>
#include "common/logging.h"
// small test program for playing around with spdlog formatting of messages
std::shared_ptr<spdlog::logger> stderrLogger(
const std::string& name,
const std::string& pattern,
const std::vector<std::string>& files) {
std::vector<spdlog::sink_ptr> sinks;
auto stderr_sink = spdlog::sinks::stderr_sink_mt::instance();
sinks.push_back(stderr_sink);
for(auto&& file : files) {
auto file_sink
= std::make_shared<spdlog::sinks::simple_file_sink_st>(file, true);
sinks.push_back(file_sink);
}
auto logger
= std::make_shared<spdlog::logger>(name, begin(sinks), end(sinks));
spdlog::register_logger(logger);
logger->set_pattern(pattern);
return logger;
}
int main() {
std::vector<std::string> logfiles;
Logger info(stderrLogger("info", "[%Y-%m-%d %T] %v", logfiles));
info->info("hello {:06.2f}", .7);
boost::timer::cpu_timer timer;
info->info("time is {} bla {:.2f}", timer.format(5, "%w"), .7);
}
| #include <boost/timer/timer.hpp>
#include <iostream>
#include <string>
#include <vector>
#include "common/logging.h"
// small test program for playing around with spdlog formatting of messages
std::shared_ptr<spdlog::logger> stderrLoggerTest(
const std::string& name,
const std::string& pattern,
const std::vector<std::string>& files) {
std::vector<spdlog::sink_ptr> sinks;
auto stderr_sink = spdlog::sinks::stderr_sink_mt::instance();
sinks.push_back(stderr_sink);
for(auto&& file : files) {
auto file_sink
= std::make_shared<spdlog::sinks::simple_file_sink_st>(file, true);
sinks.push_back(file_sink);
}
auto logger
= std::make_shared<spdlog::logger>(name, begin(sinks), end(sinks));
spdlog::register_logger(logger);
logger->set_pattern(pattern);
return logger;
}
int main() {
std::vector<std::string> logfiles;
Logger info(stderrLoggerTest("info", "[%Y-%m-%d %T] %v", logfiles));
info->info("hello {:06.2f}", .7);
boost::timer::cpu_timer timer;
info->info("time is {} bla {:.2f}", timer.format(5, "%w"), .7);
}
|
Read the dashboard file and return the content | #include "dashboardcontroller.h"
#include "serialization/result.h"
ApiMock::ResponseData ApiMock::DashboardController::get(RequestData request) {
auto result = Html("<h1>Hello, world</h1>\n<p>This is an HTML result</p>");
return createResponse(HTTP_OK, &result);
} | #include "dashboardcontroller.h"
#include "serialization/result.h"
#include <fstream>
ApiMock::ResponseData ApiMock::DashboardController::get(RequestData request) {
// TODO: This is temporary, just to try the concept out. But really: files shouldn't be loaded like this:
std::ifstream dashboard("www/dashboard.html");
std::string temp;
std::string body;
while (std::getline(dashboard, temp))
body += temp;
auto result = Html(body);
return createResponse(HTTP_OK, &result);
} |
Disable FreeRTOS task priority settings in Non-OS mode | #include "RMain.h"
#include "RGlobal.h"
#include "RThread.h"
#include "REventLoop.h"
#include "RCoreApplication.h"
#include "RSpinLocker.h"
static volatile RThread *sMainThread = NULL;
RThread *
rGetMainThread()
{
return (RThread *)sMainThread;
}
void
setup()
{
}
void
loop()
{
// Do nothing, we must not do time consuming inside loop(), it's necessary
// runtime component for FreeRTOS. If you do complicate jobs, delay inside
// and take a long time, it will lead some weird situation or lead program
// crash!
if(NULL == sMainThread)
{
const rfchar *programName = F("");
rfchar * argv[] = {const_cast<rfchar *>(programName), };
// FIXME: Idle thread only get working when other thread suspended (
// vTaskDelay() or vTaskSuspend())
// Fixed idle thread won't get any notice even yield from other thread
vTaskPrioritySet(RThread::currentThreadId(), RThread::NormalPriority);
sMainThread = RThread::currentThread();
rMain(1, argv);
}
if(rCoreApp)
{
rCoreApp->processEvents();
}
}
void
rPostEvent(RObject *receiver, REvent *event)
{
R_MAKE_SPINLOCKER();
receiver->thread()->eventLoop()->postEvent(receiver, event);
}
| #include "RMain.h"
#include "RGlobal.h"
#include "RThread.h"
#include "REventLoop.h"
#include "RCoreApplication.h"
#include "RSpinLocker.h"
static volatile RThread *sMainThread = NULL;
RThread *
rGetMainThread()
{
return (RThread *)sMainThread;
}
void
setup()
{
}
void
loop()
{
// Do nothing, we must not do time consuming inside loop(), it's necessary
// runtime component for FreeRTOS. If you do complicate jobs, delay inside
// and take a long time, it will lead some weird situation or lead program
// crash!
if(NULL == sMainThread)
{
const rfchar *programName = F("");
rfchar * argv[] = {const_cast<rfchar *>(programName), };
#ifdef R_OS_FREERTOS
// FIXME: Idle thread only get working when other thread suspended (
// vTaskDelay() or vTaskSuspend())
// Fixed idle thread won't get any notice even yield from other thread
vTaskPrioritySet(RThread::currentThreadId(), RThread::NormalPriority);
#endif // #ifdef R_OS_FREERTOS
sMainThread = RThread::currentThread();
rMain(1, argv);
}
if(rCoreApp)
{
rCoreApp->processEvents();
}
}
void
rPostEvent(RObject *receiver, REvent *event)
{
R_MAKE_SPINLOCKER();
receiver->thread()->eventLoop()->postEvent(receiver, event);
}
|
Include isqrt.hpp instead of imath.hpp | ///
/// @file pi_legendre.cpp
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primecount.hpp>
#include <primecount-internal.hpp>
#include <imath.hpp>
#include <stdint.h>
namespace primecount {
/// Count the number of primes <= x using Legendre's formula.
/// Run time: O(x)
/// Memory usage: O(x^(1/2))
///
int64_t pi_legendre(int64_t x, int threads)
{
if (x < 2)
return 0;
// temporarily disable printing
bool print = is_print();
set_print(false);
int64_t a = pi_primesieve(isqrt(x));
int64_t sum = phi(x, a, threads) + a - 1;
set_print(print);
return sum;
}
} // namespace
| ///
/// @file pi_legendre.cpp
///
/// Copyright (C) 2018 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primecount.hpp>
#include <primecount-internal.hpp>
#include <isqrt.hpp>
#include <stdint.h>
namespace primecount {
/// Count the number of primes <= x using Legendre's formula.
/// Run time: O(x)
/// Memory usage: O(x^(1/2))
///
int64_t pi_legendre(int64_t x, int threads)
{
if (x < 2)
return 0;
// temporarily disable printing
bool print = is_print();
set_print(false);
int64_t a = pi_primesieve(isqrt(x));
int64_t sum = phi(x, a, threads) + a - 1;
set_print(print);
return sum;
}
} // namespace
|
Add debug logging for example code. | #include "logger.h"
// Keep it simple for now
#include <iostream>
void error_logger(luna::log_level level, const std::string &message)
{
switch (level)
{
case luna::log_level::DEBUG:
// std::cerr << "[ DEBUG] " << message << std::endl;
break;
case luna::log_level::INFO:
std::cerr << "[ INFO] " << message << std::endl;;
break;
case luna::log_level::WARNING:
std::cerr << "[WARNING] " << message << std::endl;;
break;
case luna::log_level::ERROR:
std::cerr << "[ ERROR] " << message << std::endl;;
break;
case luna::log_level::FATAL:
std::cerr << "[ FATAL] " << message << std::endl;;
break;
}
}
void access_logger(const luna::request &request, const luna::response &response)
{
std::cout << request.ip_address << ": " << luna::to_string(request.method) << " [" << response.status_code << "] "
<< request.path << " " << request.http_version << " " << (request.headers.count("user-agent") ? request.headers.at("user-agent") : "[no user-agent]") << " { "
<< std::chrono::duration_cast<std::chrono::microseconds>(request.end - request.start).count() << "us } " << std::endl;
}
| #include "logger.h"
// Keep it simple for now
#include <iostream>
void error_logger(luna::log_level level, const std::string &message)
{
switch (level)
{
case luna::log_level::DEBUG:
std::cerr << "[ DEBUG] " << message << std::endl;
break;
case luna::log_level::INFO:
std::cerr << "[ INFO] " << message << std::endl;;
break;
case luna::log_level::WARNING:
std::cerr << "[WARNING] " << message << std::endl;;
break;
case luna::log_level::ERROR:
std::cerr << "[ ERROR] " << message << std::endl;;
break;
case luna::log_level::FATAL:
std::cerr << "[ FATAL] " << message << std::endl;;
break;
}
}
void access_logger(const luna::request &request, const luna::response &response)
{
std::cout << request.ip_address << ": " << luna::to_string(request.method) << " [" << response.status_code << "] "
<< request.path << " " << request.http_version << " " << (request.headers.count("user-agent") ? request.headers.at("user-agent") : "[no user-agent]") << " { "
<< std::chrono::duration_cast<std::chrono::microseconds>(request.end - request.start).count() << "us } " << std::endl;
}
|
Tweak test for debug/metadata change, update to FileCheck. Radar 7424645. | // RUN: %llvmgcc -g -S -O2 %s -o %t
// RUN: grep "i1 false, i1 true. . . DW_TAG_subprogram" %t | count 2
class foo {
public:
int bar(int x);
static int baz(int x);
};
int foo::bar(int x) {
return x*4 + 1;
}
int foo::baz(int x) {
return x*4 + 1;
}
| // RUN: %llvmgcc -g -S -O2 %s -o - | FileCheck %s
class foo {
public:
int bar(int x);
static int baz(int x);
};
int foo::bar(int x) {
// CHECK: {{i1 false, i1 true(, i[0-9]+ [^\}]+[}]|[}]) ; \[ DW_TAG_subprogram \]}}
return x*4 + 1;
}
int foo::baz(int x) {
// CHECK: {{i1 false, i1 true(, i[0-9]+ [^\},]+[}]|[}]) ; \[ DW_TAG_subprogram \]}}
return x*4 + 1;
}
|
Extend the tests for -Wmissing-variable-declarations. | // RUN: %clang -Wmissing-variable-declarations -fsyntax-only -Xclang -verify %s
// Variable declarations that should trigger a warning.
int vbad1; // expected-warning{{no previous extern declaration for non-static variable 'vbad1'}}
int vbad2 = 10; // expected-warning{{no previous extern declaration for non-static variable 'vbad2'}}
namespace x {
int vbad3; // expected-warning{{no previous extern declaration for non-static variable 'vbad3'}}
}
// Variable declarations that should not trigger a warning.
static int vgood1;
extern int vgood2;
int vgood2;
static struct {
int mgood1;
} vgood3;
// Functions should never trigger a warning.
void fgood1(void);
void fgood2(void) {
int lgood1;
static int lgood2;
}
static void fgood3(void) {
int lgood3;
static int lgood4;
}
// Structures, namespaces and classes should be unaffected.
struct sgood1 {
int mgood2;
};
struct {
int mgood3;
} sgood2;
class CGood1 {
static int MGood1;
};
int CGood1::MGood1;
namespace {
int mgood4;
}
class C {
void test() {
static int x = 0; // no-warn
}
};
| // RUN: %clang -Wmissing-variable-declarations -fsyntax-only -Xclang -verify %s
// Variable declarations that should trigger a warning.
int vbad1; // expected-warning{{no previous extern declaration for non-static variable 'vbad1'}}
int vbad2 = 10; // expected-warning{{no previous extern declaration for non-static variable 'vbad2'}}
namespace x {
int vbad3; // expected-warning{{no previous extern declaration for non-static variable 'vbad3'}}
}
// Variable declarations that should not trigger a warning.
static int vgood1;
extern int vgood2;
int vgood2;
static struct {
int mgood1;
} vgood3;
// Functions should never trigger a warning.
void fgood1(void);
void fgood2(void) {
int lgood1;
static int lgood2;
}
static void fgood3(void) {
int lgood3;
static int lgood4;
}
// Structures, namespaces and classes should be unaffected.
struct sgood1 {
int mgood2;
};
struct {
int mgood3;
} sgood2;
class CGood1 {
static int MGood1;
};
int CGood1::MGood1;
namespace {
int mgood4;
}
class C {
void test() {
static int x = 0; // no-warn
}
};
// There is also no need to use static in anonymous namespaces.
namespace {
int vgood4;
}
|
Fix error when converting Bullet quaternion to GLM quaternion. | #include "GlmConversion.hpp"
namespace Physics {
btVector3 glmToBt(glm::vec3 const& vec) {
return btVector3(vec.x, vec.y, vec.z);
}
glm::vec3 btToGlm(btVector3 const& vec) {
return glm::vec3(vec.getX(), vec.getY(), vec.getZ());
}
glm::quat btToGlm(btQuaternion const& quat) {
return glm::quat(quat.getX(), quat.getY(), quat.getZ(), quat.getW());
}
}
| #include "GlmConversion.hpp"
namespace Physics {
btVector3 glmToBt(glm::vec3 const& vec) {
return btVector3(vec.x, vec.y, vec.z);
}
glm::vec3 btToGlm(btVector3 const& vec) {
return glm::vec3(vec.getX(), vec.getY(), vec.getZ());
}
glm::quat btToGlm(btQuaternion const& quat) {
return glm::quat(quat.getW(), quat.getX(), quat.getY(), quat.getZ());
}
}
|
Enable WebGL in QtBrowser if able to. | // Copyright (c) 2011 Hewlett-Packard Development Company, L.P. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <QUrl>
#include <QWebView>
#include "browser.h"
Browser::Browser(QWidget *parent)
: QMainWindow(parent)
{
setupUi(this);
}
void Browser::on_urlEdit_returnPressed()
{
webView->load(QUrl::fromUserInput(urlEdit->text()));
}
void Browser::on_webView_urlChanged(QUrl& url)
{
urlEdit->setText(url.toString());
}
| // Copyright (c) 2011 Hewlett-Packard Development Company, L.P. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <QUrl>
#include <QWebView>
#include "browser.h"
Browser::Browser(QWidget *parent)
: QMainWindow(parent)
{
setupUi(this);
webView->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled,
true);
webView->settings()->setAttribute(QWebSettings::SiteSpecificQuirksEnabled,
false);
webView->settings()->setAttribute(QWebSettings::AcceleratedCompositingEnabled,
true);
#if (QTWEBKIT_VERSION >= QTWEBKIT_VERSION_CHECK(2, 2, 0))
webView->settings()->setAttribute(QWebSettings::WebGLEnabled, true);
#endif
}
void Browser::on_urlEdit_returnPressed()
{
webView->load(QUrl::fromUserInput(urlEdit->text()));
}
void Browser::on_webView_urlChanged(QUrl& url)
{
urlEdit->setText(url.toString());
}
|
Stop spamming number of gl calls to console. | #include "Vajra/Framework/Core/Framework.h"
#include "Vajra/Framework/Logging/Logger.h"
#include "Vajra/Framework/OpenGL/OpenGLCounter/OpenGLCounter.h"
OpenGLCounter::OpenGLCounter() {
this->init();
}
OpenGLCounter::~OpenGLCounter() {
this->destroy();
}
void OpenGLCounter::CountGlCall(const char* /* glFunctionName */) {
this->countOfAllGlCallsThisFrame++;
}
void OpenGLCounter::switchFrames() {
FRAMEWORK->GetLogger()->dbglog("\nNumber of gl calls in previous frame: %u", this->countOfAllGlCallsThisFrame);
this->countOfAllGlCallsThisFrame = 0;
}
void OpenGLCounter::init() {
this->countOfAllGlCallsThisFrame = 0;
}
void OpenGLCounter::destroy() {
}
| #include "Vajra/Framework/Core/Framework.h"
#include "Vajra/Framework/Logging/Logger.h"
#include "Vajra/Framework/OpenGL/OpenGLCounter/OpenGLCounter.h"
OpenGLCounter::OpenGLCounter() {
this->init();
}
OpenGLCounter::~OpenGLCounter() {
this->destroy();
}
void OpenGLCounter::CountGlCall(const char* /* glFunctionName */) {
this->countOfAllGlCallsThisFrame++;
}
void OpenGLCounter::switchFrames() {
// FRAMEWORK->GetLogger()->dbglog("\nNumber of gl calls in previous frame: %u", this->countOfAllGlCallsThisFrame);
this->countOfAllGlCallsThisFrame = 0;
}
void OpenGLCounter::init() {
this->countOfAllGlCallsThisFrame = 0;
}
void OpenGLCounter::destroy() {
}
|
Add an HTTP basic auth unit test for an empty username. | // 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 "testing/gtest/include/gtest/gtest.h"
#include "base/basictypes.h"
#include "net/http/http_auth_handler_basic.h"
namespace net {
TEST(HttpAuthHandlerBasicTest, GenerateCredentials) {
static const struct {
const wchar_t* username;
const wchar_t* password;
const char* expected_credentials;
} tests[] = {
{ L"foo", L"bar", "Basic Zm9vOmJhcg==" },
// Empty password
{ L"anon", L"", "Basic YW5vbjo=" },
};
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
std::string challenge = "Basic realm=\"Atlantis\"";
HttpAuthHandlerBasic basic;
basic.InitFromChallenge(challenge.begin(), challenge.end(),
HttpAuth::AUTH_SERVER);
std::string credentials = basic.GenerateCredentials(tests[i].username,
tests[i].password,
NULL, NULL);
EXPECT_STREQ(tests[i].expected_credentials, credentials.c_str());
}
}
} // namespace net
| // 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 "testing/gtest/include/gtest/gtest.h"
#include "base/basictypes.h"
#include "net/http/http_auth_handler_basic.h"
namespace net {
TEST(HttpAuthHandlerBasicTest, GenerateCredentials) {
static const struct {
const wchar_t* username;
const wchar_t* password;
const char* expected_credentials;
} tests[] = {
{ L"foo", L"bar", "Basic Zm9vOmJhcg==" },
// Empty username
{ L"", L"foobar", "Basic OmZvb2Jhcg==" },
// Empty password
{ L"anon", L"", "Basic YW5vbjo=" },
};
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
std::string challenge = "Basic realm=\"Atlantis\"";
HttpAuthHandlerBasic basic;
basic.InitFromChallenge(challenge.begin(), challenge.end(),
HttpAuth::AUTH_SERVER);
std::string credentials = basic.GenerateCredentials(tests[i].username,
tests[i].password,
NULL, NULL);
EXPECT_STREQ(tests[i].expected_credentials, credentials.c_str());
}
}
} // namespace net
|
Use emplace instead of insert | #include "PrimaryTreeIndex.h"
void PrimaryTreeIndex::buildIndex(Table & table, int column) {
int rowno = 0;
for(auto currentRow : table) {
index.insert( std::pair<std::string, int>(currentRow[column], rowno++) );
}
}
int PrimaryTreeIndex::size() const {
return index.size();
}
| #include "PrimaryTreeIndex.h"
void PrimaryTreeIndex::buildIndex(Table & table, int column) {
int rowno = 0;
for(auto currentRow : table) {
index.emplace(currentRow[column], rowno++);
}
}
int PrimaryTreeIndex::size() const {
return index.size();
}
|
Fix build failure in test. |
extern "C" void throw_int()
{
throw 12;
}
extern "C" void throw_id();
extern "C" int id_catchall;
extern "C" int catchall()
{
try
{
throw_id();
}
catch(...)
{
id_catchall = 1;
throw;
}
__builtin_trap();
}
|
extern "C" void throw_int()
{
throw 12;
}
extern "C" void throw_id();
extern "C" int catchall()
{
try
{
throw_id();
}
catch(...)
{
throw;
}
__builtin_trap();
}
|
Revert "Revert "Adding laser indicator"" | #include "AConfig.h"
#if(HAS_STD_CALIBRATIONLASERS)
#include "Device.h"
#include "Pin.h"
#include "CalibrationLaser.h"
#include "Settings.h"
Pin claser("claser", CALIBRATIONLASERS_PIN, claser.analog, claser.out);
void CalibrationLaser::device_setup(){
Settings::capability_bitarray |= (1 << CALIBRATION_LASERS_CAPABLE);
claser.write(0);
}
void CalibrationLaser::device_loop(Command command){
if( command.cmp("claser")){
int value = command.args[1];
claser.write(value);
}
}
#endif
| #include "AConfig.h"
#if(HAS_STD_CALIBRATIONLASERS)
#include "Device.h"
#include "Pin.h"
#include "CalibrationLaser.h"
#include "Settings.h"
Pin claser("claser", CALIBRATIONLASERS_PIN, claser.analog, claser.out);
void CalibrationLaser::device_setup(){
Settings::capability_bitarray |= (1 << CALIBRATION_LASERS_CAPABLE);
claser.write(0);
}
void CalibrationLaser::device_loop(Command command){
if( command.cmp("claser")){
int value = command.args[1];
claser.write(value);
claser.send(value);
}
}
#endif
|
Fix getAbsolutePosition() providing position for hosted app | /*=============================================================================
Library: CTK
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
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.
=============================================================================*/
// Qt includes
#include <QDebug>
// CTK includes
#include "ctkHostedAppPlaceholderWidget.h"
//----------------------------------------------------------------------------
ctkHostedAppPlaceholderWidget::ctkHostedAppPlaceholderWidget(QWidget *parent) :
QFrame(parent)
{
}
//----------------------------------------------------------------------------
QRect ctkHostedAppPlaceholderWidget::getAbsolutePosition()
{
QWidget* current = this;
int x = 0;
int y = 0;
do
{
x = x + current->x();
y = y + current->y();
current = dynamic_cast<QWidget*>(current->parent());
}
while (current);
return QRect(x,y,width(),height());
}
| /*=============================================================================
Library: CTK
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
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.
=============================================================================*/
// Qt includes
#include <QDebug>
// CTK includes
#include "ctkHostedAppPlaceholderWidget.h"
//----------------------------------------------------------------------------
ctkHostedAppPlaceholderWidget::ctkHostedAppPlaceholderWidget(QWidget *parent) :
QFrame(parent)
{
}
//----------------------------------------------------------------------------
QRect ctkHostedAppPlaceholderWidget::getAbsolutePosition()
{
QWidget* current = this;
int x = 0;
int y = 0;
do
{
x = x + current->geometry().x();
y = y + current->geometry().y();
current = dynamic_cast<QWidget*>(current->parent());
}
while (current);
return QRect(x,y,width(),height());
}
|
Fix missing scaling factor application | #include "GenericSensor.h"
GenericSensor::GenericSensor(const char* name,
uint8_t bufsize,
unsigned long sample_interval,
unsigned long send_interval)
{
_name = name;
_interval_sampling = sample_interval;
_interval_sending = send_interval;
_scale_factor = 1.0;
_scale_offset = 0;
_next_sample = 0;
_next_send = 0;
_buffer = AveragingBuffer();
_buffer.setSize(bufsize);
}
GenericSensor::~GenericSensor() {};
void GenericSensor::tick(unsigned long timestamp)
{
// TODO: Take care of overflow for millis every 50 days or so
if (timestamp >= _next_sample) {
addValue(readSensor());
_next_sample = timestamp + _interval_sampling;
}
if (timestamp >= _next_send) {
if (timestamp > 0) send();
_next_send = timestamp + _interval_sending;
}
}
void GenericSensor::send()
{
Serial.print(_name);
Serial.print(':');
Serial.println(getAverage());
}
| #include "GenericSensor.h"
GenericSensor::GenericSensor(const char* name,
uint8_t bufsize,
unsigned long sample_interval,
unsigned long send_interval)
{
_name = name;
_interval_sampling = sample_interval;
_interval_sending = send_interval;
_scale_factor = 1.0;
_scale_offset = 0;
_next_sample = 0;
_next_send = 0;
_buffer = AveragingBuffer();
_buffer.setSize(bufsize);
}
GenericSensor::~GenericSensor() {};
void GenericSensor::tick(unsigned long timestamp)
{
// TODO: Take care of overflow for millis every 50 days or so
if (timestamp >= _next_sample) {
addValue(readSensor());
_next_sample = timestamp + _interval_sampling;
}
if (timestamp >= _next_send) {
if (timestamp > 0) send();
_next_send = timestamp + _interval_sending;
}
}
void GenericSensor::send()
{
Serial.print(_name);
Serial.print(':');
Serial.println((getAverage()+_scale_offset)*_scale_factor);
}
|
Set pointer to null on delete. | /*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "SampleBuffer.h"
#include "io/wav/WavStreamReader.h"
namespace iolib {
void SampleBuffer::loadSampleData(parselib::WavStreamReader* reader) {
// Although we read this in, at this time we know a-priori that the data is mono
mAudioProperties.channelCount = reader->getNumChannels();
mAudioProperties.sampleRate = reader->getSampleRate();
reader->positionToAudio();
mNumSamples = reader->getNumSampleFrames() * reader->getNumChannels();
mSampleData = new float[mNumSamples];
reader->getDataFloat(mSampleData, reader->getNumSampleFrames());
}
void SampleBuffer::unloadSampleData() {
if (mSampleData != nullptr) {
delete[] mSampleData;
}
mNumSamples = 0;
}
}
| /*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "SampleBuffer.h"
#include "io/wav/WavStreamReader.h"
namespace iolib {
void SampleBuffer::loadSampleData(parselib::WavStreamReader* reader) {
// Although we read this in, at this time we know a-priori that the data is mono
mAudioProperties.channelCount = reader->getNumChannels();
mAudioProperties.sampleRate = reader->getSampleRate();
reader->positionToAudio();
mNumSamples = reader->getNumSampleFrames() * reader->getNumChannels();
mSampleData = new float[mNumSamples];
reader->getDataFloat(mSampleData, reader->getNumSampleFrames());
}
void SampleBuffer::unloadSampleData() {
if (mSampleData != nullptr) {
delete[] mSampleData;
mSampleData = nullptr;
}
mNumSamples = 0;
}
}
|
Fix compilation on case-sensitive filesystem. | // Copyright (c) 2014 Jrmy Ansel
// Licensed under the MIT license. See LICENSE.txt
#include "targetver.h"
#define WIN32_LEAN_AND_MEAN
#define STRICT
#include <Windows.h>
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
| // Copyright (c) 2014 Jrmy Ansel
// Licensed under the MIT license. See LICENSE.txt
#include "targetver.h"
#define WIN32_LEAN_AND_MEAN
#define STRICT
#include <windows.h>
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
|
Use <> instead "" for include local libs | #include "pdbreader.hh"
#include "yapdbr.hh"
void printList(atomsList &l) {
atomsList::iterator it1 = l.begin(), it2 = l.end();
for (; it1 != it2; ++it1) {
std::cout << std::get<0>(*it1) << " " << std::get<1>(*it1) << " " << std::get<2>(*it1) << "<-\n";
}
}
int main() {
std::string file = std::string("1ABS.pdb");
PDBReader pr(file);
pr.parsePDB();
std::map<int, std::string> data = pr.getData();
YAPDBR y(data);
y.asList("ALL");
atomsList l = y.asList("CA");
printList(l);
return 0;
}
| #include <pdbreader.hh>
#include <yapdbr.hh>
void printList(atomsList &l) {
atomsList::iterator it1 = l.begin(), it2 = l.end();
for (; it1 != it2; ++it1) {
std::cout << std::get<0>(*it1) << " " << std::get<1>(*it1) << " " << std::get<2>(*it1) << "<-\n";
}
}
int main() {
std::string file = std::string("1ABS.pdb");
PDBReader pr(file);
pr.parsePDB();
std::map<int, std::string> data = pr.getData();
YAPDBR y(data);
y.asList("ALL");
atomsList l = y.asList("CA");
printList(l);
return 0;
}
|
Include the correct implementation file | //===- Linux/TimeValue.cpp - Linux TimeValue 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 Linux specific implementation of the TimeValue class.
//
//===----------------------------------------------------------------------===//
// Include the generic Unix implementation
#include "../Unix/Unix.h"
#include <sys/time.h>
namespace llvm {
using namespace sys;
//===----------------------------------------------------------------------===//
//=== WARNING: Implementation here must contain only Linux specific code
//=== and must not be generic UNIX code (see ../Unix/TimeValue.cpp)
//===----------------------------------------------------------------------===//
TimeValue TimeValue::now() {
struct timeval the_time;
timerclear(&the_time);
if (0 != ::gettimeofday(&the_time,0))
ThrowErrno("Couldn't obtain time of day");
return TimeValue(
static_cast<TimeValue::SecondsType>( the_time.tv_sec ),
static_cast<TimeValue::NanoSecondsType>( the_time.tv_usec *
NANOSECONDS_PER_MICROSECOND ) );
}
// vim: sw=2 smartindent smarttab tw=80 autoindent expandtab
}
| //===- Linux/TimeValue.cpp - Linux TimeValue 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 Linux specific implementation of the TimeValue class.
//
//===----------------------------------------------------------------------===//
// Include the generic Unix implementation
#include "../Unix/TimeValue.cpp"
#include <sys/time.h>
namespace llvm {
using namespace sys;
//===----------------------------------------------------------------------===//
//=== WARNING: Implementation here must contain only Linux specific code
//=== and must not be generic UNIX code (see ../Unix/TimeValue.cpp)
//===----------------------------------------------------------------------===//
TimeValue TimeValue::now() {
struct timeval the_time;
timerclear(&the_time);
if (0 != ::gettimeofday(&the_time,0))
ThrowErrno("Couldn't obtain time of day");
return TimeValue(
static_cast<TimeValue::SecondsType>( the_time.tv_sec ),
static_cast<TimeValue::NanoSecondsType>( the_time.tv_usec *
NANOSECONDS_PER_MICROSECOND ) );
}
// vim: sw=2 smartindent smarttab tw=80 autoindent expandtab
}
|
Enable CS for sync word detection | #include <common.hpp>
void radio_reset()
{
// reset
radio::select();
radio::wcmd<radio::SRES>();
radio::release();
radio::select();
// 433MHz center freq
radio::set<radio::FREQ2>(0x10);
radio::set<radio::FREQ1>(0xa7);
radio::set<radio::FREQ0>(0x63);
// modulation
radio::set<radio::MDMCFG2>(0x1a);
// calibration
radio::set<radio::FSCAL3>(0xea);
radio::set<radio::FSCAL2>(0x2a);
radio::set<radio::FSCAL1>(0x00);
radio::set<radio::FSCAL0>(0x1f);
radio::set<radio::TEST2>(0x81);
radio::set<radio::TEST1>(0x35);
radio::set<radio::TEST0>(0x09);
radio::set<radio::PKTCTRL1>(0x2c);
radio::set<radio::PATABLE>(0xc0);
radio::wcmd<radio::SCAL>();
radio::set<radio::MCSM1>(0x3c);
radio::set<radio::MCSM0>(0x34);
radio::set<radio::PKTLEN>(32);
radio::release();
}
| #include <common.hpp>
void radio_reset()
{
// reset
radio::select();
radio::wcmd<radio::SRES>();
radio::release();
radio::select();
// 433MHz center freq
radio::set<radio::FREQ2>(0x10);
radio::set<radio::FREQ1>(0xa7);
radio::set<radio::FREQ0>(0x63);
// modulation
radio::set<radio::MDMCFG2>(0x1e);
// calibration
radio::set<radio::FSCAL3>(0xea);
radio::set<radio::FSCAL2>(0x2a);
radio::set<radio::FSCAL1>(0x00);
radio::set<radio::FSCAL0>(0x1f);
radio::set<radio::TEST2>(0x81);
radio::set<radio::TEST1>(0x35);
radio::set<radio::TEST0>(0x09);
radio::set<radio::PKTCTRL1>(0x2c);
radio::set<radio::PATABLE>(0xc0);
radio::wcmd<radio::SCAL>();
radio::set<radio::MCSM1>(0x3c);
radio::set<radio::MCSM0>(0x34);
radio::set<radio::PKTLEN>(32);
radio::set<radio::AGCCTRL1>(0x60);
radio::release();
}
|
Update rotation test with actual checking | #include "logic.cpp"
#include <iostream>
#include <cstdlib>
int main( void );
void printCoords( block* b );
int rotationTest( void );
int main( void )
{
std::cout << "Rotation Test : " << (rotationTest())? "PASSED\n" : "FAILED\n";
exit( EXIT_SUCCESS );
}
void printCoords( block *b )
{
for( int i = 0; i < PIECES_PER_BLOCK; ++i )
{
std::cout << i << "(" << b->coord[i].x << "," << b->coord[i].y << ")" << std::endl;
}
std::cout << std::endl;
}
int rotationTest( void )
{
for( int i = 0; i < NUM_TYPES_OF_BLOCKS; ++i )
{
auto b1 = new block( i );
std::cout << i << " {" << std::endl;
printCoords( b1 );
b1->rotate();
printCoords( b1 );
b1->rotate();
printCoords( b1 );
b1->rotate();
printCoords( b1 );
b1->rotate();
printCoords( b1 );
std::cout << "}" << std::endl;
delete b1;
}
return 1;
}
| #include "logic.cpp"
#include <iostream>
#include <cstdlib>
int main( void );
void printCoords( block* b );
int rotationTest( void );
int main( void )
{
std::cout << "Rotation Test : " << (rotationTest())? "PASSED\n" : "FAILED\n";
exit( EXIT_SUCCESS );
}
void printCoords( block *b )
{
for( int i = 0; i < PIECES_PER_BLOCK; ++i )
{
std::cout << i << "(" << b->coord[i].x << "," << b->coord[i].y << ")" << std::endl;
}
std::cout << std::endl;
}
int rotationTest( void )
{
bool success = true;
for( int i = 0; i < NUM_TYPES_OF_BLOCKS; ++i )
{
auto b1 = new block( i );
auto b2 = new block( i );;
success = true;
for( int j = 0; j < 4; ++j )
{
b2->rotate();
}
for( int j = 0; j < 4; ++j )
{
success = success && b1->coord[j].x == b2->coord[j].x && b1->coord[j].y == b2->coord[j].y;
}
std::cout << i << ": " << success << std::endl;
delete b1;
}
return success;
}
|
Handle exit vs signal better. | #include <v8.h>
#include <node.h>
#include <sys/wait.h>
#include <errno.h>
using namespace v8;
using namespace node;
static Handle<Value> Waitpid(const Arguments& args) {
HandleScope scope;
int r, target, *status = NULL;
if (args[0]->IsInt32()) {
target = args[0]->Int32Value();
r = waitpid(target, status, NULL);
if (r == -1) {
perror("waitpid");
return ThrowException(Exception::Error(String::New(strerror(errno))));
}
if (WIFEXITED(status)) {
return scope.Close(Integer::New(WEXITSTATUS(status)));
}
else if (WIFSIGNALED(status)) {
return scope.Close(Integer::New(WTERMSIG(status)));
}
return scope.Close(Undefined());
}
else {
return ThrowException(Exception::Error(String::New("Not an integer.")));
}
}
extern "C" void init(Handle<Object> target) {
HandleScope scope;
NODE_SET_METHOD(target, "waitpid", Waitpid);
}
| #include <v8.h>
#include <node.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <errno.h>
using namespace v8;
using namespace node;
static Handle<Value> Waitpid(const Arguments& args) {
HandleScope scope;
int r, child, status;
if (args[0]->IsInt32()) {
child = args[0]->Int32Value();
do {
r = waitpid(child, &status, WNOHANG);
} while (r != -1);
Local<Object> result = Object::New();
if (WIFEXITED(status)) {
result->Set(String::New("exitCode"), Integer::New(WEXITSTATUS(status)));
result->Set(String::New("signalCode"), Null());
return scope.Close(result);
}
else if (WIFSIGNALED(status)) {
result->Set(String::New("exitCode"), Null());
result->Set(String::New("signalCode"), Integer::New(WTERMSIG(status)));
return scope.Close(result);
}
return scope.Close(Undefined());
}
else {
return ThrowException(Exception::Error(String::New("Not an integer.")));
}
}
extern "C" void init(Handle<Object> target) {
HandleScope scope;
NODE_SET_METHOD(target, "waitpid", Waitpid);
}
|
Remove darwin-specific section names from this test | // RUN: %clang_cc1 -triple %itanium_abi_triple -emit-llvm -main-file-name cxx-virtual-destructor-calls.cpp %s -o - -fprofile-instr-generate | FileCheck %s
struct Member {
~Member();
};
struct A {
virtual ~A();
};
struct B : A {
Member m;
virtual ~B();
};
// Complete dtor
// CHECK: @__llvm_profile_name__ZN1BD1Ev = private constant [9 x i8] c"_ZN1BD1Ev", section "__DATA,__llvm_prf_names", align 1
// Deleting dtor
// CHECK: @__llvm_profile_name__ZN1BD0Ev = private constant [9 x i8] c"_ZN1BD0Ev", section "__DATA,__llvm_prf_names", align 1
// Complete dtor counters and profile data
// CHECK: @__llvm_profile_counters__ZN1BD1Ev = private global [1 x i64] zeroinitializer, section "__DATA,__llvm_prf_cnts", align 8
// CHECK: @__llvm_profile_data__ZN1BD1Ev =
// Deleting dtor counters and profile data
// CHECK: @__llvm_profile_counters__ZN1BD0Ev = private global [1 x i64] zeroinitializer, section "__DATA,__llvm_prf_cnts", align 8
// CHECK: @__llvm_profile_data__ZN1BD0Ev =
B::~B() { }
| // RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -emit-llvm -main-file-name cxx-virtual-destructor-calls.cpp %s -o - -fprofile-instr-generate | FileCheck %s
struct Member {
~Member();
};
struct A {
virtual ~A();
};
struct B : A {
Member m;
virtual ~B();
};
// Complete dtor
// CHECK: @__llvm_profile_name__ZN1BD1Ev = private constant [9 x i8] c"_ZN1BD1Ev"
// Deleting dtor
// CHECK: @__llvm_profile_name__ZN1BD0Ev = private constant [9 x i8] c"_ZN1BD0Ev"
// Complete dtor counters and profile data
// CHECK: @__llvm_profile_counters__ZN1BD1Ev = private global [1 x i64] zeroinitializer
// CHECK: @__llvm_profile_data__ZN1BD1Ev =
// Deleting dtor counters and profile data
// CHECK: @__llvm_profile_counters__ZN1BD0Ev = private global [1 x i64] zeroinitializer
// CHECK: @__llvm_profile_data__ZN1BD0Ev =
B::~B() { }
|
Fix a crash when loading unexisting file | #include "loader.h"
#include "gridmanager.h"
#include "bytebuffer.h"
#include "file.h"
GridManager* Loader::Load()
{
size_t size;
char* buffer;
File::Load(_fileName.c_str(), buffer, size);
ByteBuffer bb(size);
bb.WriteBuffer(buffer, size);
delete[] buffer;
return GridManager::Load(bb);
}
| #include "loader.h"
#include "gridmanager.h"
#include "bytebuffer.h"
#include "file.h"
GridManager* Loader::Load()
{
size_t size;
char* buffer;
if (!File::Load(_fileName.c_str(), buffer, size))
{
delete[] buffer;
return NULL;
}
ByteBuffer bb(size);
bb.WriteBuffer(buffer, size);
delete[] buffer;
return GridManager::Load(bb);
}
|
Use System/DynamicLibrary instead of Support/DynamicLinker to implement. | //===-- PluginLoader.cpp - Implement -load command line option ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the -load <plugin> command line option handler.
//
//===----------------------------------------------------------------------===//
#define DONT_GET_PLUGIN_LOADER_OPTION
#include "llvm/Support/PluginLoader.h"
#include "llvm/Support/DynamicLinker.h"
#include <iostream>
using namespace llvm;
void PluginLoader::operator=(const std::string &Filename) {
std::string ErrorMessage;
if (LinkDynamicObject(Filename.c_str(), &ErrorMessage))
std::cerr << "Error opening '" << Filename << "': " << ErrorMessage
<< "\n -load request ignored.\n";
}
| //===-- PluginLoader.cpp - Implement -load command line option ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the -load <plugin> command line option handler.
//
//===----------------------------------------------------------------------===//
#define DONT_GET_PLUGIN_LOADER_OPTION
#include "llvm/Support/PluginLoader.h"
#include "llvm/System/DynamicLibrary.h"
#include <iostream>
using namespace llvm;
void PluginLoader::operator=(const std::string &Filename) {
std::string ErrorMessage;
try {
sys::DynamicLibrary::LoadLibraryPermanently(Filename.c_str());
} catch (const std::string& errmsg) {
if (errmsg.empty()) {
ErrorMessage = "Unknown";
} else {
ErrorMessage = errmsg;
}
}
if (!ErrorMessage.empty())
std::cerr << "Error opening '" << Filename << "': " << ErrorMessage
<< "\n -load request ignored.\n";
}
|
Use standard absl::BitGen instead of function unavailable in open-source absl | /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/tpu/graph_rewrite/distributed_tpu_rewrite_pass_internal.h"
#include <limits>
#include "absl/random/random.h"
namespace tensorflow {
namespace {
static int64 overridden_node_id = -1;
} // namespace
namespace internal {
void OverrideNodeIdForTesting(const int64 node_id) {
overridden_node_id = node_id;
}
uint64 GetNodeId() {
if (overridden_node_id > -1) {
return overridden_node_id;
} else {
return absl::Uniform(absl::SharedBitGen(), uint64{0},
std::numeric_limits<uint64>::max());
}
}
} // namespace internal
} // namespace tensorflow
| /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/tpu/graph_rewrite/distributed_tpu_rewrite_pass_internal.h"
#include <limits>
#include "absl/random/random.h"
namespace tensorflow {
namespace {
static int64 overridden_node_id = -1;
} // namespace
namespace internal {
void OverrideNodeIdForTesting(const int64 node_id) {
overridden_node_id = node_id;
}
uint64 GetNodeId() {
static absl::BitGen bitgen;
if (overridden_node_id > -1) {
return overridden_node_id;
} else {
return absl::Uniform(bitgen, uint64{0}, std::numeric_limits<uint64>::max());
}
}
} // namespace internal
} // namespace tensorflow
|
Handle some inputs special now | #ifndef INPUTHELPER_CPP
#define INPUTHELPER_CPP
#include <termios.h>
#include <iostream>
#include <cstring>
#include "InputHelper.h"
using namespace std;
void InputHelper::handleEvents(sf::RenderWindow *window)
{
m_input = '\0';
sf::Event event;
while(window->pollEvent(event))
{
switch(event.type)
{
case sf::Event::Closed:
m_input = 'c';
window->close();
break;
case sf::Event::TextEntered:
m_input = static_cast<char>(event.text.unicode);
// If the player press the backspace (enter key)
// handle it like a next line in terminal
if (m_input == 13)
{
m_input = '\n';
}
break;
case sf::Event::KeyPressed:
break;
}
}
}
int InputHelper::isKeyPressed()
{
return m_input != '\0';
}
int InputHelper::getInputChar()
{
return m_input;
}
#endif // !INPUTHELPER_CPP
| #ifndef INPUTHELPER_CPP
#define INPUTHELPER_CPP
#include <termios.h>
#include <iostream>
#include <cstring>
#include "InputHelper.h"
using namespace std;
void InputHelper::handleEvents(sf::RenderWindow *window)
{
m_input = '\0';
sf::Event event;
while(window->pollEvent(event))
{
switch(event.type)
{
case sf::Event::Closed:
m_input = 'c';
window->close();
break;
case sf::Event::TextEntered:
cout << "Enterd Text unicode: " << event.text.unicode << endl;
m_input = static_cast<char>(event.text.unicode);
// If the player press the backspace (enter key)
// handle it like a next line in terminal
if (m_input == 13)
{
m_input = '\n';
}
// Handle a backspace press as Delete
else if (m_input == 8)
{
m_input = 127;
}
break;
case sf::Event::KeyPressed:
break;
}
}
}
int InputHelper::isKeyPressed()
{
return m_input != '\0';
}
int InputHelper::getInputChar()
{
return m_input;
}
#endif // !INPUTHELPER_CPP
|
Add a DCHECK to ECSignatureCreator::SetFactoryForTesting to help avoid use-after-free problems. | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "crypto/ec_signature_creator.h"
#include "crypto/ec_signature_creator_impl.h"
namespace crypto {
namespace {
ECSignatureCreatorFactory* g_factory_ = NULL;
} // namespace
// static
ECSignatureCreator* ECSignatureCreator::Create(ECPrivateKey* key) {
if (g_factory_)
return g_factory_->Create(key);
return new ECSignatureCreatorImpl(key);
}
// static
void ECSignatureCreator::SetFactoryForTesting(
ECSignatureCreatorFactory* factory) {
g_factory_ = factory;
}
} // namespace crypto
| // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "crypto/ec_signature_creator.h"
#include "base/logging.h"
#include "crypto/ec_signature_creator_impl.h"
namespace crypto {
namespace {
ECSignatureCreatorFactory* g_factory_ = NULL;
} // namespace
// static
ECSignatureCreator* ECSignatureCreator::Create(ECPrivateKey* key) {
if (g_factory_)
return g_factory_->Create(key);
return new ECSignatureCreatorImpl(key);
}
// static
void ECSignatureCreator::SetFactoryForTesting(
ECSignatureCreatorFactory* factory) {
// We should always clear the factory after each test to avoid
// use-after-free problems.
DCHECK(!g_factory_ || !factory);
g_factory_ = factory;
}
} // namespace crypto
|
Disable logging when running tests | /*
* Copyright 2014-2015 Adam Chyła, adam@chyla.org
* All rights reserved. Distributed under the terms of the MIT License.
*/
#include "../config.h"
#if defined(HAVE_GTEST) && defined(HAVE_GMOCK)
#include <gtest/gtest.h>
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
#else
#error Cannot make tests. Google Test or Google Mock library not found.
#endif // HAVE_BOOST_UNIT_TEST_FRAMEWORK
| /*
* Copyright 2014-2015 Adam Chyła, adam@chyla.org
* All rights reserved. Distributed under the terms of the MIT License.
*/
#include "../config.h"
#if defined(HAVE_GTEST) && defined(HAVE_GMOCK)
#include <boost/log/common.hpp>
#include <gtest/gtest.h>
int main(int argc, char **argv) {
boost::log::core::get()->set_logging_enabled(false);
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
#else
#error Cannot make tests. Google Test or Google Mock library not found.
#endif // HAVE_BOOST_UNIT_TEST_FRAMEWORK
|
Add clear button on search area | #include "includes/SWidgets/SSearchArea.hpp"
#include "includes/SMainWindow.hpp"
SSearchArea::SSearchArea(const QIcon & icon, SMainWindow * parent) :
QLineEdit(parent),
m_parent(parent),
m_icon(icon)
{
setTextMargins(18, 0, 0, 0);
connect(this, &SSearchArea::returnPressed, this, &SSearchArea::loadSearch);
}
void SSearchArea::paintEvent(QPaintEvent * event)
{
QLineEdit::paintEvent(event);
QPainter painter(this);
m_icon.paint(&painter, (height() - 16) / 2, (height() - 16) / 2, 16, 16);
}
void SSearchArea::loadSearch()
{
QString search{ text() };
search.replace(" ", "+");
m_parent->currentPage()->load(QUrl("http://www.google.com/search?q=" + search));
}
| #include "includes/SWidgets/SSearchArea.hpp"
#include "includes/SMainWindow.hpp"
SSearchArea::SSearchArea(const QIcon & icon, SMainWindow * parent) :
QLineEdit(parent),
m_parent(parent),
m_icon(icon)
{
setTextMargins(18, 0, 0, 0);
connect(this, &SSearchArea::returnPressed, this, &SSearchArea::loadSearch);
setClearButtonEnabled(true);
}
void SSearchArea::paintEvent(QPaintEvent * event)
{
QLineEdit::paintEvent(event);
QPainter painter(this);
m_icon.paint(&painter, (height() - 16) / 2, (height() - 16) / 2, 16, 16);
}
void SSearchArea::loadSearch()
{
QString search{ text() };
search.replace(" ", "+");
m_parent->currentPage()->load(QUrl("http://www.google.com/search?q=" + search));
}
|
Fix one more test on Android. | // RUN: %clangxx -O2 %s -o %t && %run %t 2>&1 | FileCheck %s
// XFAIL: android
#include <stdio.h>
// getauxval() used instead of sysconf() in GetPageSize() is defined starting
// glbc version 2.16.
#if defined(__GLIBC_PREREQ) && __GLIBC_PREREQ(2, 16)
extern "C" long sysconf(int name) {
fprintf(stderr, "sysconf wrapper called\n");
return 0;
}
#endif // defined(__GLIBC_PREREQ) && __GLIBC_PREREQ(2, 16)
int main() {
// All we need to check is that the sysconf() interceptor defined above was
// not called. Should it get called, it will crash right there, any
// instrumented code executed before sanitizer init is finished will crash
// accessing non-initialized sanitizer internals. Even if it will not crash
// in some configuration, it should never be called anyway.
fprintf(stderr, "Passed\n");
// CHECK-NOT: sysconf wrapper called
// CHECK: Passed
// CHECK-NOT: sysconf wrapper called
return 0;
}
| // RUN: %clangxx -O2 %s -o %t && %run %t 2>&1 | FileCheck %s
#include <stdio.h>
#if !defined(__GLIBC_PREREQ)
#define __GLIBC_PREREQ(a, b) 0
#endif
// getauxval() used instead of sysconf() in GetPageSize() is defined starting
// glbc version 2.16.
#if __GLIBC_PREREQ(2, 16)
extern "C" long sysconf(int name) {
fprintf(stderr, "sysconf wrapper called\n");
return 0;
}
#endif // defined(__GLIBC_PREREQ) && __GLIBC_PREREQ(2, 16)
int main() {
// All we need to check is that the sysconf() interceptor defined above was
// not called. Should it get called, it will crash right there, any
// instrumented code executed before sanitizer init is finished will crash
// accessing non-initialized sanitizer internals. Even if it will not crash
// in some configuration, it should never be called anyway.
fprintf(stderr, "Passed\n");
// CHECK-NOT: sysconf wrapper called
// CHECK: Passed
// CHECK-NOT: sysconf wrapper called
return 0;
}
|
Use xassert instead of assert | // xml_writer.cc see license.txt for copyright and terms of use
#include "xml_writer.h"
#include "xmlhelp.h" // xmlAttrDeQuote() etc.
#include "exc.h" // xBase
bool sortNameMapDomainWhenSerializing = true;
XmlWriter::XmlWriter(IdentityManager &idmgr0, ostream *out0, int &depth0, bool indent0)
: idmgr(idmgr0)
, out(out0)
, depth(depth0)
, indent(indent0)
{}
// write N spaces to OUT.
inline void writeSpaces(ostream &out, size_t n)
{
static char const spaces[] =
" "
" "
" "
" ";
static size_t const max_spaces = sizeof spaces - 1;
// If we're printing more than this many spaces it's pretty useless anyway,
// since it's only for human viewing pleasure!
while (n > max_spaces) {
out.write(spaces, max_spaces);
n -= max_spaces;
}
out.write(spaces, n);
}
void XmlWriter::newline() {
assert(out != NULL);
*out << '\n';
// FIX: turning off indentation makes the output go way faster, so
// this loop is worth optimizing, probably by printing chunks of 10
// if you can or something logarithmic like that.
if (indent) {
writeSpaces(*out, depth);
}
}
| // xml_writer.cc see license.txt for copyright and terms of use
#include "xml_writer.h"
#include "xmlhelp.h" // xmlAttrDeQuote() etc.
#include "exc.h" // xBase
bool sortNameMapDomainWhenSerializing = true;
XmlWriter::XmlWriter(IdentityManager &idmgr0, ostream *out0, int &depth0, bool indent0)
: idmgr(idmgr0)
, out(out0)
, depth(depth0)
, indent(indent0)
{}
// write N spaces to OUT.
inline void writeSpaces(ostream &out, size_t n)
{
static char const spaces[] =
" "
" "
" "
" ";
static size_t const max_spaces = sizeof spaces - 1;
// If we're printing more than this many spaces it's pretty useless anyway,
// since it's only for human viewing pleasure!
while (n > max_spaces) {
out.write(spaces, max_spaces);
n -= max_spaces;
}
out.write(spaces, n);
}
void XmlWriter::newline() {
xassert(out != NULL);
*out << '\n';
// FIX: turning off indentation makes the output go way faster, so
// this loop is worth optimizing, probably by printing chunks of 10
// if you can or something logarithmic like that.
if (indent) {
writeSpaces(*out, depth);
}
}
|
Add first test, trigger Travis CI | #define BOOST_TEST_MODULE Utility_function_tests
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_CASE( fieldListFromString_tests )
{
}
| #define BOOST_TEST_MODULE Utility_function_tests
#include <boost/test/unit_test.hpp>
#include "easyprint"
template <typename T, typename DELIMITER>
std::string easyprint_test(T&& container, DELIMITER d ){
std::stringstream ss;
print_line(ss, std::forward<T>(container), d);
return ss.str();
};
BOOST_AUTO_TEST_CASE( Print_Empty_container )
{
default_delimiter d;
BOOST_CHECK( easyprint_test(std::vector<int>({}), d) == "[]\n" );
std::cout << easyprint_test(std::vector<int>({}), d) << std::endl;
}
|
Revert "Exchange the order to load jpeg and png" | #include <dlib/image_loader/png_loader.cpp>
#include <dlib/image_saver/save_png.cpp>
#include <dlib/image_loader/jpeg_loader.cpp>
#include <dlib/image_saver/save_jpeg.cpp>
| #include <dlib/image_loader/jpeg_loader.cpp>
#include <dlib/image_saver/save_jpeg.cpp>
#include <dlib/image_loader/png_loader.cpp>
#include <dlib/image_saver/save_png.cpp>
|
Test DarwinAI save and load | #include "UnitTest++/UnitTest++.h"
#include "StrongAI/AI/DarwinAI/DarwinAI.hpp"
class MyDarwinAI : public DarwinAI
{
public:
MyDarwinAI() :
DarwinAI( 0, 1, 0, 1 )
{
}
//Select for highest output
float fitnessEval( NeuralNetAI& ai )
{
return ai.output().at( 0 );
};
};
SUITE( DarwinAITest )
{
TEST( smokeTest )
{
std::unique_ptr< DarwinAI > ai( new MyDarwinAI() );
auto output = ai->output();
CHECK_EQUAL( 1, output.size() );
ai->learn( 1 );
}
}
| #include "UnitTest++/UnitTest++.h"
#include "StrongAI/AI/DarwinAI/DarwinAI.hpp"
class MyDarwinAI : public DarwinAI
{
public:
MyDarwinAI() :
DarwinAI( 0, 1, 0, 1 )
{
}
//Select for highest output
float fitnessEval( NeuralNetAI& ai )
{
return ai.output().at( 0 );
};
private:
friend cereal::access;
template < class Archive >
void serialize( Archive & ar )
{
ar( cereal::virtual_base_class< GeneralAI >( this ) );
}
};
SUITE( DarwinAITest )
{
TEST( smokeTest )
{
std::unique_ptr< DarwinAI > ai( new MyDarwinAI() );
auto output = ai->output();
CHECK_EQUAL( 1, output.size() );
ai->learn( 1 );
}
TEST( saveAndLoad )
{
const std::string saveFileName = "MyDarwinAI.save";
MyDarwinAI originalAI;
MyDarwinAI cloneAI;
GeneralAI::save< MyDarwinAI >( originalAI, saveFileName );
GeneralAI::load< MyDarwinAI >( cloneAI, saveFileName );
const auto originalOutput = originalAI.output().front();
const auto cloneOutput = cloneAI.output().front();
const double tolerance = 0.01;
CHECK_CLOSE( originalOutput, cloneOutput, tolerance );
// Delete save file
CHECK( !remove( saveFileName.data() ) ) ;
}
}
|
Fix the test failure on msvc by specifying the triple. | // RUN: %clang_cc1 -x c++ -emit-llvm < %s | FileCheck %s
struct A { A(int); ~A(); };
int f(const A &);
// CHECK: call void @_ZN1AC1Ei
// CHECK-NEXT: call i32 @_Z1fRK1A
// CHECK-NEXT: call void @_ZN1AD1Ev
// CHECK: call void @_ZN1AC1Ei
// CHECK-NEXT: call i32 @_Z1fRK1A
// CHECK-NEXT: call void @_ZN1AD1Ev
template<typename T> void g() {
int a[f(3)];
int b[f(3)];
}
int main() { g<int>(); }
| // RUN: %clang_cc1 -x c++ -triple x86_64-pc-linux-gnu -emit-llvm < %s | FileCheck %s
struct A { A(int); ~A(); };
int f(const A &);
// CHECK: call void @_ZN1AC1Ei
// CHECK-NEXT: call i32 @_Z1fRK1A
// CHECK-NEXT: call void @_ZN1AD1Ev
// CHECK: call void @_ZN1AC1Ei
// CHECK-NEXT: call i32 @_Z1fRK1A
// CHECK-NEXT: call void @_ZN1AD1Ev
template<typename T> void g() {
int a[f(3)];
int b[f(3)];
}
int main() { g<int>(); }
|
Return original string if current language instance is NULL |
#include "U8Gettext.h"
#include <Arduino.h>
#define ENSURE(condition) do { if (!(condition)) {Serial.println("ENSURE failed at: "#condition); while(1); } } while(0)
#define SIZE_OF_ARRAY(array) (sizeof((array))/sizeof((array)[0]))
#define PTR_OFFSET_BYTES(ptr, nBytes) ((void*)(((char *)(ptr)) + (nBytes)))
#define PTR_OFFSET_BETWEEN(ptrBegin, ptrEnd) ((char*)(ptrEnd) - (char*)(ptrBegin))
extern const size_t gU8GettextLanguagesLength;
extern const U8GettextLanguage gU8GettextLanguages[];
static const char *
sU8GettextLanguage = "en_US";
const char *U8GettextSetLanguage(const char *language)
{
const char * oldLanguage = sU8GettextLanguage;
sU8GettextLanguage = language;
return oldLanguage;
}
const char *U8GettextGetLanguage()
{
return sU8GettextLanguage;
}
const char *U8Gettext(const char *str)
{
// TODO Implementation
}
|
#include "U8Gettext.h"
#include <Arduino.h>
#define ENSURE(condition) do { if (!(condition)) {Serial.println("ENSURE failed at: "#condition); while(1); } } while(0)
#define SIZE_OF_ARRAY(array) (sizeof((array))/sizeof((array)[0]))
#define PTR_OFFSET_BYTES(ptr, nBytes) ((void*)(((char *)(ptr)) + (nBytes)))
#define PTR_OFFSET_BETWEEN(ptrBegin, ptrEnd) ((char*)(ptrEnd) - (char*)(ptrBegin))
extern const size_t gU8GettextLanguagesLength;
extern const U8GettextLanguage gU8GettextLanguages[];
static const char *
sU8GettextLanguage = "en_US";
static const U8GettextLanguage *
sLanguageInstance = NULL;
const char *U8GettextSetLanguage(const char *language)
{
const char * oldLanguage = sU8GettextLanguage;
sU8GettextLanguage = language;
return oldLanguage;
}
const char *U8GettextGetLanguage()
{
return sU8GettextLanguage;
}
const char *U8Gettext(const char *str)
{
// TODO Implementation
if (!sLanguageInstance) {
return str;
}
}
|
Replace start time with end time | #include "game.h"
#include "button.h"
#include "screen.h"
#include "led.h"
#include "timer.h"
#include "const.h"
#include "logger.h"
#include "helper.h"
#include "controller.h"
namespace game {
namespace {
unsigned long startTime;
const unsigned long GAME_TIME = 3000;
unsigned int buttonsPressed = 0;
void countDown() {
screen::display("3");
helper::waitTime(1000);
screen::display("2");
helper::waitTime(1000);
screen::display("1");
helper::waitTime(1000);
}
void runMain() {
while (millis() - startTime < GAME_TIME) {
//Generate random button
int buttonNumber = random(0, constants::NUMBER_OF_LEDS - 1);
//Turn on led and wait for button press
led::turnOn(buttonNumber);
while(not button::isPressed(buttonNumber)){
controller::run();
}
led::turnOff(buttonNumber);
//Increment counter
buttonsPressed ++;
}
}
}
unsigned long getRemainingTime() {
unsigned long remainingTime = GAME_TIME - (millis() - startTime);
if (remainingTime > 0) {
return remainingTime;
}
return 0;
}
void start() {
countDown();
startTime = millis();
timer::start();
runMain();
timer::stop();
screen::display(String(buttonsPressed) + " buttons pressed");
}
}
| #include "game.h"
#include "button.h"
#include "screen.h"
#include "led.h"
#include "timer.h"
#include "const.h"
#include "logger.h"
#include "helper.h"
#include "controller.h"
namespace game {
namespace {
const unsigned long GAME_TIME = 3000;
unsigned long endTime;
unsigned int buttonsPressed = 0;
void countDown() {
screen::display("3");
helper::waitTime(1000);
screen::display("2");
helper::waitTime(1000);
screen::display("1");
helper::waitTime(1000);
}
void runMain() {
while (millis() < endTime) {
//Generate random button
int buttonNumber = random(0, constants::NUMBER_OF_LEDS - 1);
//Turn on led and wait for button press
led::turnOn(buttonNumber);
while(not button::isPressed(buttonNumber)){
controller::run();
}
led::turnOff(buttonNumber);
//Increment counter
buttonsPressed ++;
}
}
}
unsigned long getRemainingTime() {
unsigned long remainingTime = endTime - millis();
if (remainingTime > 0) {
return remainingTime;
}
return 0;
}
void start() {
countDown();
endTime = GAME_TIME + millis();
timer::start();
runMain();
timer::stop();
screen::display(String(buttonsPressed) + " buttons pressed");
}
}
|
Add information about the video url. | /**
* @file example.cpp
* @author Marcus Edel
*
* Simple random agent.
*/
#include <iostream>
#include "environment.hpp"
using namespace gym;
int main(int argc, char* argv[])
{
const std::string environment = "CartPole-v0";
const std::string host = "kurg.org";
const std::string port = "4040";
double totalReward = 0;
size_t totalSteps = 0;
Environment env(host, port, environment);
env.compression(9);
env.monitor.start("./dummy/", true, true);
env.reset();
env.render();
while (1)
{
arma::mat action = env.action_space.sample();
std::cout << "action: \n" << action << std::endl;
env.step(action);
totalReward += env.reward;
totalSteps += 1;
if (env.done)
{
break;
}
std::cout << "Current step: " << totalSteps << " current reward: "
<< totalReward << std::endl;
}
std::cout << "Instance: " << env.instance << " total steps: " << totalSteps
<< " reward: " << totalReward << std::endl;
return 0;
}
| /**
* @file example.cpp
* @author Marcus Edel
*
* Simple random agent.
*/
#include <iostream>
#include "environment.hpp"
using namespace gym;
int main(int argc, char* argv[])
{
const std::string environment = "CartPole-v0";
const std::string host = "kurg.org";
const std::string port = "4040";
double totalReward = 0;
size_t totalSteps = 0;
Environment env(host, port, environment);
env.compression(9);
env.monitor.start("./dummy/", true, true);
env.reset();
env.render();
while (1)
{
arma::mat action = env.action_space.sample();
std::cout << "action: \n" << action << std::endl;
env.step(action);
totalReward += env.reward;
totalSteps += 1;
if (env.done)
{
break;
}
std::cout << "Current step: " << totalSteps << " current reward: "
<< totalReward << std::endl;
}
std::cout << "Instance: " << env.instance << " total steps: " << totalSteps
<< " reward: " << totalReward << std::endl;
std::cout << "Video: https://kurg.org/media/gym/" << env.instance
<< " (it might take some minutes before the video is accessible)."
<< std::endl;
return 0;
}
|
Use search instead of match in pattern matcher. | #include "PatternMatcherOnig.h"
#include <cstring>
// Static member initiallization
PatternMatcherOnig::Mutex PatternMatcherOnig::mutex;
PatternMatcherOnig::PatternMatcherOnig( const char * regexp ) {
int r;
UChar * pattern = (UChar *) regexp;
OnigErrorInfo einfo;
{
ScopedLock guard(mutex);
r = onig_new(®, pattern, pattern + strlen(regexp),
ONIG_OPTION_DEFAULT, ONIG_ENCODING_UTF8, ONIG_SYNTAX_DEFAULT, &einfo);
}
if( r != ONIG_NORMAL ) {
char s[ONIG_MAX_ERROR_MESSAGE_LEN];
onig_error_code_to_str((UChar*) s, r, &einfo);
FATAL( "Onig pattern matcher error: %s\n", s);
}
}
bool PatternMatcherOnig :: Match( const char * target ) const {
int size = strlen(target);
int r = onig_match(
reg,
(UChar *) target,
(UChar *) target + size,
(UChar *) target,
NULL,
ONIG_OPTION_NONE
);
return r >= 0;
}
PatternMatcherOnig :: ~PatternMatcherOnig(void) {
onig_free(reg);
}
| #include "PatternMatcherOnig.h"
#include <cstring>
// Static member initiallization
PatternMatcherOnig::Mutex PatternMatcherOnig::mutex;
PatternMatcherOnig::PatternMatcherOnig( const char * regexp ) {
int r;
UChar * pattern = (UChar *) regexp;
OnigErrorInfo einfo;
{
ScopedLock guard(mutex);
r = onig_new(®, pattern, pattern + strlen(regexp),
ONIG_OPTION_DEFAULT, ONIG_ENCODING_UTF8, ONIG_SYNTAX_DEFAULT, &einfo);
}
if( r != ONIG_NORMAL ) {
char s[ONIG_MAX_ERROR_MESSAGE_LEN];
onig_error_code_to_str((UChar*) s, r, &einfo);
FATAL( "Onig pattern matcher error: %s\n", s);
}
}
bool PatternMatcherOnig :: Match( const char * target ) const {
int size = strlen(target);
int r = onig_search(
reg,
(UChar *) target,
(UChar *) target + size,
(UChar *) target,
(UChar *) target + size,
NULL,
ONIG_OPTION_NONE
);
return r >= 0;
}
PatternMatcherOnig :: ~PatternMatcherOnig(void) {
onig_free(reg);
}
|
Update to latest perforce change Change 14405 by waneck@wnk-asus-win-ls on 2017/12/07 17:29:14 | #include "HaxeRuntime.h"
#include "IntPtr.h"
#include "HaxeInit.h"
#include <uhx/GcRef.h>
::uhx::GcRef::GcRef() {
check_hx_init();
this->ref = ::uhx::expose::GcRefStatic::init();
}
::uhx::GcRef::~GcRef() {
::uhx::expose::GcRefStatic::destruct(this->ref);
}
::uhx::GcRef::GcRef(const GcRef& rhs) {
this->ref = ::uhx::expose::GcRefStatic::init();
this->set(const_cast<GcRef&>(rhs).get());
}
void ::uhx::GcRef::set(unreal::UIntPtr val) {
::uhx::expose::GcRefStatic::set(this->ref, val);
}
unreal::UIntPtr uhx::GcRef::get() const {
return ::uhx::expose::GcRefStatic::get(this->ref);
}
| #include "HaxeRuntime.h"
#include "CoreMinimal.h"
#include "IntPtr.h"
#include "HaxeInit.h"
#include "uhx/GcRef.h"
#include "CoreGlobals.h"
::uhx::GcRef::GcRef() {
if (!GIsRetrievingVTablePtr) {
check_hx_init();
this->ref = ::uhx::expose::GcRefStatic::init();
} else {
this->ref = 0;
}
}
::uhx::GcRef::~GcRef() {
if (this->ref != 0) {
::uhx::expose::GcRefStatic::destruct(this->ref);
}
}
::uhx::GcRef::GcRef(const GcRef& rhs) {
if (rhs.ref != 0) {
this->ref = ::uhx::expose::GcRefStatic::init();
this->set(const_cast<GcRef&>(rhs).get());
} else {
this->ref = 0;
}
}
void ::uhx::GcRef::set(unreal::UIntPtr val) {
if (this->ref == 0) {
check_hx_init();
this->ref = ::uhx::expose::GcRefStatic::init();
}
::uhx::expose::GcRefStatic::set(this->ref, val);
}
unreal::UIntPtr uhx::GcRef::get() const {
if (this->ref == 0) {
return 0;
}
return ::uhx::expose::GcRefStatic::get(this->ref);
}
|
Add comments for "Container With Most Water" | // Source : https://oj.leetcode.com/problems/container-with-most-water/
// Author : Hao Chen
// Date : 2014-06-22
/**********************************************************************************
*
* Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai).
* n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0).
*
* Find two lines, which together with x-axis forms a container, such that the container contains the most water.
*
* Note: You may not slant the container.
*
*
**********************************************************************************/
class Solution {
public:
int maxArea(vector<int> &height) {
int area = 0;
int i = 0;
int j = height.size()-1;
while(i<j){
int a = (j-i)* (height[i]>height[j] ? height[j] : height[i]);
area = a>area ? a : area;
height[i]>height[j] ? j-- : i++;
}
return area;
}
};
| // Source : https://oj.leetcode.com/problems/container-with-most-water/
// Author : Hao Chen
// Date : 2014-06-22
/**********************************************************************************
*
* Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai).
* n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0).
*
* Find two lines, which together with x-axis forms a container, such that the container contains the most water.
*
* Note: You may not slant the container.
*
*
**********************************************************************************/
class Solution {
public:
int maxArea(vector<int> &height) {
int maxArea = 0;
// two pointers scan from two sides to middle
int left = 0;
int right = height.size()-1;
int area;
while ( left < right ){
//calculate the area
area = (right - left) * ( height[left] < height[right] ? height[left] : height[right]);
//tracking the maxium area
maxArea = area > maxArea ? area : maxArea;
// because the area is decided by the shorter edge
// so we increase the area is to increase the shorter edge
height[left] < height[right] ? left++ : right-- ;
}
return maxArea;
}
};
|
Make the test deterministic by waiting for clock to tick at least once. | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/testapp.h>
#include <vespa/vespalib/util/clock.h>
#include <vespa/fastos/thread.h>
using vespalib::Clock;
using vespalib::duration;
using vespalib::steady_time;
TEST("Test that clock is ticking forward") {
Clock clock(0.050);
FastOS_ThreadPool pool(0x10000);
ASSERT_TRUE(pool.NewThread(clock.getRunnable(), nullptr) != nullptr);
steady_time start = clock.getTimeNS();
std::this_thread::sleep_for(1s);
steady_time stop = clock.getTimeNS();
EXPECT_TRUE(stop > start);
std::this_thread::sleep_for(1s);
clock.stop();
steady_time stop2 = clock.getTimeNS();
EXPECT_TRUE(stop2 > stop);
EXPECT_TRUE(vespalib::count_ms(stop2 - stop) > 1000);
}
TEST_MAIN() { TEST_RUN_ALL(); } | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/testapp.h>
#include <vespa/vespalib/util/clock.h>
#include <vespa/fastos/thread.h>
using vespalib::Clock;
using vespalib::duration;
using vespalib::steady_time;
using vespalib::steady_clock;
void waitForMovement(steady_time start, Clock & clock, vespalib::duration timeout) {
steady_time startOsClock = steady_clock::now();
while ((clock.getTimeNS() <= start) && ((steady_clock::now() - startOsClock) < timeout)) {
std::this_thread::sleep_for(1ms);
}
}
TEST("Test that clock is ticking forward") {
Clock clock(0.050);
FastOS_ThreadPool pool(0x10000);
ASSERT_TRUE(pool.NewThread(clock.getRunnable(), nullptr) != nullptr);
steady_time start = clock.getTimeNS();
waitForMovement(start, clock, 10s);
steady_time stop = clock.getTimeNS();
EXPECT_TRUE(stop > start);
std::this_thread::sleep_for(1s);
start = clock.getTimeNS();
waitForMovement(start, clock, 10s);
clock.stop();
steady_time stop2 = clock.getTimeNS();
EXPECT_TRUE(stop2 > stop);
EXPECT_TRUE(vespalib::count_ms(stop2 - stop) > 1000);
}
TEST_MAIN() { TEST_RUN_ALL(); } |
Add message on self-test failure | /**
* Author: Denis Anisimov 2015
*
* Implementation of telegram bot
*
*/
#include "telegram_bot.h"
#include <chrono>
#include <thread>
#include <cpprest/http_client.h>
constexpr char kTelegramEndpoint[] = "https://api.telegram.org/bot";
TelegramBot::TelegramBot(std::string token)
: token_(token),
bot_url_(kTelegramEndpoint + token) {}
void TelegramBot::Run() {
if (!TestMe()) {
return;
}
using namespace std::literals;
while((true)) {
std::this_thread::sleep_for(2s);
}
}
bool TelegramBot::TestMe() {
bool result{false};
web::http::client::http_client client(U(bot_url_));
client.request(web::http::methods::GET, web::http::uri_builder(U("/getMe")).to_string())
.then([&result](web::http::http_response response) {
result = (response.status_code() == 200);
})
.wait();
return result;
}
| /**
* Author: Denis Anisimov 2015
*
* Implementation of telegram bot
*
*/
#include "telegram_bot.h"
#include <chrono>
#include <thread>
#include <cpprest/http_client.h>
constexpr char kTelegramEndpoint[] = "https://api.telegram.org/bot";
TelegramBot::TelegramBot(std::string token)
: token_(token),
bot_url_(kTelegramEndpoint + token) {}
void TelegramBot::Run() {
if (!TestMe()) {
std::cout << "Bot self-test using getMe method failed." << std::endl;
return;
}
using namespace std::literals;
while((true)) {
std::this_thread::sleep_for(2s);
}
}
bool TelegramBot::TestMe() {
bool result{false};
web::http::client::http_client client(U(bot_url_));
client.request(web::http::methods::GET, web::http::uri_builder(U("/getMe")).to_string())
.then([&result](web::http::http_response response) {
result = (response.status_code() == 200);
})
.wait();
return result;
}
|
Update comments and remove bogus DCHECK in windows-specific broadcasted power message status. | // Copyright (c) 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/system_monitor.h"
namespace base {
void SystemMonitor::ProcessWmPowerBroadcastMessage(int event_id) {
PowerEvent power_event;
switch (event_id) {
case PBT_APMPOWERSTATUSCHANGE:
power_event = POWER_STATE_EVENT;
break;
case PBT_APMRESUMEAUTOMATIC:
power_event = RESUME_EVENT;
break;
case PBT_APMSUSPEND:
power_event = SUSPEND_EVENT;
break;
default:
DCHECK(false);
}
ProcessPowerMessage(power_event);
}
// Function to query the system to see if it is currently running on
// battery power. Returns true if running on battery.
bool SystemMonitor::IsBatteryPower() {
SYSTEM_POWER_STATUS status;
if (!GetSystemPowerStatus(&status)) {
LOG(ERROR) << "GetSystemPowerStatus failed: " << GetLastError();
return false;
}
return (status.ACLineStatus == 0);
}
} // namespace base
| // Copyright (c) 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/system_monitor.h"
namespace base {
void SystemMonitor::ProcessWmPowerBroadcastMessage(int event_id) {
PowerEvent power_event;
switch (event_id) {
case PBT_APMPOWERSTATUSCHANGE: // The power status changed.
power_event = POWER_STATE_EVENT;
break;
case PBT_APMRESUMEAUTOMATIC: // Non-user initiated resume from suspend.
case PBT_APMRESUMESUSPEND: // User initiated resume from suspend.
power_event = RESUME_EVENT;
break;
case PBT_APMSUSPEND: // System has been suspended.
power_event = SUSPEND_EVENT;
break;
default:
return;
// Other Power Events:
// PBT_APMBATTERYLOW - removed in Vista.
// PBT_APMOEMEVENT - removed in Vista.
// PBT_APMQUERYSUSPEND - removed in Vista.
// PBT_APMQUERYSUSPENDFAILED - removed in Vista.
// PBT_APMRESUMECRITICAL - removed in Vista.
// PBT_POWERSETTINGCHANGE - user changed the power settings.
}
ProcessPowerMessage(power_event);
}
// Function to query the system to see if it is currently running on
// battery power. Returns true if running on battery.
bool SystemMonitor::IsBatteryPower() {
SYSTEM_POWER_STATUS status;
if (!GetSystemPowerStatus(&status)) {
LOG(ERROR) << "GetSystemPowerStatus failed: " << GetLastError();
return false;
}
return (status.ACLineStatus == 0);
}
} // namespace base
|
Add RTLD_NODELETE flag when closing dynamic library. | /**
* \file dynamiclibrary.cpp
* \author Thibault Schueller <ryp.sqrt@gmail.com>
* \brief DynamicLibrary class
*/
#include "dynamiclibrary.hpp"
#include "exception/dynlibexception.hpp"
DynamicLibrary::DynamicLibrary(const std::string& file)
: _file(file),
_handle(nullptr)
{}
void DynamicLibrary::open(RelocationMode mode)
{
char* err;
if (!(_handle = dlopen(_file.c_str(), static_cast<int>(mode))))
{
if ((err = dlerror()))
throw (DynLibException(std::string("dlopen(): ") + err));
else
throw (DynLibException("dlopen(): Unknown error"));
}
}
void DynamicLibrary::close()
{
if (dlclose(_handle))
throw (DynLibException(std::string("dlclose(): ") + dlerror()));
}
void* DynamicLibrary::getSymbol(const std::string& symbol)
{
void* sym;
char* err;
sym = dlsym(_handle, symbol.c_str());
if ((err = dlerror()))
throw (DynLibException(std::string("dlsym(): ") + err));
return (sym);
}
const std::string &DynamicLibrary::getFilePath() const
{
return _file;
}
| /**
* \file dynamiclibrary.cpp
* \author Thibault Schueller <ryp.sqrt@gmail.com>
* \brief DynamicLibrary class
*/
#include "dynamiclibrary.hpp"
#include "exception/dynlibexception.hpp"
DynamicLibrary::DynamicLibrary(const std::string& file)
: _file(file),
_handle(nullptr)
{}
void DynamicLibrary::open(RelocationMode mode)
{
char* err;
if (!(_handle = dlopen(_file.c_str(), static_cast<int>(mode) | RTLD_NODELETE)))
{
if ((err = dlerror()))
throw (DynLibException(std::string("dlopen(): ") + err));
else
throw (DynLibException("dlopen(): Unknown error"));
}
}
void DynamicLibrary::close()
{
if (dlclose(_handle))
throw (DynLibException(std::string("dlclose(): ") + dlerror()));
}
void* DynamicLibrary::getSymbol(const std::string& symbol)
{
void* sym;
char* err;
sym = dlsym(_handle, symbol.c_str());
if ((err = dlerror()))
throw (DynLibException(std::string("dlsym(): ") + err));
return (sym);
}
const std::string &DynamicLibrary::getFilePath() const
{
return _file;
}
|
Add an optional device_id command line argument. | #include <cuda_runtime_api.h>
#include <stdio.h>
int main(void)
{
int num_devices = 0;
cudaGetDeviceCount(&num_devices);
if(num_devices > 0)
{
cudaDeviceProp properties;
cudaGetDeviceProperties(&properties, 0);
printf("--gpu-architecture=sm_%d%d", properties.major, properties.minor);
return 0;
} // end if
return -1;
}
| #include <cuda_runtime_api.h>
#include <stdio.h>
#include <stdlib.h>
void usage(const char *name)
{
printf("usage: %s [device_id]\n", name);
}
int main(int argc, char **argv)
{
int num_devices = 0;
int device_id = 0;
if(argc == 2)
{
device_id = atoi(argv[1]);
}
else if(argc > 2)
{
usage(argv[0]);
exit(-1);
}
cudaGetDeviceCount(&num_devices);
if(num_devices > device_id)
{
cudaDeviceProp properties;
cudaGetDeviceProperties(&properties, device_id);
printf("--gpu-architecture=sm_%d%d", properties.major, properties.minor);
return 0;
} // end if
else
{
printf("No available device with id %d\n", device_id);
}
return -1;
}
|
Replace a DCHECK with DCHECK_EQ. | // 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 "base/cancellation_flag.h"
#include "base/logging.h"
namespace base {
void CancellationFlag::Set() {
#if !defined(NDEBUG)
DCHECK(set_on_ == PlatformThread::CurrentId());
#endif
base::subtle::Release_Store(&flag_, 1);
}
bool CancellationFlag::IsSet() const {
return base::subtle::Acquire_Load(&flag_) != 0;
}
} // namespace base
| // 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 "base/cancellation_flag.h"
#include "base/logging.h"
namespace base {
void CancellationFlag::Set() {
#if !defined(NDEBUG)
DCHECK_EQ(set_on_, PlatformThread::CurrentId());
#endif
base::subtle::Release_Store(&flag_, 1);
}
bool CancellationFlag::IsSet() const {
return base::subtle::Acquire_Load(&flag_) != 0;
}
} // namespace base
|
Handle the exception thrown when the parser gets invalid input (rather than getting stuck, and not proceeding to color the background) | // Copyright (C) 2015 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
#include "sstream"
#include "qtUtilities.h"
#include "CQValidatorUnit.h"
CQValidatorUnit::CQValidatorUnit(QLineEdit * parent, const char * name):
CQValidator< QLineEdit >(parent, &QLineEdit::text, name)
{
}
QValidator::State CQValidatorUnit::validate(QString & input, int & pos) const
{
State CurrentState = Invalid;
bool success = false;
std::istringstream buffer(TO_UTF8(input));
CUnitParser Parser(&buffer);
success = (Parser.yyparse() == 0);
if (success)
{
setColor(Acceptable);
CurrentState = Acceptable;
}
if (CurrentState != Acceptable)
{
setColor(Invalid);
CurrentState = Intermediate;
}
return CurrentState;
}
| // Copyright (C) 2015 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
#include "sstream"
#include "qtUtilities.h"
#include "CQValidatorUnit.h"
#include "utilities/CCopasiException.h"
CQValidatorUnit::CQValidatorUnit(QLineEdit * parent, const char * name):
CQValidator< QLineEdit >(parent, &QLineEdit::text, name)
{
}
QValidator::State CQValidatorUnit::validate(QString & input, int & pos) const
{
State CurrentState = Invalid;
bool success = false;
std::istringstream buffer(TO_UTF8(input));
CUnitParser Parser(&buffer);
try
{
success = (Parser.yyparse() == 0);
}
catch (CCopasiException & /*exception*/)
{
success = false;
}
if (success)
{
setColor(Acceptable);
CurrentState = Acceptable;
}
else
{
setColor(Invalid);
CurrentState = Intermediate;
}
return CurrentState;
}
|
Add Main Window Title + version | #include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
| #include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
setWindowTitle("CRC Calculator ver " + QString::number(MAJOR_VERSION) + '.' + QString::number(MINOR_VERSION));
}
MainWindow::~MainWindow()
{
delete ui;
}
|
Revert to BGR color on camera to accommodate OpenCV | #include "usbCamera.h"
enum Default {
DEFAULT_CAMERA_INDEX = 0,
DEFAULT_FPS = 1
};
USBCamera::USBCamera(int frameRate, int cameraIndex, string hostname):
it(nh),
videoStream(cameraIndex) {
nh.param<int>("cameraIndex", cameraIndex, DEFAULT_CAMERA_INDEX);
nh.param<int>("fps", fps, frameRate);
if (not videoStream.isOpened()) {
ROS_ERROR_STREAM("Failed to open camera device!");
ros::shutdown();
}
ros::Duration period = ros::Duration(1. / fps);
rawImgPublish = it.advertise((hostname + "/camera/image"), 2);
rosImage = boost::make_shared<cv_bridge::CvImage>();
rosImage->encoding = sensor_msgs::image_encodings::RGB8;
timer = nh.createTimer(period, &USBCamera::capture, this);
}
void USBCamera::capture(const ros::TimerEvent& te) {
videoStream >> cvImageColor;
cv::resize(cvImageColor, cvImageLR, cv::Size(320,240), cv::INTER_LINEAR);
rosImage->image = cvImageLR;
if (not rosImage->image.empty()) {
rosImage->header.stamp = ros::Time::now();
rawImgPublish.publish(rosImage->toImageMsg());
}
}
USBCamera::~USBCamera(){
videoStream.release();
}
| #include "usbCamera.h"
enum Default {
DEFAULT_CAMERA_INDEX = 0,
DEFAULT_FPS = 1
};
USBCamera::USBCamera(int frameRate, int cameraIndex, string hostname):
it(nh),
videoStream(cameraIndex) {
nh.param<int>("cameraIndex", cameraIndex, DEFAULT_CAMERA_INDEX);
nh.param<int>("fps", fps, frameRate);
if (not videoStream.isOpened()) {
ROS_ERROR_STREAM("Failed to open camera device!");
ros::shutdown();
}
ros::Duration period = ros::Duration(1. / fps);
rawImgPublish = it.advertise((hostname + "/camera/image"), 2);
rosImage = boost::make_shared<cv_bridge::CvImage>();
rosImage->encoding = sensor_msgs::image_encodings::BGR8;
timer = nh.createTimer(period, &USBCamera::capture, this);
}
void USBCamera::capture(const ros::TimerEvent& te) {
videoStream >> cvImageColor;
cv::resize(cvImageColor, cvImageLR, cv::Size(320,240), cv::INTER_LINEAR);
rosImage->image = cvImageLR;
if (not rosImage->image.empty()) {
rosImage->header.stamp = ros::Time::now();
rawImgPublish.publish(rosImage->toImageMsg());
}
}
USBCamera::~USBCamera(){
videoStream.release();
}
|
Fix dummy compressor-test executable for util -> io move. | /**
* @file compressor_test.cpp
* @author Chase Geigle
*/
#include <array>
#include <iostream>
#include <fstream>
#include "util/gzstream.h"
using namespace meta;
int main(int argc, char** argv)
{
if (argc < 3)
{
std::cerr << "Usage: " << argv[0] << " input output" << std::endl;
return 1;
}
std::array<char, 1024> buffer;
{
std::ifstream file{argv[1], std::ios::in | std::ios::binary};
util::gzofstream output{argv[2]};
while (file)
{
file.read(&buffer[0], 1024);
output.write(&buffer[0], file.gcount());
}
}
{
util::gzifstream input{argv[2]};
std::ofstream output{std::string{argv[2]} + ".decompressed",
std::ios::out | std::ios::binary};
std::string in;
while (std::getline(input, in))
{
output << in << "\n";
}
}
return 0;
}
| /**
* @file compressor_test.cpp
* @author Chase Geigle
*/
#include <array>
#include <iostream>
#include <fstream>
#include "io/gzstream.h"
using namespace meta;
int main(int argc, char** argv)
{
if (argc < 3)
{
std::cerr << "Usage: " << argv[0] << " input output" << std::endl;
return 1;
}
std::array<char, 1024> buffer;
{
std::ifstream file{argv[1], std::ios::in | std::ios::binary};
io::gzofstream output{argv[2]};
while (file)
{
file.read(&buffer[0], 1024);
output.write(&buffer[0], file.gcount());
}
}
{
io::gzifstream input{argv[2]};
std::ofstream output{std::string{argv[2]} + ".decompressed",
std::ios::out | std::ios::binary};
while (input)
{
input.read(&buffer[0], 1024);
output.write(&buffer[0], input.gcount());
}
}
return 0;
}
|
Make default Device::init() set intialized flag. | ////////////////////////////////////////////////////////////////////////////////////////////////
///
/// @file
/// @author Kuba Sejdak
/// @date 21.08.2016
///
/// @copyright This file is a part of cosmos OS. All rights reserved.
///
////////////////////////////////////////////////////////////////////////////////////////////////
#include "device.h"
namespace Filesystem {
Device::Device()
: File(DEVICE_FILE)
, m_initialized(false)
{
}
void Device::init()
{
// Empty.
}
bool Device::ioctl(uint32_t, void*)
{
return true;
}
} // namespace Filesystem
| ////////////////////////////////////////////////////////////////////////////////////////////////
///
/// @file
/// @author Kuba Sejdak
/// @date 21.08.2016
///
/// @copyright This file is a part of cosmos OS. All rights reserved.
///
////////////////////////////////////////////////////////////////////////////////////////////////
#include "device.h"
namespace Filesystem {
Device::Device()
: File(DEVICE_FILE)
, m_initialized(false)
{
}
void Device::init()
{
m_initialized = true;
}
bool Device::ioctl(uint32_t, void*)
{
return true;
}
} // namespace Filesystem
|
Remove old try for return code | //Copyright (c) 2015 Ultimaker B.V.
//UltiScanTastic is released under the terms of the AGPLv3 or higher.
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>
/*!
* \brief Runs the test cases.
*/
int main(int argc,char** argv)
{
CppUnit::TextUi::TestRunner runner;
CppUnit::TestFactoryRegistry& registry = CppUnit::TestFactoryRegistry::getRegistry();
runner.addTest(registry.makeTest());
//return runner.run("",false);
bool success = runner.run("", false);
return success ? 0 : 1;
}
| //Copyright (c) 2015 Ultimaker B.V.
//UltiScanTastic is released under the terms of the AGPLv3 or higher.
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>
/*!
* \brief Runs the test cases.
*/
int main(int argc,char** argv)
{
CppUnit::TextUi::TestRunner runner;
CppUnit::TestFactoryRegistry& registry = CppUnit::TestFactoryRegistry::getRegistry();
runner.addTest(registry.makeTest());
bool success = runner.run("", false);
return success ? 0 : 1;
}
|
Implement awesome form to detect cycles in a graph. | #include <bits/stdc++.h>
#define NUM_NODES 8
using namespace std;
vector < int > g[NUM_NODES];
int vis[NUM_NODES];
enum {WHITE, GRAY, BLACK};
/*
* o -> origin
*/
void dfs(int o){
vis [o] = GRAY; //semi-visited
for (int i = 0; i < g[o].size(); i++){
int v = g[o][i];
if (vis[v] == WHITE) dfs(v); // visit neighbors
}
cout << o << endl;
vis[o] = BLACK; //visited;
}
int main(){
g[0].push_back(1);
g[0].push_back(2);
g[0].push_back(3);
g[1].push_back(4);
g[1].push_back(5);
g[2].push_back(6);
g[3].push_back(7);
dfs(0);
return 0;
}
| #include <bits/stdc++.h>
#define NUM_NODES 20
using namespace std;
vector < int > g[NUM_NODES];
int vis[NUM_NODES];
enum {WHITE, GRAY, BLACK};
/*
* o -> origin
*/
void dfs(int o){
vis [o] = GRAY; //semi-visited
for (int i = 0; i < g[o].size(); i++){
int v = g[o][i];
if (vis[v] == GRAY) cout << "There is a cycle. to " << o << endl;
if (vis[v] == WHITE) dfs(v); // visit neighbors
}
cout << o << endl;
vis[o] = BLACK; //visited;
}
int main(){
g[0].push_back(1);
g[0].push_back(2);
g[0].push_back(3);
g[1].push_back(4);
g[1].push_back(5);
g[2].push_back(6);
g[3].push_back(7);
g[4].push_back(0);
g[6].push_back(0);
dfs(0);
return 0;
}
|
Read max number either from command line argument or ask user. | #include <iostream>
#include <cassert>
#include <cmath>
using namespace std;
int main ( int argc, char *argv[] )
{
assert ( argc == 2 );
unsigned long maxnumber = atol(argv[1]);
// Create the sieve end initialize all numbers as prime (true)
bool *numbers = new bool[maxnumber+1];
for ( unsigned long n = 0; n<=maxnumber; ++n )
numbers[n] = true;
// Set 0 and 1 as not-prime
numbers[0] = false;
numbers[1] = false;
// Lets count the found primes
unsigned long count = 0;
for ( unsigned long n = 2; n<=maxnumber; ++n )
{
if ( numbers[n] )
{
// We found a new prime
cout << n << " " << endl;
// Count it
++count;
// Delete all multiples
for ( unsigned long m = 2*n; m<=maxnumber; m+=n )
numbers[m] = false;
}
}
cout << endl;
cout << "We found " << count << " primes." << endl;
delete [] numbers;
return 0;
}
| #include <iostream>
#include <cassert>
#include <cmath>
using namespace std;
int main ( int argc, char *argv[] )
{
unsigned long maxnumber = 0;
if ( 2 == argc )
maxnumber = atol(argv[1]);
else
{
cout << "Enter the highest number to test: ";
cin >> maxnumber;
}
// Create the sieve end initialize all numbers as prime (true)
bool *numbers = new bool[maxnumber+1];
for ( unsigned long n = 0; n<=maxnumber; ++n )
numbers[n] = true;
// Set 0 and 1 as not-prime
numbers[0] = false;
numbers[1] = false;
// Lets count the found primes
unsigned long count = 0;
for ( unsigned long n = 2; n<=maxnumber; ++n )
{
if ( numbers[n] )
{
// We found a new prime
cout << n << " " << endl;
// Count it
++count;
// Delete all multiples
for ( unsigned long m = 2*n; m<=maxnumber; m+=n )
numbers[m] = false;
}
}
cout << endl;
cout << "We found " << count << " primes." << endl;
delete [] numbers;
return 0;
}
|
Comment out sample HumanDetector and SystemMonitor to show performance | #include "MyOpenCVIF.hpp"
MyOpenCVIF::MyOpenCVIF() :
m_FPSCounter(),
m_humanDetector("/usr/local/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml")
{
}
void MyOpenCVIF::ProcessFrame(Mat& frame)
{
m_FPSCounter.ProcessFrame(frame);
m_systemMonitor.ProcessFrame(frame);
m_humanDetector.ProcessFrame(frame);
m_HUD.ProcessFrame(frame);
}
| #include "MyOpenCVIF.hpp"
MyOpenCVIF::MyOpenCVIF() :
m_FPSCounter(),
m_humanDetector("/usr/local/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml")
{
}
void MyOpenCVIF::ProcessFrame(Mat& frame)
{
m_FPSCounter.ProcessFrame(frame);
//m_systemMonitor.ProcessFrame(frame);
//m_humanDetector.ProcessFrame(frame);
m_HUD.ProcessFrame(frame);
}
|
Fix bug in ball collision code where line would be placed incorrectly | #include "Pool.h"
#include <iostream>
#include <math.h>
const float Pool::BALL_RADIUS = 0.5/40;
void Pool::setWhiteBall(Vec2 whiteBall)
{
this->whiteBall = whiteBall;
}
void Pool::setTargetBall(Vec2 targetBall)
{
this->targetBall = targetBall;
}
void Pool::setPocket(Vec2 pocket)
{
this->pocket = pocket;
}
float Pool::getHitAngle()
{
std::cout << whiteBall.getString() << std::endl;
//Calculating the angle of the vector that the target needs to travel
Vec2 targetDiff = pocket - targetBall;
float targetAngle = targetDiff.getAngle();
//Calculating where the white needs to be when it hits
Vec2 whiteTarget(BALL_RADIUS * cos(targetAngle - M_PI), BALL_RADIUS * sin(targetAngle - M_PI));
whiteTarget += targetBall;
Vec2 finalDiff = whiteTarget - whiteBall;
return finalDiff.getAngle();
}
Vec2 Pool::getWhiteBall()
{
return whiteBall;
}
| #include "Pool.h"
#include <iostream>
#include <math.h>
const float Pool::BALL_RADIUS = 0.5/40;
void Pool::setWhiteBall(Vec2 whiteBall)
{
this->whiteBall = whiteBall;
}
void Pool::setTargetBall(Vec2 targetBall)
{
this->targetBall = targetBall;
}
void Pool::setPocket(Vec2 pocket)
{
this->pocket = pocket;
}
float Pool::getHitAngle()
{
std::cout << whiteBall.getString() << std::endl;
//Calculating the angle of the vector that the target needs to travel
Vec2 targetDiff = pocket - targetBall;
float targetAngle = targetDiff.getAngle();
//Calculating where the white needs to be when it hits
Vec2 whiteTarget(BALL_RADIUS * 2 * cos(targetAngle - M_PI), BALL_RADIUS * 2 * sin(targetAngle - M_PI));
whiteTarget += targetBall;
Vec2 finalDiff = whiteTarget - whiteBall;
return finalDiff.getAngle();
}
Vec2 Pool::getWhiteBall()
{
return whiteBall;
}
|
Add exit() as program terminator; remove chpl_error(), chpl_internal_error(). | /**
* Coverity Scan model
*
* Manage false positives by giving coverity some hints.
*
* Updates to this file must be manually submitted by an admin to:
*
* https://scan.coverity.com/projects/1222
*
*/
// When tag is 1 or 2, let coverity know that execution is halting. Those
// tags correspond to INT_FATAL and USR_FATAL respectively.
//
// INT_FATAL, et al, work by calling setupError and then
// handleError. setupError simply sets some static globals, then handleError
// looks at those to decide how to error. For example, when INT_FATAL calls
// handleError it will abort execution because exit_immediately is true.
//
// Here we're fibbing to coverity by telling it that setupError results in
// abort (as opposed to handleError), but the effect should be the same.
void setupError(const char *filename, int lineno, int tag) {
if (tag == 1 || tag == 2) {
__coverity_panic__();
}
}
//==============================
// runtime
//
// chpl_error() ends execution
// Note: this signature doesn't match the real one precisely, but it's
// close enough.
void chpl_error(const char* message, int lineno, const char* filename) {
__coverity_panic__();
}
// chpl_internal_error() ends execution
void chpl_internal_error(const char* message) {
__coverity_panic__();
}
| /**
* Coverity Scan model
*
* Manage false positives by giving coverity some hints.
*
* Updates to this file must be manually submitted by an admin to:
*
* https://scan.coverity.com/projects/1222
*
*/
// When tag is 1 or 2, let coverity know that execution is halting. Those
// tags correspond to INT_FATAL and USR_FATAL respectively.
//
// INT_FATAL, et al, work by calling setupError and then
// handleError. setupError simply sets some static globals, then handleError
// looks at those to decide how to error. For example, when INT_FATAL calls
// handleError it will abort execution because exit_immediately is true.
//
// Here we're fibbing to coverity by telling it that setupError results in
// abort (as opposed to handleError), but the effect should be the same.
void setupError(const char *filename, int lineno, int tag) {
if (tag == 1 || tag == 2) {
__coverity_panic__();
}
}
//==============================
// runtime
//
//
// exit() ends execution
//
void exit(int status) {
__coverity_panic__();
}
|
Change that should have been included with earlier commit. | /*****************************************************************************
* Licensed to Qualys, Inc. (QUALYS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* QUALYS licenses this file to You 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.
****************************************************************************/
/**
* @file
* @brief IronBee++ Internals -- ModuleDelegate implementation.
* @internal
*
* @author Christopher Alfeld <calfeld@qualys.com>
**/
#include <ironbeepp/module_delegate.hpp>
namespace IronBee {
ModuleDelegate::ModuleDelegate( Module m ) :
m_module( m )
{
// nop
}
void ModuleDelegate::context_open( Context context )
{
// nop
}
void ModuleDelegate::context_close( Context context )
{
// nop
}
void ModuleDelegate::context_destroy( Context context )
{
// nop
}
} // IronBee
| /*****************************************************************************
* Licensed to Qualys, Inc. (QUALYS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* QUALYS licenses this file to You 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.
****************************************************************************/
/**
* @file
* @brief IronBee++ Internals -- ModuleDelegate implementation.
* @internal
*
* @author Christopher Alfeld <calfeld@qualys.com>
**/
#include <ironbeepp/module_delegate.hpp>
namespace IronBee {
ModuleDelegate::ModuleDelegate( Module m ) :
m_module( m )
{
// nop
}
void ModuleDelegate::context_open( Context context ) const
{
// nop
}
void ModuleDelegate::context_close( Context context ) const
{
// nop
}
void ModuleDelegate::context_destroy( Context context ) const
{
// nop
}
} // IronBee
|
Add a trivial init test | #include <gtest/gtest.h>
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| #include <gtest/gtest.h>
#if defined (WIN32)
#include <windows.h>
#include <tchar.h>
#else
#include <string.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "codec_def.h"
#include "codec_app_def.h"
#include "codec_api.h"
class CodecTest : public ::testing::Test {
public:
CodecTest() : decoder_(NULL) {}
~CodecTest() {
if (decoder_) DestroyDecoder(decoder_);
}
void SetUp() {
long rv = CreateDecoder(&decoder_);
ASSERT_EQ(0, rv);
ASSERT_TRUE(decoder_);
}
protected:
ISVCDecoder *decoder_;
};
TEST_F(CodecTest, JustInit) {
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
Update utf_string_conversions.h path in another place | #include "common/application_info.h"
#include "base/file_version_info.h"
#include "base/memory/scoped_ptr.h"
#include "base/utf_string_conversions.h"
namespace brightray {
std::string GetApplicationName() {
auto info = make_scoped_ptr(FileVersionInfo::CreateFileVersionInfoForModule(GetModuleHandle(nullptr)));
return UTF16ToUTF8(info->product_name());
}
std::string GetApplicationVersion() {
auto info = make_scoped_ptr(FileVersionInfo::CreateFileVersionInfoForModule(GetModuleHandle(nullptr)));
return UTF16ToUTF8(info->product_version());
}
}
| #include "common/application_info.h"
#include "base/file_version_info.h"
#include "base/memory/scoped_ptr.h"
#include "base/strings/utf_string_conversions.h"
namespace brightray {
std::string GetApplicationName() {
auto info = make_scoped_ptr(FileVersionInfo::CreateFileVersionInfoForModule(GetModuleHandle(nullptr)));
return UTF16ToUTF8(info->product_name());
}
std::string GetApplicationVersion() {
auto info = make_scoped_ptr(FileVersionInfo::CreateFileVersionInfoForModule(GetModuleHandle(nullptr)));
return UTF16ToUTF8(info->product_version());
}
}
|
Add a triple to fix this test on Windows | // RUN: %clang_cc1 -fsyntax-only -verify -Wold-style-cast %s
void test1() {
long x = (long)12; // expected-warning {{use of old-style cast}}
(long)x; // expected-warning {{use of old-style cast}} expected-warning {{expression result unused}}
(void**)x; // expected-warning {{use of old-style cast}} expected-warning {{expression result unused}}
long y = static_cast<long>(12);
(void)y;
typedef void VOID;
(VOID)y;
}
| // RUN: %clang_cc1 -triple x86_64-apple-darwin -fsyntax-only -verify -Wold-style-cast %s
void test1() {
long x = (long)12; // expected-warning {{use of old-style cast}}
(long)x; // expected-warning {{use of old-style cast}} expected-warning {{expression result unused}}
(void**)x; // expected-warning {{use of old-style cast}} expected-warning {{expression result unused}}
long y = static_cast<long>(12);
(void)y;
typedef void VOID;
(VOID)y;
}
|
Update copyright year to 2022 for Gridcoin About dialog box | #include "aboutdialog.h"
#include "qt/decoration.h"
#include "ui_aboutdialog.h"
#include "clientmodel.h"
AboutDialog::AboutDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::AboutDialog)
{
ui->setupUi(this);
ui->copyrightLabel->setText("Copyright 2009-2021 The Bitcoin/Peercoin/Black-Coin/Gridcoin developers");
resize(GRC::ScaleSize(this, width(), height()));
}
void AboutDialog::setModel(ClientModel *model)
{
if(model)
{
ui->versionLabel->setText(model->formatFullVersion());
}
}
AboutDialog::~AboutDialog()
{
delete ui;
}
void AboutDialog::on_buttonBox_accepted()
{
close();
}
| #include "aboutdialog.h"
#include "qt/decoration.h"
#include "ui_aboutdialog.h"
#include "clientmodel.h"
AboutDialog::AboutDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::AboutDialog)
{
ui->setupUi(this);
ui->copyrightLabel->setText("Copyright 2009-2022 The Bitcoin/Peercoin/Black-Coin/Gridcoin developers");
resize(GRC::ScaleSize(this, width(), height()));
}
void AboutDialog::setModel(ClientModel *model)
{
if(model)
{
ui->versionLabel->setText(model->formatFullVersion());
}
}
AboutDialog::~AboutDialog()
{
delete ui;
}
void AboutDialog::on_buttonBox_accepted()
{
close();
}
|
Fix typo (ordered comparison between pointer and 0). | // RUN: %clangxx_msan -O0 %s -o %t && %run %t
#include <assert.h>
#include <execinfo.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
__attribute__((noinline))
void f() {
void *buf[10];
int sz = backtrace(buf, sizeof(buf) / sizeof(*buf));
assert(sz > 0);
for (int i = 0; i < sz; ++i)
if (!buf[i])
exit(1);
char **s = backtrace_symbols(buf, sz);
assert(s > 0);
for (int i = 0; i < sz; ++i)
printf("%d\n", (int)strlen(s[i]));
}
int main(void) {
f();
return 0;
}
| // RUN: %clangxx_msan -O0 %s -o %t && %run %t
#include <assert.h>
#include <execinfo.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
__attribute__((noinline))
void f() {
void *buf[10];
int sz = backtrace(buf, sizeof(buf) / sizeof(*buf));
assert(sz > 0);
for (int i = 0; i < sz; ++i)
if (!buf[i])
exit(1);
char **s = backtrace_symbols(buf, sz);
assert(s != 0);
for (int i = 0; i < sz; ++i)
printf("%d\n", (int)strlen(s[i]));
}
int main(void) {
f();
return 0;
}
|
Fix main func of krs_servo node. forget ';'; | #include "ros/ros.h"
#include "servo_msgs/KrsServoDegree.h"
#include <string>
#include "krs_servo_driver.hpp"
class KrsServoNode {
public:
KrsServoNode();
explicit KrsServoNode(ros::NodeHandle& nh, const char* path);
private:
void krsServoDegreeCallback(const servo_msgs::KrsServoDegree::ConstPtr& msg);
ros::Subscriber sub;
KrsServoDriver krs;
};
int main(int argc, char** argv) {
ros::init(argc, argv, "krs_servo_node");
ros::NodeHandle nh;
std::string path;
nh.param<std::string>("serial_path", path, "/dev/ttyUSB0")
KrsServoNode ksn(nh, path.c_str());
ros::spin();
return 0;
}
KrsServoNode::KrsServoNode()
: krs()
{}
KrsServoNode::KrsServoNode(ros::NodeHandle& nh, const char* path)
: krs(path)
{
sub = nh.subscribe("cmd_krs", 16, &KrsServoNode::krsServoDegreeCallback, this);
}
void KrsServoNode::krsServoDegreeCallback(const servo_msgs::KrsServoDegree::ConstPtr& msg) {
krs.sendAngle(msg->id, msg->angle);
}
| #include "ros/ros.h"
#include "servo_msgs/KrsServoDegree.h"
#include <string>
#include "krs_servo_driver.hpp"
class KrsServoNode {
public:
KrsServoNode();
explicit KrsServoNode(ros::NodeHandle& nh, const char* path);
private:
void krsServoDegreeCallback(const servo_msgs::KrsServoDegree::ConstPtr& msg);
ros::Subscriber sub;
KrsServoDriver krs;
};
int main(int argc, char** argv) {
ros::init(argc, argv, "krs_servo_node");
ros::NodeHandle nh;
std::string path;
nh.param<std::string>("serial_path", path, "/dev/ttyUSB0");
KrsServoNode ksn(nh, path.c_str());
ros::spin();
return 0;
}
KrsServoNode::KrsServoNode()
: krs()
{}
KrsServoNode::KrsServoNode(ros::NodeHandle& nh, const char* path)
: krs(path)
{
sub = nh.subscribe("cmd_krs", 16, &KrsServoNode::krsServoDegreeCallback, this);
}
void KrsServoNode::krsServoDegreeCallback(const servo_msgs::KrsServoDegree::ConstPtr& msg) {
krs.sendAngle(msg->id, msg->angle);
}
|
Revert test, other precision changes make it work.... still weird. | #include <stan/math/rev.hpp>
#include <gtest/gtest.h>
#include <vector>
TEST(ProbDistributionsNegBinomial2, derivatives_lccdf) {
using stan::math::neg_binomial_2_lccdf;
using stan::math::var;
std::vector<double> N{1, 2, 3};
double alpha_dbl = 8;
double beta_dbl = 1.5;
var alpha(alpha_dbl);
var beta(beta_dbl);
var val = neg_binomial_2_lccdf(N, alpha, beta);
std::vector<var> x{alpha, beta};
std::vector<double> gradients;
val.grad(x, gradients);
double epsilon = 1e-5;
double grad_diff1 = (neg_binomial_2_lccdf(N, alpha_dbl + epsilon, beta_dbl)
- neg_binomial_2_lccdf(N, alpha_dbl - epsilon, beta_dbl))
/ (2 * epsilon);
EXPECT_FLOAT_EQ(grad_diff1, gradients[0]);
double grad_diff2 = (neg_binomial_2_lccdf(N, alpha_dbl, beta_dbl + epsilon)
- neg_binomial_2_lccdf(N, alpha_dbl, beta_dbl - epsilon))
/ (2 * epsilon);
EXPECT_FLOAT_EQ(grad_diff2, gradients[1]);
}
| #include <stan/math/rev.hpp>
#include <gtest/gtest.h>
#include <vector>
TEST(ProbDistributionsNegBinomial2, derivatives_lccdf) {
using stan::math::neg_binomial_2_lccdf;
using stan::math::var;
std::vector<double> N{1, 2, 3};
double alpha_dbl = 8;
double beta_dbl = 1.5;
var alpha(alpha_dbl);
var beta(beta_dbl);
var val = neg_binomial_2_lccdf(N, alpha, beta);
std::vector<var> x{alpha, beta};
std::vector<double> gradients;
val.grad(x, gradients);
double epsilon = 1e-6;
double grad_diff1 = (neg_binomial_2_lccdf(N, alpha_dbl + epsilon, beta_dbl)
- neg_binomial_2_lccdf(N, alpha_dbl - epsilon, beta_dbl))
/ (2 * epsilon);
EXPECT_FLOAT_EQ(grad_diff1, gradients[0]);
double grad_diff2 = (neg_binomial_2_lccdf(N, alpha_dbl, beta_dbl + epsilon)
- neg_binomial_2_lccdf(N, alpha_dbl, beta_dbl - epsilon))
/ (2 * epsilon);
EXPECT_FLOAT_EQ(grad_diff2, gradients[1]);
}
|
Add a test to show bug in MTWeakPtr types. |
#include <OSGBaseInitFunctions.h>
#include <OSGNode.h>
#include <OSGNodeCore.h>
//#include <OSGRefPtr.h>
int main (int argc, char **argv)
{
OSG::osgInit(argc, argv);
// Test getting pointers
OSG::NodeRecPtr node_ptr = OSG::Node::create();
#ifdef OSG_MT_FIELDCONTAINERPTRX
OSG::Node* node_cptr = get_pointer(node_ptr);
#else
OSG::Node* node_cptr = node_ptr;
#endif
#ifdef OSG_MT_FIELDCONTAINERPTRX
OSG::NodeRecPtr node_rptr(OSG::Node::create());
node_cptr = get_pointer(node_rptr);
#endif
node_ptr = NULL;
}
|
#include <OSGBaseInitFunctions.h>
#include <OSGNode.h>
#include <OSGNodeCore.h>
//#include <OSGRefPtr.h>
int main (int argc, char **argv)
{
OSG::osgInit(argc, argv);
// Test getting pointers
OSG::NodeRecPtr node_ptr = OSG::Node::create();
#ifdef OSG_MT_FIELDCONTAINERPTRX
OSG::Node* node_cptr = get_pointer(node_ptr);
#else
OSG::Node* node_cptr = node_ptr;
#endif
#ifdef OSG_MT_FIELDCONTAINERPTRX
OSG::NodeRecPtr node_rptr(OSG::Node::create());
node_cptr = get_pointer(node_rptr);
#endif
// Test Weak ref count ptrs
{
OSG::NodeRecPtr node_ptr(OSG::Node::create());
OSG::NodeWeakPtr node_weak(node_ptr);
OSG_ASSERT(NULL != node_ptr);
OSG_ASSERT(NULL != node_weak);
node_ptr = NULL;
OSG_ASSERT(NULL == node_ptr);
OSG_ASSERT(NULL == node_weak);
}
{
OSG::NodeMTRecPtr node_ptr(OSG::Node::create());
OSG::NodeMTWeakPtr node_weak(node_ptr);
OSG_ASSERT(NULL != node_ptr);
OSG_ASSERT(NULL != node_weak);
node_ptr = NULL;
OSG_ASSERT(NULL == node_ptr);
OSG_ASSERT(NULL == node_weak);
}
node_ptr = NULL;
}
|
Add test case for reference to null pointer param check | // RUN: %clang_cc1 -analyze -analyzer-checker=core -analyzer-output=text -verify %s
struct S {
int *x;
int y;
};
S &getSomeReference();
void test(S *p) {
S &r = *p; //expected-note {{'r' initialized here}}
if (p) return;
//expected-note@-1{{Taking false branch}}
//expected-note@-2{{Assuming 'p' is null}}
r.y = 5; // expected-warning {{Access to field 'y' results in a dereference of a null pointer (loaded from variable 'r')}}
// expected-note@-1{{Access to field 'y' results in a dereference of a null pointer (loaded from variable 'r')}}
}
| // RUN: %clang_cc1 -analyze -analyzer-checker=core -analyzer-output=text -verify %s
struct S {
int *x;
int y;
};
S &getSomeReference();
void test(S *p) {
S &r = *p; //expected-note {{'r' initialized here}}
if (p) return;
//expected-note@-1{{Taking false branch}}
//expected-note@-2{{Assuming 'p' is null}}
r.y = 5; // expected-warning {{Access to field 'y' results in a dereference of a null pointer (loaded from variable 'r')}}
// expected-note@-1{{Access to field 'y' results in a dereference of a null pointer (loaded from variable 'r')}}
}
void testRefParam(int *ptr) {
int &ref = *ptr; // expected-note {{'ref' initialized here}}
if (ptr)
// expected-note@-1{{Assuming 'ptr' is null}}
// expected-note@-2{{Taking false branch}}
return;
extern void use(int &ref);
use(ref); // expected-warning{{Forming reference to null pointer}}
// expected-note@-1{{Forming reference to null pointer}}
} |
Fix file remove for 1 to 1 test | #include "one_to_one_test.h"
using namespace std;
OneToOneTest::OneToOneTest() {}
TestError OneToOneTest::setUp() {
auto & im = InstanceManager::getInstance();
im.startMs();
left = im.nextNonColidingApp();
right = im.nextNonColidingApp();
left->run();
right->run();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
importPath = "one-to-one-import.dat";
exportPath = "one-to-one-export.dat";
auto err = generateFile(importPath, (1 << 20) * 2);
if (!err.first) {
return err;
}
return TestError{true, ""};
}
TestError OneToOneTest::tearDown() {
InstanceManager::getInstance().clear();
return TestError{true, ""};
}
TestError OneToOneTest::run() {
if (!left->importFile(importPath)) {
return TestError{false, ""};
}
if (!left->exportFile(importPath, exportPath)) {
return TestError{false, ""};
}
auto err = removeFile(importPath);
if (!err.first) {
return err;
}
return filesEqual(importPath, exportPath);
}
| #include "one_to_one_test.h"
using namespace std;
OneToOneTest::OneToOneTest() {}
TestError OneToOneTest::setUp() {
auto & im = InstanceManager::getInstance();
im.startMs();
left = im.nextNonColidingApp();
right = im.nextNonColidingApp();
left->run();
right->run();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
importPath = "one-to-one-import.dat";
exportPath = "one-to-one-export.dat";
auto err = generateFile(importPath, (1 << 20) * 2);
if (!err.first) {
return err;
}
string toRemove = this->importPath;
atDtor.push_back([toRemove] {
removeFile(toRemove);
});
return TestError{true, ""};
}
TestError OneToOneTest::tearDown() {
InstanceManager::getInstance().clear();
return TestError{true, ""};
}
TestError OneToOneTest::run() {
if (!left->importFile(importPath)) {
return TestError{false, ""};
}
if (!left->exportFile(importPath, exportPath)) {
return TestError{false, ""};
}
auto result = filesEqual(importPath, exportPath);
removeFile(exportPath);
return result;
}
|
Remove chain loading on test init. | #define BOOST_TEST_MODULE Gridcoin Test Suite
#include <boost/test/unit_test.hpp>
#include "db.h"
#include "main.h"
#include "wallet.h"
CWallet* pwalletMain;
CClientUIInterface uiInterface;
extern bool fPrintToConsole;
extern void noui_connect();
struct TestingSetup {
TestingSetup() {
fPrintToDebugger = true; // don't want to write to debug.log file
fUseFastIndex = true; // Don't verify block hashes when loading
noui_connect();
bitdb.MakeMock();
LoadBlockIndex(true);
bool fFirstRun;
pwalletMain = new CWallet("wallet.dat");
pwalletMain->LoadWallet(fFirstRun);
RegisterWallet(pwalletMain);
}
~TestingSetup()
{
delete pwalletMain;
pwalletMain = NULL;
bitdb.Flush(true);
}
};
BOOST_GLOBAL_FIXTURE(TestingSetup);
void Shutdown(void* parg)
{
exit(0);
}
void StartShutdown()
{
exit(0);
}
| #define BOOST_TEST_MODULE Gridcoin Test Suite
#include <boost/test/unit_test.hpp>
#include "db.h"
#include "main.h"
#include "wallet.h"
CWallet* pwalletMain;
CClientUIInterface uiInterface;
extern bool fPrintToConsole;
extern void noui_connect();
struct TestingSetup {
TestingSetup() {
fPrintToDebugger = true; // don't want to write to debug.log file
fUseFastIndex = true; // Don't verify block hashes when loading
noui_connect();
bitdb.MakeMock();
bool fFirstRun;
pwalletMain = new CWallet("wallet.dat");
pwalletMain->LoadWallet(fFirstRun);
RegisterWallet(pwalletMain);
}
~TestingSetup()
{
delete pwalletMain;
pwalletMain = NULL;
bitdb.Flush(true);
}
};
BOOST_GLOBAL_FIXTURE(TestingSetup);
void Shutdown(void* parg)
{
exit(0);
}
void StartShutdown()
{
exit(0);
}
|
Add frequence to image extraction | #include "projet.h"
#include <QtDebug>
#include <QProcess>
Projet::Projet(QString &name, QDir &workspace, QFile &video, int frequence)
{
if(workspace.exists())
{
if(video.exists())
{
if(workspace.mkdir(name))
{
_project = new QDir(workspace.path()+"/"+name);
qDebug() << _project->path();
_project->mkdir("input");
video.copy(_project->path()+"/input/video");
_video = new QFile(_project->path()+"/input/video");
QProcess process;
process.startDetached("avconv -i " + _project->path() +"/input/video -vsync 1 -r 8 -y " + _project->path() + "/input/img%d.jpg");
}
else
{
throw QString("Ce projet existe déjà");
}
}
else
{
throw QString("La vidéo n'existe pas");
}
}
else
{
throw QString("Le workspace n'existe pas");
}
}
| #include "projet.h"
#include <QtDebug>
#include <QProcess>
Projet::Projet(QString &name, QDir &workspace, QFile &video, int frequence)
{
if(workspace.exists())
{
if(video.exists())
{
if(workspace.mkdir(name))
{
_project = new QDir(workspace.path()+"/"+name);
qDebug() << _project->path();
_project->mkdir("input");
video.copy(_project->path()+"/input/video");
_video = new QFile(_project->path()+"/input/video");
QProcess process;
process.startDetached("avconv -i " + _project->path() +"/input/video -vsync 1 -r " + QString::number(frequence) + " -y " + _project->path() + "/input/img%d.jpg");
}
else
{
throw QString("Ce projet existe déjà");
}
}
else
{
throw QString("La vidéo n'existe pas");
}
}
else
{
throw QString("Le workspace n'existe pas");
}
}
|
Fix heap corruption that occurs when RenderViewHostObserver calls RenderViewHost to unregister when the latter is in its destructor. | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/render_view_host_observer.h"
#include "content/browser/renderer_host/render_view_host.h"
RenderViewHostObserver::RenderViewHostObserver(RenderViewHost* render_view_host)
: render_view_host_(render_view_host),
routing_id_(render_view_host->routing_id()) {
render_view_host_->AddObserver(this);
}
RenderViewHostObserver::~RenderViewHostObserver() {
if (render_view_host_)
render_view_host_->RemoveObserver(this);
}
void RenderViewHostObserver::RenderViewHostDestroyed() {
delete this;
}
bool RenderViewHostObserver::OnMessageReceived(const IPC::Message& message) {
return false;
}
bool RenderViewHostObserver::Send(IPC::Message* message) {
if (!render_view_host_) {
delete message;
return false;
}
return render_view_host_->Send(message);
}
void RenderViewHostObserver::RenderViewHostDestruction() {
render_view_host_->RemoveObserver(this);
RenderViewHostDestroyed();
render_view_host_ = NULL;
}
| // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/render_view_host_observer.h"
#include "content/browser/renderer_host/render_view_host.h"
RenderViewHostObserver::RenderViewHostObserver(RenderViewHost* render_view_host)
: render_view_host_(render_view_host),
routing_id_(render_view_host->routing_id()) {
render_view_host_->AddObserver(this);
}
RenderViewHostObserver::~RenderViewHostObserver() {
if (render_view_host_)
render_view_host_->RemoveObserver(this);
}
void RenderViewHostObserver::RenderViewHostDestroyed() {
delete this;
}
bool RenderViewHostObserver::OnMessageReceived(const IPC::Message& message) {
return false;
}
bool RenderViewHostObserver::Send(IPC::Message* message) {
if (!render_view_host_) {
delete message;
return false;
}
return render_view_host_->Send(message);
}
void RenderViewHostObserver::RenderViewHostDestruction() {
render_view_host_ = NULL;
RenderViewHostDestroyed();
}
|
Abort if read syscall fails. | #include "read_private.h"
int buffered_io::init() {
int ret;
for (int i = 0; i < num; i++) {
fds[i] = open(file_names[i], flags);
if (fds[i] < 0) {
perror("open");
exit (1);
}
ret = posix_fadvise(fds[i], 0, 0, POSIX_FADV_RANDOM);
if (ret < 0) {
perror("posix_fadvise");
exit(1);
}
}
return 0;
}
ssize_t buffered_io::access(char *buf, off_t offset, ssize_t size, int access_method) {
int fd = get_fd(offset);
#ifdef STATISTICS
if (access_method == READ)
num_reads++;
struct timeval start, end;
gettimeofday(&start, NULL);
#endif
ssize_t ret;
if (access_method == WRITE)
ret = pwrite(fd, buf, size, offset);
else
ret = pread(fd, buf, size, offset);
#ifdef STATISTICS
gettimeofday(&end, NULL);
read_time += ((long) end.tv_sec - start.tv_sec) * 1000000 + end.tv_usec - start.tv_usec;
#endif
return ret;
}
| #include "read_private.h"
int buffered_io::init() {
int ret;
for (int i = 0; i < num; i++) {
fds[i] = open(file_names[i], flags);
if (fds[i] < 0) {
perror("open");
exit (1);
}
ret = posix_fadvise(fds[i], 0, 0, POSIX_FADV_RANDOM);
if (ret < 0) {
perror("posix_fadvise");
exit(1);
}
}
return 0;
}
ssize_t buffered_io::access(char *buf, off_t offset, ssize_t size, int access_method) {
int fd = get_fd(offset);
#ifdef STATISTICS
if (access_method == READ)
num_reads++;
struct timeval start, end;
gettimeofday(&start, NULL);
#endif
ssize_t ret;
if (access_method == WRITE)
ret = pwrite(fd, buf, size, offset);
else
ret = pread(fd, buf, size, offset);
if (ret < 0) {
perror("pread");
abort();
}
#ifdef STATISTICS
gettimeofday(&end, NULL);
read_time += ((long) end.tv_sec - start.tv_sec) * 1000000 + end.tv_usec - start.tv_usec;
#endif
return ret;
}
|
Save box shape to JSON. | #include "../Physics/Shape.hpp"
#include "../Util/Json.hpp"
#include "Shape.hpp"
namespace Component {
Json::Value Shape::Save() const {
Json::Value component;
Json::Value concreteShape;
switch (shape->GetKind()) {
case ::Physics::Shape::Kind::Sphere: {
auto sphereData = shape->GetSphereData();
concreteShape["radius"] = sphereData->radius;
component["sphere"] = concreteShape;
break;
}
case ::Physics::Shape::Kind::Plane: {
auto planeData = shape->GetPlaneData();
concreteShape["normal"] = Json::SaveVec3(planeData->normal);
concreteShape["planeCoeff"] = planeData->planeCoeff;
component["plane"] = concreteShape;
break;
}
}
return component;
}
std::shared_ptr<::Physics::Shape> Shape::GetShape() const {
return shape;
}
void Shape::SetShape(std::shared_ptr<::Physics::Shape> shape) {
this->shape = shape;
}
}
| #include <Utility/Log.hpp>
#include "../Physics/Shape.hpp"
#include "../Util/Json.hpp"
#include "Shape.hpp"
namespace Component {
Json::Value Shape::Save() const {
Json::Value component;
Json::Value concreteShape;
switch (shape->GetKind()) {
case Physics::Shape::Kind::Sphere: {
auto sphereData = shape->GetSphereData();
concreteShape["radius"] = sphereData->radius;
component["sphere"] = concreteShape;
break;
}
case Physics::Shape::Kind::Plane: {
auto planeData = shape->GetPlaneData();
concreteShape["normal"] = Json::SaveVec3(planeData->normal);
concreteShape["planeCoeff"] = planeData->planeCoeff;
component["plane"] = concreteShape;
break;
}
case Physics::Shape::Kind::Box: {
auto boxData = shape->GetBoxData();
concreteShape["width"] = boxData->width;
concreteShape["height"] = boxData->height;
concreteShape["depth"] = boxData->depth;
component["box"] = concreteShape;
break;
}
default:
Log(Log::ERR) << "Component::Shape::Save: Unsupported shape `" << static_cast<uint32_t>(shape->GetKind()) << "`.\n";
}
return component;
}
std::shared_ptr<Physics::Shape> Shape::GetShape() const {
return shape;
}
void Shape::SetShape(std::shared_ptr<Physics::Shape> shape) {
this->shape = shape;
}
}
|
Initialize bounding box for coordinate system node. | #include "./coordinate_system_node.h"
#include <Eigen/Core>
CoordinateSystemNode::CoordinateSystemNode()
{
persistable = false;
x = std::make_shared<Graphics::Connector>(Eigen::Vector3f(0, 0, 0),
Eigen::Vector3f(1, 0, 0));
x->color = Eigen::Vector4f(1, 0, 0, 1);
y = std::make_shared<Graphics::Connector>(Eigen::Vector3f(0, 0, 0),
Eigen::Vector3f(0, 1, 0));
y->color = Eigen::Vector4f(0, 1, 0, 1);
z = std::make_shared<Graphics::Connector>(Eigen::Vector3f(0, 0, 0),
Eigen::Vector3f(0, 0, 1));
z->color = Eigen::Vector4f(0, 0, 1, 1);
}
CoordinateSystemNode::~CoordinateSystemNode()
{
}
void CoordinateSystemNode::render(Graphics::Gl *gl,
std::shared_ptr<Graphics::Managers> managers,
RenderData renderData)
{
x->render(gl, managers, renderData);
y->render(gl, managers, renderData);
z->render(gl, managers, renderData);
}
| #include "./coordinate_system_node.h"
#include <Eigen/Core>
CoordinateSystemNode::CoordinateSystemNode()
{
persistable = false;
x = std::make_shared<Graphics::Connector>(Eigen::Vector3f(0, 0, 0),
Eigen::Vector3f(1, 0, 0));
x->color = Eigen::Vector4f(1, 0, 0, 1);
y = std::make_shared<Graphics::Connector>(Eigen::Vector3f(0, 0, 0),
Eigen::Vector3f(0, 1, 0));
y->color = Eigen::Vector4f(0, 1, 0, 1);
z = std::make_shared<Graphics::Connector>(Eigen::Vector3f(0, 0, 0),
Eigen::Vector3f(0, 0, 1));
z->color = Eigen::Vector4f(0, 0, 1, 1);
obb = Math::Obb(Eigen::Vector3f(0, 0, 0), Eigen::Vector3f(1, 1, 1),
Eigen::Matrix3f::Identity());
}
CoordinateSystemNode::~CoordinateSystemNode()
{
}
void CoordinateSystemNode::render(Graphics::Gl *gl,
std::shared_ptr<Graphics::Managers> managers,
RenderData renderData)
{
x->render(gl, managers, renderData);
y->render(gl, managers, renderData);
z->render(gl, managers, renderData);
}
|
Fix contact link (Thanks SippieCup) | /*
Name: Velvet
Author: Alvy Piper (no contact email currently)
CSGO adaptation: aixxe <aixxe@skyenet.org>
Copyright: 2015
Usage: More complex than GreenTea and also SDKless. A simple internal cheat with bunnyhop and norecoil, written for CSPromod BETA 1.10b for fun.
Using content created by: Casual_Hacker ( http://www.unknowncheats.me/forum/member239231.html ), NanoCat, and Valve.
Any content creator that wants their work removed can contact me on UnknownCheats for now. ( http://www.unknowncheats.me/forum/member334125.html )
Feel free to redistribute, modify, and share. Please give credit where it is due, though.
*/
#include "velvet.h"
using namespace velvet;
void inject() //TODO: Change this with init::finalize in DLLMain.
{
init::finalize();
}
bool __stdcall entry(HINSTANCE inst, DWORD reason, LPVOID reserved)
{
if (reason == 1)
{
DisableThreadLibraryCalls(inst);
CreateThread(0, 0, (LPTHREAD_START_ROUTINE) inject, 0, 0, 0);
}
TerminateThread(inject, 0);
return 1;
} | /*
Name: Velvet
Author: Alvy Piper (no contact email currently)
CSGO adaptation: aixxe <aixxe@skyenet.org>
Copyright: 2015
Usage: More complex than GreenTea and also SDKless. A simple internal cheat with bunnyhop and norecoil, written for CSPromod BETA 1.10b for fun.
Using content created by: Casual_Hacker ( http://www.unknowncheats.me/forum/member239231.html ), NanoCat, and Valve.
Any content creator that wants their work removed can contact me on UnknownCheats for now. ( http://www.unknowncheats.me/forum/members/334125.html )
Feel free to redistribute, modify, and share. Please give credit where it is due, though.
*/
#include "velvet.h"
using namespace velvet;
void inject() //TODO: Change this with init::finalize in DLLMain.
{
init::finalize();
}
bool __stdcall entry(HINSTANCE inst, DWORD reason, LPVOID reserved)
{
if (reason == 1)
{
DisableThreadLibraryCalls(inst);
CreateThread(0, 0, (LPTHREAD_START_ROUTINE) inject, 0, 0, 0);
}
TerminateThread(inject, 0);
return 1;
}
|
Remove incorrect credit of authorship. | //---------------------------- parameter_handler_1.cc ---------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 2002, 2003 by the deal.II authors and Anna Schneebeli
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------- parameter_handler_1.cc ---------------------------
// check the Patterns::List pattern
#include <base/logstream.h>
#include <base/parameter_handler.h>
#include <fstream>
void check (const char *p)
{
ParameterHandler prm;
prm.declare_entry ("test_1", "-1,0",
Patterns::List(Patterns::Integer(-1,1),2,3));
std::ifstream in(p);
prm.read_input (in);
deallog << "test_1=" << prm.get ("test_1") << std::endl;
}
int main ()
{
std::ofstream logfile("parameter_handler_1.output");
deallog.attach(logfile);
deallog.depth_console(0);
check ("parameter_handler_1.prm1");
return 0;
}
| //---------------------------- parameter_handler_1.cc ---------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 2002, 2003 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------- parameter_handler_1.cc ---------------------------
// check the Patterns::List pattern
#include <base/logstream.h>
#include <base/parameter_handler.h>
#include <fstream>
void check (const char *p)
{
ParameterHandler prm;
prm.declare_entry ("test_1", "-1,0",
Patterns::List(Patterns::Integer(-1,1),2,3));
std::ifstream in(p);
prm.read_input (in);
deallog << "test_1=" << prm.get ("test_1") << std::endl;
}
int main ()
{
std::ofstream logfile("parameter_handler_1.output");
deallog.attach(logfile);
deallog.depth_console(0);
check ("parameter_handler_1.prm1");
return 0;
}
|
Use fflush to make sure libc buffer is flushed synchronously for debugging purposes. | /*
* Copyright (c) 2012 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>
#include <fcntl.h>
#include "logging.h"
FILE *logfd = NULL;
void
ori_fuse_log(const char *what, ...)
{
if (logfd == NULL) {
logfd = fopen("fuse.log", "wb+");
if (logfd == NULL) {
perror("fopen");
exit(1);
}
}
va_list vl;
va_start(vl, what);
vfprintf(logfd, what, vl);
fsync(fileno(logfd));
}
| /*
* Copyright (c) 2012 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>
#include <fcntl.h>
#include "logging.h"
FILE *logfd = NULL;
void
ori_fuse_log(const char *what, ...)
{
if (logfd == NULL) {
logfd = fopen("fuse.log", "wb+");
if (logfd == NULL) {
perror("fopen");
exit(1);
}
}
va_list vl;
va_start(vl, what);
vfprintf(logfd, what, vl);
fflush(logfd);
}
|
Use std::random_device instead of rand() | /******************************************************************************\
* This example illustrates how to use aout. *
\ ******************************************************************************/
#include <chrono>
#include <cstdlib>
#include <iostream>
#include "caf/all.hpp"
using namespace caf;
using std::endl;
int main() {
std::srand(static_cast<unsigned>(std::time(0)));
for (int i = 1; i <= 50; ++i) {
spawn<blocking_api>([i](blocking_actor* self) {
aout(self) << "Hi there! This is actor nr. "
<< i << "!" << endl;
std::chrono::milliseconds tout{std::rand() % 1000};
self->delayed_send(self, tout, atom("done"));
self->receive(others() >> [i, self] {
aout(self) << "Actor nr. "
<< i << " says goodbye!" << endl;
});
});
}
// wait until all other actors we've spawned are done
await_all_actors_done();
// done
shutdown();
return 0;
}
| /******************************************************************************\
* This example illustrates how to use aout. *
\ ******************************************************************************/
#include <random>
#include <chrono>
#include <cstdlib>
#include <iostream>
#include "caf/all.hpp"
using namespace caf;
using std::endl;
int main() {
std::srand(static_cast<unsigned>(std::time(0)));
for (int i = 1; i <= 50; ++i) {
spawn<blocking_api>([i](blocking_actor* self) {
aout(self) << "Hi there! This is actor nr. "
<< i << "!" << endl;
std::random_device rd;
std::default_random_engine re(rd());
std::chrono::milliseconds tout{re() % 10};
self->delayed_send(self, tout, atom("done"));
self->receive(others() >> [i, self] {
aout(self) << "Actor nr. "
<< i << " says goodbye!" << endl;
});
});
}
// wait until all other actors we've spawned are done
await_all_actors_done();
// done
shutdown();
return 0;
}
|
Fix a test case that was intermittently failing. The issue was that instantiations are not stored in an order preserving structure, so the print order may be impacted. Modified test case to do two FileCheck passes to ensure that both instantiations are in the same place. | // RxUN: %clang_cc1 -ast-dump %s | FileCheck %s
// RUN: %clang_cc1 -ast-dump %s > /dev/null
template <int X, typename Y, int Z = 5>
struct foo {
int constant;
foo() {}
Y getSum() { return Y(X + Z); }
};
template <int A, typename B>
B bar() {
return B(A);
}
void baz() {
int x = bar<5, int>();
int y = foo<5, int>().getSum();
double z = foo<2, double, 3>().getSum();
}
// Template instantiation - foo
// CHECK: template <int X = 5, typename Y = int, int Z = 5> struct foo {
// CHECK: template <int X = 2, typename Y = double, int Z = 3> struct foo {
// Template definition - foo
// CHECK: template <int X, typename Y, int Z = (IntegerLiteral {{.*}} 'int' 5)
// Template instantiation - bar
// CHECK: template <int A = 5, typename B = int> int bar()
// Template definition - bar
// CHECK: template <int A, typename B> B bar()
| // RUN: %clang_cc1 -ast-dump %s > %t
// RUN: FileCheck < %t %s -check-prefix=CHECK1
// RUN: FileCheck < %t %s -check-prefix=CHECK2
template <int X, typename Y, int Z = 5>
struct foo {
int constant;
foo() {}
Y getSum() { return Y(X + Z); }
};
template <int A, typename B>
B bar() {
return B(A);
}
void baz() {
int x = bar<5, int>();
int y = foo<5, int>().getSum();
double z = foo<2, double, 3>().getSum();
}
// Template instantiation - foo
// Since the order of instantiation may vary during runs, run FileCheck twice
// to make sure each instantiation is in the correct spot.
// CHECK1: template <int X = 5, typename Y = int, int Z = 5> struct foo {
// CHECK2: template <int X = 2, typename Y = double, int Z = 3> struct foo {
// Template definition - foo
// CHECK1: template <int X, typename Y, int Z = (IntegerLiteral {{.*}} 'int' 5)
// CHECK2: template <int X, typename Y, int Z = (IntegerLiteral {{.*}} 'int' 5)
// Template instantiation - bar
// CHECK1: template <int A = 5, typename B = int> int bar()
// CHECK2: template <int A = 5, typename B = int> int bar()
// Template definition - bar
// CHECK1: template <int A, typename B> B bar()
// CHECK2: template <int A, typename B> B bar()
|
Use [] operator delete to free CPUFramebuffer buffers | #include <map>
#include <kms++util/cpuframebuffer.h>
using namespace std;
namespace kms {
CPUFramebuffer::CPUFramebuffer(uint32_t width, uint32_t height, PixelFormat format)
: m_width(width), m_height(height), m_format(format)
{
const PixelFormatInfo& format_info = get_pixel_format_info(m_format);
m_num_planes = format_info.num_planes;
for (unsigned i = 0; i < format_info.num_planes; ++i) {
const PixelFormatPlaneInfo& pi = format_info.planes[i];
FramebufferPlane& plane = m_planes[i];
plane.stride = width * pi.bitspp / 8;
plane.size = plane.stride * height/ pi.ysub;
plane.offset = 0;
plane.map = new uint8_t[plane.size];
}
}
CPUFramebuffer::~CPUFramebuffer()
{
for (unsigned i = 0; i < m_num_planes; ++i) {
FramebufferPlane& plane = m_planes[i];
delete plane.map;
}
}
}
| #include <map>
#include <kms++util/cpuframebuffer.h>
using namespace std;
namespace kms {
CPUFramebuffer::CPUFramebuffer(uint32_t width, uint32_t height, PixelFormat format)
: m_width(width), m_height(height), m_format(format)
{
const PixelFormatInfo& format_info = get_pixel_format_info(m_format);
m_num_planes = format_info.num_planes;
for (unsigned i = 0; i < format_info.num_planes; ++i) {
const PixelFormatPlaneInfo& pi = format_info.planes[i];
FramebufferPlane& plane = m_planes[i];
plane.stride = width * pi.bitspp / 8;
plane.size = plane.stride * height/ pi.ysub;
plane.offset = 0;
plane.map = new uint8_t[plane.size];
}
}
CPUFramebuffer::~CPUFramebuffer()
{
for (unsigned i = 0; i < m_num_planes; ++i) {
FramebufferPlane& plane = m_planes[i];
delete [] plane.map;
}
}
}
|
Revert 205124 "Turn on touch drag and drop and touch editing by ..." | // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/base/ui_base_switches_util.h"
#include "base/command_line.h"
#include "ui/base/ui_base_switches.h"
namespace switches {
bool IsTouchDragDropEnabled() {
#if defined(OS_CHROMEOS)
return !CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableTouchDragDrop);
#else
return CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableTouchDragDrop);
#endif
}
bool IsTouchEditingEnabled() {
#if defined(OS_CHROMEOS)
return !CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableTouchEditing);
#else
return CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableTouchEditing);
#endif
}
bool IsNewDialogStyleEnabled() {
CommandLine* command_line = CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kDisableNewDialogStyle))
return false;
if (command_line->HasSwitch(switches::kEnableNewDialogStyle))
return true;
return true;
}
} // namespace switches
| // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/base/ui_base_switches_util.h"
#include "base/command_line.h"
#include "ui/base/ui_base_switches.h"
namespace switches {
bool IsTouchDragDropEnabled() {
return CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableTouchDragDrop);
}
bool IsTouchEditingEnabled() {
return CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableTouchEditing);
}
bool IsNewDialogStyleEnabled() {
CommandLine* command_line = CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kDisableNewDialogStyle))
return false;
if (command_line->HasSwitch(switches::kEnableNewDialogStyle))
return true;
return true;
}
} // namespace switches
|
Fix memory leak in RemoteClient | #pragma GCC diagnostic ignored "-Wdeprecated"
#include "remoteclient.hpp"
#include "core/messages/client/clientmsg.hpp"
#include "core/messages/server/servermsg.hpp"
#include "core/serveriface.hpp"
namespace {
struct ClientLauncher {
void operator()(RemoteClient* c) {
c->run();
}
};
}
RemoteClient::RemoteClient(ServerIface* srv)
: m_server(srv) {}
RemoteClient::~RemoteClient() {}
ServerIface* RemoteClient::server() const {
return m_server;
}
void RemoteClient::pushMessage(ClientMsg* msg) {
uint32_t type = msg->type();
m_stream.write((char*)&type, 4);
msg->write(m_stream);
}
void RemoteClient::spinup() {
ClientLauncher launcher;
boost::thread t(launcher, this);
}
void RemoteClient::run() {
m_server->addClient(this);
while(m_stream.good()) {
uint32_t type;
m_stream.read((char*)&type, 4);
// check good again, in case read failed due to disconnect
if(m_stream.good()) {
ServerMsg *msg = ServerMsg::create(type, this);
msg->read(m_stream);
m_server->pushMessage(msg);
}
}
m_server->removeClient(this);
delete this;
}
| #pragma GCC diagnostic ignored "-Wdeprecated"
#include "remoteclient.hpp"
#include "core/messages/client/clientmsg.hpp"
#include "core/messages/server/servermsg.hpp"
#include "core/serveriface.hpp"
namespace {
struct ClientLauncher {
void operator()(RemoteClient* c) {
c->run();
}
};
}
RemoteClient::RemoteClient(ServerIface* srv)
: m_server(srv) {}
RemoteClient::~RemoteClient() {}
ServerIface* RemoteClient::server() const {
return m_server;
}
void RemoteClient::pushMessage(ClientMsg* msg) {
uint32_t type = msg->type();
m_stream.write((char*)&type, 4);
msg->write(m_stream);
delete msg;
}
void RemoteClient::spinup() {
ClientLauncher launcher;
boost::thread t(launcher, this);
}
void RemoteClient::run() {
m_server->addClient(this);
while(m_stream.good()) {
uint32_t type;
m_stream.read((char*)&type, 4);
// check good again, in case read failed due to disconnect
if(m_stream.good()) {
ServerMsg *msg = ServerMsg::create(type, this);
msg->read(m_stream);
m_server->pushMessage(msg);
}
}
m_server->removeClient(this);
delete this;
}
|
Use -emit-llvm-only instead of -emit-llvm and ignoring it. | // RUN: %clang_cc1 %s -emit-llvm -o -
// https://bugs.llvm.org/show_bug.cgi?id=38356
// We only check that we do not crash.
template <typename a, a b(unsigned), int c, unsigned...>
struct d : d<a, b, c - 1> {};
template <typename a, a b(unsigned), unsigned... e>
struct d<a, b, 0, e...> {
a f[0];
};
struct g {
static g h(unsigned);
};
struct i {
void j() const;
// Current maximum depth of recursive template instantiation is 1024,
// thus, this \/ threshold value is used here. BasePathSize in CastExpr might
// not fit it, so we are testing that we do fit it.
// If -ftemplate-depth= is provided, larger values (4096 and up) cause crashes
// elsewhere.
d<g, g::h, (1U << 10U) - 2U> f;
};
void i::j() const {
const void *k{f.f};
(void)k;
}
| // RUN: %clang_cc1 %s -emit-llvm-only -o -
// https://bugs.llvm.org/show_bug.cgi?id=38356
// We only check that we do not crash.
template <typename a, a b(unsigned), int c, unsigned...>
struct d : d<a, b, c - 1> {};
template <typename a, a b(unsigned), unsigned... e>
struct d<a, b, 0, e...> {
a f[0];
};
struct g {
static g h(unsigned);
};
struct i {
void j() const;
// Current maximum depth of recursive template instantiation is 1024,
// thus, this \/ threshold value is used here. BasePathSize in CastExpr might
// not fit it, so we are testing that we do fit it.
// If -ftemplate-depth= is provided, larger values (4096 and up) cause crashes
// elsewhere.
d<g, g::h, (1U << 10U) - 2U> f;
};
void i::j() const {
const void *k{f.f};
(void)k;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.