#include <ncurses.h>

#include <string>

int main() {

    /*
     * init term
     */

    initscr();
    cbreak();
    noecho();
    clear();

    /*
     * init title
     */

    move(5, 5);
    std::string title = "TERMINAL QUEST";
    for (int i; i < title.size(); i++) {
        addch(title[i]);
        addch(' ');
    }

    refresh();
    while(true);

    /*
     * exit
     */

    return 0;
}

#include <ncurses.h>

#include <string>

using namespace std;

void menuShow();
void menuAdd(int pos, string str);
void menuDone();

int main() {

    /*
     * init term
     */

    initscr();
    cbreak();
    noecho();
    clear();

    /*
     * init title
     */
    menuShow();

    refresh();
    while(true);

    /*
     * exit
     */

    return 0;
}

void menuShow() {

    move(5, 5); // move cursor to (x,y)

    string text = "TERMINAL QUEST";
    for (size_t i = 0; i < text.size(); i++) {
        addch(text[i]);
        addch(' ');
    }

    menuAdd(1, "start");
    menuAdd(2, "quit");
    menuDone();

    refresh();

    while(1);
}

void close() {
    endwin();
}

// Private functions

void menuAdd(int pos, string str) {
    if (pos > 0 && str.length() > 0) {
        move((pos + 6), 8);
        addstr(str.c_str());
    }
}

void menuDone() {
    move(7, 6);
}

Move title screen init to private fn

Move title screen init to private fn


/*
 * This file is part of libqcalparser
 *
 * Copyright (C) Rohan Garg <rohan16garg@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "qcalparser.h"
#include "qcalevent.h"

#include <QtCore/QCoreApplication>
#include <QFile>
#include <QString>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QFile *file = new QFile(a.arguments().at(1));
    QCalParser *parser = new QCalParser(file);
    foreach(QCalEvent* event, parser->getEventList()) {
        qDebug() << event->eventUID();
        qDebug() << event->categoryList();
        qDebug() << event->eventDescription();
        qDebug() << event->eventUrl();
        qDebug() << event->eventUrlType();
        qDebug() << event->eventLocation();
        qDebug() << event->eventRoomName();
        qDebug() << event->eventStartDate();
        qDebug() << event->eventStopDate();
     }
}

Add proper licensing to file

Add proper licensing to file


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

#include "chrome/browser/icon_loader.h"

#include "base/message_loop.h"
#include "base/mime_util.h"
#include "base/thread.h"
#include "chrome/browser/browser_process.h"
#include "third_party/skia/include/core/SkBitmap.h"

IconLoader::IconLoader(const IconGroupID& group, IconSize size,
                       Delegate* delegate)
    : group_(group),
      icon_size_(size),
      bitmap_(NULL),
      delegate_(delegate) {
}

IconLoader::~IconLoader() {
  delete bitmap_;
}

void IconLoader::Start() {
  target_message_loop_ = MessageLoop::current();

#if defined(OS_LINUX)
  // This call must happen on the UI thread before we can start loading icons.
  mime_util::DetectGtkTheme();
#endif

  g_browser_process->file_thread()->message_loop()->PostTask(FROM_HERE,
      NewRunnableMethod(this, &IconLoader::ReadIcon));
}

void IconLoader::NotifyDelegate() {
  if (delegate_->OnBitmapLoaded(this, bitmap_))
    bitmap_ = NULL;
}

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

#include "chrome/browser/icon_loader.h"

#include "base/message_loop.h"
#include "base/mime_util.h"
#include "base/thread.h"
#include "chrome/browser/browser_process.h"
#include "third_party/skia/include/core/SkBitmap.h"

IconLoader::IconLoader(const IconGroupID& group, IconSize size,
                       Delegate* delegate)
    : target_message_loop_(NULL),
      group_(group),
      icon_size_(size),
      bitmap_(NULL),
      delegate_(delegate) {
}

IconLoader::~IconLoader() {
  delete bitmap_;
}

void IconLoader::Start() {
  target_message_loop_ = MessageLoop::current();

#if defined(OS_LINUX)
  // This call must happen on the UI thread before we can start loading icons.
  mime_util::DetectGtkTheme();
#endif

  g_browser_process->file_thread()->message_loop()->PostTask(FROM_HERE,
      NewRunnableMethod(this, &IconLoader::ReadIcon));
}

void IconLoader::NotifyDelegate() {
  if (delegate_->OnBitmapLoaded(this, bitmap_))
    bitmap_ = NULL;
}

Coverity: Initialize target_message_loop_ in the constructor.

CID=3970
BUG=none
TEST=none
Review URL: http://codereview.chromium.org/233001

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


/*
  Copyright(c) 2015 - 2019 Denis Blank <denis.blank at outlook dot com>

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files(the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions :

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
**/

#include <continuable/continuable.hpp>

using namespace cti;

int main(int, char**) {
  // ...
  auto e = std::make_exception_ptr(std::exception("huhu"));

  async_on(
      [] {
        //
        int i = 0;
      },
      [&](work work) {
        int i = 0;
        (void)i;
        work.set_exception(e); //
      })
      .fail([](exception_t e) {
        //
        int i = 0;
        (void)i;
      });
}

/*
  Copyright(c) 2015 - 2019 Denis Blank <denis.blank at outlook dot com>

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files(the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions :

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
**/

#include <continuable/continuable.hpp>

using namespace cti;

int main(int, char**) {
}

Clean the playground since the test was moved into the unit tests


#include "audiobase.h"

namespace openalpp {

AudioBase::AudioBase(int frequency,int refresh,int synchronous)
  throw (InitError)
{
  if(!instances_) {
    // Open a write (output) device. This should (in theory) make it possible
    // to open a read (input) device later..
    device_=alcOpenDevice((const ALubyte *)"'((direction \"write\"))");
    if(!device_)
      throw InitError("Couldn't open device.");
    int attributes[7],i=0;
    attributes[0]=0;
    if(frequency>0) {
      attributes[i++]=ALC_FREQUENCY;
      attributes[i++]=frequency;
      attributes[i]=0;
    }
    if(refresh>0) {
      attributes[i++]=ALC_REFRESH;
      attributes[i++]=refresh;
      attributes[i]=0;
    }
    if(synchronous>0) {
      attributes[i++]=ALC_SYNC;
      attributes[i++]=synchronous;
      attributes[i]=0;
    }
    context_=alcCreateContext(device_,attributes);
    if(!context_ || alcGetError(device_)!=AL_FALSE) {
      if(context_)
	alcDestroyContext(context_);
      else
	alcCloseDevice(device_);
      throw InitError("Couldn't create context.");
    }
    alcMakeContextCurrent(context_);
    reverbinitiated_=false;
  }
  instances_++;
}

AudioBase::~AudioBase() {
  instances_--;
  if(!instances_) {
    alcDestroyContext(context_);
  }
}

// Static member
int AudioBase::instances_=0;

}

#include "audiobase.h"

namespace openalpp {

AudioBase::AudioBase(int frequency,int refresh,int synchronous)
  throw (InitError)
{
  if(!instances_) {
    // Open a write (output) device. This should (in theory) make it possible
    // to open a read (input) device later..
    device_=alcOpenDevice((/*const */ALubyte *)"'((direction \"write\"))");
    if(!device_)
      throw InitError("Couldn't open device.");
    int attributes[7],i=0;
    attributes[0]=0;
    if(frequency>0) {
      attributes[i++]=ALC_FREQUENCY;
      attributes[i++]=frequency;
      attributes[i]=0;
    }
    if(refresh>0) {
      attributes[i++]=ALC_REFRESH;
      attributes[i++]=refresh;
      attributes[i]=0;
    }
    if(synchronous>0) {
      attributes[i++]=ALC_SYNC;
      attributes[i++]=synchronous;
      attributes[i]=0;
    }
    context_=alcCreateContext(device_,attributes);
    if(!context_ || alcGetError(device_)!=AL_FALSE) {
      if(context_)
	alcDestroyContext(context_);
      else
	alcCloseDevice(device_);
      throw InitError("Couldn't create context.");
    }
    alcMakeContextCurrent(context_);
    reverbinitiated_=false;
  }
  instances_++;
}

AudioBase::~AudioBase() {
  instances_--;
  if(!instances_) {
    alcDestroyContext(context_);
  }
}

// Static member
int AudioBase::instances_=0;

}

Fix to make it compile in Windows.. Hope it still compiles in Linux...


#include "chainerx/python/error.h"

#include "chainerx/error.h"

#include "chainerx/python/common.h"

namespace chainerx {
namespace python {
namespace python_internal {

namespace py = pybind11;  // standard convention

void InitChainerxError(pybind11::module& m) {
    py::register_exception<ChainerxError>(m, "ChainerxError");
    py::register_exception<ContextError>(m, "ContextError");
    py::register_exception<BackendError>(m, "BackendError");
    py::register_exception<DeviceError>(m, "DeviceError");
    py::register_exception<DimensionError>(m, "DimensionError");
    py::register_exception<DtypeError>(m, "DtypeError");
    py::register_exception<NotImplementedError>(m, "NotImplementedError");
    py::register_exception<GradientCheckError>(m, "GradientCheckError");
}

}  // namespace python_internal
}  // namespace python
}  // namespace chainerx

#include "chainerx/python/error.h"

#include "chainerx/error.h"

#include "chainerx/python/common.h"

namespace chainerx {
namespace python {
namespace python_internal {

namespace py = pybind11;  // standard convention

void InitChainerxError(pybind11::module& m) {
    py::register_exception<ChainerxError>(m, "ChainerxError");
    py::register_exception<ContextError>(m, "ContextError");
    py::register_exception<BackendError>(m, "BackendError");
    py::register_exception<DeviceError>(m, "DeviceError");
    py::register_exception<DimensionError>(m, "DimensionError");
    py::register_exception<DtypeError>(m, "DtypeError");
    py::register_exception<NotImplementedError>(m, "NotImplementedError");
    py::register_exception<GradientError>(m, "GradientError");
    py::register_exception<GradientCheckError>(m, "GradientCheckError");
}

}  // namespace python_internal
}  // namespace python
}  // namespace chainerx

Add Python binding for GradientError

Add Python binding for GradientError


#include "SkTypeface.h"

// ===== Begin Chrome-specific definitions =====

uint32_t SkTypeface::UniqueID(const SkTypeface* face)
{
    return NULL;
}

void SkTypeface::serialize(SkWStream* stream) const {
}

SkTypeface* SkTypeface::Deserialize(SkStream* stream) {
  return NULL;
}

// ===== End Chrome-specific definitions =====

#include "SkTypeface.h"

// ===== Begin Chrome-specific definitions =====

uint32_t SkTypeface::UniqueID(const SkTypeface* face)
{
    return 0;
}

void SkTypeface::serialize(SkWStream* stream) const {
}

SkTypeface* SkTypeface::Deserialize(SkStream* stream) {
  return NULL;
}

// ===== End Chrome-specific definitions =====

Return 0 instead of NULL for a non-pointer type.  Eliminates a warning in GCC.

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


// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/common/api/event_emitter_caller.h"

#include "atom/common/api/locker.h"
#include "atom/common/node_includes.h"

namespace mate {

namespace internal {

v8::Local<v8::Value> CallMethodWithArgs(v8::Isolate* isolate,
                                        v8::Local<v8::Object> obj,
                                        const char* method,
                                        ValueVector* args) {
  // Perform microtask checkpoint after running JavaScript.
  v8::MicrotasksScope script_scope(isolate,
                                   v8::MicrotasksScope::kRunMicrotasks);
  // Use node::MakeCallback to call the callback, and it will also run pending
  // tasks in Node.js.
  v8::MaybeLocal<v8::Value> ret = node::MakeCallback(isolate, obj, method,
                                                     args->size(),
                                                     &args->front(), {0, 0});
  if (ret.IsEmpty()) {
    return v8::Boolean::New(isolate, false);
  }
  return ret.ToLocalChecked();
}

}  // namespace internal

}  // namespace mate

// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/common/api/event_emitter_caller.h"

#include "atom/common/api/locker.h"
#include "atom/common/node_includes.h"

namespace mate {

namespace internal {

v8::Local<v8::Value> CallMethodWithArgs(v8::Isolate* isolate,
                                        v8::Local<v8::Object> obj,
                                        const char* method,
                                        ValueVector* args) {
  // Perform microtask checkpoint after running JavaScript.
  v8::MicrotasksScope script_scope(isolate,
                                   v8::MicrotasksScope::kRunMicrotasks);
  // Use node::MakeCallback to call the callback, and it will also run pending
  // tasks in Node.js.
  v8::MaybeLocal<v8::Value> ret = node::MakeCallback(isolate, obj, method, args->size(), &args->front(),
                            {0, 0});
  // If the JS function throws an exception (doesn't return a value) the result
  // of MakeCallback will be empty, in this case we need to return "false" as
  // that indicates that the event emitter did not handle the event
  if (ret.IsEmpty()) {
    return v8::Boolean::New(isolate, false);
  }

  v8::Local<v8::Value> localRet;
  if (ret.ToLocal(&localRet)) {
    return localRet;
  }
  // Should be unreachable, but the compiler complains if we don't check
  // the result of ToLocal
  return v8::Undefined(isolate);
}

}  // namespace internal

}  // namespace mate

Add comments and use ToLocal instead of ToLocalChecked


/*
 * Copyright (C) 2012 by Glenn Hickey (hickey@soe.ucsc.edu)
 *
 * Released under the MIT license, see LICENSE.txt
 */

#include <cstdlib>
#include <iostream>
#include "halStats.h"

using namespace std;
using namespace hal;

int main(int argc, char** argv)
{
  CLParserPtr optionsParser = hdf5CLParserInstance();
  optionsParser->addArgument("halFile", "path to hal file to validate");
  optionsParser->setDescription("Check if hal database is valid");
  string path;
  try
  {
    optionsParser->parseOptions(argc, argv);
    path = optionsParser->getArgument<string>("halFile");
  }
  catch(exception& e)
  {
    cerr << e.what() << endl;
    optionsParser->printUsage(cerr);
    exit(1);
  }
  try
  {
    AlignmentConstPtr alignment = openHalAlignmentReadOnly(path, optionsParser);
    validateAlignment(alignment);
  }
  catch(hal_exception& e)
  {
    cerr << "hal exception caught: " << e.what() << endl;
    return 1;
  }
  catch(exception& e)
  {
    cerr << "Exception caught: " << e.what() << endl;
    return 1;
  }
  cout << "\nFile valid" << endl;

  return 0;
}

/*
 * Copyright (C) 2012 by Glenn Hickey (hickey@soe.ucsc.edu)
 *
 * Released under the MIT license, see LICENSE.txt
 */

#include <cstdlib>
#include <iostream>
#include "halStats.h"

using namespace std;
using namespace hal;

int main(int argc, char** argv)
{
  CLParserPtr optionsParser = hdf5CLParserInstance();
  optionsParser->addArgument("halFile", "path to hal file to validate");
  optionsParser->addOption("genome", "specific genome to validate instead of entire file", "");
  optionsParser->setDescription("Check if hal database is valid");
  string path, genomeName;
  try
  {
    optionsParser->parseOptions(argc, argv);
    path = optionsParser->getArgument<string>("halFile");
    genomeName = optionsParser->getOption<string>("genome");
  }
  catch(exception& e)
  {
    cerr << e.what() << endl;
    optionsParser->printUsage(cerr);
    exit(1);
  }
  try
  {
    AlignmentConstPtr alignment = openHalAlignmentReadOnly(path, optionsParser);
    if (genomeName == "") {
        validateAlignment(alignment);
    } else {
        const Genome *genome = alignment->openGenome(genomeName);
        validateGenome(genome);
    }
  }
  catch(hal_exception& e)
  {
    cerr << "hal exception caught: " << e.what() << endl;
    return 1;
  }
  catch(exception& e)
  {
    cerr << "Exception caught: " << e.what() << endl;
    return 1;
  }
  cout << "\nFile valid" << endl;

  return 0;
}

Validate one genome at a time

Validate one genome at a time


#include "pch.h"
#include "DspBalance.h"

#include "AudioRenderer.h"

namespace SaneAudioRenderer
{
    void DspBalance::Process(DspChunk& chunk)
    {
        float balance = m_renderer.GetBalance();

        if (!chunk.IsEmpty() && balance != 0.0f)
        {
            assert(balance >= -1.0f && balance <= 1.0f);
            DspChunk::ToFloat(chunk);

            auto data = reinterpret_cast<float*>(chunk.GetData());
            float gain = abs(balance);
            for (size_t i = (balance < 0 ? 1 : 0), n = chunk.GetSampleCount(); i < n; i += 2)
                data[i] *= gain;
        }
    }

    void DspBalance::Finish(DspChunk& chunk)
    {
        Process(chunk);
    }
}

#include "pch.h"
#include "DspBalance.h"

#include "AudioRenderer.h"

namespace SaneAudioRenderer
{
    void DspBalance::Process(DspChunk& chunk)
    {
        float balance = m_renderer.GetBalance();

        if (!chunk.IsEmpty() && balance != 0.0f && chunk.GetChannelCount() == 2)
        {
            assert(balance >= -1.0f && balance <= 1.0f);
            DspChunk::ToFloat(chunk);

            auto data = reinterpret_cast<float*>(chunk.GetData());
            float gain = abs(balance);
            for (size_t i = (balance < 0 ? 1 : 0), n = chunk.GetSampleCount(); i < n; i += 2)
                data[i] *= gain;
        }
    }

    void DspBalance::Finish(DspChunk& chunk)
    {
        Process(chunk);
    }
}

Use balance dsp only in stereo

Use balance dsp only in stereo


#include "LevelState.h"

LevelState::LevelState()
{
}

LevelState::~LevelState()
{
}

int LevelState::ShutDown()
{
	int result = 1;
	return result;
}

int LevelState::Initialize(GameStateHandler * gsh, ComponentHandler* cHandler)
{
	int result = 0;
	result = GameState::InitializeBase(gsh, cHandler);

	//Read from file
	//Get Components
	GraphicsComponent* tempComp = this->m_cHandler->GetGraphicsComponent();
	//Set Component values
	tempComp->active = 1;
	tempComp->modelID = 1337;
	tempComp->worldMatrix = DirectX::XMMatrixIdentity();
	//Give Components to entities
	this->m_player1.Initialize();
	return result;
}

int LevelState::Update(float dt, InputHandler * inputHandler)
{
	int result = 0;

	this->m_player1.Update(dt, inputHandler);

	return result;
}

#include "LevelState.h"

LevelState::LevelState()
{
}

LevelState::~LevelState()
{
}

int LevelState::ShutDown()
{
	int result = 1;
	return result;
}

int LevelState::Initialize(GameStateHandler * gsh, ComponentHandler* cHandler)
{
	int result = 0;
	result = GameState::InitializeBase(gsh, cHandler);

	//Read from file
	//Get Components
	GraphicsComponent* tempGComp = this->m_cHandler->GetGraphicsComponent();
	PhysicsComponent* tempPComp = this->m_cHandler->GetPhysicsComponent();
	//Set Component values
	tempGComp->active = 1;
	tempGComp->modelID = 1337;
	tempGComp->worldMatrix = DirectX::XMMatrixIdentity();
	tempPComp->PC_active = 1;
	tempPComp->PC_pos = DirectX::XMVectorSet(0.0f, 2.0f, 1.0f, 1.0f);
	//Give Components to entities
	this->m_player1.Initialize();
	this->m_player1.SetGraphicsComponent(tempGComp);
	this->m_player1.SetPhysicsComponent(tempPComp);
	return result;
}

int LevelState::Update(float dt, InputHandler * inputHandler)
{
	int result = 0;

	this->m_player1.Update(dt, inputHandler);

	return result;
}

UPDATE Sets values for components properly


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

#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif

#include <tinyformat.h>
#include <util/syserror.h>

#include <cstring>

std::string SysErrorString(int err)
{
    char buf[256];
    buf[0] = 0;
    /* Too bad there are two incompatible implementations of the
     * thread-safe strerror. */
    const char *s;
#ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */
    s = strerror_r(err, buf, sizeof(buf));
#else /* POSIX variant always returns message in buffer */
    s = buf;
    if (strerror_r(err, buf, sizeof(buf)))
        buf[0] = 0;
#endif
    return strprintf("%s (%d)", s, err);
}

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

#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif

#include <tinyformat.h>
#include <util/syserror.h>

#include <cstring>

std::string SysErrorString(int err)
{
    char buf[256];
    buf[0] = 0;
    /* Too bad there are three incompatible implementations of the
     * thread-safe strerror. */
    const char *s;
#ifdef WIN32
    s = buf;
    if (strerror_s(buf, sizeof(buf), err) != 0)
        buf[0] = 0;
#else
#ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */
    s = strerror_r(err, buf, sizeof(buf));
#else /* POSIX variant always returns message in buffer */
    s = buf;
    if (strerror_r(err, buf, sizeof(buf)))
        buf[0] = 0;
#endif
#endif
    return strprintf("%s (%d)", s, err);
}

util: Use strerror_s for SysErrorString on Windows

Github-Pull: #24933
Rebased-From: e7f2f77756d33c6be9c8998a575b263ff2d39270


#include "listener.h"
#include "log.h"
#include "buffers.h"

void conditionalEnqueue(QUEUE_TYPE(uint8_t)* queue, uint8_t* message,
        int messageSize) {
    if(queue_available(queue) < messageSize + 1) {
            debug("Dropped incoming CAN message -- send queue full for USB\r\n");
            return;
    }

    for(int i = 0; i < messageSize; i++) {
        QUEUE_PUSH(uint8_t, queue, (uint8_t)message[i]);
    }
    QUEUE_PUSH(uint8_t, queue, (uint8_t)'\n');
}

void sendMessage(Listener* listener, uint8_t* message, int messageSize) {
    // TODO the more we enqueue here, the slower it gets - cuts the rate by
    // almost half to do it with 2 queues. we could either figure out how to
    // share a queue or make the enqueue function faster. right now I believe it
    // enqueues byte by byte, which could obviously be improved.
    conditionalEnqueue(&listener->usb->sendQueue, message, messageSize);
#ifdef SERIAL
    conditionalEnqueue(&listener->serial->sendQueue, message, messageSize);
#endif
}

void processListenerQueues(Listener* listener) {
    processInputQueue(listener->usb);
#ifdef SERIAL
    processInputQueue(listener->serial);
#endif
}

#include "listener.h"
#include "log.h"
#include "buffers.h"

void conditionalEnqueue(QUEUE_TYPE(uint8_t)* queue, uint8_t* message,
        int messageSize) {
    if(queue_available(queue) < messageSize + 1) {
            debug("Dropped incoming CAN message -- send queue full\r\n");
            return;
    }

    for(int i = 0; i < messageSize; i++) {
        QUEUE_PUSH(uint8_t, queue, (uint8_t)message[i]);
    }
    QUEUE_PUSH(uint8_t, queue, (uint8_t)'\n');
}

void sendMessage(Listener* listener, uint8_t* message, int messageSize) {
    // TODO the more we enqueue here, the slower it gets - cuts the rate by
    // almost half to do it with 2 queues. we could either figure out how to
    // share a queue or make the enqueue function faster. right now I believe it
    // enqueues byte by byte, which could obviously be improved.
    conditionalEnqueue(&listener->usb->sendQueue, message, messageSize);
#ifdef SERIAL
    conditionalEnqueue(&listener->serial->sendQueue, message, messageSize);
#endif
}

