#include "map.h"
#include "screen.h"
#include <sstream>

Map CreateMap(int seed)
{
    return GenerateRandomMap(std::mt19937(seed));
}

int GameMain()
{
    SetTitle("Map test");

    int seed = 1;
    Map map = CreateMap(seed);

    Screen screen;

    while(true)
    {
        screen.Clear();

        std::ostringstream ss;
        ss << "Seed = " << seed;
        screen.PutString({0,0}, Color::White, ss.str());

        for(int y=0; y<MAP_HEIGHT; ++y)
        {
            for(int x=0; x<MAP_WIDTH; ++x)
            {
                screen.PutGlyph({x+MAP_OFFSET_X,y+MAP_OFFSET_Y}, map.GetTile({x,y}).GetGlyph());
            }
        }
        WriteOutput(screen.glyphs, {7,0});

        switch(ReadInput())
        {
        case 'Q': return 0;
        case '4': map = CreateMap(--seed); break;
        case '6': map = CreateMap(++seed); break;
        case '2': map = CreateMap(seed -= 10); break;
        case '8': map = CreateMap(seed += 10); break;
        }
    }
}

#include "map.h"
#include "screen.h"
#include <sstream>

Map CreateMap(int seed)
{
    return GenerateRandomMap(std::mt19937(seed));
}

int GameMain()
{
    SetTitle("Map test");

    int seed = 1;
    Map map = CreateMap(seed);

    Screen screen;

    while(true)
    {
        screen.Clear();

        std::ostringstream ss;
        ss << "Seed = " << seed;
        screen.PutString({0,0}, Color::White, ss.str());

        for(int y=0; y<MAP_HEIGHT; ++y)
        {
            for(int x=0; x<MAP_WIDTH; ++x)
            {
                for(int dir=0; dir<9; ++dir)
                {
                    if(map.GetTile(int2(x,y) + (Direction)dir).IsWalkable())
                    {
                        screen.PutGlyph({x+MAP_OFFSET_X,y+MAP_OFFSET_Y}, map.GetTile({x,y}).GetGlyph());
                        break;
                    }
                }
            }
        }
        WriteOutput(screen.glyphs, {7,0});

        switch(ReadInput())
        {
        case 'Q': return 0;
        case '4': map = CreateMap(--seed); break;
        case '6': map = CreateMap(++seed); break;
        case '2': map = CreateMap(seed -= 10); break;
        case '8': map = CreateMap(seed += 10); break;
        }
    }
}

Split apart effect interface and implementations.


#include "Interpreter.hpp"

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

tkom::Interpreter::Interpreter(const std::vector<std::string>& arguments)
{
    try
    {
        modules::ErrorHandler::error("Hello world!");
    }
    catch (std::exception& e)
    {}

    modules::ErrorHandler::warning("Hello world!");
    modules::ErrorHandler::notice("Hello world!");

    // Main program body
}

#include "Interpreter.hpp"

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

#include <iostream>

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

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

        Lexer lexer(arguments.at(0));

        Token token;

        do
        {
            token = lexer.nextToken();

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

Create a simple example of file tokenization


#include <qapplication.h>
#include <MainApplication/Gui/MainWindow.hpp>

#include <Core/CoreMacros.hpp>

#ifdef OS_LINUX
#include <X11/Xlib.h>
#endif

int main(int argc, char** argv)
{
#ifdef OS_LINUX
    XInitThreads();
#endif
    QApplication app(argc, argv);

    QSurfaceFormat format;
    format.setVersion(4, 4);
    format.setProfile(QSurfaceFormat::CoreProfile);
    format.setSamples(0);
    format.setDepthBufferSize(24);
    format.setStencilBufferSize(8);
    format.setSamples(16);
    format.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
    QSurfaceFormat::setDefaultFormat(format);

    Ra::MainWindow w;
    w.show();
    return app.exec();
}

#include <qapplication.h>
#include <MainApplication/Gui/MainWindow.hpp>

#include <Core/CoreMacros.hpp>

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

    QSurfaceFormat format;
    format.setVersion(4, 4);
    format.setProfile(QSurfaceFormat::CoreProfile);
    format.setSamples(0);
    format.setDepthBufferSize(24);
    format.setStencilBufferSize(8);
    format.setSamples(16);
    format.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
    QSurfaceFormat::setDefaultFormat(format);

    Ra::MainWindow w;
    w.show();
    return app.exec();
}

Remove useless X11 threads on linux


#include <stdio.h>
// Make sure ASan doesn't hang in an exec loop if DYLD_INSERT_LIBRARIES is set.
// This is a regression test for
// https://code.google.com/p/address-sanitizer/issues/detail?id=159

// RUN: %clangxx_asan -m64 %s -o %t
// RUN: %clangxx -m64 %p/../SharedLibs/darwin-dummy-shared-lib-so.cc \
// RUN:     -dynamiclib -o darwin-dummy-shared-lib-so.dylib

// If the test hangs, kill it after 15 seconds.
// RUN: DYLD_INSERT_LIBRARIES=darwin-dummy-shared-lib-so.dylib \
// RUN:     alarm 15 %t 2>&1 | FileCheck %s || exit 1
#include <stdlib.h>

int main() {
  const char kEnvName[] = "DYLD_INSERT_LIBRARIES";
  printf("%s=%s\n", kEnvName, getenv(kEnvName));
  // CHECK: {{DYLD_INSERT_LIBRARIES=.*darwin-dummy-shared-lib-so.dylib.*}}
  return 0;
}

#include <stdio.h>
// Make sure ASan doesn't hang in an exec loop if DYLD_INSERT_LIBRARIES is set.
// This is a regression test for
// https://code.google.com/p/address-sanitizer/issues/detail?id=159

// RUN: %clangxx_asan -m64 %s -o %t
// RUN: %clangxx -m64 %p/../SharedLibs/darwin-dummy-shared-lib-so.cc \
// RUN:     -dynamiclib -o darwin-dummy-shared-lib-so.dylib

// FIXME: the following command line may hang in the case of a regression.
// RUN: DYLD_INSERT_LIBRARIES=darwin-dummy-shared-lib-so.dylib \
// RUN:     %t 2>&1 | FileCheck %s || exit 1
#include <stdlib.h>

int main() {
  const char kEnvName[] = "DYLD_INSERT_LIBRARIES";
  printf("%s=%s\n", kEnvName, getenv(kEnvName));
  // CHECK: {{DYLD_INSERT_LIBRARIES=.*darwin-dummy-shared-lib-so.dylib.*}}
  return 0;
}

Remove the 'alarm' script which isn't present on OS X by default. The test may hang now if a regression occurs.


/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * 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 <thrift/lib/cpp2/async/ClientChannel.h>

#include <thrift/lib/cpp2/PluggableFunction.h>

namespace apache {
namespace thrift {
namespace {
THRIFT_PLUGGABLE_FUNC_REGISTER(std::optional<std::string>, getClientHostId) {
  return {};
}
} // namespace

/* static */ const std::optional<std::string>& ClientChannel::getHostId() {
  static const auto& hostId =
      *new std::optional<std::string>{THRIFT_PLUGGABLE_FUNC(getClientHostId)()};
  return hostId;
}
} // namespace thrift
} // namespace apache

/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * 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 <thrift/lib/cpp2/async/ClientChannel.h>

#ifdef __linux__
#include <sys/utsname.h>
#endif

#include <thrift/lib/cpp2/PluggableFunction.h>

namespace apache {
namespace thrift {
namespace {
THRIFT_PLUGGABLE_FUNC_REGISTER(std::optional<std::string>, getClientHostId) {
#ifdef __linux__
  struct utsname bufs;
  ::uname(&bufs);
  return bufs.nodename;
#else
  return {};
#endif
}
} // namespace

/* static */ const std::optional<std::string>& ClientChannel::getHostId() {
  static const auto& hostId =
      *new std::optional<std::string>{THRIFT_PLUGGABLE_FUNC(getClientHostId)()};
  return hostId;
}
} // namespace thrift
} // namespace apache

Implement getClientHostId with uname() under Linux by default.


#include <boost/assert.hpp>

#include "worker.h"
#include "requests.pb.h"

bool traffic::MessageWorker::process(std::string &result, void *data, size_t size)
{
	(void) result;

	request::Request request;
	request.ParseFromArray(data, size);

	if (request.has_statistic())
		return process_statistics();
	else if (request.has_summary())
		return process_summary();

	BOOST_ASSERT(false && "Unknown message type");

	return false;
}

#include <boost/assert.hpp>

#include "worker.h"
#include "requests.pb.h"

bool traffic::MessageWorker::process(std::string &result, void *data, size_t size)
{
	(void) result;

	request::Request request;
	request.ParseFromArray(data, size);

	switch (request.Payload_case()) {
		case request::Request::kStatistic:
			return process_statistics();
		case request::Request::kSummary:
			return process_summary();
		case request::Request::PAYLOAD_NOT_SET:
			return false;
	}

	BOOST_ASSERT(false && "Message parsing failed!");

	return false;
}

Use the generated oneo proto enum


#include "gtest/gtest.h"

#include "Models/ChisqModel.hpp"
#include "Models/PosteriorSamplers/ZeroMeanGaussianConjSampler.hpp"
#include "Models/StateSpace/DynamicRegression.hpp"
#include "Models/StateSpace/StateModels/LocalLevelStateModel.hpp"
#include "Models/StateSpace/StateModels/SeasonalStateModel.hpp"
#include "Models/StateSpace/StateSpaceModel.hpp"
#include "Models/MvnGivenScalarSigma.hpp"
#include "Models/Glm/PosteriorSamplers/BregVsSampler.hpp"
#include "Models/Glm/VariableSelectionPrior.hpp"

#include "distributions.hpp"

#include "test_utils/test_utils.hpp"
#include "Models/StateSpace/tests/state_space_test_utils.hpp"
#include "stats/AsciiDistributionCompare.hpp"

#include <fstream>

namespace {
  using namespace BOOM;
  using namespace BOOM::StateSpace;
  using std::endl;
  using std::cout;

  class RegressionDataTimePointTest : public ::testing::Test {
   protected:

  };

  TEST_F(RegressionDataTimePointTest, blah) {
    NEW(RegressionDataTimePoint, dp)();
    EXPECT_EQ(0, dp->sample_size());
    EXPECT_FALSE(dp->using_suf());
  }

  class DynamicRegressionModelTest : public ::testing::Test {
   protected:

  };

}  // namespace

#include "gtest/gtest.h"

#include "Models/ChisqModel.hpp"
#include "Models/PosteriorSamplers/ZeroMeanGaussianConjSampler.hpp"
#include "Models/StateSpace/DynamicRegression.hpp"
#include "Models/StateSpace/StateModels/LocalLevelStateModel.hpp"
#include "Models/StateSpace/StateModels/SeasonalStateModel.hpp"
#include "Models/StateSpace/StateSpaceModel.hpp"
#include "Models/MvnGivenScalarSigma.hpp"
#include "Models/Glm/PosteriorSamplers/BregVsSampler.hpp"
#include "Models/Glm/VariableSelectionPrior.hpp"

#include "distributions.hpp"

#include "test_utils/test_utils.hpp"
#include "Models/StateSpace/tests/state_space_test_utils.hpp"
#include "stats/AsciiDistributionCompare.hpp"

#include <fstream>

namespace {
  using namespace BOOM;
  using namespace BOOM::StateSpace;
  using std::endl;
  using std::cout;

