// RUN: %clang_cc1 -fsyntax-only -verify -ftemplate-backtrace-limit 2 %s

template<int N, typename T> struct X : X<N+1, T*> {};
// expected-error-re@3 {{recursive template instantiation exceeded maximum depth of 1024{{$}}}}
// expected-note@3 {{instantiation of template class}}
// expected-note@3 {{skipping 1023 contexts in backtrace}}
// expected-note@3 {{use -ftemplate-depth=N to increase recursive template instantiation depth}}

X<0, int> x; // expected-note {{in instantiation of}}

// RUN: %clang_cc1 -fsyntax-only -verify -ftemplate-backtrace-limit 2 %s
//
// FIXME: Disable this test when Clang was built with ASan, because ASan
// increases our per-frame stack usage enough that this test no longer fits
// within our normal stack space allocation.
// REQUIRES: not_asan

template<int N, typename T> struct X : X<N+1, T*> {};
// expected-error-re@8 {{recursive template instantiation exceeded maximum depth of 1024{{$}}}}
// expected-note@8 {{instantiation of template class}}
// expected-note@8 {{skipping 1023 contexts in backtrace}}
// expected-note@8 {{use -ftemplate-depth=N to increase recursive template instantiation depth}}

X<0, int> x; // expected-note {{in instantiation of}}

Disable test under asan: it uses a lot of stack, and asan increases the per-frame stack usage enough to cause it to hit our stack limit. This is not ideal; we should find a better way of dealing with this, such as increasing our stack allocation when built with ASan.


// Qt includes
#include <QDebug>

// Visomics includes
#include "voAnalysis.h"
#include "voAnalysisFactory.h"
#include "voQObjectFactory.h"

#include "voPCAStatistics.h"

//----------------------------------------------------------------------------
class voAnalysisFactoryPrivate
{
public:
  voQObjectFactory<voAnalysis> AnalysisFactory;
};

//----------------------------------------------------------------------------
// voAnalysisFactoryPrivate methods

//----------------------------------------------------------------------------
// voAnalysisFactory methods

//----------------------------------------------------------------------------
voAnalysisFactory::voAnalysisFactory():d_ptr(new voAnalysisFactoryPrivate)
{
  this->registerAnalysis<voPCAStatistics>("pca");
}

//-----------------------------------------------------------------------------
voAnalysisFactory::~voAnalysisFactory()
{
}

//-----------------------------------------------------------------------------
voAnalysis* voAnalysisFactory::createAnalysis(const QString& className)
{
  Q_D(voAnalysisFactory);
  return d->AnalysisFactory.Create(className);
}

//-----------------------------------------------------------------------------
QStringList voAnalysisFactory::registeredAnalysisNames() const
{
  Q_D(const voAnalysisFactory);
  return d->AnalysisFactory.registeredObjectKeys();
}

//-----------------------------------------------------------------------------
template<typename AnalysisClassType>
void voAnalysisFactory::registerAnalysis(const QString& analysisName)
{
  Q_D(voAnalysisFactory);

  if (analysisName.isEmpty())
    {
    qCritical() << "Failed to register analysis - analysisName is an empty string";
    return;
    }

  if (this->registeredAnalysisNames().contains(analysisName))
    {
    return;
    }

  d->AnalysisFactory.registerObject<AnalysisClassType>(analysisName);
}

// Qt includes
#include <QDebug>

// Visomics includes
#include "voAnalysis.h"
#include "voAnalysisFactory.h"
#include "voQObjectFactory.h"

#include "voPCAStatistics.h"

//----------------------------------------------------------------------------
class voAnalysisFactoryPrivate
{
public:
  voQObjectFactory<voAnalysis> AnalysisFactory;
};

//----------------------------------------------------------------------------
// voAnalysisFactoryPrivate methods

//----------------------------------------------------------------------------
// voAnalysisFactory methods

//----------------------------------------------------------------------------
voAnalysisFactory::voAnalysisFactory():d_ptr(new voAnalysisFactoryPrivate)
{
  this->registerAnalysis<voPCAStatistics>("PCA");
}

//-----------------------------------------------------------------------------
voAnalysisFactory::~voAnalysisFactory()
{
}

//-----------------------------------------------------------------------------
voAnalysis* voAnalysisFactory::createAnalysis(const QString& className)
{
  Q_D(voAnalysisFactory);
  return d->AnalysisFactory.Create(className);
}

//-----------------------------------------------------------------------------
QStringList voAnalysisFactory::registeredAnalysisNames() const
{
  Q_D(const voAnalysisFactory);
  return d->AnalysisFactory.registeredObjectKeys();
}

//-----------------------------------------------------------------------------
template<typename AnalysisClassType>
void voAnalysisFactory::registerAnalysis(const QString& analysisName)
{
  Q_D(voAnalysisFactory);

  if (analysisName.isEmpty())
    {
    qCritical() << "Failed to register analysis - analysisName is an empty string";
    return;
    }

  if (this->registeredAnalysisNames().contains(analysisName))
    {
    return;
    }

  d->AnalysisFactory.registerObject<AnalysisClassType>(analysisName);
}

Change analysis name from "pca" to "PCA"


/** @file
    @brief Implementation

    @date 2014

    @author
    Ryan Pavlik
    <ryan@sensics.com>
    <http://sensics.com>

*/

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

// Internal Includes
#include <ogvr/PluginKit/PluginRegistrationC.h>

// Library/third-party includes
// - none

// Standard includes
// - none

OGVR_PLUGIN(org_opengoggles_example_NullTracker) { return LIBFUNC_SUCCESS; }

/** @file
    @brief Implementation

    @date 2014

    @author
    Ryan Pavlik
    <ryan@sensics.com>
    <http://sensics.com>

*/

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

// Internal Includes
#include <ogvr/PluginKit/PluginRegistrationC.h>

// Library/third-party includes
// - none

// Standard includes
// - none

OGVR_PLUGIN(org_opengoggles_example_NullTracker) { return OGVR_PLUGIN_SUCCESS; }

Use consistent symbols in example


#include <signal.h>
#include <unistd.h>
#include "mraa.hpp"

bool running = true;
bool relay_state = false;
int last_touch;
void sig_handler(int signo)
{
        if (signo == SIGINT)
                running = false;
}
int main(int argc, char* argv[])
{
        mraa::Gpio* touch_gpio = new mraa::Gpio(492);
        mraa::Gpio* relay_gpio = new mraa::Gpio(463);
        mraa::Result response;
        int touch;

        signal(SIGINT, sig_handler);

        response = touch_gpio->dir(mraa::DIR_IN);
        if (response != mraa::SUCCESS)
                return 1;
        response = relay_gpio->dir(mraa::DIR_OUT);
        if (response != mraa::SUCCESS)
                return 1;

        relay_gpio->write(relay_state);

        while (running) {
                touch = touch_gpio->read();
                if (touch == 1 && last_touch == 0) {
                        relay_state = !relay_state;
                        response = relay_gpio->write(relay_state);
                        usleep(100000);
                }
                last_touch = touch;
        }
        delete relay_gpio;
        delete touch_gpio;
        return response;
}

#include <signal.h>
#include <unistd.h>
#include "mraa.hpp"

bool running = true;
bool relay_state = false;
int last_touch;
void sig_handler(int signo)
{
        if (signo == SIGINT)
                running = false;
}
int main(int argc, char* argv[])
{
        mraa::Gpio* touch_gpio = new mraa::Gpio(29);
        mraa::Gpio* relay_gpio = new mraa::Gpio(27);
        mraa::Result response;
        int touch;

        signal(SIGINT, sig_handler);

        response = touch_gpio->dir(mraa::DIR_IN);
        if (response != mraa::SUCCESS)
                return 1;
        response = relay_gpio->dir(mraa::DIR_OUT);
        if (response != mraa::SUCCESS)
                return 1;

        relay_gpio->write(relay_state);

        while (running) {
                touch = touch_gpio->read();
                if (touch == 1 && last_touch == 0) {
                        relay_state = !relay_state;
                        response = relay_gpio->write(relay_state);
                        usleep(100000);
                }
                last_touch = touch;
        }
        delete relay_gpio;
        delete touch_gpio;
        return response;
}

Fix GPIO pin numbers to match MRAA change


