// 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 "content/shell/webkit_test_platform_support.h"

namespace content {

bool CheckLayoutSystemDeps() {
  return true;
}

bool WebKitTestPlatformInitialize() {
  return true;
}

}  // namespace

// 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 "content/shell/webkit_test_platform_support.h"

#include "third_party/skia/include/ports/SkTypeface_android.h"

namespace {

// The root directory on the device to which resources will be pushed. This
// value needs to be equal to that set in chromium_android.py.
#define DEVICE_SOURCE_ROOT_DIR "/data/local/tmp/content_shell/"

// Primary font configuration file on the device for Skia.
const char kPrimaryFontConfig[] =
    DEVICE_SOURCE_ROOT_DIR "android_main_fonts.xml";

// The file on the device containing the fallback font configuration for Skia.
const char kFallbackFontConfig[] =
    DEVICE_SOURCE_ROOT_DIR "android_fallback_fonts.xml";

// The directory in which fonts will be stored on the Android device.
const char kFontDirectory[] = DEVICE_SOURCE_ROOT_DIR "fonts/";

}  // namespace

namespace content {

bool CheckLayoutSystemDeps() {
  return true;
}

bool WebKitTestPlatformInitialize() {
  // Initialize Skia with the font configuration files crafted for layout tests.
  SkUseTestFontConfigFile(
      kPrimaryFontConfig, kFallbackFontConfig, kFontDirectory);

  return true;
}

}  // namespace content

content_shell: Load the correct fonts and reset hinting for Android layout tests

This fixes most of the text differences in layout tests, because Android's
default serif font is much wider than the one used on Linux. Load the
right font configuration files through Skia and set up WebKit to use
normal font hinting.

BUG=232044
R=jochen@chromium.org

Review URL: https://codereview.chromium.org/17405002

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@207536 0039d316-1c4b-4281-b951-d872f2087c98


#include "HumbugWindow.h"
#include "HumbugApplication.h"
#include "Config.h"

#ifdef Q_OS_MAC
#include "mac/Setup.h"
#endif

int main(int argc, char *argv[])
{
    HumbugApplication a(argc, argv);
    a.setApplicationName("Humbug");
    a.setApplicationVersion(HUMBUG_VERSION_STRING);

    QCoreApplication::setOrganizationName("Humbug");
    QCoreApplication::setOrganizationDomain("humbug.com");
    QCoreApplication::setApplicationName("Humbug");

    HumbugWindow w;
    if (argc == 3 && QString(argv[1]) == QString("--site")) {
        w.setUrl(QUrl(argv[2]));
    }

#ifdef Q_OS_MAC
    macMain();
#endif

    a.setMainWindow(&w);

    w.show();

    return a.exec();
}

#include "HumbugWindow.h"
#include "HumbugApplication.h"
#include "Config.h"

#ifdef Q_OS_MAC
#include "mac/Setup.h"
#endif

int main(int argc, char *argv[])
{
    HumbugApplication a(argc, argv);
    a.setApplicationName("Humbug");
    a.setApplicationVersion(HUMBUG_VERSION_STRING);

    QCoreApplication::setOrganizationName("Humbug");
    QCoreApplication::setOrganizationDomain("humbug.com");
    QCoreApplication::setApplicationName("Humbug Desktop");

    HumbugWindow w;
    if (argc == 3 && QString(argv[1]) == QString("--site")) {
        w.setUrl(QUrl(argv[2]));
    }

#ifdef Q_OS_MAC
    macMain();
#endif

    a.setMainWindow(&w);

    w.show();

    return a.exec();
}

Use a more specific application name for use in UA discrimination


#include <lua.hpp>
#include <luwra.hpp>

#include <iostream>

using namespace luwra;

static
double sum3(int a, int b, double c) {
	return (a + b) * c;
}