  class RegressionDataTimePointTest : public ::testing::Test {
   protected:
    RegressionDataTimePointTest() {}
  };

  TEST_F(RegressionDataTimePointTest, blah) {
    NEW(RegressionDataTimePoint, dp)();
    EXPECT_EQ(0, dp->sample_size());
    EXPECT_FALSE(dp->using_suf());
  }

  class DynamicRegressionModelTest : public ::testing::Test {
   protected:

  };

}  // namespace

Test file for dynamic regression model.


#include "UnixExecutablePathValidator.h"

using namespace clt::filesystem::entities;
using namespace clt::filesystem::entities::validators;

bool
UnixExecutablePathValidator::isPathValid(const Path& path, std::vector<ValidatorBrokenRules> & brokenRules) const {
//TODO: must be a file with executable right
	return path.exists()
		&& !path.isDirectory()
		&& path.isExecutable();
}

#include "UnixExecutablePathValidator.h"

using namespace clt::filesystem::entities;
using namespace clt::filesystem::entities::validators;

bool
UnixExecutablePathValidator::isPathValid(const Path& path, std::vector<ValidatorBrokenRules> & brokenRules) const {
	if (!path.exists()) {
		brokenRules.push_back(ValidatorBrokenRules("Path does not exist"));
		return false;
	}

	if (path.isDirectory()) {
		brokenRules.push_back(ValidatorBrokenRules("The path is not a file"));
		return false;
	}

	if (!path.isExecutable()) {
		brokenRules.push_back(ValidatorBrokenRules("File at path is not executable"));
		return false;
	}

	return true;
}

Add exception management on Unix


/** @file
 *
 *  A brief file description
 *
 *  @section license License
 *
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you 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 CATCH_CONFIG_MAIN
#include <catch.hpp>

/* vim: set sts=4 sw=4 ts=4 tw=79 et: */

/** @file
 *
 *  A brief file description
 *
 *  @section license License
 *
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you 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 CATCH_CONFIG_RUNNER
#include <catch.hpp>
#include <spl/list.h>
#include <sys/zfs_debug.h>

int main(int argc, char* const argv[])
{
    // Enable all debugging flags for the tests.
    zfs_flags = ~0;

    // Turn on all debug logging.
    setenv("ZFS_DEBUG", "on,long", 0 /* overwrite */);

    return Catch::Session().run(argc, argv);
}

/* vim: set sts=4 sw=4 ts=4 tw=79 et: */

Enable debug output in the tests.


#include <iostream>

int main(int argc, char *argv[]) {
    if (argc != 2) {
        std::cerr << "You must specify exactly a single input filename." << std::endl;
        exit(EXIT_FAILURE);
    }

}

#include <iostream>
#include <fstream>

int main(int argc, char *argv[]) {
    if (argc != 2) {
        std::cerr << "You must specify exactly a single input filename." << std::endl;
        exit(EXIT_FAILURE);
    }

    std::ifstream file(argv[argc - 1]);
    std::ofstream index("index.plain");
    index << file.rdbuf();
    file.close();
    index.close();

    // Only I/O which does not count towards measured time.
    std::cout << "Took 0s to build an index." << std::endl;
}

Implement index building for pairwise levenshtein


#include <iostream>
/* This program computes fibo using
 * and optimization of the matrix way
 */

/*REFERENCES
 * https://en.wikipedia.org/wiki/Fibonacci_number#Matrix_form
 * http://www.geeksforgeeks.org/program-for-nth-fibonacci-number/
 */

using namespace std;

const int MAX = 1000;

int f[MAX] = {0};

int fib(int n){
    if (n == 0)  return 0;
    if (n == 1 || n == 2) return (f[n] = 1);

    if (f[n])  return f[n];
    //pretty good way to know if a number is odd or even
    int k = (n & 1)? (n+1)/2 : n/2;

    f[n] = (n & 1) ? ( fib(k) * fib(k) + fib(k-1) * fib(k-1) )
           : (2*fib(k-1) + fib(k))*fib(k);

    return f[n];
}

int main(){
    int n = 9;
    cout<< fib(n);
    return 0;
}

#include <iostream>
/* This program computes fibo using
 * and optimization of the matrix way
 */

/*REFERENCES
 * This method is contributed by Chirag Agarwal.
 * https://en.wikipedia.org/wiki/Fibonacci_number#Matrix_form
 * http://www.geeksforgeeks.org/program-for-nth-fibonacci-number/
 */

using namespace std;

const int MAX = 1000;

int f[MAX] = {0};

int fib(int n){
    if (n == 0)  return 0;
    if (n == 1 || n == 2) return (f[n] = 1);

    if (f[n])  return f[n];
    //pretty good way to know if a number is odd or even
    int k = (n & 1)? (n+1)/2 : n/2;

    f[n] = (n & 1) ? ( fib(k) * fib(k) + fib(k-1) * fib(k-1) )
           : (2*fib(k-1) + fib(k))*fib(k);

    return f[n];
}

int main(){
    int n = 9;
    cout<< fib(n);
    return 0;
}

Add the contributor of the method


#include "math_container.h"

using std::complex;

/******************************************************/
/*solve the equation cosh(x)=exp(y), input y, return x*/
/******************************************************/
complex<double> coshx_eq_expy(double y)
{
    complex<double> ey={exp(y),0};
    complex<double> gamma=log(ey-sqrt(ey*ey-1.0));

    //Since gamma is pure real or pure imaginary, set it:
    if( abs( gamma.real() ) < abs( gamma.imag() ) )  gamma=complex<double>( 0, gamma.imag() );
    else                                             gamma=complex<double>( gamma.real(), 0 );

    return gamma;
}

Update coshx_eq_expy, make the return value pure real or pure imaginary.


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

#include "chrome/browser/ui/views/frame/browser_non_client_frame_view.h"

#include "chrome/browser/ui/touch/frame/touch_browser_frame_view.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/frame/popup_non_client_frame_view.h"

namespace browser {

BrowserNonClientFrameView* CreateBrowserNonClientFrameView(
    BrowserFrame* frame, BrowserView* browser_view) {
  if (browser_view->IsBrowserTypePopup() ||
      browser_view->IsBrowserTypePanel()) {
    // TODO(anicolao): implement popups for touch
    NOTIMPLEMENTED();
    return new PopupNonClientFrameView(frame);
  } else {
    return new TouchBrowserFrameView(frame, browser_view);
  }
}

}  // browser

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

#include "chrome/browser/ui/views/frame/browser_non_client_frame_view.h"

#include "base/command_line.h"
#include "chrome/browser/ui/panels/panel_browser_frame_view.h"
#include "chrome/browser/ui/panels/panel_browser_view.h"
#include "chrome/browser/ui/touch/frame/touch_browser_frame_view.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/frame/popup_non_client_frame_view.h"
#include "chrome/common/chrome_switches.h"

namespace browser {

BrowserNonClientFrameView* CreateBrowserNonClientFrameView(
    BrowserFrame* frame, BrowserView* browser_view) {
  Browser::Type type = browser_view->browser()->type();
  switch (type) {
    case Browser::TYPE_PANEL:
      if (CommandLine::ForCurrentProcess()->HasSwitch(
              switches::kEnablePanels)) {
        return new PanelBrowserFrameView(
            frame, static_cast<PanelBrowserView*>(browser_view));
      }  // else, fall-through and treat as popup
    case Browser::TYPE_POPUP:
      // TODO(anicolao): implement popups for touch
      NOTIMPLEMENTED();
      return new PopupNonClientFrameView(frame);
    default:
      return new TouchBrowserFrameView(frame, browser_view);
  }
}

}  // browser

Use the normal panel-frame until there's a touch-friendly version.


/*
 * Copyright 2017
 *
 * Made by vincent leroy
 * Mail <vincent.54.leroy@gmail.com>
 */

// Project includes ------------------------------------------------------------
#include "MainWindow.hpp"

// Qt includes -----------------------------------------------------------------
#include <QApplication>
#include <QWidget>
#include <QStyleFactory>
#include <QFileInfo>

// C++ standard library includes -----------------------------------------------
#include <csignal>

namespace
{
    constexpr const auto styleName = "Adwaita-Dark";
}

int main(int ac, char * av[])
{
    std::signal(SIGINT,  [](int){ qApp->quit(); });
    std::signal(SIGTERM, [](int){ qApp->quit(); });

    QApplication app(ac, av);

    QApplication::setOrganizationDomain("vivoka.com");
    QApplication::setOrganizationName("vivoka");
    QApplication::setApplicationName(QFileInfo(av[0]).baseName());
    QApplication::setApplicationVersion("1.6");

    if (QStyleFactory::keys().contains(styleName))
        QApplication::setStyle(QStyleFactory::create(styleName));

    MainWindow w;
    w.restoreState();

    return app.exec();
}

/*
 * Copyright 2017
 *
 * Made by vincent leroy
 * Mail <vincent.54.leroy@gmail.com>
 */

// Project includes ------------------------------------------------------------
#include "MainWindow.hpp"

// Qt includes -----------------------------------------------------------------
#include <QApplication>
#include <QFileInfo>

// C++ standard library includes -----------------------------------------------
#include <csignal>

int main(int ac, char * av[])
{
    std::signal(SIGINT,  [](int){ qApp->quit(); });
    std::signal(SIGTERM, [](int){ qApp->quit(); });

    QApplication app(ac, av);

    QApplication::setOrganizationDomain("vivoka.com");
    QApplication::setOrganizationName("vivoka");
    QApplication::setApplicationName(QFileInfo(av[0]).baseName());
    QApplication::setApplicationVersion("1.6");

    MainWindow w;
    w.restoreState();

    return app.exec();
}

Remove force creation of "Adwaita-Dark" style


#include "../guia1/particionar.cpp"
#include "../config.hpp"
#include <boost/filesystem.hpp>

int main()
{
    vec datos;
    datos.load(config::sourceDir + "/guia2/datos/merval.csv");

    mat tuplas(datos.n_elem - 5, 6);

    for (unsigned int i = 0; i < datos.n_rows - 5; ++i) {
        tuplas.row(i) = datos.rows(span(i, i + 5)).t();
    }

    // FIXME: ¿Hay que randomizar el orden de las tuplas?

    tuplas.save(config::sourceDir + "/guia2/datos/mervalTuplas.csv", csv_ascii);

    vector<ic::Particion> particiones = ic::leaveKOut(tuplas, 47);

    boost::filesystem::create_directory(config::sourceDir + "/guia2/datos/particionesMerval/");
    ic::guardarParticiones(particiones, config::sourceDir + "/guia2/datos/particionesMerval/");

    return 0;
}

#include "../guia1/particionar.cpp"
#include "../config.hpp"
#include <boost/filesystem.hpp>

int main()
{
    arma_rng::set_seed_random();

    vec datos;
    datos.load(config::sourceDir + "/guia2/datos/merval.csv");

    mat tuplas(datos.n_elem - 5, 6);

    for (unsigned int i = 0; i < datos.n_rows - 5; ++i) {
        tuplas.row(i) = datos.rows(span(i, i + 5)).t();
    }

    // FIXME: ¿Hay que randomizar el orden de las tuplas?

    tuplas.save(config::sourceDir + "/guia2/datos/mervalTuplas.csv", csv_ascii);

    vector<ic::Particion> particiones = ic::leaveKOut(tuplas, 47);

    boost::filesystem::create_directory(config::sourceDir + "/guia2/datos/particionesMerval/");
    ic::guardarParticiones(particiones, config::sourceDir + "/guia2/datos/particionesMerval/");

    return 0;
}