/*
    Copyright (C) 2008 Patrick Spendrin <ps_ml@gmx.de>

    This file is part of the KDE project

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

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

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

#include "GeoSceneXmlDataSource.h"

#include "global.h"

namespace Marble
{

GeoSceneXmlDataSource::GeoSceneXmlDataSource( const QString& name )
    : GeoSceneAbstractDataset( name )
{
}

GeoSceneXmlDataSource::~GeoSceneXmlDataSource()
{
}

QString GeoSceneXmlDataSource::filename() const
{
    return m_filename;
}

void GeoSceneXmlDataSource::setFilename( const QString& fileName )
{
    m_filename = fileName;
}

QString GeoSceneXmlDataSource::type()
{
    return "xmldatasource";
}

}

Check that file ends with a newline (1 issue)


#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE DummyClassTest
#include <boost/test/unit_test.hpp>
#include "../DummyClass/DummyClass.h"

BOOST_AUTO_TEST_SUITE(FirstSuite)

BOOST_AUTO_TEST_CASE( my_test1 )
{
  DummyClass obj;
  BOOST_REQUIRE_EQUAL(&obj, &obj);
  BOOST_REQUIRE_EQUAL(1, 1);
}

BOOST_AUTO_TEST_SUITE_END()

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE DummyClassTest
#include <boost/test/unit_test.hpp>
#include "./DummyClass/DummyClass.h"

BOOST_AUTO_TEST_SUITE(FirstSuite)

BOOST_AUTO_TEST_CASE( my_test1 )
{
  DummyClass obj;
  BOOST_REQUIRE_EQUAL(&obj, &obj);
  BOOST_REQUIRE_EQUAL(1, 1);
}

BOOST_AUTO_TEST_SUITE_END()

Change ../ to ./ in includes


#include <sstream>
#include <string>
#include <ccspec/matcher.h>

namespace ccspec {
namespace matchers {

// Public methods.

template <typename U>
template <typename V>
bool Eq<U>::match(V actual_value) const {
    return actual_value == this->expected_value();
}

template <typename U>
std::string Eq<U>::desc() const {
    std::ostringstream s;
    s << "should equal " << this->expected_value();
    return s.str();
}

// Private methods.

template<typename U>
Eq<U>::Eq(U expected_value) : Matcher<Eq<U>, U>(expected_value) {}

// Friend functions.

template<typename U>
Eq<U> eq(U expected_value) {
    return Eq<U>(expected_value);
}

} // namespace matchers
} // namespace ccspec

#include <sstream>

namespace ccspec {
namespace matchers {

// Public methods.

template <typename U>
template <typename V>
bool Eq<U>::match(V actual_value) const {
    return actual_value == this->expected_value();
}

template <typename U>
std::string Eq<U>::desc() const {
    std::ostringstream s;
    s << "should equal " << this->expected_value();
    return s.str();
}

// Private methods.

template<typename U>
Eq<U>::Eq(U expected_value) : Matcher<Eq<U>, U>(expected_value) {}

// Friend functions.

template<typename U>
Eq<U> eq(U expected_value) {
    return Eq<U>(expected_value);
}

} // namespace matchers
} // namespace ccspec

Remove unnecessary includes in template .cc


#ifdef _MSC_VER
#include "All.h"
#include "Common.cpp"
#include "WhisperPeer.cpp"
#endif

Disable SCUs on non MSVC builds.


/*
  Copyright (c) 2014-2015 DataStax

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

#define BOOST_TEST_MODULE cassandra

#include "test_utils.hpp"

#include <boost/test/unit_test.hpp>

using test_utils::CassLog;

BOOST_GLOBAL_FIXTURE(CassLog);

Fix required for Boost v1.59.0; missing semicolon


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

#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebSocket) {
  FilePath websocket_root_dir;
  PathService::Get(chrome::DIR_TEST_DATA, &websocket_root_dir);
  websocket_root_dir = websocket_root_dir.AppendASCII("layout_tests")
      .AppendASCII("LayoutTests");
  ui_test_utils::TestWebSocketServer server(websocket_root_dir);
  ASSERT_TRUE(RunExtensionTest("websocket")) << message_;
}

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

#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"

// Disable this test on Linux, because it fails
// http://crbug.com/40976
#if defined(OS_LINUX)
#define WebSocket DISABLED_WebSocket
#endif

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebSocket) {
  FilePath websocket_root_dir;
  PathService::Get(chrome::DIR_TEST_DATA, &websocket_root_dir);
  websocket_root_dir = websocket_root_dir.AppendASCII("layout_tests")
      .AppendASCII("LayoutTests");
  ui_test_utils::TestWebSocketServer server(websocket_root_dir);
  ASSERT_TRUE(RunExtensionTest("websocket")) << message_;
}

Disable this test on Linux, because it will fail as soon as WebKit's version is rolled forward.


#include "xchainer/testing/numeric.h"

#include <cassert>

#include "xchainer/dtype.h"
#include "xchainer/error.h"
#include "xchainer/scalar.h"

namespace xchainer {
namespace testing {

bool AllClose(const Array& a, const Array& b, double rtol, double atol) {
    if (a.shape() != b.shape()) {
        throw DimensionError("cannot compare Arrays of different shapes");
    }
    if (a.dtype() != b.dtype()) {
        throw DtypeError("cannot compare Arrays of different Dtypes");
    }
    return VisitDtype(a.dtype(), [&](auto pt) {
        using T = typename decltype(pt)::type;

        auto total_size = a.shape().total_size();
        auto adata = static_cast<const T*>(a.data().get());
        auto bdata = static_cast<const T*>(b.data().get());
        auto at = static_cast<const T>(atol);
        auto rt = static_cast<const T>(rtol);
        for (decltype(total_size) i = 0; i < total_size; i++) {
            if (std::abs(adata[i] - bdata[i]) > at + rt * std::abs(bdata[i])) {
                return false;
            }
        }
        return true;
    });
}

}  // namespace testing
}  // namespace xchainer

#include "xchainer/testing/numeric.h"

#include <cassert>

#include "xchainer/dtype.h"
#include "xchainer/error.h"
#include "xchainer/scalar.h"

namespace xchainer {
namespace testing {

bool AllClose(const Array& a, const Array& b, double rtol, double atol) {
    if (a.shape() != b.shape()) {
        throw DimensionError("cannot compare Arrays of different shapes");
    }
    if (a.dtype() != b.dtype()) {
        throw DtypeError("cannot compare Arrays of different Dtypes");
    }
    return VisitDtype(a.dtype(), [&](auto pt) {
        using T = typename decltype(pt)::type;

        auto total_size = a.shape().total_size();
        auto* adata = static_cast<const T*>(a.data().get());
        auto* bdata = static_cast<const T*>(b.data().get());
        for (decltype(total_size) i = 0; i < total_size; i++) {
            if (std::abs(adata[i] - bdata[i]) > atol + rtol * std::abs(bdata[i])) {
                return false;
            }
        }
        return true;
    });
}

}  // namespace testing
}  // namespace xchainer

Remove old and unnecessary cast


// Copyright (c) Arduino. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#include <time.h>
#include <sys/time.h>

#include <RTCZero.h>

RTCZero rtc;

extern "C" {
    int _gettimeofday(struct timeval* tp, void* /*tzvp*/)
    {
        struct tm tm;

        tm.tm_isdst = -1;
        tm.tm_yday = 0;
        tm.tm_wday = 0;
        tm.tm_year = rtc.getYear() + 100;
        tm.tm_mon = rtc.getMonth() + 1;
        tm.tm_mday = rtc.getDay();
        tm.tm_hour = rtc.getHours();
        tm.tm_min = rtc.getMinutes();
        tm.tm_sec = rtc.getSeconds();

        tp->tv_sec = mktime(&tm);
        tp->tv_usec = 0;

        return 0;
    }

    int settimeofday(const struct timeval* tp, const struct timezone* /*tzp*/)
    {
        struct tm* tmp = gmtime(&tp->tv_sec);

        rtc.begin();
        rtc.setDate(tmp->tm_mday, tmp->tm_mon - 1, tmp->tm_year - 100);
        rtc.setTime(tmp->tm_hour, tmp->tm_min, tmp->tm_sec);

        return 0;
    }
}

// Copyright (c) Arduino. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#include <time.h>
#include <sys/time.h>

#include <RTCZero.h>

RTCZero rtc;

extern "C" {
    int _gettimeofday(struct timeval* tp, void* /*tzvp*/)
    {
        tp->tv_sec = rtc.getEpoch();
        tp->tv_usec = 0;

        return 0;
    }

    int settimeofday(const struct timeval* tp, const struct timezone* /*tzp*/)
    {
        rtc.begin();
        rtc.setEpoch(tp->tv_sec);

        return 0;
    }
}

Use new RTCZero epoch API's


//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2009      Eckhart Wörner <ewoerner@kde.org>
//

#include "GpsdConnection.h"

#include "MarbleDebug.h"

using namespace Marble;

GpsdConnection::GpsdConnection( QObject* parent )
    : QObject( parent ),
      m_timer( 0 )
{
    gps_data_t* data = m_gpsd.open();
    if ( data ) {
        connect( &m_timer, SIGNAL( timeout() ), this, SLOT( update() ) );
        m_timer.start( 1000 );
    } else
        mDebug() << "Connection to gpsd failed, no position info available.";
}

void GpsdConnection::update()
{
    gps_data_t* data = m_gpsd.query( "o" );
    if ( data )
        emit gpsdInfo( *data );
}

#include "GpsdConnection.moc"

//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2009      Eckhart Wörner <ewoerner@kde.org>
//

#include "GpsdConnection.h"

#include "MarbleDebug.h"

using namespace Marble;

GpsdConnection::GpsdConnection( QObject* parent )
    : QObject( parent ),
      m_timer( 0 )
{
    gps_data_t* data = m_gpsd.open();
    if ( data ) {
#if GPSD_API_MAJOR_VERSION == 3
        m_gpsd.stream( WATCH_ENABLE );
#endif
        connect( &m_timer, SIGNAL( timeout() ), this, SLOT( update() ) );
        m_timer.start( 1000 );
    } else
        mDebug() << "Connection to gpsd failed, no position info available.";
}

void GpsdConnection::update()
{
    gps_data_t* data;
#if GPSD_API_MAJOR_VERSION == 2
    data = m_gpsd.query( "o" );
#elif GPSD_API_MAJOR_VERSION == 3
    while ((data = m_gpsd.poll()) && !(data->set & POLICY_SET)) {
        data = m_gpsd.poll();
    }
#endif
    if ( data )
        emit gpsdInfo( *data );
}

#include "GpsdConnection.moc"

Make gpsd positionprovider plugin compile with gpsd API 3, as of gpsd 2.90+.


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

#include "catch.hpp"
#include "helpers.hpp"

#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/result/delete.hpp>

TEST_CASE("delete", "[delete][result]") {
    bsoncxx::builder::stream::document build;
    build << "_id" << bsoncxx::oid{bsoncxx::oid::init_tag} << "nRemoved"
          << bsoncxx::types::b_int64{1};

    mongocxx::result::bulk_write b(bsoncxx::document::value(build.view()));

    mongocxx::result::delete_result delete_result(std::move(b));

    SECTION("returns correct removed count") {
        std::cout << bsoncxx::to_json(build.view());
        REQUIRE(delete_result.deleted_count() == 1);
    }
}

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

#include "catch.hpp"
#include "helpers.hpp"

#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/result/delete.hpp>

TEST_CASE("delete", "[delete][result]") {
    bsoncxx::builder::stream::document build;
    build << "_id" << bsoncxx::oid{bsoncxx::oid::init_tag} << "nRemoved"
          << bsoncxx::types::b_int64{1};

    mongocxx::result::bulk_write b(bsoncxx::document::value(build.view()));

    mongocxx::result::delete_result delete_result(std::move(b));

    SECTION("returns correct removed count") {
        REQUIRE(delete_result.deleted_count() == 1);
    }
}

Remove rogue print statement from test


/*
**  Copyright (C) - Triton
**
**  This program is under the terms of the LGPLv3 License.
*/

#include <iostream>

#include <Syscalls.h>
#include <TritonTypes.h>

extern const char *syscallmap[];

const char *syscallNumberLinux64ToString(uint64 syscallNumber) {
  if (syscallNumber > 0 && syscallNumber < (uint64) NB_SYSCALL)
    return syscallmap[syscallNumber];
  else
    return nullptr;
}

/*
**  Copyright (C) - Triton
**
**  This program is under the terms of the LGPLv3 License.
*/

#include <iostream>

#include <Syscalls.h>
#include <TritonTypes.h>

extern const char *syscallmap[];

const char *syscallNumberLinux64ToString(uint64 syscallNumber) {
  if (syscallNumber >= 0 && syscallNumber < (uint64) NB_SYSCALL)
    return syscallmap[syscallNumber];
  else
    return nullptr;
}

Fix - Failed to returns the syscall names


// Test that LargeAllocator unpoisons memory before releasing it to the OS.
// RUN: %clangxx_asan %s -o %t
// The memory is released only when the deallocated chunk leaves the quarantine,
// otherwise the mmap(p, ...) call overwrites the malloc header.
// RUN: ASAN_OPTIONS=quarantine_size=1 %t

#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>

int main() {
  const int kPageSize = 4096;
  void *p = NULL;
  posix_memalign(&p, kPageSize, 1024 * 1024);
  free(p);

  char *q = (char *)mmap(p, kPageSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON | MAP_FIXED, 0, 0);
  assert(q == p);

  memset(q, 42, kPageSize);

  munmap(q, kPageSize);
  return 0;
}

// Test that LargeAllocator unpoisons memory before releasing it to the OS.
// RUN: %clangxx_asan %s -o %t
// The memory is released only when the deallocated chunk leaves the quarantine,
// otherwise the mmap(p, ...) call overwrites the malloc header.
// RUN: ASAN_OPTIONS=quarantine_size=1 %t

#include <assert.h>
#include <malloc.h>
#include <string.h>
#include <sys/mman.h>

int main() {
  const int kPageSize = 4096;
  void *p = memalign(kPageSize, 1024 * 1024);
  free(p);

  char *q = (char *)mmap(p, kPageSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON | MAP_FIXED, 0, 0);
  assert(q == p);

  memset(q, 42, kPageSize);

  munmap(q, kPageSize);
  return 0;
}

Replace posix_memalign with memalign in test.


// Test that we use the suppressions from __asan_default_suppressions.
// RUN: %clangxx_asan %s -o %t && not %run %t 2>&1 | FileCheck %s
extern "C" {
  const char *__asan_default_suppressions() { return "FooBar"; }
}
// CHECK: AddressSanitizer: failed to parse suppressions
int main() {}
// Test that we use the suppressions from __asan_default_suppressions.
// RUN: %clangxx_asan %s -o %t && not %run %t 2>&1 | FileCheck %s
extern "C" {
  const char *__asan_default_suppressions() { return "FooBar"; }
}
// CHECK: AddressSanitizer: failed to parse suppressions
int main() {}

