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

struct Foo {
  unsigned file_id;

  Foo(unsigned arg);
};

Foo::Foo(unsigned arg) : file_id(arg = 42)
{ }

// RUN: %clang_cc1 %s -emit-llvm -o - | FileCheck %s
// PR7291

struct Foo {
  unsigned file_id;

  Foo(unsigned arg);
};

Foo::Foo(unsigned arg) : file_id(arg = 42)
{ }

// CHECK: define void @_ZN3FooC2Ej
// CHECK: [[ARG:%.*]] = alloca i32
// CHECK: store i32 42, i32* [[ARG]]
// CHECK: [[ARGVAL:%.*]] = load i32* [[ARG]]
// CHECK: store i32 [[ARGVAL]], i32* %{{.*}}
// CHECK: ret void

Check the output of this test.

Check the output of this test.

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


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

// <random>

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

// template <class charT, class traits>
// basic_ostream<charT, traits>&
// operator<<(basic_ostream<charT, traits>& os,
//            const piecewise_linear_distribution& x);
//
// template <class charT, class traits>
// basic_istream<charT, traits>&
// operator>>(basic_istream<charT, traits>& is,
//            piecewise_linear_distribution& x);

#include <random>
#include <sstream>
#include <cassert>

int main()
{
    {
        typedef std::piecewise_linear_distribution<> D;
        double b[] = {10, 14, 16, 17};
        double p[] = {25, 62.5, 12.5, 25};
        const size_t Np = sizeof(p) / sizeof(p[0]);
        D d1(b, b+Np+1, p);
        std::ostringstream os;
        os << d1;
        std::istringstream is(os.str());
        D d2;
        is >> d2;
        assert(d1 == d2);
    }
}

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

// <random>

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

// template <class charT, class traits>
// basic_ostream<charT, traits>&
// operator<<(basic_ostream<charT, traits>& os,
//            const piecewise_linear_distribution& x);
//
// template <class charT, class traits>
// basic_istream<charT, traits>&
// operator>>(basic_istream<charT, traits>& is,
//            piecewise_linear_distribution& x);

#include <random>
#include <sstream>
#include <cassert>

int main()
{
    {
        typedef std::piecewise_linear_distribution<> D;
        double b[] = {10, 14, 16, 17};
        double p[] = {25, 62.5, 12.5, 25};
        const size_t Np = sizeof(p) / sizeof(p[0]);
        D d1(b, b+Np, p);
        std::ostringstream os;
        os << d1;
        std::istringstream is(os.str());
        D d2;
        is >> d2;
        assert(d1 == d2);
    }
}

Fix bug in test; found by AddressSanitizer

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


/******************************************************************************
 ** Filename:    mfdefs.cpp
 ** Purpose:     Basic routines for manipulating micro-features
 ** Author:      Dan Johnson
 **
 ** (c) Copyright Hewlett-Packard Company, 1988.
 ** 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 "mfdefs.h"

#include <cmath>

namespace tesseract {

/*----------------------------------------------------------------------------
              Public Code
----------------------------------------------------------------------------**/

/**
 * This routine allocates and returns a new micro-feature
 * data structure.
 * @return New MICROFEATURE
 */
MICROFEATURE NewMicroFeature() {
  return (static_cast<MICROFEATURE>(malloc(sizeof(MFBLOCK))));
} /* NewMicroFeature */

/**
 * This routine deallocates all of the memory consumed by
 * a list of micro-features.
 * @param MicroFeatures list of micro-features to be freed
 */
void FreeMicroFeatures(MICROFEATURES MicroFeatures) {
  destroy_nodes(MicroFeatures, free);
} /* FreeMicroFeatures */

} // namespace tesseract

/******************************************************************************
 ** Filename:    mfdefs.cpp
 ** Purpose:     Basic routines for manipulating micro-features
 ** Author:      Dan Johnson
 **
 ** (c) Copyright Hewlett-Packard Company, 1988.
 ** 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 "mfdefs.h"

#include <cmath>

namespace tesseract {

/*----------------------------------------------------------------------------
              Public Code
----------------------------------------------------------------------------**/

/**
 * This routine allocates and returns a new micro-feature
 * data structure.
 * @return New MICROFEATURE
 */
MICROFEATURE NewMicroFeature() {
  return new MFBLOCK;
} /* NewMicroFeature */

/**
 * This routine deallocates all of the memory consumed by
 * a list of micro-features.
 * @param MicroFeatures list of micro-features to be freed
 */
void FreeMicroFeatures(MICROFEATURES MicroFeatures) {
  auto list = MicroFeatures;
  while (list != NIL_LIST) {
    delete first_node(list);
    list = pop(list);
  }
} /* FreeMicroFeatures */

} // namespace tesseract

Replace malloc / free by new / delete for MICROFEATURE

Signed-off-by: Stefan Weil <8d4c780fcfdc41841e5070f4c43da8958ba6aec0@weilnetz.de>


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

#include "chrome/browser/chromeos/legacy_window_manager/initial_browser_window_observer.h"

#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "chrome/common/chrome_notification_types.h"
#include "content/public/browser/notification_service.h"

namespace {

// Taken from the --initial_chrome_window_mapped_file flag in the chromeos-wm
// command line: http://goo.gl/uLwIL
const char kInitialWindowFile[] =
    "/var/run/state/windowmanager/initial-chrome-window-mapped";

}  // namespace

namespace chromeos {

InitialBrowserWindowObserver::InitialBrowserWindowObserver() {
  registrar_.Add(this,
                 chrome::NOTIFICATION_BROWSER_WINDOW_READY,
                 content::NotificationService::AllSources());
}

void InitialBrowserWindowObserver::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  registrar_.RemoveAll();
  file_util::WriteFile(FilePath(kInitialWindowFile), "", 0);
}

}  // namespace chromeos

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

#include "chrome/browser/chromeos/legacy_window_manager/initial_browser_window_observer.h"

#include "base/bind.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "chrome/common/chrome_notification_types.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_service.h"

namespace {

// Taken from the --initial_chrome_window_mapped_file flag in the chromeos-wm
// command line: http://goo.gl/uLwIL
const char kInitialWindowFile[] =
    "/var/run/state/windowmanager/initial-chrome-window-mapped";

void WriteInitialWindowFile() {
  if (file_util::WriteFile(FilePath(kInitialWindowFile), "", 0) == -1)
    LOG(ERROR) << "Failed to touch " << kInitialWindowFile;
}

}  // namespace

namespace chromeos {

InitialBrowserWindowObserver::InitialBrowserWindowObserver() {
  registrar_.Add(this,
                 chrome::NOTIFICATION_BROWSER_WINDOW_READY,
                 content::NotificationService::AllSources());
}

void InitialBrowserWindowObserver::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  registrar_.RemoveAll();
  content::BrowserThread::PostTask(
      content::BrowserThread::IO, FROM_HERE,
      base::Bind(&WriteInitialWindowFile));
}

}  // namespace chromeos

aura: Write initial browser window file from IO thread.