Revert "Guia 2 - Particionar Merval: No setear la semilla aleatoria; no estamos"


#include <fcntl.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <glog/logging.h>

namespace {
const uint32_t k_listen_backlog = 100;
}

int create_tcp_listen_socket(int port) {

  struct sockaddr_in addr;

  int socket_fd  = socket(PF_INET, SOCK_STREAM, 0);

  addr.sin_family = AF_INET;
  addr.sin_port = htons(port);
  addr.sin_addr.s_addr = INADDR_ANY;

  if (bind(socket_fd, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
    LOG(FATAL) << "bind error: " << strerror(errno);
    exit(1);
  }

  fcntl(socket_fd, F_SETFL, fcntl(socket_fd, F_GETFL, 0) | O_NONBLOCK);
  listen(socket_fd, k_listen_backlog);

  return socket_fd;
}

#include <fcntl.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <glog/logging.h>

namespace {
const uint32_t k_listen_backlog = 100;
}

int create_tcp_listen_socket(int port) {

  struct sockaddr_in addr;

  int socket_fd  = socket(PF_INET, SOCK_STREAM, 0);

  int reuse_addr = 1;

  if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &reuse_addr,
                 sizeof(reuse_addr)) != 0)
  {
    LOG(ERROR) << "failed to set SO_REUSEADDR in socket";
  }

  addr.sin_family = AF_INET;
  addr.sin_port = htons(port);
  addr.sin_addr.s_addr = INADDR_ANY;

  if (bind(socket_fd, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
    LOG(FATAL) << "bind error: " << strerror(errno);
    exit(1);
  }

  fcntl(socket_fd, F_SETFL, fcntl(socket_fd, F_GETFL, 0) | O_NONBLOCK);
  listen(socket_fd, k_listen_backlog);

  return socket_fd;
}

Set SO_REUSEADDR in listening sockets


#include <stdio.h>
#include "wcl/network/TCPSocket.h"

int main(void)
{
	char buffer[4096];

	try{
		TCPSocket s("10.220.99.84", 55555);
		s.read((char *)buffer, 4096);
		printf("Client: Server Said: %s\n", buffer);
		s.close();
	}
	catch( SocketException* e )
	{
		fprintf( stderr, e->getReason().c_str() );
	}

	return 0;
}

#include <stdio.h>
#include "wcl/network/TCPSocket.h"

int main(void)
{
	char buffer[4096];

	try{
		TCPSocket s("127.0.0.1", 55555);
		s.read((char *)buffer, 4096);
		printf("Client: Server Said: %s\n", buffer);
		s.close();
	}
	catch( SocketException* e )
	{
		fprintf( stderr, e->getReason().c_str() );
	}

	return 0;
}

Use localhost by default in our test network client


#include "gtest/gtest.h"

#include "Token.hpp"

class SemanticAnalyser
{
public:
  bool analyse(const Tokens& tokens)
  {
    return tokens.empty();
  }
};

constexpr Token createTokenWithZeroValue(TokenType type)
{
  return {type, 0};
}

TEST(SemanticAnalyserTest, ShouldAcceptEmptyTokens)
{
  SemanticAnalyser analyser;
  Tokens tokens{};
  ASSERT_TRUE(analyser.analyse(tokens));
}

TEST(SemanticAnalyserTest, ShouldNotAcceptInvalidInstructionSet)
{
  SemanticAnalyser analyser;
  Tokens tokens{createTokenWithZeroValue(TokenType::Ld)};
  ASSERT_FALSE(analyser.analyse(tokens));
}

#include "gtest/gtest.h"

#include "Token.hpp"

class SemanticAnalyser
{
public:
  bool analyse(const Tokens& tokens)
  {
    return tokens.empty();
  }
};

using namespace ::testing;

struct SemanticAnalyserTest : public Test
{
  SemanticAnalyser analyser;
  static constexpr Token createTokenWithZeroValue(TokenType type)
  {
    return
    { type, 0};
  }
};

TEST_F(SemanticAnalyserTest, ShouldAcceptEmptyTokens)
{
  Tokens tokens{};
  ASSERT_TRUE(analyser.analyse(tokens));
}

TEST_F(SemanticAnalyserTest, ShouldNotAcceptInvalidInstructionSet)
{
  Tokens tokens{createTokenWithZeroValue(TokenType::Ld)};
  ASSERT_FALSE(analyser.analyse(tokens));
}

Add test suite to Analyser


//===- Error.cpp ----------------------------------------------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "Error.h"
#include "Config.h"

#include "llvm/ADT/Twine.h"
#include "llvm/Support/raw_ostream.h"

namespace lld {
namespace elf {

bool HasError;
llvm::raw_ostream *ErrorOS;

void log(const Twine &Msg) {
  if (Config->Verbose)
    llvm::outs() << Msg << "\n";
}

void warning(const Twine &Msg) {
  if (Config->FatalWarnings)
    error(Msg);
  else
    llvm::errs() << Msg << "\n";
}

void error(const Twine &Msg) {
  *ErrorOS << Msg << "\n";
  HasError = true;
}

void error(std::error_code EC, const Twine &Prefix) {
  if (EC)
    error(Prefix + ": " + EC.message());
}

void fatal(const Twine &Msg) {
  llvm::errs() << Msg << "\n";
  exit(1);
}

void fatal(const Twine &Msg, const Twine &Prefix) {
  fatal(Prefix + ": " + Msg);
}

void check(std::error_code EC) {
  if (EC)
    fatal(EC.message());
}

} // namespace elf
} // namespace lld

//===- Error.cpp ----------------------------------------------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "Error.h"
#include "Config.h"

#include "llvm/ADT/Twine.h"
#include "llvm/Support/raw_ostream.h"

using namespace llvm;

namespace lld {
namespace elf {

bool HasError;
raw_ostream *ErrorOS;

void log(const Twine &Msg) {
  if (Config->Verbose)
    outs() << Msg << "\n";
}

void warning(const Twine &Msg) {
  if (Config->FatalWarnings)
    error(Msg);
  else
    errs() << Msg << "\n";
}

void error(const Twine &Msg) {
  *ErrorOS << Msg << "\n";
  HasError = true;
}

void error(std::error_code EC, const Twine &Prefix) {
  if (EC)
    error(Prefix + ": " + EC.message());
}

void fatal(const Twine &Msg) {
  errs() << Msg << "\n";
  exit(1);
}

void fatal(const Twine &Msg, const Twine &Prefix) {
  fatal(Prefix + ": " + Msg);
}

void check(std::error_code EC) {
  if (EC)
    fatal(EC.message());
}

} // namespace elf
} // namespace lld

Use "using namespace llvm" like the rest of ELF lld.


// Test to check if we handle pic code properly.

// RUN: %clangxx_xray -fxray-instrument -std=c++11 -fpic %s -o %t
// RUN: XRAY_OPTIONS="patch_premain=true verbosity=1 xray_logfile_base=pic-test-logging-" %run %t 2>&1 | FileCheck %s
// After all that, clean up the output xray log.
//
// RUN: rm pic-test-logging-*

#include <cstdio>

[[clang::xray_always_instrument]]
unsigned short foo (unsigned b);

[[clang::xray_always_instrument]]
unsigned short bar (unsigned short a)
{
  printf("bar() is always instrumented!\n");
  return foo(a);
}

unsigned short foo (unsigned b)
{
  printf("foo() is always instrumented!\n");
  return b + b + 5;
}

int main ()
{
  // CHECK: XRay: Log file in 'pic-test-logging-{{.*}}'
  bar(10);
  // CHECK: bar() is always instrumented!
  // CHECK-NEXT: foo() is always instrumented!
}

// Test to check if we handle pic code properly.

// RUN: %clangxx_xray -fxray-instrument -std=c++11 -ffunction-sections \
// RUN:     -fdata-sections -fpic -fpie -Wl,--gc-sections %s -o %t
// RUN: XRAY_OPTIONS="patch_premain=true verbosity=1 xray_logfile_base=pic-test-logging-" %run %t 2>&1 | FileCheck %s
// After all that, clean up the output xray log.
//
// RUN: rm pic-test-logging-*

#include <cstdio>

[[clang::xray_always_instrument]]
unsigned short foo (unsigned b);

[[clang::xray_always_instrument]]
unsigned short bar (unsigned short a)
{
  printf("bar() is always instrumented!\n");
  return foo(a);
}

unsigned short foo (unsigned b)
{
  printf("foo() is always instrumented!\n");
  return b + b + 5;
}

int main ()
{
  // CHECK: XRay: Log file in 'pic-test-logging-{{.*}}'
  bar(10);
  // CHECK: bar() is always instrumented!
  // CHECK-NEXT: foo() is always instrumented!
}

Expand the PIC test case for XRay


#if defined(WIN32) && !defined(_DEBUG)
#pragma comment(linker, "/SUBSYSTEM:WINDOWS /entry:mainCRTStartup")
#endif

#include "Application.h"

#include <memory>

#include <gloperate-qtapplication/Viewer.h>

#include <widgetzeug/dark_fusion_style.hpp>

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

    widgetzeug::enableDarkFusionStyle();

    std::unique_ptr<gloperate_qtapplication::Viewer> viewer(new gloperate_qtapplication::Viewer()); // make_unique is C++14
    viewer->show();

    return app.exec();
}

#if defined(WIN32) && !defined(_DEBUG)
#pragma comment(linker, "/SUBSYSTEM:WINDOWS /entry:mainCRTStartup")
#endif

#include "Application.h"

#include <memory>

#include <gloperate-qtapplication/Viewer.h>

#include <widgetzeug/dark_fusion_style.hpp>

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

    widgetzeug::enableDarkFusionStyle();

    gloperate_qtapplication::Viewer viewer;
    viewer.show();

    return app.exec();
}

Remove unnecessary use of heap allocation


// RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm -debug-info-kind=line-tables-only %s -o - | FileCheck %s
// Crasher for PR22929.
class Base {
  virtual void VariadicFunction(...);
};

class Derived : public virtual Base {
  virtual void VariadicFunction(...);
};

void Derived::VariadicFunction(...) { }

// CHECK: define void @_ZN7Derived16VariadicFunctionEz({{.*}} !dbg ![[SP:[0-9]+]]
// CHECK: ret void, !dbg ![[LOC:[0-9]+]]
// CHECK-LABEL: define void @_ZT{{.+}}N7Derived16VariadicFunctionEz(
// CHECK: ret void, !dbg ![[LOC:[0-9]+]]
//
// CHECK: ![[SP]] = distinct !DISubprogram(name: "VariadicFunction"
// CHECK: ![[LOC]] = !DILocation({{.*}}scope: ![[SP]])

// RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm -debug-info-kind=line-tables-only %s -o - | FileCheck %s
// Crasher for PR22929.
class Base {
  virtual void VariadicFunction(...);
};

class Derived : public virtual Base {
  virtual void VariadicFunction(...);
};

void Derived::VariadicFunction(...) { }