void processListenerQueues(Listener* listener) {
    processInputQueue(listener->usb);
#ifdef SERIAL
    processInputQueue(listener->serial);
#endif
}

Use more generic language in a log message, could be serial or USB.


#include <sstream>
#include "backend.h"

tstring CommandConsole::receiveStandardInput() {
  char input [1024];
  std::cin >> input;

  return input;
}

void CommandConsole::processStandardOutput(const tstring& output) {
  std::cout << output;
}

#include <sstream>
#include "backend.h"

tstring CommandConsole::receiveStandardInput() {
  tstring input;
  std::cin >> input;

  return input;
}

void CommandConsole::processStandardOutput(const tstring& output) {
  std::cout << output;
}

Fix console output to use tstring.

Fix console output to use tstring.


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

#include "net/base/network_change_notifier_win.h"

#include <iphlpapi.h>
#include <winsock2.h>

#pragma comment(lib, "iphlpapi.lib")

namespace net {

NetworkChangeNotifierWin::NetworkChangeNotifierWin() {
  memset(&addr_overlapped_, 0, sizeof addr_overlapped_);
  addr_overlapped_.hEvent = WSACreateEvent();
}

NetworkChangeNotifierWin::~NetworkChangeNotifierWin() {
  CancelIPChangeNotify(&addr_overlapped_);
  addr_watcher_.StopWatching();
  WSACloseEvent(addr_overlapped_.hEvent);
}

void NetworkChangeNotifierWin::OnObjectSignaled(HANDLE object) {
  NotifyObserversOfIPAddressChange();

  // Start watching for the next address change.
  WatchForAddressChange();
}

void NetworkChangeNotifierWin::WatchForAddressChange() {
  HANDLE handle = NULL;
  DWORD ret = NotifyAddrChange(&handle, &addr_overlapped_);
  CHECK(ret == ERROR_IO_PENDING);
  addr_watcher_.StartWatching(addr_overlapped_.hEvent, this);
}

}  // namespace net

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

#include "net/base/network_change_notifier_win.h"

#include <iphlpapi.h>
#include <winsock2.h>

#pragma comment(lib, "iphlpapi.lib")

namespace net {

NetworkChangeNotifierWin::NetworkChangeNotifierWin() {
  memset(&addr_overlapped_, 0, sizeof addr_overlapped_);
  addr_overlapped_.hEvent = WSACreateEvent();
  WatchForAddressChange();
}

NetworkChangeNotifierWin::~NetworkChangeNotifierWin() {
  CancelIPChangeNotify(&addr_overlapped_);
  addr_watcher_.StopWatching();
  WSACloseEvent(addr_overlapped_.hEvent);
}

void NetworkChangeNotifierWin::OnObjectSignaled(HANDLE object) {
  NotifyObserversOfIPAddressChange();

  // Start watching for the next address change.
  WatchForAddressChange();
}

void NetworkChangeNotifierWin::WatchForAddressChange() {
  HANDLE handle = NULL;
  DWORD ret = NotifyAddrChange(&handle, &addr_overlapped_);
  CHECK(ret == ERROR_IO_PENDING);
  addr_watcher_.StartWatching(addr_overlapped_.hEvent, this);
}

}  // namespace net

Fix regression where we didn't ever start watching for network address changes on Windows.

BUG=48204
TEST=NetworkChangeNotifier works on Windows
Review URL: http://codereview.chromium.org/2807036

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

Former-commit-id: 245af1ba8f24bc82b82cdb378479a4c2470dca8a


#include "accessobject.h"
#include "accessclass.h"
#include "util.h"
#include <QSet>
#include <QQmlEngine>

namespace RubyQml {

AccessObject::AccessObject(const SP<ForeignClass> &klass, VALUE value) :
    ForeignObject(klass),
    mValue(value)
{
    globalMarkValues() << value;
    QQmlEngine::setObjectOwnership(this, QQmlEngine::JavaScriptOwnership);
}

AccessObject::~AccessObject()
{
    globalMarkValues().remove(mValue);
}

} // namespace RubyQml

#include "accessobject.h"
#include "accessclass.h"
#include "util.h"
#include <QSet>

namespace RubyQml {

AccessObject::AccessObject(const SP<ForeignClass> &klass, VALUE value) :
    ForeignObject(klass),
    mValue(value)
{
    globalMarkValues() << value;
}

AccessObject::~AccessObject()
{
    globalMarkValues().remove(mValue);
}

} // namespace RubyQml

Revert "AccessObject objects are owned by QML"

This reverts commit 79352321388304c7ff2fc5ecdcf78b35e5958b33.


// RUN: %clang_cc1 -fsyntax-only -verify %s

struct S {
   S (S);  // expected-error {{copy constructor must pass its first argument by reference}}
};

S f();

void g() {
  S a( f() );
}

namespace PR6064 {
  struct A {
    A() { }
    inline A(A&, int);
  };

  A::A(A&, int = 0) { }

  void f() {
    A const a;
    A b(a);
  }
}

Add test case from PR6064, which now works

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


// REQUIRES: asan-64-bits
// Regression test: __tls_get_addr interceptor must recognize static TLS.
//
// RUN: %clangxx_asan -DSHARED %s -shared -o %t-so.so -fPIC
// RUN: %clangxx_asan %s -ldl -pthread -o %t %t-so.so
// RUN: ASAN_OPTIONS=verbosity=2 %run %t 2>&1 | FileCheck %s

// CHECK: before
// CHECK: __tls_get_addr: static tls
// CHECK: after

#ifndef SHARED
#include <stdio.h>

unsigned *f();
int main(int argc, char *argv[]) {
  fprintf(stderr, "before\n");
  f();
  fprintf(stderr, "after\n");
  return 0;
}
#else  // SHARED
static __thread unsigned ThreadLocal;
unsigned *f() {
  return &ThreadLocal;
}
#endif

// REQUIRES: asan-64-bits
// Regression test: __tls_get_addr interceptor must recognize static TLS.
//
// RUN: %clangxx_asan -DSHARED %s -shared -o %t-so.so -fPIC
// RUN: %clangxx_asan %s -ldl -pthread -o %t %t-so.so
// RUN: ASAN_OPTIONS=verbosity=2 %run %t 2>&1 | FileCheck %s

// CHECK: before
// CHECK: __tls_get_addr: static tls
// CHECK: after

// XFAIL: powerpc64

#ifndef SHARED
#include <stdio.h>

unsigned *f();
int main(int argc, char *argv[]) {
  fprintf(stderr, "before\n");
  f();
  fprintf(stderr, "after\n");
  return 0;
}
#else  // SHARED
static __thread unsigned ThreadLocal;
unsigned *f() {
  return &ThreadLocal;
}
#endif

Disable static-tls test on PowerPC.

[asan] Disable static-tls test on PowerPC.

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


#include "event.h"
#include "deconz.h"
#include "resource.h"

/*! Constructor.
 */
Event::Event() :
    m_resource(0),
    m_what(0),
    m_num(0),
    m_numPrev(0)
{
}

Event::Event(const char *resource, const char *what, const QString &id, ResourceItem *item) :
    m_resource(resource),
    m_what(what),
    m_id(id),
    m_num(0),
    m_numPrev(0)
{
    DBG_Assert(item != 0);
    if (item)
    {
        m_num = item->toNumber();
        m_numPrev = item->toNumberPrevious();
    }
}

/*! Constructor.
 */
Event::Event(const char *resource, const char *what, const QString &id) :
    m_resource(resource),
    m_what(what),
    m_id(id),
    m_num(0),
    m_numPrev(0)
{
}

/*! Constructor.
 */
Event::Event(const char *resource, const char *what, int num) :
    m_resource(resource),
    m_what(what),
    m_num(num),
    m_numPrev(0)
{
}

#include "event.h"
#include "deconz.h"
#include "resource.h"

/*! Constructor.
 */
Event::Event() :
    m_resource(0),
    m_what(0),
    m_num(0),
    m_numPrev(0)
{
}

Event::Event(const char *resource, const char *what, const QString &id, ResourceItem *item) :
    m_resource(resource),
    m_what(what),
    m_id(id),
    m_num(0),
    m_numPrev(0)
{
    DBG_Assert(item != 0);
    if (item)
    {
        m_num = item->toNumber();
        m_numPrev = item->toNumberPrevious();
    }
}

/*! Constructor.
 */
Event::Event(const char *resource, const char *what, const QString &id) :
    m_resource(resource),
    m_what(what),
    m_id(id),
    m_num(0),
    m_numPrev(0)
{
}

/*! Constructor.
 */
Event::Event(const char *resource, const char *what, int num) :
    m_resource(resource),
    m_what(what),
    m_num(num),
    m_numPrev(0)
{
    if (resource == RGroups)
    {
        m_id = QString::number(num);
    }
}

Support id() method for RGroup resources used in rules


// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
//
// Copyright 2015 Heiko Fink, All Rights Reserved.
//
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
//
// Perception Neuron (TM) is a trademark of Beijing Noitom Technology Ltd.
//
// Description:
// This code implements the module startup and shutdown functions.
//

#include "PerceptionNeuronPrivatePCH.h"

#define LOCTEXT_NAMESPACE "FPerceptionNeuronModule"

void FPerceptionNeuronModule::StartupModule()
{
	// This code will execute after your module is loaded into memory; the exact timing is specified in the .uplugin file per-module

}

void FPerceptionNeuronModule::ShutdownModule()
{
	// This function may be called during shutdown to clean up your module.  For modules that support dynamic reloading,
	// we call this function before unloading the module.

}

#undef LOCTEXT_NAMESPACE

IMPLEMENT_MODULE(FPerceptionNeuronModule, PerceptionNeuron)

// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
//
// Copyright 2015 Heiko Fink, All Rights Reserved.
//
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
//
// Perception Neuron (TM) is a trademark of Beijing Noitom Technology Ltd.
//
// Description:
// This code implements the Perception Neuron (TM) module startup and shutdown functions.
//

#include "PerceptionNeuronPrivatePCH.h"

#define LOCTEXT_NAMESPACE "FPerceptionNeuronModule"

void FPerceptionNeuronModule::StartupModule()
{
	// This code will execute after your module is loaded into memory; the exact timing is specified in the .uplugin file per-module

	UE_LOG(LogInit, Log, TEXT("Unofficial Perception Neuron (TM) Plugin started."));
}

void FPerceptionNeuronModule::ShutdownModule()
{
	// This function may be called during shutdown to clean up your module.  For modules that support dynamic reloading,
	// we call this function before unloading the module.

	UE_LOG(LogExit, Log, TEXT("Unofficial Perception Neuron (TM) Plugin unloaded."));
}

#undef LOCTEXT_NAMESPACE

IMPLEMENT_MODULE(FPerceptionNeuronModule, PerceptionNeuron)

Add Logmessage on Module Start and Stop

Add Logmessage on Module Start and Stop


#include <gtest/gtest.h>
#include <stdlib.h>
#include <time.h>
#if defined (ANDROID_NDK)
#include <stdio.h>
#endif