I was carelessly doing this from the UI thread before. :-(

BUG=107938
TEST=none

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

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


#include "qtfirebaseanalytics.h"
#include "qtfirebaseremoteconfig.h"
#include "qtfirebaseadmob.h"
#include "qtfirebaseauth.h"
#include "qtfirebasedatabase.h"

#ifdef QTFIREBASE_BUILD_ANALYTICS
QtFirebaseAnalytics* QtFirebaseAnalytics::self = nullptr;
#endif

#ifdef QTFIREBASE_BUILD_REMOTE_CONFIG
QtFirebaseRemoteConfig* QtFirebaseRemoteConfig::self = nullptr;
#endif

#ifdef QTFIREBASE_BUILD_ADMOB
QtFirebaseAdMob *QtFirebaseAdMob::self = nullptr;
#endif

#ifdef QTFIREBASE_BUILD_AUTH
QtFirebaseAuth *QtFirebaseAuth::self = nullptr;
#endif

#ifdef QTFIREBASE_BUILD_DATABASE
QtFirebaseDatabase *QtFirebaseDatabase::self = nullptr;
#endif

#include "qtfirebaseanalytics.h"
#include "qtfirebaseremoteconfig.h"
#include "qtfirebaseadmob.h"
#include "qtfirebaseauth.h"
#include "qtfirebasedatabase.h"
#include "qtfirebasemessaging.h"

#ifdef QTFIREBASE_BUILD_ANALYTICS
QtFirebaseAnalytics* QtFirebaseAnalytics::self = nullptr;
#endif

#ifdef QTFIREBASE_BUILD_REMOTE_CONFIG
QtFirebaseRemoteConfig* QtFirebaseRemoteConfig::self = nullptr;
#endif

#ifdef QTFIREBASE_BUILD_ADMOB
QtFirebaseAdMob *QtFirebaseAdMob::self = nullptr;
#endif

#ifdef QTFIREBASE_BUILD_AUTH
QtFirebaseAuth *QtFirebaseAuth::self = nullptr;
#endif

#ifdef QTFIREBASE_BUILD_DATABASE
QtFirebaseDatabase *QtFirebaseDatabase::self = nullptr;
#endif

#ifdef QTFIREBASE_BUILD_MESSAGING
QtFirebaseMessaging *QtFirebaseMessaging::self = nullptr;
#endif

Fix build with stub implementation

Fix build with stub implementation


/*
 * File:   NetworkThread.cpp
 * Author: matthieu
 *
 * Created on 6 février 2015, 11:40
 */

#include "NetworkThread.h"
#include "RecalboxSystem.h"
#include "guis/GuiMsgBox.h"

NetworkThread::NetworkThread(Window* window) : mWindow(window){

    // creer le thread
    mFirstRun = true;
    mRunning = true;
    mThreadHandle = new boost::thread(boost::bind(&NetworkThread::run, this));

}

NetworkThread::~NetworkThread() {
    	mThreadHandle->join();
}

void NetworkThread::run(){
    while(mRunning){
        if(mFirstRun){
            boost::this_thread::sleep(boost::posix_time::seconds(15));
            mFirstRun = false;
        }else {
            boost::this_thread::sleep(boost::posix_time::hours(1));
        }

        if(RecalboxSystem::getInstance()->canUpdate()){
            if(RecalboxSystem::getInstance()->canUpdate()){
                mWindow->displayMessage("AN UPDATE IS AVAILABLE FOR YOUR RECALBOX");
                mRunning = false;
            }
        }
    }
}

/*
 * File:   NetworkThread.cpp
 * Author: matthieu
 *
 * Created on 6 février 2015, 11:40
 */

#include "NetworkThread.h"
#include "RecalboxSystem.h"
#include "guis/GuiMsgBox.h"

NetworkThread::NetworkThread(Window* window) : mWindow(window){

    // creer le thread
    mFirstRun = true;
    mRunning = true;
    mThreadHandle = new boost::thread(boost::bind(&NetworkThread::run, this));

}

NetworkThread::~NetworkThread() {
    	mThreadHandle->join();
}

void NetworkThread::run(){
    while(mRunning){
        if(mFirstRun){
            boost::this_thread::sleep(boost::posix_time::seconds(15));
            mFirstRun = false;
        }else {
            boost::this_thread::sleep(boost::posix_time::hours(1));
        }

	if(RecalboxConf::getInstance()->get("updates.enabled") == "1") {
	  if(RecalboxSystem::getInstance()->canUpdate()){
	    mWindow->displayMessage("AN UPDATE IS AVAILABLE FOR YOUR RECALBOX");
	    mRunning = false;
	  }
	}
    }
}

Update : make the updates.enabled switch usefull

Signed-off-by: Nicolas Adenis-Lamarre <dc6fdc1a9744a7ef1c7adc041d3cf105890663bc@gmail.com>


/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */

#include "config.h"
#include "tapthrottle.hh"

const size_t MINIMUM_SPACE(1024 * 1024);
const size_t MAXIMUM_QUEUE(100000);

bool TapThrottle::persistenceQueueSmallEnough() const {
    size_t queueSize = stats.queue_size.get() + stats.flusher_todo.get();
    return queueSize < MAXIMUM_QUEUE;
}

bool TapThrottle::hasSomeMemory() const {
    size_t currentSize = stats.currentSize.get() + stats.memOverhead.get();
    size_t maxSize = stats.maxDataSize.get();

    return currentSize < maxSize && (maxSize - currentSize) > MINIMUM_SPACE;
}

bool TapThrottle::shouldProcess() const {
    return persistenceQueueSmallEnough() && hasSomeMemory();
}

/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */

#include "config.h"
#include "tapthrottle.hh"

const size_t MINIMUM_SPACE(1024 * 1024);
const size_t MAXIMUM_QUEUE(500000);

bool TapThrottle::persistenceQueueSmallEnough() const {
    size_t queueSize = stats.queue_size.get() + stats.flusher_todo.get();
    return queueSize < MAXIMUM_QUEUE;
}

bool TapThrottle::hasSomeMemory() const {
    size_t currentSize = stats.currentSize.get() + stats.memOverhead.get();
    size_t maxSize = stats.maxDataSize.get();

    return currentSize < maxSize && (maxSize - currentSize) > MINIMUM_SPACE;
}

bool TapThrottle::shouldProcess() const {
    return persistenceQueueSmallEnough() && hasSomeMemory();
}

Adjust tap throttle max persistence queue size up to 500k

Change-Id: I0e38be6bc984a47f3c8157a39ad2c10a886b6e33
Reviewed-on: http://review.membase.org/3867
Tested-by: Trond Norbye <60edd2ef23891a753f231b0c6f161dc634079a93@gmail.com>
Reviewed-by: Trond Norbye <60edd2ef23891a753f231b0c6f161dc634079a93@gmail.com>


#include "WebSocketWrapper.hpp"

#include <iostream>

using namespace rtcdcpp;

WebSocketWrapper::WebSocketWrapper(std::string url) : url(url), send_queue() { ; }

WebSocketWrapper::~WebSocketWrapper() { delete this->ws; }

bool WebSocketWrapper::Initialize() {
  this->ws = WebSocket::from_url(this->url);
  return this->ws ? true : false;
}

void WebSocketWrapper::SetOnMessage(std::function<void(std::string)> onMessage) { this->onMessage = onMessage; }

void WebSocketWrapper::Start() {
  this->stopping = false;
  this->send_loop = std::thread(&WebSocketWrapper::Loop, this);
}

void WebSocketWrapper::Loop() {
  while (!this->stopping) {
    this->ws->poll();

    if (!this->send_queue.empty()) {
      ChunkPtr chunk = this->send_queue.wait_and_pop();
      std::string msg(reinterpret_cast<char const*>(chunk->Data()), chunk->Length());
      this->ws->send(msg);
      this->ws->poll();
    }
    this->ws->dispatch(this->onMessage);
  }
}

void WebSocketWrapper::Send(std::string msg) { this->send_queue.push(std::shared_ptr<Chunk>(new Chunk((const void*)msg.c_str(), msg.length()))); }

void WebSocketWrapper::Close() { this->stopping = true; this->send_loop.join(); }

#include "WebSocketWrapper.hpp"
#include <thread>
#include <iostream>

using namespace rtcdcpp;

WebSocketWrapper::WebSocketWrapper(std::string url) : url(url), send_queue() { ; }

WebSocketWrapper::~WebSocketWrapper() { delete this->ws; }

bool WebSocketWrapper::Initialize() {
  this->ws = WebSocket::from_url(this->url);
  return this->ws ? true : false;
}

void WebSocketWrapper::SetOnMessage(std::function<void(std::string)> onMessage) { this->onMessage = onMessage; }

void WebSocketWrapper::Start() {
  this->stopping = false;
  this->send_loop = std::thread(&WebSocketWrapper::Loop, this);
}

void WebSocketWrapper::Loop() {
  while (!this->stopping) {
    this->ws->poll();
    std::this_thread::sleep_for(std::chrono::milliseconds(500));
    if (!this->send_queue.empty()) {
      ChunkPtr chunk = this->send_queue.wait_and_pop();
      std::string msg(reinterpret_cast<char const*>(chunk->Data()), chunk->Length());
      this->ws->send(msg);
      this->ws->poll();
    }
    this->ws->dispatch(this->onMessage);
  }
}

void WebSocketWrapper::Send(std::string msg) { this->send_queue.push(std::shared_ptr<Chunk>(new Chunk((const void*)msg.c_str(), msg.length()))); }

void WebSocketWrapper::Close() { this->stopping = true; this->send_loop.join(); }

Add sleep in WebSocket poll

Add sleep in WebSocket poll


#define SOFA_COMPONENT_COLLISION_CYLINDERMODEL_CPP
#include "CylinderModel.inl"

namespace sofa
{

namespace component
{

namespace collision
{

using namespace sofa::defaulttype;
using namespace sofa::core::collision;
using namespace helper;

SOFA_DECL_CLASS(Cylinder)

int RigidCylinderModelClass = core::RegisterObject("Collision model which represents a set of rigid cylinders")
#ifndef SOFA_FLOAT
        .add<  TCylinderModel<defaulttype::Rigid3dTypes> >()
#endif
#ifndef SOFA_DOUBLE
        .add < TCylinderModel<defaulttype::Rigid3fTypes> >()
#endif
        .addAlias("Cylinder")
        .addAlias("CylinderModel")
//.addAlias("CylinderMesh")
//.addAlias("CylinderSet")
        ;

#ifndef SOFA_FLOAT
template class SOFA_BASE_COLLISION_API TCylinder<defaulttype::Rigid3dTypes>;
template class SOFA_BASE_COLLISION_API TCylinderModel<defaulttype::Rigid3dTypes>;
#endif
#ifndef SOFA_DOUBLE
template class SOFA_BASE_COLLISION_API TCylinder<defaulttype::Rigid3fTypes>;
template class SOFA_BASE_COLLISION_API TCylinderModel<defaulttype::Rigid3fTypes>;
#endif

}
}
}

#define SOFA_COMPONENT_COLLISION_CYLINDERMODEL_CPP
#include "CylinderModel.inl"

namespace sofa
{

namespace component
{

namespace collision
{

using namespace sofa::defaulttype;
using namespace sofa::core::collision;
using namespace helper;

SOFA_DECL_CLASS(Cylinder)

int RigidCylinderModelClass = core::RegisterObject("Collision model which represents a set of rigid cylinders")
#ifndef SOFA_FLOAT
        .add<  TCylinderModel<defaulttype::Rigid3dTypes> >()
#endif
#ifndef SOFA_DOUBLE
        .add < TCylinderModel<defaulttype::Rigid3fTypes> >()
#endif
        //TODO(dmarchal): Fix deprecated management...
        .addAlias("Cylinder")
        .addAlias("CylinderModel")
//.addAlias("CylinderMesh")
//.addAlias("CylinderSet")
        ;

#ifndef SOFA_FLOAT
template class SOFA_BASE_COLLISION_API TCylinder<defaulttype::Rigid3dTypes>;
template class SOFA_BASE_COLLISION_API TCylinderModel<defaulttype::Rigid3dTypes>;
#endif
#ifndef SOFA_DOUBLE
template class SOFA_BASE_COLLISION_API TCylinder<defaulttype::Rigid3fTypes>;
template class SOFA_BASE_COLLISION_API TCylinderModel<defaulttype::Rigid3fTypes>;
#endif

}
}
}

Add a TODO to not forget some tasks

[SofaKernel] Add a TODO to not forget some tasks


#include "Halide.h"

namespace {

class EdgeDetect : public Halide::Generator<EdgeDetect> {
public:
    ImageParam input{ UInt(8), 2, "input" };

    Func build() {
        Var x, y;

        Func clamped = Halide::BoundaryConditions::repeat_edge(input);

        // Gradients in x and y.
        Func gx("gx");
        Func gy("gy");
        gx(x, y) = (clamped(x + 1, y) - clamped(x - 1, y)) / 2;
        gy(x, y) = (clamped(x, y + 1) - clamped(x, y - 1)) / 2;

        Func result("result");

        result(x, y) = gx(x, y) * gx(x, y) + gy(x, y) * gy(x, y) + 128;

        // CPU schedule:
        //   Parallelize over scan lines, 4 scanlines per task.
        //   Independently, vectorize in x.
        result
            .parallel(y, 4)
            .vectorize(x, natural_vector_size(UInt(8)));

        return result;
    }
};

Halide::RegisterGenerator<EdgeDetect> register_edge_detect{ "edge_detect" };

}  // namespace

#include "Halide.h"

namespace {

class EdgeDetect : public Halide::Generator<EdgeDetect> {
public:
    ImageParam input{ UInt(8), 2, "input" };

    Func build() {
        Var x, y;

        Func clamped = Halide::BoundaryConditions::repeat_edge(input);

        // Upcast to 16-bit
        Func in16;
        in16(x, y) = cast<int16_t>(clamped(x, y));

        // Gradients in x and y.
        Func gx;
        Func gy;
        gx(x, y) = (in16(x + 1, y) - in16(x - 1, y)) / 2;
        gy(x, y) = (in16(x, y + 1) - in16(x, y - 1)) / 2;

        // Gradient magnitude.
        Func grad_mag;
        grad_mag(x, y) = (gx(x, y) * gx(x, y) + gy(x, y) * gy(x, y));

        // Draw the result
        Func result;
        result(x, y) = cast<uint8_t>(clamp(grad_mag(x, y), 0, 255));

        result
            .compute_root()
            .vectorize(x, 8)
            .parallel(y, 8);

        return result;
    }
};

Halide::RegisterGenerator<EdgeDetect> register_edge_detect{ "edge_detect" };

}  // namespace

Improve edge detector (fix overflow)

Improve edge detector (fix overflow)

Former-commit-id: 34d9d1e630c8195888530530f806efd1f9132137


#include "Server.h"
#include "IgnoreDebugOutput.h"
#include "StdinNotifier.h"
#include <QApplication>
#include <iostream>
#ifdef Q_OS_UNIX
  #include <unistd.h>
#endif

int main(int argc, char **argv) {
#ifdef Q_OS_UNIX
  if (setpgid(0, 0) < 0) {
    std::cerr << "Unable to set new process group." << std::endl;
    return 1;
  }
#endif

  QApplication app(argc, argv);
  app.setApplicationName("capybara-webkit");
  app.setOrganizationName("thoughtbot, inc");
  app.setOrganizationDomain("thoughtbot.com");

  StdinNotifier notifier;
  QObject::connect(&notifier, SIGNAL(eof()), &app, SLOT(quit()));

  ignoreDebugOutput();
  Server server(0);

  if (server.start()) {
    std::cout << "Capybara-webkit server started, listening on port: " << server.server_port() << std::endl;
    return app.exec();
  } else {
    std::cerr << "Couldn't start capybara-webkit server" << std::endl;
    return 1;
  }
}

#include "Server.h"
#include "IgnoreDebugOutput.h"
#include "StdinNotifier.h"
#include <QApplication>
#include <iostream>
#ifdef Q_OS_UNIX
  #include <unistd.h>
#endif

int main(int argc, char **argv) {
#ifdef Q_OS_UNIX
  if (setpgid(0, 0) < 0) {
    std::cerr << "Unable to set new process group." << std::endl;
    return 1;
  }
#endif

#ifdef Q_OS_MAC
  QApplication::setStyle(QStyleFactory::create("Fusion"));
#endif

  QApplication app(argc, argv);
  app.setApplicationName("capybara-webkit");
  app.setOrganizationName("thoughtbot, inc");
  app.setOrganizationDomain("thoughtbot.com");

  StdinNotifier notifier;
  QObject::connect(&notifier, SIGNAL(eof()), &app, SLOT(quit()));

  ignoreDebugOutput();
  Server server(0);

  if (server.start()) {
    std::cout << "Capybara-webkit server started, listening on port: " << server.server_port() << std::endl;
    return app.exec();
  } else {
    std::cerr << "Couldn't start capybara-webkit server" << std::endl;
    return 1;
  }
}

Use the Fusion Qt Style on OS X

Use the Fusion Qt Style on OS X

This fixes issues with checkboxes and radio buttons not being rendered
at the appropriate location on newer version of OS X.


#include <QtCore/QSettings>
#include <QtCore/QVariant>
#include <QtGui/QApplication>
#include <QtGui/QFont>

#include <memory>

extern "C" {
#include <libxslt/xslt.h>
#include <libxml/parser.h>
#include <libxml/xpath.h>
#include <libexslt/exslt.h>
}

#include "DactMainWindow.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QSettings settings("RUG", "Dact");
    QVariant fontValue = settings.value("appFont", qApp->font().toString());
    QFont appFont;
    appFont.fromString(fontValue.toString());
    qApp->setFont(appFont);

    xmlInitMemory();
    xmlInitParser();

    // EXSLT extensions
    exsltRegisterAll();

    // XPath
    xmlXPathInit();

    std::auto_ptr<DactMainWindow> w(new DactMainWindow);
    w->show();

    if (qApp->arguments().size() == 2)
        w->readCorpus(qApp->arguments().at(1));

    int r = a.exec();

    xsltCleanupGlobals();
    xmlCleanupParser();

    return r;
}

