#include <3ds.h>
#include <stdio.h>

void shutdown3DS()
{
	Handle ptmSysmHandle = 0;
	Result result = srvGetServiceHandle(&ptmSysmHandle, "ns:s");
	if (result != 0)
		return;

	// http://3dbrew.org/wiki/NSS:ShutdownAsync

	u32 *commandBuffer = getThreadCommandBuffer();
	commandBuffer[0] = 0x000E0000;

	svcSendSyncRequest(ptmSysmHandle);
	svcCloseHandle(ptmSysmHandle);
}

int main(int argc, char **argv) {
	hidScanInput();

#ifndef ALWAYS_SHUTDOWN
	// If any key is pressed, cancel the shutdown.
	if (hidKeysDown() != 0)
		goto done;
#endif
	shutdown3DS();

done:
	// Hack: the 3ds crashes ("An error has occcurred.") for some reason
	// without one iteration of the main loop.
	aptMainLoop();
	return 0;
}

#include <3ds.h>
#include <stdio.h>

void shutdown3DS()
{
	Handle nssHandle = 0;
	Result result = srvGetServiceHandle(&nssHandle, "ns:s");
	if (result != 0)
		return;

	// http://3dbrew.org/wiki/NSS:ShutdownAsync

	u32 *commandBuffer = getThreadCommandBuffer();
	commandBuffer[0] = 0x000E0000;

	svcSendSyncRequest(nssHandle);
	svcCloseHandle(nssHandle);
}

int main(int argc, char **argv) {
	hidScanInput();

#ifndef ALWAYS_SHUTDOWN
	// If any key is pressed, cancel the shutdown.
	if (hidKeysDown() != 0)
		goto done;
#endif
	shutdown3DS();

done:
	// Hack: the 3ds crashes ("An error has occcurred.") for some reason
	// without one iteration of the main loop.
	aptMainLoop();
	return 0;
}

Rename a variable due to using a different service.


// Copyright 2015 FMAW

#include <iostream>
#include <fstream>
#include "./grid.h"
#include "./gridmap.h"
#include <fat.h>
#include <nds.h>

namespace GridMap{

void loadDefaultGridMap( Grid &g ) { loadGridMap("defaultMap", g); }

void loadGridMap( const char* mapName, Grid &g ){
	FILE* test = fopen ("./defaultMap", "r");

	int rows, cols, aux;

	fscanf( test, "%d %d\n", &rows, &cols );
	for( int row = 0; row < rows; row++ ){
		for( int col = 0; col < cols; col++ ){
			if(col < cols-1) fscanf( test, "%d ", &aux );
			else fscanf( test, "%d\n", &aux );

			IndexPath path {row, col};
			g.cellAtIndexPath(path)->setBackgroundType(
				static_cast<CellBackgroundType>(aux)
			);

			g.cellAtIndexPath(path)->renderBackground();
		}
	}

	fclose(test);
}

}

// Copyright 2015 FMAW

#include <fat.h>
#include <nds.h>
#include <iostream>
#include <fstream>
#include "./grid.h"
#include "./gridmap.h"

namespace GridMap {

void loadDefaultGridMap(Grid &g) {
    loadGridMap("defaultMap", g);
}

void loadGridMap(const char *mapName, Grid &g) {
    FILE *test = fopen("./defaultMap", "r");

    if (test != NULL) {
        int rows, cols, aux;

        fscanf(test, "%d %d\n", &rows, &cols);
        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < cols; col++) {
                if (col < cols - 1) {
                    fscanf(test, "%d ", &aux);
                } else {
                    fscanf(test, "%d\n", &aux);
                }

                IndexPath path {row, col};
                g.cellAtIndexPath(path)->setBackgroundType(
                    static_cast<CellBackgroundType>(aux));

                g.cellAtIndexPath(path)->renderBackground();
            }
        }

        fclose(test);
    }
}

}  // namespace GridMap

Fix to prevent crashing if file couldn't be opened.


#include <glow/memory.h>

#include <glow/global.h>
#include <glow/Extension.h>

namespace {

GLint getMemoryInformation(GLenum pname)
{
    if (!glow::hasExtension("NVX_gpu_memory_info"))
        return -1;

    return glow::getInteger(pname);
}

}

namespace glow
{

namespace memory
{

GLint total()
{
    return getMemoryInformation(GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX);
}

GLint dedicated()
{
    return getMemoryInformation(GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX);
}

GLint available()
{
    return getMemoryInformation(GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX);
}

GLint evicted()
{
    return getMemoryInformation(GPU_MEMORY_INFO_EVICTED_MEMORY_NVX);
}

GLint evictionCount()
{
    return getMemoryInformation(GPU_MEMORY_INFO_EVICTION_COUNT_NVX);
}

}
}

#include <glow/memory.h>

#include <glow/global.h>
#include <glow/Extension.h>

namespace {

GLint getMemoryInformation(GLenum pname)
{
    if (!glow::hasExtension("NVX_gpu_memory_info"))
        return -1;

    return glow::getInteger(pname);
}

}

namespace glow
{

namespace memory
{

GLint total()
{
    return getMemoryInformation(GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX);
}

GLint dedicated()
{
    return getMemoryInformation(GL_GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX);
}

GLint available()
{
    return getMemoryInformation(GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX);
}

GLint evicted()
{
    return getMemoryInformation(GL_GPU_MEMORY_INFO_EVICTED_MEMORY_NVX);
}

GLint evictionCount()
{
    return getMemoryInformation(GL_GPU_MEMORY_INFO_EVICTION_COUNT_NVX);
}

}
}

Add missing GL_ prefixes to previously removed constants


/*
* This is an open source non-commercial project. Dear PVS-Studio, please check it.
* PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
*/

#include "mips_memory.h"
#include "mips_instr.h"

#include <infra/instrcache/instr_cache.h>

#include <iostream>
FuncInstr MIPSMemory::fetch_instr( Addr PC)
{
    auto it = instr_cache.find( PC);

    FuncInstr instr = ( it != instr_cache.end())
                      ? FuncInstr( it->second)
                      : FuncInstr( read( PC), PC);

    if ( it != instr_cache.end())
        instr_cache.update( PC, instr);

    return instr;
}

/*
* This is an open source non-commercial project. Dear PVS-Studio, please check it.
* PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
*/

#include "mips_memory.h"
#include "mips_instr.h"

#include <infra/instrcache/instr_cache.h>

FuncInstr MIPSMemory::fetch_instr( Addr PC)
{
    auto it = instr_cache.find( PC);

    FuncInstr instr = ( it != instr_cache.end())
                      ? FuncInstr( it->second)
                      : FuncInstr( read( PC), PC);

    instr_cache.update( PC, instr);

    return instr;
}

Update InstrCache in case of cache miss

Update InstrCache in case of cache miss


Test commit: Reverting whitespace changes

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


// For conditions of distribution and use, see copyright notice in license.txt

/**
 *  @file InventoryAsset.cpp
 *  @brief A class representing asset in inventory.
 */

#include "
#include "StableHeaders.h"
#include "InventoryAsset.h"
#include "InventoryFolder.h"

namespace Inventory
{

InventoryAsset::InventoryAsset(const QString &id, const QString &asset_reference,const QString &name, InventoryFolder *parent) :
    AbstractInventoryItem(id, name, parent), itemType_(AbstractInventoryItem::Type_Asset), assetReference_(asset_reference),
    libraryAsset_(false)
{
}

// virtual
InventoryAsset::~InventoryAsset()
{
}

bool InventoryAsset::IsDescendentOf(AbstractInventoryItem *searchFolder)
{
    forever
    {
        AbstractInventoryItem *parent = GetParent();
        if (parent)
        {
            if (parent == searchFolder)
                return true;
            else
                return parent->IsDescendentOf(searchFolder);
        }

        return false;
    }
}

/*
int InventoryAsset::ColumnCount() const
{
    return itemData_.count();
}

int InventoryAsset::Row() const
{
    if (GetParent())
        return GetParent()->Children().indexOf(const_cast<InventoryAsset *>(this));

    return 0;
}
*/

}

// For conditions of distribution and use, see copyright notice in license.txt

/**
 *  @file InventoryAsset.cpp
 *  @brief A class representing asset in inventory.
 */

#include "StableHeaders.h"
#include "InventoryAsset.h"
#include "InventoryFolder.h"

namespace Inventory
{

InventoryAsset::InventoryAsset(const QString &id, const QString &asset_reference,const QString &name, InventoryFolder *parent) :
    AbstractInventoryItem(id, name, parent), itemType_(AbstractInventoryItem::Type_Asset), assetReference_(asset_reference),
    libraryAsset_(false)
{
}

// virtual
InventoryAsset::~InventoryAsset()
{
}

bool InventoryAsset::IsDescendentOf(AbstractInventoryItem *searchFolder)
{
    forever
    {
        AbstractInventoryItem *parent = GetParent();
        if (parent)
        {
            if (parent == searchFolder)
                return true;
            else
                return parent->IsDescendentOf(searchFolder);
        }

        return false;
    }
}

/*
int InventoryAsset::ColumnCount() const
{
    return itemData_.count();
}

int InventoryAsset::Row() const
{
    if (GetParent())
        return GetParent()->Children().indexOf(const_cast<InventoryAsset *>(this));

    return 0;
}
*/

}

Remove accidentally added "include ""

Remove accidentally added "include ""

git-svn-id: 65dd0ccd495961f396d5302e5521154b071f0302@2447 5b2332b8-efa3-11de-8684-7d64432d61a3


#include <ros/ros.h>
#include <tf2_ros/transform_broadcaster.h>

#include <geometry_msgs/PointStamped.h>
#include <geometry_msgs/TransformStamped.h>

class TomatoBroadcaster {
  tf2_ros::TransformBroadcaster broadcaster_;
  geometry_msgs::TransformStamped transform_;
  ros::Subscriber sub_;

public:
  TomatoBroadcaster(ros::NodeHandle node_handle)
    : transform_ {},
      sub_ {node_handle.subscribe<geometry_msgs::PointStamped>("tomato_point", 1, &TomatoBroadcaster::callback, this)}
  {
  }

private:
  void callback(const geometry_msgs::PointStamped::ConstPtr& msg)
  {
    transform_.header = msg->header;
    transform_.header.frame_id = "kinect";
    transform_.child_frame_id = "tomato";

    transform_.transform.translation.x = msg->point.x;
    transform_.transform.translation.y = msg->point.y;
    transform_.transform.translation.z = msg->point.z;
    transform_.transform.rotation.w = 1.0;

    broadcaster_.sendTransform(transform_);
  }
};

int main(int argc, char** argv){
  ros::init(argc, argv, "kinect_tomato_broadcaster_node");
  ros::NodeHandle node_handle;

  TomatoBroadcaster broadcaster {node_handle};

  ros::spin();

  return 0;
}

#include <ros/ros.h>
#include <tf2_ros/transform_broadcaster.h>

#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/TransformStamped.h>

class TomatoBroadcaster {
  tf2_ros::TransformBroadcaster broadcaster_;
  geometry_msgs::TransformStamped transform_;
  ros::Subscriber sub_;

public:
  TomatoBroadcaster(ros::NodeHandle& node_handle)
    : broadcaster_ {},
      transform_ {},
      sub_ {node_handle.subscribe<geometry_msgs::PoseStamped>("tomato_point", 1, &TomatoBroadcaster::callback, this)}
  {
  }

private:
  void callback(const geometry_msgs::PoseStamped::ConstPtr& msg)
  {
    transform_.header = msg->header;
    transform_.header.frame_id = "kinect";
    transform_.child_frame_id = "tomato";

    transform_.transform.translation.x = msg->pose.position.x;
    transform_.transform.translation.y = msg->pose.position.y;
    transform_.transform.translation.z = msg->pose.position.z;
    transform_.transform.rotation = msg->pose.orientation;

    broadcaster_.sendTransform(transform_);
  }
};

int main(int argc, char** argv){
  ros::init(argc, argv, "kinect_tomato_broadcaster_node");
  ros::NodeHandle node_handle;

  TomatoBroadcaster broadcaster {node_handle};

  ros::spin();

  return 0;
}

Update message type for PoseStamped

Update message type for PoseStamped


#include "application.h"
#include "Adafruit_LEDBackpack.h"