#if (defined(ANDROID_NDK)||defined(APPLE_IOS))
int CodecUtMain (int argc , char** argv) {
#else
int main (int argc, char** argv) {
#endif

#if (defined(ANDROID_NDK)||defined(APPLE_IOS))
  char xmlPath[1024] = "";
  sprintf (xmlPath, "xml:%s", argv[1]);
  ::testing::GTEST_FLAG (output) = xmlPath;
#endif
  srand ((unsigned int)time (NULL));
  ::testing::InitGoogleTest (&argc, argv);

  return RUN_ALL_TESTS();
}

#include <gtest/gtest.h>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <string.h>

#if (defined(ANDROID_NDK)||defined(APPLE_IOS))
int CodecUtMain (int argc , char** argv) {
#else
int main (int argc, char** argv) {
#endif

#if (defined(ANDROID_NDK)||defined(APPLE_IOS))
  char xmlPath[1024] = "";
  sprintf (xmlPath, "xml:%s", argv[1]);
  ::testing::GTEST_FLAG (output) = xmlPath;
#endif
  ::testing::InitGoogleTest (&argc, argv);
  unsigned int seed = (unsigned int) time (NULL);
  if (argc >= 2 && !strncmp (argv[1], "--seed=", 7))
    seed = atoi (argv[1] + 7);
  printf ("Random seed: %u\n", seed);
  srand (seed);

  return RUN_ALL_TESTS();
}

Print the random seed at startup

Print the random seed at startup

Also add an option for overriding the seed at startup.

This allows reproducing temporary issues by rerunning the test suite
with the same random seed.

Note that if tests are added or removed (or tests are skipped by passing
the --gtest_filter option), or if running on a different libc, the same
seed might result in different random values.


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

// The fixture for testing class Foo.
class CpuTest : public Cpu, public ::testing::Test
{
protected:
  CpuTest()
  {
  }

  ~CpuTest() override
  {
  }

  void SetUp() override
  {
  }

  void TearDown() override
  {
  }
};

TEST_F(CpuTest, pcNop)
{
  runOpcode(0x01);
  EXPECT_EQ(getPC(), 3);
}

TEST_F(CpuTest, integrationBlop)
{
  //run bootstrap rom to see if we crash?
  getMMU().injectBoot();
  for (long long unsigned int i = 0; i < 1000000; i++)
    execute();

  // std::cout << getInfo() << std::endl
  //           << "Cyles: " << getTotalCycles();
}

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

// The fixture for testing class Foo.
class CpuTest : public Cpu, public ::testing::Test
{
protected:
  CpuTest()
  {
  }

  ~CpuTest() override
  {
  }

  void SetUp() override
  {
  }

  void TearDown() override
  {
  }
};

TEST_F(CpuTest, pcNop)
{
  runOpcode(0x01);
  EXPECT_EQ(getPC(), 3);
}

TEST_F(CpuTest, DMGboot)
{
  //run bootstrap rom to see if we crash
  getMMU().injectBoot();
  getMMU().writeByte(0xff44, 0x90); //$0064, screen frame skip
  getMMU().writeByte(0x0135, 0xe7); //ensure the checksum is correct

  long long unsigned int i = 0;
  while(getRegisters().pc != 0x100)
  {
    execute();
    ASSERT_LT(i++, 15000000); //shouldn't take more?

  }

}

Add integration-ish test for the boot

Add integration-ish test for the boot


#include "Halide.h"
#include <stdint.h>
#include <stdio.h>
#include <cmath>

using namespace Halide;

// FIXME: Why aren't we using a unit test framework for this?
// See Issue #898
void h_assert(bool condition, const char* msg) {
    if (!condition) {
        printf("FAIL: %s\n", msg);
        abort();
    }
}

int main() {
    // Number is larger than can be represented in half and won't be rounded
    // down to the largest representable value in half(65504).  but should be
    // representable in single precision
    const int32_t largeNum = 65536;
    h_assert(!std::isnan(largeNum), "largeNum should not be NaN");
    h_assert(!std::isinf(largeNum), "largeNum should not be inf");

    // This should fail as it triggers overflow
    float16_t fail = float16_t::make_from_signed_int(largeNum, RoundingMode::ToNearestTiesToEven);

    // Supress -Wunused-but-set-variable
    fail.is_infinity();

    printf("Should not be reached!\n");
    return 0;
}

#include "Halide.h"
#include <stdint.h>
#include <stdio.h>
#include <cmath>

using namespace Halide;

// FIXME: Why aren't we using a unit test framework for this?
// See Issue #898
void h_assert(bool condition, const char* msg) {
    if (!condition) {
        printf("FAIL: %s\n", msg);
        abort();
    }
}

int main() {
    // Number is larger than can be represented in half and won't be rounded
    // down to the largest representable value in half(65504).  but should be
    // representable in single precision
    const int32_t largeNum = 65536;

    // This should fail as it triggers overflow
    float16_t fail = float16_t::make_from_signed_int(largeNum, RoundingMode::ToNearestTiesToEven);

    // Supress -Wunused-but-set-variable
    fail.is_infinity();

    printf("Should not be reached!\n");
    return 0;
}

Remove isnan of an int

Remove isnan of an int


/*
Copyright c1997-2006 Trygve Isaacson. All rights reserved.
This file is part of the Code Vault version 2.5
http://www.bombaydigital.com/
*/

/** @file */

#include "vwritebufferedstream.h"

#include "vexception.h"

VWriteBufferedStream::VWriteBufferedStream(VStream& rawStream, Vs64 initialBufferSize, Vs64 resizeIncrement) :
VMemoryStream(initialBufferSize, resizeIncrement),
mRawStream(rawStream)
    {
    }

Vs64 VWriteBufferedStream::read(Vu8* /*targetBuffer*/, Vs64 /*numBytesToRead*/)
    {
    throw VException("VWriteBufferedStream::read: Read is not permitted on buffered write stream.");

    return CONST_S64(0);
    }

void VWriteBufferedStream::flush()
    {
    // Flush the complete contents of our buffer to the raw stream.
    this->seek(SEEK_SET, 0);    // set our i/o offset back to 0
    ::streamCopy(*this, mRawStream, this->eofOffset());

    // Reset ourself to be "empty" and at i/o offset 0.
    this->seek(SEEK_SET, 0);
    this->setEOF(0);
    }

bool VWriteBufferedStream::skip(Vs64 /*numBytesToSkip*/)
    {
    throw VException("VWriteBufferedStream::skip: Skip is not permitted on buffered write stream.");

    return false;
    }

/*
Copyright c1997-2006 Trygve Isaacson. All rights reserved.
This file is part of the Code Vault version 2.5
http://www.bombaydigital.com/
*/

/** @file */

#include "vwritebufferedstream.h"

#include "vexception.h"

VWriteBufferedStream::VWriteBufferedStream(VStream& rawStream, Vs64 initialBufferSize, Vs64 resizeIncrement) :
VMemoryStream(initialBufferSize, resizeIncrement),
mRawStream(rawStream)
    {
    }

Vs64 VWriteBufferedStream::read(Vu8* /*targetBuffer*/, Vs64 /*numBytesToRead*/)
    {
    throw VException("VWriteBufferedStream::read: Read is not permitted on buffered write stream.");

    return CONST_S64(0);
    }

void VWriteBufferedStream::flush()
    {
    // Flush the complete contents of our buffer to the raw stream.
    this->seek(SEEK_SET, 0);    // set our i/o offset back to 0
    (void) streamCopy(*this, mRawStream, this->eofOffset());

    // Reset ourself to be "empty" and at i/o offset 0.
    this->seek(SEEK_SET, 0);
    this->setEOF(0);
    }

bool VWriteBufferedStream::skip(Vs64 /*numBytesToSkip*/)
    {
    throw VException("VWriteBufferedStream::skip: Skip is not permitted on buffered write stream.");

    return false;
    }

Fix ignored return type warning.

Fix ignored return type warning.


#include "BezierCurve.h"

BezierCurve::BezierCurve(int range, double accur, int bits)
{
	m_range = range;
	m_accur = accur;
	m_bits = bits;
}

double BezierCurve::normalize(int x)
{
	double result;
	int scale = ((1 << m_bits) - 1) / 255;

	if (m_range == 0)  // PC range
	{
		result = x / (255. * scale);
	}
	else  // TV range
	{
		if (x < 16 * scale)
			result = 0;
		else if (x > 255 * scale)
			result = 1;
		else
			result = (x - 16 * scale) / (235. * scale - 16. * scale);
	}

	return result;
}

#include "BezierCurve.h"

BezierCurve::BezierCurve(int range, double accur, int bits)
{
	m_range = range;
	m_accur = accur;
	m_bits = bits;
}

double BezierCurve::normalize(int x)
{
	double result;
	int scale = ((1 << m_bits) - 1) / 255;

	if (m_range == 0)  // PC range
	{
		result = x / (255. * scale);
	}
	else  // TV range
	{
		if (x < 16 * scale)
			result = 0;
		else if (x > 235 * scale)
			result = 1;
		else
			result = (x - 16 * scale) / (235. * scale - 16. * scale);
	}

	return result;
}

Fix an error of tv range normalization

Fix an error of tv range normalization


/* Copyright 2011 Thomas McGuire <mcguire@kde.org>
   Copyright 2011 Alexander Potashev <aspotashev@gmail.com>

   This library is free software; you can redistribute it and/or modify
   it under the terms of the GNU Library General Public License as published
   by the Free Software Foundation; either version 2 of the License or
   ( at your option ) version 3 or, at the discretion of KDE e.V.
   ( which shall act as a proxy as in section 14 of the GPLv3 ), any later version.

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

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/
#include "util.h"

#include <KGlobal>

static const KCatalogLoader loader("libkvkontakte");

KDateTime unixTimeToKDateTime(const QString &unixTime)
{
    KDateTime res;
    res.setTime_t(unixTime.toLongLong());
    return res;
}

/* Copyright 2011 Thomas McGuire <mcguire@kde.org>
   Copyright 2011 Alexander Potashev <aspotashev@gmail.com>

   This library is free software; you can redistribute it and/or modify
   it under the terms of the GNU Library General Public License as published
   by the Free Software Foundation; either version 2 of the License or
   ( at your option ) version 3 or, at the discretion of KDE e.V.
   ( which shall act as a proxy as in section 14 of the GPLv3 ), any later version.

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

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/
#include "util.h"

#include <kdeversion.h>

#if KDE_IS_VERSION(4,6,2)
#include <KDE/KGlobal>
static const KCatalogLoader loader("libkvkontakte");
#endif

KDateTime unixTimeToKDateTime(const QString &unixTime)
{
    KDateTime res;
    res.setTime_t(unixTime.toLongLong());
    return res;
}

Disable KCatalogLoader for kdelibs below 4.6.2

BUG:282113


#include "stdafx.h"
#include "foobar2000/SDK/foobar2000.h"

#include "ServerProxy.h"

DECLARE_COMPONENT_VERSION(
"foo_rest",
"0.1",
"REST interface for foobar."
)

class InitQuit : public initquit
{
public:
	virtual void on_init();
	virtual void on_quit();
};

std::unique_ptr<ServerProxy> serverProxy;

void InitQuit::on_init()
{
	serverProxy = std::make_unique<ServerProxy>();
}

void InitQuit::on_quit()
{
	serverProxy.release();
}

initquit_factory_t<InitQuit> initQuitFactory;

#include "stdafx.h"
#include "foobar2000/SDK/foobar2000.h"

#include "ServerProxy.h"

DECLARE_COMPONENT_VERSION(
"foo_rest",
"0.1",
"REST interface for foobar.\nhttps://github.com/ivarboms/foo_rest"
)

class InitQuit : public initquit
{
public:
	virtual void on_init();
	virtual void on_quit();
};

std::unique_ptr<ServerProxy> serverProxy;

void InitQuit::on_init()
{
	serverProxy = std::make_unique<ServerProxy>();
}

void InitQuit::on_quit()
{
	serverProxy.release();
}

initquit_factory_t<InitQuit> initQuitFactory;

Add link to github in about text.

Add link to github in about text.


//===-- main.cpp ------------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include <stdio.h>
#include <unistd.h>

int main (int argc, char const *argv[])
{
    char my_string[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 0};
    double my_double = 1234.5678;

    // For simplicity assume that any cmdline argument means wait for attach.
    if (argc > 1)
    {
        volatile int wait_for_attach=1;
        while (wait_for_attach)
            usleep(1);
    }

    printf("my_string=%s\n", my_string);
    printf("my_double=%g\n", my_double);
    return 0;
}

//===-- main.cpp ------------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include <stdio.h>
#include <unistd.h>

#if defined(__linux__)
#include <sys/prctl.h>
#endif

int main (int argc, char const *argv[])
{
#if defined(__linux__)
    // Immediately enable any ptracer so that we can allow the stub attach
    // operation to succeed.  Some Linux kernels are locked down so that
    // only an ancestor process can be a ptracer of a process.  This disables that
    // restriction.  Without it, attach-related stub tests will fail.
#if defined(PR_SET_PTRACER) && defined(PR_SET_PTRACER_ANY)
    // For now we execute on best effort basis.  If this fails for
    // some reason, so be it.
    const int prctl_result = prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0);
    static_cast<void> (prctl_result);
#endif
#endif

    char my_string[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 0};
    double my_double = 1234.5678;

    // For simplicity assume that any cmdline argument means wait for attach.
    if (argc > 1)
    {
        volatile int wait_for_attach=1;
        while (wait_for_attach)
            usleep(1);
    }

    printf("my_string=%s\n", my_string);
    printf("my_double=%g\n", my_double);
    return 0;
}

Fix up TestRegisters for Linux ptracer lock-down.

All of these test fixups are prep work for when llgs is
running with llgs for local process debugging, where these
tests fail without the ptracer lock-down suppression.

git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@220656 91177308-0d34-0410-b5e6-96231b3b80d8


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

#include "ppapi/proxy/ppapi_messages.h"

#include "base/file_path.h"
#include "ipc/ipc_channel_handle.h"
#include "ppapi/c/dev/pp_file_info_dev.h"
#include "ppapi/c/ppb_var.h"

// This actually defines the implementations of all the IPC message functions.
#define MESSAGES_INTERNAL_IMPL_FILE "ppapi/proxy/ppapi_messages_internal.h"
#include "ipc/ipc_message_impl_macros.h"

Add a blank line to force this file to be recompiled on Mac on the bots.

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


#include "tmfs.hh"

int main(int argc, char ** argv)
{
  if (argc < 3)
  {
    fprintf(stderr, "%s: <path> fuse-options...\n", argv[0]);
    return 2;
  }

  /* global structure setup */
  tmfs::instance().hfs_root_ = argv[1];
  --argc;
  for (int i = 1; i < argc; ++i)
    argv[i] = argv[i + 1];

  /* check that hfs_root is a directory */
  struct stat st;
  if (lstat(tmfs::instance().hfs_root_.c_str(), &st)) {
    fprintf(stderr, "%s: %m\n", tmfs::instance().hfs_root_.c_str());
    return 1;
  }

  if (!S_ISDIR(st.st_mode)) {
    fprintf(stderr, "%s: is not a directory\n", tmfs::instance().hfs_root_.c_str());
    return 1;
  }

  /* vtable setup */
  struct fuse_operations ops;
  memset(&ops, 0, sizeof (ops));
  ops.read    = tmfs_read;
  ops.getattr = tmfs_getattr;
  ops.readdir = tmfs_readdir;

  /* lets go */
  fuse_main(argc, argv, &ops, NULL);
  return 0;
}

#include "tmfs.hh"

int main(int argc, char ** argv)
{
  if (argc < 3)
  {
    fprintf(stderr, "usage: %s: <HFS+ mount> <Time Machine Mount>"
            " [fuse options]\n", argv[0]);
    return 2;
  }

  /* global structure setup */
  tmfs::instance().hfs_root_ = argv[1];
  --argc;
  for (int i = 1; i < argc; ++i)
    argv[i] = argv[i + 1];

  /* check that hfs_root is a directory */
  struct stat st;
  if (lstat(tmfs::instance().hfs_root_.c_str(), &st)) {
    fprintf(stderr, "%s: %m\n", tmfs::instance().hfs_root_.c_str());
    return 1;
  }

  if (!S_ISDIR(st.st_mode)) {
    fprintf(stderr, "%s: is not a directory\n", tmfs::instance().hfs_root_.c_str());
    return 1;
  }

  /* vtable setup */
  struct fuse_operations ops;
  memset(&ops, 0, sizeof (ops));
  ops.read    = tmfs_read;
  ops.getattr = tmfs_getattr;
  ops.readdir = tmfs_readdir;

  /* lets go */
  fuse_main(argc, argv, &ops, NULL);
  return 0;
}

Improve usage message, according to nickrw's suggestion.


#include "fdsb/fabric.hpp"
#include "fdsb/nid.hpp"
#include "fdsb/harc.hpp"

#include <unordered_map>

using namespace fdsb;

std::unordered_multimap<unsigned long long,Harc*> fabric;

Harc &fdsb::get(const Nid &a, const Nid &b)
{
	for (auto i : fabric.find(Nid::dual_hash(a,b)))
	{
		if ((i->tail(0) == a && i->tail(1) == b) || (i->tail(0) == b && i->tail(1) == a))
		{
			return *i;
		}
	}

	Harc *nh = new Harc(a,b);
	add(*nh);
	return *nh;
}

void fdsb::add(Harc &h)
{
	fabric.insert({{Nid::dual_hash(h.tail(0),h.tail(1)), &h}});
}

void fdsb::add(const Nid &n1, const Nid &n2)
{
	fdsb::add(*(new Harc(n1,n2)));
}

Harc &Nid::operator[](const Nid &n)
{
	return fdsb::get(*this,n);
}

Harc &Harc::operator[](const Nid &n)
{
	return fdsb::get(query(),n);
}

#include "fdsb/fabric.hpp"
#include "fdsb/nid.hpp"
#include "fdsb/harc.hpp"

#include <unordered_map>

using namespace fdsb;

std::unordered_multimap<unsigned long long,Harc*> fabric;

Harc &fdsb::get(const Nid &a, const Nid &b)
{
	auto range = fabric.equal_range(Nid::dual_hash(a,b));
	for (auto i : range)
	{
		if ((i->tail(0) == a && i->tail(1) == b) || (i->tail(0) == b && i->tail(1) == a))
		{
			return *i;
		}
	}

	Harc *nh = new Harc(a,b);
	add(*nh);
	return *nh;
}

void fdsb::add(Harc &h)
{
	fabric.insert({{Nid::dual_hash(h.tail(0),h.tail(1)), &h}});
}

void fdsb::add(const Nid &n1, const Nid &n2)
{
	fdsb::add(*(new Harc(n1,n2)));
}

Harc &Nid::operator[](const Nid &n)
{
	return fdsb::get(*this,n);
}

Harc &Harc::operator[](const Nid &n)
{
	return fdsb::get(query(),n);
}

Use map range for iterator

Use map range for iterator


/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * LXDE-Qt - a lightweight, Qt based, desktop toolset
 * http://razor-qt.org
 *
 * Copyright: 2012 Razor team
 * Authors:
 *   Christian Surlykke <christian@surlykke.dk>
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include <LXQt/Application>

#include "mainwindow.h"

int main(int argc, char *argv[])
{
    LxQt::Application a(argc, argv);

    MainWindow mainWindow;
    mainWindow.setWindowIcon(QIcon::fromTheme("preferences-system-power-management"));
    mainWindow.show();

    return a.exec();
}

/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * LXDE-Qt - a lightweight, Qt based, desktop toolset
 * http://razor-qt.org
 *
 * Copyright: 2012 Razor team
 * Authors:
 *   Christian Surlykke <christian@surlykke.dk>
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include <LXQt/SingleApplication>

#include "mainwindow.h"

int main(int argc, char *argv[])
{
    LxQt::SingleApplication a(argc, argv);

    MainWindow mainWindow;
    mainWindow.setWindowIcon(QIcon::fromTheme("preferences-system-power-management"));
    mainWindow.show();
    a.setActivationWindow(&mainWindow);

    return a.exec();
}

Use SingleApplication rather than Application


#include <iostream>

int main(void)
{
    std::cout << "woooot" << std::endl;
}

#define BOOST_TEST_MODULE simple_test
#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_CASE(simple_cpp_test)
{
        BOOST_CHECK(true);
}

Make cpp test a unit test

Make cpp test a unit test


// Copyright 2020 The Google Research Authors.
//
// 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 "benchmark/benchmark.h"
#include "benchmark_utils.h"
#include "lossy_count.h"
#include "sketch.h"
#include "utils.h"

static void BM_LossyCountAdd(benchmark::State& state) {
  sketch::LossyCount sketch(/*window_size=*/2000);
  Add(state, &sketch);
}

static void BM_LossyCountFallbackAdd(benchmark::State& state) {
  sketch::LossyCount_Fallback sketch(/*window_size=*/2000, /*hash_count=*/5,
                                     /*hash_size=*/2048);
  Add(state, &sketch);
}

BENCHMARK(BM_LossyCountAdd)->Range(1 << 12, 1 << 21);
BENCHMARK(BM_LossyCountFallbackAdd)->Range(1 << 12, 1 << 21);
BENCHMARK_MAIN();

// Copyright 2020 The Google Research Authors.
//
// 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 "benchmark/benchmark.h"
#include "benchmark_utils.h"
#include "lossy_count.h"
#include "sketch.h"
#include "utils.h"

static void BM_LossyCountAdd(benchmark::State& state) {
  sketch::LossyCount sketch(/*window_size=*/2000);
  Add(state, &sketch);
}

static void BM_LossyCountFallbackAdd(benchmark::State& state) {
  sketch::LossyCountFallback sketch(/*window_size=*/2000, /*hash_count=*/5,
                                    /*hash_size=*/2048);
  Add(state, &sketch);
}

BENCHMARK(BM_LossyCountAdd)->Range(1 << 12, 1 << 21);
BENCHMARK(BM_LossyCountFallbackAdd)->Range(1 << 12, 1 << 21);
BENCHMARK_MAIN();

Fix broken benchmark of Lossy count.

Fix broken benchmark of Lossy count.

PiperOrigin-RevId: 305310909


// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <hspp/Commons/Utils.hpp>
#include <hspp/Policies/IoPolicy.hpp>

namespace Hearthstonepp
{
IoPolicy::IoPolicy(std::ostream& out, std::istream& in) : m_out(out), m_in(in)
{
    // Do nothing
}

TaskMeta IoPolicy::RequireMulligan(Player& player)
{
    TaskMetaTrait trait(TaskID::MULLIGAN, TaskStatus::MULLIGAN_SUCCESS,
                        player.GetID());

    return TaskMeta(trait, SizedPtr<std::size_t>(3));
}

TaskMeta IoPolicy::RequirePlayCard(Player& player)
{
    (void)player;
    return TaskMeta();
}

TaskMeta IoPolicy::RequireCombat(Player& player)
{
    (void)player;
    return TaskMeta();
}

void IoPolicy::NotifyOverDraw(const TaskMeta& meta)
{
    (void)meta;
}
}  // namespace Hearthstonepp

// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <hspp/Commons/Utils.hpp>
#include <hspp/Policies/IoPolicy.hpp>

namespace Hearthstonepp
{
IoPolicy::IoPolicy(std::ostream& out, std::istream& in) : m_out(out), m_in(in)
{
    // Do nothing
}

TaskMeta IoPolicy::RequireMulligan(Player& player)
{
    TaskMetaTrait trait(TaskID::MULLIGAN, TaskStatus::MULLIGAN_SUCCESS,
                        player.GetID());

    return TaskMeta(trait, SizedPtr<std::size_t>(3));
}

TaskMeta IoPolicy::RequirePlayCard(Player& player)
{
    (void)player;
    return TaskMeta();
}

TaskMeta IoPolicy::RequireCombat(Player& player)
{
    (void)player;
    return TaskMeta();
}

void IoPolicy::NotifyOverDraw(const TaskMeta& meta)
{
    (void)m_in;
    (void)m_out;
    (void)meta;
}
}  // namespace Hearthstonepp

Correct 'unused private field' warning

fix: Correct 'unused private field' warning


/*
 * Copyright (c) 2017 Akil Darjean (adarjean@uh.edu)
 * Distributed under the MIT License.
 * See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT
 */

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

int main(int argc, char const* argv[])
{
    Window window;

    if (argc > 1) {
        std::string filename = argv[1];
        window.create(filename);
    } else {
        window.create();
    }

    return 0;
}

/*
 * Copyright (c) 2017 Akil Darjean (adarjean@uh.edu)
 * Distributed under the MIT License.
 * See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT
 */

#include "window.h"
#include <iostream>
#include <string>

int main(int argc, char const* argv[])
{
    Window window;

    if (argc > 1) {
        std::string filename = argv[1];
        window.create(filename);
    } else {
        std::cout << "SFML Image Viewer (c) 2017" << std::endl;
        std::cout << std::endl;
        std::cout << "Usage: sfiv FILE" << std::endl;
    }

    return 0;
}

Make application open only if file is provided


#include <cstdio>

int main(int argc, char* argv[])
{
    printf("testapp reporting in!\n");

    for (;;) ;
    return 0;
}

#include <cstdio>
#include <unistd.h>

int main(int argc, char* argv[])
{
    printf("testapp reporting in!\n");
    sleep(100000000);
    return 0;
}

Change infinite loop to sleep

Change infinite loop to sleep


#include "clang.h"
#include <memory>
#include <utility>
#pragma warning(push, 0)
#include <clang/Basic/Diagnostic.h>
#include <clang/Basic/DiagnosticIDs.h>
#include <clang/Basic/VirtualFileSystem.h> // Fixes "Member access into incomplete type 'clang::vfs::FileSystem'".
#include <clang/Driver/Compilation.h>
#include <clang/Driver/Driver.h>
#include <clang/Frontend/TextDiagnosticPrinter.h>
#include <llvm/ADT/ArrayRef.h>
#include <llvm/Support/Host.h>
#include <llvm/Support/Path.h>
#include <llvm/Support/raw_ostream.h>
#pragma warning(pop)

int delta::invokeClang(llvm::ArrayRef<const char*> args) {
    auto* diagClient = new clang::TextDiagnosticPrinter(llvm::errs(), nullptr);
    diagClient->setPrefix(llvm::sys::path::filename(args[0]));
    clang::DiagnosticsEngine diags(new clang::DiagnosticIDs(), nullptr, diagClient);
    clang::driver::Driver driver(args[0], llvm::sys::getDefaultTargetTriple(), diags);
    std::unique_ptr<clang::driver::Compilation> compilation(driver.BuildCompilation(args));
    if (compilation) {
        llvm::SmallVector<std::pair<int, const clang::driver::Command*>, 4> failingCommands;
        return driver.ExecuteCompilation(*compilation, failingCommands);
    }
    diags.getClient()->finish();
    return 1;
}

#include "clang.h"
#include <memory>
#include <utility>
#pragma warning(push, 0)
#include <clang/Basic/Diagnostic.h>
#include <clang/Basic/DiagnosticIDs.h>
#include <clang/Basic/VirtualFileSystem.h> // Fixes "Member access into incomplete type 'clang::vfs::FileSystem'".
#include <clang/Driver/Compilation.h>
#include <clang/Driver/Driver.h>
#include <clang/Frontend/TextDiagnosticPrinter.h>
#include <llvm/ADT/ArrayRef.h>
#include <llvm/Support/Host.h>
#include <llvm/Support/Path.h>
#include <llvm/Support/raw_ostream.h>
#pragma warning(pop)

int delta::invokeClang(llvm::ArrayRef<const char*> args) {
    auto* diagClient = new clang::TextDiagnosticPrinter(llvm::errs(), new clang::DiagnosticOptions());
    diagClient->setPrefix(llvm::sys::path::filename(args[0]));
    clang::DiagnosticsEngine diags(new clang::DiagnosticIDs(), nullptr, diagClient);
    clang::driver::Driver driver(args[0], llvm::sys::getDefaultTargetTriple(), diags);
    std::unique_ptr<clang::driver::Compilation> compilation(driver.BuildCompilation(args));
    if (compilation) {
        llvm::SmallVector<std::pair<int, const clang::driver::Command*>, 4> failingCommands;
        return driver.ExecuteCompilation(*compilation, failingCommands);
    }
    diags.getClient()->finish();
    return 1;
}

Fix diagnostics when using Clang compilation API


#include "cell.hpp"

namespace roadagain
{

Cell::Cell() : color(EMPTY)
{
}

Cell::Cell(const Point& point, CellColor color) : point(point), color(color)
{
}

void Cell::reverse()
{
    color_ = reversed(color_);
}

} // namespace roadagain

#include "cell.hpp"

namespace roadagain
{

Cell::Cell() : color(EMPTY)
{
}

Cell::Cell(const Point& point, CellColor color) : point_(point), color_(color)
{
}

void Cell::reverse()
{
    color_ = reversed(color_);
}

} // namespace roadagain

Fix wrong member names in Cell

Fix wrong member names in Cell


#define BOOST_TEST_MODULE VexIO
#include <boost/test/unit_test.hpp>
#include <boost/test/tools/output_test_stream.hpp>
#include <vexcl/vector.hpp>
#include <vexcl/element_index.hpp>
#include "context_setup.hpp"

BOOST_AUTO_TEST_CASE(stream_vector) {
    boost::test_tools::output_test_stream output;

    vex::vector<int> x(ctx, 32);
    x = vex::element_index();

    output << x;

    BOOST_CHECK(output.is_equal(
        "{\n"
        "     0:      0      1      2      3      4      5      6      7      8      9\n"
        "    10:     10     11     12     13     14     15     16     17     18     19\n"
        "    20:     20     21     22     23     24     25     26     27     28     29\n"
        "    30:     30     31\n"
        "}\n"
        ));
}

BOOST_AUTO_TEST_SUITE_END()

#define BOOST_TEST_MODULE VexIO
#include <boost/test/unit_test.hpp>
#if BOOST_VERSION >= 107100
#  include <boost/test/tools/output_test_stream.hpp>
#else
#  include <boost/test/output_test_stream.hpp>
#endif
#include <vexcl/vector.hpp>
#include <vexcl/element_index.hpp>
#include "context_setup.hpp"

BOOST_AUTO_TEST_CASE(stream_vector) {
    boost::test_tools::output_test_stream output;

    vex::vector<int> x(ctx, 32);
    x = vex::element_index();

    output << x;

    BOOST_CHECK(output.is_equal(
        "{\n"
        "     0:      0      1      2      3      4      5      6      7      8      9\n"
        "    10:     10     11     12     13     14     15     16     17     18     19\n"
        "    20:     20     21     22     23     24     25     26     27     28     29\n"
        "    30:     30     31\n"
        "}\n"
        ));
}

BOOST_AUTO_TEST_SUITE_END()

Include correct version of <boost/test/.../output_test_stream.hpp>


#include "fdsb/fabric.hpp"
#include "fdsb/nid.hpp"
#include "fdsb/harc.hpp"

#include <unordered_map>

using namespace fdsb;

std::unordered_multimap<unsigned long long,Harc*> fabric;

Harc &fdsb::get(const Nid &a, const Nid &b)
{
	auto range = fabric.equal_range(Nid::dual_hash(a,b));
	for (auto i : range)
	{
		if ((i->tail(0) == a && i->tail(1) == b) || (i->tail(0) == b && i->tail(1) == a))
		{
			return *i;
		}
	}

	Harc *nh = new Harc(a,b);
	add(*nh);
	return *nh;
}

void fdsb::add(Harc &h)
{
	fabric.insert({{Nid::dual_hash(h.tail(0),h.tail(1)), &h}});
}

void fdsb::add(const Nid &n1, const Nid &n2)
{
	fdsb::add(*(new Harc(n1,n2)));
}

Harc &Nid::operator[](const Nid &n)
{
	return fdsb::get(*this,n);
}

Harc &Harc::operator[](const Nid &n)
{
	return fdsb::get(query(),n);
}

#include "fdsb/fabric.hpp"
#include "fdsb/nid.hpp"
#include "fdsb/harc.hpp"

#include <unordered_map>

using namespace fdsb;

std::unordered_multimap<unsigned long long,Harc*> fabric;

Harc &fdsb::get(const Nid &a, const Nid &b)
{
	auto range = fabric.equal_range(Nid::dual_hash(a,b));
	for (auto i = range.first; i != range.second; i++)
	{
		if (((*i)->tail(0) == a && (*i)->tail(1) == b) || ((*i)->tail(0) == b && (*i)->tail(1) == a))
		{
			return *(*i);
		}
	}

	Harc *nh = new Harc(a,b);
	add(*nh);
	return *nh;
}

void fdsb::add(Harc &h)
{
	fabric.insert({{Nid::dual_hash(h.tail(0),h.tail(1)), &h}});
}

void fdsb::add(const Nid &n1, const Nid &n2)
{
	fdsb::add(*(new Harc(n1,n2)));
}

Harc &Nid::operator[](const Nid &n)
{
	return fdsb::get(*this,n);
}

Harc &Harc::operator[](const Nid &n)
{
	return fdsb::get(query(),n);
}

Fix for map get iteration

Fix for map get iteration


/**
 ** \file libport/string.cc
 ** \brief string: implements file libport/string.hh
 */

#include <boost/lexical_cast.hpp>

#include "libport/cstring"

#include "libport/detect_win32.h"

namespace libport
{

#ifdef WIN32

# define LIBPORT_BUFFER_SIZE  1024
  const char*
  getWinErrorMessage()
  {
    static char msg_buf[LIBPORT_BUFFER_SIZE];

    FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
                   | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), 0,
                   (LPTSTR)msg_buf, LIBPORT_BUFFER_SIZE, NULL);

    return msg_buf;
  }