#include <QtCore/QSettings>
#include <QtCore/QVariant>
#include <QtGui/QApplication>
#include <QtGui/QFont>
#include <QScopedPointer>

extern "C" {
#include <libxslt/xslt.h>
#include <libxml/parser.h>
#include <libxml/xpath.h>
#include <libexslt/exslt.h>
}

#include "DactMainWindow.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QSettings settings("RUG", "Dact");
    QVariant fontValue = settings.value("appFont", qApp->font().toString());
    QFont appFont;
    appFont.fromString(fontValue.toString());
    qApp->setFont(appFont);

    xmlInitMemory();
    xmlInitParser();

    // EXSLT extensions
    exsltRegisterAll();

    // XPath
    xmlXPathInit();

    QScopedPointer<DactMainWindow> w(new DactMainWindow);
    w->show();

    if (qApp->arguments().size() == 2)
        w->readCorpus(qApp->arguments().at(1));

    int r = a.exec();

    xsltCleanupGlobals();
    xmlCleanupParser();

    return r;
}

Use QScopedPointer instead of std::auto_ptr, per Daniel's request


#include<cmath>
#include<iostream>

using namespace std;

bool isPrimeBruteForce(int x)
{
	if (x < 2)
		return false;
	float sqroot_x = sqrt(x);
	for(int i=0; i <= sqroot_x; i++) { /* If there were only factors above the square root of x, they would be bigger than x itself. */
		if (x%i==0)
			return false;
	}
	return true;
}

int main(int argc, char* argv[])
{
	int number;
	bool result;
	cout << "Enter number to test if it's prime: ";
	cin >> number;
	result = isPrimeBruteForce(number);
	if result {
		cout << number << " is a prime number.";
	} else {
		cout << number << " is not a prime number.";
	}
	return 0;
}

#include<cmath>
#include<iostream>

using namespace std;

bool isPrimeBruteForce(int x)
{
	if (x < 2)
		return false;
	float sqroot_x = sqrt(x);
	for(int i=0; i <= sqroot_x; i++) { /* If there were only factors above the square root of x, they would be bigger than x itself. */
		if (x%i==0)
			return false;
	}
	return true;
}

int main(int argc, char* argv[])
{
	int number;
	bool result;
	cout << "Enter number to test if it's prime: ";
	cin >> number;
	result = isPrimeBruteForce(number);
	if (result) {
		cout << number << " is a prime number.";
	} else {
		cout << number << " is not a prime number.";
	}
	return 0;
}

Correct syntax error in line 25

Correct syntax error in line 25


#include "WebSocketWrapper.hpp"
#include <thread>
#include <iostream>

using namespace rtcdcpp;

WebSocketWrapper::WebSocketWrapper(std::string url) : url(url), send_queue() { ; }

WebSocketWrapper::~WebSocketWrapper() { delete this->ws; }

bool WebSocketWrapper::Initialize() {
  this->ws = WebSocket::from_url(this->url);
  return this->ws ? true : false;
}

void WebSocketWrapper::SetOnMessage(std::function<void(std::string)> onMessage) { this->onMessage = onMessage; }

void WebSocketWrapper::Start() {
  this->stopping = false;
  this->send_loop = std::thread(&WebSocketWrapper::Loop, this);
}

void WebSocketWrapper::Loop() {
  while (!this->stopping) {
    this->ws->poll();
    std::this_thread::sleep_for(std::chrono::milliseconds(500));
    if (!this->send_queue.empty()) {
      ChunkPtr chunk = this->send_queue.wait_and_pop();
      std::string msg(reinterpret_cast<char const*>(chunk->Data()), chunk->Length());
      this->ws->send(msg);
      this->ws->poll();
    }
    this->ws->dispatch(this->onMessage);
  }
}

void WebSocketWrapper::Send(std::string msg) { this->send_queue.push(std::shared_ptr<Chunk>(new Chunk((const void*)msg.c_str(), msg.length()))); }

void WebSocketWrapper::Close() { this->stopping = true; this->send_loop.join(); }

#include "WebSocketWrapper.hpp"
#include <thread>
#include <iostream>

using namespace rtcdcpp;

WebSocketWrapper::WebSocketWrapper(std::string url) : url(url), send_queue() { ; }

WebSocketWrapper::~WebSocketWrapper() { delete this->ws; }

bool WebSocketWrapper::Initialize() {
  this->ws = WebSocket::from_url(this->url);
  return this->ws ? true : false;
}

void WebSocketWrapper::SetOnMessage(std::function<void(std::string)> onMessage) { this->onMessage = onMessage; }

void WebSocketWrapper::Start() {
  this->stopping = false;
  this->send_loop = std::thread(&WebSocketWrapper::Loop, this);
}

void WebSocketWrapper::Loop() {
  while (!this->stopping) {
    this->ws->poll();
    std::this_thread::sleep_for(std::chrono::milliseconds(50));
    if (!this->send_queue.empty()) {
      ChunkPtr chunk = this->send_queue.wait_and_pop();
      std::string msg(reinterpret_cast<char const*>(chunk->Data()), chunk->Length());
      this->ws->send(msg);
      this->ws->poll();
    }
    this->ws->dispatch(this->onMessage);
  }
}

void WebSocketWrapper::Send(std::string msg) { this->send_queue.push(std::shared_ptr<Chunk>(new Chunk((const void*)msg.c_str(), msg.length()))); }

void WebSocketWrapper::Close() { this->stopping = true; this->send_loop.join(); }

Reduce WebSocket poll delay to 50ms

Reduce WebSocket poll delay to 50ms


#include <iostream>

#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "google/protobuf/util/json_util.h"

#include "src/protobuf/test.pb.h"

int main() {
  // verify link and compile versions are the same
  GOOGLE_PROTOBUF_VERIFY_VERSION;

  // testing absl
  std::cout << absl::StrCat("Hello ", "World!") << std::endl;

  TestMessage test_message;
  test_message.set_value(10);
  test_message.set_name("My String");

  // as a string
  std::cout << "String debug:" << std::endl;
  std::cout << test_message.DebugString() << std::endl;

  // as JSON
  std::string json_output;
  google::protobuf::util::MessageToJsonString(test_message, &json_output);
  std::cout << "JSON:" << std::endl;
  std::cout << json_output << std::endl << std::endl;

  // parsing JSON
  TestMessage test_message_2;
  google::protobuf::util::JsonStringToMessage(
      "{\"value\":1, \"name\": \"Testing\" }",
      &test_message_2);
  std::cout << "Debug Reading:" << std::endl;
  std::cout << test_message_2.DebugString() << std::endl;

  return 0;
};

#include <iostream>
#include <string>

// #include "absl/strings/str_cat.h"
// #include "absl/strings/string_view.h"
#include "google/protobuf/util/json_util.h"

#include "src/protobuf/bmv2/program.pb.h"

void ReadStdin(std::string& str) {
  std::istreambuf_iterator<char> cin_iterator{std::cin};
  std::istreambuf_iterator<char> end;
  str = std::string(cin_iterator, end);
}

int main() {
  // verify link and compile versions are the same
  GOOGLE_PROTOBUF_VERIFY_VERSION;

  std::string input;
  ReadStdin(input);

  // testing absl
  // std::cout << absl::StrCat("Hello ", "World!") << std::endl;

  // parsing JSON
  P4Program program;
  google::protobuf::util::JsonParseOptions parsing_options;
  parsing_options.ignore_unknown_fields = true;
  google::protobuf::util::JsonStringToMessage(input, &program, parsing_options);

  // printing JSON
  google::protobuf::util::JsonPrintOptions dumping_options;
  dumping_options.add_whitespace = true;
  dumping_options.always_print_primitive_fields = true;
  dumping_options.preserve_proto_field_names = true;

  std::string output;
  google::protobuf::util::MessageToJsonString(program, &output, dumping_options);
  std::cout << output << std::endl;

  return 0;
};

Add simple C++ stub for testing protobuf definitions


#include <iostream>

#include "Board.h"

int main()
{
  Board b(10, 10);
  b.fillRandomly(10);

  std::cout << "main executed" << std::endl;
  return 0;
}

#include <cstdio>

#include "Board.h"
#include "AGE/Engine.h"

int main()
{
  AGE::Engine engine;

  printf("Initializing...\n");
  if (!engine.init())
  {
    printf("Advanced Game Engine failed to initialize. Exiting.\n");
    exit(1);
  }

  printf("Initialization complete.\nLoading the media...\n");
  if (!engine.loadMedia())
  {
    printf("Warning: some media files failed to load!\n");
  }
  printf("Media loded.\n");

  engine.startLoop();

  // Destroys the window and quits the SDL system:
  engine.close();
  return 0;
}

Use the engine to create a game window

Use the engine to create a game window

Modifies the main unit, so that it will use the Advanced Graphics
Engine. The engine creates an 800x600 window and renders
the minesweeper tiles' texture in the top-left corner.


/*
 * BasicLayout.cpp
 *
 * Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
 * Copyright 2000, Bastiaan Bakker. All rights reserved.
 *
 * See the COPYING file for the terms of usage and distribution.
 */

#include "PortabilityImpl.hh"
#include <log4cpp/BasicLayout.hh>
#include <log4cpp/Priority.hh>
#include <log4cpp/FactoryParams.hh>
#ifdef LOG4CPP_HAVE_SSTREAM
#include <sstream>
#endif

namespace log4cpp {

    BasicLayout::BasicLayout() {
    }

    BasicLayout::~BasicLayout() {
    }

    std::string BasicLayout::format(const LoggingEvent& event) {
        std::ostringstream message;

        const std::string& priorityName = Priority::getPriorityName(event.priority);
        message << event.timeStamp.getSeconds() << " " << priorityName << " "
                << event.categoryName << " " << event.ndc << ": "
                << event.message << std::endl;

        return message.str();
    }

    std::auto_ptr<Layout> create_basic_layout(const FactoryParams& params)
    {
       return std::auto_ptr<Layout>(new BasicLayout);
    }
}

