// Copyright 2019 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 "quic/masque/masque_utils.h"

namespace quic {

ParsedQuicVersionVector MasqueSupportedVersions() {
  QuicVersionInitializeSupportForIetfDraft();
  ParsedQuicVersion version = UnsupportedQuicVersion();
  for (const ParsedQuicVersion& vers : AllSupportedVersions()) {
    // Find the first version that supports IETF QUIC.
    if (vers.HasIetfQuicFrames() && vers.UsesTls()) {
      version = vers;
      break;
    }
  }
  QUICHE_CHECK(version.IsKnown());
  QuicEnableVersion(version);
  return {version};
}

QuicConfig MasqueEncapsulatedConfig() {
  QuicConfig config;
  config.SetMaxPacketSizeToSend(kMasqueMaxEncapsulatedPacketSize);
  return config;
}

std::string MasqueModeToString(MasqueMode masque_mode) {
  switch (masque_mode) {
    case MasqueMode::kInvalid:
      return "Invalid";
    case MasqueMode::kLegacy:
      return "Legacy";
    case MasqueMode::kOpen:
      return "Open";
  }
  return absl::StrCat("Unknown(", static_cast<int>(masque_mode), ")");
}

std::ostream& operator<<(std::ostream& os, const MasqueMode& masque_mode) {
  os << MasqueModeToString(masque_mode);
  return os;
}

}  // namespace quic

// Copyright 2019 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 "quic/masque/masque_utils.h"

namespace quic {

ParsedQuicVersionVector MasqueSupportedVersions() {
  QuicVersionInitializeSupportForIetfDraft();
  ParsedQuicVersionVector versions;
  for (const ParsedQuicVersion& version : AllSupportedVersions()) {
    // Use all versions that support IETF QUIC.
    if (version.UsesHttp3()) {
      QuicEnableVersion(version);
      versions.push_back(version);
    }
  }
  QUICHE_CHECK(!versions.empty());
  return versions;
}

QuicConfig MasqueEncapsulatedConfig() {
  QuicConfig config;
  config.SetMaxPacketSizeToSend(kMasqueMaxEncapsulatedPacketSize);
  return config;
}

std::string MasqueModeToString(MasqueMode masque_mode) {
  switch (masque_mode) {
    case MasqueMode::kInvalid:
      return "Invalid";
    case MasqueMode::kLegacy:
      return "Legacy";
    case MasqueMode::kOpen:
      return "Open";
  }
  return absl::StrCat("Unknown(", static_cast<int>(masque_mode), ")");
}

std::ostream& operator<<(std::ostream& os, const MasqueMode& masque_mode) {
  os << MasqueModeToString(masque_mode);
  return os;
}

}  // namespace quic

Support all HTTP/3 versions in MASQUE

Support all HTTP/3 versions in MASQUE

This means we'll use h3,h3-29 instead of just h3, and
that'll help simplify IETF MASQUE interop events.
This code is not used in production.

PiperOrigin-RevId: 360223566
Change-Id: I519f6785e130075cb1ed75fcc45f0b3160f3c1b2


// RUN: %clang_cc1 -pedantic -fixit %s -o - | %clang_cc1 -fsyntax-only -pedantic -Werror -x c++ -

/* This is a test of the various code modification hints that are
   provided as part of warning or extension diagnostics. All of the
   warnings will be fixed by -fixit, and the resulting file should
   compile cleanly with -Werror -pedantic. */

struct C1 {
  virtual void f();
  static void g();
};
struct C2 : virtual public virtual C1 { }; // expected-error{{duplicate}}

virtual void C1::f() { } // expected-error{{'virtual' can only be specified inside the class definition}}

static void C1::g() { } // expected-error{{'static' can only be specified inside the class definition}}

template<int Value> struct CT { }; // expected-note{{previous use is here}}

CT<10 >> 2> ct; // expected-warning{{require parentheses}}

class C3 {
public:
  C3(C3, int i = 0); // expected-error{{copy constructor must pass its first argument by reference}}
};

struct CT<0> { }; // expected-error{{'template<>'}}

template<> class CT<1> { }; // expected-error{{tag type}}

// PR5444
namespace PR5444 {
  void foo(int x, int y = 0);
  void foo(int x, int y = 0) { }

  void foo(int  = 0);
  void foo(int  = 0) { }
}

// RUN: %clang_cc1 -pedantic -Wall -fixit %s -o - | %clang_cc1 -fsyntax-only -pedantic -Wall -Werror -x c++ -

/* This is a test of the various code modification hints that are
   provided as part of warning or extension diagnostics. All of the
   warnings will be fixed by -fixit, and the resulting file should
   compile cleanly with -Werror -pedantic. */

struct C1 {
  virtual void f();
  static void g();
};
struct C2 : virtual public virtual C1 { }; // expected-error{{duplicate}}

virtual void C1::f() { } // expected-error{{'virtual' can only be specified inside the class definition}}

static void C1::g() { } // expected-error{{'static' can only be specified inside the class definition}}

template<int Value> struct CT { }; // expected-note{{previous use is here}}

CT<10 >> 2> ct; // expected-warning{{require parentheses}}

class C3 {
public:
  C3(C3, int i = 0); // expected-error{{copy constructor must pass its first argument by reference}}
};

struct CT<0> { }; // expected-error{{'template<>'}}

template<> class CT<1> { }; // expected-error{{tag type}}

// Access declarations
class A {
protected:
  int foo();
};

class B : public A {
  A::foo; // expected-warning{{access declarations are deprecated}}
};

Make this fix-it test case actually fail when there is a problem; add
a test for access declarations and remove a (broken) test for removal
of default arguments.

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


#include<ros/ros.h>
#include<ics3/ics>
#include<servo_msgs/IdBased.h>

ics::ICS3* driver {nullptr};
ros::Publisher pub;

void move(const servo_msgs::IdBased::ConstPtr& msg) {
  servo_msgs::IdBased result;
  result.id = msg->id;
  try {
    result.angle = driver->move(msg->id, ics::Angle::newDegree(msg->angle));
    pub.publish(result);
  } catch (std::runtime_error e) {
    ROS_INFO("Communicate error: %s", e.what());
  }
}

int main(int argc, char** argv) {
  ros::init(argc, argv, "servo_krs_node");
  ros::NodeHandle n {};
  ros::NodeHandle pn {"~"};
  std::string path {"/dev/ttyUSB0"};
  pn.param<std::string>("path", path, path);
  ics::ICS3 ics {path.c_str()};
  driver = &ics;
  ros::Subscriber sub = n.subscribe("cmd_krs", 100, move);
  pub = n.advertise<servo_msgs::IdBased>("pose_krs", 10);
  ros::spin();
  return 0;
}

#include<ros/ros.h>
#include<servo_msgs/IdBased.h>
#include<ics3/ics>

ics::ICS3* driver {nullptr};
ros::Publisher pub;

void move(const servo_msgs::IdBased::ConstPtr& msg) {
  servo_msgs::IdBased result;
  result.id = msg->id;
  try {
    result.angle = driver->move(msg->id, ics::Angle::newDegree(msg->angle));
    pub.publish(result);
  } catch (std::runtime_error e) {
    ROS_INFO("Communicate error: %s", e.what());
  }
}

int main(int argc, char** argv) {
  ros::init(argc, argv, "servo_krs_node");
  ros::NodeHandle pn {"~"};
  std::string path {"/dev/ttyUSB0"};
  pn.param<std::string>("path", path, path);
  ics::ICS3 ics {std::move(path)};
  driver = &ics;
  ros::NodeHandle n {};
  ros::Subscriber sub {n.subscribe("cmd_krs", 100, move)};
  pub = n.advertise<servo_msgs::IdBased>("pose_krs", 10);
  ros::spin();
  return 0;
}

Update servo_krs for runtime speed

Update servo_krs for runtime speed

あと使う時に変数を宣言しろの教えの通り、NodeHandleの宣言を遅らせた
ぶっちゃけ短すぎて最適化する余地がなくて悲しみ。


// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "WatermarkDataFactory.h"

namespace ExampleApp
{
    namespace Watermark
    {
        namespace View
        {
            WatermarkDataFactory::WatermarkDataFactory(const std::string& appName,
                                                       const std::string& googleAnalyticsReferrerToken)
            : m_appName(appName)
            , m_googleAnalyticsReferrerToken(googleAnalyticsReferrerToken)
            {

            }

            WatermarkData WatermarkDataFactory::Create(const std::string& imageAssetUrl,
                                                       const std::string& popupTitle,
                                                       const std::string& popupBody,
                                                       const std::string& webUrl,
                                                       const bool shouldShowShadow)
            {
                return WatermarkData(imageAssetUrl,
                                     popupTitle,
                                     popupBody,
                                     webUrl,
                                     shouldShowShadow);
            }

            WatermarkData WatermarkDataFactory::CreateDefaultEegeo()
            {
                std::string imageAssetName = "eegeo_logo";
                std::string popupTitle = "Maps by eeGeo";
                std::string popupBody = "The " + m_appName + " app is open source. It's built using the eeGeo maps SDK, a cross platform API for building engaging, customizable apps.";
                std::string webUrl = "http://eegeo.com/?utm_source=" + m_googleAnalyticsReferrerToken + "&utm_medium=referral&utm_campaign=eegeo";

                return Create(imageAssetName,
                              popupTitle,
                              popupBody,
                              webUrl);
            }
        }
    }
}

// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "WatermarkDataFactory.h"

namespace ExampleApp
{
    namespace Watermark
    {
        namespace View
        {
            WatermarkDataFactory::WatermarkDataFactory(const std::string& appName,
                                                       const std::string& googleAnalyticsReferrerToken)
            : m_appName(appName)
            , m_googleAnalyticsReferrerToken(googleAnalyticsReferrerToken)
            {

            }

            WatermarkData WatermarkDataFactory::Create(const std::string& imageAssetUrl,
                                                       const std::string& popupTitle,
                                                       const std::string& popupBody,
                                                       const std::string& webUrl,
                                                       const bool shouldShowShadow)
            {
                return WatermarkData(imageAssetUrl,
                                     popupTitle,
                                     popupBody,
                                     webUrl,
                                     shouldShowShadow);
            }

            WatermarkData WatermarkDataFactory::CreateDefaultEegeo()
            {
                std::string imageAssetName = "eegeo_logo";
                std::string popupTitle = "Maps by eeGeo";
                std::string popupBody = "This app is open source. It's built using the eeGeo maps SDK, a cross platform API for building engaging, customizable apps.";
                std::string webUrl = "http://eegeo.com/?utm_source=" + m_googleAnalyticsReferrerToken + "&utm_medium=referral&utm_campaign=eegeo";

                return Create(imageAssetName,
                              popupTitle,
                              popupBody,
                              webUrl);
            }
        }
    }
}

Fix for MPLY-7058. Buddy: Paul

Fix for MPLY-7058. Buddy: Paul


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

#include "chrome/browser/app_modal_dialog_queue.h"

#include "chrome/browser/browser_list.h"

void AppModalDialogQueue::AddDialog(AppModalDialog* dialog) {
  if (!active_dialog_) {
    ShowModalDialog(dialog);
    return;
  }
  app_modal_dialog_queue_.push(dialog);
}

void AppModalDialogQueue::ShowNextDialog() {
  if (!app_modal_dialog_queue_.empty()) {
    AppModalDialog* dialog = app_modal_dialog_queue_.front();
    app_modal_dialog_queue_.pop();
    ShowModalDialog(dialog);
  } else {
    active_dialog_ = NULL;
  }
}

void AppModalDialogQueue::ActivateModalDialog() {
  if (active_dialog_)
    active_dialog_->ActivateModalDialog();
}

void AppModalDialogQueue::ShowModalDialog(AppModalDialog* dialog) {
  dialog->ShowModalDialog();
  active_dialog_ = dialog;
}

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

#include "chrome/browser/app_modal_dialog_queue.h"

#include "chrome/browser/browser_list.h"

void AppModalDialogQueue::AddDialog(AppModalDialog* dialog) {
  if (!active_dialog_) {
    ShowModalDialog(dialog);
    return;
  }
  app_modal_dialog_queue_.push(dialog);
}

void AppModalDialogQueue::ShowNextDialog() {
  if (!app_modal_dialog_queue_.empty()) {
    AppModalDialog* dialog = app_modal_dialog_queue_.front();
    app_modal_dialog_queue_.pop();
    ShowModalDialog(dialog);
  } else {
    active_dialog_ = NULL;
  }
}