# undef LIBPORT_BUFFER_SIZE

#endif

  const char*
  strerror(int errnum)
  {
#ifndef WIN32
    return ::strerror(errnum);
#else
    const char* str;

    if (errnum != 0)
      str = ::strerror(errnum);
    else
      str = getWinErrorMessage();

    return str;
#endif
  }

}

/**
 ** \file libport/string.cc
 ** \brief string: implements file libport/string.hh
 */

#include <boost/lexical_cast.hpp>

#include "libport/cstring"

#include "libport/detect_win32.h"

namespace libport
{

#ifdef WIN32

# define LIBPORT_BUFFER_SIZE  1024
  const char*
  getWinErrorMessage()
  {
    static char msg_buf[LIBPORT_BUFFER_SIZE];

    FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
                   0, GetLastError(), 0, (LPTSTR)msg_buf, LIBPORT_BUFFER_SIZE, 0);

    return msg_buf;
  }
# undef LIBPORT_BUFFER_SIZE

#endif

  const char*
  strerror(int errnum)
  {
#ifndef WIN32
    return ::strerror(errnum);
#else
    const char* str;

    if (errnum != 0)
      str = ::strerror(errnum);
    else
      str = getWinErrorMessage();

    return str;
#endif
  }

}

Use static buffer instead of allocation in libport::getWinErrorMessage.

    lib/libport/string.cc: Here.