Adafruit_8x8matrix matrix1;
Adafruit_8x8matrix matrix2;
Adafruit_8x8matrix matrix3;

static const uint8_t smile[] = {
  0b00111100,
  0b01000010,
  0b10100101,
  0b10000001,
  0b10100101,
  0b10011001,
  0b01000010,
  0b00111100
};

void setup()
{
  Wire.begin();
  matrix1.begin(0x70);
  matrix2.begin(0x71);
  matrix3.begin(0x72);
}

void loop()
{
  matrix1.clear();
  delay(500);
  matrix1.drawBitmap(0, 0, smile, 8, 8, LED_ON);
  matrix1.writeDisplay();
  delay(500);
}

#include "application.h"
#include "Adafruit_LEDBackpack.h"

Adafruit_8x8matrix matrix1;
Adafruit_8x8matrix matrix2;
Adafruit_8x8matrix matrix3;

static const uint8_t smile[] = {
  0b00111100,
  0b01000010,
  0b10100101,
  0b10000001,
  0b10100101,
  0b10011001,
  0b01000010,
  0b00111100
};

int currentTemperature = 0;
int desiredTemperature = 0;
bool isHeatOn = false;
bool isFanOn = false;

int setTemperature(String t)
{
  return 1;
}

void setup()
{
  Wire.begin();
  matrix1.begin(0x70);
  matrix2.begin(0x71);
  matrix3.begin(0x72);

  Spark.function("set_temp", setTemperature);
  Spark.variable("current_temp", &currentTemperature, INT);
  Spark.variable("desired_temp", &desiredTemperature, INT);
  Spark.variable("is_heat_on", &isHeatOn, BOOLEAN);
  Spark.variable("is_fan_on", &isFanOn, BOOLEAN);
}

void loop()
{
  matrix3.clear();
  matrix3.drawBitmap(0, 0, smile, 8, 8, LED_ON);
  matrix3.writeDisplay();
  delay(500);
}

Add Spark function and variables

Add Spark function and variables


#include "../../include/base/ErrorInfo.hpp"

namespace cutehmi {
namespace base {

QString ErrorInfo::toString() const
{
	QString result = str;
	result += "\n[error class: ";
	result += errClass;
	result += " code: ";
	result += code;
	result += "]";
	return result;
}

}
}

//(c)MP: Copyright © 2017, Michal Policht. All rights reserved.
//(c)MP: This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "../../include/base/ErrorInfo.hpp"

namespace cutehmi {
namespace base {

QString ErrorInfo::toString() const
{
	QString result = str;
	result += "\n[error class: ";
	result += errClass;
	result += " code: ";
	result += QString::number(code);
	result += "]";
	return result;
}

}
}

//(c)MP: Copyright © 2017, Michal Policht. All rights reserved.
//(c)MP: This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

Fix code to string conversion.

Fix code to string conversion.


//===--- Heap.cpp - Swift Language Heap Logic -----------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Implementations of the Swift heap
//
//===----------------------------------------------------------------------===//

#include "swift/Runtime/HeapObject.h"
#include "swift/Runtime/Heap.h"
#include "Private.h"
#include "swift/Runtime/Debug.h"
#include <stdlib.h>

using namespace swift;

void *swift::swift_slowAlloc(size_t size, size_t alignMask) {
  // FIXME: use posix_memalign if alignMask is larger than the system guarantee.
  void *p = malloc(size);
  if (!p) swift::crash("Could not allocate memory.");
  return p;
}

void swift::swift_slowDealloc(void *ptr, size_t bytes, size_t alignMask) {
  free(ptr);
}

//===--- Heap.cpp - Swift Language Heap Logic -----------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Implementations of the Swift heap
//
//===----------------------------------------------------------------------===//

#include "swift/Runtime/HeapObject.h"
#include "swift/Runtime/Heap.h"
#include "Private.h"
#include "swift/Runtime/Debug.h"
#include <stdlib.h>

using namespace swift;

void *swift::swift_slowAlloc(size_t size, size_t alignMask) {
  void *p = AlignedAlloc(size, alignMask + 1);
  if (!p) swift::crash("Could not allocate memory.");
  return p;
}

void swift::swift_slowDealloc(void *ptr, size_t bytes, size_t alignMask) {
  AlignedFree(ptr);
}

[Runtime] Fix swift_slowAlloc to respect its alignMask parameter.

Instead of calling malloc, call AlignedAlloc. That calls posix_memalign on platforms where it's available. The man page cautions to use it judiciously, but Apple OSes and Linux implement it to call through to malloc when the alignment is suitable. Presumably/hopefully other OSes do the same.

rdar://problem/22975669


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

// <random>

// template<class RealType = double>
// class piecewise_linear_distribution

// param_type param() const;

#include <random>
#include <cassert>

int main()
{
    {
        typedef std::piecewise_linear_distribution<> D;
        typedef D::param_type P;
        double b[] = {10, 14, 16, 17};
        double p[] = {25, 62.5, 12.5, 10};
        const size_t Np = sizeof(p) / sizeof(p[0]);
        P pa(b, b+Np+1, p);
        D d(pa);
        assert(d.param() == pa);
    }
}

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

// <random>

// template<class RealType = double>
// class piecewise_linear_distribution

// param_type param() const;

#include <random>
#include <cassert>

int main()
{
    {
        typedef std::piecewise_linear_distribution<> D;
        typedef D::param_type P;
        double b[] = {10, 14, 16, 17};
        double p[] = {25, 62.5, 12.5, 10};
        const size_t Np = sizeof(p) / sizeof(p[0]);
        P pa(b, b+Np, p);
        D d(pa);
        assert(d.param() == pa);
    }
}

Fix bug in test; found by AddressSanitizer

git-svn-id: 273b07cebdae5845b4a75aae04570b978db9eb50@177355 91177308-0d34-0410-b5e6-96231b3b80d8


#include "erlang_v8_drv.h"

Persistent<ObjectTemplate> GlobalFactory::Generate(Vm *vm,
    ErlNifEnv *env) {
  TRACE("GlobalFactory::Generate\n");
  Locker locker(vm->isolate);
  TRACE("GlobalFactory::Generate - 1\n");
  Isolate::Scope iscope(vm->isolate);
  TRACE("GlobalFactory::Generate - 2\n");
  HandleScope handle_scope;
  TRACE("GlobalFactory::Generate - 3\n");
  Context::Scope scope(Context::New());

  Local<ObjectTemplate> global = ObjectTemplate::New();
  Local<Object> erlang = Object::New();

  global->Set(String::New("erlang"), erlang);
  erlang->Set(String::New("vm"), ErlWrapper::MakeHandle(vm, env, vm->term));

  return Persistent<ObjectTemplate>::New(global);
}

#include "erlang_v8_drv.h"

Persistent<ObjectTemplate> GlobalFactory::Generate(Vm *vm,
    ErlNifEnv *env) {
  TRACE("GlobalFactory::Generate\n");
  Locker locker(vm->isolate);
  TRACE("GlobalFactory::Generate - 1\n");
  Isolate::Scope iscope(vm->isolate);
  TRACE("GlobalFactory::Generate - 2\n");
  HandleScope handle_scope;
  TRACE("GlobalFactory::Generate - 3\n");
  Context::Scope scope(Context::New());

  Local<ObjectTemplate> global = ObjectTemplate::New();
  Local<Object> erlangV8 = Object::New();

  global->Set(String::New("erlang_v8"), erlangV8);
  erlangV8->Set(String::New("vm"), ErlWrapper::MakeHandle(vm, env, vm->term));

  return Persistent<ObjectTemplate>::New(global);
}

Call it erlang_v8 instead of erlang.

Call it erlang_v8 instead of erlang.