void AppModalDialogQueue::ActivateModalDialog() {
  if (active_dialog_)
    active_dialog_->ActivateModalDialog();
}

void AppModalDialogQueue::ShowModalDialog(AppModalDialog* dialog) {
  // Set active_dialog_ before showing it, because ShowModalDialog can wind up
  // calling ShowNextDialog in some cases, which will change active_dialog_.
  active_dialog_ = dialog;
  dialog->ShowModalDialog();
}

Set active_dialog_ before showing it, since showing a dialog can sometimes
actually move to the next one in the queue instead.

BUG=26398
TEST=Make sure alert/confirm boxes work properly. Make sure a background
    tab that shows a (delayed) alert box works. Same with a background
    browser. Especially make sure http://crbug.com/10699 doesn't recur.
Review URL: http://codereview.chromium.org/339094

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


#include<ros/ros.h>
#include<servo_msgs/IdBased.h>
#include<ics3/ics>

ics::ICS3* driver {nullptr};
ros::Publisher pub;

void move(const servo_msgs::IdBased::ConstPtr& msg) {
  servo_msgs::IdBased result;
  try {
    result.angle = driver->move(msg->id, ics::Angle::newDegree(msg->angle));
    result.id = msg->id;
    pub.publish(result);
  } catch (std::runtime_error e) {
    ROS_INFO("Communicate error: %s", e.what());
  }
}

int main(int argc, char** argv) {
  ros::init(argc, argv, "servo_krs_node");
  ros::NodeHandle pn {"~"};
  std::string path {"/dev/ttyUSB0"};
  pn.param<std::string>("path", path, path);
  ics::ICS3 ics {std::move(path)};
  driver = &ics;
  ros::NodeHandle n {};
  ros::Subscriber sub {n.subscribe("cmd_krs", 100, move)};
  pub = n.advertise<servo_msgs::IdBased>("pose_krs", 10);
  ros::spin();
  return 0;
}

#include<ros/ros.h>
#include<servo_msgs/IdBased.h>
#include<ics3/ics>

ics::ICS3* driver {nullptr};
ros::Publisher pub;

void move(const servo_msgs::IdBased::ConstPtr& msg) {
  servo_msgs::IdBased result;
  try {
    result.angle = driver->move(msg->id, ics::Angle::newDegree(msg->angle));
    result.id = msg->id;
    pub.publish(result);
  } catch (std::runtime_error e) {
    ROS_INFO("Communicate error: %s", e.what());
  }
}

int main(int argc, char** argv) {
  ros::init(argc, argv, "servo_krs_node");
  ros::NodeHandle pn {"~"};
  std::string path {"/dev/ttyUSB0"};
  pn.param<std::string>("path", path, path);
  ROS_INFO("Open servo motor path: %s", path.c_str());
  ics::ICS3 ics {std::move(path)};
  driver = &ics;
  ros::NodeHandle n {};
  ros::Subscriber sub {n.subscribe("cmd_krs", 100, move)};
  pub = n.advertise<servo_msgs::IdBased>("pose_krs", 10);
  ros::spin();
  return 0;
}

Add message of reading path

Add message of reading path


/**
 * Appcelerator Titanium - licensed under the Apache Public License 2
 * see LICENSE in the root folder for details on the license.
 * Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.
 */

#include <kroll/kroll.h>
#include "../app_binding.h"

namespace ti
{

void AppBinding::Restart(const ValueList& args, KValueRef result)
{
	Host* host = Host::GetInstance();
	std::string cmdline(host->GetApplication()->arguments.at(0));

	// Remove all quotes.
	size_t i = cmdline.find('\"');
	while (i != std::string::npos)
	{
		cmdline.replace(i, 1, "");
		i = cmdline.find('\"');
	}

	std::string script = "\"" + cmdline + "\" &";
	system(script.c_str());

	host->Exit(0);
}

}

/**
 * Appcelerator Titanium - licensed under the Apache Public License 2
 * see LICENSE in the root folder for details on the license.
 * Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.
 */

#include <kroll/kroll.h>
#include "../app_binding.h"

namespace ti
{

void AppBinding::Restart(const ValueList& args, KValueRef result)
{
	Host* host = Host::GetInstance();
	std::string cmdline(host->GetApplication()->arguments.at(0));

	// Remove all quotes.
	size_t i = cmdline.find('\"');
	while (i != std::string::npos)
	{
		cmdline.replace(i, 1, "");
		i = cmdline.find('\"');
	}

	std::string script = "\"" + cmdline + "\" &";
	if (system(script.c_str()) == -1)
		throw ValueException::FromString("Failed to start new process.");

	host->Exit(0);
}

}

Throw an exception when App.restart fails on Linux.


#include <wangle/client/persistence/test/TestUtil.h>

namespace wangle {

std::string getPersistentCacheFilename() {
  char filename[] = "/tmp/fbtls.XXXXXX";
  int fd = mkstemp(filename);
  close(fd);
  EXPECT_TRUE(unlink(filename) != -1);
  return std::string(filename);
}

}

/*
 *  Copyright (c) 2016, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */
#include <wangle/client/persistence/test/TestUtil.h>

#include <folly/experimental/TestUtil.h>

namespace wangle {

std::string getPersistentCacheFilename() {
  folly::test::TemporaryFile file("fbtls");
  return file.path().string();
}

}

Handle tmp dir on Android

Handle tmp dir on Android

Summary:
There is no universally accessible tmpdir on Android which
means mkstemp fails. This diff calls a function that the test runner
should provide to fill a valid temporary directory.

Reviewed By: yangchi

Differential Revision: D2842034

fb-gh-sync-id: 186c931ddf4424cb482c8fbd728ae37877017685


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

#include "base/thread_local.h"

#include <pthread.h>

#include "base/logging.h"

namespace base {

// static
void ThreadLocalPlatform::AllocateSlot(SlotType& slot) {
  int error = pthread_key_create(&slot, NULL);
  CHECK(error == 0);
}

// static
void ThreadLocalPlatform::FreeSlot(SlotType& slot) {
  int error = pthread_key_delete(slot);
  DCHECK(error == 0);
}

// static
void* ThreadLocalPlatform::GetValueFromSlot(SlotType& slot) {
  return pthread_getspecific(slot_);
}

// static
void ThreadLocalPlatform::SetValueInSlot(SlotType& slot, void* value) {
  int error = pthread_setspecific(slot, value);
  CHECK(error == 0);
}

}  // namespace base

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

#include "base/thread_local.h"

#include <pthread.h>

#include "base/logging.h"

namespace base {

// static
void ThreadLocalPlatform::AllocateSlot(SlotType& slot) {
  int error = pthread_key_create(&slot, NULL);
  CHECK(error == 0);
}

// static
void ThreadLocalPlatform::FreeSlot(SlotType& slot) {
  int error = pthread_key_delete(slot);
  DCHECK(error == 0);
}

// static
void* ThreadLocalPlatform::GetValueFromSlot(SlotType& slot) {
  return pthread_getspecific(slot);
}

// static
void ThreadLocalPlatform::SetValueInSlot(SlotType& slot, void* value) {
  int error = pthread_setspecific(slot, value);
  CHECK(error == 0);
}

}  // namespace base

Fix a typo that broke the posix build.

Fix a typo that broke the posix build.

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


#include <kernel/rng.hpp>
#include <kernel/cpuid.hpp>
#include <kernel/os.hpp>
#include <arch.hpp>
#include <kprint>
extern "C" void intel_rdrand(uint64_t*);
extern "C" void intel_rdseed(uint64_t*);

static void fallback_entropy(uint64_t* res)
{
  uint64_t clock = (uint64_t) res;
  // this is horrible, better solution needed here
  for (int i = 0; i < 64; ++i) {
    clock += OS::cycles_since_boot();
    asm volatile("cpuid" ::: "memory", "eax", "ebx", "ecx", "edx");
  }
  // here we need to add our own bits
  *res = clock;
}

// used to generate initial
// entropy for a cryptographic randomness generator
void RNG::init()
{
  if (CPUID::has_feature(CPUID::Feature::RDSEED)) {
    rng_reseed_init(intel_rdseed, 2);
  }
  else if (CPUID::has_feature(CPUID::Feature::RDRAND)) {
    rng_reseed_init(intel_rdrand, 65);
  }
  else {
    rng_reseed_init(fallback_entropy, 64*16);
    return;
  }
  assert(0 && "No randomness fallback");
}

#include <kernel/rng.hpp>
#include <kernel/cpuid.hpp>
#include <kernel/os.hpp>
#include <arch.hpp>
#include <kprint>
extern "C" void intel_rdrand(uint64_t*);
extern "C" void intel_rdseed(uint64_t*);

static void fallback_entropy(uint64_t* res)
{
  uint64_t clock = (uint64_t) res;
  // this is horrible, better solution needed here
  for (int i = 0; i < 64; ++i) {
    clock += OS::cycles_since_boot();
    asm volatile("cpuid" ::: "memory", "eax", "ebx", "ecx", "edx");
  }
  // here we need to add our own bits
  *res = clock;
}

// used to generate initial
// entropy for a cryptographic randomness generator
void RNG::init()
{
  if (CPUID::has_feature(CPUID::Feature::RDSEED)) {
    rng_reseed_init(intel_rdseed, 2);
    return;
  }
  else if (CPUID::has_feature(CPUID::Feature::RDRAND)) {
    rng_reseed_init(intel_rdrand, 65);
    return;
  }
#ifndef PLATFORM_x86_solo5
  rng_reseed_init(fallback_entropy, 64*16);
  return;
#endif
  assert(0 && "No randomness fallback");
}

x86: Add missing returns in RNG init, and fail avoid TSC with solo5


// RUN: clang -fsyntax-only -verify %s
namespace A { // expected-error {{error: previous definition is here}}
  int A;
  void f() { A = 0; }
}

void f() { A = 0; } // expected-error {{error: unexpected namespace name 'A': expected expression}}
int A; // expected-error {{error: redefinition of 'A' as different kind of symbol}}
class A; // expected-error {{error: redefinition of 'A' as different kind of symbol}}

class B; // expected-error {{error: previous definition is here}}
namespace B {} // expected-error {{error: redefinition of 'B' as different kind of symbol}}

void C(); // expected-error {{error: previous definition is here}}
namespace C {} // expected-error {{error: redefinition of 'C' as different kind of symbol}}

Convert CFLF to LF.  CRLF was causing this test to fail under Mac OS X.

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


#include <unistd.h>
#include <gtest/gtest.h>
#include "getusername.h"

TEST(GetUserName,simple)
{
	// allocate a WCHAR_T buffer to receive username
	DWORD lpnSize = 64;
	WCHAR_T lpBuffer[lpnSize];

	BOOL result = GetUserName(lpBuffer, &lpnSize);

	// GetUserName returns 1 on success
	ASSERT_EQ(1, result);

	// get expected username
	const char *username = getlogin();

	// GetUserName sets lpnSize to length of username including null
	ASSERT_EQ(strlen(username)+1, lpnSize);

	// TODO: ASSERT_STREQ(username, Utf16leToUtf8(lpBuffer))
}

#include <string>
#include <vector>
#include <unistd.h>
#include <gtest/gtest.h>
#include <scxcorelib/scxstrencodingconv.h>
#include "getusername.h"

using std::string;
using std::vector;
using SCXCoreLib::Utf16leToUtf8;

TEST(GetUserName,simple)
{
	// allocate a WCHAR_T buffer to receive username
	DWORD lpnSize = 64;
	WCHAR_T lpBuffer[lpnSize];

	BOOL result = GetUserName(lpBuffer, &lpnSize);

	// GetUserName returns 1 on success
	ASSERT_EQ(1, result);

	// get expected username
	string username = string(getlogin());

	// GetUserName sets lpnSize to length of username including null
	ASSERT_EQ(username.size()+1, lpnSize);

	// copy UTF-16 bytes from lpBuffer to vector for conversion
	vector<unsigned char> input(reinterpret_cast<unsigned char *>(&lpBuffer[0]),
	                            reinterpret_cast<unsigned char *>(&lpBuffer[lpnSize-1]));
	// convert to UTF-8 for assertion
	string output;
	Utf16leToUtf8(input, output);

	EXPECT_EQ(username, output);
}