Fix duplicate test code introduced by running "patch -p0" twice


#include <tests.hh>

BEGIN_TEST(values, client, )
client.setErrorCallback(callback(&dump));
client.setCallback(callback(&dump), "output");

client.send("output << 1;");
//= D output 1
client.send("output << \"coin\";");
//= D output "coin"
client.send("error << non.existent;");
//= E error 1.39-50: Unknown identifier: non.existent
//= E error 1.39-50: EXPR evaluation failed
client.send("var mybin = BIN 10 mybin header;1234567890;output << mybin;");
//= D output BIN 10  mybin header;1234567890
client.send("output << [\"coin\", 5, [3, mybin, 0]];");
//= D output ["coin", 5, [3, BIN 10  mybin header;1234567890, 0]]
sleep(5);
END_TEST

#include <tests.hh>

BEGIN_TEST(values, client, )
client.setErrorCallback(callback(&dump));
client.setCallback(callback(&dump), "output");

client.send("output << 1;");
//= D output 1
client.send("output << \"coin\";");
//= D output "coin"
client.send("error << nonexistent;");
//= E error 1.39-49: lookup failed: nonexistent
client.send("var mybin = BIN 10 mybin header;1234567890;output << mybin;");
//= D output BIN 10  mybin header;1234567890
client.send("output << [\"coin\", 5, [3, mybin, 0]];");
//= D output ["coin", 5, [3, BIN 10  mybin header;1234567890, 0]]
sleep(5);
END_TEST

Update test output to k2.


/*
 * User.cpp
 *
 *  Created on: May 1, 2017
 *      Author: Daniel
 */

#include "User.hpp"

using namespace std;

User::User(string cuname, string chash)
{
	uname = cuname;
	hash = chash;
	commandfd = 0;
	mediafd = 0;
	sessionkey = 0;
}

User::~User()
{
	// TODO Auto-generated destructor stub
}

string User::getUname()
{
	return uname;
}

string User::getHash()
{
	return hash;
}

uint32_t User::getCommandfd()
{
	return commandfd;
}

void User::setCommandfd(uint32_t newCommandfd)
{
	if(newCommandfd > 4)
	{
		commandfd = newCommandfd;
	}
}

uint32_t User::getMediafd()
{
	return mediafd;
}

void User::setMediafd(uint32_t newMediafd)
{
	if(newMediafd > 4)
	{
		mediafd = newMediafd;
	}
}

uint64_t User::getSessionkey()
{
	return sessionkey;
}

void User::setSessionkey(uint64_t newSessionkey)
{
	sessionkey = newSessionkey;
}

/*
 * User.cpp
 *
 *  Created on: May 1, 2017
 *      Author: Daniel
 */

#include "User.hpp"

using namespace std;

User::User(string cuname, string chash)
{
	uname = cuname;
	hash = chash;
	commandfd = 0;
	mediafd = 0;
	sessionkey = 0;
}

User::~User()
{
	// TODO Auto-generated destructor stub
}

string User::getUname()
{
	return uname;
}

string User::getHash()
{
	return hash;
}

uint32_t User::getCommandfd()
{
	return commandfd;
}

void User::setCommandfd(uint32_t newCommandfd)
{

	commandfd = newCommandfd;
}

uint32_t User::getMediafd()
{
	return mediafd;
}

void User::setMediafd(uint32_t newMediafd)
{

	mediafd = newMediafd;
}

uint64_t User::getSessionkey()
{
	return sessionkey;
}

void User::setSessionkey(uint64_t newSessionkey)
{
	sessionkey = newSessionkey;
}

Remove check that causes more harm than good.


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

#include "chrome/browser/extensions/extension_apitest.h"
#include "net/base/mock_host_resolver.h"

// This test failed at times on the Vista dbg builder and has been marked as
// flaky for now. Bug http://code.google.com/p/chromium/issues/detail?id=28630
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_ExecuteScript) {
  // We need a.com to be a little bit slow to trigger a race condition.
  host_resolver()->AddRuleWithLatency("a.com", "127.0.0.1", 500);
  host_resolver()->AddRule("b.com", "127.0.0.1");
  host_resolver()->AddRule("c.com", "127.0.0.1");
  StartHTTPServer();

  ASSERT_TRUE(RunExtensionTest("executescript/basic")) << message_;
  ASSERT_TRUE(RunExtensionTest("executescript/in_frame")) << message_;
  ASSERT_TRUE(RunExtensionTest("executescript/permissions")) << message_;
}

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

#include "chrome/browser/extensions/extension_apitest.h"
#include "net/base/mock_host_resolver.h"

// EXTREMELY flaky, crashy, and bad. See http://crbug.com/28630 and don't dare
// to re-enable without a real fix or at least adding more debugging info.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_ExecuteScript) {
  // We need a.com to be a little bit slow to trigger a race condition.
  host_resolver()->AddRuleWithLatency("a.com", "127.0.0.1", 500);
  host_resolver()->AddRule("b.com", "127.0.0.1");
  host_resolver()->AddRule("c.com", "127.0.0.1");
  StartHTTPServer();

  ASSERT_TRUE(RunExtensionTest("executescript/basic")) << message_;
  ASSERT_TRUE(RunExtensionTest("executescript/in_frame")) << message_;
  ASSERT_TRUE(RunExtensionTest("executescript/permissions")) << message_;
}

Mark ExtensionApiTest.ExecuteScript DISABLED because it's not only flaky, but crashy and it has been ignored for weeks!


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

#include "acceptor.h"
#include <vespa/vespalib/net/socket_spec.h>
#include <functional>
#ifdef __APPLE__
#include <poll.h>
#endif

namespace vespalib::ws {

void
Acceptor::accept_main(Handler<Socket> &socket_handler)
{
#ifdef __APPLE__
    _server_socket.set_blocking(false);
#endif
    while (!_is_closed) {
#ifdef __APPLE__
        pollfd fds;
        fds.fd = _server_socket.get_fd();
        fds.events = POLLIN;
        fds.revents = 0;
        int res = poll(&fds, 1, 10);
        if (res < 1 || fds.revents == 0 || _is_closed) {
            continue;
        }
#endif
        SocketHandle handle = _server_socket.accept();
        if (handle.valid()) {
#ifdef __APPLE__
            handle.set_blocking(true);
#endif
            socket_handler.handle(std::make_unique<SimpleSocket>(std::move(handle)));
        }
    }
}

Acceptor::Acceptor(int port_in, Handler<Socket> &socket_handler)
    : _server_socket(port_in),
      _is_closed(false),
      _accept_thread(&Acceptor::accept_main, this, std::ref(socket_handler))
{
}

Acceptor::~Acceptor()
{
    _server_socket.shutdown();
    _is_closed = true;
    _accept_thread.join();
}

} // namespace vespalib::ws

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

#include "acceptor.h"
#include <vespa/vespalib/net/socket_spec.h>
#include <functional>

namespace vespalib::ws {

void
Acceptor::accept_main(Handler<Socket> &socket_handler)
{
    while (!_is_closed) {
        SocketHandle handle = _server_socket.accept();
        if (handle.valid()) {
            socket_handler.handle(std::make_unique<SimpleSocket>(std::move(handle)));
        }
    }
}

Acceptor::Acceptor(int port_in, Handler<Socket> &socket_handler)
    : _server_socket(port_in),
      _is_closed(false),
      _accept_thread(&Acceptor::accept_main, this, std::ref(socket_handler))
{
}

Acceptor::~Acceptor()
{
    _server_socket.shutdown();
    _is_closed = true;
    _accept_thread.join();
}

} // namespace vespalib::ws

Revert "Avoid hang in vepalib::ws::Acceptor::accept_main on systems where"


// RUN: rm -rf %t
// RUN: %clang_cc1 -triple %itanium_abi_triple -fmodules -fmodules-cache-path=%t %s -emit-llvm -o - | FileCheck %s

// CHECK: @_Z3varIiE = {{.*}} %union.union_type { i8 1 },

#pragma clang module build bar
module bar {
  header "bar.h" { size 40 mtime 0 }
  export *
}
#pragma clang module contents
#pragma clang module begin bar
union union_type {
  char h{1};
};
#pragma clang module end
#pragma clang module endbuild
#pragma clang module build foo
module foo {
  header "foo.h" { size 97 mtime 0 }
  export *
}
#pragma clang module contents
#pragma clang module begin foo
union union_type {
  char h{1};
};
#pragma clang module import bar
template<typename T>
union_type var;
#pragma clang module end
#pragma clang module endbuild
#pragma clang module import foo
int main() {
  (void)&var<int>;
}

// RUN: rm -rf %t
// RUN: %clang_cc1 -triple %itanium_abi_triple -fmodules -fmodules-cache-path=%t %s -emit-llvm -o - | FileCheck %s

// CHECK: @{{.*var.*}} = {{.*}} %union.union_type { i8 1 },

#pragma clang module build bar
module bar {
  header "bar.h" { size 40 mtime 0 }
  export *
}
#pragma clang module contents
#pragma clang module begin bar
union union_type {
  char h{1};
};
#pragma clang module end
#pragma clang module endbuild
#pragma clang module build foo
module foo {
  header "foo.h" { size 97 mtime 0 }
  export *
}
#pragma clang module contents
#pragma clang module begin foo
union union_type {
  char h{1};
};
#pragma clang module import bar
template<typename T>
union_type var;
#pragma clang module end
#pragma clang module endbuild
#pragma clang module import foo
int main() {
  (void)&var<int>;
}

Fix r361428 for Windows buildbots/mangling


#include <iostream>

int main(int argc, char* argv[])
{
}

#include <functional>
#include <type_traits>
#include <iostream>

int main(int argc, char* argv [])
{
	auto f_1 = [](int x) { return x; };
	std::cout << "auto f_1 = [](int x) { return x; };\n";

	auto f_2 = [](int x, int y) { return x + y; };
	std::cout << "auto f_2 = [](int x, int y) { return x + y; };\n";

	std::cout << "\n";

	std::cout << "std::is_constructible<std::function<int(int)>, decltype(f_1)>::value "
		<< std::is_constructible<std::function<int(int)>, decltype(f_1)>::value << "\n";

	std::cout << "std::is_constructible<std::function<int(int)>, decltype(f_2)>::value "
		<< std::is_constructible<std::function<int(int)>, decltype(f_2)>::value << "\n";

	std::cout << "\n";

	std::cout << "std::is_constructible<std::function<int(int,int)>, decltype(f_1)>::value "
		<< std::is_constructible<std::function<int(int, int)>, decltype(f_1)>::value << "\n";

	std::cout << "std::is_constructible<std::function<int(int,int)>, decltype(f_2)>::value "
		<< std::is_constructible<std::function<int(int, int)>, decltype(f_2)>::value << "\n";

	std::function<int(int)> f_i_i(f_1);
	//std::function<int(int)> f_i_ii(f_2); // does not compile as it is not constructible

	//std::function<int(int,int)> f_ii_i(f_1); // does not compile as it is not constructible
	std::function<int(int,int)> f_ii_ii(f_2);

	return 0;
}

Add source for demo of odd VS 2013 behaviour


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

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