// CHECK: define void @_ZN7Derived16VariadicFunctionEz({{.*}} !dbg ![[SP:[0-9]+]]
// CHECK: ret void, !dbg ![[LOC:[0-9]+]]
// CHECK: define void @_ZT{{.+}}N7Derived16VariadicFunctionEz({{.*}} !dbg ![[SP_I:[0-9]+]]
// CHECK: ret void, !dbg ![[LOC_I:[0-9]+]]
//
// CHECK: ![[SP]] = distinct !DISubprogram(name: "VariadicFunction"
// CHECK: ![[LOC]] = !DILocation({{.*}}scope: ![[SP]])
// CHECK: ![[SP_I]] = distinct !DISubprogram(name: "VariadicFunction"
// CHECK: ![[LOC_I]] = !DILocation({{.*}}scope: ![[SP_I]])

Update testcase for upstream LLVM changes.


#include "highlighter.hh"

#include "buffer_utils.hh"

namespace Kakoune
{

void Highlighter::highlight(HighlightContext context, DisplayBuffer& display_buffer, BufferRange range)
{
    if (context.pass & m_passes) try
    {
        do_highlight(context, display_buffer, range);
    }
    catch (runtime_error& error)
    {
        write_to_debug_buffer(format("Error while highlighting: {}", error.what()));
    }
}

void Highlighter::compute_display_setup(HighlightContext context, DisplaySetup& setup) const
{
    if (context.pass & m_passes)
        do_compute_display_setup(context, setup);
}

bool Highlighter::has_children() const
{
    return false;
}

Highlighter& Highlighter::get_child(StringView path)
{
    throw runtime_error("this highlighter do not hold children");
}

void Highlighter::add_child(HighlighterAndId&& hl)
{
    throw runtime_error("this highlighter do not hold children");
}

void Highlighter::remove_child(StringView id)
{
    throw runtime_error("this highlighter do not hold children");
}

Completions Highlighter::complete_child(StringView path, ByteCount cursor_pos, bool group) const
{
    throw runtime_error("this highlighter do not hold children");
}

void Highlighter::fill_unique_ids(Vector<StringView>& unique_ids) const
{}

}

#include "highlighter.hh"

#include "buffer_utils.hh"

namespace Kakoune
{

void Highlighter::highlight(HighlightContext context, DisplayBuffer& display_buffer, BufferRange range)
{
    if (context.pass & m_passes) try
    {
        do_highlight(context, display_buffer, range);
    }
    catch (runtime_error& error)
    {
        write_to_debug_buffer(format("Error while highlighting: {}", error.what()));
    }
}

void Highlighter::compute_display_setup(HighlightContext context, DisplaySetup& setup) const
{
    if (context.pass & m_passes)
        do_compute_display_setup(context, setup);
}

bool Highlighter::has_children() const
{
    return false;
}

Highlighter& Highlighter::get_child(StringView path)
{
    throw runtime_error("this highlighter does not hold children");
}

void Highlighter::add_child(HighlighterAndId&& hl)
{
    throw runtime_error("this highlighter does not hold children");
}

void Highlighter::remove_child(StringView id)
{
    throw runtime_error("this highlighter does not hold children");
}

Completions Highlighter::complete_child(StringView path, ByteCount cursor_pos, bool group) const
{
    throw runtime_error("this highlighter does not hold children");
}

void Highlighter::fill_unique_ids(Vector<StringView>& unique_ids) const
{}

}

Fix grammar in highlight error message


#include <bonefish/wamp_dealer.hpp>
#include <bonefish/wamp_session.hpp>
#include <iostream>

namespace bonefish {

wamp_dealer::wamp_dealer()
    : m_sessions()
{
}

wamp_dealer::~wamp_dealer()
{
}

bool wamp_dealer::attach_session(const std::shared_ptr<wamp_session>& session)
{
    std::cerr << "attach session: " << session->get_session_id() << std::endl;
    auto result = m_sessions.insert(
            std::make_pair(session->get_session_id(), std::move(session)));
    return result.second;
}

bool wamp_dealer::detach_session(const wamp_session_id& session_id)
{
    std::cerr << "detach session:" << session_id << std::endl;
    return m_sessions.erase(session_id) == 1;
}

} // namespace bonefish

#include <bonefish/wamp_dealer.hpp>
#include <bonefish/wamp_session.hpp>
#include <iostream>

namespace bonefish {

wamp_dealer::wamp_dealer()
    : m_sessions()
{
}

wamp_dealer::~wamp_dealer()
{
}

bool wamp_dealer::attach_session(const std::shared_ptr<wamp_session>& session)
{
    std::cerr << "attach session: " << session->get_session_id() << std::endl;
    auto result = m_sessions.insert(std::make_pair(session->get_session_id(), session));
    return result.second;
}

bool wamp_dealer::detach_session(const wamp_session_id& session_id)
{
    std::cerr << "detach session:" << session_id << std::endl;
    return m_sessions.erase(session_id) == 1;
}

} // namespace bonefish

Fix incorrect move of shared session pointer.


#include <iostream>
#include "CompileToBash.h"
#include "Parser.h"

void compile_to_bash(std::ostream &os, Bish::AST *ast) {
    Bish::CompileToBash compile(os);
    ast->accept(&compile);
}

int main(int argc, char **argv) {
    if (argc < 2) {
        std::cerr << "USAGE: " << argv[0] << " <INPUT>\n";
        std::cerr << "  Compiles Bish file <INPUT> to bash.\n";
        return 1;
    }

    std::string path(argv[1]);
    Bish::Parser p;
    Bish::AST *ast = p.parse(path);

    compile_to_bash(std::cout, ast);

    return 0;
}

#include <iostream>
#include "CompileToBash.h"
#include "Parser.h"

void compile_to_bash(std::ostream &os, Bish::AST *ast) {
    os << "#!/bin/bash\n";
    Bish::CompileToBash compile(os);
    ast->accept(&compile);
}

int main(int argc, char **argv) {
    if (argc < 2) {
        std::cerr << "USAGE: " << argv[0] << " <INPUT>\n";
        std::cerr << "  Compiles Bish file <INPUT> to bash.\n";
        return 1;
    }

    std::string path(argv[1]);
    Bish::Parser p;
    Bish::AST *ast = p.parse(path);

    compile_to_bash(std::cout, ast);

    return 0;
}