int main() {
	lua_State* state = luaL_newstate();
	luaL_openlibs(state);

	// Build stack
	lua_pushinteger(state, 13);
	lua_pushinteger(state, 37);
	lua_pushnumber(state, 42);

	// Each value can be retrieved individually.
	std::cout << "a = " << Value<int>::Read(state, 1) << std::endl;
	std::cout << "b = " << Value<int>::Read(state, 2) << std::endl;
	std::cout << "c = " << Value<double>::Read(state, 3) << std::endl;

	// ... which is a little cumbersome. Instead we might apply a fitting function to our stack.
	std::cout << "(a + b) * c = "
	          << Apply(state, sum3)
	          << std::endl;

	lua_close(state);
	return 0;
}

#include <lua.hpp>
#include <luwra.hpp>

#include <iostream>

using namespace luwra;

static
double sum3(int a, int b, double c) {
	return (a + b) * c;
}

int main() {
	lua_State* state = luaL_newstate();
	luaL_openlibs(state);

	// Build stack
	lua_pushinteger(state, 13);
	lua_pushinteger(state, 37);
	lua_pushnumber(state, 42);

	// Each value can be retrieved individually.
	std::cout << "a = " << Value<int>::Read(state, 1) << std::endl;
	std::cout << "b = " << Value<int>::Read(state, 2) << std::endl;
	std::cout << "c = " << Value<double>::Read(state, 3) << std::endl;

	// ... which is a little cumbersome. Instead we might apply a fitting function to our stack.
	std::cout << "(a + b) * c = "
	          << Apply(state, sum3) // Equivalent to Apply(state, 1, sum3) or Apply(state, -3, sum3)
	          << std::endl;

	lua_close(state);
	return 0;
}

examples: Add note about negative indexes when using Apply


#include <unistd.h>

#include <event/event_callback.h>
#include <event/event_main.h>

#include <io/stream_handle.h>

class Sink {
	LogHandle log_;

	StreamHandle fd_;
	Action *action_;
public:
	Sink(int fd)
	: log_("/sink"),
	  fd_(fd),
	  action_(NULL)
	{
		EventCallback *cb = callback(this, &Sink::read_complete);
		action_ = fd_.read(0, cb);
	}

	~Sink()
	{
		ASSERT(log_, action_ == NULL);
	}

	void read_complete(Event e)
	{
		action_->cancel();
		action_ = NULL;

		switch (e.type_) {
		case Event::Done:
		case Event::EOS:
			break;
		default:
			HALT(log_) << "Unexpected event: " << e;
			return;
		}

		if (e.type_ == Event::EOS) {
			SimpleCallback *cb = callback(this, &Sink::close_complete);
			action_ = fd_.close(cb);
			return;
		}

		EventCallback *cb = callback(this, &Sink::read_complete);
		action_ = fd_.read(0, cb);
	}

	void close_complete(void)
	{
		action_->cancel();
		action_ = NULL;
	}
};

int
main(void)
{
	Sink sink(STDIN_FILENO);

	event_main();
}

#include <unistd.h>

#include <event/callback_handler.h>
#include <event/event_callback.h>
#include <event/event_handler.h>
#include <event/event_main.h>

#include <io/stream_handle.h>

class Sink {
	LogHandle log_;

	StreamHandle fd_;
	CallbackHandler close_handler_;
	EventHandler read_handler_;
public:
	Sink(int fd)
	: log_("/sink"),
	  fd_(fd),
	  read_handler_()
	{
		read_handler_.handler(Event::Done, this, &Sink::read_done);
		read_handler_.handler(Event::EOS, this, &Sink::read_eos);

		close_handler_.handler(this, &Sink::close_done);

		read_handler_.wait(fd_.read(0, read_handler_.callback()));
	}

	~Sink()
	{ }

	void read_done(Event)
	{
		read_handler_.wait(fd_.read(0, read_handler_.callback()));
	}

	void read_eos(Event)
	{
		close_handler_.wait(fd_.close(close_handler_.callback()));
	}