/* Copyright 2022 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/mlir/quantization/tensorflow/utils/quant_spec.h"

#include <memory>

#include "tensorflow/compiler/mlir/lite/quantization/quantization_utils.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"

namespace mlir {
namespace quant {

std::unique_ptr<OpQuantScaleSpec> GetTfQuantScaleSpec(Operation* op) {
  auto scale_spec = std::make_unique<OpQuantScaleSpec>();
  if (llvm::isa<
          // clang-format off
          // go/keep-sorted start
          TF::ConcatV2Op,
          TF::IdentityOp,
          TF::MaxPoolOp,
          TF::ReshapeOp
          // go/keep-sorted end
          // clang-format on
          >(op)) {
    scale_spec->has_same_scale_requirement = true;
  }
  return scale_spec;
}

}  // namespace quant
}  // namespace mlir

/* Copyright 2022 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/mlir/quantization/tensorflow/utils/quant_spec.h"

#include <memory>

#include "tensorflow/compiler/mlir/lite/quantization/quantization_utils.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"

namespace mlir {
namespace quant {

std::unique_ptr<OpQuantScaleSpec> GetTfQuantScaleSpec(Operation* op) {
  auto scale_spec = std::make_unique<OpQuantScaleSpec>();
  if (llvm::isa<
          // clang-format off
          // go/keep-sorted start
          TF::ConcatV2Op,
          TF::IdentityOp,
          TF::MaxPoolOp,
          TF::PadV2Op,
          TF::ReshapeOp,
          TF::SqueezeOp
          // go/keep-sorted end
          // clang-format on
          >(op)) {
    scale_spec->has_same_scale_requirement = true;
  }
  return scale_spec;
}

}  // namespace quant
}  // namespace mlir

Add more same scale ops

Add more same scale ops

PiperOrigin-RevId: 436897574


//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

// <functional>

// class function<R(ArgTypes...)>

// explicit function();

#include <functional>
#include <cassert>

int main(int, char**)
{
    std::function<int(int)> f;
    assert(!f);

  return 0;
}

//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

// <functional>

// class function<R(ArgTypes...)>

// function();

#include <functional>
#include <cassert>

int main(int, char**)
{
    std::function<int(int)> f;
    assert(!f);

  return 0;
}

[NFC] Fix incorrect comment in std::function test

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


#include <ros/ros.h>
#include <tf2_ros/transform_broadcaster.h>
#include <geometry_msgs/TransformStamped.h>
#include <geometry_msgs/Point.h>

void pointCallback(const geometry_msgs::Point::ConstPtr& msg) {
  static tf2_ros::TransformBroadcaster br;
  geometry_msgs::TransformStamped transformStamped;

  transformStamped.header.stamp = ros::Time::now();
  transformStamped.header.frame_id = "kinect";
  transformStamped.child_frame_id = "tomato";
  transformStamped.transform.translation.x = msg->x;
  transformStamped.transform.translation.y = msg->y;
  transformStamped.transform.translation.z = msg->z;
  transformStamped.transform.rotation.x = 0;
  transformStamped.transform.rotation.y = 0;
  transformStamped.transform.rotation.z = 0;
  transformStamped.transform.rotation.w = 1;

  br.sendTransform(transformStamped);
}

int main(int argc, char** argv){
  ros::init(argc, argv, "tomato_broadcaster");
  ros::NodeHandle node;

  ros::Subscriber sub = node.subscribe("/tomato_point", 1, &pointCallback);

  ros::spin();
  return 0;
}

#include <ros/ros.h>
#include <tf2_ros/transform_broadcaster.h>
#include <geometry_msgs/TransformStamped.h>
#include <geometry_msgs/Point.h>

int offsetX, offsetY, offsetZ;

void pointCallback(const geometry_msgs::Point::ConstPtr& msg) {
  static tf2_ros::TransformBroadcaster br;
  geometry_msgs::TransformStamped transformStamped;

  transformStamped.header.stamp = ros::Time::now();
  transformStamped.header.frame_id = "kinect";
  transformStamped.child_frame_id = "tomato";
  transformStamped.transform.translation.x = msg->x + offsetX;
  transformStamped.transform.translation.y = msg->y + offsetY;
  transformStamped.transform.translation.z = msg->z + offsetZ;
  transformStamped.transform.rotation.x = 0;
  transformStamped.transform.rotation.y = 0;
  transformStamped.transform.rotation.z = 0;
  transformStamped.transform.rotation.w = 1;

  br.sendTransform(transformStamped);
}

int main(int argc, char** argv){
  ros::init(argc, argv, "tomato_broadcaster");
  ros::NodeHandle node;
  ros::NodeHandle private_node;

  private_node.getParam("kinect_offset_x", offsetX);
  private_node.getPrram("kinect_offset_y", offsetY);
  private_node.getPrram("kinect_offset_z", offsetZ);

  ros::Subscriber sub = node.subscribe("/tomato_point", 1, &pointCallback);

  ros::spin();
  return 0;
}

Add offset from rosparam on kinect_broadcaster


#include "qmljspreviewrunner.h"

#include <projectexplorer/environment.h>
#include <utils/synchronousprocess.h>

#include <QtGui/QMessageBox>
#include <QtGui/QApplication>

#include <QDebug>

namespace QmlJSEditor {
namespace Internal {

QmlJSPreviewRunner::QmlJSPreviewRunner(QObject *parent) :
    QObject(parent)
{
    // prepend creator/bin dir to search path (only useful for special creator-qml package)
    const QString searchPath = QCoreApplication::applicationDirPath()
                               + Utils::SynchronousProcess::pathSeparator()
                               + QString(qgetenv("PATH"));
    m_qmlViewerDefaultPath = Utils::SynchronousProcess::locateBinary(searchPath, QLatin1String("qml"));

    ProjectExplorer::Environment environment = ProjectExplorer::Environment::systemEnvironment();
    m_applicationLauncher.setEnvironment(environment.toStringList());
}

void QmlJSPreviewRunner::run(const QString &filename)
{
    QString errorMessage;
    if (!filename.isEmpty()) {
        m_applicationLauncher.start(ProjectExplorer::ApplicationLauncher::Gui, m_qmlViewerDefaultPath,
                                    QStringList() << filename);

    } else {
        errorMessage = "No file specified.";
    }

    if (!errorMessage.isEmpty())
        QMessageBox::warning(0, tr("Failed to preview Qt Quick file"),
                             tr("Could not preview Qt Quick (QML) file. Reason: \n%1").arg(errorMessage));
}

} // namespace Internal
} // namespace QmlJSEditor

#include "qmljspreviewrunner.h"

#include <projectexplorer/environment.h>
#include <utils/synchronousprocess.h>

#include <QtGui/QMessageBox>
#include <QtGui/QApplication>

#include <QDebug>

namespace QmlJSEditor {
namespace Internal {

QmlJSPreviewRunner::QmlJSPreviewRunner(QObject *parent) :
    QObject(parent)
{
    // prepend creator/bin dir to search path (only useful for special creator-qml package)
    const QString searchPath = QCoreApplication::applicationDirPath()
                               + Utils::SynchronousProcess::pathSeparator()
                               + QString(qgetenv("PATH"));
    m_qmlViewerDefaultPath = Utils::SynchronousProcess::locateBinary(searchPath, QLatin1String("qmlviewer"));

    ProjectExplorer::Environment environment = ProjectExplorer::Environment::systemEnvironment();
    m_applicationLauncher.setEnvironment(environment.toStringList());
}

void QmlJSPreviewRunner::run(const QString &filename)
{
    QString errorMessage;
    if (!filename.isEmpty()) {
        m_applicationLauncher.start(ProjectExplorer::ApplicationLauncher::Gui, m_qmlViewerDefaultPath,
                                    QStringList() << filename);

    } else {
        errorMessage = "No file specified.";
    }

    if (!errorMessage.isEmpty())
        QMessageBox::warning(0, tr("Failed to preview Qt Quick file"),
                             tr("Could not preview Qt Quick (QML) file. Reason: \n%1").arg(errorMessage));
}

} // namespace Internal
} // namespace QmlJSEditor

Fix QtQuick->Preview shortcut to start a qmlviewer

The executable has been renamed to 'qmlviewer' months ago


#include <znc/Client.h>
#include <znc/Modules.h>
#include <znc/IRCNetwork.h>
#include <znc/IRCSock.h>

class CPrioritySend : public CModule {
public:
	MODCONSTRUCTOR(CPrioritySend) {}

	virtual EModRet OnUserNotice(CString& sTarget, CString& sMessage) override {
		return ProcessMessage("NOTICE", sTarget, sMessage);
	}

	virtual EModRet OnUserMsg(CString& sTarget, CString& sMessage) override {
		return ProcessMessage("PRIVMSG", sTarget, sMessage);
	}

	EModRet ProcessMessage(const CString& sFunction, CString& sTarget, CString& sMessage) {
		if (!sMessage.TrimPrefix("(p!)")) // TODO: This could be a config variable
			return CONTINUE;

		CIRCSock* pIRCSock = GetNetwork()->GetIRCSock();

		if (!pIRCSock)
			return CONTINUE;

		pIRCSock->PutIRCQuick(sFunction + " " + sTarget + " :" + sMessage);

		return HALT;
	}
};

NETWORKMODULEDEFS(CPrioritySend, "Allows certain messages to be placed in front of the send queue")

#include <znc/Client.h>
#include <znc/Modules.h>
#include <znc/IRCNetwork.h>
#include <znc/IRCSock.h>

class CPrioritySend : public CModule {
public:
	MODCONSTRUCTOR(CPrioritySend) {}

	virtual EModRet OnUserNotice(CString& sTarget, CString& sMessage) override {
		return ProcessMessage("NOTICE", sTarget, sMessage);
	}

	virtual EModRet OnUserMsg(CString& sTarget, CString& sMessage) override {
		return ProcessMessage("PRIVMSG", sTarget, sMessage);
	}

	EModRet ProcessMessage(const CString& sFunction, CString& sTarget, CString& sMessage) {
		if (!sMessage.TrimPrefix("(p!)")) // TODO: This could be a config variable
			return CONTINUE;

		CIRCNetwork* pNetwork = GetNetwork();

		if (!pNetwork)
			return CONTINUE;

		CIRCSock* pIRCSock = pNetwork->GetIRCSock();

		if (!pIRCSock)
			return CONTINUE;

		pIRCSock->PutIRCQuick(sFunction + " " + sTarget + " :" + sMessage);

		return HALT;
	}
};

NETWORKMODULEDEFS(CPrioritySend, "Allows certain messages to be placed in front of the send queue")

Make sure GetNetwork doesn't return null


/*
 * GoForward.cpp
 *
 *  Created on: Mar 25, 2014
 *      Author: user
 */

#include "GoBackward.h"

GoBackward::GoBackward(Robot* robot):Behavior(robot) {
	// TODO Auto-generated constructor stub

}
bool GoBackward::startCondition()
{

	return false;
}
void GoBackward::action()
{

}
bool GoBackward::stopCondition()
{
	return false;
}
GoBackward::~GoBackward() {
	// TODO Auto-generated destructor stub
}

/*
 * GoForward.cpp
 *
 *  Created on: Mar 25, 2014
 *      Author: user
 */

#include "GoBackward.h"

GoBackward::GoBackward(Robot* robot):Behavior(robot), _steps_count(0)
{
}

bool GoBackward::startCondition()
{
	return true;
}

void GoBackward::action()
{
	++_steps_count;
	_robot->setSpeed(-0.1,0.0);
}

bool GoBackward::stopCondition()
{
	if (_steps_count < 10)
	{
		return false;
	}
	else
	{
		_steps_count = 0;
		_robot->setSpeed(0.0, 0.0);
		return true;
	}

}

GoBackward::~GoBackward()
{
}

Add logic to this behavior

Add logic to this behavior


#include <GL/glew.h> // to load OpenGL extensions at runtime
#include <GLFW/glfw3.h> // to set up the OpenGL context and manage window lifecycle and inputs

#include <stdio.h>
#include <iostream>

/// The main function

int main () {
	std::cout << "Hello !" << std::endl;
	return 0;
}

Include headers for GLEW and glfw3

Include headers for GLEW and glfw3

GLEW is used to load OpenGL extensions (hardware dependent) at runtime.
glfw3 is used to create a window, an OpenGL context, and handle
interactions.

Former-commit-id: 4d2c192166c2735a8d6150e11838cb8c8f3a1382


#include <iostream>
#include "configure.hpp"
#include "parsers/md_parser.hpp"
#include "display_drivers/ncurses_display_driver.hpp"

using namespace std;

int main(int argc, char ** argv) {
	cout << "mdl v" << MDL_VERSION_STRING << endl;
	if (argc < 2) {
		cerr << "mdl: missing at least one argument" << endl;
		return 1;
	}

	MdParser parser(argv[1]);
	NcursesDisplayDriver drv;
	drv.display(parser.get_document());
	return 0;
}

#include "configure.hpp"
#include "parsers/md_parser.hpp"
#include "display_drivers/ncurses_display_driver.hpp"

#include <iostream>
#include <locale.h>

using namespace std;

int main(int argc, char ** argv) {
	setlocale(LC_ALL, "");
	cout << "mdl v" << MDL_VERSION_STRING << endl;
	if (argc < 2) {
		cerr << "mdl: missing at least one argument" << endl;
		return 1;
	}

	MdParser parser(argv[1]);
	NcursesDisplayDriver drv;
	drv.display(parser.get_document());
	return 0;
}

Make program usable for all locales

Make program usable for all locales


//===--- MiscTidyModule.cpp - clang-tidy ----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "../ClangTidy.h"
#include "../ClangTidyModule.h"
#include "../ClangTidyModuleRegistry.h"
#include "DispatchOnceNonstaticCheck.h"

namespace clang {
namespace tidy {
namespace darwin {

class DarwinModule : public ClangTidyModule {
public:
  void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override {
    CheckFactories.registerCheck<DispatchOnceNonstaticCheck>(
        "darwin-dispatch-once-nonstatic");
  }
};

} // namespace darwin

// Register the DarwinTidyModule using this statically initialized variable.
static ClangTidyModuleRegistry::Add<darwin::DarwinModule>
    X("misc-module", "Adds miscellaneous lint checks.");

// This anchor is used to force the linker to link in the generated object file
// and thus register the DarwinModule.
volatile int DarwinModuleAnchorSource = 0;

} // namespace tidy
} // namespace clang

//===--- MiscTidyModule.cpp - clang-tidy ----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "../ClangTidy.h"
#include "../ClangTidyModule.h"
#include "../ClangTidyModuleRegistry.h"
#include "DispatchOnceNonstaticCheck.h"

namespace clang {
namespace tidy {
namespace darwin {

class DarwinModule : public ClangTidyModule {
public:
  void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override {
    CheckFactories.registerCheck<DispatchOnceNonstaticCheck>(
        "darwin-dispatch-once-nonstatic");
  }
};

} // namespace darwin

// Register the DarwinTidyModule using this statically initialized variable.
static ClangTidyModuleRegistry::Add<darwin::DarwinModule>
    X("darwin-module", "Adds Darwin-specific lint checks.");

// This anchor is used to force the linker to link in the generated object file
// and thus register the DarwinModule.
volatile int DarwinModuleAnchorSource = 0;

} // namespace tidy
} // namespace clang

[clang-tidy] Fix module registry name and description for Darwin clang-tidy module.

Summary: When creating the module, must have copy-pasted from the misc module, and forgotten to update the name/description of the module in the registry.

Reviewers: stephanemoore, benhamilton, gribozavr

Reviewed By: gribozavr

Subscribers: xazax.hun, cfe-commits

Tags: #clang, #clang-tools-extra, #llvm

Differential Revision: https://reviews.llvm.org/D68251

git-svn-id: a34e9779ed74578ad5922b3306b3d80a0c825546@373304 91177308-0d34-0410-b5e6-96231b3b80d8


// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.

// Simple test for a fuzzer: find interesting value of array index.
#include <assert.h>
#include <cstdint>
#include <cstring>
#include <cstddef>
#include <iostream>

static volatile int Sink;
const int kArraySize = 1234567;
int array[kArraySize];

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
  if (Size < 8) return 0;
  size_t a = 0;
  memcpy(&a, Data, 8);
  Sink = array[a % (kArraySize + 1)];
  return 0;
}

// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.

// Simple test for a fuzzer: find interesting value of array index.
#include <assert.h>
#include <cstdint>
#include <cstring>
#include <cstddef>
#include <iostream>

static volatile int Sink;
const int kArraySize = 1234567;
int array[kArraySize];

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
  if (Size < 8) return 0;
  uint64_t a = 0;
  memcpy(&a, Data, 8);
  Sink = array[a % (kArraySize + 1)];
  return 0;
}

Update Load test to work on 32 bits.