Add bash shebang (is that what it's called?) to bash output.


//
//  CRectangleShape.cpp
//  MenuTest
//
//  Created by Tim Brier on 14/05/2015.
//
//

#include "CRectangleShape.hpp"

CRectangleShape::CRectangleShape(CVector2f size)
{
    CRectangleShape(size.x, size.y);
}

CRectangleShape::CRectangleShape(float width, float height)
: CConvexShape(4)
{
    setPoint(0, CVector2f(0.0f, 0.0f));
    setPoint(1, CVector2f(width, 0.0f));
    setPoint(2, CVector2f(width, height));
    setPoint(3, CVector2f(0.0f, height));
}

CRectangleShape::~CRectangleShape()
{

}

//
//  CRectangleShape.cpp
//  MenuTest
//
//  Created by Tim Brier on 14/05/2015.
//
//

#include "CRectangleShape.hpp"

CRectangleShape::CRectangleShape(CVector2f size)
: CRectangleShape(size.x, size.y)
{

}

CRectangleShape::CRectangleShape(float width, float height)
: CConvexShape(4)
{
    setPoint(0, CVector2f(0.0f, 0.0f));
    setPoint(1, CVector2f(width, 0.0f));
    setPoint(2, CVector2f(width, height));
    setPoint(3, CVector2f(0.0f, height));
}

CRectangleShape::~CRectangleShape()
{

}

Update overloaded constructor so it actually works


#include <random>
#include <vector>
#include <algorithm>
#include "Statistic.hpp"

#include <cstdlib>

namespace cctag {
namespace numerical {

static constexpr size_t MAX_POINTS = 1000;
static constexpr size_t MAX_RANDOMNESS = 10000000;

struct Randomness : public std::vector<unsigned short>
{
  Randomness();
};

static Randomness randomness;

Randomness::Randomness() : std::vector<unsigned short>(MAX_RANDOMNESS)
{
  std::ranlux24 engine;
  engine.seed(2718282);
  std::uniform_int_distribution<int> dist(0, MAX_POINTS);
  for (size_t i = 0; i < MAX_RANDOMNESS; ++i)
    randomness[i] = dist(engine);
}

void rand_5_k(std::array<int, 5>& perm, size_t N)
{
  static thread_local int sourceIndex = 0;

  auto it = perm.begin();
  int r;

  for (int i = 0; i < 5; ++i) {
retry:
    do {
      if (sourceIndex >= MAX_RANDOMNESS) sourceIndex = 0;
      r = randomness[sourceIndex++];
    } while (r >= N);
    if (std::find(perm.begin(), it, r) != it)
      goto retry;
    *it++ = r;
  }
}

}
}

#include <algorithm>
#include "Statistic.hpp"
#include "utils/pcg_random.hpp"

namespace cctag {
namespace numerical {

void rand_5_k(std::array<int, 5>& perm, size_t N)
{
  static thread_local pcg32 rng(271828);

  auto it = perm.begin();
  int r;

  for (int i = 0; i < 5; ++i) {
    do {
      r = rng(N);
    } while (std::find(perm.begin(), it, r) != it);
    *it++ = r;
  }
}

}
}

Use PCG32 instead of table for rand_5_k.


#include <stdio.h>
#include <stdlib.h>

int *list;
int size;
int sum;

int main(void)
{
    size = 9;
    sum = 15;
    list = (int *)malloc(sizeof(int) * size);

    list[0] = 1;
    list[1] = 5;
    list[2] = 8;
    list[3] = 3;
    list[4] = 7;
    list[5] = 12;
    list[6] = 11;
    list[7] = 2;
    list[8] = 6;

    func(size - 1);

    free(list);

    return 0;
}

Add test case in main()


#include <omp.h>

#include "proctor/detector.h"
#include "proctor/proctor.h"
#include "proctor/scanning_model_source.h"

using pcl::proctor::Detector;
//using pcl::proctor::ProctorMPI;
using pcl::proctor::Proctor;
using pcl::proctor::ScanningModelSource;

Detector detector;
Proctor proctor;

int main(int argc, char **argv) {
  unsigned int model_seed = 2;
  unsigned int test_seed = 0; //time(NULL);
  if (argc >= 2) model_seed = atoi(argv[1]);
  if (argc >= 3) test_seed = atoi(argv[2]);

  ScanningModelSource model_source("Princeton", "/home/justin/Documents/benchmark/db");
  model_source.loadModels();

  //detector.enableVisualization();
  proctor.setModelSource(&model_source);
  proctor.train(detector);
  proctor.test(detector, test_seed);
  proctor.printResults(detector);

  while (true) {}

  return 0;
}

#include <omp.h>

#include "proctor/detector.h"
#include "proctor/proctor.h"
#include "proctor/scanning_model_source.h"

using pcl::proctor::Detector;
//using pcl::proctor::ProctorMPI;
using pcl::proctor::Proctor;
using pcl::proctor::ScanningModelSource;

Detector detector;
Proctor proctor;

int main(int argc, char **argv) {
  unsigned int model_seed = 2;
  unsigned int test_seed = 0; //time(NULL);
  if (argc >= 2) model_seed = atoi(argv[1]);
  if (argc >= 3) test_seed = atoi(argv[2]);

  ScanningModelSource model_source("Princeton", "/home/justin/Documents/benchmark/db");
  model_source.loadModels();

  //detector.enableVisualization();
  proctor.setModelSource(&model_source);
  proctor.train(detector);
  proctor.test(detector, test_seed);
  proctor.printResults(detector);

  sleep(100000);

  return 0;
}

Use sleep instead of a busy-wait while loop to retain the output.


#include "canwrite.h"
#include "canutil_pic32.h"
#include "bitfield.h"
#include "log.h"

void copyToMessageBuffer(uint64_t source, uint8_t* destination) {
    for(int i = 0; i < 8; i++) {
        destination[i] = ((uint8_t*)&source)[i];
    }
}

bool sendCanMessage(CanBus* bus, CanMessage request) {
    CAN::TxMessageBuffer* message = CAN_CONTROLLER(bus)->getTxMessageBuffer(
            CAN::CHANNEL0);
    if (message != NULL) {
        message->messageWord[0] = 0;
        message->messageWord[1] = 0;
        message->messageWord[2] = 0;
        message->messageWord[3] = 0;

        message->msgSID.SID = request.id;
        message->msgEID.IDE = 0;
        message->msgEID.DLC = 8;
        memset(message->data, 0, 8);
        copyToMessageBuffer(request.data, message->data);

        // Mark message as ready to be processed
        CAN_CONTROLLER(bus)->updateChannel(CAN::CHANNEL0);
        CAN_CONTROLLER(bus)->flushTxChannel(CAN::CHANNEL0);
        return true;
    } else {
        debug("Unable to get TX message area");
    }
    return false;
}

#include "canwrite.h"
#include "canutil_pic32.h"
#include "bitfield.h"
#include "log.h"

void copyToMessageBuffer(uint64_t source, uint8_t* destination) {
    for(int i = 0; i < 8; i++) {
        destination[i] = ((uint8_t*)&source)[i];
    }
}

bool sendCanMessage(CanBus* bus, CanMessage request) {
    CAN::TxMessageBuffer* message = CAN_CONTROLLER(bus)->getTxMessageBuffer(
            CAN::CHANNEL0);
    if (message != NULL) {
        message->messageWord[0] = 0;
        message->messageWord[1] = 0;
        message->messageWord[2] = 0;
        message->messageWord[3] = 0;

        message->msgSID.SID = request.id;
        message->msgEID.IDE = 0;
        message->msgEID.DLC = 8;
        memset(message->data, 0, 8);
        copyToMessageBuffer(request.data, message->data);

        // Mark message as ready to be processed
        CAN_CONTROLLER(bus)->updateChannel(CAN::CHANNEL0);
        CAN_CONTROLLER(bus)->flushTxChannel(CAN::CHANNEL0);
        return true;
    } else {
        debug("Unable to get TX message area\r\n");
    }
    return false;
}

Add newline to end of another debug message.


/*
 * Copyright (c) 2014 Samsung Electronics Co., Ltd.
 *
 * 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.
 *
 */

// CLASS HEADER
#include <adaptor-impl.h>

// EXTERNAL INCLUDES
#ifdef OVER_TIZEN_SDK_2_2
#include <app.h>
#endif

namespace Dali
{

namespace Internal
{

namespace Adaptor
{

void Adaptor::GetDataStoragePath( std::string& path)
{
  path = "";
#ifdef OVER_TIZEN_SDK_2_2
  char *pathInt = app_get_data_path();
  if ( pathInt )
  {
    path = pathInt;
  }
#endif
}

} // namespace Adaptor

} // namespace Internal

} // namespace Dali

/*
 * Copyright (c) 2014 Samsung Electronics Co., Ltd.
 *
 * 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.
 *
 */

// CLASS HEADER
#include <adaptor-impl.h>

// EXTERNAL INCLUDES
#ifdef OVER_TIZEN_SDK_2_2
#include <app.h>
#endif

namespace Dali
{

namespace Internal
{

namespace Adaptor
{

void Adaptor::GetDataStoragePath( std::string& path)
{
  path = "";
#ifdef OVER_TIZEN_SDK_2_2
  char *pathInt = app_get_data_path();
  if ( pathInt )
  {
    path = pathInt;
    free( pathInt );
  }
#endif
}

} // namespace Adaptor

} // namespace Internal

} // namespace Dali

Fix a prevent issue - Resource leak


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

#include "net/base/network_change_notifier_win.h"

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

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

namespace net {

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

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

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

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

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

}  // namespace net

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

#include "net/base/network_change_notifier_win.h"

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

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

namespace net {

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

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

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

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

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

}  // namespace net

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


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

#include "net/disk_cache/cache_util.h"

#include "base/file_util.h"
#include "base/logging.h"
#include "base/string_util.h"

namespace disk_cache {

bool MoveCache(const std::wstring& from_path, const std::wstring& to_path) {
  // Just use the version from base.
  return file_util::Move(from_path.c_str(), to_path.c_str());
}

void DeleteCache(const std::wstring& path, bool remove_folder) {
  if (remove_folder) {
    file_util::Delete(path, false);
  } else {
    std::wstring name(path);
    // TODO(rvargas): Fix this after file_util::delete is fixed.
    // file_util::AppendToPath(&name, L"*");
    file_util::Delete(name, true);
  }
}

bool DeleteCacheFile(const std::wstring& name) {
  return file_util::Delete(name, false);
}

void WaitForPendingIO(int* num_pending_io) {
  if (*num_pending_io) {
    NOTIMPLEMENTED();
  }
}

}  // namespace disk_cache

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

#include "net/disk_cache/cache_util.h"

#include "base/file_util.h"
#include "base/logging.h"
#include "base/string_util.h"

namespace disk_cache {

bool MoveCache(const std::wstring& from_path, const std::wstring& to_path) {
  // Just use the version from base.
  return file_util::Move(from_path.c_str(), to_path.c_str());
}

void DeleteCache(const std::wstring& path, bool remove_folder) {
  file_util::FileEnumerator iter(path, /* recursive */ false,
                                 file_util::FileEnumerator::FILES);
  for (std::wstring file = iter.Next(); !file.empty(); file = iter.Next()) {
    if (!file_util::Delete(file, /* recursive */ false))
      NOTREACHED();
  }

  if (remove_folder) {
    if (!file_util::Delete(path, /* recursive */ false))
      NOTREACHED();
  }
}

bool DeleteCacheFile(const std::wstring& name) {
  return file_util::Delete(name, false);
}

void WaitForPendingIO(int* num_pending_io) {
  if (*num_pending_io) {
    NOTIMPLEMENTED();
  }
}

}  // namespace disk_cache

Fix DeleteCache on POSIX. It wasn't successfully deleting before.


/***
    This is a simple demo project that you can copy to get started.
    Comments blocks starting with '***' and subsequent non-empty lines
    are automatically added to this project's wiki page.
*/

#include <stdio.h>

#include <vector>
#include <iostream>

#include "Maxfiles.h"
#include "MaxSLiCInterface.h"

int main(void)
{

  const int inSize = 384;

  std::vector<int> a(inSize), b(inSize), expected(inSize), out(inSize, 0);

  for(int i = 0; i < inSize; ++i) {
    a[i] = i + 1;
    b[i] = i - 1;
    expected[i] = 2 * i;
  }

  std::cout << "Running on DFE." << std::endl;
  Demo(inSize, &a[0], &b[0], &out[0]);

  /***
      Note that you should always test the output of your DFE
      design against a CPU version to ensure correctness.
  */
  for (int i = 0; i < inSize; i++)
    if (out[i] != expected[i]) {
      printf("Output from DFE did not match CPU: %d : %d != %d\n",
        i, out[i], expected[i]);
      return 1;
    }

  std::cout << "Test passed!" << std::endl;
  return 0;
}

/***
    This is a simple demo project that you can copy to get started.
    Comments blocks starting with '***' and subsequent non-empty lines
    are automatically added to this project's wiki page.
*/

#include <stdio.h>

#include <vector>
#include <iostream>

#include "Maxfiles.h"
#include "MaxSLiCInterface.h"

int main(void)
{

  const int inSize = 384;

  std::vector<int> a(inSize), b(inSize), expected(inSize), out(inSize, 0);

  for(int i = 0; i < inSize; ++i) {
    a[i] = i + 1;
    b[i] = i - 1;
    expected[i] = 2 * i;
  }

  std::cout << "Running on DFE." << std::endl;
  %%%ProjectName%%%(inSize, &a[0], &b[0], &out[0]);

  /***
      Note that you should always test the output of your DFE
      design against a CPU version to ensure correctness.
  */
  for (int i = 0; i < inSize; i++)
    if (out[i] != expected[i]) {
      printf("Output from DFE did not match CPU: %d : %d != %d\n",
        i, out[i], expected[i]);
      return 1;
    }

  std::cout << "Test passed!" << std::endl;
  return 0;
}

Replace Demo with macro in CpuCode.cpp.


/**********************************************************************
 *
 * GEOS - Geometry Engine Open Source
 * http://geos.osgeo.org
 *
 * Copyright (C) 2001-2002 Vivid Solutions Inc.
 *
 * This is free software; you can redistribute and/or modify it under
 * the terms of the GNU Lesser General Public Licence as published
 * by the Free Software Foundation.
 * See the COPYING file for more information.
 *
 **********************************************************************
 *
 * Last port: geom/prep/PreparedPoint.java rev. 1.2 (JTS-1.10)
 *
 **********************************************************************/

#include <geos/geom/prep/PreparedPoint.h>

namespace geos {
namespace geom { // geos.geom
namespace prep { // geos.geom.prep

bool
PreparedPoint::intersects(const geom::Geometry* g) const
{
	if (! envelopesIntersect( g)) return false;

	// This avoids computing topology for the test geometry
	return isAnyTargetComponentInTest( g);
}

} // namespace geos.geom.prep
} // namespace geos.geom
} // namespace geos

/**********************************************************************
 *
 * GEOS - Geometry Engine Open Source
 * http://geos.osgeo.org
 *
 * Copyright (C) 2001-2002 Vivid Solutions Inc.
 *
 * This is free software; you can redistribute and/or modify it under
 * the terms of the GNU Lesser General Public Licence as published
 * by the Free Software Foundation.
 * See the COPYING file for more information.
 *
 **********************************************************************
 *
 * Last port: geom/prep/PreparedPoint.java rev. 1.2 (JTS-1.10)
 *
 **********************************************************************/

#include <geos/geom/prep/PreparedPoint.h>
#include <geos/geom/Point.h>

namespace geos {
namespace geom { // geos.geom
namespace prep { // geos.geom.prep

bool
PreparedPoint::intersects(const geom::Geometry* g) const
{
	if (! envelopesIntersect( g)) return false;

	const Point *pt_geom = dynamic_cast<const Point *>(g);
	if (pt_geom)
        return getGeometry().equals(g);

	// This avoids computing topology for the test geometry
	return isAnyTargetComponentInTest( g);
}

} // namespace geos.geom.prep
} // namespace geos.geom
} // namespace geos

Fix corner case of comparing preparedpoint to point


#include "gamelib/sprite/SpriteData.hpp"
#include <cmath>

namespace gamelib
{
    AnimationData::AnimationData() :
        length(1),
        speed(0),
        offset(0)
    { }

    void AnimationData::update(float fps)
    {
        offset = std::fmod(offset + speed / fps, length);
    }

    sf::IntRect AnimationData::getRect(int texw, int texh) const
    {
        int x = rect.left + (int)offset * rect.width;
        return sf::IntRect(x % texw, (rect.top + x / texw * rect.height) % texh, rect.width, rect.height);
    }
}

#include "gamelib/sprite/SpriteData.hpp"
#include <cmath>

namespace gamelib
{
    AnimationData::AnimationData() :
        length(1),
        speed(0),
        offset(0)
    { }

    void AnimationData::update(float fps)
    {
        if (length > 1 && speed != 0)
            offset = std::fmod(offset + speed / fps, length);
    }

    sf::IntRect AnimationData::getRect(int texw, int texh) const
    {
        int x = rect.left + (int)offset * rect.width;
        return sf::IntRect(x % texw, (rect.top + x / texw * rect.height) % texh, rect.width, rect.height);
    }
}

Fix bug causing a wrong frame index


/*
MIT License

Copyright (c) 2017 Blockchain-VCS

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

bool __nosha256 = false;
bool __useJSONFormat = false;

Add Use JSON as a command line argument


/*
  Copyright (c) 2014, J.D. Koftinoff Software, Ltd.
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

   3. Neither the name of J.D. Koftinoff Software, Ltd. nor the names of its
      contributors may be used to endorse or promote products derived from
      this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  POSSIBILITY OF SUCH DAMAGE.
*/

#include "JDKSAvdeccMCU_World.hpp"
#include "JDKSAvdeccMCU_AppMessageHandler.hpp"

namespace JDKSAvdeccMCU
{

}

/*
  Copyright (c) 2014, J.D. Koftinoff Software, Ltd.
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

   3. Neither the name of J.D. Koftinoff Software, Ltd. nor the names of its
      contributors may be used to endorse or promote products derived from
      this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  POSSIBILITY OF SUCH DAMAGE.
*/

#include "JDKSAvdeccMCU_World.hpp"
#include "JDKSAvdeccMCU_AppMessageHandler.hpp"

namespace JDKSAvdeccMCU
{
    const char *jdksavdeccmcu_appmessagehandler_file = __FILE__;
}

Add symbol to empty file


#include "librt_error.h"

using namespace librt;

Error::Error() :
    errorCode_(Error::Code::Ok),
    message_()
{
}

Error::Error(Error::Code errorCode, std::__cxx11::string &&message) :
    errorCode_(errorCode),
    message_(message)
{
}

Error::Error(Error &&other) :
    errorCode_(other.errorCode_),
    message_(std::move(other.message_))
{
}

Error &Error::operator =(Error &&other)
{
    errorCode_ = other.errorCode_;
    message_ = std::move(other.message_);

    return *this;
}

Error &Error::operator =(std::pair<Error::Code, std::string> &&other)
{
    errorCode_ = other.first;
    message_ = std::move(other.second);

    return *this;
}

Error::Code Error::errorCode() const
{
    return errorCode_;
}

const std::string &Error::message() const
{
    return message_;
}

#include "librt_error.h"

using namespace librt;

Error::Error() :
    errorCode_(Error::Code::Ok),
    message_()
{
}

Error::Error(Error::Code errorCode, std::string &&message) :
    errorCode_(errorCode),
    message_(message)
{
}

Error::Error(Error &&other) :
    errorCode_(other.errorCode_),
    message_(std::move(other.message_))
{
}

Error &Error::operator =(Error &&other)
{
    errorCode_ = other.errorCode_;
    message_ = std::move(other.message_);

    return *this;
}

Error &Error::operator =(std::pair<Error::Code, std::string> &&other)
{
    errorCode_ = other.first;
    message_ = std::move(other.second);

    return *this;
}

Error::Code Error::errorCode() const
{
    return errorCode_;
}

const std::string &Error::message() const
{
    return message_;
}

Remove cxx11 namespace from Error


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

#include <iostream>

#include "AssemblyFileWriter.hpp"
#include "Functions.hpp"

using namespace eddic;

using std::endl;

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

void FunctionCall::checkFunctions(Program& program){
    if(!program.exists(m_function)){
        throw CompilerException("The function does not exists");
    }
}

void Function::write(AssemblyFileWriter& writer){
    writer.stream() << endl << m_name << ":" << endl;

    writer.stream() << "pushl %ebp" << std::endl;
    writer.stream() << "movl %esp, %ebp" << std::endl;

    ParseNode::write(writer);

    writer.stream() << "leave" << std::endl;
    writer.stream() << "ret" << std::endl;
}

void FunctionCall::write(AssemblyFileWriter& writer){
    writer.stream() << "call " << m_function << endl;
}

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

#include <iostream>

#include "AssemblyFileWriter.hpp"
#include "Functions.hpp"

using namespace eddic;

using std::endl;

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

void FunctionCall::checkFunctions(Program& program){
    if(!program.exists(m_function)){
        throw CompilerException("The function \"" + m_function + "\"does not exists");
    }
}

void Function::write(AssemblyFileWriter& writer){
    writer.stream() << endl << m_name << ":" << endl;

    writer.stream() << "pushl %ebp" << std::endl;
    writer.stream() << "movl %esp, %ebp" << std::endl;

    ParseNode::write(writer);

    writer.stream() << "leave" << std::endl;
    writer.stream() << "ret" << std::endl;
}

void FunctionCall::write(AssemblyFileWriter& writer){
    writer.stream() << "call " << m_function << endl;
}

Add the function name on the error reporting


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

#include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"

#include "chrome/browser/sync/glue/data_type_controller.h"
#include "sync/util/data_type_histogram.h"

namespace browser_sync {

bool DataTypeController::IsUnrecoverableResult(StartResult result) {
  return (result == UNRECOVERABLE_ERROR);
}

syncer::SyncError DataTypeController::CreateAndUploadError(
    const tracked_objects::Location& location,
    const std::string& message,
    syncable::ModelType type) {
  ChromeReportUnrecoverableError();
  return syncer::SyncError(location, message, type);
}

void DataTypeController::RecordUnrecoverableError(
    const tracked_objects::Location& from_here,
    const std::string& message) {
  DVLOG(1) << "Datatype Controller failed for type "
           << ModelTypeToString(type()) << "  "
           << message << " at location "
           << from_here.ToString();
  UMA_HISTOGRAM_ENUMERATION("Sync.DataTypeRunFailures", type(),
                            syncable::MODEL_TYPE_COUNT);
  ChromeReportUnrecoverableError();
}

}  // namespace browser_sync

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

#include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"

#include "chrome/browser/sync/glue/data_type_controller.h"
#include "sync/util/data_type_histogram.h"

namespace browser_sync {

bool DataTypeController::IsUnrecoverableResult(StartResult result) {
  return (result == UNRECOVERABLE_ERROR);
}

syncer::SyncError DataTypeController::CreateAndUploadError(
    const tracked_objects::Location& location,
    const std::string& message,
    syncable::ModelType type) {
  // TODO(sync): remove this once search engines triggers less errors, such as
  // due to crbug.com/130448.
  if (type != syncable::SEARCH_ENGINES)
    ChromeReportUnrecoverableError();
  return syncer::SyncError(location, message, type);
}

void DataTypeController::RecordUnrecoverableError(
    const tracked_objects::Location& from_here,
    const std::string& message) {
  DVLOG(1) << "Datatype Controller failed for type "
           << ModelTypeToString(type()) << "  "
           << message << " at location "
           << from_here.ToString();
  UMA_HISTOGRAM_ENUMERATION("Sync.DataTypeRunFailures", type(),
                            syncable::MODEL_TYPE_COUNT);

  // TODO(sync): remove this once search engines triggers less errors, such as
  // due to crbug.com/130448.
  if (type() != syncable::SEARCH_ENGINES)
    ChromeReportUnrecoverableError();
}

}  // namespace browser_sync

Disable uploading of search engine datatype errors.


#include <string.h>
#include "tree_sitter/runtime.h"

void test_log(void *payload, TSLogType type, const char *string) { }

TSLogger logger = {
  .log = test_log,
};

extern "C" const TSLanguage *TS_LANG();

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
  const char *str = reinterpret_cast<const char *>(data);

  TSParser *parser = ts_parser_new();
  ts_parser_set_language(parser, TS_LANG());
  ts_parser_halt_on_error(parser, TS_HALT_ON_ERROR);

  TSTree *tree = ts_parser_parse_string(parser, NULL, str, size);
  TSNode root_node = ts_document_root_node(tree);

  ts_tree_delete(tree);
  ts_parser_delete(parser);

  return 0;
}