	void close_done(void)
	{ }
};

int
main(void)
{
	Sink sink(STDIN_FILENO);

	event_main();
}

Convert to use Handlers. Could be simpler.


// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/android/sys_utils.h"

#include "base/sys_info.h"
#include "jni/SysUtils_jni.h"

// Any device that reports a physical RAM size less than this, in megabytes
// is considered 'low-end'. IMPORTANT: Read the LinkerLowMemoryThresholdTest
// comments in build/android/pylib/linker/test_case.py before modifying this
// value.
#define ANDROID_LOW_MEMORY_DEVICE_THRESHOLD_MB 512

const int64 kLowEndMemoryThreshold =
    1024 * 1024 * ANDROID_LOW_MEMORY_DEVICE_THRESHOLD_MB;

// Defined and called by JNI
static jboolean IsLowEndDevice(JNIEnv* env, jclass clazz) {
  return base::android::SysUtils::IsLowEndDevice();
}

namespace base {
namespace android {

bool SysUtils::Register(JNIEnv* env) {
  return RegisterNativesImpl(env);
}

bool SysUtils::IsLowEndDevice() {
  return SysInfo::AmountOfPhysicalMemory() <= kLowEndMemoryThreshold;
}

SysUtils::SysUtils() { }

}  // namespace android
}  // namespace base

// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/android/sys_utils.h"

#include "base/android/build_info.h"
#include "base/sys_info.h"
#include "jni/SysUtils_jni.h"

// Any device that reports a physical RAM size less than this, in megabytes
// is considered 'low-end'. IMPORTANT: Read the LinkerLowMemoryThresholdTest
// comments in build/android/pylib/linker/test_case.py before modifying this
// value.
#define ANDROID_LOW_MEMORY_DEVICE_THRESHOLD_MB 512

const int64 kLowEndMemoryThreshold =
    1024 * 1024 * ANDROID_LOW_MEMORY_DEVICE_THRESHOLD_MB;

// Only support low end device changes on builds greater than JB MR2.
const int kLowEndSdkIntThreshold = 18;

// Defined and called by JNI
static jboolean IsLowEndDevice(JNIEnv* env, jclass clazz) {
  return base::android::SysUtils::IsLowEndDevice();
}

namespace base {
namespace android {

bool SysUtils::Register(JNIEnv* env) {
  return RegisterNativesImpl(env);
}

bool SysUtils::IsLowEndDevice() {
  return SysInfo::AmountOfPhysicalMemory() <= kLowEndMemoryThreshold &&
      BuildInfo::GetInstance()->sdk_int() > kLowEndSdkIntThreshold;
}

SysUtils::SysUtils() { }

}  // namespace android
}  // namespace base

Disable low memory device check for JB and lower

Only switch to low memory device states for higher than JB.

BUG=310842
NOTRY=true

Review URL: https://codereview.chromium.org/38113005

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@230873 0039d316-1c4b-4281-b951-d872f2087c98


/******************************************************
 * 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;
}

Remove unnecessary dependency on ~~driver_node.cpp


// 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;
}

Add solution for Day 11 part two

Add solution for Day 11 part two


/**
 * Appcelerator Titanium Mobile
 * Copyright (c) 2013 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */

#include "BasicListItem.h"

using namespace bb::cascades;

BasicListItem::BasicListItem() {
    item_ = new StandardListItem();
    setRoot(item_);
}

void BasicListItem::setData(QObject* data) {
    updateImage(data->property("leftImage").value<QUrl>());
    updateTitle(data->property("title").toString());
    connect(data, SIGNAL(leftImageChanged(const QUrl&)), SLOT(updateImage(const QUrl&)));
    connect(data, SIGNAL(titleChanged(const QString&)), SLOT(updateTitle(const QString&)));
    data_->disconnect(this);
    data_ = data;
}