/*
 * BasicLayout.cpp
 *
 * Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
 * Copyright 2000, Bastiaan Bakker. All rights reserved.
 *
 * See the COPYING file for the terms of usage and distribution.
 */

#include "PortabilityImpl.hh"
#include <log4cpp/BasicLayout.hh>
#include <log4cpp/Priority.hh>
#include <log4cpp/FactoryParams.hh>
#ifdef LOG4CPP_HAVE_SSTREAM
#include <sstream>
#endif
#include <memory>

namespace log4cpp {

    BasicLayout::BasicLayout() {
    }

    BasicLayout::~BasicLayout() {
    }

    std::string BasicLayout::format(const LoggingEvent& event) {
        std::ostringstream message;

        const std::string& priorityName = Priority::getPriorityName(event.priority);
        message << event.timeStamp.getSeconds() << " " << priorityName << " "
                << event.categoryName << " " << event.ndc << ": "
                << event.message << std::endl;

        return message.str();
    }

    std::auto_ptr<Layout> create_basic_layout(const FactoryParams& params)
    {
       return std::auto_ptr<Layout>(new BasicLayout);
    }
}

Add missing header file for Ubuntu Jaunty and beyond


#include "Interpreter.hpp"

#include "modules/error-handler/ErrorHandler.hpp"
#include "modules/lexer/Lexer.hpp"

#include <iostream>

using Interpreter = tkom::Interpreter;
using ErrorHandler = tkom::modules::ErrorHandler;
using Lexer = tkom::modules::Lexer;

Interpreter::Interpreter(const std::vector<std::string>& arguments)
{
    try
    {
        if (arguments.size() < 1)
        {
            ErrorHandler::error("No input file specified");
        }

        Lexer lexer(arguments.at(0));

        Token token;

        do
        {
            token = lexer.nextToken();

            std::cout << tkom::modules::utils::getTokenTypeName(token.type) << " = " << token.value << std::endl;
        }
        while(token.type != TokenType::Invalid && token.type != TokenType::EndOfFile);
    }
    catch(ErrorHandler::Exception &e)
    {
        ErrorHandler::error("Terminating...", true);
    }
}

#include "Interpreter.hpp"

#include "modules/error-handler/ErrorHandler.hpp"
#include "modules/lexer/Lexer.hpp"
#include "modules/parser/Parser.hpp"

using Interpreter = tkom::Interpreter;
using ErrorHandler = tkom::modules::ErrorHandler;
using Lexer = tkom::modules::Lexer;
using Parser = tkom::modules::Parser;

Interpreter::Interpreter(const std::vector<std::string>& arguments)
{
    try
    {
        if (arguments.size() < 1)
        {
            ErrorHandler::error("No input file specified");
        }

        Lexer lexer(arguments.at(0));
        Parser parser(lexer);

        parser.parse();
    }
    catch(ErrorHandler::Exception &e)
    {
        ErrorHandler::error("Terminating...", true);
    }
}

Use Parser module to parse a file

Use Parser module to parse a 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 "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Popup) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("popup")) << message_;
}

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

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

// Flaky, http://crbug.com/46601.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_Popup) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("popup")) << message_;
}

Mark ExtensionApiTest.Popup as FLAKY, it is still flaky.

TBR=twiz

BUG=46601
TEST=browser_tests

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

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


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

#include "chrome/test/chromedriver/chrome/device_metrics.h"

DeviceMetrics::DeviceMetrics(int width, int height, double device_scale_factor)
  : width(width),
    height(height),
    device_scale_factor(device_scale_factor),
    mobile(false),
    fit_window(false),
    text_autosizing(true),
    font_scale_factor(1) {}

DeviceMetrics::~DeviceMetrics() {}

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

#include "chrome/test/chromedriver/chrome/device_metrics.h"

DeviceMetrics::DeviceMetrics(int width, int height, double device_scale_factor)
  : width(width),
    height(height),
    device_scale_factor(device_scale_factor),
    mobile(true),
    fit_window(false),
    text_autosizing(true),
    font_scale_factor(1) {}

DeviceMetrics::~DeviceMetrics() {}

[chromedriver] Set mobile=true when calling setDeviceMetricsOverride

BUG=chromedriver:944
TBR=stgao@chromium.org

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

Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#300390}


#include "scene/scenegroup.hpp"

#include <algorithm>

using namespace scene;

SceneGroup::SceneGroup(unsigned int octreeLevels) {
	addOctreeLayers(octreeLevels);
}

void SceneGroup::addOctreeLayers(unsigned int levels) {
	childGroups.reset(new std::array<SceneGroup,8>);

	std::for_each(childGroups->begin(), childGroups->end(),
	[&levels](SceneGroup& child) {
		child.addOctreeLayers(--levels);
	});
}

void SceneGroup::updateScene() {
	std::for_each(childItems.begin(), childItems.end(), [](std::unique_ptr<SceneItem>& child) {
		child->update();
	});

	if(childGroups != nullptr) {
		std::for_each(childGroups->begin(), childGroups->end(),
		[](SceneGroup& child) {
			child.updateScene();
		});
	}
}

void SceneGroup::renderScene() {
	std::for_each(childItems.begin(), childItems.end(), [](std::unique_ptr<SceneItem>& child) {
		child->draw();
	});

	if(childGroups != nullptr) {
		std::for_each(childGroups->begin(), childGroups->end(),
		[](SceneGroup& child) {
			child.renderScene();
		});
	}
}

#include "scene/scenegroup.hpp"

#include <algorithm>

using namespace scene;

SceneGroup::SceneGroup(unsigned int octreeLevels) {
	addOctreeLayers(octreeLevels);
}

void SceneGroup::addOctreeLayers(unsigned int levels) {
	if(levels != 0) {
		childGroups.reset(new std::array<SceneGroup,8>);

		std::for_each(childGroups->begin(), childGroups->end(),
		[&levels](SceneGroup& child) {
			child.addOctreeLayers(--levels);
		});
	}
}

void SceneGroup::updateScene() {
	std::for_each(childItems.begin(), childItems.end(), [](std::unique_ptr<SceneItem>& child) {
		child->update();
	});

	if(childGroups != nullptr) {
		std::for_each(childGroups->begin(), childGroups->end(),
		[](SceneGroup& child) {
			child.updateScene();
		});
	}
}

void SceneGroup::renderScene() {
	std::for_each(childItems.begin(), childItems.end(), [](std::unique_ptr<SceneItem>& child) {
		child->draw();
	});

	if(childGroups != nullptr) {
		std::for_each(childGroups->begin(), childGroups->end(),
		[](SceneGroup& child) {
			child.renderScene();
		});
	}
}

Fix recursive add of octreelevels in SceneGroup


// RUN: %clang_cl_asan -O0 %s -Fe%t
// RUN: env ASAN_OPTIONS=handle_segv=0 %run %t 2>&1 | FileCheck %s --check-prefix=USER
// RUN: env ASAN_OPTIONS=handle_segv=1 not %run %t 2>&1 | FileCheck %s --check-prefix=ASAN
// Test the default.
// RUN: not %run %t 2>&1 | FileCheck %s --check-prefix=ASAN

// This test exits zero when its unhandled exception filter is set. ASan should
// not disturb it when handle_segv=0.

// USER: in main
// USER: in SEHHandler

// ASAN: in main
// ASAN: ERROR: AddressSanitizer: access-violation

#include <windows.h>
#include <stdio.h>

static long WINAPI SEHHandler(EXCEPTION_POINTERS *info) {
  DWORD exception_code = info->ExceptionRecord->ExceptionCode;
  if (exception_code == EXCEPTION_ACCESS_VIOLATION) {
    fprintf(stderr, "in SEHHandler\n");
    fflush(stdout);
    TerminateProcess(GetCurrentProcess(), 0);
  }
  return EXCEPTION_CONTINUE_SEARCH;
}

int main() {
  SetUnhandledExceptionFilter(SEHHandler);
  fprintf(stderr, "in main\n");

  volatile int *p = nullptr;
  *p = 42;
}

// RUN: %clang_cl_asan -O0 %s -Fe%t
// RUN: env ASAN_OPTIONS=handle_segv=0 %run %t 2>&1 | FileCheck %s --check-prefix=USER
// RUN: env ASAN_OPTIONS=handle_segv=1 not %run %t 2>&1 | FileCheck %s --check-prefix=ASAN
// Test the default.
// RUN: not %run %t 2>&1 | FileCheck %s --check-prefix=ASAN

// This test exits zero when its unhandled exception filter is set. ASan should
// not disturb it when handle_segv=0.

// USER: in main
// USER: in SEHHandler

// ASAN: in main
// ASAN: ERROR: AddressSanitizer: access-violation

#include <windows.h>
#include <stdio.h>

static long WINAPI SEHHandler(EXCEPTION_POINTERS *info) {
  DWORD exception_code = info->ExceptionRecord->ExceptionCode;
  if (exception_code == EXCEPTION_ACCESS_VIOLATION) {
    fprintf(stderr, "in SEHHandler\n");
    fflush(stderr);
    TerminateProcess(GetCurrentProcess(), 0);
  }
  return EXCEPTION_CONTINUE_SEARCH;
}

int main() {
  SetUnhandledExceptionFilter(SEHHandler);
  fprintf(stderr, "in main\n");
  fflush(stderr);

  volatile int *p = nullptr;
  *p = 42;
}

Add flushes to try to fix test

[asan] Add flushes to try to fix test

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


#include "singletons/Emotes.hpp"

#include "Application.hpp"
#include "controllers/accounts/AccountController.hpp"

namespace chatterino {

void Emotes::initialize(Application &app)
{
    app.accounts->twitch.currentUserChanged.connect([this, &app] {
        auto currentUser = app.accounts->twitch.getCurrent();
        assert(currentUser);
        this->twitch.refresh(currentUser);
    });

    this->emojis.load();
    this->bttv.loadGlobalEmotes();
    this->ffz.loadGlobalEmotes();

    this->gifTimer.initialize();
}

bool Emotes::isIgnoredEmote(const QString &)
{
    return false;
}

}  // namespace chatterino

#include "singletons/Emotes.hpp"

#include "Application.hpp"
#include "controllers/accounts/AccountController.hpp"

namespace chatterino {

void Emotes::initialize(Application &app)
{
    const auto refreshTwitchEmotes = [this, &app] {
        auto currentUser = app.accounts->twitch.getCurrent();
        assert(currentUser);
        this->twitch.refresh(currentUser);
    };
    app.accounts->twitch.currentUserChanged.connect(refreshTwitchEmotes);
    refreshTwitchEmotes();

    this->emojis.load();
    this->bttv.loadGlobalEmotes();
    this->ffz.loadGlobalEmotes();

    this->gifTimer.initialize();
}

bool Emotes::isIgnoredEmote(const QString &)
{
    return false;
}

}  // namespace chatterino

Load twitch emotes on initialize as well

Fix #581


#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE flatten_tests
#include <boost/test/unit_test.hpp>

#include "flatten/flatten.hpp"

BOOST_AUTO_TEST_CASE(flatten_tests)
{

}

#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE flatten_tests
#include <boost/test/unit_test.hpp>

#include <list>
#include <vector>
#include <map>

#include "flatten/flatten.hpp"

typedef std::vector<int> IntList;
typedef std::vector<IntList> IntListList;
typedef std::vector<IntListList> IntListListList;

IntListListList example1_values()
{
    IntListListList values;
    IntListList a;
    IntList a1;
    IntList a2;
    IntList a3;
    IntListList b;
    IntList b1;
    IntList b2;
    IntList b3;

    a1.push_back(1);
    a1.push_back(2);
    a1.push_back(3);

    a2.push_back(4);
    a2.push_back(5);
    a2.push_back(6);

    /* a3 empty */

    b1.push_back(7);

    b2.push_back(8);

    b3.push_back(9);

    a.push_back(a1);
    a.push_back(a2);
    a.push_back(a3);

    b.push_back(b1);
    b.push_back(b2);
    b.push_back(b3);

    values.push_back(a);
    values.push_back(b);
    return values;
}