/**********************************************************************
 *
 * GEOS - Geometry Engine Open Source
 * http://geos.osgeo.org
 *
 * Copyright (C) 2008 Sean Gillies
 *
 * This is free software; you can redistribute and/or modify it under
 * the terms of the GNU Lesser General Public Licence as published
 * by the Free Software Foundation.
 * See the COPYING file for more information.
 *
 **********************************************************************
 *
 * Last port: ORIGINAL WORK
 *
 **********************************************************************/

#include <geos/io/CLocalizer.h>

#include <string>
#include <clocale>

using namespace std;

namespace geos {
namespace io {

CLocalizer::CLocalizer()
{
    char* p = std::setlocale(LC_NUMERIC, NULL);
    if (0 != p)
    {
        saved_locale = p;
    }
    std::setlocale(LC_NUMERIC, "C");
}

CLocalizer::~CLocalizer()
{
    std::setlocale(LC_NUMERIC, saved_locale.c_str());
}

} // namespace geos.io
} // namespace geos

/**********************************************************************
 *
 * GEOS - Geometry Engine Open Source
 * http://geos.osgeo.org
 *
 * Copyright (C) 2008 Sean Gillies
 *
 * This is free software; you can redistribute and/or modify it under
 * the terms of the GNU Lesser General Public Licence as published
 * by the Free Software Foundation.
 * See the COPYING file for more information.
 *
 **********************************************************************
 *
 * Last port: ORIGINAL WORK
 *
 **********************************************************************/