#if defined(TOOLKIT_VIEWS)
#define MAYBE_Infobars Infobars
#elif defined(OS_MACOSX)
// Temporarily marking as FAILS. See http://crbug.com/60990 for details.
#define MAYBE_Infobars FAILS_Infobars
#else
// Need to finish port to Linux. See http://crbug.com/39916 for details.
#define MAYBE_Infobars DISABLED_Infobars
#endif

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) {
  // TODO(finnur): Remove once infobars are no longer experimental (bug 39511).
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

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

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

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

#if defined(TOOLKIT_VIEWS) || defined(OS_MACOSX)
#define MAYBE_Infobars Infobars
#else
// Need to finish port to Linux. See http://crbug.com/39916 for details.
#define MAYBE_Infobars DISABLED_Infobars
#endif

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) {
  // TODO(finnur): Remove once infobars are no longer experimental (bug 39511).
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

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

Revert 64157 - Marking ExtensionApiTest.Infobars as FAILS until 10.5 issue is resolved. Reverting in order to create a proper CL for it. BUG=60990


// RUN: %clang_cc1 -fsyntax-only -verify %s -std=c++0x

struct  S {
	int i;

	int mem(int);
};

int foo(int S::* ps, S *s)
{
    return (s->*ps)(1); // expected-error {{called object type 'int' is not a function or function pointer}}
}

struct S2 {
  int bitfield : 1;
};

int S2::*pf = &S2::bitfield; // expected-error {{address of bit-field requested}}

struct S3 {
  void m();
};

void f3(S3* p, void (S3::*m)()) {
    p->*m; // expected-error {{a bound member function may only be called}}
    (void)(p->*m); // expected-error {{a bound member function may only be called}}
    (void)(void*)(p->*m); // expected-error {{a bound member function may only be called}}
    (void)reinterpret_cast<void*>(p->*m); // expected-error {{a bound member function may only be called}}
    if (p->*m) {} // expected-error {{a bound member function may only be called}}

    p->m; // expected-error {{a bound member function may only be called}}
}

// RUN: %clang_cc1 -fsyntax-only -verify %s -std=c++0x

struct  S {
	int i;

	int mem(int);
};

int foo(int S::* ps, S *s)
{
    return (s->*ps)(1); // expected-error {{called object type 'int' is not a function or function pointer}}
}

struct S2 {
  int bitfield : 1;
};

int S2::*pf = &S2::bitfield; // expected-error {{address of bit-field requested}}

struct S3 {
  void m();
};

void f3(S3* p, void (S3::*m)()) {
    p->*m; // expected-error {{a bound member function may only be called}}
    (void)(p->*m); // expected-error {{a bound member function may only be called}}
    (void)(void*)(p->*m); // expected-error {{a bound member function may only be called}}
    (void)reinterpret_cast<void*>(p->*m); // expected-error {{a bound member function may only be called}}
    if (p->*m) {} // expected-error {{a bound member function may only be called}}
    if (!p->*m) {} // expected-error {{a bound member function may only be called}}
    if (p->m) {}; // expected-error {{a bound member function may only be called}}
    if (!p->m) {}; // expected-error {{a bound member function may only be called}}
}

Add a test for !ptr-to-member (should fail)


// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2016-2017 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 <common.cxx>

#include <kernel/os.hpp>

CASE("version() returns string representation of OS version")
{
  EXPECT(OS::version() != "");
  EXPECT(OS::version().front() == 'v');
}

CASE("cycles_since_boot() returns clock cycles since boot")
{
  EXPECT(OS::cycles_since_boot() != 0ull);
}

CASE("page_size() returns page size")
{
  EXPECT(OS::page_size() == 4096u);
}

CASE("page_nr_from_addr() returns page number from address")
{
  EXPECT(OS::page_nr_from_addr(512) == 0u);
}

// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2016-2017 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 <common.cxx>
#include <kernel/os.hpp>

CASE("version() returns string representation of OS version")
{
  EXPECT(OS::version() != "");
  EXPECT(OS::version().front() == 'v');
}

CASE("cycles_since_boot() returns clock cycles since boot")
{
  EXPECT(OS::cycles_since_boot() != 0ull);
}

CASE("page_size() returns page size")
{
  EXPECT(OS::page_size() == 4096u);
}

CASE("page_nr_from_addr() returns page number from address")
{
  EXPECT(OS::addr_to_page(512) == 0u);
  EXPECT(OS::page_to_addr(1) > 0u);
}

Update OS test, avoid hard-coded values


#define BOOST_TEST_NO_MAIN
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE "VAST Unit Test Suite"

#include "test.h"
#include "vast/configuration.h"
#include "vast/logger.h"

int main(int argc, char* argv[])
{
  vast::configuration config;
  config.load("/dev/null");
  vast::init(config);

  boost::unit_test::unit_test_log.set_stream(vast::logger::get()->console());
  char const* args[] = {"", "--log_level=test_suite"};
  auto rc = boost::unit_test::unit_test_main(
      &init_unit_test,
      sizeof(args) / sizeof(char*),
      const_cast<char**>(args));

  if (rc)
    LOG(error, core) << "unit test suite exited with error code " << rc;

  return rc;
}

#define BOOST_TEST_NO_MAIN
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE "VAST Unit Test Suite"

#include <ze.h>
#include "test.h"
#include "vast/configuration.h"
#include "vast/logger.h"

int main(int argc, char* argv[])
{
  vast::configuration config;
  config.load("/dev/null");
  vast::init(config);

  boost::unit_test::unit_test_log.set_stream(vast::logger::get()->console());
  auto rc = boost::unit_test::unit_test_main(&init_unit_test, argc, argv);

  if (rc)
    LOG(error, core) << "unit test suite exited with error code " << rc;

  ze::rm(ze::logger::filename());
  ze::shutdown();
  return rc;
}

Clean up after running tests.


#include <iostream>

#include "pool.h"
#include "machine.h"
#include "job.h"

int main ()
{
    Pool machine_pool;
    Job first_job(1, "one");

    machine_pool.add_machine(Machine("one"));
    machine_pool.add_machine(Machine("two"));

    machine_pool.add_job(first_job);
    machine_pool.add_job(Job(2, "two"));

    std::cout << "Job 1 moveable: " << first_job.moveable() << std::endl;

    return 0;
}

#include <iostream>

#include "pool.h"
#include "machine.h"
#include "job.h"

int main ()
{
    Pool machine_pool;

    machine_pool.add_machine(Machine("one"));
    machine_pool.add_machine(Machine("two"));

    Job first_job(1, "one");

    machine_pool.add_job(first_job);
    machine_pool.add_job(Job(2, "two"));

    std::cout << "Job 1 moveable: " << first_job.moveable() << std::endl;

    return 0;
}

Move variable definition to the point just before it is needed.


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

#include "LoaderImage.hpp"
#include "Cache.hpp"
#include "graphics/ImageDataSTB.hpp"
#include "graphics/Texture.hpp"
#define STBI_NO_PSD
#define STBI_NO_HDR
#define STBI_NO_PIC
#define STBI_NO_GIF
#define STBI_NO_PNM
#include "stb_image.h"

namespace ouzel
{
    namespace assets
    {
        LoaderImage::LoaderImage():
            Loader(TYPE, {"jpg", "jpeg", "png", "bmp", "tga"})
        {
        }

        bool LoaderImage::loadAsset(const std::string& filename, const std::vector<uint8_t>& data, bool mipmaps)
        {
            graphics::ImageDataSTB image;
            if (!image.init(data))
                return false;

            std::shared_ptr<graphics::Texture> texture(new graphics::Texture());

            if (!texture->init(image.getData(), image.getSize(), 0, mipmaps ? 0 : 1, image.getPixelFormat()))
                return false;

            cache->setTexture(filename, texture);

            return true;
        }
    } // namespace assets
} // namespace ouzel

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

#include "LoaderImage.hpp"
#include "Cache.hpp"
#include "graphics/ImageDataSTB.hpp"
#include "graphics/Texture.hpp"

namespace ouzel
{
    namespace assets
    {
        LoaderImage::LoaderImage():
            Loader(TYPE, {"jpg", "jpeg", "png", "bmp", "tga"})
        {
        }

        bool LoaderImage::loadAsset(const std::string& filename, const std::vector<uint8_t>& data, bool mipmaps)
        {
            graphics::ImageDataSTB image;
            if (!image.init(data))
                return false;

            std::shared_ptr<graphics::Texture> texture(new graphics::Texture());

            if (!texture->init(image.getData(), image.getSize(), 0, mipmaps ? 0 : 1, image.getPixelFormat()))
                return false;

            cache->setTexture(filename, texture);

            return true;
        }
    } // namespace assets
} // namespace ouzel

Remove unneeded includes from the image loader


/*
 * Project: Particle Fire Explosion
 * Stage: 1
 * File: main.cpp
 * Author: suyashd95
 */

#include <iostream>
#include <SDL.h>

using namespace std;

int main() {

	if(SDL_Init(SDL_INIT_VIDEO) < 0) {

		cout << "SDL_Init failed." << endl;
		return 1;
	}

	cout << "SDL_Init succeeded." << endl;
	SDL_Quit();

	return 0;
}

/*
 * Project: Particle Fire Explosion
 * Stage: 1
 * File: main.cpp
 * Author: suyashd95
 */

#include <iostream>
#include <SDL.h>

using namespace std;

void setWindowToBlack(SDL_Window* window) {

	//	We must call SDL_CreateRenderer in order for draw calls to affect this window.
		SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, 0);

	//	Select the color for drawing. It is set to black here.
		SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE);

	//	Clear the entire screen to our selected color.
		SDL_RenderClear(renderer);

	//	Up until now everything was drawn behind the scenes. This will show the new, black contents of the window.
		SDL_RenderPresent(renderer);

}

int main() {

	const int SCREEN_WIDTH = 800;
	const int SCREEN_HEIGHT = 600;

	if (SDL_Init(SDL_INIT_VIDEO) < 0) {

		cout << "SDL_Init Failed." << endl;
		return 1;
	}

//	Create an application window.
	SDL_Window* window = SDL_CreateWindow("Particle Fire Explosion", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
														 SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);

	// Set Window background to Black.
	setWindowToBlack(window);

	// Check that window has been successfully created
	if(window == NULL) { // Same as if(!window)

		printf("Could not show window: %s\n", SDL_GetError()); // Outputs the error code/statement for debugging purposes
		SDL_Quit();
		return 2;
	}

	bool quit = false;

	SDL_Event event;

	while(!quit) {

		// Update particles
		// Draw particles
		// Check for messages/events

		while(SDL_PollEvent(&event)) {

			if(event.type == SDL_QUIT) {

				quit = true;
			}
		}
	}

//	SDL_Delay(10000); Pauses or delays the execution of the program

	SDL_DestroyWindow(window);

	SDL_Quit();

	return 0;
}

Define a function setWindowToBlack() to create a window with a black background.


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


/*
 * Illarionserver - server for the game Illarion
 * Copyright 2011 Illarion e.V.
 *
 * This file is part of Illarionserver.
 *
 * Illarionserver  is  free  software:  you can redistribute it and/or modify it
 * under the terms of the  GNU  General  Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any
 * later version.
 *
 * Illarionserver 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 General Public License for more
 * details.
 *
 * You should have received a copy of the GNU  General Public License along with
 * Illarionserver. If not, see <http://www.gnu.org/licenses/>.
 */

#include "db/QueryAssign.hpp"

using namespace Database;

QueryAssign::QueryAssign(const Connection &connection) : connection(connection) {
}

void QueryAssign::addAssignColumnNull(const std::string &column) {
    Query::appendToStringList(assignColumns, Query::escapeAndChainKeys("", column) + " = nullptr");
}

std::string &QueryAssign::buildQuerySegment() {
    return assignColumns;
}