[libFuzzer] Update Load test to work on 32 bits.

We should ensure the size of the variable `a` is 8 bytes. Otherwise, this
generates a stack buffer overflow inside the memcpy call in 32 bits machines.
(We write more bytes than the size of a, when it is 4 bytes)

Differential Revision: https://reviews.llvm.org/D29602

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


#include "yuyvtoyuv420.h"

YUYVtoYUV420::YUYVtoYUV420(QString id, StatisticsInterface *stats,
                           std::shared_ptr<HWResourceManager> hwResources) :
      Filter(id, "YUYVtoYUV420", stats, hwResources, YUYVVIDEO, YUV420VIDEO)
{}

void YUYVtoYUV420::process()
{
  std::unique_ptr<Data> input = getInput();

  while(input)
  {
    uint32_t finalDataSize = input->width*input->height*2;
    std::unique_ptr<uchar[]> yuyv_frame(new uchar[finalDataSize]);

    yuyv2yuv420_cpu(input->data.get(), yuyv_frame.get(), input->width, input->height);

    input->type = YUYVVIDEO;
    input->data = std::move(yuyv_frame);
    input->data_size = finalDataSize;
    sendOutput(std::move(input));

    input = getInput();
  }
}

void YUYVtoYUV420::yuyv2yuv420_cpu(uint8_t* input, uint8_t* output,
                                   uint16_t width, uint16_t height)
{

}

#include "yuyvtoyuv420.h"

YUYVtoYUV420::YUYVtoYUV420(QString id, StatisticsInterface *stats,
                           std::shared_ptr<HWResourceManager> hwResources) :
      Filter(id, "YUYVtoYUV420", stats, hwResources, YUYVVIDEO, YUV420VIDEO)
{}

void YUYVtoYUV420::process()
{
  std::unique_ptr<Data> input = getInput();

  while(input)
  {
    uint32_t finalDataSize = input->width*input->height + input->width*input->height/2;
    std::unique_ptr<uchar[]> yuyv_frame(new uchar[finalDataSize]);

    yuyv2yuv420_cpu(input->data.get(), yuyv_frame.get(), input->width, input->height);

    input->type = YUYVVIDEO;
    input->data = std::move(yuyv_frame);
    input->data_size = finalDataSize;
    sendOutput(std::move(input));

    input = getInput();
  }
}

void YUYVtoYUV420::yuyv2yuv420_cpu(uint8_t* input, uint8_t* output,
                                   uint16_t width, uint16_t height)
{
  // Luma pixels
  for(int i = 0; i < width*height; i += 2)
  {
    output[i] = input[i*2];
    output[i + 1] = input[i*2 + 2];
  }
}

Convert luma pixels from YUYV to YUV420

feature(Processing): Convert luma pixels from YUYV to YUV420

Still working on chroma


#include "scanner/api/kernel.h"
#include "scanner/api/op.h"
#include "scanner/util/memory.h"

namespace scanner {

class DiscardKernel : public BatchedKernel {
 public:
  DiscardKernel(const KernelConfig& config)
    : BatchedKernel(config),
      device_(config.devices[0]),
      work_item_size_(config.work_item_size) {}

  void execute(const BatchedColumns& input_columns,
               BatchedColumns& output_columns) override {
    i32 input_count = (i32)num_rows(input_columns[0]);
    u8* output_block = new_block_buffer(device_, 1, input_count);
    for (i32 i = 0; i < input_count; ++i) {
      insert_element(output_columns[0], output_block, 1);
    }
  }

 private:
  DeviceHandle device_;
  i32 work_item_size_;
};

REGISTER_OP(Discard).input("ignore").output("dummy");

REGISTER_OP(DiscardFrame).frame_input("ignore").output("dummy");

REGISTER_KERNEL(Discard, DiscardKernel).device(DeviceType::CPU).num_devices(1);

REGISTER_KERNEL(Discard, DiscardKernel).device(DeviceType::GPU).num_devices(1);

REGISTER_KERNEL(DiscardFrame, DiscardKernel)
    .device(DeviceType::CPU)
    .num_devices(1);

REGISTER_KERNEL(DiscardFrame, DiscardKernel)
    .device(DeviceType::GPU)
    .num_devices(1);
}

#include "scanner/api/kernel.h"
#include "scanner/api/op.h"
#include "scanner/util/memory.h"

namespace scanner {

class DiscardKernel : public BatchedKernel {
 public:
  DiscardKernel(const KernelConfig& config)
    : BatchedKernel(config),
      device_(config.devices[0]),
      work_item_size_(config.work_item_size) {}

  void execute(const BatchedColumns& input_columns,
               BatchedColumns& output_columns) override {
    i32 input_count = (i32)num_rows(input_columns[0]);
    u8* output_block = new_block_buffer(device_, 1, input_count);
    for (i32 i = 0; i < input_count; ++i) {
      insert_element(output_columns[0], output_block, 1);
    }
  }

 private:
  DeviceHandle device_;
  i32 work_item_size_;
};

REGISTER_OP(Discard).input("ignore").output("dummy");

REGISTER_OP(DiscardFrame).frame_input("ignore").output("dummy");

REGISTER_KERNEL(Discard, DiscardKernel).device(DeviceType::CPU).num_devices(1);

REGISTER_KERNEL(Discard, DiscardKernel).device(DeviceType::GPU).num_devices(1);

REGISTER_KERNEL(DiscardFrame, DiscardKernel)
    .device(DeviceType::CPU)
    .batch()
    .num_devices(1);

REGISTER_KERNEL(DiscardFrame, DiscardKernel)
    .device(DeviceType::GPU)
    .batch()
    .num_devices(1);
}

Support batching on discard kernel

Support batching on discard kernel


// RUN: mkdir -p %T/read-file-config/
// RUN: cp %s %T/read-file-config/test.cpp
// RUN: echo 'Checks: "-*,modernize-use-nullptr"' > %T/read-file-config/.clang-tidy
// RUN: echo '[{"command": "cc -c -o test.o test.cpp", "directory": "%T/read-file-config", "file": "%T/read-file-config/test.cpp"}]' > %T/read-file-config/compile_commands.json
// RUN: clang-tidy %T/read-file-config/test.cpp | not grep "warning: .*\[clang-analyzer-deadcode.DeadStores\]$"
// RUN: clang-tidy -checks="-*,clang-analyzer-*" %T/read-file-config/test.cpp | grep "warning: .*\[clang-analyzer-deadcode.DeadStores\]$"

void f() {
  int x;
  x = 1;
  x = 2;
}

// RUN: mkdir -p %T/read-file-config/
// RUN: cp %s %T/read-file-config/test.cpp
// RUN: echo 'Checks: "-*,modernize-use-nullptr"' > %T/read-file-config/.clang-tidy
// RUN: echo '[{"command": "cc -c -o test.o test.cpp", "directory": "%/T/read-file-config", "file": "%/T/read-file-config/test.cpp"}]' > %T/read-file-config/compile_commands.json
// RUN: clang-tidy %T/read-file-config/test.cpp | not grep "warning: .*\[clang-analyzer-deadcode.DeadStores\]$"
// RUN: clang-tidy -checks="-*,clang-analyzer-*" %T/read-file-config/test.cpp | grep "warning: .*\[clang-analyzer-deadcode.DeadStores\]$"

void f() {
  int x;
  x = 1;
  x = 2;
}

Fix test from r330245 on Windows.

Fix test from r330245 on Windows.

git-svn-id: a34e9779ed74578ad5922b3306b3d80a0c825546@330305 91177308-0d34-0410-b5e6-96231b3b80d8


// RUN: clang-cc -fsyntax-only -verify %s
// XFAIL

template<typename T>
struct X0 {
  typedef int size_type;

  size_type f0() const;
};

template<typename T>
typename X0<T>::size_type X0<T>::f0() const { }

// RUN: clang-cc -fsyntax-only -verify %s
// XFAIL

template<typename T> struct X1 { };

template<typename T>
struct X0 {
  typedef int size_type;
  typedef T value_type;

  size_type f0() const;
  value_type *f1();
  X1<value_type*> f2();
};

template<typename T>
typename X0<T>::size_type X0<T>::f0() const {
  return 0;
}

template<typename U>
typename X0<U>::value_type *X0<U>::f1() {
  return 0;
};

template<typename U>
X1<typename X0<U>::value_type*> X0<U>::f2() {
  return 0;
};

Make the recanonicalization-for-an-out-of-line-definition test case a bit trickier

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


#include "common.th"

// c <- multiplicand
// d <- multiplier
// b -> product
.global imul
imul:
    pushall(h,i,j,k)

    i <- d == 0
    jnzrel(i, L_done)
    h <- 1
    b <- 0

    j <- c >> 31    // save sign bit in j
    j <- -j         // convert sign to flag
    c <- c ^ j      // adjust multiplicand
    c <- c - j

    k <- d >> 31    // save sign bit in k
    k <- -k         // convert sign to flag
    d <- d ^ k      // adjust multiplier
    d <- d - k

    j <- j ^ k      // final flip flag is in j

L_top:
    // use constant 1 in h to combine instructions
    i <- d & h - 1
    i <- c &~ i
    b <- b + i
    c <- c << 1
    d <- d >> 1
    i <- d <> 0
    jnzrel(i, L_top)

L_done:
    b <- b ^ j      // adjust product for signed math
    b <- b - j

    popall(h,i,j,k)
    ret

#include "common.th"

// c <- multiplicand
// d <- multiplier
// b -> product
.global imul
imul:
    pushall(h,i,j)

    i <- d == 0
    jnzrel(i, L_done)
    h <- 1
    b <- 0

    j <- d >> 31    // save sign bit in j
    j <- -j         // convert sign to flag
    d <- d ^ j      // adjust multiplier
    d <- d - j

L_top:
    // use constant 1 in h to combine instructions
    i <- d & h - 1
    i <- c &~ i
    b <- b + i
    c <- c << 1
    d <- d >> 1
    i <- d <> 0
    jnzrel(i, L_top)

L_done:
    b <- b ^ j      // adjust product for signed math
    b <- b - j

    popall(h,i,j)
    ret

Simplify imul (no need to check both signs)


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

#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/path_service.h"
#include "base/process/launch.h"
#include "base/strings/string_util.h"
#include "testing/gtest/include/gtest/gtest.h"

base::FilePath GinShellPath() {
  base::FilePath dir;
  PathService::Get(base::DIR_EXE, &dir);
  return dir.AppendASCII("gin_shell");
}

base::FilePath HelloWorldPath() {
  base::FilePath path;
  PathService::Get(base::DIR_SOURCE_ROOT, &path);
  return path
    .AppendASCII("gin")
    .AppendASCII("shell")
    .AppendASCII("hello_world.js");
}

TEST(GinShellTest, HelloWorld) {
  CommandLine cmd(GinShellPath());
  cmd.AppendArgPath(HelloWorldPath());
  std::string output;
  ASSERT_TRUE(base::GetAppOutput(cmd, &output));
  base::TrimWhitespaceASCII(output, base::TRIM_ALL, &output);
  ASSERT_EQ("Hello World", output);
}

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

#include "base/command_line.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/process/launch.h"
#include "base/strings/string_util.h"
#include "testing/gtest/include/gtest/gtest.h"

base::FilePath GinShellPath() {
  base::FilePath dir;
  PathService::Get(base::DIR_EXE, &dir);
  return dir.AppendASCII("gin_shell");
}

base::FilePath HelloWorldPath() {
  base::FilePath path;
  PathService::Get(base::DIR_SOURCE_ROOT, &path);
  return path
    .AppendASCII("gin")
    .AppendASCII("shell")
    .AppendASCII("hello_world.js");
}

TEST(GinShellTest, HelloWorld) {
  base::FilePath gin_shell_path(GinShellPath());
  base::FilePath hello_world_path(HelloWorldPath());
  ASSERT_TRUE(base::PathExists(gin_shell_path));
  ASSERT_TRUE(base::PathExists(hello_world_path));

  CommandLine cmd(gin_shell_path);
  cmd.AppendArgPath(hello_world_path);
  std::string output;
  ASSERT_TRUE(base::GetAppOutput(cmd, &output));
  base::TrimWhitespaceASCII(output, base::TRIM_ALL, &output);
  ASSERT_EQ("Hello World", output);
}