BOOST_AUTO_TEST_CASE(example1)
{
    IntListListList values = example1_values();
    IntList result;

    flatten::flatten<int>(
        values.begin(), values.end(), std::back_inserter(result)
    );

    for (int i = 0; i < 9; ++i)
    {
        BOOST_REQUIRE(i < result.size());
        BOOST_CHECK_EQUAL(result[i], i + 1);
    }
}

Add test for Example 1.

Add test for Example 1.


#if defined(__x86_64__) || defined(_M_X64)
  X86_64

#elif defined(__i386__) || defined(__i386) || defined(_M_IX86)
  X86_32

#elif defined(__aarch64__) || defined(__ARM_ARCH_ISA_A64)
  ARM64

#elif defined(__arm__) || defined(_M_ARM) || defined(__ARM_ARCH_7A__)
  ARM32

#elif defined(__powerpc64__) || defined(__ppc64__) || defined(_ARCH_PPC64)
  PPC64

#elif defined(__powerpc__) || defined(__ppc__) || defined(_ARCH_PPC)
  PPC32

#elif defined(__mips__) || defined(__mips)
  MIPS32

#elif defined(__sparc__)
  SPARC32

#elif defined(__alpha__)
  ALPHA

#elif defined(__hppa__) || defined(__hppa)
  HPPA

#elif defined(__ia64__)
  IA64

#elif defined(__m68k__)
  M68K

#elif defined(__sh__)
  SH

#elif defined(__s390x__)
  S390X

#elif defined(__s390__)
  S390

#else
  UNKNOWN

#endif

#if defined(__x86_64__) || defined(_M_X64)
  X86_64

#elif defined(__i386__) || defined(__i386) || defined(_M_IX86)
  X86_32

#elif defined(__aarch64__) || defined(__ARM_ARCH_ISA_A64)
  ARM64

#elif defined(__arm__) || defined(_M_ARM) || defined(__ARM_ARCH_7A__)
  ARM32

#elif defined(__powerpc64__) || defined(__ppc64__) || defined(_ARCH_PPC64)
  PPC64

#elif defined(__powerpc__) || defined(__ppc__) || defined(_ARCH_PPC)
  PPC32

#elif defined(__mips__) || defined(__mips)

  #if defined(__LP64__) || defined(_LP64)
  MIPS64
  #else
  MIPS32
  #endif

#elif defined(__sparc__)

  #if defined(__LP64__) || defined(_LP64)
  SPARC64
  #else
  SPARC32
  #endif

#elif defined(__alpha__)
  ALPHA

#elif defined(__hppa__) || defined(__hppa)
  HPPA

#elif defined(__ia64__)
  IA64

#elif defined(__m68k__)
  M68K

#elif defined(__sh__)
  SH

#elif defined(__s390x__)
  S390X

#elif defined(__s390__)
  S390

#else
  UNKNOWN

#endif

Fix autodetection of sparc64/mips64 [ci skip]


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

struct NonPOD {
  virtual void f();
  int m;
};

struct P {
  NonPOD fieldThatPointsToANonPODType;
};

void f() {
  int i = __builtin_offsetof(P, fieldThatPointsToANonPODType.m); // expected-warning{{offset of on non-POD type 'struct P'}}
}

// FIXME: This test fails on 32-bit platforms? Investigate.

// RUNX: clang-cc -fsyntax-only -verify %s -Winvalid-offsetof

struct NonPOD {
  virtual void f();
  int m;
};

struct P {
  NonPOD fieldThatPointsToANonPODType;
};

void f() {
  int i = __builtin_offsetof(P, fieldThatPointsToANonPODType.m); // expected-warning{{offset of on non-POD type 'struct P'}}
}

Disable this test case, I'm tired of seeing red. :)

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


// ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //

#include <gtest/gtest.h>

#include <DO/Defines.hpp>
#include <DO/ImageProcessing/Deriche.hpp>

#include "utilities.hpp"

using namespace std;
using namespace DO;

TEST(TestDericheFilter, test_inplace_deriche_blur)
{
}

int main(int argc, char** argv)
{
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

// ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //

#include <gtest/gtest.h>

#include <DO/Defines.hpp>
#include <DO/ImageProcessing/Deriche.hpp>

using namespace std;
using namespace DO;

TEST(TestDericheFilter, test_inplace_deriche_blur)
{
}

int main(int argc, char** argv)
{
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

Remove inclusion of unversioned header.

Remove inclusion of unversioned header.


/**
 ** Test code for libport/shared-ptr.hh features.
 */

#include <libport/ref-counted.hh>
#include <libport/shared-ptr.hh>

#define INSTANCES(N) assert(Counted::instances == N)

using libport::shared_ptr;

struct Counted : libport::RefCounted
{
  Counted () : libport::RefCounted() { ++instances; }
  virtual ~Counted () { assert (0 < instances); --instances; }
  static unsigned instances;
};

struct SubCounted : Counted
{
};

unsigned Counted::instances;

typedef shared_ptr<Counted> rCounted;
typedef shared_ptr<SubCounted> rSubCounted;

int
main ()
{
  {
    SubCounted* subcounted = new SubCounted;
    rSubCounted r1 (subcounted);
    {
      INSTANCES(1);
      rCounted r2;
      INSTANCES(1);
      r2 = r1;
      INSTANCES(1);
      rSubCounted r3 = r2.cast<SubCounted>();
      INSTANCES(1);
      rCounted r4 = new Counted;
      INSTANCES(2);
      r4 = r3;
      INSTANCES(1);
    }
    INSTANCES(1);
  }
  INSTANCES(0);
}

/**
 ** Test code for libport/shared-ptr.hh features.
 */

#include <libport/ref-counted.hh>
#include <libport/shared-ptr.hh>

#define INSTANCES(N) assert(Counted::instances == N)

using libport::shared_ptr;

struct Counted : libport::RefCounted
{
  Counted () : libport::RefCounted() { ++instances; }
  virtual ~Counted () { assert (0 < instances); --instances; }
  static unsigned instances;
};

struct SubCounted : Counted
{
};

unsigned Counted::instances;

typedef shared_ptr<Counted> rCounted;
typedef shared_ptr<SubCounted> rSubCounted;

int
main ()
{
  {
    SubCounted* subcounted = new SubCounted;
    rSubCounted r1 (subcounted);
    {
      INSTANCES(1);
      rCounted r2;
      INSTANCES(1);
      r2 = r1;
      INSTANCES(1);
      rSubCounted r3 = r2.cast<SubCounted>();
      INSTANCES(1);
      rCounted r4 = new Counted;
      INSTANCES(2);
      r4 = r3;
      INSTANCES(1);
    }
    INSTANCES(1);
  }
  INSTANCES(0);

  {
    rSubCounted p = new SubCounted();
    p = p;
    INSTANCES(1);
  }
  INSTANCES(0);
}

Test shared pointers assignment to self.

    * tests/libport/test-shared-ptr-intrusive.cc: Here.


#include <iostream>
#include <cstdlib>
#include "NTClient.h"
using namespace std;

void initBot() {
	NTClient nclient = NTClient(20, 0.89);
	nclient.login("sascf3", "123asd123"); // Throw-away account
	nclient.connect();
}
int main(int argc, char** argv) {
	srand(static_cast<unsigned int>(time(0)));
	initBot();
	return 0;
}

#include <iostream>
#include <cstdlib>
#include <fstream>
#include "NTClient.h"
#include "colors.h"
#include "json.hpp"
using namespace std;

void initBot(string username, string password, int wpm, double acc) {
	NTClient nclient = NTClient(wpm, acc);
	nclient.login(username, password);
	nclient.connect();
}
void initlog(string msg) {
	cout << CLR_GRN << STYLE_BOLD << "[INIT] " << CLR_RESET << CLR_WHT << msg << CLR_RESET;
}
void errlog(string msg) {
	cout << CLR_RED << STYLE_BOLD << "[ERR!] " << CLR_RESET << CLR_WHT << msg << CLR_RESET;
}
int main(int argc, char** argv) {
	srand(static_cast<unsigned int>(time(0)));
	ifstream configf;
	configf.exceptions(std::ios::failbit | std::ios::badbit);
	try {
		configf.open("config.json");
	} catch(const exception& e) {
		errlog("Failed to open the JSON config. For help, read the UltraType++ repository README.\n");
		return 1;
	}
	return 0;
}

Add basic config file support

Add basic config file support


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

#include "base/process_util.h"

#include <sys/types.h>
#include <unistd.h>

#include "base/basictypes.h"
#include "base/sys_info.h"

namespace process_util {

int GetCurrentProcId() {
  return getpid();
}

ProcessHandle GetCurrentProcessHandle() {
  return GetCurrentProcId();
}

int GetProcId(ProcessHandle process) {
  return process;
}

ProcessMetrics::ProcessMetrics(ProcessHandle process) : process_(process),
                                                        last_time_(0),
                                                        last_system_time_(0) {
  processor_count_ = base::SysInfo::NumberOfProcessors();
}

// static
ProcessMetrics* ProcessMetrics::CreateProcessMetrics(ProcessHandle process) {
  return new ProcessMetrics(process);
}

ProcessMetrics::~ProcessMetrics() { }

void EnableTerminationOnHeapCorruption() {
  // On POSIX, there nothing to do AFAIK.
}

void RaiseProcessToHighPriority() {
  // On POSIX, we don't actually do anything here.  We could try to nice() or
  // setpriority() or sched_getscheduler, but these all require extra rights.
}

}  // namespace process_util

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

#include "base/process_util.h"

#include <sys/types.h>
#include <unistd.h>

#include "base/basictypes.h"
#include "base/sys_info.h"

namespace base {

int GetCurrentProcId() {
  return getpid();
}

ProcessHandle GetCurrentProcessHandle() {
  return GetCurrentProcId();
}

int GetProcId(ProcessHandle process) {
  return process;
}

ProcessMetrics::ProcessMetrics(ProcessHandle process) : process_(process),
                                                        last_time_(0),
                                                        last_system_time_(0) {
  processor_count_ = base::SysInfo::NumberOfProcessors();
}

// static
ProcessMetrics* ProcessMetrics::CreateProcessMetrics(ProcessHandle process) {
  return new ProcessMetrics(process);
}

ProcessMetrics::~ProcessMetrics() { }

void EnableTerminationOnHeapCorruption() {
  // On POSIX, there nothing to do AFAIK.
}

void RaiseProcessToHighPriority() {
  // On POSIX, we don't actually do anything here.  We could try to nice() or
  // setpriority() or sched_getscheduler, but these all require extra rights.
}

}  // namespace base

Move process utils into the base namespace (fix build bustage).
Review URL: http://codereview.chromium.org/10736

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


#include <iostream>

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

  std::cout << "Hello Lamure Virtual Texture!\n";
  return 0;
}

#include <iostream>

// scism shit
#include <scm/core.h>
#include <scm/log.h>
#include <scm/core/pointer_types.h>
#include <scm/core/io/tools.h>
#include <scm/core/time/accum_timer.h>
#include <scm/core/time/high_res_timer.h>

#include <scm/gl_core.h>

#include <scm/gl_util/data/imaging/texture_loader.h>
#include <scm/gl_util/manipulators/trackball_manipulator.h>
#include <scm/gl_util/primitives/box.h>
#include <scm/gl_util/primitives/quad.h>
#include <scm/gl_util/primitives/wavefront_obj.h>

// Window library
#include <GL/freeglut.h>

static int winx = 1600;
static int winy = 1024;

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

    // init GLUT and create Window
    glutInit(&argc, argv);
    glutInitContextVersion (4,2);
    glutInitContextProfile(GLUT_CORE_PROFILE);

    glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);

    // set properties from window
    glutCreateWindow("First test with GLUT and SCHISM");
    glutInitWindowPosition(0, 0);
    glutInitWindowSize(winx, winy);

    // register callbacks
    glutDisplayFunc(display);

    // enter GLUT event processing cycle
    glutMainLoop();
    return 0;
}