/*
 * Illarionserver - server for the game Illarion
 * Copyright 2011 Illarion e.V.
 *
 * This file is part of Illarionserver.
 *
 * Illarionserver  is  free  software:  you can redistribute it and/or modify it
 * under the terms of the  GNU  General  Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any
 * later version.
 *
 * Illarionserver 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 General Public License for more
 * details.
 *
 * You should have received a copy of the GNU  General Public License along with
 * Illarionserver. If not, see <http://www.gnu.org/licenses/>.
 */

#include "db/QueryAssign.hpp"

using namespace Database;

QueryAssign::QueryAssign(const Connection &connection) : connection(connection) {
}

void QueryAssign::addAssignColumnNull(const std::string &column) {
    Query::appendToStringList(assignColumns, Query::escapeAndChainKeys("", column) + " = NULL");
}

std::string &QueryAssign::buildQuerySegment() {
    return assignColumns;
}

Fix setting NULL as db column value


#include <Value.h>

namespace tests {

namespace valueSuite {

TEST(ValueSuite, UInt8Test) {
	Value<uint8_t, 1, 3, true> v0={{{13, 37}, {1, 1}, {3, 7}}};
	Value<uint8_t, 1, 3, true> v2={{{73, 1}, {3, 1}, {7, 1}}};
	EXPECT_EQ(v0, v0) << "Equally assigned values are not equal";
	EXPECT_NE(v0, v2) << "Unequally assigned values are equal";
	EXPECT_FALSE(v0==v2) << "Unequally assigned values are equal";
}

}}

#include <Value.h>

namespace tests {

namespace valueSuite {

TEST(ValueSuite, uInt8Test) {
	Value<uint8_t, 1, 3, true> v0={{{13, 37}, {1, 1}, {3, 7}}};
	Value<uint8_t, 1, 3, true> v2={{{73, 1}, {3, 1}, {7, 1}}};
	EXPECT_EQ(v0, v0) << "Equally assigned values are not equal";
	EXPECT_NE(v0, v2) << "Unequally assigned values are equal";
	EXPECT_FALSE(v0==v2) << "Unequally assigned values are equal";
	EXPECT_FALSE((v0<v2).prod()) << "Vector comparision failed";
}

}}

Add vector comparision test case


#include "Simulation.hpp"

using namespace aff3ct;
using namespace aff3ct::simulation;

Simulation
::Simulation(const factory::Simulation::parameters& simu_params)
: params(simu_params)
{
}

Simulation
::~Simulation()
{
}

void Simulation
::build_communication_chain()
{
	_build_communication_chain();

	for (auto &m : modules)
		for (auto mm : m.second)
			if (mm != nullptr)
				for (auto &t : mm->tasks)
				{
					t.second->set_autoexec (true);
					t.second->set_autoalloc(true);
					t.second->set_stats    (true);

					// enable the debug mode in the modules
					if (params.debug)
					{
						t.second->set_debug(true);
						if (params.debug_limit)
							t.second->set_debug_limit((uint32_t)params.debug_limit);
						if (params.debug_precision)
							t.second->set_debug_precision((uint8_t)params.debug_precision);
					}
				}
}

#include "Simulation.hpp"

using namespace aff3ct;
using namespace aff3ct::simulation;

Simulation
::Simulation(const factory::Simulation::parameters& simu_params)
: params(simu_params)
{
}

Simulation
::~Simulation()
{
}

void Simulation
::build_communication_chain()
{
	_build_communication_chain();

	for (auto &m : modules)
		for (auto mm : m.second)
			if (mm != nullptr)
				for (auto &t : mm->tasks)
				{
					t.second->set_autoexec (true);
					t.second->set_autoalloc(true);

					if (params.statistics)
						t.second->set_stats(true);

					// enable the debug mode in the modules
					if (params.debug)
					{
						t.second->set_debug(true);
						if (params.debug_limit)
							t.second->set_debug_limit((uint32_t)params.debug_limit);
						if (params.debug_precision)
							t.second->set_debug_precision((uint8_t)params.debug_precision);
					}
				}
}

Enable the statistics in the task only if the user want to display the stats.


#include "engine/events-manager.h"

#include "engine/game-manager.h"

void EventsManager::EventsLoop(sf::RenderWindow* window) {
  sf::Event event;

  auto instances = GameManager::GetInstancesManager();
  while (window->pollEvent(event)) {
    switch (event.type) {
      case sf::Event::Closed:
        window->close();
        break;

      case sf::Event::KeyPressed:
        instances->KeyPressed(event.key);
        break;

      case sf::Event::KeyReleased:
        instances->KeyReleased(event.key);
        break;

      case sf::Event::MouseButtonPressed:
        instances->MousePressed(event.mouseButton);
        break;

      case sf::Event::MouseButtonReleased:
        instances->MouseReleased(event.mouseButton);
        break;

      case sf::Event::MouseMoved:
        instances->MouseMoved(event.mouseMove);
        break;

      default:
        break;
    }
  }

  if (sf::Keyboard::isKeyPressed(sf::Keyboard::Q)) {
    window->close();
  }
}

void EventsManager::Trigger(GameEvent event) {
}

#include "engine/events-manager.h"

#include "engine/game-manager.h"

void EventsManager::EventsLoop(sf::RenderWindow* window) {
  sf::Event event;

  auto instances = GameManager::GetInstancesManager();
  while (window->pollEvent(event)) {
    switch (event.type) {
      case sf::Event::Closed:
        window->close();
        break;

      case sf::Event::KeyPressed:
        instances->KeyPressed(event.key);
        break;

      case sf::Event::KeyReleased:
        instances->KeyReleased(event.key);
        break;

      case sf::Event::MouseButtonPressed:
        instances->MousePressed(event.mouseButton);
        break;

      case sf::Event::MouseButtonReleased:
        instances->MouseReleased(event.mouseButton);
        break;

      case sf::Event::MouseMoved:
        instances->MouseMoved(event.mouseMove);
        break;

      default:
        break;
    }
  }

  if (sf::Keyboard::isKeyPressed(sf::Keyboard::Q)) {
    window->close();
  }
}

void EventsManager::Trigger(GameEvent event) {
  auto mapController = GameManager::GetMapController();
  mapController->EventTriggered(event);

  auto playerController = GameManager::GetPlayerController();
  playerController->EventTriggered(event);

  auto instances = GameManager::GetInstancesManager();
  instances->EventTriggered(event);
}

Send triggered events to the instances and the controllers


#include "Course.h"

#include <cstdio>
#include <iostream>

using namespace std;

int main() {
  if (remove("test-0.sqlite") != 0) {
    cout << "Error with deletion of database file\n";
  } else {
    cout << "Database file successfully deleted\n";
  }

  // test instantiation of a Course object.
  cout << "Testing instantiation of a Course object:" << endl;
  Course course("test-0");
  cout << "Created " << course.getName() << endl;

  cout << "All Assignments:" << endl;

  for (auto it : course.assignments) {
    cout << it.first << "=>" << it.second << '\n';
  }
}

#include "Course.h"
#include "Assignment.h"

#include <cstdio>
#include <iostream>

using namespace std;

int main() {
  if (remove("test-0.sqlite") != 0) {
    cout << "Error with deletion of database file\n";
  } else {
    cout << "Database file successfully deleted\n";
  }

  // test instantiation of a Course object.
  cout << "Testing instantiation of a Course object:" << endl;
  Course course("test-0");
  cout << "Created " << course.getName() << endl;

  cout << "All Assignments: " << course.assignments.size() << endl;
  cout << "All Categories: " << course.categories.size() << endl;
  cout << "All Students: " << course.students.size() << endl;
  cout << "All Submitted: " << course.submitted.size() << endl;

  // Test adding items to the db
  Category c1(0, "Homework", 20, course.getDb());
  Category c2(0, "Labs", 30, course.getDb());
  Category c3(0, "Exams", 50, course.getDb());
  c1.insert();
  c2.insert();
  c3.insert();

  course.categories[c1.getId()] = &c1;
  course.categories[c2.getId()] = &c2;
  course.categories[c3.getId()] = &c3;

  for (auto it : course.categories) {
    cout << it.first << " " << it.second->getName() << endl;
  }
}

Test adding items to the db


#include <iostream>
#include <vector>
#include <thread>
#include <algorithm>
#include <cstdlib>

class AccumulatorFunctor {
public:
    void operator() (const std::vector<int> &v, unsigned long long &acm, unsigned int beginIndex, unsigned int endIndex) {
        acm = 0;
        for (unsigned int i = beginIndex; i < endIndex; ++i) {
            acm += v[i];
        }
    }

    unsigned long long acm;
};

int main() {
    std::vector<int> v(1024);
    srand(time(nullptr));
    std::generate(v.begin(), v.end(), [&v]() { return rand() % v.size(); } );

    for_each(begin(v), end(v), [](int i) { std::cout << i << ' '; } );

    AccumulatorFunctor accumulator1 = AccumulatorFunctor();
    AccumulatorFunctor accumulator2 = AccumulatorFunctor();

    std::thread t1(std::ref(accumulator1), std::ref(v), 0, v.size() / 2);
    std::thread t2(std::ref(accumulator2), std::ref(v), v.size() / 2, v.size());

    t1.join();
    t2.join();

    std::cout << "acm1: " << accumulator1.acm << std::endl;
    std::cout << "acm2: " << accumulator2.acm << std::endl;
    std::cout << "acm1 + acm2: " << accumulator1.acm + accumulator2.acm << std::endl;

    return 0;
}

Add c++11 thread creation with functor object. It generates random vector of 1024 integers and creates two threads to summarize bottom and top half respectfully.


// RUN: %llvmgcc -c -g %s -o - | llc -fast -f -o %t.s
// RUN: %compile_c %t.s -o %t.o
// PR4025

template <typename _Tp> class vector
{
public:
  ~vector ()
  {
  }
};

class Foo
{
  ~Foo();
  class FooImpl *impl_;
};

namespace {
  class Bar;
}

class FooImpl
{
  vector<Bar*> thing;
};

Foo::~Foo()
{
  delete impl_;
}

Test case for revision 69683.


#include<iostream>
using namespace std;

struct node {
   int data;
   struct node *left;
   struct node *right;
};

struct node *createNode(int val) {
   struct node *temp = (struct node *)malloc(sizeof(struct node));
   temp->data = val;
   temp->left = temp->right = NULL;
   return temp;
}

void postorder(struct node *root) {
   if (root != NULL) {
      postorder(root->left);
      postorder(root->right);
      cout<<root->data<<" ";
   }
}

struct node* insertNode(struct node* node, int val) {
   if (node == NULL) return createNode(val);
   if (val < node->data)
   node->left = insertNode(node->left, val);
   else if (val > node->data)
   node->right = insertNode(node->right, val);
   return node;
}

int main() {
   struct node *root = NULL;
   root = insertNode(root, 4);
   insertNode(root, 5);
   insertNode(root, 2);
   insertNode(root, 9);
   insertNode(root, 1);
   insertNode(root, 3);
   cout<<"Post-Order traversal of the Binary Search Tree is: ";
   postorder(root);
   return 0;
}

Add cpp program for postorder recursive Traversal


// The MIT License (MIT)

// Copyright (c) 2014 Rapptz

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

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

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

#include <catch.hpp>
#include <jsonpp/value.hpp>