#include <geos/io/CLocalizer.h>

#include <string>
#include <clocale>

using namespace std;

namespace geos {
namespace io {

CLocalizer::CLocalizer()
{
#ifdef _MSC_VER
    // Avoid multithreading issues caused by setlocale
    _configthreadlocale(_ENABLE_PER_THREAD_LOCALE);
#endif
    char* p = std::setlocale(LC_NUMERIC, NULL);
    if (0 != p)
    {
        saved_locale = p;
    }
    std::setlocale(LC_NUMERIC, "C");
}

CLocalizer::~CLocalizer()
{
    std::setlocale(LC_NUMERIC, saved_locale.c_str());
}

} // namespace geos.io
} // namespace geos

Fix multithreading issue for MSVC caused by setlocale


// Copyright 2017 Google 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.
//
///////////////////////////////////////////////////////////////////////////////

#ifndef _GNU_SOURCE
#define _GNU_SOURCE  // needed for vasprintf(3)
#endif

#include "tink/util/errors.h"

#include <stdarg.h>
#include <stdlib.h>

#include "tink/util/status.h"

using crypto::tink::util::error::Code;
using crypto::tink::util::Status;

namespace crypto {
namespace tink {

// Construct a Status object given a printf-style va list.
Status ToStatusF(Code code, const char* format, ...) {
  va_list ap;
  va_start(ap, format);
  char* p;
  vasprintf(&p, format, ap);
  va_end(ap);
  Status status(code, p);
  free(p);
  return status;
}

}  // namespace tink
}  // namespace crypto

// Copyright 2017 Google 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.
//
///////////////////////////////////////////////////////////////////////////////

#ifndef _GNU_SOURCE
#define _GNU_SOURCE  // needed for vasprintf(3)
#endif

#include "tink/util/errors.h"

#include <stdarg.h>
#include <stdlib.h>

#include "tink/util/status.h"

using crypto::tink::util::error::Code;
using crypto::tink::util::Status;

namespace crypto {
namespace tink {

// Construct a Status object given a printf-style va list.
Status ToStatusF(Code code, const char* format, ...) {
  va_list ap;
  va_start(ap, format);
  char* p;
  if (vasprintf(&p, format, ap) < 0) {
    abort();
  }
  va_end(ap);
  Status status(code, p);
  free(p);
  return status;
}

}  // namespace tink
}  // namespace crypto

Make the program crash if vasprintf cannot allocate memory.

PiperOrigin-RevId: 260727250


#include "output.h"

Output output;

float a = 123.0;
int b = 79;
unsigned int c = 24;

int main()
{
	float d = b;
	float e = c;

	output << (int) a;			// CHECK: 0x0000007b
	output << (unsigned int) a;	// CHECK: 0x0000007b
	output << (int) d;			// CHECK: 0x0000004f
}

#include "output.h"

Output output;

float a = 123.0;
int b = 79;
unsigned int c = 24;

int main()
{
	float d = b;
	float e = c;

	output << (int) a;			// CHECK: 0x0000007b
	output << (unsigned int) a;	// CHECK: 0x0000007b
	output << (int) d;			// CHECK: 0x0000004f
//	output << (int) e;			// XXX should be 0x18, but is 0x17 for some reason
}

Add a (commented out) incorrect conversion


// Copyright © 2017 Dmitriy Khaustov
//
// 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.
//
// Author: Dmitriy Khaustov aka xDimon
// Contacts: khaustov.dm@gmail.com
// File created on: 2017.05.21

// ShutdownManager.cpp

#include "ShutdownManager.hpp"
#include "../thread/ThreadPool.hpp"

void ShutdownManager::doAtShutdown(std::function<void()> handler)
{
	std::lock_guard<std::mutex> lockGuard(getInstance()._mutex);

	getInstance()._handlers.emplace_front(std::move(handler));
}

void ShutdownManager::shutdown()
{
	std::lock_guard<std::mutex> lockGuard(getInstance()._mutex);

//	ThreadPool::hold();

	getInstance()._shutingdown = true;

	for (auto handler : getInstance()._handlers)
	{
		handler();
	}

//	ThreadPool::unhold();

}

// Copyright © 2017 Dmitriy Khaustov
//
// 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.
//
// Author: Dmitriy Khaustov aka xDimon
// Contacts: khaustov.dm@gmail.com
// File created on: 2017.05.21

// ShutdownManager.cpp

#include "ShutdownManager.hpp"
#include "../thread/ThreadPool.hpp"

void ShutdownManager::doAtShutdown(std::function<void()> handler)
{
	std::lock_guard<std::mutex> lockGuard(getInstance()._mutex);

	getInstance()._handlers.emplace_front(std::move(handler));
}

void ShutdownManager::shutdown()
{
	std::lock_guard<std::mutex> lockGuard(getInstance()._mutex);

//	ThreadPool::hold();

	getInstance()._shutingdown = true;

	for (auto handler : getInstance()._handlers)
	{
		handler();
	}

	getInstance()._handlers.clear();

//	ThreadPool::unhold();
}

Add clean handlers at shuttingdown

Add clean handlers at shuttingdown


#include "validate_timing_graph_constraints.hpp"
#include "TimingGraph.hpp"
#include "TimingConstraints.hpp"

#include "tatum_error.hpp"
#include "loop_detect.hpp"

namespace tatum {

bool validate_timing_graph_constraints(const TimingGraph& /*timing_graph*/, const TimingConstraints& /*timing_constraints*/) {

    //Nothing here for now
    return true;
}

} //namespace

#include "validate_timing_graph_constraints.hpp"
#include "TimingGraph.hpp"
#include "TimingConstraints.hpp"

#include "tatum_error.hpp"
#include "loop_detect.hpp"

namespace tatum {

bool validate_timing_graph_constraints(const TimingGraph& timing_graph, const TimingConstraints& timing_constraints) {

    //Check that all clocks are defined as sources
    for(DomainId domain : timing_constraints.clock_domains()) {
        NodeId source_node = timing_constraints.clock_domain_source_node(domain);

        if(timing_graph.node_type(source_node) != NodeType::SOURCE) {
            std::string msg;

            msg = "Clock Domain " + std::to_string(size_t(domain)) + " (" + timing_constraints.clock_domain_name(domain) + ")"
                  " source node " + std::to_string(size_t(source_node)) + " is not a node of type SOURCE.";

            throw tatum::Error(msg);
        }
    }

    //Nothing here for now
    return true;
}

} //namespace

Verify that clock domain sources are nodes of expected SOURCE type


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

// This is a simple allocator based on the windows heap.

extern "C" {

HANDLE win_heap;

bool win_heap_init(bool use_lfh) {
  win_heap = HeapCreate(0, 0, 0);
  if (win_heap == NULL)
    return false;

  if (use_lfh) {
    ULONG enable_lfh = 2;
    HeapSetInformation(win_heap, HeapCompatibilityInformation,
                       &enable_lfh, sizeof(enable_lfh));
    // NOTE: Setting LFH may fail.  Vista already has it enabled.
    //       And under the debugger, it won't use LFH.  So we
    //       ignore any errors.
  }

  return true;
}

void* win_heap_malloc(size_t s) {
  return HeapAlloc(win_heap, 0, s);
}

void* win_heap_realloc(void* p, size_t s) {
  if (!p)
    return win_heap_malloc(s);
  return HeapReAlloc(win_heap, 0, p, s);
}

void win_heap_free(void* s) {
  HeapFree(win_heap, 0, s);
}

size_t win_heap_msize(void* p) {
  return HeapSize(win_heap, 0, p);
}

}  // extern "C"

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

// This is a simple allocator based on the windows heap.

extern "C" {

HANDLE win_heap;

bool win_heap_init(bool use_lfh) {
  win_heap = HeapCreate(0, 0, 0);
  if (win_heap == NULL)
    return false;

  if (use_lfh) {
    ULONG enable_lfh = 2;
    HeapSetInformation(win_heap, HeapCompatibilityInformation,
                       &enable_lfh, sizeof(enable_lfh));
    // NOTE: Setting LFH may fail.  Vista already has it enabled.
    //       And under the debugger, it won't use LFH.  So we
    //       ignore any errors.
  }

  return true;
}

void* win_heap_malloc(size_t size) {
  return HeapAlloc(win_heap, 0, size);
}

void win_heap_free(void* size) {
  HeapFree(win_heap, 0, size);
}

void* win_heap_realloc(void* ptr, size_t size) {
  if (!ptr)
    return win_heap_malloc(size);
  if (!size) {
    win_heap_free(ptr);
    return NULL;
  }
  return HeapReAlloc(win_heap, 0, ptr, size);
}

size_t win_heap_msize(void* ptr) {
  return HeapSize(win_heap, 0, ptr);
}

}  // extern "C"

Fix the windows allocator to behave properly on realloc.

The spec says that calling realloc(ptr, 0) should free ptr
and return NULL.

BUG=none
TEST=none

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

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


//===--- Phases.cpp - Transformations on Driver Types -------------------*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "clang/Driver/Phases.h"

#include <cassert>

using namespace clang::driver;

const char *phases::getPhaseName(ID Id) {
  switch (Id) {
  case Preprocess: return "preprocess";
  case Precompile: return "precompile";
  case Compile: return "compile";
  case Assemble: return "assemble";
  case Link: return "link";
  }

  assert(0 && "Invalid phase id.");
  return 0;
}

//===--- Phases.cpp - Transformations on Driver Types -------------------*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "clang/Driver/Phases.h"

#include <cassert>

using namespace clang::driver;

const char *phases::getPhaseName(ID Id) {
  switch (Id) {
  case Preprocess: return "preprocesser";
  case Precompile: return "precompiler";
  case Compile: return "compiler";
  case Assemble: return "assembler";
  case Link: return "linker";
  }

  assert(0 && "Invalid phase id.");
  return 0;
}

Make phase names nouns not verbs.

Driver: Make phase names nouns not verbs.

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


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

#include "Application.h"

void ouzelMain(const std::vector<std::string>& args)
{
    OUZEL_UNUSED(args);

    ouzel::Settings settings;
    settings.driver = ouzel::video::Renderer::Driver::METAL;
    settings.size = ouzel::Size2(800.0f, 600.0f);
    settings.resizable = true;
    ouzel::sharedEngine->init(settings);

    std::shared_ptr<Application> application = std::make_shared<Application>();
    ouzel::sharedEngine->setApp(application);
}

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

#include "Application.h"

void ouzelMain(const std::vector<std::string>& args)
{
    OUZEL_UNUSED(args);

    ouzel::Settings settings;
    //settings.driver = ouzel::video::Renderer::Driver::METAL;
    settings.size = ouzel::Size2(800.0f, 600.0f);
    settings.resizable = true;
    ouzel::sharedEngine->init(settings);

    std::shared_ptr<Application> application = std::make_shared<Application>();
    ouzel::sharedEngine->setApp(application);
}

Disable Metal renderer for sample project


// gtest macros raise -Wsign-compare
#pragma GCC diagnostic ignored "-Wsign-compare"

#include <string>

#include "gtest/gtest.h"

#include "libparse/driver.h"
#include "libparse/parser.tab.h"

extern casmi_driver *global_driver;

class ParserTest: public ::testing::Test {
  protected:
    virtual void SetUp() { global_driver = &driver_; }

    casmi_string_driver driver_;
};