Test UTF-16 output of GetUserName

Test UTF-16 output of GetUserName


//===-- ubsan_init_standalone.cc ------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Initialization of standalone UBSan runtime.
//
//===----------------------------------------------------------------------===//

#include "ubsan_platform.h"
#if !CAN_SANITIZE_UB
# error "UBSan is not supported on this platform!"
#endif

#include "ubsan_init.h"

#if SANITIZER_CAN_USE_PREINIT_ARRAY
__attribute__((section(".preinit_array"), used))
void (*__local_ubsan_preinit)(void) = __ubsan::InitAsStandalone;
#else
// Use a dynamic initializer.
class UbsanStandaloneInitializer {
 public:
  UbsanStandaloneInitializer() {
    __ubsan::InitAsStandalone();
  }
};
static UbsanStandaloneInitializer ubsan_standalone_initializer;
#endif  // SANITIZER_CAN_USE_PREINIT_ARRAY

//===-- ubsan_init_standalone.cc ------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Initialization of standalone UBSan runtime.
//
//===----------------------------------------------------------------------===//

#include "ubsan_platform.h"
#if !CAN_SANITIZE_UB
# error "UBSan is not supported on this platform!"
#endif

#include "sanitizer_common/sanitizer_internal_defs.h"
#include "ubsan_init.h"

#if SANITIZER_CAN_USE_PREINIT_ARRAY
__attribute__((section(".preinit_array"), used))
void (*__local_ubsan_preinit)(void) = __ubsan::InitAsStandalone;
#else
// Use a dynamic initializer.
class UbsanStandaloneInitializer {
 public:
  UbsanStandaloneInitializer() {
    __ubsan::InitAsStandalone();
  }
};
static UbsanStandaloneInitializer ubsan_standalone_initializer;
#endif  // SANITIZER_CAN_USE_PREINIT_ARRAY

[UBSan] Add missing header that defines SANITIZER_CAN_USE_PREINIT_ARRAY

Otherwise this compile definition was undefined, and .preinit_array
was never used on the platforms that support it.

git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@237045 91177308-0d34-0410-b5e6-96231b3b80d8


#include "binary_threshold.h"

namespace TooManyPeeps {

  BinaryThreshold::BinaryThreshold(const cv::Mat& original, cv::Mat& result, int threshold)
    : ProcessFilter(original, result) {
    this->threshold = threshold;
  }

  BinaryThreshold::BinaryThreshold(cv::Mat& image, int threshold)
    : BinaryThreshold(original, result, threshold) {
  }

  void BinaryThreshold::execute(void) {
    cv::threshold(get_original(), get_result(), threshold, MAX_OUTPUT_VALUE, cv::THRESH_BINARY);
  }

};

#include "binary_threshold.h"

namespace TooManyPeeps {

  BinaryThreshold::BinaryThreshold(const cv::Mat& original, cv::Mat& result, int threshold)
    : ProcessFilter(original, result) {
    this->threshold = threshold;
  }

  BinaryThreshold::BinaryThreshold(cv::Mat& image, int threshold)
    : BinaryThreshold(image, image, threshold) {
  }

  void BinaryThreshold::execute(void) {
    cv::threshold(get_original(), get_result(), threshold, MAX_OUTPUT_VALUE, cv::THRESH_BINARY);
  }

};

Fix wrong constructor argument in binary thresh


/**
 * Appcelerator Titanium - licensed under the Apache Public License 2
 * see LICENSE in the root folder for details on the license.
 * Copyright (c) 2009, 2010 Appcelerator, Inc. All Rights Reserved.
 */

#include "../network_status.h"
#include <SystemConfiguration/SCNetworkReachability.h>

namespace ti
{

void NetworkStatus::InitializeLoop()
{
}

void NetworkStatus::CleanupLoop()
{
}

bool NetworkStatus::GetStatus()
{
	static SCNetworkReachabilityRef primaryTarget =
		SCNetworkReachabilityCreateWithName(0, "www.google.com");
	if (!primaryTarget)
		return true;

	SCNetworkConnectionFlags flags;
	SCNetworkReachabilityGetFlags(primaryTarget, &flags);
	if ((flags & kSCNetworkFlagsReachable) &&
		!(flags & kSCNetworkFlagsConnectionRequired))
		return true;

	static SCNetworkReachabilityRef secondaryTarget =
		SCNetworkReachabilityCreateWithName(0, "www.yahoo.com");
	if (!secondaryTarget)
		return true;

	SCNetworkReachabilityGetFlags(secondaryTarget, &flags);
	if ((flags & kSCNetworkFlagsReachable) &&
		!(flags & kSCNetworkFlagsConnectionRequired))
		return true;

	return false;
}

}

/**
 * Appcelerator Titanium - licensed under the Apache Public License 2
 * see LICENSE in the root folder for details on the license.
 * Copyright (c) 2009, 2010 Appcelerator, Inc. All Rights Reserved.
 */

#include "../network_status.h"
#include <SystemConfiguration/SCNetworkReachability.h>

namespace ti
{

static SCNetworkReachabilityRef primaryTarget = 0;
static SCNetworkReachabilityRef secondaryTarget = 0;

void NetworkStatus::InitializeLoop()
{
	primaryTarget = SCNetworkReachabilityCreateWithName(0, "www.google.com");
	secondaryTarget = SCNetworkReachabilityCreateWithName(0, "www.yahoo.com");
}

void NetworkStatus::CleanupLoop()
{
	if (primaryTarget)
		CFRelease(primaryTarget);
	if (secondaryTarget)
		CFRelease(secondaryTarget);
}

bool NetworkStatus::GetStatus()
{
	if (!primaryTarget)
		return true;

	SCNetworkConnectionFlags flags;
	SCNetworkReachabilityGetFlags(primaryTarget, &flags);
	if ((flags & kSCNetworkFlagsReachable) &&
		!(flags & kSCNetworkFlagsConnectionRequired))
		return true;

	if (!secondaryTarget)
		return true;

	SCNetworkReachabilityGetFlags(secondaryTarget, &flags);
	if ((flags & kSCNetworkFlagsReachable) &&
		!(flags & kSCNetworkFlagsConnectionRequired))
		return true;

	return false;
}

}

Clean up allocated memory during shutdown in OS X NetworkStatus.


// 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-CHROMIUM file.

#include "common/content_client.h"

#include "common/application_info.h"

#include "base/stringprintf.h"
#include "base/string_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "webkit/user_agent/user_agent_util.h"

namespace brightray {

ContentClient::ContentClient() {
}

ContentClient::~ContentClient() {
}

std::string ContentClient::GetProduct() const {
  auto name = GetApplicationName();
  RemoveChars(name, kWhitespaceASCII, &name);
  return base::StringPrintf("%s/%s", name.c_str(), GetApplicationVersion().c_str());
}

std::string ContentClient::GetUserAgent() const {
  return webkit_glue::BuildUserAgentFromProduct(GetProduct());
}

base::StringPiece ContentClient::GetDataResource(int resource_id, ui::ScaleFactor scale_factor) const {
  return ui::ResourceBundle::GetSharedInstance().GetRawDataResourceForScale(resource_id, scale_factor);
}

gfx::Image& ContentClient::GetNativeImageNamed(int resource_id) const {
  return ui::ResourceBundle::GetSharedInstance().GetNativeImageNamed(resource_id);
}

}

// 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-CHROMIUM file.

#include "common/content_client.h"

#include "common/application_info.h"

#include "base/stringprintf.h"
#include "base/string_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "webkit/common/user_agent/user_agent_util.h"

namespace brightray {

ContentClient::ContentClient() {
}

ContentClient::~ContentClient() {
}

std::string ContentClient::GetProduct() const {
  auto name = GetApplicationName();
  RemoveChars(name, kWhitespaceASCII, &name);
  return base::StringPrintf("%s/%s", name.c_str(), GetApplicationVersion().c_str());
}

std::string ContentClient::GetUserAgent() const {
  return webkit_glue::BuildUserAgentFromProduct(GetProduct());
}

base::StringPiece ContentClient::GetDataResource(int resource_id, ui::ScaleFactor scale_factor) const {
  return ui::ResourceBundle::GetSharedInstance().GetRawDataResourceForScale(resource_id, scale_factor);
}

gfx::Image& ContentClient::GetNativeImageNamed(int resource_id) const {
  return ui::ResourceBundle::GetSharedInstance().GetNativeImageNamed(resource_id);
}

}

Update for webkit header moves

Update for webkit header moves


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

#include "chrome/browser/ui/webui/print_preview_ui.h"

#include "base/values.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/print_preview_handler.h"
#include "chrome/browser/ui/webui/print_preview_ui_html_source.h"
#include "content/browser/browser_thread.h"
#include "content/browser/tab_contents/tab_contents.h"

PrintPreviewUI::PrintPreviewUI(TabContents* contents)
    : WebUI(contents),
      html_source_(new PrintPreviewUIHTMLSource()) {
  // PrintPreviewUI owns |handler|.
  PrintPreviewHandler* handler = new PrintPreviewHandler();
  AddMessageHandler(handler->Attach(this));

  // Set up the chrome://print/ source.
  contents->profile()->GetChromeURLDataManager()->AddDataSource(html_source_);
}

PrintPreviewUI::~PrintPreviewUI() {
}

PrintPreviewUIHTMLSource* PrintPreviewUI::html_source() {
  return html_source_.get();
}

void PrintPreviewUI::PreviewDataIsAvailable(int expected_pages_count) {
  FundamentalValue pages_count(expected_pages_count);
  CallJavascriptFunction("createPDFPlugin", pages_count);
}

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

#include "chrome/browser/ui/webui/print_preview_ui.h"

#include "base/values.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/print_preview_handler.h"
#include "chrome/browser/ui/webui/print_preview_ui_html_source.h"
#include "content/browser/browser_thread.h"
#include "content/browser/tab_contents/tab_contents.h"

PrintPreviewUI::PrintPreviewUI(TabContents* contents)
    : WebUI(contents),
      html_source_(new PrintPreviewUIHTMLSource()) {
  // PrintPreviewUI owns |handler|.
  PrintPreviewHandler* handler = new PrintPreviewHandler();
  AddMessageHandler(handler->Attach(this));

  // Set up the chrome://print/ source.
  contents->profile()->GetChromeURLDataManager()->AddDataSource(html_source_);
}

PrintPreviewUI::~PrintPreviewUI() {
}

PrintPreviewUIHTMLSource* PrintPreviewUI::html_source() {
  return html_source_.get();
}

void PrintPreviewUI::PreviewDataIsAvailable(int expected_pages_count) {
  FundamentalValue pages_count(expected_pages_count);
  CallJavascriptFunction("updatePrintPreview", pages_count);
}

Print Preview: Fix typo from r78639.

Print Preview: Fix typo from r78639.

BUG=76707
TEST=page count initialized correctly in print preview.
R=arv@chromium.org
Review URL: http://codereview.chromium.org/6688041

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


#include <patlms/util/remove_file.h>
#include <patlms/util/detail/cant_remove_file_exception.h>

#include <string>
#include <cstring>
#include <cerrno>
#include <boost/log/trivial.hpp>

using namespace std;

namespace util
{

void RemoveFile(const std::string &path, detail::SystemInterfacePtr system) {
  BOOST_LOG_TRIVIAL(debug) << "libpatlms::util::RemovePidFile: Function call with (path=" << path << ")";

  int ret = system->unlink(path.c_str());
  if (ret < 0) {
    BOOST_LOG_TRIVIAL(error) << "libpatlms::util::RemovePidFile: Couldn't remove pid file: " << strerror(errno);
    throw detail::CantRemoveFileException();
  }

  BOOST_LOG_TRIVIAL(debug) << "libpatlms::util::RemovePidFile: Done";
}

}

#include <patlms/util/remove_file.h>
#include <patlms/util/detail/cant_remove_file_exception.h>

#include <string>
#include <cstring>
#include <cerrno>
#include <boost/log/trivial.hpp>

using namespace std;

namespace util
{

void RemoveFile(const std::string &path, detail::SystemInterfacePtr system) {
  BOOST_LOG_TRIVIAL(debug) << "libpatlms::util::RemoveFile: Function call with (path=" << path << ")";

  int ret = system->unlink(path.c_str());
  if (ret < 0) {
    BOOST_LOG_TRIVIAL(error) << "libpatlms::util::RemoveFile: Couldn't remove file: " << strerror(errno);
    throw detail::CantRemoveFileException();
  }

  BOOST_LOG_TRIVIAL(debug) << "libpatlms::util::RemoveFile: Done";
}

}