Verify that gin_shell and hello_world.js exist.

This issue: https://code.google.com/p/chromium/issues/detail?id=398549,
was difficult to debug because gin/shell/gin_shell_unittest.cc didn't verify
that its input files existed before forging ahead.

The unit test now verifies that the gin_shell and hello_world.js paths
exist before launching the former and loading the latter.

BUG=398549

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

Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#289599}
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@289599 0039d316-1c4b-4281-b951-d872f2087c98


//===- llvm-xray.cc - XRay Tool Main Program ------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the main entry point for the suite of XRay tools. All
// additional functionality are implemented as subcommands.
//
//===----------------------------------------------------------------------===//
//
// Basic usage:
//
//   llvm-xray [options] <subcommand> [subcommand-specific options]
//
#include "xray-registry.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/raw_ostream.h"
#include <unistd.h>

using namespace llvm;
using namespace llvm::xray;

int main(int argc, char *argv[]) {
  cl::ParseCommandLineOptions(argc, argv,
                              "XRay Tools\n\n"
                              "  This program consolidates multiple XRay trace "
                              "processing tools for convenient access.\n");
  for (auto *SC : cl::getRegisteredSubcommands()) {
    if (*SC)
      if (auto C = dispatch(SC)) {
        ExitOnError("llvm-xray: ")(C());
        return 0;
      }
  }

  cl::PrintHelpMessage(false, true);
}

//===- llvm-xray.cc - XRay Tool Main Program ------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the main entry point for the suite of XRay tools. All
// additional functionality are implemented as subcommands.
//
//===----------------------------------------------------------------------===//
//
// Basic usage:
//
//   llvm-xray [options] <subcommand> [subcommand-specific options]
//
#include "xray-registry.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/raw_ostream.h"

using namespace llvm;
using namespace llvm::xray;

int main(int argc, char *argv[]) {
  cl::ParseCommandLineOptions(argc, argv,
                              "XRay Tools\n\n"
                              "  This program consolidates multiple XRay trace "
                              "processing tools for convenient access.\n");
  for (auto *SC : cl::getRegisteredSubcommands()) {
    if (*SC)
      if (auto C = dispatch(SC)) {
        ExitOnError("llvm-xray: ")(C());
        return 0;
      }
  }

  cl::PrintHelpMessage(false, true);
}

[XRay] Remove unnecessary include of <unistd.h>

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


// Copyright (C) 2018 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "RenderTargetResourceEmpty.hpp"

namespace ouzel
{
    namespace graphics
    {
    } // namespace graphics
} // namespace ouzel

// Copyright (C) 2018 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "RenderTargetResourceD3D11.hpp"

namespace ouzel
{
    namespace graphics
    {
    } // namespace graphics
} // namespace ouzel

Fix the render target D3D11 include

Fix the render target D3D11 include


//===-- llvm/CodeGen/AddressPool.cpp - Dwarf Debug Framework ---*- C++ -*--===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "AddressPool.h"
#include "llvm/CodeGen/AsmPrinter.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/Target/TargetLoweringObjectFile.h"

using namespace llvm;

class MCExpr;

unsigned AddressPool::getIndex(const MCSymbol *Sym, bool TLS) {
  auto IterBool =
      Pool.insert(std::make_pair(Sym, AddressPoolEntry(Pool.size(), TLS)));
  return IterBool.first->second.Number;
}

// Emit addresses into the section given.
void AddressPool::emit(AsmPrinter &Asm, const MCSection *AddrSection) {
  if (Pool.empty())
    return;

  // Start the dwarf addr section.
  Asm.OutStreamer.SwitchSection(AddrSection);

  // Order the address pool entries by ID
  SmallVector<const MCExpr *, 64> Entries(Pool.size());

  for (const auto &I : Pool)
    Entries[I.second.Number] =
        I.second.TLS
            ? Asm.getObjFileLowering().getDebugThreadLocalSymbol(I.first)
            : MCSymbolRefExpr::Create(I.first, Asm.OutContext);

  for (const MCExpr *Entry : Entries)
    Asm.OutStreamer.EmitValue(Entry, Asm.getDataLayout().getPointerSize());
}

Add missing cpp file header

Add missing cpp file header

Code review feedback from Paul Robinson on r207022

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


#include "CPU.h"
#if defined(__x86_64__) || defined(__i386__)
#include <cpuid.h>
#endif
#include "Log.h"

#ifndef bit_AES
#define bit_AES (1 << 25)
#endif
#ifndef bit_AVX
#define bit_AVX (1 << 28)
#endif

namespace i2p
{
namespace cpu
{
	bool aesni = false;
	bool avx = false;

	void Detect()
	{
#if defined(__x86_64__) || defined(__i386__)
		int info[4];
		__cpuid(0, info[0], info[1], info[2], info[3]);
		if (info[0] >= 0x00000001) {
			__cpuid(0x00000001, info[0], info[1], info[2], info[3]);
			aesni = info[2] & bit_AES;  // AESNI
			avx = info[2] & bit_AVX;  // AVX
		}
#endif
		if(aesni)
		{
			LogPrint(eLogInfo, "AESNI enabled");
		}
		if(avx)
		{
			LogPrint(eLogInfo, "AVX enabled");
		}
	}
}
}

#include "CPU.h"
#if defined(__x86_64__) || defined(__i386__)
#include <cpuid.h>
#endif
#include "Log.h"
namespace i2p
{
namespace cpu
{
	bool aesni = false;
	bool avx = false;

	void Detect()
	{
#if defined(__x86_64__) || defined(__i386__)
		int info[4];
		__cpuid(0, info[0], info[1], info[2], info[3]);
		if (info[0] >= 0x00000001) {
			__cpuid(0x00000001, info[0], info[1], info[2], info[3]);
			aesni = info[2] & bit_AES;  // AESNI
			avx = info[2] & bit_AVX;  // AVX
		}
#endif
		if(aesni)
		{
			LogPrint(eLogInfo, "AESNI enabled");
		}
		if(avx)
		{
			LogPrint(eLogInfo, "AVX enabled");
		}
	}
}
}

Revert "define cpu_* if not set"

Revert "define cpu_* if not set"

This reverts commit a077d7671f03f6cb3c940212bbaa28a79500d210.


// 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/renderer/renderer_main_platform_delegate.h"

#include "base/debug_util.h"

// This is a no op class because we do not have a sandbox on linux.

RendererMainPlatformDelegate::RendererMainPlatformDelegate(
    const MainFunctionParams& parameters)
        : parameters_(parameters) {
}

RendererMainPlatformDelegate::~RendererMainPlatformDelegate() {
}

void RendererMainPlatformDelegate::PlatformInitialize() {
}

void RendererMainPlatformDelegate::PlatformUninitialize() {
}

bool RendererMainPlatformDelegate::InitSandboxTests(bool no_sandbox) {
  NOTIMPLEMENTED();
  return true;
}

bool RendererMainPlatformDelegate::EnableSandbox() {
  NOTIMPLEMENTED();
  return true;
}

void RendererMainPlatformDelegate::RunSandboxTests() {
  NOTIMPLEMENTED();
}

// 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/renderer/renderer_main_platform_delegate.h"

#include "base/debug_util.h"

// This is a no op class because we do not have a sandbox on linux.

RendererMainPlatformDelegate::RendererMainPlatformDelegate(
    const MainFunctionParams& parameters)
        : parameters_(parameters) {
}

RendererMainPlatformDelegate::~RendererMainPlatformDelegate() {
}

void RendererMainPlatformDelegate::PlatformInitialize() {
}

void RendererMainPlatformDelegate::PlatformUninitialize() {
}

bool RendererMainPlatformDelegate::InitSandboxTests(bool no_sandbox) {
  // We have no sandbox.
  // http://code.google.com/p/chromium/issues/detail?id=8081
  return true;
}

bool RendererMainPlatformDelegate::EnableSandbox() {
  // We have no sandbox.
  // http://code.google.com/p/chromium/issues/detail?id=8081
  return true;
}

void RendererMainPlatformDelegate::RunSandboxTests() {
  // We have no sandbox.
  // http://code.google.com/p/chromium/issues/detail?id=8081
}

Convert sandbox NOTIMPLEMENTED()s into a bug.

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

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


/**
 * \file
 * \brief Unit Test for Thermal Mock Config
 *
 * \author Uilian Ries <uilianries@gmail.com>
 */
/** Should not link with unit test lib */
#define BOOST_TEST_NO_LIB

#include <string>

#include <boost/filesystem.hpp>

#include <boost/test/unit_test.hpp>
#include <Poco/File.h>

#include "bbbgpio/thermal_config.hpp"

namespace bbb {
namespace test {

    /**
 * \brief Test mock config gpio class.
 *        Create a fake gpio fd
 */
    BOOST_AUTO_TEST_SUITE(MockGPIO)

    BOOST_AUTO_TEST_CASE(FileValidation)
    {
        bbb::gpio::thermal_config thermal_config;
        auto&& thermal_config_path = thermal_config.get_config_file().toString();

        BOOST_CHECK(boost::filesystem::exists(thermal_config_path));
        BOOST_CHECK(boost::filesystem::is_regular_file(thermal_config_path));

        Poco::File file(thermal_config_path);
        BOOST_CHECK(file.canRead());
        BOOST_CHECK(file.canWrite());
    }

    BOOST_AUTO_TEST_SUITE_END() // BOOST_AUTO_TEST_SUITE(MockGPIO)

} // namespace test
} // namespace bbb

/**
 * \file
 * \brief Unit Test for Thermal Mock Config
 *
 * \author Uilian Ries <uilianries@gmail.com>
 */
/** Should not link with unit test lib */
#define BOOST_TEST_NO_LIB

#include <string>

#include <boost/filesystem.hpp>

#include <boost/test/unit_test.hpp>
#include <boost/filesystem/operations.hpp>

#include "bbbgpio/thermal_config.hpp"

namespace bbb {
namespace test {

    /**
 * \brief Test mock config gpio class.
 *        Create a fake gpio fd
 */
    BOOST_AUTO_TEST_SUITE(MockGPIO)

    BOOST_AUTO_TEST_CASE(FileValidation)
    {
        bbb::gpio::thermal_config thermal_config;
        auto&& thermal_config_path = thermal_config.get_config_file();

        BOOST_CHECK(boost::filesystem::exists(thermal_config_path));
        BOOST_CHECK(boost::filesystem::is_regular_file(thermal_config_path));
    }

    BOOST_AUTO_TEST_SUITE_END() // BOOST_AUTO_TEST_SUITE(MockGPIO)

} // namespace test
} // namespace bbb

Fix boos usage on mock test

Fix boos usage on mock test

Signed-off-by: Uilian Ries <d4bad57018205bdda203549c36d3feb0bfe416a7@gmail.com>


// Borrowed reference to QtGui module
extern PyObject* moduleQtGui;

int SbkQApplication_Init(PyObject* self, PyObject* args, PyObject*)
{
    int numArgs = PyTuple_GET_SIZE(args);
    if (numArgs != 1) {
        PyErr_BadArgument();
        return -1;
    }

    char** argv;
    int argc;
    if (!PySequence_to_argc_argv(PyTuple_GET_ITEM(args, 0), &argc, &argv)) {
        PyErr_BadArgument();
        return -1;
    }

    SbkBaseWrapper_setCptr(self, new QApplication(argc, argv));
    SbkBaseWrapper_setValidCppObject(self, 1);
    Shiboken::BindingManager::instance().registerWrapper(reinterpret_cast<SbkBaseWrapper*>(self));

    // Verify if qApp is in main module
    const char QAPP_MACRO[] = "qApp";
    PyObject* localsDict = PyEval_GetLocals();
    if (localsDict) {
        PyObject* qAppObj = PyDict_GetItemString(localsDict, QAPP_MACRO);
        if (qAppObj)
            PyDict_SetItemString(localsDict, QAPP_MACRO, self);
    }
    PyObject_SetAttrString(moduleQtGui, QAPP_MACRO, self);

    return 1;
}

// Borrowed reference to QtGui module
extern PyObject* moduleQtGui;