#include <string.h>
#include "tree_sitter/runtime.h"

void test_log(void *payload, TSLogType type, const char *string) { }

TSLogger logger = {
  .log = test_log,
};

extern "C" const TSLanguage *TS_LANG();

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
  const char *str = reinterpret_cast<const char *>(data);

  TSParser *parser = ts_parser_new();
  ts_parser_set_language(parser, TS_LANG());
  ts_parser_halt_on_error(parser, TS_HALT_ON_ERROR);

  TSTree *tree = ts_parser_parse_string(parser, NULL, str, size);
  TSNode root_node = ts_tree_root_node(tree);

  ts_tree_delete(tree);
  ts_parser_delete(parser);

  return 0;
}

Use ts_tree_root_node in fuzz driver


#include "stdafx.h"
#include "CppUnitTest.h"

#include "datastore.h"

using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;

namespace YouDataStoreTests {
TEST_CLASS(DataStoreApiTest) {
public:
	TEST_METHOD(Post_EmptyTask_Test) {
		// You::DataStore::DataStore sut;
		// sut.post(std::unordered_map<std::wstring, std::wstring>());
		Assert::IsTrue(true);
	}
};
}  // namespace YouDataStoreTests

#include "stdafx.h"
#include "CppUnitTest.h"

#include "datastore.h"

using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;

namespace YouDataStoreTests {
TEST_CLASS(DataStoreApiTest) {
public:
	TEST_METHOD(DataStoreDummyTest) {
		// You::DataStore::DataStore sut;
		// sut.post(std::unordered_map<std::wstring, std::wstring>());
		Assert::IsTrue(true);
	}
};
}  // namespace YouDataStoreTests

Rename incomplete test on datastore to DataStoreDummyTest


#include <iostream>

#include "EventAction.hh"

#include "G4Event.hh"
#include "RunAction.hh"
#include "Run.hh"

EventAction::EventAction():
    G4UserEventAction{},
    _draw_flag("all")
{
}

EventAction::~EventAction()
{
}

void EventAction::BeginOfEventAction(const G4Event* evt)
{
    G4cout << "EV: " << evt->GetEventID() << G4endl;
}

void EventAction::EndOfEventAction(const G4Event*)
{
}

#include <iostream>

#include "EventAction.hh"

#include "G4Event.hh"
#include "RunAction.hh"
#include "Run.hh"

EventAction::EventAction():
    G4UserEventAction{},
    _draw_flag("all")
{
}

EventAction::~EventAction()
{
}

void EventAction::BeginOfEventAction(const G4Event*)
{
    // G4cout << "EV: " << evt->GetEventID() << G4endl;
}

void EventAction::EndOfEventAction(const G4Event*)
{
}

Remove printout from event action


#include "cardreader.h"

#include <QEvent>
#include <QKeyEvent>