Fix debug messages in library when removing file


// This file is part of MorphoDiTa <http://github.com/ufal/morphodita/>.
//
// Copyright 2016 Institute of Formal and Applied Linguistics, Faculty of
// Mathematics and Physics, Charles University in Prague, Czech Republic.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "generic_tokenizer.h"
#include "generic_tokenizer_factory.h"

namespace ufal {
namespace morphodita {

tokenizer* generic_tokenizer_factory::new_tokenizer() const {
  return new generic_tokenizer(version);
}

bool generic_tokenizer_factory::load(istream& is) {
  version = is.get();

  return is;
}

} // namespace morphodita
} // namespace ufal

// This file is part of MorphoDiTa <http://github.com/ufal/morphodita/>.
//
// Copyright 2016 Institute of Formal and Applied Linguistics, Faculty of
// Mathematics and Physics, Charles University in Prague, Czech Republic.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "generic_tokenizer.h"
#include "generic_tokenizer_factory.h"

namespace ufal {
namespace morphodita {

tokenizer* generic_tokenizer_factory::new_tokenizer() const {
  return new generic_tokenizer(version);
}

bool generic_tokenizer_factory::load(istream& is) {
  version = is.get();

  return bool(is);
}

} // namespace morphodita
} // namespace ufal

Add explicit conversion to bool.

Add explicit conversion to bool.

Required by standard and g++ 5.0.


#include "impl_send_posture.hpp"

#include "servo_msgs/KrsServoDegree.h"

std::map<std::string, const SendPosture*> SendPostureFactory::sends;

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

const SendPosture* SendPostureFactory::create(const std::string& name, ros::NodeHandle& nh) {
  if (name == "krs") {
    sends["krs"] = new KrsSendPosture(nh);
    return sends.at("krs");
  }
  return NULL;
}

KrsSendPosture::KrsSendPosture(ros::NodeHandle& nh) : nh(nh) {
  pub = nh.advertise<servo_msgs::KrsServoDegree>("cmd_krs", 16);
  nh.getParam("id_vec", id_vec);
}

void KrsSendPosture::sendPosture(std::vector<double>& posture) {

}

#include "impl_send_posture.hpp"

#include "algorithm"

#include "servo_msgs/KrsServoDegree.h"

std::map<std::string, const SendPosture*> SendPostureFactory::sends;

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

const SendPosture* SendPostureFactory::create(const std::string& name, ros::NodeHandle& nh) {
  if (name == "krs") {
    sends["krs"] = new KrsSendPosture(nh);
    return sends.at("krs");
  }
  return NULL;
}

KrsSendPosture::KrsSendPosture(ros::NodeHandle& nh) : nh(nh) {
  pub = nh.advertise<servo_msgs::KrsServoDegree>("cmd_krs", 16);
  nh.getParam("id_vec", id_vec);
}

void KrsSendPosture::sendPosture(std::vector<double>& posture) {
  servo_msgs::KrsServoDegree msg;
  std::vector<double>::size_type length = std::min(posture.size(), id_vec.size());
  for (std::vector<double>::size_type i = 0; i < length; i++) {
    msg.id = id_vec[i];
    msg.angle = posture[i];
    pub.publish(msg);
  }
}

Implement krs send posture method.

Implement krs send posture method.


#include "reg_language_translator.h"
#include "orz/types.h"

namespace Reg {
	namespace Internal {
		// TODO: Centralize (de)serialization the same way as for keyboard events

		boost::optional<LanguageTranslator::external_type> LanguageTranslator::get_value(internal_type const sval) {
			if (sval == "English") {
				return Intl::Language::English;
			}
			if (sval == "Swedish") {
				return Intl::Language::Swedish;
			}
			auto val = FromAString<int>(sval);
			if (val == 0) return Intl::Language::English;
			if (val == 1) return Intl::Language::Swedish;
			return boost::none;
		}

		boost::optional<LanguageTranslator::internal_type> LanguageTranslator::put_value(external_type const& val) {
			if (val == Intl::Language::English) {
				return "English";
			}
			if (val == Intl::Language::Swedish) {
				return "Swedish";
			}
			return boost::none;
		}
	}
}

#include "reg_language_translator.h"
#include "orz/types.h"

namespace Reg {
	namespace Internal {
		// TODO: Centralize (de)serialization the same way as for keyboard events

		boost::optional<LanguageTranslator::external_type> LanguageTranslator::get_value(internal_type const sval) {
			if (sval == "English") {
				return Intl::Language::English;
			}
			if (sval == "Swedish") {
				return Intl::Language::Swedish;
			}
			auto val = FromAString<int>(sval);
			if (val == 0) return Intl::Language::English;
			if (val == 1) return Intl::Language::Swedish;
			return boost::none;
		}

		boost::optional<LanguageTranslator::internal_type> LanguageTranslator::put_value(external_type const& val) {
			if (val == Intl::Language::English) {
				return std::string("English");
			}
			if (val == Intl::Language::Swedish) {
				return std::string("Swedish");
			}
			return boost::none;
		}
	}
}

Fix compile errors on Linux

Fix compile errors on Linux


#include "./mesh_node.h"
#include <string>
#include "./graphics/gl.h"

MeshNode::MeshNode(std::string assetFilename, int meshIndex,
                   std::shared_ptr<Graphics::Mesh> mesh,
                   Eigen::Matrix4f transformation)
  : assetFilename(assetFilename), meshIndex(meshIndex), mesh(mesh),
    transformation(transformation)
{
  obb = mesh->obb * transformation;
}

MeshNode::~MeshNode()
{
}

void MeshNode::render(Graphics::Gl *gl,
                      std::shared_ptr<Graphics::Managers> managers,
                      RenderData renderData)
{
  if (!isVisible)
    return;

  renderData.modelMatrix = transformation;
  mesh->render(gl, managers, renderData);
}

Eigen::Matrix4f MeshNode::getTransformation()
{
  return this->transformation;
}

void MeshNode::setTransformation(Eigen::Matrix4f transformation)
{
  this->transformation = transformation;
}

#include "./mesh_node.h"
#include <string>
#include "./graphics/gl.h"

MeshNode::MeshNode(std::string assetFilename, int meshIndex,
                   std::shared_ptr<Graphics::Mesh> mesh,
                   Eigen::Matrix4f transformation)
  : assetFilename(assetFilename), meshIndex(meshIndex), mesh(mesh),
    transformation(transformation)
{
  obb = mesh->obb * transformation;
}

MeshNode::~MeshNode()
{
}

void MeshNode::render(Graphics::Gl *gl,
                      std::shared_ptr<Graphics::Managers> managers,
                      RenderData renderData)
{
  if (!isVisible)
    return;

  renderData.modelMatrix = transformation;
  mesh->render(gl, managers, renderData);
}

Eigen::Matrix4f MeshNode::getTransformation()
{
  return this->transformation;
}

void MeshNode::setTransformation(Eigen::Matrix4f transformation)
{
  this->transformation = transformation;
  obb = mesh->obb * transformation;
}

Update bounding box in MeshNode::setTransformation.


#include <fstream>
#include <iostream>
#include "person.pb.h"
//#include "../pb2json.h"
#include <pb2json.h>

using namespace std;

int main(int argc,char *argv[])
{
 	// Test 1: read binary PB from a file and convert it to JSON
	ifstream fin("dump",ios::binary);
	fin.seekg(0,ios_base::end);
	size_t len = fin.tellg();
	fin.seekg(0,ios_base::beg);
	char *buf = new char [len];

	fin.read(buf,len);
	google::protobuf::Message *p = new Person();
	char *json = pb2json(p,buf,len);
	cout<<json<<endl;
	free(json);
	delete p;

	// Test 2: convert PB to JSON directly
	Person p2;
	char *json2 = pb2json(p2);
	cout<<json2<<endl;
	free(json2);

	return 0;
}

#include <fstream>
#include <iostream>
#include "person.pb.h"
//#include "../pb2json.h"
#include <pb2json.h>

using namespace std;

int main(int argc,char *argv[])
{
 	// Test 1: read binary PB from a file and convert it to JSON
	ifstream fin("dump",ios::binary);
	fin.seekg(0,ios_base::end);
	size_t len = fin.tellg();
	fin.seekg(0,ios_base::beg);
	char *buf = new char [len];

	fin.read(buf,len);
	google::protobuf::Message *p = new Person();
	char *json = pb2json(p,buf,len);
	cout<<json<<endl;
	free(json);
	delete p;

	// Test 2: convert PB to JSON directly
	Person p2;
    p2.set_name("Shafreeck Sea");
    p2.set_id(2);
    p2.set_email("renenglish@gmail.com");
	Person_PhoneNumber *pn1 = p2.add_phone();
	pn1->set_number("1234567");
	pn1->set_type(Person::HOME);
	char *json2 = pb2json(p2);
	cout<<json2<<endl;
	free(json2);

	return 0;
}

Add test translate protobuf object to json directly


#include "log4qt/dailyfileappender.h"

#include "log4qt/simplelayout.h"

#include <QTemporaryDir>
#include <QtTest/QtTest>

using Log4Qt::DailyFileAppender;

class DailyFileAppenderTest : public QObject
{
    Q_OBJECT

private Q_SLOTS:
    void init();
    void cleanup();

    void testFileCreation();

private:
    QTemporaryDir *mLogDirectory;
    DailyFileAppender *mAppender;
};

void DailyFileAppenderTest::init()
{
    mLogDirectory = new QTemporaryDir;

    mAppender = new DailyFileAppender;
    mAppender->setLayout(Log4Qt::LayoutSharedPtr(new Log4Qt::SimpleLayout));
}

void DailyFileAppenderTest::cleanup()
{
    delete mAppender;
    delete mLogDirectory;  // destructor will remove temporary directory
}

void DailyFileAppenderTest::testFileCreation()
{
    mAppender->setDatePattern(QStringLiteral("_yyyy_MM_dd"));
    mAppender->setFile(mLogDirectory->filePath(QStringLiteral("app.log")));

    mAppender->activateOptions();

    QVERIFY(QFileInfo::exists(mAppender->file()));
}

QTEST_GUILESS_MAIN(DailyFileAppenderTest)

#include "dailyfileappendertest.moc"

#include "log4qt/dailyfileappender.h"

#include "log4qt/loggingevent.h"
#include "log4qt/simplelayout.h"

#include <QTemporaryDir>
#include <QtTest/QtTest>

using Log4Qt::DailyFileAppender;

class DailyFileAppenderTest : public QObject
{
    Q_OBJECT

private Q_SLOTS:
    void init();
    void cleanup();

    void testFileCreation();
    void testAppend();

private:
    QTemporaryDir *mLogDirectory;
    DailyFileAppender *mAppender;
};

void DailyFileAppenderTest::init()
{
    mLogDirectory = new QTemporaryDir;

    mAppender = new DailyFileAppender;
    mAppender->setLayout(Log4Qt::LayoutSharedPtr(new Log4Qt::SimpleLayout));
}

void DailyFileAppenderTest::cleanup()
{
    delete mAppender;
    delete mLogDirectory;  // destructor will remove temporary directory
}

void DailyFileAppenderTest::testFileCreation()
{
    mAppender->setDatePattern(QStringLiteral("_yyyy_MM_dd"));
    mAppender->setFile(mLogDirectory->filePath(QStringLiteral("app.log")));

    mAppender->activateOptions();

    QVERIFY(QFileInfo::exists(mAppender->file()));
}

void DailyFileAppenderTest::testAppend()
{
    mAppender->setFile(mLogDirectory->filePath(QStringLiteral("app.log")));

    mAppender->activateOptions();

    const auto fileName = mAppender->file();

    QVERIFY(QFileInfo::exists(fileName));

    const QFile logFile(fileName);

    // nothing written yet
    QCOMPARE(logFile.size(), 0);

    mAppender->append(Log4Qt::LoggingEvent());

    QVERIFY(logFile.size() > 0);
}

QTEST_GUILESS_MAIN(DailyFileAppenderTest)

#include "dailyfileappendertest.moc"

Add test for simple append using DailyFileAppender


#include <fstream>
#include "rang.hpp"