TEST_CASE("accessors", "[subscripts-accessors]") {
    json::value v = { json::object{ {"test", 1} }, nullptr, "my_string", 1.0 };
    json::value o = json::object{ {"key", "value"}, {"int", 1} };

    SECTION("get from json::array") {
        REQUIRE(v[0].is<json::object>());
        REQUIRE(v[1].is<json::null>());
        REQUIRE(v[2].is<std::string>());
        REQUIRE(v[3].is<double>());
        REQUIRE(v[3].is<float>());
        REQUIRE(v[3].is<int>());
        REQUIRE(v[4].is<json::null>()); //Never throw, return json::null
    };

    SECTION("get from json::object") {
        REQUIRE(o["key"].is<std::string>());
        REQUIRE(o["int"].is<int>());
        REQUIRE(o["unexist"].is<json::null>()); //Never throw, return json::null
    };

    SECTION("get from complex structure") {
        REQUIRE(v[0]["test"].is<int>());
        REQUIRE(v[0]["test"].as<int>() == 1);
    };
}

Add tests for new feature


/*
 * Copyright (C) 2015-2016 Pavel Dolgov
 *
 * See the LICENSE file for terms of use.
 */

#include <bits/stdc++.h>

struct Foo {
public:
    Foo() {
        std::cout << "Foo's constructor." << std::endl;
    }

    ~Foo() {
        std::cout << "Foo's destructor." << std::endl;
    }
};

template<typename T>
class SharedPtr {
private:
    struct Storage {
        int counter;
        T* obj;
    };

    Storage* storage_;

public:
    SharedPtr():
        storage_(0) {
        reset();
    }

    explicit SharedPtr(T* obj):
        storage_(0) {
        reset(obj);
    }

    SharedPtr(const SharedPtr& ptr):
        storage_(0) {
        reset(ptr);
    }

    ~SharedPtr() {
        reset();
    }

    bool empty() {
        return storage_ == 0;
    }

    void reset() {
        if (storage_ != 0) {
            storage_->counter -= 1;
            if (storage_->counter == 0) {
                delete storage_->obj;
                delete storage_;
            }
            storage_ = 0;
        }
    }

    void reset(T* t) {
        reset();
        if (t != 0) {
            storage_ = new Storage();
            storage_->obj = t;
            storage_->counter = 1;
        }
    }

    void reset(const SharedPtr& ptr) {
        reset();
        if (ptr.storage_ != 0) {
            storage_ = ptr.storage_;
            storage_->counter += 1;
        }
    }

    SharedPtr& operator=(const SharedPtr& ptr) {
        reset(ptr);
        return *this;
    }
};

int main() {
    std::cout << "zer0main's shared pointer" << std::endl;
    SharedPtr<Foo> foo_ptr = SharedPtr<Foo>(new Foo());
    std::cout << "foo_ptr is empty: " << foo_ptr.empty() << std::endl;
    SharedPtr<Foo> foo_ptr2 = foo_ptr;
    std::cout << "foo_ptr is empty: " << foo_ptr.empty() << std::endl;
    foo_ptr.reset();
    std::cout << "foo_ptr is empty: " << foo_ptr.empty() << std::endl;
    foo_ptr.reset(new Foo());
    std::cout << "foo_ptr is empty: " << foo_ptr.empty() << std::endl;
    foo_ptr.reset(foo_ptr2);
    SharedPtr<Foo> foo_ptr3;
    std::cout << "foo_ptr3 is empty: " << foo_ptr3.empty() << std::endl;
    foo_ptr3 = foo_ptr2;
    std::cout << "foo_ptr3 is empty: " << foo_ptr3.empty() << std::endl;
    return 0;
}

Add implementation of Shared Pointer


/**
 * link: https://leetcode.com/problems/reverse-bits/
 */
class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
        bitset<32> res(n);
        string str = res.to_string();
        reverse(str.begin(), str.end());
        return bitset<32>(str).to_ulong();
    }
};

Add solution for 190. Reverse Bits.


#include <cassert>
#include <vector>

template <class RandomAccessIterator, class KeyValue, class DefaultValue>
DefaultValue recursive_binary_search(
        RandomAccessIterator start, RandomAccessIterator end, KeyValue key,
        DefaultValue default_value) {
    if (start == end) {
        return default_value;
    }

    RandomAccessIterator middle = start + ((end - start) / 2);

    if (*middle == key) {
        return middle;
    }
    else if (*middle < key) {
        return recursive_binary_search(middle + 1, end, key, default_value);
    }
    else {
        return recursive_binary_search(start, middle, key, default_value);
    }
}

template <class RandomAccessIterator, class Value>
RandomAccessIterator recursive_binary_search(RandomAccessIterator first,
                                             RandomAccessIterator last,
                                             Value key) {
    return recursive_binary_search(first, last, key, last);
}

template <class RandomAccessIterator, class Value>
RandomAccessIterator iterative_binary_search(RandomAccessIterator first,
                                             RandomAccessIterator last,
                                             Value key) {
    RandomAccessIterator start, end;
    start = first;
    end = last;

    while (start != end) {
        RandomAccessIterator middle = start + ((end - start) / 2);
        if (*middle == key) {
            return middle;
        }
        else if (*middle < key) {
            start = middle + 1;
        }
        else {
            end = middle;
        }
    }

    return last;
}

int main(int argc, char** argv) {
    int seq[] = {1, 1, 2, 5, 9, 11, 11, 11, 12, 18, 29, 37, 38, 40, 67, 78, 94,
                 94};

    std::vector<int> sorted_seq(seq, seq + (sizeof seq / sizeof seq[0]));

    assert(recursive_binary_search(sorted_seq.begin(), sorted_seq.end(), 12)
           == sorted_seq.begin() + 8);
    assert(recursive_binary_search(sorted_seq.begin(), sorted_seq.end(), 13)
           == sorted_seq.end());

    assert(iterative_binary_search(sorted_seq.begin(), sorted_seq.end(), 12)
           == sorted_seq.begin() + 8);
    assert(iterative_binary_search(sorted_seq.begin(), sorted_seq.end(), 13)
            == sorted_seq.end());

    return 0;
}

Add C++ binary search implementation (recursive and iterative)


// RUN: %llvmgxx -c -emit-llvm %s -o /dev/null -g
// This crashes if we try to emit debug info for TEMPLATE_DECL members.
template <class T> class K2PtrVectorBase {};
template <class T> class K2Vector {};
template <class U > class K2Vector<U*> : public K2PtrVectorBase<U*> {};
class ScriptInfoManager {
  void PostRegister() ;
  template <class SI> short ReplaceExistingElement(K2Vector<SI*>& v);
};
void ScriptInfoManager::PostRegister() {}

Test for llvm-gcc patch 73564.


#include "fish_detector/image_annotator/image_annotation.h"

namespace fish_detector { namespace image_annotator {

ImageAnnotation::ImageAnnotation(const std::string& image_file,
                                 const std::string& species,
                                 const std::string& subspecies,
                                 uint64_t id,
                                 const Rect &rect)
  : image_file_(image_file)
  , species_(species)
  , subspecies_(subspecies)
  , id_(id)
  , rect_(rect) {
}

ImageAnnotation::ImageAnnotation()
  : image_file_()
  , species_()
  , subspecies_()
  , id_(0)
  , rect_(0, 0, 0, 0) {
}

pt::ptree ImageAnnotation::write() const {
  pt::ptree tree;
  return tree;
}

void ImageAnnotation::read(const pt::ptree &tree) {
}

ImageAnnotationList::ImageAnnotationList()
  : list_()
  , by_file_()
  , by_species_() {
}

void ImageAnnotationList::insert(const ImageAnnotation &annotation) {
}

void ImageAnnotationList::remove(const std::string &image_file, uint64_t id) {
}

void ImageAnnotationList::write() const {
}

void ImageAnnotationList::read(const std::vector<std::string> &filenames) {
}

}} // namespace fish_detector::image_annotator

Add framework for image annotation implementation


/**
 * Divide Two Integers
 *
 * cpselvis (cpselvis@gmail.com)
 * August 25th, 2016
 */
#include<iostream>
#include<cmath>

using namespace std;

class Solution {
public:
  int divide(int dividend, int divisor) {
    if (divisor == 0 || (dividend == INT_MIN && divisor == -1))
    {
      return INT_MAX;
    }

    int sign = ((dividend > 0) ^ (divisor > 0 )) ? -1 : 1;  // ^ in C++ means XOR, when condition returns same result , then value is 0, or value is 1.
    long long int dvd = labs(dividend);                     // abs is only used for int type, when input is long int, use labs, float, use fabs.
    long long int dvr = labs(divisor);

    int ret = 0;
    while (dvd >= dvr)
    {
      int multiple = 1;
      long long int tmp = dvr;
      while (dvd >= (tmp << 1))
      {
	tmp <<= 1;
	multiple <<= 1;
      }
      dvd -= tmp;
      ret += multiple;
    }
    return  ret * sign;
  }
};

int main(int argc, char **argv)
{
  Solution s;
  cout << s.divide(6, 2) << endl;
  cout << s.divide(-1, 1) << endl;
  cout << s.divide(-2147483648, 1) << endl;
}

Divide two numbers (use substract.)


class Solution {
public:
    stack<int> sta;
    bool isNum(string str) {
        if (str.size() > 1)
            return true;
        if (str[0] >= '0' && str[0] <= '9')
            return true;
        return false;
    }
    int evalRPN(vector<string>& tokens) {
        int a, b, i;
        string s;
        for (i = 0; i < tokens.size(); i++) {
            s = tokens[i];

            if (isNum(s)){
                int num = 0;
                int sig = 1;
                int begin = 0;
                if (s[0] == '+') {
                    sig = 1;
                    begin = 1;
                } else if (s[0] == '-') {
                    sig = -1;
                    begin = 1;
                }

                for (int j = begin; j < s.size(); j++)
                    num = num*10 + s[j] - '0';

                sta.push(num*sig);
            } else {
                if (s.size() != 1) {
                    //assert(0);
                    break;
                }
                if (sta.size() < 2) {
                    //assert(0);
                    break;
                }
                //notice devide zero.
                b = sta.top();
                sta.pop();
                a = sta.top();
                sta.pop();
                switch (s[0]) {
                    case '+': a = a+b; break;
                    case '-': a = a-b; break;
                    case '*': a = a*b; break;
                    case '/': a = a/b; break;
                    default : break;//assert(0);
                }
                sta.push(a);
            }
        }
        if (s.size() != 1) {
        //    assert(0);
        }
        a = sta.top();
        return a;
    }
};

Create Evaluate reverse polish notation.cpp