bool CardReader::eventFilter(QObject *object, QEvent *event)
{
	if (event->type() != QEvent::KeyPress) {
		return false;
	}

	if (cardNumber.isEmpty()) {
		writeTime.start();
	}

	//accumulate characters
	QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
	cardNumber += keyEvent->text();

	//send signal on enter (RFID card reader ends string input with an enter)
	if (keyEvent->key() == Qt::Key_Return) {
		//disallow entries with duration less than a time limit in order to avoid keyboard input and allow only the fast RFID reader
		if (writeTime.elapsed() < CARDREADER_TIME_LIMIT_MS) {
			emit newCardNumber(cardNumber);
		}

		cardNumber.clear();
	}

	return true;
}

#include "cardreader.h"

#include <QEvent>
#include <QKeyEvent>

bool CardReader::eventFilter(QObject *object, QEvent *event)
{
	if (event->type() != QEvent::KeyPress) {
		return false;
	}

	if (cardNumber.isEmpty()) {
		writeTime.start();
	}

	//accumulate characters
	QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
	cardNumber += keyEvent->text();

	//send signal on enter (RFID card reader ends string input with an enter)
	if (keyEvent->key() == Qt::Key_Return) {
		//disallow entries with duration less than a time limit in order to avoid keyboard input and allow only the fast RFID reader
		if (writeTime.elapsed() < CARDREADER_TIME_LIMIT_MS) {
			emit newCardNumber(cardNumber.simplified());
		}

		cardNumber.clear();
	}

	return true;
}

Simplify card string before emitting, in case any key characters are added by the return.


#include <hw/serial.hpp>

extern "C"
void __serial_print1(const char* cstr)
{
  const uint16_t port = 0x3F8; // Serial 1
  while (*cstr) {
    while (not (hw::inb(port + 5) & 0x20));
    hw::outb(port, *cstr++);
  }
}

#include <hw/serial.hpp>

extern "C"
void __serial_print1(const char* cstr)
{
  const uint16_t port = 0x3F8; // Serial 1
  static bool init = false;
  if (!init) {
    init = true;
    // properly initialize serial port
    hw::outb(port + 1, 0x00);    // Disable all interrupts
    hw::outb(port + 3, 0x80);    // Enable DLAB (set baud rate divisor)
    hw::outb(port + 0, 0x03);    // Set divisor to 3 (lo byte) 38400 baud
    hw::outb(port + 1, 0x00);    //                  (hi byte)
    hw::outb(port + 3, 0x03);    // 8 bits, no parity, one stop bit
    hw::outb(port + 2, 0xC7);    // Enable FIFO, clear them, with 14-byte threshold
  }

  while (*cstr) {
    while (not (hw::inb(port + 5) & 0x20));
    hw::outb(port, *cstr++);
  }
}

Initialize the default serial port properly


#include "mainwindow.h"
#include <QGridLayout>
#include <QLabel>
#include <QEvent>
#include <QKeyEvent>

#include <iostream>

MainWindow::MainWindow(QWidget *parent)
{
	QGridLayout *layout = new QGridLayout(this);
	layout->addWidget(new QLabel("ARK kryssesystem"));

	//install cardReader as an filter which intercepts keyboard events
	CardReader *cardReader = new CardReader(this);
	installEventFilter(cardReader);
}

bool CardReader::eventFilter(QObject *object, QEvent *event)
{
	if (event->type() != QEvent::KeyPress) {
		return false;
	}

	if (cardNumber.isEmpty()) {
		writeTime.start();
	}

	//accumulate characters
	QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
	cardNumber += keyEvent->text();

	//send signal on enter (RFID card reader ends string input with an enter)
	if (keyEvent->key() == Qt::Key_Return) {
		//disallow entries with duration less than a time limit in order to avoid keyboard input and allow only the fast RFID reader
		if (writeTime.elapsed() < CARDREADER_TIME_LIMIT_MS) {
			emit newCardNumber(cardNumber);
		}

		cardNumber.clear();
	}

	return true;
}

#include "mainwindow.h"
#include <QGridLayout>
#include <QLabel>
#include <QEvent>
#include <QKeyEvent>

#include <iostream>

MainWindow::MainWindow(QWidget *parent)
{
	QGridLayout *layout = new QGridLayout(this);
	layout->addWidget(new QLabel("ARK kryssesystem. Bipp et kort:"));

	QLabel *testLabel = new QLabel;
	layout->addWidget(testLabel);

	//install cardReader as an filter which intercepts keyboard events
	CardReader *cardReader = new CardReader(this);
	installEventFilter(cardReader);
	connect(cardReader, SIGNAL(newCardNumber(QString)), testLabel, SLOT(setText(QString)));
}

bool CardReader::eventFilter(QObject *object, QEvent *event)
{
	if (event->type() != QEvent::KeyPress) {
		return false;
	}

	if (cardNumber.isEmpty()) {
		writeTime.start();
	}

	//accumulate characters
	QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
	cardNumber += keyEvent->text();

	//send signal on enter (RFID card reader ends string input with an enter)
	if (keyEvent->key() == Qt::Key_Return) {
		//disallow entries with duration less than a time limit in order to avoid keyboard input and allow only the fast RFID reader
		if (writeTime.elapsed() < CARDREADER_TIME_LIMIT_MS) {
			emit newCardNumber(cardNumber);
		}

		cardNumber.clear();
	}

	return true;
}

Test qlabel for displaying string from card reader.


/*
Copyright (C) 2014,2015,2018 Rodrigo Jose Hernandez Cordoba

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 "SettingsDialog.h"
#include <QColorDialog>
namespace AeonGames
{
    SettingsDialog::SettingsDialog()
    {
        setupUi ( this );
        settings.beginGroup ( "MainWindow" );
        backgroundColorPushButton->setPalette ( QPalette ( settings.value ( "background color", QColor ( 57, 57, 57 ) ).value<QColor>() ) );
        settings.endGroup();
    }

    SettingsDialog::~SettingsDialog()
    {
    }

    void SettingsDialog::onChangeBackgroundColor()
    {

        QColor color = QColorDialog::getColor ( backgroundColorPushButton->palette().background().color() );
        settings.beginGroup ( "MainWindow" );
        settings.setValue ( "background color", color );
        settings.endGroup();
        backgroundColorPushButton->setPalette ( QPalette ( color ) );
        emit backgroundColor ( color );
    }
}

/*
Copyright (C) 2014,2015,2018,2019 Rodrigo Jose Hernandez Cordoba

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 "SettingsDialog.h"
#include <QColorDialog>
namespace AeonGames
{
    SettingsDialog::SettingsDialog()
    {
        setupUi ( this );
        settings.beginGroup ( "MainWindow" );
        backgroundColorPushButton->setPalette ( QPalette ( settings.value ( "background color", QColor ( 57, 57, 57 ) ).value<QColor>() ) );
        settings.endGroup();
    }

    SettingsDialog::~SettingsDialog()
    {
    }

    void SettingsDialog::onChangeBackgroundColor()
    {
#if QT_VERSION < QT_VERSION_CHECK(5, 13, 0)
        QColor color = QColorDialog::getColor ( backgroundColorPushButton->palette().background().color() );
#else
        QColor color = QColorDialog::getColor ( backgroundColorPushButton->palette().window().color() );
#endif
        settings.beginGroup ( "MainWindow" );
        settings.setValue ( "background color", color );
        settings.endGroup();
        backgroundColorPushButton->setPalette ( QPalette ( color ) );
        emit backgroundColor ( color );
    }
}

Fix compilation against Qt 5.13.


#ifndef UHX_NO_UOBJECT

#include "Core.h"
#include "IntPtr.h"
#include "uhx/ue/RuntimeLibrary.h"
#include "HAL/PlatformAtomics.h"

static int uhx_tls_slot = 0;

#if defined(_MSC_VER)
unreal::UIntPtr *uhx::ue::RuntimeLibrary_obj::tlsObj = nullptr;
#elif defined(__GNUC__)
thread_local unreal::UIntPtr *uhx::ue::RuntimeLibrary_obj::tlsObj = nullptr;
#else
static int uhx_tls_obj = FPlatformTLS::AllocTlsSlot();

unreal::UIntPtr uhx::ue::RuntimeLibrary_obj::getTlsObj() {
  unreal::UIntPtr *ret = (unreal::UIntPtr *) FPlatformTLS::GetTlsValue(uhx_tls_obj);
  if (!ret) {
    ret = (unreal::UIntPtr*) uhx::GcRef::createRoot();
    FPlatformTLS::SetTlsValue(uhx_tls_obj, (void*) ret);
    return *ret = uhx::expose::HxcppRuntime::createArray();
  }
  return *ret;
}
#endif

int uhx::ue::RuntimeLibrary_obj::allocTlsSlot() {
  return FPlatformAtomics::InterlockedIncrement(&uhx_tls_slot);
}

#endif

Update to latest perforce change


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

#include "base/message_loop.h"
#include "base/perf_test_suite.h"
#include "chrome/common/chrome_paths.cc"

int main(int argc, char **argv) {
  chrome::RegisterPathProvider();
  MessageLoop main_message_loop;

  return PerfTestSuite(argc, argv).Run();
}

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

#include "base/message_loop.h"
#include "base/perf_test_suite.h"
#include "chrome/common/chrome_paths.cc"

int main(int argc, char **argv) {
  PerfTestSuite suite(argc, argv);
  chrome::RegisterPathProvider();
  MessageLoop main_message_loop;

  return suite.Run();
}

Fix error [FATAL:at_exit.cc(40)] Check failed: false. Tried to RegisterCallback without an AtExitManager in (possibly unused) binary perf_tests


// Test main file for the Player and Team classes

#include "Player.hpp"
#include "Team.hpp"

int main()
{
    // Don't do anything
    return 0;
}

// Test main file for the Player and Team classes

#include "Player.hpp"
#include "Team.hpp"
#include <string>
#include <iostream>

int main()
{
    // Test code from the assignment description

    Player::Player p1("Charlotte", 24, 10, 7);
    Player::Player p2("Emily", 21, 13, 9);
    Player::Player p3("Anne", 20, 10, 8);
    Player::Player p4("Jane", 19, 10, 10);
    Player::Player p5("Mary", 18, 11, 8);
    p5.setRebounds(12);

    Team::Team team1(p1, p2, p3, p4, p5);

    Player::Player p = team1.getShootingGuard();
    std::cout << p.getName() << std::endl;

    return 0;
}

Test code from assignment description


// 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/basictypes.h"
#include "base/file_path.h"
#include "build/build_config.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"

class DefaultPluginUITest : public UITest {
 public:
  DefaultPluginUITest() {
    dom_automation_enabled_ = true;
  }
};

TEST_F(DefaultPluginUITest, DefaultPluginLoadTest) {
  // Open page with default plugin.
  FilePath test_file(test_data_directory_);
  test_file = test_file.AppendASCII("default_plugin.html");
  NavigateToURL(net::FilePathToFileURL(test_file));

  // Check that the default plugin was loaded. It executes a bit of javascript
  // in the HTML file which replaces the innerHTML of div |result| with "DONE".
  scoped_refptr<TabProxy> tab(GetActiveTab());
  std::wstring out;
  ASSERT_TRUE(tab->ExecuteAndExtractString(L"",
      L"domAutomationController.send("
      L"document.getElementById('result').innerHTML)", &out));
  ASSERT_EQ(L"DONE", out);
}

// 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/basictypes.h"
#include "base/file_path.h"
#include "build/build_config.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"

class DefaultPluginUITest : public UITest {
 public:
  DefaultPluginUITest() {
    dom_automation_enabled_ = true;
  }
};

#if defined(OS_WIN)
#define MAYBE_DefaultPluginLoadTest DISABLED_DefaultPluginLoadTest
#else
#define MAYBE_DefaultPluginLoadTest DefaultPluginLoadTest
#endif
TEST_F(DefaultPluginUITest, MAYBE_DefaultPluginLoadTest) {
  // Open page with default plugin.
  FilePath test_file(test_data_directory_);
  test_file = test_file.AppendASCII("default_plugin.html");
  NavigateToURL(net::FilePathToFileURL(test_file));

  // Check that the default plugin was loaded. It executes a bit of javascript
  // in the HTML file which replaces the innerHTML of div |result| with "DONE".
  scoped_refptr<TabProxy> tab(GetActiveTab());
  std::wstring out;
  ASSERT_TRUE(tab->ExecuteAndExtractString(L"",
      L"domAutomationController.send("
      L"document.getElementById('result').innerHTML)", &out));
  ASSERT_EQ(L"DONE", out);
}

Disable DefaultPluginUITest::DefaultPluginLoadTest on windows as it crashes.


/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include "AndroidTextInputState.h"

#include <react/renderer/components/text/conversions.h>
#include <react/renderer/debug/debugStringConvertibleUtils.h>

namespace facebook {
namespace react {

#ifdef ANDROID
folly::dynamic AndroidTextInputState::getDynamic() const {
  // Java doesn't need all fields, so we don't pass them along.
  folly::dynamic newState = folly::dynamic::object();
  newState["mostRecentEventCount"] = mostRecentEventCount;
  if (mostRecentEventCount != 0) {
    newState["attributedString"] = toDynamic(attributedString);
    newState["hash"] = newState["attributedString"]["hash"];
  }
  newState["paragraphAttributes"] =
      toDynamic(paragraphAttributes); // TODO: can we memoize this in Java?
  return newState;
}
#endif

} // namespace react
} // namespace facebook

/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include "AndroidTextInputState.h"

#include <react/renderer/components/text/conversions.h>
#include <react/renderer/debug/debugStringConvertibleUtils.h>

namespace facebook {
namespace react {

#ifdef ANDROID
folly::dynamic AndroidTextInputState::getDynamic() const {
  // Java doesn't need all fields, so we don't pass them along.
  folly::dynamic newState = folly::dynamic::object();
  newState["mostRecentEventCount"] = mostRecentEventCount;
  newState["attributedString"] = toDynamic(attributedString);
  newState["hash"] = newState["attributedString"]["hash"];
  newState["paragraphAttributes"] =
      toDynamic(paragraphAttributes); // TODO: can we memoize this in Java?
  return newState;
}
#endif

} // namespace react
} // namespace facebook

Fix initial render of RN Android TextInput


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

#include "Application.h"

ouzel::AppPtr ouzelMain(const std::vector<std::string>& args)
{
    std::shared_ptr<ouzel::Application> application(new ouzel::Application());

    return application;
}

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

#include "Application.h"

ouzel::AppPtr ouzelMain(const std::vector<std::string>& args)
{
    std::shared_ptr<ouzel::Application> application = std::make_shared<ouzel::Application>();

    return application;
}

Use make_shared instead of new for creation of Application instance


/**
 *  fastcall.cpp
 *
 *  This file holds some PHP functions implementation in C directly.
 *
 */