int main()
{
	std::cout << rang::fg::blue << "\nShould be blue";
	std::ofstream out("out.txt");
	std::streambuf *coutbuf = std::cout.rdbuf();
	std::cout.rdbuf(out.rdbuf());

	std::string word = "not blue";
	std::cout << "START " << rang::fg::blue << word << " END";

	std::cout.rdbuf(coutbuf);
	std::cout << "\nShould again be blue" << rang::style::reset << std::endl;
	return 0;
}

#define CATCH_CONFIG_MAIN
#include "catch.hpp"

#include "rang.hpp"

#include <fstream>
#include <string>

std::string RCB(std::string input)
{
	std::ofstream out("out.txt");
	std::streambuf *coutbuf = std::cout.rdbuf();
	std::cout.rdbuf(out.rdbuf());

	std::cout << rang::fg::blue << input << rang::style::reset;

	std::cout.rdbuf(coutbuf);
	out.close();

	std::ifstream in("out.txt");
	std::string output;
	std::getline(in,output);
	return output;

}

TEST_CASE("Redirected cout buffer", "RCB")
{
	REQUIRE(RCB("HelloWorld") == "HelloWorld");
}

Add a simple write-then-read test

Add a simple write-then-read test


// 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 "remoting/host/event_executor_mac.h"

namespace remoting {

EventExecutorMac::EventExecutorMac(Capturer* capturer)
  : EventExecutor(capturer) {
}

EventExecutorMac::~EventExecutorMac() {
}

void EventExecutorMac::HandleInputEvent(ChromotingClientMessage* message) {
  delete message;
}

}  // namespace remoting

// 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 "remoting/host/event_executor_mac.h"

#include "remoting/protocol/messages_decoder.h"

namespace remoting {

EventExecutorMac::EventExecutorMac(Capturer* capturer)
  : EventExecutor(capturer) {
}

EventExecutorMac::~EventExecutorMac() {
}

void EventExecutorMac::HandleInputEvent(ChromotingClientMessage* message) {
  delete message;
}

}  // namespace remoting

Fix build break on mac. TBR=ajwong

Fix build break on mac.
TBR=ajwong

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


// Copyright (c) 2011 The Native Client 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 "native_client/src/shared/platform/nacl_check.h"
#include "native_client/tests/ppapi_test_lib/test_interface.h"

namespace {

// This will crash a PPP_Messaging function.
void CrashViaExitCall() {
  printf("--- CrashViaExitCall\n");
  _exit(0);
}

}  // namespace

void SetupTests() {
  RegisterTest("CrashViaExitCall", CrashViaExitCall);
}

void SetupPluginInterfaces() {
  // none
}

// Copyright (c) 2011 The Native Client 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 <unistd.h>

#include "native_client/src/shared/platform/nacl_check.h"
#include "native_client/tests/ppapi_test_lib/test_interface.h"

namespace {

// This will crash a PPP_Messaging function.
void CrashViaExitCall() {
  printf("--- CrashViaExitCall\n");
  _exit(0);
}

}  // namespace

void SetupTests() {
  RegisterTest("CrashViaExitCall", CrashViaExitCall);
}

void SetupPluginInterfaces() {
  // none
}

Add include for unistd.h for _exit.
Otherwise, the exit test won't build w/ pnacl.

R= polina@google.com,dspringer@google.com
BUG=
TEST= ./scons platform=x86-32 bitcode=1 run_ppapi_crash_browser_test

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

git-svn-id: 721b910a23eff8a86f00c8fd261a7587cddf18f8@6282 fcba33aa-ac0c-11dd-b9e7-8d5594d729c2


//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads
// UNSUPPORTED: c++98, c++03

// <future>

// class packaged_task<R(ArgTypes...)>
// template <class F, class Allocator>
//   packaged_task(allocator_arg_t, const Allocator& a, F&& f);
// These constructors shall not participate in overload resolution if
//    decay<F>::type is the same type as std::packaged_task<R(ArgTypes...)>.

#include <future>
#include <cassert>

#include "test_allocator.h"

struct A {};
typedef std::packaged_task<A(int, char)> PT;
typedef volatile std::packaged_task<A(int, char)> VPT;

int main()
{
    PT p { std::allocator_arg_t{}, test_allocator<A>{}, VPT {}}; // expected-error {{no matching constructor for initialization of 'PT' (aka 'packaged_task<A (int, char)>')}}
    // expected-note@future:* 1 {{candidate template ignored: disabled by 'enable_if'}}
}

//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads
// UNSUPPORTED: c++98, c++03

// <future>

// class packaged_task<R(ArgTypes...)>
// template <class F, class Allocator>
//   packaged_task(allocator_arg_t, const Allocator& a, F&& f);
// These constructors shall not participate in overload resolution if
//    decay<F>::type is the same type as std::packaged_task<R(ArgTypes...)>.

#include <future>
#include <cassert>

#include "test_allocator.h"

struct A {};
typedef std::packaged_task<A(int, char)> PT;
typedef volatile std::packaged_task<A(int, char)> VPT;

int main()
{
    PT p { std::allocator_arg_t{}, test_allocator<A>{}, VPT {}}; // expected-error {{no matching constructor for initialization of 'PT' (aka 'packaged_task<A (int, char)>')}}
    // expected-note-re@future:* 1 {{candidate template ignored: {{(disabled by 'enable_if')|(requirement '.*' was not satisfied)}}}}
}

Fix diagnostic in verify test to match new Clang output

git-svn-id: 756ef344af921d95d562d9e9f9389127a89a6314@307450 91177308-0d34-0410-b5e6-96231b3b80d8


// RUN: %clang_cc1 -emit-llvm %s -o - -triple=i386-pc-win32 -mconstructor-aliases -fcxx-exceptions -fexceptions -fno-rtti -DTRY   | FileCheck %s -check-prefix=TRY
// RUN: %clang_cc1 -emit-llvm %s -o - -triple=i386-pc-win32 -mconstructor-aliases -fcxx-exceptions -fexceptions -fno-rtti -DTHROW | FileCheck %s -check-prefix=THROW

void external();

inline void not_emitted() {
  throw int(13); // no error
}

int main() {
  int rv = 0;
#ifdef TRY
  try {
    external(); // TRY: invoke void @"\01?external@@YAXXZ"
  } catch (int) {
    rv = 1;
    // TRY: call i8* @llvm.eh.begincatch
    // TRY: call void @llvm.eh.endcatch
  }
#endif
#ifdef THROW
  // THROW: call void @"\01?terminate@@YAXXZ"
  throw int(42);
#endif
  return rv;
}

// RUN: %clang_cc1 -emit-llvm %s -o - -triple=i386-pc-win32 -mconstructor-aliases -fcxx-exceptions -fexceptions -fno-rtti -DTRY   | FileCheck %s -check-prefix=TRY
// FIXME: Disabled until catch IRgen change lands.
// RUNX: %clang_cc1 -emit-llvm %s -o - -triple=i386-pc-win32 -mconstructor-aliases -fcxx-exceptions -fexceptions -fno-rtti -DTHROW | FileCheck %s -check-prefix=THROW

void external();

inline void not_emitted() {
  throw int(13); // no error
}

int main() {
  int rv = 0;
#ifdef TRY
  try {
    external(); // TRY: invoke void @"\01?external@@YAXXZ"
  } catch (int) {
    rv = 1;
    // TRY: call i8* @llvm.eh.begincatch
    // TRY: call void @llvm.eh.endcatch
  }
#endif
#ifdef THROW
  // THROW: call void @"\01?terminate@@YAXXZ"
  throw int(42);
#endif
  return rv;
}

Disable a Clang test until the begincatch change lands

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


#include <fastarduino/soft_uart.h>

constexpr const board::InterruptPin RX = board::InterruptPin::D0_PD0_PCI2;
#define PCI_NUM 2

REGISTER_UART_PCI_ISR(RX, PCI_NUM)

// Buffers for UARX
static const uint8_t INPUT_BUFFER_SIZE = 64;
static char input_buffer[INPUT_BUFFER_SIZE];

int main()
{
    board::init();
    sei();

    // Start UART
	typename interrupt::PCIType<RX>::TYPE pci;
	serial::soft::UARX_PCI<RX> uarx{input_buffer, pci};
	pci.enable();
	uarx.begin(115200);

    streams::istream in = uarx.in();

    // Wait for a char
    char value1;
    in >> streams::skipws >> value1;

    // Wait for an uint16_t
    uint16_t value2;
    in >> streams::skipws >> value2;

    return 0;
}

#include <fastarduino/soft_uart.h>

constexpr const board::InterruptPin RX = board::InterruptPin::D0_PD0_PCI2;
#define PCI_NUM 2

REGISTER_UARX_PCI_ISR(RX, PCI_NUM)

// Buffers for UARX
static const uint8_t INPUT_BUFFER_SIZE = 64;
static char input_buffer[INPUT_BUFFER_SIZE];

int main()
{
    board::init();
    sei();

    // Start UART
	typename interrupt::PCIType<RX>::TYPE pci;
	serial::soft::UARX_PCI<RX> uarx{input_buffer, pci};
	pci.enable();
	uarx.begin(115200);

    streams::istream in = uarx.in();

    // Wait for a char
    char value1;
    in >> streams::skipws >> value1;

    // Wait for an uint16_t
    uint16_t value2;
    in >> streams::skipws >> value2;

    return 0;
}

Fix tutorial SW UART example

Fix tutorial SW UART example


// RUN: %clang_cc1 %s -fsyntax-only -verify -Wmissing-noreturn -Wno-unreachable-code

// A destructor may be marked noreturn and should still influence the CFG.
namespace PR6884 {
  struct abort_struct {
    abort_struct() {} // Make this non-POD so the destructor is invoked.
    ~abort_struct() __attribute__((noreturn));
  };

  int f() {
    abort_struct();
  }

  int f2() {
    abort_struct s;
  } // expected-warning{{control reaches end of non-void function}}
}

// RUN: %clang_cc1 %s -fsyntax-only -verify -Wmissing-noreturn -Wno-unreachable-code

// A destructor may be marked noreturn and should still influence the CFG.
namespace PR6884 {
  struct abort_struct {
    abort_struct() {} // Make this non-POD so the destructor is invoked.
    ~abort_struct() __attribute__((noreturn));
  };

  // FIXME: Should either of these actually warn, since the destructor is
  //  marked noreturn?

  int f() {
    abort_struct();
  } // expected-warning{{control reaches end of non-void function}}

  int f2() {
    abort_struct s;
  } // expected-warning{{control reaches end of non-void function}}
}

Update test case, with comment to later investigate the correct behavior.  Now the behavior is at least consistent.

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


#include <log4cpp/Category.hh>
#include <log4cpp/Appender.hh>
#include <log4cpp/OstreamAppender.hh>
#include <log4cpp/Layout.hh>
#include <log4cpp/PatternLayout.hh>
#include <log4cpp/Priority.hh>

#include "LoggerFactory.h"

using namespace Log;

bool LoggerFactory::isCreated = false;
log4cpp::Category *LoggerFactory::instance;

LoggerFactory::LoggerFactory() {}

/* Factory for a simple log4cpp logger. */
log4cpp::Category* LoggerFactory::create() {
    log4cpp::Category *logger = &log4cpp::Category::getRoot();
    log4cpp::Appender *p_appender = new log4cpp::OstreamAppender("console", &std::cout);
    log4cpp::PatternLayout *layout = new log4cpp::PatternLayout();
    layout->setConversionPattern("%d{%Y-%m-%d %H:%M:%S} [%p] %c: %m%n");
    p_appender->setLayout(layout);

    logger->setPriority(log4cpp::Priority::DEBUG);
    logger->addAppender(p_appender);
    return logger;
}

/* Returns a singleton root logger. */
log4cpp::Category *LoggerFactory::getLogger() {
    if (!isCreated) {
        isCreated = true;
        instance = create();
    }
    return instance;
}

#include <log4cpp/Category.hh>
#include <log4cpp/Appender.hh>
#include <log4cpp/OstreamAppender.hh>
#include <log4cpp/Layout.hh>
#include <log4cpp/PatternLayout.hh>
#include <log4cpp/Priority.hh>

#include "LoggerFactory.h"

using namespace Log;

bool LoggerFactory::isCreated = false;
log4cpp::Category *LoggerFactory::instance;