int SbkQApplication_Init(PyObject* self, PyObject* args, PyObject*)
{
    if (QApplication::instance()) {
        PyErr_SetString(PyExc_RuntimeError, "A QApplication instance already exists.");
        return -1;
    }

    int numArgs = PyTuple_GET_SIZE(args);
    if (numArgs != 1) {
        PyErr_BadArgument();
        return -1;
    }

    char** argv;
    int argc;
    if (!PySequence_to_argc_argv(PyTuple_GET_ITEM(args, 0), &argc, &argv)) {
        PyErr_BadArgument();
        return -1;
    }

    SbkBaseWrapper_setCptr(self, new QApplication(argc, argv));
    SbkBaseWrapper_setValidCppObject(self, 1);
    Shiboken::BindingManager::instance().registerWrapper(reinterpret_cast<SbkBaseWrapper*>(self));

    // Verify if qApp is in main module
    const char QAPP_MACRO[] = "qApp";
    PyObject* localsDict = PyEval_GetLocals();
    if (localsDict) {
        PyObject* qAppObj = PyDict_GetItemString(localsDict, QAPP_MACRO);
        if (qAppObj)
            PyDict_SetItemString(localsDict, QAPP_MACRO, self);
    }
    PyObject_SetAttrString(moduleQtGui, QAPP_MACRO, self);

    return 1;
}

Throw an exception when the user attempt to create more than one instance of QApplication.

Reviewed by Marcelo Lira <marcelo.lira@openbossa.org>


/*
 * Copyright 2015 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

// A benchmark designed to isolate the constant overheads of picture recording.
// We record a very tiny (one op) picture; one op is better than none, as it forces
// us to allocate memory to store that op... we can't just cheat by holding onto NULLs.

#include "Benchmark.h"
#include "SkCanvas.h"
#include "SkPictureRecorder.h"

struct PictureOverheadBench : public Benchmark {
    const char* onGetName() override { return "picture_overhead"; }
    bool isSuitableFor(Backend backend) override { return backend == kNonRendering_Backend; }

    void onDraw(const int loops, SkCanvas*) override {
        SkPictureRecorder rec;
        for (int i = 0; i < loops; i++) {
            SkCanvas* c = rec.beginRecording(SkRect::MakeWH(2000,3000));
                c->drawRect(SkRect::MakeXYWH(10, 10, 1000, 1000), SkPaint());
            SkAutoTUnref<SkPicture> pic(rec.endRecordingAsPicture());
        }
    }
};
DEF_BENCH(return new PictureOverheadBench;)

/*
 * Copyright 2015 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

// A benchmark designed to isolate the constant overheads of picture recording.
// We record an empty picture and a picture with one draw op to force memory allocation.

#include "Benchmark.h"
#include "SkCanvas.h"
#include "SkPictureRecorder.h"

template <bool kDraw>
struct PictureOverheadBench : public Benchmark {
    const char* onGetName() override {
        return kDraw ? "picture_overhead_draw" : "picture_overhead_nodraw";
    }
    bool isSuitableFor(Backend backend) override { return backend == kNonRendering_Backend; }

    void onDraw(const int loops, SkCanvas*) override {
        SkPictureRecorder rec;
        for (int i = 0; i < loops; i++) {
            rec.beginRecording(SkRect::MakeWH(2000,3000));
            if (kDraw) {
                rec.getRecordingCanvas()->drawRect(SkRect::MakeXYWH(10, 10, 1000, 1000), SkPaint());
            }
            SkAutoTUnref<SkPicture> pic(rec.endRecordingAsPicture());
        }
    }
};

DEF_BENCH(return (new PictureOverheadBench<false>);)
DEF_BENCH(return (new PictureOverheadBench< true>);)

Expand bench to cover no-draw SkPictures too.

This looks a lot closer to what Chromium's profiling is showing.

BUG=chromium:470553

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


// StackTrace.cpp

// Implements the functions to print current stack traces

#include "Globals.h"
#include "StackTrace.h"
#ifdef _WIN32
	#include "../StackWalker.h"
#else
	#include <execinfo.h>
	#include <unistd.h>
#endif

// FreeBSD uses size_t for the return type of backtrace()
#if defined(__FreeBSD__) && (__FreeBSD__ >= 10)
	#define btsize size_t
#else
	#define btsize int
#endif

void PrintStackTrace(void)
{
	#ifdef _WIN32
		// Reuse the StackWalker from the LeakFinder project already bound to MCS
		// Define a subclass of the StackWalker that outputs everything to stdout
		class PrintingStackWalker :
			public StackWalker
		{
			virtual void OnOutput(LPCSTR szText) override
			{
				puts(szText);
			}
		} sw;
		sw.ShowCallstack();
	#else
		#ifdef __GLIBC__
			// Use the backtrace() function to get and output the stackTrace:
			// Code adapted from http://stackoverflow.com/questions/77005/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes
			void * stackTrace[30];
			btsize numItems = backtrace(stackTrace, ARRAYCOUNT(stackTrace));
			backtrace_symbols_fd(stackTrace, numItems, STDERR_FILENO);
		#endif
	#endif
}

// StackTrace.cpp

// Implements the functions to print current stack traces

#include "Globals.h"
#include "StackTrace.h"
#ifdef _WIN32
	#include "../StackWalker.h"
#else
	#ifdef __GLIBC__
		#include <execinfo.h>
	#endif
	#include <unistd.h>
#endif

// FreeBSD uses size_t for the return type of backtrace()
#if defined(__FreeBSD__) && (__FreeBSD__ >= 10)
	#define btsize size_t
#else
	#define btsize int
#endif

void PrintStackTrace(void)
{
	#ifdef _WIN32
		// Reuse the StackWalker from the LeakFinder project already bound to MCS
		// Define a subclass of the StackWalker that outputs everything to stdout
		class PrintingStackWalker :
			public StackWalker
		{
			virtual void OnOutput(LPCSTR szText) override
			{
				puts(szText);
			}
		} sw;
		sw.ShowCallstack();
	#else
		#ifdef __GLIBC__
			// Use the backtrace() function to get and output the stackTrace:
			// Code adapted from http://stackoverflow.com/questions/77005/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes
			void * stackTrace[30];
			btsize numItems = backtrace(stackTrace, ARRAYCOUNT(stackTrace));
			backtrace_symbols_fd(stackTrace, numItems, STDERR_FILENO);
		#endif
	#endif
}

Include execinfo.h only on __GLIBC__

Include execinfo.h only on __GLIBC__


#include "ofMain.h"
#include "ofApp.h"

int main()
{
#ifdef TARGET_RASPBERRY_PI
	ofSetupOpenGL(600, 500, OF_FULLSCREEN);
#else
    ofSetupOpenGL(600, 500, OF_WINDOW);
#endif
	ofRunApp(new ofApp());
}

#include "ofMain.h"
#include "ofApp.h"
#include <string>

#ifdef TARGET_RASPBERRY_PI
// Accept arguments in the Pi version
int main(int argc, char* argv[]) {

  bool fullscreen = false;

  if (argc > 0) {
    std::string fullscreenFlag = "-f";
    for (int i = 0; i < argc; i++) {
      if (strcmp(argv[i], fullscreenFlag.c_str()) == 0) {
        fullscreen = true;
        break;
      }
    }
  }

  if (fullscreen) {
    ofSetupOpenGL(600, 500, OF_FULLSCREEN);
  } else {
    ofSetupOpenGL(800, 450, OF_WINDOW);
  }

  ofRunApp(new ofApp());
}
#else
int main() {
  ofSetupOpenGL(800, 600, OF_WINDOW);
  ofRunApp(new ofApp());
}
#endif

Add -f flag option to RPi version of he example


#include <iostream>
#include <tcp_server.hpp>

int main()
{

  TcpServer server(12001);
  server.Listen(2000);

  return 0;
}

#include <iostream>
#include <tcp/tcp_server.hpp>
#include <sstream>

int main(int argc, char** argv)
{
  //initalize default port number and max connection cout
  int port = 12001, max_connection_count= 1000;

  // check if there are any passed arguments
  if(argc > 1)
  {
    // initialize string stream from argument
    std::istringstream arg_stream(argv[1]);

    // bind arguments stream to port int variable if valid
    if ( !(arg_stream >> port) )
      std::cerr << "Invalid number " << argv[1] << '\n';
  }

  // create server instance with specified port number
  TcpServer server(port);

  //start listening to connections
  server.Listen(max_connection_count);

  return 0;
}

Update tcp server example to accept cmd args


// RUN: clang-cc -fsyntax-only -verify %s

struct S { };

template<typename T> void f1(T a, T b = 10) { } // expected-error{{cannot initialize 'b' with an rvalue of type 'int'}}

template<typename T> void f2(T a, T b = T()) { }

template<typename T> void f3(T a, T b = T() + T()); // expected-error{{invalid operands to binary expression ('struct S' and 'struct S')}}

void g() {
  f1(10);
  f1(S()); // expected-note{{in instantiation of default argument for 'f1<struct S>' required here}}

  f2(10);
  f2(S());

  f3(10);
  f3(S()); // expected-note{{in instantiation of default argument for 'f3<struct S>' required here}}
}

template<typename T> struct F {
	F(T t = 10);
};

void g2() {
	F<int> f;
}

template<typename T> struct G {
	G(T) {}
};

void s(G<int> flags = 10) { }

// RUN: clang-cc -fsyntax-only -verify %s

struct S { };

template<typename T> void f1(T a, T b = 10) { } // expected-error{{cannot initialize 'b' with an rvalue of type 'int'}}

template<typename T> void f2(T a, T b = T()) { }

template<typename T> void f3(T a, T b = T() + T()); // expected-error{{invalid operands to binary expression ('struct S' and 'struct S')}}

void g() {
  f1(10);
  f1(S()); // expected-note{{in instantiation of default argument for 'f1<struct S>' required here}}

  f2(10);
  f2(S());

  f3(10);
  f3(S()); // expected-note{{in instantiation of default argument for 'f3<struct S>' required here}}
}

template<typename T> struct F {
	F(T t = 10);
};

struct FD : F<int> { };

void g2() {
	F<int> f;
  FD fd;
}

template<typename T> struct G {
	G(T) {}
};

void s(G<int> flags = 10) { }

Add a little more testing for default arguments of constructors in a class template

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


// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "servicelayercomponent.h"

#include <vespa/storage/common/content_bucket_space_repo.h>
#include <vespa/storage/common/nodestateupdater.h>
#include <vespa/vdslib/distribution/distribution.h>

using document::BucketSpace;

namespace storage {

const ContentBucketSpaceRepo &
ServiceLayerComponent::getBucketSpaceRepo() const
{
    assert(_bucketSpaceRepo != nullptr);
    return *_bucketSpaceRepo;
}

StorBucketDatabase&
ServiceLayerComponent::getBucketDatabase(BucketSpace bucketSpace) const
{
    assert(bucketSpace == BucketSpace::placeHolder());
    assert(_bucketSpaceRepo != nullptr);
    return _bucketSpaceRepo->get(bucketSpace).bucketDatabase();
}

uint16_t
ServiceLayerComponent::getIdealPartition(const document::Bucket& bucket) const
{
    return _bucketSpaceRepo->get(bucket.getBucketSpace()).getDistribution()->getIdealDisk(
            *getStateUpdater().getReportedNodeState(), getIndex(), bucket.getBucketId(),
            lib::Distribution::IDEAL_DISK_EVEN_IF_DOWN);
}

uint16_t
ServiceLayerComponent::getPreferredAvailablePartition(
        const document::Bucket& bucket) const
{
    return _bucketSpaceRepo->get(bucket.getBucketSpace()).getDistribution()->getPreferredAvailableDisk(
            *getStateUpdater().getReportedNodeState(), getIndex(), bucket.getBucketId());
}

} // storage

// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "servicelayercomponent.h"

#include <vespa/storage/common/content_bucket_space_repo.h>
#include <vespa/storage/common/nodestateupdater.h>
#include <vespa/vdslib/distribution/distribution.h>

using document::BucketSpace;

namespace storage {

const ContentBucketSpaceRepo &
ServiceLayerComponent::getBucketSpaceRepo() const
{
    assert(_bucketSpaceRepo != nullptr);
    return *_bucketSpaceRepo;
}

StorBucketDatabase&
ServiceLayerComponent::getBucketDatabase(BucketSpace bucketSpace) const
{
    assert(_bucketSpaceRepo != nullptr);
    return _bucketSpaceRepo->get(bucketSpace).bucketDatabase();
}

uint16_t
ServiceLayerComponent::getIdealPartition(const document::Bucket& bucket) const
{
    return _bucketSpaceRepo->get(bucket.getBucketSpace()).getDistribution()->getIdealDisk(
            *getStateUpdater().getReportedNodeState(), getIndex(), bucket.getBucketId(),
            lib::Distribution::IDEAL_DISK_EVEN_IF_DOWN);
}

uint16_t
ServiceLayerComponent::getPreferredAvailablePartition(
        const document::Bucket& bucket) const
{
    return _bucketSpaceRepo->get(bucket.getBucketSpace()).getDistribution()->getPreferredAvailableDisk(
            *getStateUpdater().getReportedNodeState(), getIndex(), bucket.getBucketId());
}

} // storage

Remove outdated bucket space assertion

Remove outdated bucket space assertion


// RUN: %clang_cc1 %s -emit-llvm

namespace test0 {
template <typename T> struct X {
  virtual void foo();
  virtual void bar();
  virtual void baz();
};

template <typename T> void X<T>::foo() {}
template <typename T> void X<T>::bar() {}
template <typename T> void X<T>::baz() {}

template <> void X<char>::foo() {}
template <> void X<char>::bar() {}
}

namespace test1 {
template <typename T> struct X {
  virtual void foo();
  virtual void bar();
  virtual void baz();
};

template <typename T> void X<T>::foo() {}
template <typename T> void X<T>::bar() {}
template <typename T> void X<T>::baz() {}

template <> void X<char>::bar() {}
template <> void X<char>::foo() {}
}

// RUN: %clang_cc1 %s -emit-llvm-only

namespace test0 {
template <typename T> struct X {
  virtual void foo();
  virtual void bar();
  virtual void baz();
};

template <typename T> void X<T>::foo() {}
template <typename T> void X<T>::bar() {}
template <typename T> void X<T>::baz() {}

template <> void X<char>::foo() {}
template <> void X<char>::bar() {}
}

namespace test1 {
template <typename T> struct X {
  virtual void foo();
  virtual void bar();
  virtual void baz();
};

template <typename T> void X<T>::foo() {}
template <typename T> void X<T>::bar() {}
template <typename T> void X<T>::baz() {}

template <> void X<char>::bar() {}
template <> void X<char>::foo() {}
}

Use -emit-llvm-only, to avoid leaving a temp around.

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


/* Copyright 2019 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/lite/delegates/nnapi/nnapi_delegate.h"

namespace tflite {

// Return a non-functional NN API Delegate struct.
TfLiteDelegate* NnApiDelegate() {
  static TfLiteDelegate delegate = [] {
    TfLiteDelegate delegate = TfLiteDelegateCreate();
    delegate.Prepare = [](TfLiteContext* context,
                          TfLiteDelegate* delegate) -> TfLiteStatus {
      // Silently succeed without modifying the graph.
      return kTfLiteOk;
    };
    return delegate;
  }();

  return &delegate;
}

}  // namespace tflite

/* Copyright 2019 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/lite/delegates/nnapi/nnapi_delegate.h"

namespace tflite {

// Return a non-functional NN API Delegate struct.
TfLiteDelegate* NnApiDelegate() {
  static StatefulNnApiDelegate* delegate = new StatefulNnApiDelegate();
  return delegate;
}

StatefulNnApiDelegate::StatefulNnApiDelegate(Options /* options */)
    : StatefulNnApiDelegate() {}