Implement first basic black window setup without any content


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

#include "../JPetAnalysisTools/JPetAnalysisTools.h"

BOOST_AUTO_TEST_SUITE(FirstSuite)

BOOST_AUTO_TEST_CASE(constructor_getHitsOrderedByTime)
{
  std::vector<JPetHit> hits(4);
  hits[0].setTime(2);
  hits[1].setTime(1);
  hits[2].setTime(4);
  hits[3].setTime(3);
  auto results = JPetAnalysisTools::getHitsOrderedByTime(hits);
  BOOST_REQUIRE_EQUAL(results[0].getTime(), 1);
  BOOST_REQUIRE_EQUAL(results[1].getTime(), 2);
  BOOST_REQUIRE_EQUAL(results[2].getTime(), 3);
  BOOST_REQUIRE_EQUAL(results[3].getTime(), 4);
}

BOOST_AUTO_TEST_SUITE_END()

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

#include "../JPetAnalysisTools/JPetAnalysisTools.h"

BOOST_AUTO_TEST_SUITE(FirstSuite)

BOOST_AUTO_TEST_CASE(constructor_getHitsOrderedByTime)
{
  std::vector<JPetHit> hits(4);
  hits[0].setTime(2);
  hits[1].setTime(1);
  hits[2].setTime(4);
  hits[3].setTime(3);
  auto results = JPetAnalysisTools::getHitsOrderedByTime(hits);
  double epsilon = 0.0001;
  BOOST_REQUIRE_CLOSE(results[0].getTime(), 1, epsilon );
  BOOST_REQUIRE_CLOSE(results[1].getTime(), 2, epsilon );
  BOOST_REQUIRE_CLOSE(results[2].getTime(), 3, epsilon );
  BOOST_REQUIRE_CLOSE(results[3].getTime(), 4, epsilon );
}

BOOST_AUTO_TEST_SUITE_END()

Change tests in JPetAnalysisTools to use double instead of int


#include "AppInfo.h"
#include "Builder.h"
#include "LibInfoDySySim.h"

#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>

namespace dss = dysysim;

int main(int argc, char *argv[])
{
   std::cout << "-- " APPNAME_VERSION " " << std::string(50, '-') << std::endl
             << "-- uses " + dss::libName + " v" << dss::libVersion << std::endl
             << std::endl;

   dss::Builder builder;

   std::ifstream programFile;

   if (argc > 2) {
      return 1;
   }

   if (argc == 1) {
      programFile.open("../appDySySim/data/RCnetwork.dss");
   } else {
      programFile.open(argv[1]);
   }

   if (programFile.is_open()) {
       std::cout << "\n-- Syntax check\n";
     builder(programFile);
   }
   std::cout << "\n";

   programFile.close();

   return 0;
}

#include "AppInfo.h"
#include "Builder.h"
#include "LibInfoDySySim.h"

#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>

namespace dss = dysysim;

int main(int argc, char *argv[])
{
   std::cout << "-- " APPNAME_VERSION " " << std::string(50, '-') << std::endl
             << "-- uses " + dss::libName + " v" << dss::libVersion << std::endl
             << std::endl;

   dss::Builder builder;

   std::ifstream programFile;

   if (argc > 2) {
      return 1;
   }

   if (argc == 1) {
      programFile.open("../appDySySim/scripts/RCnetwork.dss");
   } else {
      programFile.open(argv[1]);
   }

   if (programFile.is_open()) {
      std::cout << "\n-- Syntax check\n";
      builder(programFile);
   }
   std::cout << "\n";

   programFile.close();

   return 0;
}

Rename dir data to scripts

Rename dir data to scripts


//===--- ThreadSanitizer.cpp - Thread Sanitizer support -------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Thread Sanitizer support for the Swift Task runtime
//
//===----------------------------------------------------------------------===//

#include "TaskPrivate.h"

#include <dlfcn.h>

using TSanFunc = void(void *);

void swift::_swift_tsan_acquire(void *addr) {
  static auto ptr = (TSanFunc *)dlsym(RTLD_DEFAULT, "__tsan_acquire");
  if (ptr) {
    ptr(addr);
  }
}

void swift::_swift_tsan_release(void *addr) {
  static auto ptr = (TSanFunc *)dlsym(RTLD_DEFAULT, "__tsan_release");
  if (ptr) {
    ptr(addr);
  }
}

//===--- ThreadSanitizer.cpp - Thread Sanitizer support -------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Thread Sanitizer support for the Swift Task runtime
//
//===----------------------------------------------------------------------===//

#include "TaskPrivate.h"

#if defined(_WIN32)
#define NOMINMAX
#include <windows.h>
#else
#include <dlfcn.h>
#endif

using TSanFunc = void(void *);

namespace {
static TSanFunc *loadSymbol(const char *name) {
#if defined(_WIN32)
  return (TSanFunc *)GetProcAddress(GetModuleHandle(NULL), name);
#else
  return (TSanFunc *)dlsym(RTLD_DEFAULT, name);
#endif
}
}

void swift::_swift_tsan_acquire(void *addr) {
  static auto ptr = loadSymbol("__tsan_acquire");
  if (ptr) {
    ptr(addr);
  }
}

void swift::_swift_tsan_release(void *addr) {
  static auto ptr = loadSymbol("__tsan_release");
  if (ptr) {
    ptr(addr);
  }
}

Fix TSan symbol lookup on Windows

Fix TSan symbol lookup on Windows


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

// <experimental/utility>

#include <experimental/utility>

int main()
{
    std::experimental::erased_type e();
}

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

// <experimental/utility>

#include <experimental/utility>

int main()
{
    std::experimental::erased_type e;
}

Fix vexing parse in test.

Fix vexing parse in test.

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


/* **********************************************************
 * Copyright (c) 2011 Google, Inc.  All rights reserved.
 * **********************************************************/

/* Dr. Memory: the memory debugger
 *
 * 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;
 * version 2.1 of the License, and no 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 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.
 */

#include <windows.h>

#include "gtest/gtest.h"

TEST(NtUserTests, SystemParametersInfo) {
    NONCLIENTMETRICS metrics;
    ZeroMemory(&metrics, sizeof(NONCLIENTMETRICS));
    metrics.cbSize = sizeof(NONCLIENTMETRICS);
    EXPECT_NE(0, SystemParametersInfo(SPI_GETNONCLIENTMETRICS,
                                      sizeof(NONCLIENTMETRICS), &metrics, 0));
}

/* **********************************************************
 * Copyright (c) 2011 Google, Inc.  All rights reserved.
 * **********************************************************/

/* Dr. Memory: the memory debugger
 *
 * 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;
 * version 2.1 of the License, and no 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 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.
 */

#include <windows.h>

#include "gtest/gtest.h"

TEST(NtUserTests, SystemParametersInfo) {
    NONCLIENTMETRICS metrics;
    ZeroMemory(&metrics, sizeof(NONCLIENTMETRICS));
    metrics.cbSize = sizeof(NONCLIENTMETRICS);
    SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS),
                         &metrics, 0);
}

Remove the return value check in the SystemParametersInfo test since it is failing on Windows XP for some reason

git-svn-id: fe3cd4388a6e5a968b09397a3d721fe124e8117a@400 5b54908e-ead4-fc18-b48a-0285e6dbc711


// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include <autowiring/config_descriptor.h>
#include <autowiring/config.h>
#include <autowiring/ConfigRegistry.h>
#include <autowiring/observable.h>

namespace aw = autowiring;

class AutoConfig_SliderTest :
  public testing::Test
{};

namespace {
  struct slider {
    template<typename T>
    struct valid {
      static const bool value = std::is_integral<T>::value;
    };
  };

  class ClassWithASlider {
  public:
    std::string api_path;
    int timeout;

    static aw::config_descriptor GetConfigDescriptor(void) {
      return{
        { "api_path", &ClassWithASlider::api_path },
        { "timeout", &ClassWithASlider::timeout, slider{} }
      };
    }
  };
}

// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include <autowiring/config_descriptor.h>
#include <autowiring/config.h>
#include <autowiring/ConfigRegistry.h>
#include <autowiring/observable.h>

namespace aw = autowiring;

class AutoConfig_SliderTest :
  public testing::Test
{};

namespace {
  struct slider {
    template<typename T>
    struct valid {
      static const bool value = std::is_integral<T>::value;
    };
  };

  class ClassWithASlider {
  public:
    std::string api_path;
    int timeout;

    static aw::config_descriptor GetConfigDescriptor(void) {
      return{
        { "api_path", &ClassWithASlider::api_path, slider{} },
        { "timeout", &ClassWithASlider::timeout, slider{} }
      };
    }
  };

  class SliderManager {
    SliderManager(void) {
      AutoCurrentContext ctxt;
      ctxt->Config.When([](const aw::config_field& field, const slider&) {
      });
    }
  };
}

TEST_F(AutoConfig_SliderTest, CanFindAllSliders) {

  // Get a full list of all sliders:
}

Extend slider use case test

Extend slider use case test


//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <iostream>

#include "il/Main.hpp"
#include "AssemblyFileWriter.hpp"

using namespace eddic;

void Main::write(AssemblyFileWriter& writer){
    writer.stream() << ".text" << std::endl
                    << ".globl main" << std::endl
                    << "\t.type main, @function" << std::endl;
}

//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <iostream>

#include "il/Main.hpp"
#include "AssemblyFileWriter.hpp"

using namespace eddic;

void Main::write(AssemblyFileWriter& writer){
    writer.stream() << ".text" << std::endl
                    << ".globl _start" << std::endl

                    << "_start:" << std::endl
                    << "call main" << std::endl
                    << "movl $1, %eax" << std::endl
                    << "xorl %ebx, %ebx" << std::endl
                    << "int $0x80" << std::endl;
}

Improve main declaration to include runtime start


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

#include "PerfHelper.h"
#include "llvm/Config/config.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"

namespace exegesis {
namespace pfm {
namespace {

using ::testing::IsEmpty;
using ::testing::Not;

TEST(PerfHelperTest, FunctionalTest) {
#ifdef HAVE_LIBPFM
  ASSERT_FALSE(pfmInitialize());
  const PerfEvent SingleEvent("CYCLES:u");
  const auto &EmptyFn = []() {};
  std::string CallbackEventName;
  std::string CallbackEventNameFullyQualifed;
  int64_t CallbackEventCycles;
  Measure(llvm::makeArrayRef(SingleEvent),
          [&](const PerfEvent &Event, int64_t Value) {
            CallbackEventName = Event.name();
            CallbackEventNameFullyQualifed = Event.getPfmEventString();
            CallbackEventCycles = Value;
          },
          EmptyFn);
  EXPECT_EQ(CallbackEventName, "CYCLES:u");
  EXPECT_THAT(CallbackEventNameFullyQualifed, Not(IsEmpty()));
  pfmTerminate();
#else
  ASSERT_TRUE(PfmInitialize());
#endif
}

} // namespace
} // namespace pfm
} // namespace exegesis

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

#include "PerfHelper.h"
#include "llvm/Config/config.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"