LoggerFactory::LoggerFactory() {}

/* Factory for a simple log4cpp logger. */
log4cpp::Category* LoggerFactory::create() {
    log4cpp::Category *logger = &log4cpp::Category::getRoot();
    log4cpp::Appender *p_appender = new log4cpp::OstreamAppender("console", &std::cout);
    log4cpp::PatternLayout *layout = new log4cpp::PatternLayout();
    layout->setConversionPattern("%d{%Y-%m-%d %H:%M:%S} [%p] %c: %m%n");
    p_appender->setLayout(layout);

    logger->setPriority(log4cpp::Priority::INFO);
    logger->addAppender(p_appender);
    return logger;
}

/* Returns a singleton root logger. */
log4cpp::Category *LoggerFactory::getLogger() {
    if (!isCreated) {
        isCreated = true;
        instance = create();
    }
    return instance;
}

Change logging level to INFO (DEBUG is slowing down the execution too much).


// This code is in the public domain -- castano@gmail.com

#include "FileSystem.h"
#include <nvcore/nvcore.h>

#if NV_OS_WIN32
#include <direct.h>
#else
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#endif

using namespace nv;

bool FileSystem::exists(const char * path)
{
#if NV_OS_UNIX
	struct stat buf;
	return stat(path, &buf) == 0;
#else
	if (FILE * fp = fopen(path, "r"))
	{
		fclose(fp);
		return true;
	}
	return false;
#endif
}

bool FileSystem::createDirectory(const char * path)
{
#if NV_OS_WIN32
    return _mkdir(path) != -1;
#else
    return mkdir(path, 0777) != -1;
#endif
}

// This code is in the public domain -- castano@gmail.com

#include "FileSystem.h"
#include <nvcore/nvcore.h>

#if NV_OS_WIN32
#include <direct.h>
#else
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#endif

using namespace nv;

bool FileSystem::exists(const char * path)
{
#if NV_OS_UNIX
	return access(path, F_OK|R_OK) == 0;
	//struct stat buf;
	//return stat(path, &buf) == 0;
#else
	if (FILE * fp = fopen(path, "r"))
	{
		fclose(fp);
		return true;
	}
	return false;
#endif
}

bool FileSystem::createDirectory(const char * path)
{
#if NV_OS_WIN32
    return _mkdir(path) != -1;
#else
    return mkdir(path, 0777) != -1;
#endif
}

Implement exists with access instead of stat.

git-svn-id: bd2008fbba0f7d30fd6598b54f2cd88503fdd2e4@802 95f4ed2b-212e-0410-8b90-d31948207fce


// Copyright (c) 2013, Facebook, Inc.  All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.

#include <atomic>

#include "rocksdb/env.h"
#include "util/thread_status_updater.h"
#include "util/thread_status_util.h"

namespace rocksdb {

#ifndef NDEBUG
// the delay for debugging purpose.
static std::atomic<int> states_delay[ThreadStatus::NUM_STATE_TYPES];

void ThreadStatusUtil::TEST_SetStateDelay(
    const ThreadStatus::StateType state, int micro) {
  states_delay[state].store(micro, std::memory_order_relaxed);
}

void ThreadStatusUtil::TEST_StateDelay(
    const ThreadStatus::StateType state) {
  Env::Default()->SleepForMicroseconds(
      states_delay[state].load(std::memory_order_relaxed));
}

#endif  // !NDEBUG

}  // namespace rocksdb

// Copyright (c) 2013, Facebook, Inc.  All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.

#include <atomic>

#include "rocksdb/env.h"
#include "util/thread_status_updater.h"
#include "util/thread_status_util.h"

namespace rocksdb {

#ifndef NDEBUG
// the delay for debugging purpose.
static std::atomic<int> states_delay[ThreadStatus::NUM_STATE_TYPES];

void ThreadStatusUtil::TEST_SetStateDelay(
    const ThreadStatus::StateType state, int micro) {
  states_delay[state].store(micro, std::memory_order_relaxed);
}

void ThreadStatusUtil::TEST_StateDelay(const ThreadStatus::StateType state) {
  auto delay = states_delay[state].load(std::memory_order_relaxed);
  if (delay > 0) {
    Env::Default()->SleepForMicroseconds(delay);
  }
}

#endif  // !NDEBUG

}  // namespace rocksdb

Fix bad performance in debug mode

Fix bad performance in debug mode

Summary:
See github issue 574: https://github.com/facebook/rocksdb/issues/574

Basically when we're running in DEBUG mode we're calling `usleep(0)` on
every mutex lock. I bisected the issue to
https://reviews.facebook.net/D36963. Instead of calling sleep(0), this
diff just avoids calling SleepForMicroseconds() when delay is not set.

Test Plan:
    bpl=10485760;overlap=10;mcz=2;del=300000000;levels=2;ctrig=10000000; delay=10000000; stop=10000000; wbn=30; mbc=20; mb=1073741824;wbs=268435456; dds=1; sync=0; r=100000; t=1; vs=800; bs=65536; cs=1048576; of=500000; si=1000000; ./db_bench --benchmarks=fillrandom --disable_seek_compaction=1 --mmap_read=0 --statistics=1 --histogram=1 --num=$r --threads=$t --value_size=$vs --block_size=$bs --cache_size=$cs --bloom_bits=10 --cache_numshardbits=4 --open_files=$of --verify_checksum=1 --db=/tmp/rdb10test --sync=$sync --disable_wal=1 --compression_type=snappy --stats_interval=$si --compression_ratio=0.5 --disable_data_sync=$dds --write_buffer_size=$wbs --target_file_size_base=$mb --max_write_buffer_number=$wbn --max_background_compactions=$mbc --level0_file_num_compaction_trigger=$ctrig --level0_slowdown_writes_trigger=$delay --level0_stop_writes_trigger=$stop --num_levels=$levels --delete_obsolete_files_period_micros=$del --min_level_to_compress=$mcz --max_grandparent_overlap_factor=$overlap --stats_per_interval=1 --max_bytes_for_level_base=$bpl --memtablerep=vector --use_existing_db=0 --disable_auto_compactions=1 --source_compaction_factor=10000000 | grep ops

Before:
fillrandom   :     117.525 micros/op 8508 ops/sec;    6.6 MB/s
After:
fillrandom   :       1.283 micros/op 779502 ops/sec;  606.6 MB/s

Reviewers: rven, yhchiang, sdong

Reviewed By: sdong

Subscribers: meyering, dhruba, leveldb

Differential Revision: https://reviews.facebook.net/D36963