StatefulNnApiDelegate::StatefulNnApiDelegate()
    : TfLiteDelegate(TfLiteDelegateCreate()) {
  Prepare = DoPrepare;
}

TfLiteStatus StatefulNnApiDelegate::DoPrepare(TfLiteContext* /* context */,
                                              TfLiteDelegate* /* delegate */) {
  return kTfLiteOk;
}

}  // namespace tflite

Add portable (no-op) version of StatefulNnApiDelegate

PiperOrigin-RevId: 249683139


#include <avr/io.h>
#include <avr/interrupt.h>

/*
           _____   ___ ___
           RESET -|   U   |- VCC
     (Mode) ADC3 -| AT13A |- ADC1 (Depth)
    (Speed) ADC2 -|       |- OC0B (PWM Output)
             GND -|_______|- PB0  (Button)
*/

int main()
{
    while(1)
    {
        cli();
    }
}

#include <avr/io.h>
#include <avr/interrupt.h>

/*
           _____   ___ ___
           RESET -|   U   |- VCC
     (Mode) ADC3 -| AT13A |- ADC1 (Depth)
    (Speed) ADC2 -|       |- OC0B (PWM Output)
             GND -|_______|- PB0  (Button)
*/

enum {
    ADC_DEPTH = 1,
    ADC_SPEED = 2,
    ADC_MODE = 3,
};

int main()
{
    while(1)
    {
        cli();
    }
}

Add enum definitions for ADC's.

Add enum definitions for ADC's.


/**
 * Copyright (c) 2016-present, Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "aten_op.h"
#include "caffe2/core/context_gpu.h"

namespace caffe2 {

REGISTER_CUDA_OPERATOR(ATen, ATenOp<CUDAContext>);
template<>
at::Backend ATenOp<CUDAContext>::backend() const {
  return at::kCUDA;
}

namespace math {
template<>
void Set<at::Half,CUDAContext>(TIndex N, at::Half h, at::Half* v, CUDAContext * c) {
  Set(0, h.x, (uint16_t*) v, c);
}
}

}

/**
 * Copyright (c) 2016-present, Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "aten_op.h"
#include "caffe2/core/context_gpu.h"

namespace caffe2 {

REGISTER_CUDA_OPERATOR(ATen, ATenOp<CUDAContext>);
template<>
at::Backend ATenOp<CUDAContext>::backend() const {
  return at::kCUDA;
}

namespace math {
template<>
void Set<at::Half,CUDAContext>(const size_t N, const at::Half h, at::Half* v, CUDAContext * c) {
  Set(0, h.x, (uint16_t*) v, c);
}
}

}

Fix function signature in ATenOp for at::Half Set function (GPU version)

Summary:
The CPU version is fixed here. https://github.com/caffe2/caffe2/pull/1464/files

Now fix GPU version.
Closes https://github.com/caffe2/caffe2/pull/1506

Reviewed By: jamesr66a

Differential Revision: D6392830

Pulled By: houseroad

fbshipit-source-id: 922205630cbd8e24da80e269c6cd32bc4f040100


#include "generator/sponsored_scoring.hpp"

#include "generator/opentable_dataset.hpp"
#include "generator/feature_builder.hpp"

namespace
{
// Calculated with tools/python/booking_hotels_quality.py.
double constexpr kOptimalThreshold = 0.304875;
}  // namespace

namespace generator
{
namespace sponsored_scoring
{
template <>
double MatchStats<OpentableRestaurant>::GetMatchingScore() const
{
  // TODO(mgsergio): Use tuner to get optimal function.
  return m_linearNormDistanceScore * m_nameSimilarityScore;
}

template <>
bool MatchStats<OpentableRestaurant>::IsMatched() const
{
  return GetMatchingScore() > kOptimalThreshold;
}

template <>
MatchStats<OpentableRestaurant> Match(OpentableRestaurant const & h, FeatureBuilder1 const & fb)
{
  MatchStats<OpentableRestaurant> score;

  auto const fbCenter = MercatorBounds::ToLatLon(fb.GetKeyPoint());
  auto const distance = ms::DistanceOnEarth(fbCenter.lat, fbCenter.lon, h.m_lat, h.m_lon);
  score.m_linearNormDistanceScore =
      impl::GetLinearNormDistanceScore(distance, OpentableDataset::kDistanceLimitInMeters);

  score.m_nameSimilarityScore =
      impl::GetNameSimilarityScore(h.m_name, fb.GetName(StringUtf8Multilang::kDefaultCode));

  return score;
}
}  // namespace sponsored_scoring
}  // namespace generator

#include "generator/sponsored_scoring.hpp"

#include "generator/opentable_dataset.hpp"
#include "generator/feature_builder.hpp"

namespace
{
// Calculated with tools/python/booking_hotels_quality.py.
double constexpr kOptimalThreshold = 0.312887;
}  // namespace

namespace generator
{
namespace sponsored_scoring
{
template <>
double MatchStats<OpentableRestaurant>::GetMatchingScore() const
{
  // TODO(mgsergio): Use tuner to get optimal function.
  return m_linearNormDistanceScore * m_nameSimilarityScore;
}

template <>
bool MatchStats<OpentableRestaurant>::IsMatched() const
{
  return GetMatchingScore() > kOptimalThreshold;
}

template <>
MatchStats<OpentableRestaurant> Match(OpentableRestaurant const & h, FeatureBuilder1 const & fb)
{
  MatchStats<OpentableRestaurant> score;

  auto const fbCenter = MercatorBounds::ToLatLon(fb.GetKeyPoint());
  auto const distance = ms::DistanceOnEarth(fbCenter.lat, fbCenter.lon, h.m_lat, h.m_lon);
  score.m_linearNormDistanceScore =
      impl::GetLinearNormDistanceScore(distance, OpentableDataset::kDistanceLimitInMeters);

  score.m_nameSimilarityScore =
      impl::GetNameSimilarityScore(h.m_name, fb.GetName(StringUtf8Multilang::kDefaultCode));

  return score;
}
}  // namespace sponsored_scoring
}  // namespace generator

Adjust classificator theshold for opentable.


// Copyright (c) 2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <amount.h>
#include <optional.h>
#include <policy/fees.h>
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h>

#include <cstdint>
#include <string>
#include <vector>

void test_one_input(const std::vector<uint8_t>& buffer)
{
    FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
    const CFeeRate minimal_incremental_fee{ConsumeMoney(fuzzed_data_provider)};
    FeeFilterRounder fee_filter_rounder{minimal_incremental_fee};
    while (fuzzed_data_provider.ConsumeBool()) {
        const CAmount current_minimum_fee = ConsumeMoney(fuzzed_data_provider);
        const CAmount rounded_fee = fee_filter_rounder.round(current_minimum_fee);
        assert(MoneyRange(rounded_fee));
    }
}

// Copyright (c) 2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <amount.h>
#include <optional.h>
#include <policy/fees.h>
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h>
#include <util/fees.h>

#include <cstdint>
#include <string>
#include <vector>

void test_one_input(const std::vector<uint8_t>& buffer)
{
    FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
    const CFeeRate minimal_incremental_fee{ConsumeMoney(fuzzed_data_provider)};
    FeeFilterRounder fee_filter_rounder{minimal_incremental_fee};
    while (fuzzed_data_provider.ConsumeBool()) {
        const CAmount current_minimum_fee = ConsumeMoney(fuzzed_data_provider);
        const CAmount rounded_fee = fee_filter_rounder.round(current_minimum_fee);
        assert(MoneyRange(rounded_fee));
    }
    const FeeReason fee_reason = fuzzed_data_provider.PickValueInArray({FeeReason::NONE, FeeReason::HALF_ESTIMATE, FeeReason::FULL_ESTIMATE, FeeReason::DOUBLE_ESTIMATE, FeeReason::CONSERVATIVE, FeeReason::MEMPOOL_MIN, FeeReason::PAYTXFEE, FeeReason::FALLBACK, FeeReason::REQUIRED});
    (void)StringForFeeReason(fee_reason);
}

tests: Add fuzzing coverage for StringForFeeReason(...)


#include "alnindex.hpp"
#include <cstring>

AlnIndex::AlnIndex()
{
    t = hattrie_create();
}

AlnIndex::~AlnIndex()
{
    hattrie_free(t);
}

size_t AlnIndex::size() const
{
    return hattrie_size(t);
}

void AlnIndex::clear()
{
    hattrie_clear(t);
}

long AlnIndex::add(const char* key)
{
    value_t* val = hattrie_get(t, key, strlen(key));
    if (*val == 0) {
        *val = hattrie_size(t) + 1;
    }
    return *val;
}

long AlnIndex::get(const char* key)
{
    value_t* val = hattrie_tryget(t, key, strlen(key));
    if (val == NULL) return -1;
    else {
        return *val - 1;;
    }
}

size_t AlnIndex::used_memory() const
{
    return hattrie_sizeof(t);
}

#include "alnindex.hpp"
#include <cstring>

AlnIndex::AlnIndex()
{
    t = hattrie_create();
}

AlnIndex::~AlnIndex()
{
    hattrie_free(t);
}

size_t AlnIndex::size() const
{
    return hattrie_size(t);
}

void AlnIndex::clear()
{
    hattrie_clear(t);
}

long AlnIndex::add(const char* key)
{
    value_t* val = hattrie_get(t, key, strlen(key));
    if (*val == 0) {
        *val = hattrie_size(t);
    }
    return *val;
}

long AlnIndex::get(const char* key)
{
    value_t* val = hattrie_tryget(t, key, strlen(key));
    if (val == NULL) return -1;
    else {
        return *val - 1;;
    }
}

size_t AlnIndex::used_memory() const
{
    return hattrie_sizeof(t);
}

Fix off-by-one memory access error.

Fix off-by-one memory access error.


#include <QCoreApplication>
#include <QSettings>

#include "Application.h"

int main(int argc, char *argv[])
{
    Application a(argc, argv);
    return a.exec();
}

#include <QCoreApplication>
#include <QSettings>

#include "Application.h"

#include <QtGlobal>
#include <QTime>
#include <iostream>

#define COLOR_LIGHTRED  "\033[31;1m"
#define COLOR_RED       "\033[31m"
#define COLOR_LIGHTBLUE "\033[34;1m"
#define COLOR_BLUE      "\033[34m"
#define COLOR_GREEN     "\033[32;1m"
#define COLOR_YELLOW    "\033[33;1m"
#define COLOR_ORANGE    "\033[0;33m"
#define COLOR_WHITE     "\033[37;1m"
#define COLOR_LIGHTCYAN "\033[36;1m"
#define COLOR_CYAN      "\033[36m"
#define COLOR_RESET     "\033[0m"
#define COLOR_HIGH      "\033[1m"

#define LOG_WRITE(OUTPUT, COLOR, LEVEL, MSG) OUTPUT << COLOR << \
QTime::currentTime().toString("hh:mm:ss:zzz").toStdString() << \
" " LEVEL " " << COLOR_RESET << MSG << "\n"

static void EmsCustomLogWriter(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{

   switch (type)
     {
      case QtWarningMsg:
         LOG_WRITE(std::cout, COLOR_YELLOW, "WARN", msg.toStdString());
         break;
      case QtCriticalMsg:
         LOG_WRITE(std::cout, COLOR_RED, "CRIT",  msg.toStdString());
         break;
      case QtFatalMsg:
         LOG_WRITE(std::cout, COLOR_ORANGE, "FATAL",  msg.toStdString());
         break;
      case QtDebugMsg:
         LOG_WRITE(std::cout, COLOR_CYAN, "DEBUG",  msg.toStdString());
         break;
      default:
         LOG_WRITE(std::cout, COLOR_CYAN, "DEBUG",  msg.toStdString());
         break;
     }
}

int main(int argc, char *argv[])
{
    qInstallMessageHandler(EmsCustomLogWriter);
    Application a(argc, argv);

    return a.exec();
}

Add color and timestamp to loggin messages


#include <string>

#include <config/config.h>
#include <config/config_type_pointer.h>
#include <config/config_value.h>

ConfigTypePointer config_type_pointer;

bool
ConfigTypePointer::set(ConfigValue *cv, const std::string& vstr)
{
	if (pointers_.find(cv) != pointers_.end())
		return (false);

	Config *config = cv->config_;
	ConfigObject *co = config->lookup(vstr);
	if (co == NULL)
		return (false);

	pointers_[cv] = co;

	return (true);
}

#include <string>

#include <config/config.h>
#include <config/config_type_pointer.h>
#include <config/config_value.h>

ConfigTypePointer config_type_pointer;

bool
ConfigTypePointer::set(ConfigValue *cv, const std::string& vstr)
{
	if (pointers_.find(cv) != pointers_.end())
		return (false);

	/* XXX Have a magic None that is easily-detected?  */
	if (vstr == "None") {
		pointers_[cv] = NULL;
		return (true);
	}

	Config *config = cv->config_;
	ConfigObject *co = config->lookup(vstr);
	if (co == NULL)
		return (false);

	pointers_[cv] = co;

	return (true);
}