namespace exegesis {
namespace pfm {
namespace {

using ::testing::IsEmpty;
using ::testing::Not;

TEST(PerfHelperTest, FunctionalTest) {
#ifdef HAVE_LIBPFM
  ASSERT_FALSE(pfmInitialize());
  const PerfEvent SingleEvent("CYCLES:u");
  const auto &EmptyFn = []() {};
  std::string CallbackEventName;
  std::string CallbackEventNameFullyQualifed;
  int64_t CallbackEventCycles;
  Measure(llvm::makeArrayRef(SingleEvent),
          [&](const PerfEvent &Event, int64_t Value) {
            CallbackEventName = Event.name();
            CallbackEventNameFullyQualifed = Event.getPfmEventString();
            CallbackEventCycles = Value;
          },
          EmptyFn);
  EXPECT_EQ(CallbackEventName, "CYCLES:u");
  EXPECT_THAT(CallbackEventNameFullyQualifed, Not(IsEmpty()));
  pfmTerminate();
#else
  ASSERT_TRUE(pfmInitialize());
#endif
}

} // namespace
} // namespace pfm
} // namespace exegesis

Fix build when libpfm is not available.

[llvm-exegesis] Fix build when libpfm is not available.

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


/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/core/kernels/cwise_ops_common.h"

namespace tensorflow {
REGISTER2(BinaryOp, CPU, "Zeta", functor::zeta, float, double);
REGISTER2(BinaryOp, CPU, "Polygamma", functor::polygamma, float, double);
}  // namespace tensorflow

/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/core/kernels/cwise_ops_common.h"

namespace tensorflow {
REGISTER2(BinaryOp, CPU, "Zeta", functor::zeta, float, double);
REGISTER2(BinaryOp, CPU, "Polygamma", functor::polygamma, float, double);

#if GOOGLE_CUDA
REGISTER2(BinaryOp, GPU, "Zeta", functor::zeta, float, double);
REGISTER2(BinaryOp, GPU, "Polygamma", functor::polygamma, float, double);
#endif
}  // namespace tensorflow

Enable GPU support for Zeta and Polygamma ops.

PiperOrigin-RevId: 211082683


/*
 * Copyright 2008 The Android Open Source Project
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include <windows.h>
#include "SkThread.h"

int32_t sk_atomic_inc(int32_t* addr) {
    // InterlockedIncrement returns the new value, we want to return the old.
    return InterlockedIncrement(reinterpret_cast<LONG*>(addr)) - 1;
}

int32_t sk_atomic_dec(int32_t* addr) {
    return InterlockedDecrement(reinterpret_cast<LONG*>(addr)) + 1;
}

SkMutex::SkMutex() {
    SK_COMPILE_ASSERT(sizeof(fStorage) > sizeof(CRITICAL_SECTION),
                      NotEnoughSizeForCriticalSection);
    InitializeCriticalSection(reinterpret_cast<CRITICAL_SECTION*>(&fStorage));
}

SkMutex::~SkMutex() {
    DeleteCriticalSection(reinterpret_cast<CRITICAL_SECTION*>(&fStorage));
}

void SkMutex::acquire() {
    EnterCriticalSection(reinterpret_cast<CRITICAL_SECTION*>(&fStorage));
}

void SkMutex::release() {
    LeaveCriticalSection(reinterpret_cast<CRITICAL_SECTION*>(&fStorage));
}

/*
 * Copyright 2008 The Android Open Source Project
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include <windows.h>
#include <intrin.h>
#include "SkThread.h"

//MSDN says in order to declare an interlocked function for use as an
//intrinsic, include intrin.h and put the function in a #pragma intrinsic
//directive.
//The pragma appears to be unnecessary, but doesn't hurt.
#pragma intrinsic(_InterlockedIncrement, _InterlockedDecrement)

int32_t sk_atomic_inc(int32_t* addr) {
    // InterlockedIncrement returns the new value, we want to return the old.
    return _InterlockedIncrement(reinterpret_cast<LONG*>(addr)) - 1;
}

int32_t sk_atomic_dec(int32_t* addr) {
    return _InterlockedDecrement(reinterpret_cast<LONG*>(addr)) + 1;
}

SkMutex::SkMutex() {
    SK_COMPILE_ASSERT(sizeof(fStorage) > sizeof(CRITICAL_SECTION),
                      NotEnoughSizeForCriticalSection);
    InitializeCriticalSection(reinterpret_cast<CRITICAL_SECTION*>(&fStorage));
}

SkMutex::~SkMutex() {
    DeleteCriticalSection(reinterpret_cast<CRITICAL_SECTION*>(&fStorage));
}

void SkMutex::acquire() {
    EnterCriticalSection(reinterpret_cast<CRITICAL_SECTION*>(&fStorage));
}

void SkMutex::release() {
    LeaveCriticalSection(reinterpret_cast<CRITICAL_SECTION*>(&fStorage));
}

Use intrinsics for atomic inc and dec on Windows.
http://codereview.appspot.com/5677080/

git-svn-id: e8541e15acce502a64c929015570ad1648e548cd@3223 2bbb7eff-a529-9590-31e7-b0007b416f81


// Check existence of a key
// C++11

#include <map>
#include <string>

int main()
{
  std::map<string, int> m = {{"a", 1}, {"b", 2}, {"c", 3}};

  if (m.count("b"))
  {
     // We know "b" is in m
  }
}

// Check if a particular key is in an associative container.
//
// On [9], we create a [`std::map`](cpp/container/map) as an example
// associative container and initialise it with key-value pairs.
//
// On [11], we count the number of occurrences of the key "b" in m
// by using the memeber function [`count`](cpp/container/map/count).
// If "b" is in m, count will return 1; otherwise it will return 0.
//
// Note: in C++14, an instance of the searched key will not be created
// if the container's comparator is
// [transparent](http://stackoverflow.com/q/20317413/150634) and
// supports the appropriate comparison without conversions.

// Check existence of a key
// C++11

#include <map>
#include <string>

int main()
{
	std::map<std::string, int> m = {{"a", 1}, {"b", 2}, {"c", 3}};

	if (m.count("b"))
	{
		// We know "b" is in m
	}
}

// Check if a particular key is in an associative container.
//
// On [9], we create a [`std::map`](cpp/container/map) as an example
// associative container and initialize it with key-value pairs.
//
// On [11], we count the number of occurrences of the key `"b"` in `m`
// by using the memeber function [`count`](cpp/container/map/count).
// If `"b"` is in `m`, `count` will return 1; otherwise it will return
// 0.
//
// Note: in C++14, an instance of the searched key will not be created
// if the container's comparator is
// [transparent](http://stackoverflow.com/q/20317413/150634) and
// supports the appropriate comparison without conversions.

Make corrections to key existence sample


#include <QApplication>
#include <QQmlApplicationEngine>
#include <QDir>
#include <QFile>
#include <QFileInfo>

int main(int argc, char *argv[])
{
	QApplication app(argc, argv);

	QQmlApplicationEngine engine;

	if (argc < 2) {
		printf("Usage: OwaViewer [directory]\n");
		return 1;
	}

	QDir dirPath(argv[1]);
	QString qmlPath;

	// It's a directory
	if (QFileInfo(dirPath.path()).isDir()) {

		// Trying to read QML file in the directory
		qmlPath = dirPath.filePath("app.qml");
		if (!QFile(qmlPath).exists()) {

			qmlPath = dirPath.filePath("App.qml");
			if (!QFile(qmlPath).exists()) {
				printf("OwaNEXT Application doesn't exist.\n");
				return 1;
			}
		}
	}

	engine.load(QUrl(qmlPath));

	return app.exec();
}

#include <QApplication>
#include <QQmlApplicationEngine>
#include <QDir>
#include <QFile>
#include <QFileInfo>

int main(int argc, char *argv[])
{
	QApplication app(argc, argv);

	QQmlApplicationEngine engine;

	if (argc < 2) {
		printf("Usage: OwaViewer [directory]\n");
		printf("   or: OwaViewer [File]\n");
		return 1;
	}

	QDir dirPath(argv[1]);
	QString qmlPath;

	// It's a directory
	if (QFileInfo(dirPath.path()).isDir()) {

		// Trying to read QML file in the directory
		qmlPath = dirPath.filePath("app.qml");
		if (!QFile(qmlPath).exists()) {

			qmlPath = dirPath.filePath("App.qml");
			if (!QFile(qmlPath).exists()) {
				printf("Cannot find application in the directory.\n");
				return 1;
			}
		}
	} else {

		// Whether does the QML file exists or not?
		qmlPath = dirPath.path();
		if (!QFile(qmlPath).exists()) {
			printf("OwaNEXT Application doesn't exist.\n");
			return 1;
		}
	}

	// Run it
	engine.load(QUrl(qmlPath));

	return app.exec();
}

Support to specify single QML file by argument


#include "cameras/itf/pinhole_camera.h"

#include "core/itf/film.h"
#include "core/itf/ray.h"
#include "core/itf/sampling.h"

#include <iostream>

using namespace lb;

/// Constructs a pinhole camera, where the image plane's origin is pointed to
/// the by the look at vector relative from the camera's location. Together with
/// the look at vector, the up vector defines the camera's roll, pitch, and
/// tilt. Note: up vector should be a unit vector preferably.
PinholeCamera::PinholeCamera(std::unique_ptr<Film> film,
        const Point3d& location, const Vector3d& lookAt, const Vector3d& up):
    Camera(std::move(film), location),
    lookAt_(lookAt),
    left_(-cross(lookAt, up)),
    top_(cross(lookAt.normalize(), left_)),
    dx_(-2 * left_ / (film_->xResolution() - 1)),
    dy_(-2 * top_ / (film_->yResolution() - 1))
{
}

void PinholeCamera::calculateRay(const Sample& s, Ray& r) const
{
    r.o = location_;
    r.d = ((r.o + lookAt_ + left_ + s.imageX * dx_ + top_ + s.imageY * dy_) - r.o).normalize();
    // std::cout << r.o << "\n";
}

#include "cameras/itf/pinhole_camera.h"

#include "core/itf/film.h"
#include "core/itf/ray.h"
#include "core/itf/sampling.h"

using namespace lb;

/// Constructs a pinhole camera, where the image plane's origin is pointed to
/// the by the look at vector relative from the camera's location. Together with
/// the look at vector, the up vector defines the camera's roll, pitch, and
/// tilt. Note: up vector should be a unit vector preferably.
PinholeCamera::PinholeCamera(std::unique_ptr<Film> film,
        const Point3d& location, const Vector3d& lookAt, const Vector3d& up):
    Camera(std::move(film), location),
    lookAt_(lookAt),
    left_(-cross(lookAt, up)),
    top_(cross(lookAt.normalize(), left_)),
    dx_(-2 * left_ / (film_->xResolution() - 1)),
    dy_(-2 * top_ / (film_->yResolution() - 1))
{
}

void PinholeCamera::calculateRay(const Sample& s, Ray& r) const
{
    r.o = location_;
    r.d = ((r.o + lookAt_ + left_ + s.imageX * dx_ + top_ + s.imageY * dy_) - r.o).normalize();
}

Remove comment and redundant include

Remove comment and redundant include


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

// Various tests for -fno-exceptions

typedef __typeof(sizeof(int)) size_t;

namespace test0 {
  // rdar://problem/7878149
  class Foo {
  public:
    void* operator new(size_t x);
  private:
    void operator delete(void *x);
  };

  void test() {
    // Under -fexceptions, this does access control for the associated
    // 'operator delete'.
    (void) new Foo();
  }
}

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

// Various tests for -fno-exceptions

typedef __SIZE_TYPE__ size_t;

namespace test0 {
  // rdar://problem/7878149
  class Foo {
  public:
    void* operator new(size_t x);
  private:
    void operator delete(void *x);
  };

  void test() {
    // Under -fexceptions, this does access control for the associated
    // 'operator delete'.
    (void) new Foo();
  }
}

Use __SIZE_TYPE__ as suggested by dgregor.

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


/*
Copyright (c), Helios
All rights reserved.

Distributed under a permissive license. See COPYING.txt for details.
*/