/* Copyright 2017 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/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"

namespace tensorflow {
namespace {

class XlaReplicaIdOp : public XlaOpKernel {
 public:
  explicit XlaReplicaIdOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {}
  void Compile(XlaOpKernelContext* ctx) override;

 private:
  TF_DISALLOW_COPY_AND_ASSIGN(XlaReplicaIdOp);
};

void XlaReplicaIdOp::Compile(XlaOpKernelContext* ctx) {
  ctx->SetOutput(
      0, xla::ConvertElementType(xla::ReplicaId(ctx->builder()), xla::S32));
}

REGISTER_XLA_OP(Name("XlaReplicaId"), XlaReplicaIdOp);

}  // namespace
}  // namespace tensorflow

/* Copyright 2017 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/compiler/tf2xla/mlir_xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"

namespace tensorflow {
namespace {

REGISTER_XLA_OP(Name("XlaReplicaId"), MlirXlaOpKernel);

}  // namespace
}  // namespace tensorflow

Remove the fallback to the old bridge for tf.XlaReplicaId

PiperOrigin-RevId: 409854723
Change-Id: I6d099e1874c56f24ada98b81036e14647af50c76


//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <vector>

// void assign(size_type n, const_reference v);

#include <vector>
#include <algorithm>
#include <cassert>
#include <iostream>

#include "min_allocator.h"
#include "asan_testing.h"

bool is6(int x) { return x == 6; }

template <typename Vec>
void test ( Vec &v )
{
    std::cout << "Size, cap: " << v.size() << " " << v.capacity() << std::endl;
    v.assign(5, 6);
    std::cout << "Size, cap: " << v.size() << " " << v.capacity() << std::endl;
    assert(v.size() == 5);
    assert(is_contiguous_container_asan_correct(v));
    assert(std::all_of(v.begin(), v.end(), is6));
}

int main()
{
    {
    typedef std::vector<int> V;
    V d1;
    V d2;
    d2.reserve(10);  // no reallocation during assign.
    test(d1);
    test(d2);
    }

#if __cplusplus >= 201103L
    {
    typedef std::vector<int, min_allocator<int>> V;
    V d1;
    V d2;
    d2.reserve(10);  // no reallocation during assign.
    test(d1);
    test(d2);
    }
#endif
}

//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <vector>

// void assign(size_type n, const_reference v);

#include <vector>
#include <algorithm>
#include <cassert>
#include <iostream>

#include "min_allocator.h"
#include "asan_testing.h"

bool is6(int x) { return x == 6; }

template <typename Vec>
void test ( Vec &v )
{
    v.assign(5, 6);
    assert(v.size() == 5);
    assert(is_contiguous_container_asan_correct(v));
    assert(std::all_of(v.begin(), v.end(), is6));
}

int main()
{
    {
    typedef std::vector<int> V;
    V d1;
    V d2;
    d2.reserve(10);  // no reallocation during assign.
    test(d1);
    test(d2);
    }

#if __cplusplus >= 201103L
    {
    typedef std::vector<int, min_allocator<int>> V;
    V d1;
    V d2;
    d2.reserve(10);  // no reallocation during assign.
    test(d1);
    test(d2);
    }
#endif
}

Remove some debugging printout lines. No functionality change.

git-svn-id: 756ef344af921d95d562d9e9f9389127a89a6314@236949 91177308-0d34-0410-b5e6-96231b3b80d8


// Copyright 2016 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 <stddef.h>
#include <stdint.h>
#ifndef OTS_FUZZER_NO_MAIN
#include <fstream>
#include <iostream>
#include <iterator>
#endif

#include "opentype-sanitiser.h"
#include "ots-memory-stream.h"

// Entry point for LibFuzzer.
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  ots::OTSContext context;
  ots::MemoryStream stream((void*)data, size);
  context.Process(&stream, data, size);
  return 0;
}

#ifndef OTS_FUZZER_NO_MAIN
int main(int argc, char **argv) {
  for (int i = 1; i < argc; i++) {
    std::cout << argv[i] << std::endl;

    std::ifstream f(argv[i]);
    if (!f.good())
      return 1;

    std::string s((std::istreambuf_iterator<char>(f)),
                  (std::istreambuf_iterator<char>()));
    LLVMFuzzerTestOneInput((const uint8_t*)s.data(), s.size());
  }
  return 0;
}
#endif

// Copyright 2016 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 <stddef.h>
#include <stdint.h>
#ifndef OTS_FUZZER_NO_MAIN
#include <fstream>
#include <iostream>
#include <iterator>
#endif

#include "opentype-sanitiser.h"
#include "ots-memory-stream.h"

static uint8_t buffer[256 * 1024] = { 0 };

// Entry point for LibFuzzer.
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  ots::OTSContext context;
  ots::MemoryStream stream(static_cast<void*>(buffer), sizeof(buffer));
  context.Process(&stream, data, size);
  return 0;
}

#ifndef OTS_FUZZER_NO_MAIN
int main(int argc, char **argv) {
  for (int i = 1; i < argc; i++) {
    std::cout << argv[i] << std::endl;

    std::ifstream f(argv[i]);
    if (!f.good())
      return 1;

    std::string s((std::istreambuf_iterator<char>(f)),
                  (std::istreambuf_iterator<char>()));
    LLVMFuzzerTestOneInput((const uint8_t*)s.data(), s.size());
  }
  return 0;
}
#endif

Fix thinko In inroduced while importing the fuzzer


#include "halley/maths/circle.h"
using namespace Halley;

bool Circle::contains(Vector2f point) const
{
	return (point - centre).squaredLength() <= radius * radius;
}

bool Circle::overlaps(const Circle& circle) const
{
	const float r = radius + circle.radius;
	return (circle.centre - centre).squaredLength() <= r * r;
}

Circle Circle::getSpanningCircle(const std::vector<Vector2f>& points)
{
	// TODO: should use Matousek, Sharir, Welzl's algorithm (https://en.wikipedia.org/wiki/Smallest-circle_problem#Matou%C5%A1ek,_Sharir,_Welzl's_algorithm)

	Vector2f centre;
	for (auto& p: points) {
		centre += p;
	}
	centre /= float(points.size());

	float radius2 = 0;
	for (auto& p: points) {
		const auto d = (p - centre).squaredLength();
		if (d > radius2) {
			radius2 = d;
		}
	}

	return Circle(centre, std::sqrtf(radius2));
}

#include "halley/maths/circle.h"
using namespace Halley;

bool Circle::contains(Vector2f point) const
{
	return (point - centre).squaredLength() <= radius * radius;
}

bool Circle::overlaps(const Circle& circle) const
{
	const float r = radius + circle.radius;
	return (circle.centre - centre).squaredLength() <= r * r;
}

Circle Circle::getSpanningCircle(const std::vector<Vector2f>& points)
{
	// TODO: should use Matousek, Sharir, Welzl's algorithm (https://en.wikipedia.org/wiki/Smallest-circle_problem#Matou%C5%A1ek,_Sharir,_Welzl's_algorithm)

	Vector2f centre;
	for (auto& p: points) {
		centre += p;
	}
	centre /= float(points.size());

	float radius2 = 0;
	for (auto& p: points) {
		const auto d = (p - centre).squaredLength();
		if (d > radius2) {
			radius2 = d;
		}
	}

	return Circle(centre, std::sqrt(radius2));
}

Rename std::sqrtf -> std::sqrt because gcc is not standards compliant on that for whatever reason.


//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//

// UNSUPPORTED: c++98, c++03

//  Tuples of smart pointers; based on bug #18350
//  auto_ptr doesn't have a copy constructor that takes a const &, but tuple does.

#include <tuple>
#include <memory>

int main () {
    {
    std::tuple<std::unique_ptr<char>> up;
    std::tuple<std::shared_ptr<char>> sp;
    std::tuple<std::weak_ptr  <char>> wp;
//     std::tuple<std::auto_ptr  <char>> ap;
    }
    {
    std::tuple<std::unique_ptr<char[]>> up;
    std::tuple<std::shared_ptr<char[]>> sp;
    std::tuple<std::weak_ptr  <char[]>> wp;
//     std::tuple<std::auto_ptr  <char[]>> ap;
    }
    {
    std::tuple<std::unique_ptr<char[5]>> up;
    std::tuple<std::shared_ptr<char[5]>> sp;
    std::tuple<std::weak_ptr  <char[5]>> wp;
//     std::tuple<std::auto_ptr  <char[5]>> ap;
    }
}

//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//

// UNSUPPORTED: c++98, c++03

//  Tuples of smart pointers; based on bug #18350
//  auto_ptr doesn't have a copy constructor that takes a const &, but tuple does.

#include <tuple>
#include <memory>

int main () {
    {
    std::tuple<std::unique_ptr<char>> up;
    std::tuple<std::shared_ptr<char>> sp;
    std::tuple<std::weak_ptr  <char>> wp;
    }
    {
    std::tuple<std::unique_ptr<char[]>> up;
    std::tuple<std::shared_ptr<char[]>> sp;
    std::tuple<std::weak_ptr  <char[]>> wp;
    }
    // Smart pointers of type 'T[N]' are not tested here since they are not
    // supported by the standard nor by libc++'s implementation.
    // See http://reviews.llvm.org/D21320 for move information.
}

Fix warning in tuple tests. The test suite should now run clean with most warnings enabled

git-svn-id: 756ef344af921d95d562d9e9f9389127a89a6314@272822 91177308-0d34-0410-b5e6-96231b3b80d8


#include "catch.hpp"

//#define KASSERT REQUIRE

#include <Segment.hh>

#include <cstring>

#define SEGMENTSIZE 4096

SCENARIO("Memory segment representation", "[kernelheap]")
{
   GIVEN("A memory segment")
   {
      char* memorySegment = new char[SEGMENTSIZE];
      memset(memorySegment, 0x55, SEGMENTSIZE);

      WHEN("Constructing a segment header for the segment")
      {
         Segment* segment = new(memorySegment) Segment();

         THEN("The size is zero")
         {
            CHECK(segment->getSize() == 0);
         }

         THEN("The segment is marked as unallocated")
         {
            CHECK(segment->isAllocated() == false);
         }

         AND_WHEN("Updating the checksum")
         {
            segment->updateChecksum();

            THEN("The checksum is valid")
            {
               CHECK(segment->verifyChecksum() == true);
            }

            AND_WHEN("The segment is mutated")
            {
               segment->setSize(1110);

               THEN("The checksum is no longer valid")
               {
                  CHECK(segment->verifyChecksum() == false);
               }
            }
         }
      }
   }
}

#include "catch.hpp"

//#define KASSERT REQUIRE

#include <Segment.hh>

#include <cstring>

#define SEGMENTSIZE 4096

SCENARIO("Memory segment representation", "[kernelheap]")
{
   GIVEN("A memory segment")
   {
      char* memorySegment = new char[SEGMENTSIZE];
      memset(memorySegment, 0x55, SEGMENTSIZE);

      WHEN("Constructing a segment header for the segment")
      {
         Segment* segment = new(memorySegment) Segment();

         THEN("The size is zero")
         {
            CHECK(segment->getSize() == 0);
         }

         THEN("The segment is marked as unallocated")
         {
            CHECK(segment->isAllocated() == false);
         }

         THEN("The segment checksum is valid")
         {
            CHECK(segment->verifyChecksum() == true);
         }

         AND_WHEN("Updating the checksum")
         {
            segment->updateChecksum();

            THEN("The checksum is valid")
            {
               CHECK(segment->verifyChecksum() == true);
            }

            AND_WHEN("The segment is mutated")
            {
               segment->setSize(1110);

               THEN("The checksum is no longer valid")
               {
                  CHECK(segment->verifyChecksum() == false);
               }
            }
         }
      }
   }
}

Check that newly created has correct checksum


// 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 "printing/backend/print_backend.h"

namespace printing {

PrinterBasicInfo::PrinterBasicInfo() : printer_status(0) {}

PrinterBasicInfo::~PrinterBasicInfo() {}

PrinterCapsAndDefaults::PrinterCapsAndDefaults() {}

PrinterCapsAndDefaults::~PrinterCapsAndDefaults() {}

PrintBackend::~PrintBackend() {}

}  // namespace printing

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

#include "printing/backend/print_backend.h"

namespace printing {

PrinterBasicInfo::PrinterBasicInfo()
    : printer_status(0),
      is_default(false) {}

PrinterBasicInfo::~PrinterBasicInfo() {}

PrinterCapsAndDefaults::PrinterCapsAndDefaults() {}

PrinterCapsAndDefaults::~PrinterCapsAndDefaults() {}

PrintBackend::~PrintBackend() {}

}  // namespace printing

Coverity: Initialize a variable in PrinterBasicInfo.

BUG=none
TEST=none
CID=16140

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

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


#include "ewk_settings_private.h"

#include "net/http/http_stream_factory.h"

void Ewk_Settings::setSpdyEnabled(bool flag)
{
  net::HttpStreamFactory::set_spdy_enabled(flag);
}

void Ewk_Settings::setCurrentLegacyFontSizeMode(tizen_webview::Legacy_Font_Size_Mode mode) {
    m_currentLegacyFontSizeMode = mode;
    m_preferences.current_legacy_font_size_mode = static_cast<content::LegacyFontSizeMode>(mode);
}

#include "ewk_settings_private.h"

#include "net/http/http_stream_factory.h"

void Ewk_Settings::setSpdyEnabled(bool flag)
{
  net::HttpStreamFactory::set_spdy_enabled(flag);
}

void Ewk_Settings::setCurrentLegacyFontSizeMode(tizen_webview::Legacy_Font_Size_Mode mode) {
    m_currentLegacyFontSizeMode = mode;
#if !defined(EWK_BRINGUP)
    m_preferences.current_legacy_font_size_mode = static_cast<content::LegacyFontSizeMode>(mode);
#endif
}

Disable call to WebPreferences::current_legacy_font_size_mode. Missing API.

Signed-off-by: Antonio Gomes <a1.gomes@sisa.samsung.com>

Conflicts:
	impl/API/ewk_settings_private.cc


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

#include "chrome/browser/ui/webui/print_preview_ui.h"

#include "base/values.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/print_preview_handler.h"
#include "chrome/browser/ui/webui/print_preview_ui_html_source.h"
#include "content/browser/browser_thread.h"
#include "content/browser/tab_contents/tab_contents.h"

PrintPreviewUI::PrintPreviewUI(TabContents* contents)
    : WebUI(contents),
      html_source_(new PrintPreviewUIHTMLSource()) {
  // PrintPreviewUI owns |handler|.
  PrintPreviewHandler* handler = new PrintPreviewHandler();
  AddMessageHandler(handler->Attach(this));

  // Set up the chrome://print/ source.
  contents->profile()->GetChromeURLDataManager()->AddDataSource(html_source_);
}

PrintPreviewUI::~PrintPreviewUI() {
}

PrintPreviewUIHTMLSource* PrintPreviewUI::html_source() {
  return html_source_.get();
}

void PrintPreviewUI::PreviewDataIsAvailable(int expected_pages_count) {
  FundamentalValue pages_count(expected_pages_count);
  CallJavascriptFunction("createPDFPlugin", pages_count);
}

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

#include "chrome/browser/ui/webui/print_preview_ui.h"

#include "base/values.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/print_preview_handler.h"
#include "chrome/browser/ui/webui/print_preview_ui_html_source.h"
#include "content/browser/browser_thread.h"
#include "content/browser/tab_contents/tab_contents.h"

PrintPreviewUI::PrintPreviewUI(TabContents* contents)
    : WebUI(contents),
      html_source_(new PrintPreviewUIHTMLSource()) {
  // PrintPreviewUI owns |handler|.
  PrintPreviewHandler* handler = new PrintPreviewHandler();
  AddMessageHandler(handler->Attach(this));

  // Set up the chrome://print/ source.
  contents->profile()->GetChromeURLDataManager()->AddDataSource(html_source_);
}

PrintPreviewUI::~PrintPreviewUI() {
}

PrintPreviewUIHTMLSource* PrintPreviewUI::html_source() {
  return html_source_.get();
}

void PrintPreviewUI::PreviewDataIsAvailable(int expected_pages_count) {
  FundamentalValue pages_count(expected_pages_count);
  CallJavascriptFunction("updatePrintPreview", pages_count);
}

Print Preview: Fix typo from r78639.

Print Preview: Fix typo from r78639.

BUG=76707
TEST=page count initialized correctly in print preview.
R=arv@chromium.org
Review URL: http://codereview.chromium.org/6688041

git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@78747 4ff67af0-8c30-449e-8e8b-ad334ec8d88c


#include <nstd/Debug.h>
#include <nstd/Variant.h>

void_t testVariant()
{
  // test default constructor
  {
    Variant var;
    ASSERT(var.isNull());
    ASSERT(var.toBool() == false);
  }

  // test boolean constructor
  {
    Variant var(true);
    ASSERT(var.toBool() == true);
  }

  // test map constructor
  {
    HashMap<String, Variant> map;
    map.append("dasd", Variant(String("yes")));
    Variant var(map);
    ASSERT(((const Variant&)var).toMap().find("dasd")->toString() == "yes");
    ASSERT(var.toMap().find("dasd")->toString() == "yes");
  }

}

#include <nstd/Debug.h>
#include <nstd/Variant.h>

void_t testVariant()
{
  // test default constructor
  {
    Variant var;
    ASSERT(var.isNull());
    ASSERT(var.toBool() == false);
  }

  // test boolean constructor
  {
    Variant var(true);
    ASSERT(var.toBool() == true);
  }

  // test map constructor
  {
    HashMap<String, Variant> map;
    map.append(_T("dasd"), Variant(String(_T("yes"))));
    Variant var(map);
    ASSERT(((const Variant&)var).toMap().find(_T("dasd"))->toString() == _T("yes"));
    ASSERT(var.toMap().find(_T("dasd"))->toString() == _T("yes"));
  }

}

Use Unicode compatible in Variant test

Variant: Use Unicode compatible in Variant test


#include "square.h"
#include <gtest/gtest.h>

TEST(TestSuite, squareTwo)
{
  const double ret = square(2);
  ASSERT_EQ(4, ret);
}

TEST(TestSuite, squareFour)
{
  const double ret = square(4.1);
  ASSERT_EQ(16.81, ret);
}

// Run all the tests that were declared with TEST()
int main(int argc, char **argv){
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

#include "square.h"
#include <gtest/gtest.h>

TEST(TestSuite, squareTwo)
{
  const double ret = square(2);
  ASSERT_EQ(5, ret);
}

TEST(TestSuite, squareFour)
{
  const double ret = square(4.1);
  ASSERT_EQ(16.81, ret);
}

// Run all the tests that were declared with TEST()
int main(int argc, char **argv){
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

Make sure failed tests actually fail.

Make sure failed tests actually fail.


#include "HaxeRuntime.h"
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif

#include "PrintfCaptureTypes.h"
#include "CoreMinimal.h"
#include "uhx/expose/HxcppRuntime.h"
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>

#if PLATFORM_WINDOWS && !defined(vsnprintf)
	#define vsnprintf _vsnprintf
#endif

#define PRINTF_BUFFER_SIZE 2048

static FString& getPrintfString() {
	static FString str;
	return str;
}

void uhx_printf(const char * const format, ...) {
	va_list args;
	int len = 0;
	char buffer[PRINTF_BUFFER_SIZE];

	va_start( args, format );
	len = vsnprintf(buffer, PRINTF_BUFFER_SIZE, format, args);

	if (len < 0) {
		strcpy(buffer, "(internal printf capture format error)\n");
	} else {
		buffer[len] = '\0';
	}

	getPrintfString() += UTF8_TO_TCHAR(buffer);

	va_end(args);
}

unreal::UIntPtr PrintfHelper_obj::getAndFlush() {
	FString ret = getPrintfString();
	getPrintfString() = TEXT("");
	return uhx::expose::HxcppRuntime::constCharToString(TCHAR_TO_UTF8(*ret));
}

#include "HaxeRuntime.h"
#include "uhx/NoDeprecateHeader.h"

#include "PrintfCaptureTypes.h"
#include "CoreMinimal.h"
#include "uhx/expose/HxcppRuntime.h"
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>

#if PLATFORM_WINDOWS && !defined(vsnprintf)
	#define vsnprintf _vsnprintf
#endif

#define PRINTF_BUFFER_SIZE 2048

static FString& getPrintfString() {
	static FString str;
	return str;
}

void uhx_printf(const char * const format, ...) {
	va_list args;
	int len = 0;
	char buffer[PRINTF_BUFFER_SIZE];

	va_start( args, format );
	len = vsnprintf(buffer, PRINTF_BUFFER_SIZE, format, args);

	if (len < 0) {
		strcpy(buffer, "(internal printf capture format error)\n");
	} else {
		buffer[len] = '\0';
	}

	getPrintfString() += UTF8_TO_TCHAR(buffer);

	va_end(args);
}

unreal::UIntPtr PrintfHelper_obj::getAndFlush() {
	FString ret = getPrintfString();
	getPrintfString() = TEXT("");
	return uhx::expose::HxcppRuntime::constCharToString(TCHAR_TO_UTF8(*ret));
}

#include "uhx/NoDeprecateFooter.h"

[CL-16676] Update to latest perforce change
Change 16676 by waneck@wnk-razer on 2018/03/08 15:01:22

[unreal.hx] Get rid of the CRT SECURE deprecation warnings on PrintfCapture


#include "Person.h"
#include <gtest/gtest.h>

TEST(GreeterTests, PersonGetNameTest) {
  Person p{"Woz"};
  ASSERT_STREQ(p.getName().c_str(), "Woz");
}

#include "Person.h"
#include <stdexcept>
#include <gtest/gtest.h>

TEST(GreeterTests, PersonValidCtorTest) {
	ASSERT_NO_THROW({
		Person p{"Alexa"};
	});
}

TEST(GreeterTests, PersonInvalidCtorTest) {
	ASSERT_THROW({
		Person p{""};
	}, std::invalid_argument);
}

TEST(GreeterTests, PersonGetNameTest) {
  Person p{"Woz"};
  ASSERT_STREQ(p.getName().c_str(), "Woz");
}

Add UT for invalid param in ctor

Add UT for invalid param in ctor


/*
Copyright (C) 2010 by Frank Richter

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Library General Public License for more details.

You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "../memutil.h"

namespace CS {
  namespace Platform {
    namespace Implementation {

      size_t GetMaxVirtualSize()
      {
	// Guess available virtual address space ...
      #if CS_PROCESSOR_SIZE == 32
	// 32-bit: 2GiB virtual address space
	return 2 * 1024 * 1024;
      #else
	// 64-bit: 8TiB virtual address space
	return 8 * 1024 * 1024 * 1024;
      #endif
      }

    } // End namespace Implementation
  } // End namespace Platform
} // End namespace CS

/*
Copyright (C) 2010 by Frank Richter

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Library General Public License for more details.

You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "../memutil.h"

namespace CS {
  namespace Platform {
    namespace Implementation {

      size_t GetMaxVirtualSize()
      {
	// Guess available virtual address space ...
      #if CS_PROCESSOR_SIZE == 32
	// 32-bit: 2GiB virtual address space
	return 2 * 1024 * 1024;
      #else
	// 64-bit: 8TiB virtual address space
	return 8 * size_t (1024 * 1024 * 1024);
      #endif
      }

    } // End namespace Implementation
  } // End namespace Platform
} // End namespace CS

Fix integer overflow reported by gcc

Fix integer overflow reported by gcc

git-svn-id: 28d9401aa571d5108e51b194aae6f24ca5964c06@34079 8cc4aa7f-3514-0410-904f-f2cc9021211c


#include "Logger.h"
#include <string>

void Logger::Start() {
#ifdef ENABLE_3RVX_LOGTOFILE
    /* Disable buffering */
    setvbuf(stdout, NULL, _IONBF, 0);
    setvbuf(stderr, NULL, _IONBF, 0);

    FILE *out, *err;
    _wfreopen_s(&out, L"3RVX_Log.txt", L"w", stdout);
    _wfreopen_s(&err, L"3RVX_Log.txt", L"w", stderr);