#include "includes.h"

namespace Php {

    bool class_exists(const std::string &classname, bool autoload) {
        // we need the tsrm_ls variable
        TSRMLS_FETCH();

        zend_class_entry **ce;
        int found;
        const char * str = classname.c_str();
        int32_t len = (int32_t)classname.length();

        if (autoload) {
            char lc_name[len + 1];
            zend_str_tolower_copy(lc_name, str, len);

            char *name = lc_name;
            if (lc_name[0] == '\\') {
                name = &lc_name[1];
                --len;
            }

            found = zend_hash_find(EG(class_table), name, len + 1, (void **) &ce);
            return (found == SUCCESS && !(((*ce)->ce_flags & (ZEND_ACC_INTERFACE | ZEND_ACC_TRAIT)) > ZEND_ACC_EXPLICIT_ABSTRACT_CLASS));
        }

        if (zend_lookup_class(str, len, &ce TSRMLS_CC) == SUCCESS) {
            return (((*ce)->ce_flags & (ZEND_ACC_INTERFACE | (ZEND_ACC_TRAIT - ZEND_ACC_EXPLICIT_ABSTRACT_CLASS))) == 0);
        }
        return false;
    }

}

/**
 *  fastcall.cpp
 *
 *  This file holds some PHP functions implementation in C directly.
 *
 */

#include "includes.h"

namespace Php {

    bool class_exists(const std::string &classname, bool autoload) {
        // we need the tsrm_ls variable
        TSRMLS_FETCH();

        zend_class_entry **ce;
        int found;
        const char * str = classname.c_str();
        int32_t len = (int32_t)classname.length();

        if (autoload) {
            char *lc_name = new char[len + 1];
            zend_str_tolower_copy(lc_name, str, len);

            char *name = lc_name;
            if (lc_name[0] == '\\') {
                name = &lc_name[1];
                --len;
            }

            found = zend_hash_find(EG(class_table), name, len + 1, (void **) &ce);
            delete [] lc_name;
            return (found == SUCCESS && !(((*ce)->ce_flags & (ZEND_ACC_INTERFACE | ZEND_ACC_TRAIT)) > ZEND_ACC_EXPLICIT_ABSTRACT_CLASS));
        }

        if (zend_lookup_class(str, len, &ce TSRMLS_CC) == SUCCESS) {
            return (((*ce)->ce_flags & (ZEND_ACC_INTERFACE | (ZEND_ACC_TRAIT - ZEND_ACC_EXPLICIT_ABSTRACT_CLASS))) == 0);
        }
        return false;
    }

}

Change C99 VLA C++ dynamic array


#include <jni.h>
#include <string>
#include "SpatialFilter.h"
#include "VideoProcessor.h"

extern "C"

jstring
Java_cn_edu_seu_evmhr_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */,
        jstring jFileName) {
    const char* jnamestr = env->GetStringUTFChars(jFileName, NULL);

    VideoProcessor VP;
    VP.setInput(jnamestr);

    std::stringstream ss;
    ss << VP.colorMagnify();

    std::string peaks;
    ss >> peaks;

    return env->NewStringUTF(peaks.c_str());
}

#include <jni.h>
#include <string>
#include "SpatialFilter.h"
#include "VideoProcessor.h"

extern "C"

jstring
Java_cn_edu_seu_evmhr_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */,
        jstring jFileName) {
    const char* jnamestr = env->GetStringUTFChars(jFileName, NULL);

    VideoProcessor VP;
    VP.setInput(jnamestr);

    double length = VP.getLengthMS() / 1000;
    int peaks = VP.colorMagnify();

    std::stringstream ss;
    ss << std::floor(60 / length * peaks);

    std::string heartRate;
    ss >> heartRate;

    return env->NewStringUTF(heartRate.c_str());
}

Move heart rate calculation to cpp


#include "SharedResource.h"

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

BOOST_AUTO_TEST_CASE(Basic_construction)
{
    SharedResource<int> shared_int;
}

BOOST_AUTO_TEST_CASE(Construction_with_argument)
{
    SharedResource<int> shared_int(5);
}

BOOST_AUTO_TEST_CASE(Construction_no_default_constructor)
{
    struct TestClass
    {
        TestClass() = delete;
        TestClass(int) { }
    };

    SharedResource<TestClass> stc2(5);
}

BOOST_AUTO_TEST_CASE(Basic_Locking)
{
    SharedResource<int> shared_int(0);
    shared_int.lock();
}

BOOST_AUTO_TEST_CASE(Locking_with_accessor)
{
    SharedResource<int> shared_int(0);
    auto shared_int_accessor = shared_int.lock();
}

BOOST_AUTO_TEST_CASE(Accessor_isValid)
{
    SharedResource<int> shared_int(0);
    auto shared_int_accessor = shared_int.lock();
    BOOST_CHECK(shared_int_accessor.isValid());
    auto shared_int_accessor_new(std::move(shared_int_accessor));
    BOOST_CHECK(!shared_int_accessor.isValid());
    BOOST_CHECK(shared_int_accessor_new.isValid());
}

Test for SharedResourse::Accessor::isValid method added


// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "checksumaggregators.h"

namespace proton::bucketdb {

std::unique_ptr<ChecksumAggregator>
ChecksumAggregator::create(ChecksumType type, BucketChecksum seed) {
    switch (type) {
    case ChecksumType::LEGACY:
        return std::make_unique<LegacyChecksumAggregator>(seed);
    case ChecksumType::XXHASH64:
        return std::make_unique<XXH64ChecksumAggregator>(seed);
    }
    return std::unique_ptr<ChecksumAggregator>();
}

}

// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "checksumaggregators.h"

namespace proton::bucketdb {

std::unique_ptr<ChecksumAggregator>
ChecksumAggregator::create(ChecksumType type, BucketChecksum seed) {
    switch (type) {
    case ChecksumType::LEGACY:
        return std::make_unique<LegacyChecksumAggregator>(seed);
    case ChecksumType::XXHASH64:
        return std::make_unique<XXH64ChecksumAggregator>(seed);
    }
    abort();
}

}

Use abort instead to signal unreachable code.


// cc.in79
// problem with templatized forward decl?
// no, was a problem with templatized prototypes

class istream;

template<class TP> class smanip;
//template<class TP> class smanip {};

template<class TP>
inline istream& operator>>(istream& i, const smanip<TP>& m);
//int foo(smanip<TP> &m);

typedef smanip<int> smanip_int;

template<class TP> class smanip {
  smanip *whatever;
  smanip<TP> *whatever2;
};

void f()
{
  smanip_int s;
  s.whatever;
}

// in/t0079.cc
// problem with templatized forward decl?
// no, was a problem with templatized prototypes

class istream;

template<class TP> class smanip;
//template<class TP> class smanip {};

template<class TP>
inline istream& operator>>(istream& i, const smanip<TP>& m);
//int foo(smanip<TP> &m);

typedef smanip<int> smanip_int;

template<class TP> class smanip {
public:
  smanip *whatever;
  smanip<TP> *whatever2;
};

void f()
{
  smanip_int s;
  s.whatever;
}

Fix gcc compilation issue, thanks to Evan Driscoll.


#include <ostree.h>
#include <stdlib.h>

extern "C" OstreeDeployment *ostree_sysroot_get_booted_deployment(OstreeSysroot *self) {
  (void)self;
  const char *hash = getenv("OSTREE_HASH");
  return ostree_deployment_new(0, "dummy-os", hash, 1, hash, 1);
}

extern "C" const char *ostree_deployment_get_csum(OstreeDeployment *self) {
  (void)self;
  return getenv("OSTREE_HASH");
}

#include <ostree.h>
#include <stdlib.h>

extern "C" OstreeDeployment *ostree_sysroot_get_booted_deployment(OstreeSysroot *self) {
  (void)self;
  static OstreeDeployment *deployment;

  if (deployment != nullptr) {
    return deployment;
  }

  const char *hash = getenv("OSTREE_HASH");
  deployment = ostree_deployment_new(0, "dummy-os", hash, 1, hash, 1);
  return deployment;
}

extern "C" const char *ostree_deployment_get_csum(OstreeDeployment *self) {
  (void)self;
  return getenv("OSTREE_HASH");
}

Fix mem leak in test code