#include "ImageViewerApplication.h"

int main(int argc, char **argv){
	try{
		initialize_supported_extensions();
		ImageViewerApplication app(argc, argv, "BorderlessViewer" + get_per_user_unique_id());
		return app.exec();
	}catch (ApplicationAlreadyRunningException &){
		return 0;
	}catch (NoWindowsException &){
		return 0;
	}
}

/*
Copyright (c), Helios
All rights reserved.

Distributed under a permissive license. See COPYING.txt for details.
*/

#include "ImageViewerApplication.h"
#include <QImageReader>

int main(int argc, char **argv){
	try{
		//Set the limit to 1 GiB.
		QImageReader::setAllocationLimit(1024);
		initialize_supported_extensions();
		ImageViewerApplication app(argc, argv, "BorderlessViewer" + get_per_user_unique_id());
		return app.exec();
	}catch (ApplicationAlreadyRunningException &){
		return 0;
	}catch (NoWindowsException &){
		return 0;
	}
}

Increase the QImageReader allocation limit.


/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
// SOComWindowPeer.cpp : Implementation of CHelpApp and DLL registration.

#include "stdafx2.h"
#include "so_activex.h"
#include "SOComWindowPeer.h"

/////////////////////////////////////////////////////////////////////////////
//

STDMETHODIMP SOComWindowPeer::InterfaceSupportsErrorInfo(REFIID riid)
{
    static const IID* arr[] =
    {
        &IID_ISOComWindowPeer,
    };

    for (int i=0;i<SAL_N_ELEMENTS(arr);i++)
    {
#if defined(_MSC_VER) && (_MSC_VER >= 1300)
        if (InlineIsEqualGUID(*arr[i],riid))
#else
        if (::ATL::InlineIsEqualGUID(*arr[i],riid))
#endif
            return S_OK;
    }
    return S_FALSE;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */

/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
// SOComWindowPeer.cpp : Implementation of CHelpApp and DLL registration.

#include "stdafx2.h"
#include "so_activex.h"
#include "SOComWindowPeer.h"

/////////////////////////////////////////////////////////////////////////////
//

STDMETHODIMP SOComWindowPeer::InterfaceSupportsErrorInfo(REFIID riid)
{
    static const IID* arr[] =
    {
        &IID_ISOComWindowPeer,
    };

    for (int i=0;i<sizeof(arr)/sizeof(arr[0]);i++)
    {
#if defined(_MSC_VER) && (_MSC_VER >= 1300)
        if (InlineIsEqualGUID(*arr[i],riid))
#else
        if (::ATL::InlineIsEqualGUID(*arr[i],riid))
#endif
            return S_OK;
    }
    return S_FALSE;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */

Revert SAL_N_ELEMENTS change for one file

This source file does not seem to include any of the usual LibreOffice
headers, so we should not use SAL_N_ELEMENTS in it.


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

#include "chrome/browser/extensions/extension_input_method_api.h"

#include "base/values.h"
#include "chrome/browser/chromeos/input_method/input_method_manager.h"
#include "chrome/browser/chromeos/extensions/input_method_event_router.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"

GetInputMethodFunction::GetInputMethodFunction() {
}

GetInputMethodFunction::~GetInputMethodFunction() {
}

bool GetInputMethodFunction::RunImpl() {
#if !defined(OS_CHROMEOS)
  NOTREACHED();
#else
  chromeos::ExtensionInputMethodEventRouter* router =
      profile_->GetExtensionService()->input_method_event_router();
  chromeos::input_method::InputMethodManager* manager =
      chromeos::input_method::InputMethodManager::GetInstance();
  const std::string input_method =
      router->GetInputMethodForXkb(manager->current_input_method().id());
  result_.reset(Value::CreateStringValue(input_method));
  return true;
#endif
}

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

#include "chrome/browser/extensions/extension_input_method_api.h"

#include "base/values.h"
#include "chrome/browser/chromeos/input_method/input_method_manager.h"
#include "chrome/browser/chromeos/extensions/input_method_event_router.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"

GetInputMethodFunction::GetInputMethodFunction() {
}

GetInputMethodFunction::~GetInputMethodFunction() {
}

bool GetInputMethodFunction::RunImpl() {
#if !defined(OS_CHROMEOS)
  NOTREACHED();
  return false;
#else
  chromeos::ExtensionInputMethodEventRouter* router =
      profile_->GetExtensionService()->input_method_event_router();
  chromeos::input_method::InputMethodManager* manager =
      chromeos::input_method::InputMethodManager::GetInstance();
  const std::string input_method =
      router->GetInputMethodForXkb(manager->current_input_method().id());
  result_.reset(Value::CreateStringValue(input_method));
  return true;
#endif
}

Fix a build error when OS_CHROMEOS is not defined.

BUG=None
TEST=Manually

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

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


#include <cstdint>

#include <Magick++/Blob.h>
#include <Magick++/Image.h>

#define FUZZ_ENCODER_STRING_LITERAL(name) #name
#define FUZZ_ENCODER FUZZ_ENCODER_STRING_LITERAL(FUZZ_IMAGEMAGICK_ENCODER)

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
  const Magick::Blob blob(Data, Size);
  Magick::Image image;
  try {
    image.magick(FUZZ_ENCODER);
    image.fileName(FUZZ_ENCODER + ':');
    image.read(blob);
  } catch (Magick::Exception &e) {
    return 0;
  }

  Magick::Blob outBlob;
  try {
    image.write(&outBlob, FUZZ_ENCODER);
  } catch (Magick::Exception &e) {
  }
  return 0;
}

#include <cstdint>

#include <Magick++/Blob.h>
#include <Magick++/Image.h>

#define FUZZ_ENCODER_STRING_LITERAL(name) #name
#define FUZZ_ENCODER FUZZ_ENCODER_STRING_LITERAL(FUZZ_IMAGEMAGICK_ENCODER)

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
  const Magick::Blob blob(Data, Size);
  Magick::Image image;
  try {
    image.read(blob, FUZZ_ENCODER);
  } catch (Magick::Exception &e) {
    return 0;
  }

  Magick::Blob outBlob;
  try {
    image.write(&outBlob, FUZZ_ENCODER);
  } catch (Magick::Exception &e) {
  }
  return 0;
}

Use new overload when reading the image.


#include <iostream>
#include <string>
#include <maproute/ip.hpp>
#include <maproute/ip_convertor.hpp>
#include <maproute/stringhelp.hpp>
#include <maproute/tr_parser.hpp>
#include <maproute/ip_location_finder.hpp>

int main() {

    IPLocationFinder finder{};

    while (std::cin.good()) {
        std::string line;
        std::string ip_string;
        IPV4Convertor convertor{};
        TracerouteLineParser parser{};
        IPV4 ip {0, 0, 0, 0};

        std::getline(std::cin, line);
        bool success = parser.parse(&line, &ip);

        if (!success) {
            std::cerr << "Failed to parse: '"
                      << line
                      << "' did the request timeout?"
                      << std::endl;
        } else {
            convertor.ip_to_string(&ip, &ip_string);
            std::cout << ip_string << std::endl;
        }
    }

    finder.close();

    return 0;

}

#include <iostream>
#include <string>
#include <maproute/ip.hpp>
#include <maproute/ip_convertor.hpp>
#include <maproute/stringhelp.hpp>
#include <maproute/tr_parser.hpp>
#include <maproute/ip_location_finder.hpp>

int main() {

    while (std::cin.good()) {
        std::string line;
        std::string ip_string;
        IPV4Convertor convertor{};
        TracerouteLineParser parser{};
        IPV4 ip {0, 0, 0, 0};

        std::getline(std::cin, line);
        bool success = parser.parse(&line, &ip);

        if (!success) {
            std::cerr << "Failed to parse: '"
                      << line
                      << "' did the request timeout?"
                      << std::endl;
        } else {
            convertor.ip_to_string(&ip, &ip_string);
            std::cout << ip_string << std::endl;
        }
    }

    return 0;

}

Remove unused finder on traceroute parse command


#include "material.hpp"

Material::Material():
        name{},
        ka{0,0,0},
        kd{0,0,0},
        ks{0,0,0},
        m{0}
        {}

Material::Material(std::string const& name, Color const& ka, Color const& kd,
                Color const& ks, float m):
        name{name},
        ka{ka},
        kd{kd},
        ks{ks},
        m{m}
        {}

std::string const& Material::getName() const {
        return name;
}

Color const& Material::getColorKa() const {
        return ka;
}

Color const& Material::getColorKd() const {
        return kd;
}

Color const& Material::getColorKs() const {
        return ks;
}

float const Material::getM() const {
        return m;
}

std::ostream& operator<<(std::ostream& os, Material const& m) {
        os << "--------" << "\n" << "Material " << "\n" << "--------" << "\n"
                << "Name: " << m.getName() << "\n" << "Colors (RGB):" << "\n"
                << "        ka: " << m.getColorKa() << "        kd: "
                << m.getColorKd() << "        ks: " << m.getColorKs()
                << "m: " << m.getM();
        return os;
}

#include "material.hpp"

Material::Material():
        name{},
        ka{0,0,0},
        kd{0,0,0},
        ks{0,0,0},
        m{0}
        {}

Material::Material(std::string const& name, Color const& ka, Color const& kd,
                Color const& ks, float m):
        name{name},
        ka{ka},
        kd{kd},
        ks{ks},
        m{m}
        {}

std::string const& Material::getName() const {
        return name;
}

Color const& Material::getColorKa() const {
        return ka;
}

Color const& Material::getColorKd() const {
        return kd;
}

Color const& Material::getColorKs() const {
        return ks;
}

float const Material::getM() const {
        return m;
}

std::ostream& operator<<(std::ostream& os, Material const& m) {
        os << "--------" << "\n" << "Material " << "\n" << "--------" << "\n"
                << "Name: " << m.getName() << "\n" << "Light coefficients:" << "\n"
                << "        ka: " << m.getColorKa() << "        kd: "
                << m.getColorKd() << "        ks: " << m.getColorKs()
                << "m: " << m.getM();
        return os;
}

Change print to match actual content of ka, kd, ks.


#include "perf_precomp.hpp"

using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;

#define MAT_TYPES_DFT  CV_32FC1, CV_64FC1
#define MAT_SIZES_DFT  sz1080p, sz2K
#define TEST_MATS_DFT  testing::Combine(testing::Values(MAT_SIZES_DFT), testing::Values(MAT_TYPES_DFT))

PERF_TEST_P(Size_MatType, dft, TEST_MATS_DFT)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());

    Mat src(sz, type);
    Mat dst(sz, type);

    declare.in(src, WARMUP_RNG).time(60);

    TEST_CYCLE() dft(src, dst);

    SANITY_CHECK(dst, 1e-5);
}

#include "perf_precomp.hpp"

using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;

#define MAT_TYPES_DFT  CV_32FC1, CV_64FC1
#define MAT_SIZES_DFT  sz1080p, sz2K
#define TEST_MATS_DFT  testing::Combine(testing::Values(MAT_SIZES_DFT), testing::Values(MAT_TYPES_DFT))

PERF_TEST_P(Size_MatType, dft, TEST_MATS_DFT)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());

    Mat src(sz, type);
    Mat dst(sz, type);

    declare.in(src, WARMUP_RNG).time(60);

    TEST_CYCLE() dft(src, dst);

    SANITY_CHECK(dst, 1e-5, ERROR_RELATIVE);
}

Change sanity check for perfomance test of dft