#else
#ifdef ENABLE_3RVX_LOG
    AllocConsole();
    FILE *in, *out, *err;
    freopen_s(&in, "CONIN$", "r", stdin);
    freopen_s(&out, "CONOUT$", "w", stdout);
    freopen_s(&err, "CONOUT$", "w", stderr);
#endif
#endif
}

void Logger::Stop() {
#ifdef ENABLE_3RVX_LOGTOFILE
    CLOG(L"Logger stopped.");
    fclose(stdout);
    fclose(stderr);
#else
#ifdef ENABLE_3RVX_LOG
    FreeConsole();
#endif
#endif
}

#include "Logger.h"
#include <string>

void Logger::Start() {
#ifdef ENABLE_3RVX_LOGTOFILE
    /* Disable buffering */
    setvbuf(stdout, NULL, _IONBF, 0);
    setvbuf(stderr, NULL, _IONBF, 0);

    FILE *out, *err;
    _wfreopen_s(&out, L"3RVX_Log.txt", L"w", stdout);
    _wfreopen_s(&err, L"3RVX_Log.txt", L"w", stderr);
#else
#if ENABLE_3RVX_LOG != 0
    AllocConsole();
    FILE *in, *out, *err;
    freopen_s(&in, "CONIN$", "r", stdin);
    freopen_s(&out, "CONOUT$", "w", stdout);
    freopen_s(&err, "CONOUT$", "w", stderr);
#endif
#endif
}

void Logger::Stop() {
#ifdef ENABLE_3RVX_LOGTOFILE
    CLOG(L"Logger stopped.");
    fclose(stdout);
    fclose(stderr);
#else
#if ENABLE_3RVX_LOG != 0
    FreeConsole();
#endif
#endif
}

Fix release build console bug

Fix release build console bug


// 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/chromeos/status_area_button.h"

#include "app/gfx/canvas.h"
#include "app/gfx/skbitmap_operations.h"
#include "app/resource_bundle.h"
#include "grit/theme_resources.h"
#include "views/border.h"
#include "views/view.h"

////////////////////////////////////////////////////////////////////////////////
// StatusAreaButton

StatusAreaButton::StatusAreaButton(views::ViewMenuDelegate* menu_delegate)
    : MenuButton(NULL, std::wstring(), menu_delegate, false) {
  set_border(NULL);
  SetShowHighlighted(true);
}

void StatusAreaButton::Paint(gfx::Canvas* canvas, bool for_drag) {
  int bitmap_id;

  switch(state()) {
    case BS_NORMAL:
      bitmap_id = IDR_STATUSBAR_CONTAINER;
      break;
    case BS_HOT:
      bitmap_id = IDR_STATUSBAR_CONTAINER_HOVER;
      break;
    case BS_PUSHED:
      bitmap_id = IDR_STATUSBAR_CONTAINER_PRESSED;
      break;
    default:
      NOTREACHED();
  }
  SkBitmap* container =
      ResourceBundle::GetSharedInstance().GetBitmapNamed(bitmap_id);
  canvas->DrawBitmapInt(*container, 0, 0);
  canvas->DrawBitmapInt(icon(), 0, 0);
}

// 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/chromeos/status_area_button.h"

#include "app/gfx/canvas.h"
#include "app/gfx/skbitmap_operations.h"
#include "app/resource_bundle.h"
#include "grit/theme_resources.h"
#include "views/border.h"
#include "views/view.h"

////////////////////////////////////////////////////////////////////////////////
// StatusAreaButton

StatusAreaButton::StatusAreaButton(views::ViewMenuDelegate* menu_delegate)
    : MenuButton(NULL, std::wstring(), menu_delegate, false) {
  set_border(NULL);
  SetShowHighlighted(true);
}

void StatusAreaButton::Paint(gfx::Canvas* canvas, bool for_drag) {
  int bitmap_id;

  switch(state()) {
    case BS_NORMAL:
      bitmap_id = IDR_STATUSBAR_CONTAINER;
      break;
    case BS_HOT:
      bitmap_id = IDR_STATUSBAR_CONTAINER_HOVER;
      break;
    case BS_PUSHED:
      bitmap_id = IDR_STATUSBAR_CONTAINER_PRESSED;
      break;
    default:
      bitmap_id = IDR_STATUSBAR_CONTAINER;
      NOTREACHED();
  }
  SkBitmap* container =
      ResourceBundle::GetSharedInstance().GetBitmapNamed(bitmap_id);
  canvas->DrawBitmapInt(*container, 0, 0);
  canvas->DrawBitmapInt(icon(), 0, 0);
}

Fix for Release build break

Fix for Release build break

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

git-svn-id: http://src.chromium.org/svn/trunk/src@29656 4ff67af0-8c30-449e-8e8b-ad334ec8d88c

Former-commit-id: 43f80bde7c30b954275cbe636b8522517653304d


#include "generator.h"

int main()
{
	QStringList l;
	l
	<< "kernel_metamodel.xml"
	<< "basicbehaviors_metamodel.xml"
	<< "trace.xml"
	<< "requirements_metamodel.xml"
	<< "class_metamodel.xml"
	<< "usecase_metamodel.xml"
	<< "sequence_metamodel.xml"
	//<< "communication_metamodel.xml"
	<< "statemachines_metamodel.xml"
	//<< "deployment.xml"
	//<< "component_metamodel.xml"
	//<< "timing_metamodel.xml"
	<< "activity_metamodel.xml"
	<< "package.xml"
	<< "bpel.xml"
	<< "qrealparallel_metamodel.xml";
	delete (new Generator(l));
	return 0;
}

#include "generator.h"

int main()
{
	QStringList l;
	l
	<< "kernel_metamodel.xml"
	<< "basicbehaviors_metamodel.xml"
	<< "trace.xml"
	<< "requirements_metamodel.xml"
	<< "class_metamodel.xml"
	<< "usecase_metamodel.xml"
	<< "sequence_metamodel.xml"
	//<< "communication_metamodel.xml"
	<< "statemachines_metamodel.xml"
	//<< "deployment.xml"
	//<< "component_metamodel.xml"
	//<< "timing_metamodel.xml"
	<< "activity_metamodel.xml"
	<< "package.xml"
	<< "bpel.xml"
	<< "qrealparallel_metamodel.xml";
	Generator generator(l);
	return 0;
}

Create generator object on stack. Testing build system.