Support pointers to "None" as used in the wanproxy.conf.

git-svn-id: 9e2532540f1574e817ce42f20b9d0fb64899e451@173 4068ffdb-0463-0410-8185-8cc71e3bd399


#include <cassert>

#include "structures/congruence_atom.h"

using namespace theorysolver;

Term::Term(unsigned int symbol_id) : type(Term::SYMBOL), symbol_id(symbol_id), function_name(), arguments() {
}
Term::Term(std::string function_name, std::vector<std::shared_ptr<Term>> arguments) : type(Term::FUNCTION), symbol_id(0), function_name(function_name), arguments(arguments) {
}

bool Term::operator==(const Term &that) const {
    if (this->type != that.type)
        return false;
    else if (this->type == Term::SYMBOL)
        return this->symbol_id == that.symbol_id;
    else if (this->type == Term::FUNCTION) {
        if (this->arguments.size() != that.arguments.size())
            return false;
        for (unsigned i=0; i<this->arguments.size(); i++)
            if (!(this->arguments[i] == that.arguments[i]))
                return false;
        return true;
    }
    else
        assert(false);
}

CongruenceAtom::CongruenceAtom(std::shared_ptr<Term> left, enum Operator op, std::shared_ptr<Term> right) : left(left), right(right), op(op) {
}

std::string CongruenceAtom::to_string() const {
    // TODO
    return std::string();
}

#include <cassert>

#include "structures/congruence_atom.h"

using namespace theorysolver;

Term::Term(unsigned int symbol_id) : type(Term::SYMBOL), symbol_id(symbol_id), function_name(), arguments() {
}
Term::Term(std::string function_name, std::vector<std::shared_ptr<Term>> arguments) : type(Term::FUNCTION), symbol_id(0), function_name(function_name), arguments(arguments) {
}

bool Term::operator==(const Term &that) const {
    if (this->type != that.type)
        return false;
    else if (this->type == Term::SYMBOL)
        return this->symbol_id == that.symbol_id;
    else if (this->type == Term::FUNCTION) {
        if (this->arguments.size() != that.arguments.size())
            return false;
        if (this->function_name != that.function_name)
            return false;
        for (unsigned i=0; i<this->arguments.size(); i++)
            if (!(this->arguments[i] == that.arguments[i]))
                return false;
        return true;
    }
    else
        assert(false);
}

CongruenceAtom::CongruenceAtom(std::shared_ptr<Term> left, enum Operator op, std::shared_ptr<Term> right) : left(left), right(right), op(op) {
}

std::string CongruenceAtom::to_string() const {
    // TODO
    return std::string();
}

Fix forgotten case in previous commit.

Fix forgotten case in previous commit.


#include <iostream>

#include <limits>
#include <bitset>

std::bitset<10> split(unsigned number) noexcept
{
        std::bitset<10> result;

        while (number > 0) {
                unsigned digit = number % 10;
                number /= 10;

                result[digit] = true;
        }

        return result;
}

template <size_t size>
bool isPermutation(std::bitset<size> const &first, std::bitset<size> const &second) noexcept
{
        for (size_t i = 0; i < second.size(); ++i) {
                if (first[i] != second[i]) {
                        return false;
                }
        }

        return true;
}

bool isPermutation(unsigned first, unsigned second) noexcept
{
        std::bitset<10> i = split(first);
        std::bitset<10> k = split(second);

        return isPermutation(i, k);
}

int main(int count, char *arguments[])
{
        for (unsigned i = 1; i < std::numeric_limits<unsigned>::max(); ++i) {
                unsigned k = 2;

                for (; k < 7; ++k) {
                        if (isPermutation(i, i * k) == false) {
                                break;
                        }
                }

                if (k == 7) {
                        std::cout << i << '\n';
                        return 0;
                }
        }

        return 0;
}

#include <iostream>

#include <limits>
#include <bitset>

std::bitset<10> split(unsigned number) noexcept
{
        std::bitset<10> result;

        while (number > 0) {
                unsigned digit = number % 10;
                number /= 10;

                result[digit] = true;
        }

        return result;
}

template <size_t size>
bool isPermutation(std::bitset<size> const &first, std::bitset<size> const &second) noexcept
{
        for (size_t i = 0; i < second.size(); ++i) {
                if (first[i] != second[i]) {
                        return false;
                }
        }

        return true;
}

int main(int count, char *arguments[])
{
        for (unsigned i = 1; i < std::numeric_limits<unsigned>::max(); ++i) {
                std::bitset<10> r = split(i);

                unsigned k = 2;
                for (; k < 7; ++k) {
                        std::bitset<10> l = split(i * k);
                        if (isPermutation(r, l) == false) {
                                break;
                        }
                }

                if (k == 7) {
                        std::cout << i << '\n';
                        return 0;
                }
        }

        return 0;
}

Optimize number to bitset conversion

Optimize number to bitset conversion


#include <ncurses.h>
#include <stdlib.h>
#include <time.h>

#include "lightsout.hpp"

namespace roadagain
{

board::board(int width, int height) : width(width), height(height)
{
    // init seed of rand() by current time
    srand(time(NULL));

    lights = new bool*[height + 2]();
    for (int i = 0; i < height + 2; i++){
        lights[i] = new bool[width + 2]();
        for (int j = 1; j < width + 1; j++){
            lights[i][j] = (rand() % 2 == 0);
        }
    }
}

board::~board()
{
    ;
}

}

#include <ncurses.h>
#include <stdlib.h>
#include <time.h>

#include "lightsout.hpp"
#include "print.hpp"

namespace roadagain
{

board::board(int width, int height) : width(width), height(height)
{
    // init seed of rand() by current time
    srand(time(NULL));

    lights = new bool*[height + 2]();
    for (int i = 0; i < height + 2; i++){
        lights[i] = new bool[width + 2]();
        for (int j = 1; j < width + 1; j++){
            lights[i][j] = (rand() % 2 == 0);
        }
    }

    // print the board
    print_board(width, height);
}

board::~board()
{
    ;
}

}

Modify board::board to call print_board()


#include "coincontroltreewidget.h"
#include "coincontroldialog.h"

CoinControlTreeWidget::CoinControlTreeWidget(QWidget *parent) :
    QTreeWidget(parent)
{

}

void CoinControlTreeWidget::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Space) // press spacebar -> select checkbox
    {
        event->ignore();
        int COLUMN_CHECKBOX = 0;
        this->currentItem()->setCheckState(COLUMN_CHECKBOX, ((this->currentItem()->checkState(COLUMN_CHECKBOX) == Qt::Checked) ? Qt::Unchecked : Qt::Checked));
    }
    else if (event->key() == Qt::Key_Escape) // press esc -> close dialog
    {
        event->ignore();
        CoinControlDialog *coinControlDialog = (CoinControlDialog*)this->parentWidget();
        coinControlDialog->done(QDialog::Accepted);
    }
    else
    {
        this->QTreeWidget::keyPressEvent(event);
    }
}

#include "coincontroltreewidget.h"
#include "coincontroldialog.h"

CoinControlTreeWidget::CoinControlTreeWidget(QWidget *parent) :
    QTreeWidget(parent)
{

}

void CoinControlTreeWidget::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Space) // press spacebar -> select checkbox
    {
        event->ignore();
        int COLUMN_CHECKBOX = 0;
        if(this->currentItem())
            this->currentItem()->setCheckState(COLUMN_CHECKBOX, ((this->currentItem()->checkState(COLUMN_CHECKBOX) == Qt::Checked) ? Qt::Unchecked : Qt::Checked));
    }
    else if (event->key() == Qt::Key_Escape) // press esc -> close dialog
    {
        event->ignore();
        CoinControlDialog *coinControlDialog = (CoinControlDialog*)this->parentWidget();
        coinControlDialog->done(QDialog::Accepted);
    }
    else
    {
        this->QTreeWidget::keyPressEvent(event);
    }
}

Fix crash: CoinControl "space" bug

Fix crash: CoinControl "space" bug

This is a port of the pull bitcoin/bitcoin#5700 made by fsb4000 for
Bitcoin Core to fix the crash problem: CoinControl "space" bug.