/** \brief Test harness for the SimpleXmlParser class.
 *  \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
 *
 *  \copyright 2015 Universitätsbiblothek Tübingen.  All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program 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 Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include "SimpleXmlParser.h"
#include "util.h"

void Usage() {
    std::cerr << "Usage: " << progname << " xml_input\n";
    std::exit(EXIT_FAILURE);
}

int main(int argc, char *argv[]) {
    progname = argv[0];

    if (argc != 2)
        Usage();

    const std::string input_filename(argv[1]);
    File input(input_filename, "rm");
    if (not input)
	Error("can't open \"" + input_filename + "\" for reading!");

    SimpleXmlParser::Type type;
    std::string data;
    std::map<std::string, std::string> attrib_map;
    SimpleXmlParser xml_parser(&input);
    while (xml_parser.getNext(&type, &attrib_map, &data)) {
	switch (type) {
	case SimpleXmlParser::UNINITIALISED:
	    Error("we should never get here as UNINITIALISED should never be returned!");
	case SimpleXmlParser::START_OF_DOCUMENT:
	    std::cout << "START_OF_DOCUMENT()\n";
	    break;
	case SimpleXmlParser::END_OF_DOCUMENT:
	    break;
	case SimpleXmlParser::ERROR:
	    Error("we should never get here because SimpleXmlParser::getNext() should have returned false!");
	case SimpleXmlParser::OPENING_TAG:
	    std::cout << "OPENING_TAG(" << data;
	    for (const auto &name_and_value : attrib_map)
		std::cout << ' ' << name_and_value.first << '=' << name_and_value.second;
	    std::cout << ")\n";
	    break;
	case SimpleXmlParser::CLOSING_TAG:
	    std::cout << "CLOSING_TAG(" << data << ")\n";
	    break;
	case SimpleXmlParser::CHARACTERS:
	    std::cout << "CHARACTERS(" << data << ")\n";
	    break;
	}
    }

    Error("XML parsing error: " + xml_parser.getLastErrorMessage());
}

Test harness for the new SimpleXMLParser class.


#include <iostream>
#include<string>

using namespace std;

template <typename T>
T fobj(T a, T b) {
    return a;
}

template <typename T>
void fref(const T &a, const T &b) {

}

int main() {
    string s1("a value");
    const string s2("another value");
    fobj(s1, s2);
    fref(s1, s2);

    int a[10], b[10];
    fobj(a, b);
    fref(a, b);
    return 0;
}

Add solution for chapter 16 page 601


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

#include "SkAlphaThresholdFilter.h"
#include "SkImage.h"
#include "Test.h"

static void test_flattenable(skiatest::Reporter* r,
                             const SkFlattenable* f,
                             const char* desc) {
    if (f) {
        SkFlattenable::Factory factory = f->getFactory();
        REPORTER_ASSERT(r, factory);
        if (factory) {
            if (!SkFlattenable::FactoryToName(factory)) {
                ERRORF(r, "SkFlattenable::FactoryToName() fails with %s.", desc);
            }
        }
    }
}

DEF_TEST(FlattenableFactoryToName, r) {
    SkIRect rects[2];
    rects[0] = SkIRect::MakeXYWH(0, 150, 500, 200);
    rects[1] = SkIRect::MakeXYWH(150, 0, 200, 500);
    SkRegion region;
    region.setRects(rects, 2);
    SkAutoTUnref<SkImageFilter> filter( SkAlphaThresholdFilter::Create(region, 0.2f, 0.7f));
    test_flattenable(r, filter, "SkAlphaThresholdFilter()");

    SkBitmap bm;
    bm.allocN32Pixels(8, 8);
    bm.eraseColor(SK_ColorCYAN);
    SkAutoTUnref<SkImage> image(SkImage::NewFromBitmap(bm));
    SkAutoTUnref<SkShader> shader(image->newShader(SkShader::kClamp_TileMode,
                                                   SkShader::kClamp_TileMode));
    test_flattenable(r, shader, "SkImage::newShader()");
}

Add test for previously unflattenables


// http://www.geeksforgeeks.org/snake-ladder-problem-2/
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;

struct QNode {
	int v; // vertex
	int d; //distance;
};

int getMinDice(int moves[], int N) {
	bool *visited = new bool[N];
	memset(visited, false, sizeof(visited));

	queue<QNode> q;
	QNode qN = {0, 0}; // start node
	q.push(qN);
	visited[0] = true;
	QNode qE;
	while (!q.empty()) {
		qE = q.front();
		cout<<"pop: "<<qE.v<<" "<<qE.d<<endl;
		q.pop();

		int v = qE.v;

		if (v == N-1) break;

		for (int j = v+1; j <= v+6 && j < N; j++) {
			if (!visited[j]) {
				QNode qN;
				qN.d = qE.d+1;
				visited[j] = true;
				if (moves[j] != -1) {
					qN.v = moves[j];
				} else {
					qN.v = j;
				}
				cout<<"push: "<<qN.v<<" "<<qN.d<<endl;
				q.push(qN);
			}
		}
	}
	delete [] visited;
	return qE.d;
}

int main() {
	int N = 30; // Board Size;
	int moves[N];
	memset(moves, -1, sizeof(moves));

	// snakes positions
	moves[26] = 0;
	moves[20] = 8;
	moves[16] = 9;
	moves[18] = 6;

	// ladder positions
	moves[10] = 25;
	moves[2] = 21;
	moves[4] = 7;
	moves[19] = 28;

	cout<<"The min number of dices required to reach destination is: "<<getMinDice(moves, N)<<endl;
	return 0;
}

Implement Snakes and Ladders using BFS


#include <iostream>

using std::cout;

const int MAX = 20;

void spiral_traversal(int matrix[][MAX], int rows, int cols) {
  int start_row = 0;
  int end_row = rows - 1;
  int start_column = 0;
  int end_column = cols - 1;

  while (start_row <= end_row && start_column <= end_column) {
    for (int i = start_column; i <= end_column; ++i) {
      cout << matrix[start_row][i] << ' ';
    }
    ++start_row;

    for (int i = start_row; i <= end_row; ++i) {
      cout << matrix[i][end_column] << ' ';
    }
    --end_column;

    if (start_row <= end_row) {
      for (int i = end_column; i >= start_column; --i) {
        cout << matrix[end_row][i] << ' ';
      }
      --end_row;
    }

    if (start_column <= end_column) {
      for (int i = end_row; i >= start_row; --i) {
        cout << matrix[i][start_column] << ' ';
      }
      ++start_column;
    }
  }
}

int main() {
  int matrix[MAX][MAX] = {
    {1, 2, 3, 4, 5, 6},
    {7, 8, 9, 10, 11, 12},
    {13, 14, 15, 16, 17, 18}
  };

  spiral_traversal(matrix, 3, 6);

  return 0;
}

Add solution to spiral traversal of matrix problem


#include "testing/gtest.hh"

#include "geometry/spatial/time_interpolator.hh"

namespace geometry {
namespace spatial {

TEST(TimeInterpolatorTest, time_interpolator) {
  const estimation::TimePoint t0 = {};
  const estimation::TimeDuration dt = estimation::to_duration(1.0);

  const std::vector<geometry::spatial::TimeControlPoint> points = {
      geometry::spatial::TimeControlPoint{t0, jcc::Vec3(0.0, 0.0, 0.0)},
      geometry::spatial::TimeControlPoint{t0 + dt, jcc::Vec3(1.0, 1.0, 1.0)},
      geometry::spatial::TimeControlPoint{t0 + (2 * dt), jcc::Vec3(5.0, 5.0, 5.0)},
  };

  const TimeInterpolator interp(points);
  constexpr double EPS = 1e-6;

  {
    const auto error = (*interp(t0) - points[0].value).norm();
    EXPECT_LT(error, EPS);
  }

  {
    const auto error = (*interp(t0 + dt) - points[1].value).norm();
    EXPECT_LT(error, EPS);
  }

  {  // Nothing at the end point
    EXPECT_FALSE(interp(t0 + (2 * dt)));

    const estimation::TimePoint t = t0 + estimation::to_duration(1.9999);
    const auto interp_at_t = interp(t);
    ASSERT_TRUE(interp_at_t);
    const auto error = (*interp_at_t - points[2].value).norm();
    EXPECT_LT(error, 1e-3);
  }

  {
    const estimation::TimePoint t = t0 + estimation::to_duration(0.5);
    const auto error = (*interp(t) - jcc::Vec3(0.5, 0.5, 0.5)).norm();
    EXPECT_LT(error, EPS);
  }

  {
    const estimation::TimePoint t = t0 + estimation::to_duration(1.5);
    const auto error = (*interp(t) - jcc::Vec3(3.0, 3.0, 3.0)).norm();
    EXPECT_LT(error, EPS);
  }
}

}  // namespace spatial
}  // namespace geometry

Add test for time interpolator


// Chapter 19, exercise 13: Tracer class where constructor and destructor print
// strings (given as argument to constructor). Use it to see where RAII objects
// will do their job (local objects, member objects, global objects, objects
// allocated with new...), then add copy constructor and copy assignment to see
// when copying is done

#include "../lib_files/std_lib_facilities.h"

//------------------------------------------------------------------------------

class Tracer {
    string msg;
public:
    Tracer(const string& s) : msg(s) { cout << "Constructed " << msg << "\n"; }
    Tracer(const Tracer& t) : msg(t.msg)
    {
        cout << "Copy constructed from " << msg << "\n";
    }
    Tracer& operator=(const Tracer& t)
    {
        msg = t.msg;
        cout << "Copy assigned " << msg << "\n";
        return *this;
    }
    ~Tracer() { cout << "Destroyed " << msg << "\n"; }
    void set_msg(const string& s) { msg = s; }
};

//------------------------------------------------------------------------------

struct Test {
    Test(const string& s) : val(Tracer(s)) { }
    Tracer val;
};

//------------------------------------------------------------------------------

Tracer global("global");

//------------------------------------------------------------------------------

int main()
try {
    { Tracer t_scope("allocated in local scope"); } // immediately destroyed
    Tracer copy_global = global;
    cout << "and renamed to 'local copy of global'\n";
    copy_global.set_msg("local copy of global");
    Tracer local("local");
    Test member("as member object");
    Tracer* local_ptr = new Tracer("allocated with new");   // leaks!
    Tracer t_cpyassign = *local_ptr;
    cout << "and renamed to 'copy assigned from pointer'\n";
    t_cpyassign.set_msg("copy assigned from pointer");
}
catch (exception& e) {
    cerr << "exception: " << e.what() << endl;
}
catch (...) {
    cerr << "exception\n";
}

Add Chapter 19, exercise 13


// 43. Multiply Strings
/**
 * Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.
 *
 * Note:
 *
 * 1. The length of both num1 and num2 is < 110.
 * 2. Both num1 and num2 contains only digits 0-9.
 * 3. Both num1 and num2 does not contain any leading zero.
 * 4. You must not use any built-in BigInteger library or convert the inputs to integer directly.
 *
 * Tags: Math, String
 *
 * Similar Problems: (M) Add Two Numbers, (E) Plus One, (E) Add Binary, (E) Add Strings
 *
 * Author: Kuang Qin
 */

#include <iostream>
#include <string>
#include <vector>

using namespace std;

class Solution {
public:
    string multiply(string num1, string num2) {
        if (num1 == "0" || num2 == "0")
            return "0";

        // product length will not exceed the total length of two multipliers
        int n1 = num1.size(), n2 = num2.size(), n = n1 + n2;
        vector<int> product(n, 0);

        // add result from multiplying by digit
        for (int i = n1 - 1; i >= 0; i--) {
            for (int j = n2 - 1; j >= 0; j--) {
                product[i + j + 1] += (num1[i] - '0') * (num2[j] - '0');
            }
        }

        // make each digit valid
        for (int i = n - 1; i > 0; i--) {
            product[i - 1] += product[i] / 10;  // higher digit
            product[i] = product[i] % 10;       // lower digit
        }

        // convert into string
        string res("");
        if (product[0] != 0)    // first digit could be zero
            res += product[0] + '0';

        for (int i = 1; i < n; i++)
            res += product[i] + '0';

        return res;
    }
};

int main() {
    string num1("2143"), num2("2");
    Solution sol;
    string p = sol.multiply(num1, num2);
    cout << num1 << " * " << num2 << " = " << p << endl;
    cin.get();

    return 0;
}

Add Solution for 043 Multiply Strings


#include <iostream>

using namespace std;

int main() {

    int N, K;
    cin >> N >> K;

    if (K == 0 || K > N) {
        cout << 0 << endl;
        return 0;
    }

    if (N % 2 == 1 && K == (N + 1) / 2) {
        cout << N - 1 << endl;
    } else {
        cout << N - 2 << endl;
    }

    return 0;

}