void BasicListItem::updateImage(const QUrl& url) {
    if (url.isEmpty()) {
        item_->resetImage();
        return;
    }
    item_->setImage(Image(url));
}

void BasicListItem::updateTitle(const QString& title) {
    item_->setTitle(title);
}

/**
 * Appcelerator Titanium Mobile
 * Copyright (c) 2013 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */

#include "BasicListItem.h"

using namespace bb::cascades;

BasicListItem::BasicListItem()
    : data_(NULL) {
    item_ = new StandardListItem();
    setRoot(item_);
}

void BasicListItem::setData(QObject* data) {
    updateImage(data->property("leftImage").value<QUrl>());
    updateTitle(data->property("title").toString());

    connect(data, SIGNAL(leftImageChanged(const QUrl&)), SLOT(updateImage(const QUrl&)));
    connect(data, SIGNAL(titleChanged(const QString&)), SLOT(updateTitle(const QString&)));

    if (data_) {
        // Remove any signals from the previous data object.
        data_->disconnect(this);
    }
    data_ = data;
}

void BasicListItem::updateImage(const QUrl& url) {
    if (url.isEmpty()) {
        item_->resetImage();
        return;
    }
    item_->setImage(Image(url));
}

void BasicListItem::updateTitle(const QString& title) {
    item_->setTitle(title);
}

Fix segfault when bad data pointer is set.


#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)
{}

Update Parameter for init data to impossible


#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;
}

Fix creating new object of incomplete type

Display should never be instantiated, as ::refresh() is pure virtual.


// 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));
}

Disable WebKitThreadTest.ExposedInChromeThread, due to subsequent assert.

BUG=46087
TEST=see bug
TBR=evan

Review URL: http://codereview.chromium.org/2777001

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@49174 0039d316-1c4b-4281-b951-d872f2087c98


#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);
  }
}

Update Problem 33. Search in Rotated Sorted Array


// 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_);
            }
        });
    }
}

Check if collider or one of it's inner objects has a controller to award a badge.


// 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_;
}

Disable ExtensionApiTest.WebSocket instead of marked as FAILS_

BUG=111165
TEST=none
TBR=hbono@chromium.org

Review URL: https://chromiumcodereview.appspot.com/9117027

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@118821 0039d316-1c4b-4281-b951-d872f2087c98


// 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 DllMain hang onto the HINSTANCE passed to it


#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;
}

Make header include compat with std.

Make header include compat with std.


// 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_;
}

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

TBR=vangelis@chromium.org
Review URL: http://codereview.chromium.org/4200006

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@64161 0039d316-1c4b-4281-b951-d872f2087c98


// 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_;
}

Disable ExtensionApiTest.Storage because it crashes the browser_tests too.

BUG:25746

Review URL: http://codereview.chromium.org/328024

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@30021 0039d316-1c4b-4281-b951-d872f2087c98