TEST_F(ParserTest, parse_simple) {
  std::string test = "init main\n"
                     "rule main = {\n"
                     "    x := 1 - 2\n"
                     "}\n";
  AstNode *root = driver_.parse(test);

  AstListNode *stmts = new AstListNode(NodeType::STATEMENTS);
  stmts->add(new UpdateNode(
        new Expression(
            new Expression(nullptr, create_atom(1)),
            create_atom(2))
  ));

  AstListNode *ast = new AstListNode(NodeType::BODY_ELEMENTS);
  ast->add(new AstNode(NodeType::INIT));
  ast->add(new UnaryNode(NodeType::RULE, new UnaryNode(NodeType::PARBLOCK, stmts)));
  EXPECT_EQ(true, root->equals(ast));

  delete ast;
  delete root;
}

TEST_F(ParserTest, parse_error) {
  std::string test = "init\n";
  EXPECT_EQ(nullptr, driver_.parse(test));
}

// gtest macros raise -Wsign-compare
#pragma GCC diagnostic ignored "-Wsign-compare"

#include <string>

#include "gtest/gtest.h"

#include "libparse/driver.h"
#include "libparse/parser.tab.h"

extern casmi_driver *global_driver;

class ParserTest: public ::testing::Test {
  protected:
    virtual void SetUp() { global_driver = &driver_; }

    casmi_string_driver driver_;
};

TEST_F(ParserTest, parse_simple) {
  std::string test = "init main\n"
                     "rule main = {\n"
                     "    x := 1 - 2\n"
                     "    y := 5 - 10\n"
                     "}\n";
  AstNode *root = driver_.parse(test);

  AstListNode *stmts = new AstListNode(NodeType::STATEMENTS);
  stmts->add(new UpdateNode(
        new Expression(
            new Expression(nullptr, create_atom(1)),
            create_atom(2))
  ));
  stmts->add(new UpdateNode(
        new Expression(
            new Expression(nullptr, create_atom(5)),
            create_atom(10))
  ));

  AstListNode *ast = new AstListNode(NodeType::BODY_ELEMENTS);
  ast->add(new AstNode(NodeType::INIT));
  ast->add(new UnaryNode(NodeType::RULE, new UnaryNode(NodeType::PARBLOCK, stmts)));
  EXPECT_EQ(true, root->equals(ast));

  delete ast;
  delete root;
}

TEST_F(ParserTest, parse_error) {
  std::string test = "init\n";
  EXPECT_EQ(nullptr, driver_.parse(test));
}

Make parser unit test slightly more complex


#include "Genes/Priority_Threshold_Gene.h"

#include <memory>
#include <string>
#include <algorithm>

#include "Utility.h"

class Board;

Priority_Threshold_Gene::Priority_Threshold_Gene() : threshold(0.0)
{
}

void Priority_Threshold_Gene::reset_properties() const
{
    properties["Threshold"] = threshold;
}

void Priority_Threshold_Gene::load_properties()
{
    threshold = properties["Threshold"];
}

std::unique_ptr<Gene> Priority_Threshold_Gene::duplicate() const
{
    return std::make_unique<Priority_Threshold_Gene>(*this);
}

std::string Priority_Threshold_Gene::name() const
{
    return "Priority Threshold Gene";
}

double Priority_Threshold_Gene::score_board(const Board&) const
{
    return 0.0;
}

double Priority_Threshold_Gene::get_threshold() const
{
    return threshold;
}

void Priority_Threshold_Gene::gene_specific_mutation()
{
    threshold = std::max(0.0, threshold + Random::random_normal(1.0));
}

#include "Genes/Priority_Threshold_Gene.h"

#include <memory>
#include <string>
#include <algorithm>

#include "Utility.h"

class Board;

Priority_Threshold_Gene::Priority_Threshold_Gene() : threshold(0.0)
{
}

void Priority_Threshold_Gene::reset_properties() const
{
    properties["Threshold"] = threshold;
}

void Priority_Threshold_Gene::load_properties()
{
    threshold = properties["Threshold"];
}

std::unique_ptr<Gene> Priority_Threshold_Gene::duplicate() const
{
    return std::make_unique<Priority_Threshold_Gene>(*this);
}

std::string Priority_Threshold_Gene::name() const
{
    return "Priority Threshold Gene";
}

double Priority_Threshold_Gene::score_board(const Board&) const
{
    return 0.0;
}

double Priority_Threshold_Gene::get_threshold() const
{
    return threshold;
}

void Priority_Threshold_Gene::gene_specific_mutation()
{
    threshold = std::max(0.0, threshold + Random::random_normal(2.0));
}

Increase mutation size of Priority Threshold Gene


//===-- RegularExpression.cpp -----------------------------------*- C++ -*-===//
//
// 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 "lldb/Utility/RegularExpression.h"

#include <string>

using namespace lldb_private;

RegularExpression::RegularExpression(llvm::StringRef str)
    : m_regex_text(str),
      // m_regex does not reference str anymore after it is constructed.
      m_regex(llvm::Regex(str)) {}

RegularExpression::RegularExpression(const RegularExpression &rhs)
    : RegularExpression(rhs.GetText()) {}

bool RegularExpression::Execute(
    llvm::StringRef str,
    llvm::SmallVectorImpl<llvm::StringRef> *matches) const {
  if (!IsValid())
    return false;
  return m_regex.match(str, matches);
}

bool RegularExpression::IsValid() const {
  std::string discarded;
  return m_regex.isValid(discarded);
}

llvm::StringRef RegularExpression::GetText() const { return m_regex_text; }

llvm::Error RegularExpression::GetError() const {
  std::string error;
  if (!m_regex.isValid(error))
    return llvm::make_error<llvm::StringError>(llvm::inconvertibleErrorCode(),
                                               error);
  return llvm::Error::success();
}

//===-- RegularExpression.cpp -----------------------------------*- C++ -*-===//
//
// 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 "lldb/Utility/RegularExpression.h"

#include <string>

using namespace lldb_private;

RegularExpression::RegularExpression(llvm::StringRef str)
    : m_regex_text(str),
      // m_regex does not reference str anymore after it is constructed.
      m_regex(llvm::Regex(str)) {}

RegularExpression::RegularExpression(const RegularExpression &rhs)
    : RegularExpression(rhs.GetText()) {}

bool RegularExpression::Execute(
    llvm::StringRef str,
    llvm::SmallVectorImpl<llvm::StringRef> *matches) const {
  if (!IsValid())
    return false;
  return m_regex.match(str, matches);
}

bool RegularExpression::IsValid() const { return m_regex.isValid(); }

llvm::StringRef RegularExpression::GetText() const { return m_regex_text; }

llvm::Error RegularExpression::GetError() const {
  std::string error;
  if (!m_regex.isValid(error))
    return llvm::make_error<llvm::StringError>(llvm::inconvertibleErrorCode(),
                                               error);
  return llvm::Error::success();
}

[lldb] Use the new Regex::isValid() with no parameter

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

git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@369398 91177308-0d34-0410-b5e6-96231b3b80d8


#include <gtest/gtest.h>

#include <fixedcube.hh>
#include <side.hh>

using namespace Rubik;

class FixedCubeTests : public testing::Test
{
private:
  static int n;

public:
  int generateInteger()
  {
    return n++;
  }

  Side::Data generateSideData()
  {
    Side::Data result;
    for(unsigned int i=0; i<result.size(); i++)
      result[i] = generateInteger();

    return result;
  }
};

int FixedCubeTests::n = 0;

TEST_F(FixedCubeTests, Initialize)
{
  CubeData data =
    top(generateSideData()).
    left(generateSideData()).
    front(generateSideData()).
    right(generateSideData()).
    bottom(generateSideData()).
    back(generateSideData());

  FixedCube::Ptr cube = FixedCube::create(data);

  EXPECT_EQ(data, cube->data());
}

#include <gtest/gtest.h>

#include <fixedcube.hh>
#include <side.hh>

using namespace Rubik;

class FixedCubeTests : public testing::Test
{
private:
  static int n;

public:
  CubeData data;

public:
  FixedCubeTests()
    : data(top(generateSideData()).
           left(generateSideData()).
           front(generateSideData()).
           right(generateSideData()).
           bottom(generateSideData()).
           back(generateSideData()))
  {
  }

  ~FixedCubeTests()
  {
    // Keep square values relatively small
    n=0;
  }

  int generateInteger()
  {
    return n++;
  }

  Side::Data generateSideData()
  {
    Side::Data result;
    for(unsigned int i=0; i<result.size(); i++)
      result[i] = generateInteger();

    return result;
  }
};

int FixedCubeTests::n = 0;

TEST_F(FixedCubeTests, Initialize)
{
  FixedCube::Ptr cube = FixedCube::create(data);

  EXPECT_EQ(data, cube->data());
}

TEST_F(FixedCubeTests, InitializeWithFactory)
{
  FixedCube::Ptr cube = FixedCube::create(data);

  EXPECT_EQ(data, cube->data());
}

Duplicate FixedCube test, move initializing cube data to fixture


// RUN: %clangxx -O0 %s -o %t
// RUN: %env_tool_opts=strip_path_prefix=/TestCases/ %run %t 2>&1 | FileCheck %s
// UNSUPPORTED: i386-apple
//
// Tests __sanitizer_symbolize_pc.
#include <stdio.h>
#include <sanitizer/common_interface_defs.h>
void SymbolizeCaller() {
  char data[1000];
  __sanitizer_symbolize_pc(__builtin_return_address(0), "%p %F %L", data,
                           sizeof(data));
  printf("FIRST_FORMAT %s\n", data);
  __sanitizer_symbolize_pc(__builtin_return_address(0),
                           "FUNC:%f LINE:%l FILE:%s", data, sizeof(data));
  printf("SECOND_FORMAT %s\n", data);
}

// CHECK: FIRST_FORMAT 0x{{.*}} in main symbolize_pc.cc:[[@LINE+3]]
// CHECK: SECOND_FORMAT FUNC:main LINE:[[@LINE+2]] FILE:symbolize_pc.cc
int main() {
  SymbolizeCaller();
}

// RUN: %clangxx -O0 %s -o %t
// RUN: %env_tool_opts=strip_path_prefix=/TestCases/ %run %t 2>&1 | FileCheck %s
// REQUIRES: x86_64-target-arch
//
// Tests __sanitizer_symbolize_pc.
#include <stdio.h>
#include <sanitizer/common_interface_defs.h>
void SymbolizeCaller() {
  char data[1000];
  __sanitizer_symbolize_pc(__builtin_return_address(0), "%p %F %L", data,
                           sizeof(data));
  printf("FIRST_FORMAT %s\n", data);
  __sanitizer_symbolize_pc(__builtin_return_address(0),
                           "FUNC:%f LINE:%l FILE:%s", data, sizeof(data));
  printf("SECOND_FORMAT %s\n", data);
}

// CHECK: FIRST_FORMAT 0x{{.*}} in main symbolize_pc.cc:[[@LINE+3]]
// CHECK: SECOND_FORMAT FUNC:main LINE:[[@LINE+2]] FILE:symbolize_pc.cc
int main() {
  SymbolizeCaller();
}

[asan] Use "REQUIRES: x86_64-target-arch" to disable the test on i386.

My attempt to disable this test on i386 by adding "UNSUPPORTED: i386-apple"
in r279880 wasn't succesful, so I'm using REQUIRES instead.

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


// RUN: %llvmgxx %s -S -emit-llvm -O2 -o - | grep _Unwind_Resume | wc -l | grep {\[03\]}

struct One { };
struct Two { };

void handle_unexpected () {
  try
  {
    throw;
  }
  catch (One &)
  {
    throw Two ();
  }
}

// RUN: %llvmgxx %s -S -emit-llvm -O2 -o - | grep -c {handle\\|_Unwind_Resume} | grep {\[14\]}

struct One { };
struct Two { };

void handle_unexpected () {
  try
  {
    throw;
  }
  catch (One &)
  {
    throw Two ();
  }
}

Make this test pass if llvm-g++ was built without exception handling support.

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