Create : 521 Cheeses and a Mousetrap


// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -emit-llvm -std=c++1y -O1 -disable-llvm-optzns %s -o - | FileCheck %s -check-prefix=CHECKA -check-prefix=CHECK
// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -emit-llvm -std=c++1y -O1 -disable-llvm-optzns -fcxx-exceptions %s -o - | FileCheck %s -check-prefix=CHECKB -check-prefix=CHECK
// expected-no-diagnostics

// The variable template specialization x<Foo> generated in each file
// should be 'internal global' and not 'linkonce_odr global'.

template <typename T> int x = 42;

// CHECK-DAG: @_Z1xIZL3foovE3FooE = internal global

// CHECK-DAG: define internal dereferenceable(4) i32* @_ZL3foov(
static int &foo() {
   struct Foo { };

   // CHECK-DAG: ret i32* @_Z1xIZL3foovE3FooE
   return x<Foo>;
}

#if !__has_feature(cxx_exceptions) // File A
// CHECKA-DAG: define dereferenceable(4) i32* @_Z3barv(
int &bar() {
	// CHECKA-DAG: %call = call dereferenceable(4) i32* @_ZL3foov()
	return foo();
}

#else // File B

// CHECKB-DAG: declare dereferenceable(4) i32* @_Z3barv(
int &bar();

int main() {
	// CHECKB-DAG: %call = call dereferenceable(4) i32* @_Z3barv()
	// CHECKB-DAG: %call1 = call dereferenceable(4) i32* @_ZL3foov()
	&bar() == &foo() ? throw 0 : (void)0; // Should not throw exception at runtime.
}

#endif // end of Files A and B

Add test case for fix of linkage bug that miscompiled variable templates instantiated from similarly named local types (cf. r212233)


/*
	This program tests class LinkedList
*/

#include<iostream>
#include<vector>
#include "linkedlist.h"

// tests insertion

void testInsert(){

	std::cout<<"Test Insert\n";

	// define vector of values
	std::vector<int> values = {6,5,4,3,2,1};

	// create linked list
	LinkedList ll;

	// insert values into linked list (always at beginning i.e. index 0)
	for(auto x: values){
		ll.insertFirst(x);
	}

	// display linked list
	ll.print();

	// insert 100 at end
	ll.insertLast(100);

	// display linked list
	ll.print();

	// insert in between
	ll.insert_node(3,5000);

	// display linked list
	ll.print();

}

// tests valueAt() and getLength()

void testB(){

	std::cout<<"Test B\n";

	// define vector of values
	std::vector<int> values = {6,5,4,3,2,1};

	// create linked list
	LinkedList ll;

	// insert values into linked list (always at beginning i.e. index 0)
	for(auto x: values){
		ll.insertFirst(x);
	}

	// insert 100 at end
	ll.insertLast(1000);

	// insert in between
	ll.insert_node(3,5000);

	// display linked list
	ll.print();

	std::cout<<"Length: "<<ll.getLength();

	for(int i=0;i<ll.getLength();i++){

		std::cout<<"\nValut at "<<i<<": "<<ll.valueAt(i);

	}

}

int main(){

	// test insert
	testInsert();

	// test B
	testB();

	return 0;
}

Add test case for insertion, retrieval and display


#include <chrono>
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>

#include <vpp/vpp.hh>
#include <vpp/utils/opencv_bridge.hh>
#include <vpp/algorithms/FAST_detector/FAST.hh>

#include "get_time.hh"

int main(int argc, char* argv[])
{
  using namespace vpp;

  if (argc != 3)
  {
    std::cerr << "Usage : " << argv[0] << " image threshold" << std::endl;
    return 1;
  }

  int K = 400;

  typedef image2d<vuchar3> I;
  I A = clone_with_border(from_opencv<vuchar3>(cv::imread(argv[1])), 3);
  I B(A.domain(), 1);

  image2d<unsigned char> Agl(A.domain(), 3);
  image2d<unsigned char> Bgl(A.domain());

  pixel_wise(Agl, A) << [] (unsigned char& gl, vuchar3& c)
  {
    gl = (c[0] + c[1] + c[2]) / 3;
  };

  auto time = get_time_in_seconds();
  for (unsigned i = 0; i < K; i++)
    fast_detector<9>(Agl, Bgl, atoi(argv[2]));
  double vpp_ms_per_iter = 1000 * (get_time_in_seconds() - time) / K;

  // Opencv: void FAST(InputArray _img, std::vector<KeyPoint>& keypoints, int threshold, bool nonmax_suppression)
  time = get_time_in_seconds();
  cv::Mat cv_Agl = to_opencv(Agl);
  cv::Mat cv_B = to_opencv(B);
  std::vector<cv::KeyPoint> keypoints;
  for (unsigned i = 0; i < K; i++)
  {
    keypoints.clear();
    FAST(cv_Agl, keypoints, 10, false);
  }
  double opencv_ms_per_iter = 1000 * (get_time_in_seconds() - time) / K;

  std::cout << "Time per iterations: " << std::endl
            << "OpenCV: " << opencv_ms_per_iter << "ms" << std::endl
            << "VPP: " << vpp_ms_per_iter << "ms" << std::endl;

  pixel_wise(Bgl) << [] (unsigned char& gl)
  {
    gl = gl * 255;
  };

  cv::imwrite("b.pgm", to_opencv(Bgl));

}

Add benchmark of the fast detector


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        ListNode* dummy = new ListNode(), *pre = dummy;
        dummy->next = head;
        bool in = false;
        while (head && head->next) {
            if (in) {
                if (head->val != head->next->val) {
                    pre->next = head->next;
                    in = false;
                }
                head = head->next;
            } else {
                if (head->val == head->next->val) {
                    in = true;
                } else {
                    pre = pre->next;
                }
                head = head->next;
            }
        }
        if (in) pre->next = nullptr;
        return dummy->next;

    }
};

Remove Duplicates from Sorted List II


#include <iostream>
#include <deque>

using namespace std;

// This is a very well known problem that can easily be found
// in google as 'maximum sliding window' where basically we are
// moving over an array printing each max value for each sub-array
// (or window). You can take a look to the explanation and
// code from:
// http://articles.leetcode.com/sliding-window-maximum/

void printKMax(int arr[], int n, int k){
   deque <int> q;

    // First we need to take care of the first window.
    // We will ensure that the highest element of the window is always in
    // the front of the deque, for that reason on each iteration (i) we
    // remove all the elements in the back of the deque with lower that
    // the current element in the array. This is done in this first while
    // loop.
    for (int i = 0; i < k; i++) {
        while(!q.empty() && arr[i] >= arr[q.back()]) {
            q.pop_back();
        }
        //Each element in the array 'arr' is added at some time into the
        // queue elements with lower value that the current maximum one
        // are removed with the previous while loop.
        q.push_back(i);
    }

    // Section 2.
    // By this point we already checked the first window and all the remaining
    // sections will be taken care in the next for loop.
    for (int i = k; i < n; i++) {
        cout << arr[q.front()] << " ";
        while (!q.empty() && arr[i] >= arr[q.back()])
            q.pop_back();
        //let's remove the elements that are out of the window from the front.
        // As you can see we are attacking the deque in the front as well, but
        // now we only remove the elements that are not part of the subarray
        // and for that reason not valid.
        while(!q.empty() && q.front() <= i-k)
            q.pop_front();
        q.push_back(i);
    }
    cout << arr[q.front()] << " ";
    cout << endl;
}

int main(){
    int t;
    cin >> t;
    while(t>0) {
        int n,k;
        cin >> n >> k;
        int i;
        int arr[n];
        for(i=0;i<n;i++)
            cin >> arr[i];
        printKMax(arr, n, k);
        t--;
    }
    return 0;
}

Add first version of C++ stl deque.


// RUN: clang-cc %s -emit-llvm -o - | FileCheck %s

// Check that call to constructor for struct A is generated correctly.
struct A { A(int x = 2); };
struct B : public A {};
B x;

// CHECK: call void @_ZN1AC1Ei

Add code generation test for r86500.


// RUN: rm -rf %t
// RUN: %clang_cc1 -x objective-c++ -fmodules -fmodule-cache-path %t -I %S/Inputs %s -verify

// expected-no-diagnostics
@import cxx_many_overloads;

void g() {
  f(N::X<0>());
}

// RUN: rm -rf %t
// RUN: %clang_cc1 -x objective-c++ -fmodules -fmodules-cache-path=%t -I %S/Inputs %s -verify

// expected-no-diagnostics
@import cxx_many_overloads;

void g() {
  f(N::X<0>());
}

Fix conflict between r174685 and r174645 (rename -fmodule-cache-path <foo> to -fmodules-cache-path=<foo>).


// RUN: clang-cc -emit-llvm %s -o %t -triple=x86_64-apple-darwin9 &&
struct A {
  A();
  ~A();
  void f();
};

void f() {
  // RUN: grep "call void @_ZN1AC1Ev" %t | count 2 &&
  // RUN: grep "call void @_ZN1AD1Ev" %t | count 2
  A();
  A().f();
}

Add a simple test for temporaries.


// Test that on the second entry to a function the origins are still right.

// RUN: %clangxx_msan -m64 -O0 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out
// RUN: %clangxx_msan -m64 -O1 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out
// RUN: %clangxx_msan -m64 -O2 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out
// RUN: %clangxx_msan -m64 -O3 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out

// RUN: %clangxx_msan -fsanitize-memory-track-origins -m64 -O0 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out && FileCheck %s --check-prefix=CHECK-ORIGINS < %t.out
// RUN: %clangxx_msan -fsanitize-memory-track-origins -m64 -O1 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out && FileCheck %s --check-prefix=CHECK-ORIGINS < %t.out
// RUN: %clangxx_msan -fsanitize-memory-track-origins -m64 -O2 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out && FileCheck %s --check-prefix=CHECK-ORIGINS < %t.out
// RUN: %clangxx_msan -fsanitize-memory-track-origins -m64 -O3 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out && FileCheck %s --check-prefix=CHECK-ORIGINS < %t.out

#include <stdlib.h>

extern "C"
int f(int depth) {
  if (depth) return f(depth - 1);

  int x;
  int *volatile p = &x;
  return *p;
}

int main(int argc, char **argv) {
  return f(1);
  // CHECK: WARNING: MemorySanitizer: use-of-uninitialized-value
  // CHECK: {{#0 0x.* in main .*stack-origin2.cc:}}[[@LINE-2]]

  // CHECK-ORIGINS: Uninitialized value was created by an allocation of 'x' in the stack frame of function 'f'
  // CHECK-ORIGINS: {{#0 0x.* in f .*stack-origin2.cc:}}[[@LINE-14]]

  // CHECK: SUMMARY: MemorySanitizer: use-of-uninitialized-value {{.*stack-origin2.cc:.* main}}
}

Add one more test for the handling of stack origins.


#include "cxx_runtime.h"
#include "output.h"

Output output;

int bar(char *buffer, int size)
{
	char tmp[size * 2];
	int index = 0;

	output << "enter bar\n";

	for (int i = 0; i < size; i++)
	{
		if (buffer[i] == 'i')
		{
			tmp[index++] = '~';
			tmp[index++] = 'i';
		}
		else
			tmp[index++] = buffer[i];
	}

	memcpy(buffer, tmp, index);
	return index;
}

int main()
{
	char foo[256] = "this is a test";

	int newLen = bar(foo, strlen(foo));
	for (int i = 0; i < newLen; i++)
		output << foo[i];

	// CHECK: th~is ~is a test
}

Add test for dynamic stack allocation