/*
 * 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);
}

Revert "Fix boolean expectation from strcmp."

This reverts commit c9a687d927e07aad1eab655ee271e00cb93adbd7.


#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 );
}

Implement adding of torrents over the commandline


#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);
}

Fix compilation error in logger test

Fix compilation error in logger test


#include "dashboardcontroller.h"
#include "serialization/result.h"

ApiMock::ResponseData ApiMock::DashboardController::get(RequestData request) {
	auto result = Html("
Hello, world
\n
This is an HTML result
");
	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);
}

Read the dashboard file and return the content

For now. This is an ugly solution that I'll have to do more
with. But it'll do for now.


#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);
}

Disable FreeRTOS task priority settings in Non-OS mode


///
/// @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

Include isqrt.hpp instead of imath.hpp

Include isqrt.hpp instead of imath.hpp


#include <QtGui/QGuiApplication>
#include <QQmlContext>
#include <QStateMachine>
#include <memory>
#include "./window.h"
#include "./demo_scene.h"
#include "./input/invoke_manager.h"
#include "./input/signal_manager.h"
#include "./input/scxml_importer.h"

int main(int argc, char **argv)
{
  QGuiApplication application(argc, argv);

  auto invokeManager = std::shared_ptr<InvokeManager>(new InvokeManager());
  auto scene = std::make_shared<DemoScene>(invokeManager);
  Window window(scene);
  window.rootContext()->setContextProperty("window", &window);
  window.setSource(QUrl("qrc:ui.qml"));

  auto signalManager = std::shared_ptr<SignalManager>(new SignalManager());
  ScxmlImporter importer(QUrl::fromLocalFile("../config/states.xml"),
                         invokeManager, signalManager);

  invokeManager->addHandler(&window);
  signalManager->addSender("KeyboardEventSender", &window);

  auto stateMachine = importer.import();

  // just for printCurrentState slot for debugging
  window.stateMachine = stateMachine;

  stateMachine->start();

  window.show();

  return application.exec();
}

#include <QtGui/QGuiApplication>
#include <QQmlContext>
#include <QStateMachine>
#include <QDebug>
#include <memory>
#include "./window.h"
#include "./demo_scene.h"
#include "./input/invoke_manager.h"
#include "./input/signal_manager.h"
#include "./input/scxml_importer.h"

int main(int argc, char **argv)
{
  qputenv("QT_MESSAGE_PATTERN",
          QString("%{time [yyyy'-'MM'-'dd' 'hh':'mm':'ss]} - %{threadid} "
                  "%{if-category}%{category}: %{endif}%{message}").toUtf8());
  QGuiApplication application(argc, argv);

  auto invokeManager = std::shared_ptr<InvokeManager>(new InvokeManager());
  auto scene = std::make_shared<DemoScene>(invokeManager);
  Window window(scene);
  window.rootContext()->setContextProperty("window", &window);
  window.setSource(QUrl("qrc:ui.qml"));

  auto signalManager = std::shared_ptr<SignalManager>(new SignalManager());
  ScxmlImporter importer(QUrl::fromLocalFile("../config/states.xml"),
                         invokeManager, signalManager);

  invokeManager->addHandler(&window);
  signalManager->addSender("KeyboardEventSender", &window);

  auto stateMachine = importer.import();

  // just for printCurrentState slot for debugging
  window.stateMachine = stateMachine;

  stateMachine->start();

  window.show();

  return application.exec();
}

Change formatting of logs. Add time and thread id.


#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;
}

Add debug logging for example code.

Add debug logging for example code.


// 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;
}

Tweak test for debug/metadata change, update to FileCheck.  Radar 7424645.

git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@105559 91177308-0d34-0410-b5e6-96231b3b80d8


// 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;
}

Extend the tests for -Wmissing-variable-declarations.

We shouldn't throw a warning when the static keyword is not present in
an anonymous namespace, just like we do for -Wmissing-prototypes.

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@290443 91177308-0d34-0410-b5e6-96231b3b80d8


#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());
    }

}

Fix error when converting Bullet quaternion to GLM quaternion.


// 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());
}

Enable WebGL in QtBrowser if able to.

Enable WebGL in QtBrowser if able to.


#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() {
}

Stop spamming number of gl calls to console.


// 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

Add an HTTP basic auth unit test for an empty username.

R=eroman
BUG=297
Review URL: http://codereview.chromium.org/8859

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@4109 0039d316-1c4b-4281-b951-d872f2087c98


#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();
}

Use emplace instead of insert

Use emplace instead of insert


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();
}

Fix build failure in test.

Fix build failure in test.


#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

Revert "Revert "Adding laser indicator""

This reverts commit 282ea0b855b20d23abed1a45d7fcfc311a9ef623.


/*=============================================================================

  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 getAbsolutePosition() providing position for hosted app


#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    widget = new QWidget(this);
    layout = new QGridLayout(widget);

    loadImageButton = new QPushButton("Load Image", widget);
    connect(loadImageButton, SIGNAL(clicked()), this, SLOT(loadImage()));
    layout->addWidget(loadImageButton);

    applyAlgorithmButton = new QPushButton("Apply Algorithm", widget);
    connect(applyAlgorithmButton, SIGNAL(clicked()), this, SLOT(applyAlgorithm()));
    layout->addWidget(applyAlgorithmButton);

    imageLabel = new QLabel(widget);
    imageLabel->setFixedSize(IMAGE_WIDTH, IMAGE_HEIGHT);
    layout->addWidget(imageLabel);

    widget->setLayout(layout);
    setCentralWidget(widget);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::loadImage()
{
    QString path = QFileDialog::getOpenFileName(this, "Open image", "C:\\Users\\frost\\Dropbox", "Images (*.png *.img *.jpg *.xpm)");

    image = new QImage(path);
    QPixmap pixmap = QPixmap::fromImage(*image);
    pixmap = pixmap.scaled(imageLabel->width(), imageLabel->height(), Qt::KeepAspectRatio);
    imageLabel->setPixmap(pixmap);
}

void MainWindow::applyAlgorithm()
{

}

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    widget = new QWidget(this);
    layout = new QGridLayout(widget);

    loadImageButton = new QPushButton("Load Image", widget);
    connect(loadImageButton, SIGNAL(clicked()), this, SLOT(loadImage()));
    layout->addWidget(loadImageButton);

    applyAlgorithmButton = new QPushButton("Apply Algorithm", widget);
    connect(applyAlgorithmButton, SIGNAL(clicked()), this, SLOT(applyAlgorithm()));
    layout->addWidget(applyAlgorithmButton);

    imageLabel = new QLabel(widget);
    imageLabel->setFixedSize(IMAGE_WIDTH, IMAGE_HEIGHT);
    layout->addWidget(imageLabel);

    widget->setLayout(layout);
    setCentralWidget(widget);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::loadImage()
{
    imageLabel->setText("loading image...");
    QString path = QFileDialog::getOpenFileName(this, "Open image", "C:\\Users\\frost\\Dropbox", "Images (*.png *.img *.jpg *.xpm)");

    image = new QImage(path);
    QPixmap pixmap = QPixmap::fromImage(*image);
    pixmap = pixmap.scaled(imageLabel->width(), imageLabel->height(), Qt::KeepAspectRatio);
    imageLabel->setPixmap(pixmap);
}

void MainWindow::applyAlgorithm()
{

}

Set a text for the label while the image is loading


#include "impl_send_posture.hpp"

#include "algorithm"

#include "std_srvs/Empty.h"

SendPostureFactory SendPostureFactory::unique;

SendPostureFactory::SendPostureFactory() : sends() {}

SendPostureFactory::~SendPostureFactory() {
  for (auto it = sends.begin(), end_it = sends.end();
       it != end_it;
       it++) {
    delete it->second;
    it->second = NULL;
  }
}

SendPosture* SendPostureFactory::get(const std::string& name, ros::NodeHandle& nh) {
  const auto& found_it = unique.sends.find(name);
  if (found_it == unique.sends.end()) return unique.create(name, nh);
  return found_it->second;
}

SendPosture* SendPostureFactory::create(const std::string& name, ros::NodeHandle& nh) {
  return NULL;
}

#include "impl_send_posture.hpp"

#include "std_srvs/Empty.h"

#include<algorithm>

SendPostureFactory SendPostureFactory::unique;

SendPostureFactory::SendPostureFactory() : sends() {}

SendPostureFactory::~SendPostureFactory() {
  for (auto it = sends.begin(), end_it = sends.end();
       it != end_it;
       it++) {
    delete it->second;
    it->second = NULL;
  }
}

SendPosture* SendPostureFactory::get(const std::string& name, ros::NodeHandle& nh) {
  const auto& found_it = unique.sends.find(name);
  if (found_it == unique.sends.end()) return unique.create(name, nh);
  return found_it->second;
}

SendPosture* SendPostureFactory::create(const std::string& name, ros::NodeHandle& nh) {
  return NULL;
}

Update header include for standard library


#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);
}

Fix missing scaling factor application

Fix missing scaling factor application


/*
 * 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;
}

}

Set pointer to null on delete.

Set pointer to null on delete.


// 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;
}

Fix compilation on case-sensitive filesystem.


#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;
}

Use <> instead "" for include local libs


//===- 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

}

Include the correct implementation file

Include the correct implementation file

git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@17778 91177308-0d34-0410-b5e6-96231b3b80d8


#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();
}

Enable CS for sync word detection

Enable CS for sync word detection


#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;
}

Update rotation test with actual checking


#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);
}

Handle exit vs signal better.

[api] Handle exit vs signal better.


#include "./transfer_function_manager.h"
#include <QLoggingCategory>
#include <stdexcept>
#include "./texture_manager.h"
#include "./texture2d.h"
#include "../utils/gradient_utils.h"

namespace Graphics
{

// QLoggingCategory tfChan("Graphics.TransferFunction");

TransferFunctionManager::TransferFunctionManager(
    std::shared_ptr<TextureManager> textureManager)
  : textureManager(textureManager)
{
}

TransferFunctionManager::~TransferFunctionManager()
{
}

int TransferFunctionManager::add(std::string path)
{
  auto vector =
      GradientUtils::loadGradientAsFloats(QString(path.c_str()), width);

  if (textureId < 0)
  {
    textureId = textureManager->addTexture(vector.data(), width, height);
    return usedRows++;
  }

  auto texture = textureManager->getTextureFor(textureId);
  texture->texSubImage2D(0, 0, ++usedRows, width, 1, GL_RGBA, GL_FLOAT,
                         vector.data());

  return usedRows;
}

TextureAddress TransferFunctionManager::getTextureAddress()
{
  return textureManager->getAddressFor(textureId);
}

}  // namespace Graphics

#include "./transfer_function_manager.h"
#include <QLoggingCategory>
#include <stdexcept>
#include "./texture_manager.h"
#include "./texture2d.h"
#include "../utils/gradient_utils.h"

namespace Graphics
{

// QLoggingCategory tfChan("Graphics.TransferFunction");

TransferFunctionManager::TransferFunctionManager(
    std::shared_ptr<TextureManager> textureManager)
  : textureManager(textureManager)
{
}

TransferFunctionManager::~TransferFunctionManager()
{
}

int TransferFunctionManager::add(std::string path)
{
  auto vector =
      GradientUtils::loadGradientAsFloats(QString(path.c_str()), width);

  if (textureId < 0)
  {
    textureId = textureManager->addTexture(vector.data(), width, height);
    return usedRows++;
  }

  auto texture = textureManager->getTextureFor(textureId);
  texture->texSubImage2D(0, 0, usedRows, width, 1, GL_RGBA, GL_FLOAT,
                         vector.data());

  return usedRows++;
}

TextureAddress TransferFunctionManager::getTextureAddress()
{
  return textureManager->getAddressFor(textureId);
}

}  // namespace Graphics

Fix error in return value from TransferFunctionManager::add.


// 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() { }

InstrProf: Remove darwin-specific section names from this test

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@237805 91177308-0d34-0410-b5e6-96231b3b80d8


#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);
}

Fix a crash when loading unexisting file


//===-- 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 System/DynamicLibrary instead of Support/DynamicLinker to implement.

git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@18356 91177308-0d34-0410-b5e6-96231b3b80d8


#include <assert.h>
#include <time.h>
#include <stdlib.h>
#include <vector>
#include "Thread/Mutex.hh"
#include "Thread/Thread.hpp"

int increment_value;

struct mock
{
  int _data;
  LilWrapper::Mutex _access;
};

void increment(struct mock *m)
{
  m->_access.lock();
  for (int i = 0; i < increment_value; i++)
    m->_data++;
  m->_access.unlock();
}

int main()
{
  mock m;

  srand(time(NULL));

  int nb = random() % 30 + 1;
  increment_value = random() % 15 + 1;
  std::vector<LilWrapper::Thread *> threads(nb);

  m._data = 0;
  for (int i = 0; i < nb; i++)
    threads[i] = new LilWrapper::Thread(&increment, &m);

  for (int i = 0; i < nb; i++)
    threads[i]->launch();

  for (int i = 0; i < nb; i++)
    threads[i]->wait();

  assert(m._data == nb * increment_value);
  return (0);
}

#include <iostream>
#include <assert.h>
#include <time.h>
#include <stdlib.h>
#include <vector>
#include "Thread/Mutex.hh"
#include "Thread/Thread.hpp"

int increment_value;

struct mock
{
  int _data;
  LilWrapper::Mutex _access;
};

void increment(mock *m)
{
  m->_access.lock();
  for (int i = 0; i < increment_value; i++)
    m->_data++;
  m->_access.unlock();
}

int main()
{
  mock m;

  srand(time(NULL));

  int thread_count = random() % 100 + 1;
  increment_value = random() % 1000 + 1;
  std::vector<LilWrapper::Thread *> threads(thread_count);

  std::cout << "Increment value   ==> " << increment_value << std::endl;
  std::cout << "Number of Threads ==> " << thread_count << std::endl;

  m._data = 0;
  for (int i = 0; i < thread_count; i++)
    threads[i] = new LilWrapper::Thread(&increment, &m);

  for (int i = 0; i < thread_count; i++)
    threads[i]->launch();

  for (int i = 0; i < thread_count; i++)
    threads[i]->wait();

  assert(m._data == thread_count * increment_value);
  return (0);
}

Add some output and make code more readable.


// Copyright (c) 2013 The Chromium Embedded Framework 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 <AtomicWebView/Internal/WebAppOther.h>
#include <AtomicWebView/Internal/WebAppRenderer.h>

using namespace Atomic;

#include "include/cef_app.h"

// Entry point function for sub-processes.
int main(int argc, char* argv[])
{
    // Provide CEF with command-line arguments.
    CefMainArgs main_args(argc, argv);

    // Parse command-line arguments.
    CefRefPtr<CefCommandLine> command_line = CefCommandLine::CreateCommandLine();
    command_line->InitFromArgv(argc, argv);

    // Create a ClientApp of the correct type.
    CefRefPtr<CefApp> app;
    WebApp::ProcessType process_type = WebApp::GetProcessType(command_line);
    if (process_type == WebApp::RendererProcess)
        app = new WebAppRenderer();
    else if (process_type == WebApp::OtherProcess)
        app = new WebAppOther();

    // Execute the secondary process.
    return CefExecuteProcess(main_args, app, NULL);
}

// Copyright (c) 2013 The Chromium Embedded Framework 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 <AtomicWebView/AtomicWebView.h>

// Entry point function for sub-processes.
int main(int argc, char* argv[])
{
    return Atomic::WebMain(argc, argv);
}

Use WebMain for web helper executable on OS X


/* 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

Use standard absl::BitGen instead of function unavailable in open-source absl

PiperOrigin-RevId: 322697824
Change-Id: I98242ddd7368d4d302e0ddea52ea5626bd064d45


#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

Handle some inputs special now

Handle some inputs special now


// 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

Add a DCHECK to ECSignatureCreator::SetFactoryForTesting to help avoid use-after-free problems.

Review URL: https://chromiumcodereview.appspot.com/10828118

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@149506 0039d316-1c4b-4281-b951-d872f2087c98


/*
 * 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

Disable logging when running tests

Disable logging when running tests