#include <algorithm>

#include "url.h"

#include "agent.h"
#include "directive.h"

namespace Rep
{
    Agent& Agent::allow(const std::string& query)
    {
        directives_.push_back(Directive(escape(query), true));
        sorted_ = false;
        return *this;
    }

    Agent& Agent::disallow(const std::string& query)
    {
        if (query.empty())
        {
            // Special case: "Disallow:" means "Allow: /"
            directives_.push_back(Directive(query, true));
        }
        else
        {
            directives_.push_back(Directive(escape(query), false));
        }
        sorted_ = false;
        return *this;
    }

    const std::vector<Directive>& Agent::directives() const
    {
        if (!sorted_)
        {
            std::sort(directives_.begin(), directives_.end(), [](const Directive& a, const Directive& b) {
                return b.priority() < a.priority();
            });
            sorted_ = true;
        }
        return directives_;
    }

    bool Agent::allowed(const std::string& query) const
    {
        std::string path(escape(query));

        if (path.compare("/robots.txt") == 0)
        {
            return true;
        }

        std::string escaped = escape(path);
        for (auto directive : directives())
        {
            if (directive.match(escaped))
            {
                return directive.allowed();
            }
        }
        return true;
    }

    std::string Agent::escape(const std::string& query)
    {
        return Url::Url(query).defrag().escape().fullpath();
    }
}

#include <algorithm>

#include "url.h"

#include "agent.h"
#include "directive.h"

namespace Rep
{
    Agent& Agent::allow(const std::string& query)
    {
        directives_.push_back(Directive(escape(query), true));
        sorted_ = false;
        return *this;
    }

    Agent& Agent::disallow(const std::string& query)
    {
        if (query.empty())
        {
            // Special case: "Disallow:" means "Allow: /"
            directives_.push_back(Directive(query, true));
        }
        else
        {
            directives_.push_back(Directive(escape(query), false));
        }
        sorted_ = false;
        return *this;
    }

    const std::vector<Directive>& Agent::directives() const
    {
        if (!sorted_)
        {
            std::sort(directives_.begin(), directives_.end(), [](const Directive& a, const Directive& b) {
                return b.priority() < a.priority();
            });
            sorted_ = true;
        }
        return directives_;
    }

    bool Agent::allowed(const std::string& query) const
    {
        std::string path(escape(query));

        if (path.compare("/robots.txt") == 0)
        {
            return true;
        }

        for (auto directive : directives())
        {
            if (directive.match(path))
            {
                return directive.allowed();
            }
        }
        return true;
    }

    std::string Agent::escape(const std::string& query)
    {
        return Url::Url(query).defrag().escape().fullpath();
    }
}

Remove redundant escaping in allowed check.


// Copyright 2015 Adam Grandquist

#include "./test.hpp"

#include "./ReQL.hpp"

void
consume(ReQL::Cursor<ReQL::Result> cursor) {
  for (auto && : cursor) {}
}

// Copyright 2015 Adam Grandquist

#include "./test.hpp"

#include "./ReQL.hpp"

void
consume(ReQL::Cursor<ReQL::Result> cursor) {
  for (auto &&_ : cursor) {}
}

Add blank name for loop syntax.


// AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from wallet.djinni

#include "CosmosConfigurationDefaults.hpp"  // my header

namespace ledger { namespace core { namespace api {

std::string const CosmosConfigurationDefaults::COSMOS_DEFAULT_API_ENDPOINT = {"http://lite-client-0e27eefb-4031-4859-a88e-249fd241989d.cosmos.bison.run:1317"};

std::string const CosmosConfigurationDefaults::COSMOS_OBSERVER_WS_ENDPOINT = {""};

} } }  // namespace ledger::core::api

// AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from wallet.djinni

#include "CosmosConfigurationDefaults.hpp"  // my header

namespace ledger { namespace core { namespace api {

std::string const CosmosConfigurationDefaults::COSMOS_DEFAULT_API_ENDPOINT = {"https://cosmos.coin.staging.aws.ledger.com"};

std::string const CosmosConfigurationDefaults::COSMOS_OBSERVER_WS_ENDPOINT = {""};

} } }  // namespace ledger::core::api

Fix forgetting generating interfaces for explorer


//
// Created by Alex Gurung
//
#include "helper.h"

void testnums(unsigned long long int hail){
    unsigned long long int orghail = hail;
    while(hail!= 0){
        hail = testHail(hail); //Within helper.h file, testHail returns the next hailstone number, or 0 if you get to 4
    }
    cout << orghail << endl;
}
int main(){
    unsigned long long int counter = 10000;
    for(unsigned long long int i = 5476377146882523136; i<18446744073709551615 ; i++){
//18446744073709551615 is the largest value available for an unsigned long long int, and 5476377146882523136 was the previous largest tested value
        testnums(i);
    }
    return 0;
}

//
// Created by Alex Gurung
//
#include "helper.h"

void testnums(unsigned long long int hail){
    unsigned long long int orghail = hail;
    while(hail!= 0){
        hail = testHail(hail); //Within helper.h file, testHail returns the next hailstone number, or 0 if you get to 4
    }
    cout << orghail << endl; //This is a test commit
}
int main(){
    unsigned long long int counter = 10000;
    for(unsigned long long int i = 5476377146882523136; i<18446744073709551615 ; i++){
//18446744073709551615 is the largest value available for an unsigned long long int, and 5476377146882523136 was the previous largest tested value
        testnums(i);
    }
    return 0;
}

Test commit EMAIL PROBLEM MEANS COMMITS DONT COUNT


#include <cstring>
#include "Vector.h"

Vector::Vector() {
  capacity = 8;
  data = new int[8];
}

void Vector::add(int value) {
  size += 1;
  if (size > capacity) {
    reserve(capacity * 2);
  }
  data[size - 1] = value;
}

void Vector::reserve(int newCapacity) {
  capacity = newCapacity;
  int* newData = new int[capacity];
  memcpy(newData, data, sizeof(int) * size);
  data = newData;
}

int Vector::getCapacity() {
  return capacity;
}

#include <cstring>
#include "Vector.h"

Vector::Vector() {
  capacity = 8;
  data = new int[8];
}

void Vector::add(int value) {
  size += 1;
  if (size > capacity) {
    reserve(capacity * 2);
  }
  data[size - 1] = value;
}

void Vector::reserve(int newCapacity) {
  capacity = newCapacity;
  int* newData = new int[capacity];
  memcpy(newData, data, sizeof(int) * size);
  delete[] data;
  data = newData;
}

int Vector::getCapacity() {
  return capacity;
}

Fix memory leak for reserving new arrays


/**
  ******************************************************************************
  * @file    main.c
  * @author  Ac6
  * @version V1.0
  * @date    01-December-2013
  * @brief   Default main function.
  ******************************************************************************
*/

#include "stm32f4xx.h"
#include "stm32f4xx_nucleo.h"
#include "stm32f4xx_hal.h"
#include "PWM_Generator.h"

extern "C" void initialise_monitor_handles(void);

int main(void)
{
	HAL_Init();
	//initialise_monitor_handles();

	PWM_Generator *pwm = PWM_Generator::Instance();

	pwm->Init();
	pwm->Arm(NULL);

	pwm->SetPulse(1050, 1);
	pwm->SetPulse(1050, 2);
	pwm->SetPulse(1050, 3);
	pwm->SetPulse(1050, 4);

	for(;;);
}

Add sample code for PWM


/*
 * DesktopNetworkAccessManager.cpp
 *
 * Copyright (C) 2009-11 by RStudio, Inc.
 *
 * This program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "DesktopNetworkAccessManager.hpp"
#include <QNetworkDiskCache>
#include <QDesktopServices>

#include <core/FilePath.hpp>

using namespace core;

NetworkAccessManager::NetworkAccessManager(QString secret, QObject *parent) :
    QNetworkAccessManager(parent), secret_(secret)
{
   setProxy(QNetworkProxy::NoProxy);

   // initialize cache
   QString cacheDir =
         QDesktopServices::storageLocation(QDesktopServices::CacheLocation);
   FilePath cachePath(cacheDir.toUtf8().constData());
   FilePath browserCachePath = cachePath.complete("RStudioWebkit");
   Error error = browserCachePath.ensureDirectory();
   if (!error)
   {
      QNetworkDiskCache* pCache = new QNetworkDiskCache(parent);
      QString browserCacheDir = QString::fromUtf8(
                                    browserCachePath.absolutePath().c_str());
      pCache->setCacheDirectory(browserCacheDir);
      setCache(pCache);
   }
   else
   {
      LOG_ERROR(error);
   }
}

QNetworkReply* NetworkAccessManager::createRequest(
      Operation op,
      const QNetworkRequest& req,
      QIODevice* outgoingData)
{
   QNetworkRequest req2 = req;
   req2.setRawHeader("X-Shared-Secret",
                     secret_.toAscii());
   return this->QNetworkAccessManager::createRequest(op, req2, outgoingData);
}

/*
 * DesktopNetworkAccessManager.cpp
 *
 * Copyright (C) 2009-11 by RStudio, Inc.
 *
 * This program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "DesktopNetworkAccessManager.hpp"

NetworkAccessManager::NetworkAccessManager(QString secret, QObject *parent) :
    QNetworkAccessManager(parent), secret_(secret)
{
   setProxy(QNetworkProxy::NoProxy);
}

QNetworkReply* NetworkAccessManager::createRequest(
      Operation op,
      const QNetworkRequest& req,
      QIODevice* outgoingData)
{
   QNetworkRequest req2 = req;
   req2.setRawHeader("X-Shared-Secret",
                     secret_.toAscii());
   return this->QNetworkAccessManager::createRequest(op, req2, outgoingData);
}

Revert "use file based webkit cache in desktop mode" (was crashing when opening the history pane on linux)


// Check that --gc-sections does not throw away (or localize) parts of sanitizer
// interface.
// RUN: %clang_asan -m64 %s -Wl,--gc-sections -o %t
// RUN: %clang_asan -m64 %s -DBUILD_SO -fPIC -o %t-so.so -shared
// RUN: %t 2>&1

#ifndef BUILD_SO
#include <assert.h>
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
  char path[4096];
  snprintf(path, sizeof(path), "%s-so.so", argv[0]);

  void *handle = dlopen(path, RTLD_LAZY);
  if (!handle) fprintf(stderr, "%s\n", dlerror());
  assert(handle != 0);

  typedef void (*F)();
  F f = (F)dlsym(handle, "call_rtl_from_dso");
  printf("%s\n", dlerror());
  assert(dlerror() == 0);
  f();

  dlclose(handle);
  return 0;
}

#else // BUILD_SO

#include <sanitizer/msan_interface.h>
extern "C" void call_rtl_from_dso() {
  volatile int32_t x;
  volatile int32_t y = __sanitizer_unaligned_load32((void *)&x);
}

#endif // BUILD_SO

// Check that --gc-sections does not throw away (or localize) parts of sanitizer
// interface.
// RUN: %clang_asan %s -Wl,--gc-sections -o %t
// RUN: %clang_asan %s -DBUILD_SO -fPIC -o %t-so.so -shared
// RUN: %t 2>&1

// REQUIRES: asan-64-bits

#ifndef BUILD_SO
#include <assert.h>
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
  char path[4096];
  snprintf(path, sizeof(path), "%s-so.so", argv[0]);

  void *handle = dlopen(path, RTLD_LAZY);
  if (!handle) fprintf(stderr, "%s\n", dlerror());
  assert(handle != 0);

  typedef void (*F)();
  F f = (F)dlsym(handle, "call_rtl_from_dso");
  printf("%s\n", dlerror());
  assert(dlerror() == 0);
  f();

  dlclose(handle);
  return 0;
}

#else // BUILD_SO

#include <sanitizer/asan_interface.h>
extern "C" void call_rtl_from_dso() {
  volatile int32_t x;
  volatile int32_t y = __sanitizer_unaligned_load32((void *)&x);
}

#endif // BUILD_SO

Mark this test as 64-bit specific


#include <iostream>

using namespace std;

int main() {
  int a[100][100];
  int d[100][100];

  a = d;

  for (int k = 0; k < n; k++) {
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        d[i][j] = min(d[i][j], d[i][k] + d[k][j]);
      }
    }
  }
}

#include <iostream>

using namespace std;

int main() {
  int n = 4;
  int a[n][n];
  int d[n][n];

  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      cin >> a[i][j];
      d[i][j] = a[i][j];
    }
  }

  for (int k = 0; k < n; k++) {
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        d[i][j] = min(d[i][j], d[i][k] + d[k][j]);
      }
    }
  }

  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      cout << d[i][j] << ' ';
    }
    cout << endl;
  }
}

Update Floyd with input output


/**
 * 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 "SimplifyCFG.h"

#include "ControlFlow.h"
#include "DexClass.h"
#include "IRCode.h"
#include "Walkers.h"

void SimplifyCFGPass::run_pass(DexStoresVector& stores,
                           ConfigFiles& /* unused */,
                           PassManager& mgr) {
  const auto& scope = build_class_scope(stores);
  auto total_insns_removed =
      walk::parallel::reduce_methods<std::nullptr_t, int64_t, Scope>(
          scope,
          [](std::nullptr_t, DexMethod* m) {
            auto code = m->get_code();
            if (code == nullptr) {
              return 0l;
            }

            int64_t before_insns = code->count_opcodes();

            // build and linearize the CFG
            code->build_cfg(/* editable */ true);
            code->clear_cfg();

            int64_t after_insns = code->count_opcodes();
            return before_insns - after_insns;
          },
          [](int64_t a, int64_t b) { return a + b; },
          [](int) { return nullptr; }, 0);
  mgr.set_metric("insns_removed", total_insns_removed);
}

static SimplifyCFGPass s_pass;

/**
 * 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 "SimplifyCFG.h"

#include "ControlFlow.h"
#include "DexClass.h"
#include "IRCode.h"
#include "Walkers.h"

void SimplifyCFGPass::run_pass(DexStoresVector& stores,
                           ConfigFiles& /* unused */,
                           PassManager& mgr) {
  const auto& scope = build_class_scope(stores);
  auto total_insns_removed =
      walk::parallel::reduce_methods<std::nullptr_t, int64_t, Scope>(
          scope,
          [](std::nullptr_t, DexMethod* m) -> int64_t {
            auto code = m->get_code();
            if (code == nullptr) {
              return 0;
            }

            int64_t before_insns = code->count_opcodes();

            // build and linearize the CFG
            code->build_cfg(/* editable */ true);
            code->clear_cfg();

            int64_t after_insns = code->count_opcodes();
            return before_insns - after_insns;
          },
          [](int64_t a, int64_t b) { return a + b; },
          [](int) { return nullptr; }, 0);
  mgr.set_metric("insns_removed", total_insns_removed);
}

static SimplifyCFGPass s_pass;

Fix integer casting issues in Mac OSS build


/* -*- mode:linux -*- */
/**
 * \file closed_list.cc
 *
 *
 *
 * \author Ethan Burns
 * \date 2008-10-09
 */

#include <map>

#include "state.h"
#include "closed_list.h"

void ClosedList::add(const State *s)
{
	m[s->hash()] = s;
}

const State *ClosedList::lookup(const State *c) const
{
	// this is stupid: apparently you can't do an assignment with
	// iterators, so instead we need to do two lookups.

	if (m.find(c->hash()) == m.end())
		return NULL;

	return m.find(c->hash())->second;
}

/**
 * Delete (free up the memory for) all states in the closed list.
 */
void ClosedList::delete_all_states(void)
{
	map<int, const State *>::iterator iter;

	for (iter = m.begin(); iter != m.end(); iter++)
		delete iter->second;
}

/* -*- mode:linux -*- */
/**
 * \file closed_list.cc
 *
 *
 *
 * \author Ethan Burns
 * \date 2008-10-09
 */

#include <map>

#include "state.h"
#include "closed_list.h"

void ClosedList::add(const State *s)
{
	m[s->hash()] = s;
}

const State *ClosedList::lookup(const State *c) const
{
	map<int, const State *>::const_iterator iter;

	iter = m.find(c->hash());

	if (iter == m.end())
		return NULL;

	return iter->second;
}

/**
 * Delete (free up the memory for) all states in the closed list.
 */
void ClosedList::delete_all_states(void)
{
	map<int, const State *>::iterator iter;

	for (iter = m.begin(); iter != m.end(); iter++)
		delete iter->second;
}

Use a const_iterator in ClosedList::lookup.


/**************************************************
 * Source Code for the Original Compiler for the
 * Programming Language Wake
 *
 * EarlyBailoutMethodInvecation.cpp
 *
 * Licensed under the MIT license
 * See LICENSE.TXT for details
 *
 * Author: Michael Fairhurst
 * Revised By:
 *
 **************************************************/

#include "ast/EarlyBailoutMethodInvocation.h"
#include "TypeError.h"

using namespace wake;

PureType<QUALIFIED>* ast::EarlyBailoutMethodInvocation::typeCheck(bool forceArrayIdentifier) {
	PureType<QUALIFIED> subject = *auto_ptr<PureType<QUALIFIED> >(subjectExpr->typeCheck(false));
	if(subject.type == TYPE_MATCHALL) {
		return new PureType<QUALIFIED>(subject);
	} else if(subject.type != TYPE_OPTIONAL) {
		errors->addError(new SemanticError(OPTIONAL_USE_OF_NONOPTIONAL_TYPE, "using .? on a nonoptional", node));
		return new PureType<QUALIFIED>(TYPE_MATCHALL);
	} else {
		PureType<QUALIFIED>* ret = new PureType<QUALIFIED>(TYPE_OPTIONAL);
		PureType<QUALIFIED>* nonoptional = subject.typedata.optional.contained;

		while(nonoptional->type == TYPE_OPTIONAL) {
			nonoptional = nonoptional->typedata.optional.contained;
		}

		ret->typedata.optional.contained = typeCheckMethodInvocation(*nonoptional);

		return ret;
	}
}

/**************************************************
 * Source Code for the Original Compiler for the
 * Programming Language Wake
 *
 * EarlyBailoutMethodInvecation.cpp
 *
 * Licensed under the MIT license
 * See LICENSE.TXT for details
 *
 * Author: Michael Fairhurst
 * Revised By:
 *
 **************************************************/

#include "ast/EarlyBailoutMethodInvocation.h"
#include "TypeError.h"

using namespace wake;

PureType<QUALIFIED>* ast::EarlyBailoutMethodInvocation::typeCheck(bool forceArrayIdentifier) {
	PureType<QUALIFIED> subject = *auto_ptr<PureType<QUALIFIED> >(subjectExpr->typeCheck(false));
	addSubNode(node, makeNodeFromPureType((PureType<UNQUALIFIED>*) new PureType<QUALIFIED>(subject), node->loc));
	if(subject.type == TYPE_MATCHALL) {
		return new PureType<QUALIFIED>(subject);
	} else if(subject.type != TYPE_OPTIONAL) {
		errors->addError(new SemanticError(OPTIONAL_USE_OF_NONOPTIONAL_TYPE, "using .? on a nonoptional", node));
		return new PureType<QUALIFIED>(TYPE_MATCHALL);
	} else {
		PureType<QUALIFIED>* ret = new PureType<QUALIFIED>(TYPE_OPTIONAL);
		PureType<QUALIFIED>* nonoptional = subject.typedata.optional.contained;

		while(nonoptional->type == TYPE_OPTIONAL) {
			nonoptional = nonoptional->typedata.optional.contained;
		}

		ret->typedata.optional.contained = typeCheckMethodInvocation(*nonoptional);

		return ret;
	}
}

Add type hint for java codegen


/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2013 BMW Car IT GmbH
 * %%
 * 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.
 * #L%
 */
#include "joynr/JoynrRuntime.h"
#include "JoynrClusterControllerRuntime.h"
#include "joynr/SettingsMerger.h"

namespace joynr
{
JoynrRuntime* JoynrRuntime::createRuntime(const QString& pathToLibjoynrSettings,
                                          const QString& pathToMessagingSettings)
{
    QSettings* settings = SettingsMerger::mergeSettings(pathToLibjoynrSettings);
    SettingsMerger::mergeSettings(pathToMessagingSettings, settings);
    return JoynrClusterControllerRuntime::create(settings);
}
} // namespace joynr

/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2013 BMW Car IT GmbH
 * %%
 * 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.
 * #L%
 */
#include "joynr/JoynrRuntime.h"
#include "JoynrClusterControllerRuntime.h"
#include "joynr/SettingsMerger.h"

namespace joynr
{
JoynrRuntime* JoynrRuntime::createRuntime(const QString& pathToLibjoynrSettings,
                                          const QString& pathToMessagingSettings)
{
    QSettings* settings = SettingsMerger::mergeSettings(pathToLibjoynrSettings);
    SettingsMerger::mergeSettings(pathToMessagingSettings, settings);
    return JoynrClusterControllerRuntime::create(settings);
}

void JoynrRuntime::addBroadcastFilter(QSharedPointer<IBroadcastFilter> filter)
{
    if (!publicationManager) {
        throw JoynrException("Exception in JoynrRuntime: PublicationManager not created yet.");
    }
    publicationManager->addBroadcastFilter(filter);
}
} // namespace joynr

Fix cluster controller runtime not defining addBroadcast()


// REQUIRES: shell

// MSYS doesn't emulate umask.
// FIXME: Could we introduce another feature for it?
// REQUIRES: shell-preserves-root'

// RUN: umask 000
// RUN: %clang_cc1 -emit-llvm-bc %s -o %t
// RUN: ls -l %t | FileCheck --check-prefix=CHECK000 %s
// CHECK000: rw-rw-rw-

// RUN: umask 002
// RUN: %clang_cc1 -emit-llvm-bc %s -o %t
// RUN: ls -l %t | FileCheck --check-prefix=CHECK002 %s
// CHECK002: rw-rw-r--

// REQUIRES: shell

// MSYS doesn't emulate umask.
// FIXME: Could we introduce another feature for it?
// REQUIRES: shell-preserves-root

// RUN: umask 000
// RUN: %clang_cc1 -emit-llvm-bc %s -o %t
// RUN: ls -l %t | FileCheck --check-prefix=CHECK000 %s
// CHECK000: rw-rw-rw-

// RUN: umask 002
// RUN: %clang_cc1 -emit-llvm-bc %s -o %t
// RUN: ls -l %t | FileCheck --check-prefix=CHECK002 %s
// CHECK002: rw-rw-r--

Fix typo in test's REQUIRES line


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

// This file contains LLVM stub functions - these are functions that are never
// called and are declared to satisfy the linker.

#include <assert.h>

#define STUB() assert(!"Stub function. Should not be called");

#include "llvm/Transforms/IPO/PassManagerBuilder.h"

namespace llvm
{

void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) { STUB(); }

} // namespace llvm

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

// This file contains LLVM stub functions - these are functions that are never
// called and are declared to satisfy the linker.

#include <assert.h>

#define STUB() assert(false); // Stub function. Should not be called

#include "llvm/Transforms/IPO/PassManagerBuilder.h"

namespace llvm
{

void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) { STUB(); }

} // namespace llvm

Fix warning treated as error


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

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

#include "chrome/browser/browser.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"

// TODO(skerner): This test is flaky in chromeos.  Figure out why and fix.
#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)
#define MAYBE_Tabs DISABLED_Tabs
#else
#define MAYBE_Tabs Tabs
#endif

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) {
  StartHTTPServer();

  // The test creates a tab and checks that the URL of the new tab
  // is that of the new tab page.  Make sure the pref that controls
  // this is set.
  browser()->profile()->GetPrefs()->SetBoolean(
      prefs::kHomePageIsNewTabPage, true);

  ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_;
}

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

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

#include "chrome/browser/browser.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"

// TODO(skerner): This test is flaky in chromeos and on Mac OS X 10.6.  Figure
// out why and fix.
#if (defined(OS_LINUX) && defined(TOOLKIT_VIEWS)) || defined(OS_MACOSX)
#define MAYBE_Tabs DISABLED_Tabs
#else
#define MAYBE_Tabs Tabs
#endif

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) {
  StartHTTPServer();

  // The test creates a tab and checks that the URL of the new tab
  // is that of the new tab page.  Make sure the pref that controls
  // this is set.
  browser()->profile()->GetPrefs()->SetBoolean(
      prefs::kHomePageIsNewTabPage, true);

  ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_;
}

Disable ExtensionApiTest.Tabs on Mac. TEST=no random redness on Mac OS X 10.6 bot BUG=37387 TBR=skerner@


/**
 * Copyright 2014 Truphone
 */
#include "XmppHarness.h"

#include "CommandFactory.h"
#include "XmppResourceStore.h"
#include "XmppHelpCommand.h"
#include "XmppPresenceCommand.h"
#include "XmppConnectCommand.h"
#include "XmppMessageCommand.h"

namespace truphone
{
namespace test
{
namespace cascades
{
    XmppHarness::XmppHarness(QObject *parent) :
        QObject(parent)
    {
    }
    XmppHarness::~XmppHarness()
    {
    }
    bool XmppHarness::installHarness()
    {
        XMPPResourceStore::initialiseStore(this);
        CommandFactory::installCommand(
                    XMPPHelpCommand::getCmd(),
                    &XMPPHelpCommand::create);
        CommandFactory::installCommand(
                    XMPPConnectCommand::getCmd(),
                    &XMPPConnectCommand::create);
        CommandFactory::installCommand(
                    XMPPPresenceCommand::getCmd(),
                    &XMPPPresenceCommand::create);
        CommandFactory::installCommand(
                    XMPPMessageCommand::getCmd(),
                    &XMPPMessageCommand::create);
        return true;
    }
}  // namespace cascades
}  // namespace test
}  // namespace truphone

/**
 * Copyright 2014 Truphone
 */
#include "XmppHarness.h"

#include "CommandFactory.h"
#include "XmppResourceStore.h"
#include "XmppHelpCommand.h"
#include "XmppPresenceCommand.h"
#include "XmppConnectCommand.h"
#include "XmppMessageCommand.h"
#include "XmppDisconnectCommand.h"

namespace truphone
{
namespace test
{
namespace cascades
{
    XmppHarness::XmppHarness(QObject *parent) :
        QObject(parent)
    {
    }
    XmppHarness::~XmppHarness()
    {
    }
    bool XmppHarness::installHarness()
    {
        XMPPResourceStore::initialiseStore(this);
        CommandFactory::installCommand(
                    XMPPHelpCommand::getCmd(),
                    &XMPPHelpCommand::create);
        CommandFactory::installCommand(
                    XMPPConnectCommand::getCmd(),
                    &XMPPConnectCommand::create);
        CommandFactory::installCommand(
                    XMPPPresenceCommand::getCmd(),
                    &XMPPPresenceCommand::create);
        CommandFactory::installCommand(
                    XMPPMessageCommand::getCmd(),
                    &XMPPMessageCommand::create);
        CommandFactory::installCommand(
                    XMPPDisconnectCommand::getCmd(),
                    &XMPPDisconnectCommand::create);
        return true;
    }
}  // namespace cascades
}  // namespace test
}  // namespace truphone

Add the disconnect command to the factory.


// 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/metrics/metrics_service.h"

#include <string>

#include "base/base64.h"

#include "testing/gtest/include/gtest/gtest.h"

class MetricsServiceTest : public ::testing::Test {
};

// Ensure the ClientId is formatted as expected.
TEST(MetricsServiceTest, ClientIdCorrectlyFormatted) {
  std::string clientid = MetricsService::GenerateClientID();
  EXPECT_EQ(36U, clientid.length());
  std::string hexchars = "0123456789ABCDEF";
  for (uint32 i = 0; i < clientid.length(); i++) {
    char current = clientid.at(i);
    if (i == 8 || i == 13 || i == 18 || i == 23) {
      EXPECT_EQ('-', current);
    } else {
      EXPECT_TRUE(std::string::npos != hexchars.find(current));
    }
  }
}

TEST(MetricsServiceTest, IsPluginProcess) {
  EXPECT_TRUE(
      MetricsService::IsPluginProcess(content::PROCESS_TYPE_PLUGIN));
  EXPECT_TRUE(
      MetricsService::IsPluginProcess(content::PROCESS_TYPE_PPAPI_PLUGIN));
  EXPECT_FALSE(
      MetricsService::IsPluginProcess(content::PROCESS_TYPE_GPU));
}

// 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 <ctype.h>
#include <string>

#include "chrome/browser/metrics/metrics_service.h"
#include "testing/gtest/include/gtest/gtest.h"

// Ensure the ClientId is formatted as expected.
TEST(MetricsServiceTest, ClientIdCorrectlyFormatted) {
  std::string clientid = MetricsService::GenerateClientID();
  EXPECT_EQ(36U, clientid.length());

  for (size_t i = 0; i < clientid.length(); ++i) {
    char current = clientid[i];
    if (i == 8 || i == 13 || i == 18 || i == 23)
      EXPECT_EQ('-', current);
    else
      EXPECT_TRUE(isxdigit(current));
  }
}

TEST(MetricsServiceTest, IsPluginProcess) {
  EXPECT_TRUE(
      MetricsService::IsPluginProcess(content::PROCESS_TYPE_PLUGIN));
  EXPECT_TRUE(
      MetricsService::IsPluginProcess(content::PROCESS_TYPE_PPAPI_PLUGIN));
  EXPECT_FALSE(
      MetricsService::IsPluginProcess(content::PROCESS_TYPE_GPU));
}

Clean up MetricsService unit test.


#include "PoissonDiskSampling.h"

PoissonDiskSampling::PoissonDiskSampling(int pointWidth, int pointHeight, double pointMinDist, double pointCount) :
	m_width(pointWidth),
	m_height(pointHeight),
	m_minDist(pointMinDist),
	m_pointCount(pointCount),
	m_cellSize(m_minDist / 1.414214f),
	m_gridWidth(ceil(m_width / m_cellSize)),
	m_gridHeight(ceil(m_height / m_cellSize)),
	m_grid(std::vector<std::vector<std::shared_ptr<Point>>>(m_gridWidth, std::vector<std::shared_ptr<Point>>(m_gridHeight, nullptr)))
{

}

#include "PoissonDiskSampling.h"

#include <random>

PoissonDiskSampling::PoissonDiskSampling(int pointWidth, int pointHeight, double pointMinDist, double pointCount) :
	m_width(pointWidth),
	m_height(pointHeight),
	m_minDist(pointMinDist),
	m_pointCount(pointCount),
	m_cellSize(m_minDist / 1.414214f),
	m_gridWidth(ceil(m_width / m_cellSize)),
	m_gridHeight(ceil(m_height / m_cellSize)),
	m_grid(std::vector<std::vector<std::shared_ptr<Point>>>(m_gridWidth, std::vector<std::shared_ptr<Point>>(m_gridHeight, nullptr)))
{

}

std::vector<std::pair<double, double>> PoissonDiskSampling::Generate()
{
	std::random_device rd;
	std::mt19937 gen(rd());

	Point firstPoint(gen() / m_width, gen() / m_height);

	m_process.push_back(firstPoint);
	m_sample.push_back(std::make_pair(firstPoint.x, firstPoint.y));
	int firstPointX = firstPoint.x / m_cellSize;
	int firstPointY = firstPoint.y / m_cellSize;
	m_grid[firstPointX][firstPointY] = std::make_shared<Point>(firstPoint);

	while (!m_process.empty())
	{

	}
}

Implement Generate() : create firstPoint and assign it


#include "main_action_planner_node.hpp"

int main(int argc, char** argv) {
  ros::init(argc, argv, "test_action_planner_node");
  ros::NodeHandle nh {"~"};
  StateChecker status {nh};

  while (ros::ok()) {
    auto posture_key = status.getPostureKey();
    RequestPosture* rp_p = RequestPostureFactory::get(posture_key[0], nh);
    if (!rp_p) {
      ROS_INFO("Error: get nullptr by RP Factory: arg is [%s]", posture_key[0].c_str());
      return -1;
    }

    SendPosture* sp_p = SendPostureFactory::get(posture_key[1], nh);
    if (!sp_p) {
      ROS_INFO("Error: get nullptr by SP Factory: arg is [%s]", posture_key[1].c_str());
      return -1;
    }

    std::vector<double> angles;
    rp_p->requestPosture(angles);
    sp_p->sendPosture(angles);

    ros::spinOnce();
  }
  return 0;
}

#include "main_action_planner_node.hpp"

int main(int argc, char** argv) {
  ros::init(argc, argv, "test_action_planner_node");
  ros::NodeHandle nh {};
  StateChecker status {nh};

  while (ros::ok()) {
    auto posture_key = status.getPostureKey();
    RequestPosture* rp_p = RequestPostureFactory::get(posture_key[0], nh);
    if (!rp_p) {
      ROS_INFO("Error: get nullptr by RP Factory: arg is [%s]", posture_key[0].c_str());
      return -1;
    }

    SendPosture* sp_p = SendPostureFactory::get(posture_key[1], nh);
    if (!sp_p) {
      ROS_INFO("Error: get nullptr by SP Factory: arg is [%s]", posture_key[1].c_str());
      return -1;
    }

    std::vector<double> angles;
    rp_p->requestPosture(angles);
    sp_p->sendPosture(angles);

    ros::spinOnce();
  }
  return 0;
}

Use relational node handle for topic communicate


/*=========================================================================

  Program:   Converter Base Class
  Language:  C++

  Copyright (c) Brigham and Women's Hospital. All rights reserved.

  This software is distributed WITHOUT ANY WARRANTY; without even
  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "rib_converter_base.h"

RIBConverterBase::RIBConverterBase()
{
  this->nodeHandle = NULL;
}

RIBConverterBase::RIBConverterBase(ros::NodeHandle *nh)
{
  this->setNodeHandle(nh);
}

RIBConverterBase::RIBConverterBase(const char* topicPublish, const char* topicSubscribe, ros::NodeHandle *nh)
{
  this->topicPublish = topicPublish;
  this->topicSubscribe = topicSubscribe;
  this->setNodeHandle(nh);
}

RIBConverterBase::~RIBConverterBase()
{
}

void RIBConverterBase::setup(ros::NodeHandle* nh, uint32_t queuSize)
{
  this->setNodeHandle(nh);
  this->setQueueSize(queueSize);
}

//void RIBConverterBase::setup(ros::NodeHandle* nh, igtl::Socket * socket, const char* topicSubscribe, const char* topicPublish)
//{
//  this->nodeHandle = nh;
//  this->socket = socket;
//  this->topicSubscribe = topicSubscribe;
//  this->topicPublish = topicPublish;
//}

/*=========================================================================

  Program:   Converter Base Class
  Language:  C++

  Copyright (c) Brigham and Women's Hospital. All rights reserved.

  This software is distributed WITHOUT ANY WARRANTY; without even
  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "rib_converter_base.h"

RIBConverterBase::RIBConverterBase()
{
  this->nodeHandle = NULL;
}

RIBConverterBase::RIBConverterBase(ros::NodeHandle *nh)
{
  this->setNodeHandle(nh);
}

RIBConverterBase::RIBConverterBase(const char* topicPublish, const char* topicSubscribe, ros::NodeHandle *nh)
{
  this->topicPublish = topicPublish;
  this->topicSubscribe = topicSubscribe;
  this->setNodeHandle(nh);
}

RIBConverterBase::~RIBConverterBase()
{
}

void RIBConverterBase::setup(ros::NodeHandle* nh, uint32_t queuSize)
{
  this->setNodeHandle(nh);
  this->setQueue(nh);
  this->setQueueSize(queueSize);
}

//void RIBConverterBase::setup(ros::NodeHandle* nh, igtl::Socket * socket, const char* topicSubscribe, const char* topicPublish)
//{
//  this->nodeHandle = nh;
//  this->socket = socket;
//  this->topicSubscribe = topicSubscribe;
//  this->topicPublish = topicPublish;
//}

Call setQueue in setup function.


#include "robot_editor.h"
#include "robot_preview.h"

#include <cstdlib>

RobotEditor::RobotEditor()
{
	main_window_ui_.setupUi(&main_window_);
	robot_preview_ = new RobotPreview(main_window_ui_.rvizFrame);

	QObject::connect(main_window_ui_.actionExit, SIGNAL(triggered()), this, SLOT(exitTrigger()));
	QObject::connect(main_window_ui_.actionOpen, SIGNAL(triggered()), this, SLOT(openTrigger()));
	QObject::connect(main_window_ui_.actionSave, SIGNAL(triggered()), this, SLOT(saveTrigger()));
	QObject::connect(main_window_ui_.actionSave_As, SIGNAL(triggered()), this, SLOT(saveAsTrigger()));
}

RobotEditor::~RobotEditor()
{
	delete robot_preview_;
}

void RobotEditor::show()
{
	main_window_.show();
}

void RobotEditor::openTrigger() {
	printf("Open selected\n");
}

void RobotEditor::saveTrigger() {
	printf("Save selected\n");
}

void RobotEditor::saveAsTrigger() {
	printf("Save as selected\n");
}

void RobotEditor::exitTrigger() {
	printf("Exit selected\n");
}

#include "robot_editor.h"
#include "robot_preview.h"

#include <cstdlib>

RobotEditor::RobotEditor()
{
	main_window_ui_.setupUi(&main_window_);
	robot_preview_ = new RobotPreview(main_window_ui_.rvizFrame);

	QObject::connect(main_window_ui_.actionExit, SIGNAL(triggered()), this, SLOT(exitTrigger()));
	QObject::connect(main_window_ui_.actionOpen, SIGNAL(triggered()), this, SLOT(openTrigger()));
	QObject::connect(main_window_ui_.actionSave, SIGNAL(triggered()), this, SLOT(saveTrigger()));
	QObject::connect(main_window_ui_.actionSave_As, SIGNAL(triggered()), this, SLOT(saveAsTrigger()));
}

RobotEditor::~RobotEditor()
{
	delete robot_preview_;
}

void RobotEditor::show()
{
	main_window_.show();
}

void RobotEditor::openTrigger() {
	printf("Open selected\n");
}

void RobotEditor::saveTrigger() {
	printf("Save selected\n");
}

void RobotEditor::saveAsTrigger() {
	printf("Save as selected\n");
}

void RobotEditor::exitTrigger() {
	// quit the application
	exit(0);
}

Exit menu action now works.


#include <QtQuick>

#include <sailfishapp.h>
#include <QScopedPointer>
#include <QQuickView>
#include <QQmlEngine>
#include <QGuiApplication>

#include "factor.h"

void loadTranslations() {
    QString langCode = QLocale::system().name().mid(0, 2);
    const QString Prefix("sailfactor_");

    if (QFile::exists(QString(":/lang/") + Prefix + langCode + ".qm")) {
        QTranslator *translator = new QTranslator(QCoreApplication::instance());
        translator->load(Prefix + langCode, ":/lang");
        QCoreApplication::installTranslator(translator);
    }
}

int main(int argc, char *argv[])
{
    QScopedPointer<QGuiApplication> app(SailfishApp::application(argc, argv));
    QScopedPointer<QQuickView> view(SailfishApp::createView());

    loadTranslations();

    Factorizer fact;

#ifdef QT_QML_DEBUG
    runUnitTests();
#endif

    view->engine()->rootContext()->setContextProperty("fact", &fact);
    view->setSource(SailfishApp::pathTo("qml/main.qml"));

    view->setTitle("Sailfactor");

    app->setApplicationName("harbour-sailfactor");
    app->setApplicationDisplayName("Sailfactor");

    view->show();

    return app->exec();
}

#include <QtQuick>

#include <sailfishapp.h>
#include <QScopedPointer>
#include <QQuickView>
#include <QQmlEngine>
#include <QGuiApplication>

#include "factor.h"

static void loadTranslations() {
    QString langCode = QLocale::system().name().mid(0, 2);
    const QString Prefix("sailfactor_");

    if (QFile::exists(QString(":/lang/") + Prefix + langCode + ".qm")) {
        QTranslator *translator = new QTranslator(QCoreApplication::instance());
        translator->load(Prefix + langCode, ":/lang");
        QCoreApplication::installTranslator(translator);
    }
}

int main(int argc, char *argv[])
{
    QScopedPointer<QGuiApplication> app(SailfishApp::application(argc, argv));
    QScopedPointer<QQuickView> view(SailfishApp::createView());

    loadTranslations();

    Factorizer fact;

#ifdef QT_QML_DEBUG
    runUnitTests();
#endif

    view->engine()->rootContext()->setContextProperty("fact", &fact);
    view->setSource(SailfishApp::pathTo("qml/main.qml"));

    view->setTitle("Sailfactor");

    app->setApplicationName("harbour-sailfactor");
    app->setApplicationDisplayName("Sailfactor");

    view->show();

    return app->exec();
}

Make loadTranslations() a static function.


#include <functional>

#include <QApplication>
#include <QMenu>
#include <QObject>
#include <QSystemTrayIcon>
#include <QTranslator>

#include "piemenu.h"

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

    QTranslator translator;
    translator.load(QLocale(), "", "i18n", ".qm");
    app.installTranslator(&translator);

    PieMenu pieMenu(qApp->applicationDirPath());

    QSystemTrayIcon tray(QIcon(qApp->applicationDirPath() + "/icons/app.png"), &app);

    QMenu trayMenu;
    trayMenu.addAction(QObject::tr("Open menu"), std::bind(&PieMenu::open, &pieMenu));
    trayMenu.addAction(QObject::tr("&Quit"));

    tray.setContextMenu(&trayMenu);
    tray.show();

    return app.exec();
}

#include <functional>

#include <QApplication>
#include <QMenu>
#include <QObject>
#include <QSystemTrayIcon>
#include <QTranslator>

#include "piemenu.h"

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

    QTranslator translator;
    translator.load(QLocale(), "", "i18n", ".qm");
    app.installTranslator(&translator);

    PieMenu pieMenu(qApp->applicationDirPath());

    QSystemTrayIcon tray(QIcon(qApp->applicationDirPath() + "/icons/app.png"), &app);

    QMenu trayMenu;
    trayMenu.addAction(QObject::tr("Open menu"), std::bind(&PieMenu::open, &pieMenu));
    trayMenu.addAction(QObject::tr("&Quit"), qApp, &QApplication::quit);

    tray.setContextMenu(&trayMenu);
    tray.show();

    return app.exec();
}

Make quit tray menu option work


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

ShipBlockPacket::ShipBlockPacket(uint8_t ip1, uint8_t ip2, uint8_t ip3, uint8_t ip4, uint16_t port) {
    static const uint8_t ipBits[] = { ip1, ip2, ip3, ip4};
    memcpy(this->ipaddr, ipBits, sizeof(ipBits));
    this->port = port;
}

ShipBlockPacket::~ShipBlockPacket() {
    delete[] ipaddr;
}

PacketData ShipBlockPacket::build() {
    PacketData data;
    PacketHeader header(0x90, 0x11, 0x2C, 0x0, 0x0);
    data.appendData(&header, sizeof(header));

    // TODO fill in gap

    // Offset 0x64
    data.appendData(&ipaddr, 4);

    // Offset 0x68
    data.appendData(&port, 2);

    // TODO fill in gap

    return data;
}

Stop deleting my includes clion


//===-- AVRMCAsmInfo.cpp - AVR asm properties -----------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declarations of the AVRMCAsmInfo properties.
//
//===----------------------------------------------------------------------===//

#include "AVRMCAsmInfo.h"

#include "llvm/ADT/Triple.h"

namespace llvm {

AVRMCAsmInfo::AVRMCAsmInfo(const Triple &TT) {
  CodePointerSize = 2;
  CalleeSaveStackSlotSize = 2;
  CommentString = ";";
  PrivateGlobalPrefix = ".L";
  UsesELFSectionDirectiveForBSS = true;
  UseIntegratedAssembler = true;
}

} // end of namespace llvm

Migrate to new MCAsmInfo CodePointerSize


/*
 *  Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "voice_engine/test/auto_test/fixtures/before_initialization_fixture.h"

#include <cstdlib>

class VoeBaseMiscTest : public BeforeInitializationFixture {
};

using namespace testing;

TEST_F(VoeBaseMiscTest, MaxNumChannelsIs32) {
  EXPECT_EQ(32, voe_base_->MaxNumOfChannels());
}

TEST_F(VoeBaseMiscTest, GetVersionPrintsSomeUsefulInformation) {
  char char_buffer[1024];
  memset(char_buffer, 0, sizeof(char_buffer));
  EXPECT_EQ(0, voe_base_->GetVersion(char_buffer));
  EXPECT_THAT(char_buffer, ContainsRegex("VoiceEngine"));
}

/*
 *  Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "voice_engine/test/auto_test/fixtures/before_initialization_fixture.h"

#include <cstdlib>

class VoeBaseMiscTest : public BeforeInitializationFixture {
};

using namespace testing;

TEST_F(VoeBaseMiscTest, MaxNumChannelsIs100) {
  EXPECT_EQ(100, voe_base_->MaxNumOfChannels());
}

TEST_F(VoeBaseMiscTest, GetVersionPrintsSomeUsefulInformation) {
  char char_buffer[1024];
  memset(char_buffer, 0, sizeof(char_buffer));
  EXPECT_EQ(0, voe_base_->GetVersion(char_buffer));
  EXPECT_THAT(char_buffer, ContainsRegex("VoiceEngine"));
}

Fix MaxChannels test; 32 -> 100.


#include "Flax/WindowsFiberImpl.h"

#include <cassert>

#include <Windows.h>

namespace flax {

WindowsFiberImpl::WindowsFiberImpl(Fiber* fiber, FiberMainFunction mainFunction, bool isMainFiber)
   : address(nullptr), mainFiber(isMainFiber), fiberAndMain(fiber, mainFunction) {
   assert(fiber && mainFunction);

   if (mainFiber) {
      address = ConvertThreadToFiber(this);
      assert(address);
   } else {
      address = CreateFiber(0, [](LPVOID param) {
         FiberAndMain* fiberAndMain = reinterpret_cast<FiberAndMain*>(param);
         assert(fiberAndMain);

         fiberAndMain->mainFunction(fiberAndMain->fiber);
      }, &fiberAndMain);
   }
}

WindowsFiberImpl::~WindowsFiberImpl() {
   if (mainFiber) {
      assert(address);
      bool success = ConvertFiberToThread() != 0;
      assert(success);
   } else if (address) {
      DeleteFiber(address);
   }

   address = nullptr;
}

void WindowsFiberImpl::swapTo(WindowsFiberImpl& lastFiberImpl) {
   assert(address && GetCurrentFiber() != address && GetCurrentFiber() == lastFiberImpl.address);
   SwitchToFiber(address);
}

} // namespace flax

#include "Flax/WindowsFiberImpl.h"

#include <cassert>

#include <Windows.h>

namespace flax {

WindowsFiberImpl::WindowsFiberImpl(Fiber* fiber, FiberMainFunction mainFunction, bool isMainFiber)
   : address(nullptr), mainFiber(isMainFiber), fiberAndMain(fiber, mainFunction) {
   assert(fiber && mainFunction);

   if (mainFiber) {
      address = ConvertThreadToFiber(this);
      assert(address);
   } else {
      address = CreateFiber(0, [](LPVOID param) {
         FiberAndMain* fiberAndMain = reinterpret_cast<FiberAndMain*>(param);
         assert(fiberAndMain);

         fiberAndMain->mainFunction(fiberAndMain->fiber);
      }, &fiberAndMain);
   }
}

WindowsFiberImpl::~WindowsFiberImpl() {
   if (mainFiber) {
      assert(address);
      bool success = ConvertFiberToThread() != 0;
      assert(success);
   } else if (address) {
      DeleteFiber(address);
   }

   address = nullptr;
}

void WindowsFiberImpl::swapTo(WindowsFiberImpl& lastFiberImpl) {
   assert(address && lastFiberImpl.address && GetCurrentFiber() != address && GetCurrentFiber() == lastFiberImpl.address);
   SwitchToFiber(address);
}

} // namespace flax

Add additional check to assert call


/*
 * Copyright (c) 2007 Digital Bazaar, Inc.  All rights reserved.
 */

#include <iostream>

#include "db/database/sqlite3/Sqlite3Connection.h"
#include "db/database/sqlite3/Sqlite3Statement.h"

using namespace std;
using namespace db::database;
using namespace db::database::sqlite3;

Sqlite3Connection::Sqlite3Connection(const char* params) :
   Connection(params)
{
   int ret;
   mHandle = NULL;

   if(mInitParams->getScheme() != "sqlite3")
   {
      // FIXME error handling
   }
   else
   {
      string dbFile = mInitParams->getSchemeSpecificPart();
      ret = sqlite3_open(dbFile.c_str(), &mHandle);
      if(ret != SQLITE_OK)
      {
         Sqlite3Connection::close();
         // FIXME error handling
      }
   }
}

Sqlite3Connection::~Sqlite3Connection()
{
   Sqlite3Connection::close();
}

void Sqlite3Connection::close()
{
   if(mHandle != NULL)
   {
      sqlite3_close(mHandle);
   }
}

void Sqlite3Connection::commit()
{
   cout << "FIXME: commit" << endl;
}

void Sqlite3Connection::rollback()
{
   cout << "FIXME: rollback" << endl;
}

Statement* Sqlite3Connection::createStatement(const char* sql)
{
   return new Sqlite3Statement(this, sql);
}

/*
 * Copyright (c) 2007 Digital Bazaar, Inc.  All rights reserved.
 */

#include <iostream>

#include "db/database/sqlite3/Sqlite3Connection.h"
#include "db/database/sqlite3/Sqlite3Statement.h"

using namespace std;
using namespace db::database;
using namespace db::database::sqlite3;

Sqlite3Connection::Sqlite3Connection(const char* params) :
   Connection(params)
{
   int ret;
   mHandle = NULL;

   if(mInitParams->getScheme() != "sqlite3")
   {
      // FIXME error handling
   }
   else
   {
      string dbFile = mInitParams->getSchemeSpecificPart();
      ret = sqlite3_open(dbFile.c_str(), &mHandle);
      if(ret != SQLITE_OK)
      {
         Sqlite3Connection::close();
         // FIXME error handling
      }
   }
}

Sqlite3Connection::~Sqlite3Connection()
{
   Sqlite3Connection::close();
}

void Sqlite3Connection::close()
{
   if(mHandle != NULL)
   {
      sqlite3_close(mHandle);
      mHandle = NULL;
   }
}

void Sqlite3Connection::commit()
{
   cout << "FIXME: commit" << endl;
}

void Sqlite3Connection::rollback()
{
   cout << "FIXME: rollback" << endl;
}

Statement* Sqlite3Connection::createStatement(const char* sql)
{
   return new Sqlite3Statement(this, sql);
}

Set mHandle to NULL after closing.


// RUN: %clang_cl_asan -O0 %s -Fe%t
// RUN: not %run %t 2>&1 | FileCheck %s
// REQUIRES: asan-32-bits

#include <malloc.h>

int main() {
  while (true) {
    void *ptr = malloc(200 * 1024 * 1024);  // 200MB
  }
// CHECK: failed to allocate
}

// RUN: %clang_cl_asan -O0 %s -Fe%t
// RUN: not %run %t 2>&1 | FileCheck %s
// REQUIRES: asan-32-bits

#include <malloc.h>

int main() {
  while (true) {
    void *ptr = malloc(200 * 1024 * 1024);  // 200MB
  }
// CHECK: allocator is terminating the process instead of returning 0
}

Fix allocator OOM test on Windows.


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

#include "realsense/enhanced_photography/enhanced_photography_extension.h"

#include <string>

#include "realsense/enhanced_photography/enhanced_photography_instance.h"

xwalk::common::Extension* CreateExtension() {
  return new realsense::enhanced_photography::EnhancedPhotographyExtension;
}

// This will be generated from common_api.js
extern const char kSource_common_api[];
// This will be generated from common_promise_api.js
extern const char kSource_common_promise_api[];
// This will be generated from enhanced_photography_api.js.
extern const char kSource_enhanced_photography_api[];

namespace realsense {
namespace enhanced_photography {

EnhancedPhotographyExtension::EnhancedPhotographyExtension() {
  SetExtensionName("realsense.EnhancedPhotography");
  std::string jsapi(kSource_common_api);
  jsapi += kSource_common_promise_api;
  jsapi += kSource_enhanced_photography_api;
  SetJavaScriptAPI(jsapi.c_str());
}

EnhancedPhotographyExtension::~EnhancedPhotographyExtension() {}

xwalk::common::Instance* EnhancedPhotographyExtension::CreateInstance() {
  return new EnhancedPhotographyInstance();
}

}  // namespace enhanced_photography
}  // namespace realsense

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

#include "realsense/enhanced_photography/enhanced_photography_extension.h"

#include <string>

#include "base/at_exit.h"
#include "realsense/enhanced_photography/enhanced_photography_instance.h"

base::AtExitManager exit_manager;

xwalk::common::Extension* CreateExtension() {
  return new realsense::enhanced_photography::EnhancedPhotographyExtension;
}

// This will be generated from common_api.js
extern const char kSource_common_api[];
// This will be generated from common_promise_api.js
extern const char kSource_common_promise_api[];
// This will be generated from enhanced_photography_api.js.
extern const char kSource_enhanced_photography_api[];

namespace realsense {
namespace enhanced_photography {

EnhancedPhotographyExtension::EnhancedPhotographyExtension() {
  SetExtensionName("realsense.EnhancedPhotography");
  std::string jsapi(kSource_common_api);
  jsapi += kSource_common_promise_api;
  jsapi += kSource_enhanced_photography_api;
  SetJavaScriptAPI(jsapi.c_str());
}

EnhancedPhotographyExtension::~EnhancedPhotographyExtension() {}

xwalk::common::Instance* EnhancedPhotographyExtension::CreateInstance() {
  return new EnhancedPhotographyInstance();
}

}  // namespace enhanced_photography
}  // namespace realsense

Fix DCHECK of AtExitManager failure


//===-- sanitizer_allocator.cc --------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is shared between AddressSanitizer and ThreadSanitizer
// run-time libraries.
// This allocator that is used inside run-times.
//===----------------------------------------------------------------------===//
#include "sanitizer_common.h"

// FIXME: We should probably use more low-level allocator that would
// mmap some pages and split them into chunks to fulfill requests.
#include <stdlib.h>

namespace __sanitizer {

static const u64 kInternalAllocBlockMagic = 0x7A6CB03ABCEBC042ull;

void *InternalAlloc(uptr size) {
  void *p = malloc(size + sizeof(u64));
  ((u64*)p)[0] = kInternalAllocBlockMagic;
  return (char*)p + sizeof(u64);
}

void InternalFree(void *addr) {
  if (!addr) return;
  addr = (char*)addr - sizeof(u64);
  CHECK_EQ(((u64*)addr)[0], kInternalAllocBlockMagic);
  ((u64*)addr)[0] = 0;
  free(addr);
}

}  // namespace __sanitizer

//===-- sanitizer_allocator.cc --------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is shared between AddressSanitizer and ThreadSanitizer
// run-time libraries.
// This allocator that is used inside run-times.
//===----------------------------------------------------------------------===//
#include "sanitizer_common.h"

// FIXME: We should probably use more low-level allocator that would
// mmap some pages and split them into chunks to fulfill requests.
#ifdef __linux__
extern "C" void *__libc_malloc(__sanitizer::uptr size);
extern "C" void __libc_free(void *ptr);
# define LIBC_MALLOC __libc_malloc
# define LIBC_FREE __libc_free
#else  // __linux__
# include <stdlib.h>
# define LIBC_MALLOC malloc
# define LIBC_FREE free
#endif  // __linux__

namespace __sanitizer {

static const u64 kInternalAllocBlockMagic = 0x7A6CB03ABCEBC042ull;

void *InternalAlloc(uptr size) {
  void *p = LIBC_MALLOC(size + sizeof(u64));
  ((u64*)p)[0] = kInternalAllocBlockMagic;
  return (char*)p + sizeof(u64);
}

void InternalFree(void *addr) {
  if (!addr) return;
  addr = (char*)addr - sizeof(u64);
  CHECK_EQ(((u64*)addr)[0], kInternalAllocBlockMagic);
  ((u64*)addr)[0] = 0;
  LIBC_FREE(addr);
}

}  // namespace __sanitizer

Use __libc_malloc/__libc_free instead of malloc/free inside internal allocator on Linux (important for TSan)


#include <ros/ros.h>
#include <geometry_msgs/Twist.h>

namespace quadrotor_obstacle_avoidance {

int main(int argc, char *argv[]){
    ros::init(argc, argv, "quadrotor_obstacle_avoidance");

    ros::NodeHandle node;
    ros::Publisher cmd_pub = node.advertise<geometry_msgs::Twist>("cmd_vel", 10);

    geometry_msgs::Twist cmd;

    cmd.linear.z = 0.5;
    cmd_pub.publish(cmd);
    ros::Duration(5);

    cmd.linear.z = 0.0;
    cmd_pub.publish(cmd);
    ros::Duration(5);

    return 0;
}

};

#include <ros/ros.h>
#include <geometry_msgs/Twist.h>

int main(int argc, char *argv[]){
    ros::init(argc, argv, "quadrotor_obstacle_avoidance");

    ros::NodeHandle node;
    ros::Publisher cmd_pub = node.advertise<geometry_msgs::Twist>("cmd_vel", 10);

    ros::Duration(1).sleep();

    geometry_msgs::Twist cmd;

    cmd.linear.z = 5;
    cmd_pub.publish(cmd);
    ros::Duration(5).sleep();

    cmd.linear.z = 0.0;
    cmd_pub.publish(cmd);
    ros::Duration(5).sleep();

    return 0;
}

Fix building error of node


#include <iostream>
#include <string>

using namespace std;

typedef struct {
    String nome;
    String cpf;
    float saldo;
} Conta;

float get_saldo( Conta &conta ) {
    return conta.saldo;
}

void set_saldo( Conta &conta ) {
    conta.saldo;
}
int main() {
    Conta conta;

    init_conta( conta );

    return 0;
}

#include <iostream>
#include <string>

using namespace std;

typedef struct {
    String nome;
    String cpf;
    float saldo;
} Conta;

int main() {
    Conta conta;

    init_conta( conta );

    return 0;
}

Revert "Criando estruturas de dados"


// 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/common/thumbnail_support.h"

#include "base/command_line.h"
#include "chrome/common/chrome_switches.h"

#if defined(OS_WIN)
#include "base/win/windows_version.h"
#endif

bool ShouldEnableInBrowserThumbnailing() {
  if (CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kDisableInBrowserThumbnailing))
    return false;

#if defined(OS_CHROMEOS)
  return true;
#else
  return false;
#endif
}

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

#include "chrome/common/thumbnail_support.h"

#include "base/command_line.h"
#include "chrome/common/chrome_switches.h"

#if defined(OS_WIN)
#include "base/win/windows_version.h"
#endif

bool ShouldEnableInBrowserThumbnailing() {
  if (CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kDisableInBrowserThumbnailing))
    return false;

#if defined(OS_WIN)
  // Disables in-browser thumbnailing on Windows XP where not supported yet.
  if (base::win::GetVersion() < base::win::VERSION_VISTA)
    return false;
  return true;
#elif defined(OS_LINUX) && !defined(USE_AURA)
  // Disables in-browser thumbnailing on non-Aura Linux where not supported yet.
  return false;
#else
  return true;
#endif
}

Revert "Temporarily disable in-browser thumbnailing on Win and Mac."


// AMX profiler for SA-MP server: http://sa-mp.com
//
// Copyright (C) 2011-2012 Sergey Zolotarev
//
// 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 "function_info.h"

namespace amx_profiler {

FunctionInfo::FunctionInfo(const FunctionPtr &func)
	: func_(func)
	, num_calls_(1)
	, total_time_(0)
	, child_time_(0)
{
}

} // namespace amx_profiler

// AMX profiler for SA-MP server: http://sa-mp.com
//
// Copyright (C) 2011-2012 Sergey Zolotarev
//
// 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 "function_info.h"

namespace amx_profiler {

FunctionInfo::FunctionInfo(const FunctionPtr &func)
	: func_(func)
	, num_calls_(0)
	, total_time_(0)
	, child_time_(0)
{
}

} // namespace amx_profiler

Fix num_calls initialized to 1 instead of 0


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

struct GrGLInterface;

const GrGLInterface* GrGLDefaultInterface() {
    return NULL;
}

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

#include "GrGLInterface.h"

const GrGLInterface* GrGLDefaultInterface() {
    return NULL;
}

Include GrGLInterface.h instead of forward declaring, since we have to get NULL defined anyway.


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

#include "remoting/jingle_glue/ssl_adapter.h"

#if defined(OS_WIN)
#include "third_party/libjingle/source/talk/base/ssladapter.h"
#else
#include "remoting/jingle_glue/ssl_socket_adapter.h"
#endif

namespace remoting {

talk_base::SSLAdapter* CreateSSLAdapter(talk_base::AsyncSocket* socket) {
  talk_base::SSLAdapter* ssl_adapter =
#if defined(OS_WIN)
      talk_base::SSLAdapter::Create(socket);
#else
      remoting::SSLSocketAdapter::Create(socket);
#endif
  DCHECK(ssl_adapter);
  return ssl_adapter;
}

}  // namespace remoting

// 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 "remoting/jingle_glue/ssl_adapter.h"

#if defined(OS_WIN)
#include "third_party/libjingle/source/talk/base/ssladapter.h"
#else
#include "remoting/jingle_glue/ssl_socket_adapter.h"
#endif

namespace remoting {

talk_base::SSLAdapter* CreateSSLAdapter(talk_base::AsyncSocket* socket) {
  talk_base::SSLAdapter* ssl_adapter =
      remoting::SSLSocketAdapter::Create(socket);
  DCHECK(ssl_adapter);
  return ssl_adapter;
}

}  // namespace remoting

Use NSS for SSL encryption of XMPP connection on Windows.


#include "Emulator.hpp"

int main(const int argc, char* argv[]) {
    Emulator emulator;

    emulator.run();
}

#include <iostream>
#include <string>
#include <stdexcept>
#include <limits>

#include "Emulator.hpp"

void printHelpMessage() {
    std::cout
        << "A NES emulator. Takes .nes files.\n\n"
        << "Usage: turbones [options] <path-to-rom-file>\n\n"
        << "Options:\n"
        << "\t-h  --help\n"
        << "\t\tPrint this help text and exit."
        << std::endl;
}

void handleArguments(const int& argc, char* argv[], Emulator& emulator) {
    for (int i = 1; i < argc; ++i) {
        std::string arg = argv[i];

        if (arg == "-h"
            || arg == "--help") {
            printHelpMessage();
            exit(EXIT_SUCCESS);
        }
        else if (i == argc - 1) {
            emulator.rom_path = arg;
        }
        else {
            std::cerr << "Unrecognized argument: " << arg << std::endl; }
    }
}

int main(const int argc, char* argv[]) {
    Emulator emulator;
    handleArguments(argc, argv, emulator);

    try {
        emulator.run();
    }
    catch (const std::runtime_error& e) {
        std::cerr << "\nFailed to run (" << e.what() << "). Shutting down." << std::endl;
        // The pause here is to make sure the error can be read.
        std::cout << "Press Enter to exit . . . ";
        // Waits until Enter ('\n') is pressed. It turns out to be simpler
        // to write this portably, if we wait for Enter, rather than "any key".
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        return EXIT_FAILURE;
    }
}

Add basic command line argument parsing.


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

#include <vespa/fastos/fastos.h>
#include <vespa/log/log.h>
#include "multi_value_mapping2.h"
#include "multi_value_mapping2.hpp"
#include <vespa/vespalib/stllike/string.h>

LOG_SETUP(".searchlib.attribute.multivaluemapping2");

namespace search {
namespace attribute {

template class MultiValueMapping2<int32_t>;

} // namespace search::attribute
} // namespace search

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

#include <vespa/fastos/fastos.h>
#include <vespa/log/log.h>
#include "multi_value_mapping2.h"
#include "multi_value_mapping2.hpp"
#include <vespa/vespalib/stllike/string.h>
#include "multivalue.h"
#include "enumstorebase.h"

LOG_SETUP(".searchlib.attribute.multivaluemapping2");

using search::multivalue::Value;
using search::multivalue::WeightedValue;

namespace search {
namespace attribute {

template class MultiValueMapping2<Value<EnumStoreIndex>>;
template class MultiValueMapping2<WeightedValue<EnumStoreIndex>>;
template class MultiValueMapping2<Value<int8_t>>;
template class MultiValueMapping2<WeightedValue<int8_t>>;
template class MultiValueMapping2<Value<int16_t>>;
template class MultiValueMapping2<WeightedValue<int16_t>>;
template class MultiValueMapping2<Value<int32_t>>;
template class MultiValueMapping2<WeightedValue<int32_t>>;
template class MultiValueMapping2<Value<int64_t>>;
template class MultiValueMapping2<WeightedValue<int64_t>>;
template class MultiValueMapping2<Value<float>>;
template class MultiValueMapping2<WeightedValue<float>>;
template class MultiValueMapping2<Value<double>>;
template class MultiValueMapping2<WeightedValue<double>>;

} // namespace search::attribute
} // namespace search

Add explicit instantiation of variants to be used in production.


#include <QString>
#include <QtTest>
#include <execinfo.h>
#include <signal.h>
#include <unistd.h>
#include <TestRunner>
#include <QtQuickTest/quicktest.h>
#include "aconcurrenttests.h"
#include "aconcurrent.h"

void dummy() {
    // Dummy function. It is not called.
    // It just prove it won't create any duplicated symbols

    auto worker = [](int value) {
        return value * value;
    };

    AConcurrent::blockingMapped(QThreadPool::globalInstance(), QList<int>(), worker);
}

void handleBacktrace(int sig) {
    void *array[100];
    size_t size;

    // get void*'s for all entries on the stack
    size = backtrace(array, 100);

    // print out all the frames to stderr
    fprintf(stderr, "Error: signal %d:\n", sig);
    backtrace_symbols_fd(array, size, STDERR_FILENO);
    exit(1);
}

namespace AutoTestRegister {
QUICK_TEST_MAIN(QuickTests)
}

int main(int argc, char *argv[])
{
    signal(SIGSEGV, handleBacktrace);

    QCoreApplication app(argc, argv);

    TestRunner runner;
    runner.addImportPath("qrc:///");
    runner.add<AConcurrentTests>();

    bool error = runner.exec(app.arguments());

    if (!error) {
        qDebug() << "All test cases passed!";
    }

    return error;
}

#include <QString>
#include <QtTest>
#include <TestRunner>
#include <QtQuickTest/quicktest.h>
#include "aconcurrenttests.h"
#include "aconcurrent.h"

void dummy() {
    // Dummy function. It is not called.
    // It just prove it won't create any duplicated symbols

    auto worker = [](int value) {
        return value * value;
    };

    AConcurrent::blockingMapped(QThreadPool::globalInstance(), QList<int>(), worker);
}

#if defined(Q_OS_MAC) || defined(Q_OS_LINUX)
#include <execinfo.h>
#include <unistd.h>
#include <signal.h>
void handleBacktrace(int sig) {
    void *array[100];
    size_t size;

    // get void*'s for all entries on the stack
    size = backtrace(array, 100);

    // print out all the frames to stderr
    fprintf(stderr, "Error: signal %d:\n", sig);
    backtrace_symbols_fd(array, size, STDERR_FILENO);
    exit(1);
}
#endif

namespace AutoTestRegister {
QUICK_TEST_MAIN(QuickTests)
}

int main(int argc, char *argv[])
{
#if defined(Q_OS_MAC) || defined(Q_OS_LINUX)
    signal(SIGSEGV, handleBacktrace);
#endif

    QCoreApplication app(argc, argv);

    TestRunner runner;
    runner.addImportPath("qrc:///");
    runner.add<AConcurrentTests>();

    bool error = runner.exec(app.arguments());

    if (!error) {
        qDebug() << "All test cases passed!";
    }

    return error;
}

Fix a build issue in Windows


// This program is free software licenced under MIT Licence. You can
// find a copy of this licence in LICENCE.txt in the top directory of
// source code.
//

#include "../include/turing_machine.hpp"

using namespace turingmachine;

class do_nothing final: public tm_abstract_problem {
  public:
    const char *name() const override {
        return "Empty";
    }

    void configure() override {
        // Do nothing, tape should remain the same
    }

    void add_units() override {
        ADD_UNIT_TEST(">#01#", ">#01#");
        ADD_UNIT_TEST(">", ">");
        ADD_UNIT_TEST(">9$1#", ">9$1#");
    }
};

class dummy final: public tm_abstract_problem {
  public:
    const char *name() const override {
        return "Dummy";
    }

    void configure() override {
        ADD_TRANSITION(0, '#', 1, '0', GO_RIGHT);
    }

    void add_units() override {
        ADD_UNIT_TEST(">#01#", ">001#");
    }
};

int main() {
    do_nothing{}.run();
    dummy{}.run();
}

// This program is free software licenced under MIT Licence. You can
// find a copy of this licence in LICENCE.txt in the top directory of
// source code.
//

#include "../include/turing_machine.hpp"

using namespace turingmachine;

class do_nothing final: public tm_abstract_problem {
  public:
    const char *name() const override {
        return "Empty";
    }

    void configure() override {
        // Do nothing, tape should remain the same
    }

    void add_units() override {
        ADD_UNIT_TEST(">#01#", ">#01#");
        ADD_UNIT_TEST(">", ">");
        ADD_UNIT_TEST(">9$1#", ">9$1#");
    }
};

class dummy final: public tm_abstract_problem {
  public:
    const char *name() const override {
        return "Dummy";
    }

    void configure() override {
        // Note that the last state is considered the final one.
        ADD_TRANSITION(0, '#', 1, '0', GO_RIGHT);
    }

    void add_units() override {
        ADD_UNIT_TEST(">#01#", ">001#");
    }
};

int main() {
    do_nothing{}.run();
    dummy{}.run();
}

Add comment to make it clear


#include <lua.hpp>
#include <luwra.hpp>

#include <iostream>

using namespace luwra;

// You may add custom specializations of luwra::Value in order to retrieve them from the stack.
template <>
struct Value<char> {
	/**
	 * Retrieve the value at position `n`.
	 */
	static inline
	char Read(State* state, int n) {
		auto str = Value<std::string>::Read(state, n);

		if (str.length() < 1) {
			luaL_argerror(state, n, "Given empty string instead of character");
		}

		return str[0];
	}

	/**
	 * Push the value onto the stack.
	 */
	static inline
	int Push(State* state, char val) {
		if (val == 0)
			return 0;

		lua_pushlstring(state, &val, 1);

		return 1;
	}
};

static
void read_chars(char a, char b) {
	std::cout << "Got '" << a << b << "'" << std::endl;
}

int main() {
	lua_State* state = luaL_newstate();
	luaL_openlibs(state);

	// Build stack
	Value<char>::Push(state, 'H');
	Value<char>::Push(state, 'i');

	// Apply function to stack values
	Apply(state, read_chars);

	lua_close(state);
	return 0;
}

#include <lua.hpp>
#include <luwra.hpp>

#include <iostream>

using namespace luwra;

// You may add custom specializations of luwra::Value in order to retrieve them from the stack.
template <>
struct Value<char> {
	/**
	 * Retrieve the value at position `n`.
	 */
	static inline
	char Read(State* state, int n) {
		auto str = Value<std::string>::Read(state, n);

		if (str.length() < 1) {
			luaL_argerror(state, n, "Given empty string instead of character");
		}

		return str[0];
	}

	/**
	 * Push the value onto the stack.
	 */
	static inline
	int Push(State* state, char val) {
		if (val == 0)
			return 0;

		lua_pushlstring(state, &val, 1);

		return 1;
	}
};

static
void read_chars(char a, char b) {
	std::cout << "Got '" << a << b << "'" << std::endl;
}

int main() {
	lua_State* state = luaL_newstate();
	luaL_openlibs(state);

	// Build stack
	Push(state, 'H');
	Push(state, 'i');

	// Apply function to stack values
	Apply(state, read_chars);

	lua_close(state);
	return 0;
}

Use Push to push a value


#include <CppUnit/framework/TestSuite.h>
#include <CppUnit/textui/TestRunner.h>
#include <TestCases/Socket/SocketTest.h>
#include <TestCases/Thread/ThreadTest.h>
#include <TestCases/IO/Socket/InetAddrTest.h>

using namespace vpr;

int main (int ac, char **av)
{
   TestRunner runner;

   //------------------------------------
   //  noninteractive
   //------------------------------------
   // create non-interactive test suite
   TestSuite* noninteractive_suite = new TestSuite("NonInteractive");

   // add tests to the suite
   //suite_1->addTest( /* put your test here */ );
   noninteractive_suite->addTest(vprTest::InetAddrTest::suite());
   noninteractive_suite->addTest(SocketTest::suite());

   // Add the test suite to the runner
   runner.addTest( "noninteractive", noninteractive_suite );

   // create test suite #2
   TestSuite* suite_2 = new TestSuite("suite_2");

   // add tests to the suite
   //suite_2->addTest(gmtlTest::Vec3Test::suite());
   //suite_2->addTest(gmtlTest::MatrixTest::suite());
   //suite_2->addTest(gmtlTest::Point3Test::suite());
   suite_2->addTest(ThreadTest::suite());

   // Add the test suite to the runner
   runner.addTest("suite_2_tests", suite_2);

   // run all test suites
   runner.run( ac, av );

   return 0;
}

#include <CppUnit/framework/TestSuite.h>
#include <CppUnit/textui/TestRunner.h>
#include <TestCases/Socket/SocketTest.h>
#include <TestCases/Thread/ThreadTest.h>
#include <TestCases/IO/Socket/InetAddrTest.h>

//using namespace vpr;

int main (int ac, char **av)
{
   TestRunner runner;

   //------------------------------------
   //  noninteractive
   //------------------------------------
   // create non-interactive test suite
   TestSuite* noninteractive_suite = new TestSuite("NonInteractive");

   // add tests to the suite
   //suite_1->addTest( /* put your test here */ );
   noninteractive_suite->addTest(vprTest::InetAddrTest::suite());
   noninteractive_suite->addTest(vprTest::SocketTest::suite());

   // Add the test suite to the runner
   runner.addTest( "noninteractive", noninteractive_suite );

   // create test suite #2
   TestSuite* suite_2 = new TestSuite("suite_2");

   // add tests to the suite
   //suite_2->addTest(gmtlTest::Vec3Test::suite());
   //suite_2->addTest(gmtlTest::MatrixTest::suite());
   //suite_2->addTest(gmtlTest::Point3Test::suite());
   suite_2->addTest(ThreadTest::suite());

   // Add the test suite to the runner
   runner.addTest("suite_2_tests", suite_2);

   // run all test suites
   runner.run( ac, av );

   return 0;
}

Put sock test in vprTest namespace


// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#include "platform/globals.h"
#if defined(HOST_OS_MACOS)

#include <errno.h>  // NOLINT
#include <fcntl.h>  // NOLINT

#include "bin/crypto.h"
#include "bin/fdutils.h"
#include "platform/signal_blocker.h"

namespace dart {
namespace bin {

bool Crypto::GetRandomBytes(intptr_t count, uint8_t* buffer) {
  ThreadSignalBlocker signal_blocker(SIGPROF);
  intptr_t fd = TEMP_FAILURE_RETRY_NO_SIGNAL_BLOCKER(
      open("/dev/urandom", O_RDONLY | O_CLOEXEC));
  if (fd < 0) {
    return false;
  }
  intptr_t bytes_read = 0;
  do {
    int res = TEMP_FAILURE_RETRY_NO_SIGNAL_BLOCKER(
        read(fd, buffer + bytes_read, count - bytes_read));
    if (res < 0) {
      int err = errno;
      close(fd);
      errno = err;
      return false;
    }
    bytes_read += res;
  } while (bytes_read < count);
  close(fd);
  return true;
}

}  // namespace bin
}  // namespace dart

#endif  // defined(HOST_OS_MACOS)

// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#include "platform/globals.h"
#if defined(HOST_OS_MACOS)

#include <errno.h>  // NOLINT
#include <fcntl.h>  // NOLINT

#include "bin/crypto.h"
#include "bin/fdutils.h"
#include "platform/signal_blocker.h"

namespace dart {
namespace bin {

bool Crypto::GetRandomBytes(intptr_t count, uint8_t* buffer) {
  intptr_t fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC));
  if (fd < 0) {
    return false;
  }
  intptr_t bytes_read = 0;
  do {
    int res =
        TEMP_FAILURE_RETRY(read(fd, buffer + bytes_read, count - bytes_read));
    if (res < 0) {
      int err = errno;
      close(fd);
      errno = err;
      return false;
    }
    bytes_read += res;
  } while (bytes_read < count);
  close(fd);
  return true;
}

}  // namespace bin
}  // namespace dart

#endif  // defined(HOST_OS_MACOS)

Disable checking of sigprof on mac.


#include "ReQL-test.hpp"

#include "catch.h"

using namespace ReQL;

TEST_CASE("Connection", "[c++][connect]") {
  Connection conn = connect();

  REQUIRE(conn.isOpen());
}

TEST_CASE("Expr", "[c][expr]") {
  SECTION("string") {
    _ReQL_Op_t string;

    const uint32_t size = 12;

    uint8_t buf[size] = "Hello World";

    std::string orig = std::string((char *)buf, size);

    _reql_string_init(&string, buf, size, size);

    CHECK(orig.compare(0, size, (char *)_reql_string_buf(&string), size) == 0);
    CHECK(size == _reql_string_size(&string));
  }
}

Add string c constructor test.


// Copyright (c) 2011 - 2019, GS Group, https://github.com/GSGroup
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
// provided that the above copyright notice and this permission notice appear in all copies.
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

#include <stingraykit/log/Logger.h>
#include <stingraykit/diagnostics/Backtrace.h>

extern "C" typeof(abort) __real_abort;

extern "C" void __wrap_abort(ssize_t size)
{
	using namespace stingray;

	Logger::Error() << "Abort called: " << Backtrace().Get();

	__real_abort();
}

// Copyright (c) 2011 - 2019, GS Group, https://github.com/GSGroup
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
// provided that the above copyright notice and this permission notice appear in all copies.
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

#include <stingraykit/log/Logger.h>
#include <stingraykit/diagnostics/Backtrace.h>

extern "C" __typeof__(abort) __real_abort;

extern "C" void __wrap_abort(ssize_t size)
{
	using namespace stingray;

	Logger::Error() << "Abort called: " << Backtrace().Get();

	__real_abort();
}

Use ANSI compatible __typeof__ instead of GNU's typeof


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

#include "RendererOGLOSX.h"

namespace ouzel
{
    namespace graphics
    {
        bool RendererOGLOSX::init(const WindowPtr& window,
                                  uint32_t newSampleCount,
                                  TextureFiltering newTextureFiltering,
                                  float newTargetFPS,
                                  bool newVerticalSync)
        {
            return RendererOGL::init(window, newSampleCount, newTextureFiltering, newTargetFPS, newVerticalSync);
        }
    } // namespace graphics
} // namespace ouzel

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

#include "RendererOGLOSX.h"

namespace ouzel
{
    namespace graphics
    {
        bool RendererOGLOSX::init(const WindowPtr& window,
                                  uint32_t newSampleCount,
                                  TextureFiltering newTextureFiltering,
                                  float newTargetFPS,
                                  bool newVerticalSync)
        {
            free();

            return RendererOGL::init(window, newSampleCount, newTextureFiltering, newTargetFPS, newVerticalSync);
        }
    } // namespace graphics
} // namespace ouzel

Call free in OSX renderer's init


#include "parsertest.h"
#include "fileast.h"
#include "scanner.h"
#include "myexception.h"
#include <QtTest/QtTest>

ParserTest::ParserTest(QObject *parent) : QObject(parent)
{

}

void ParserTest::initTestCase() {
}

void ParserTest::cleanupTestCase() {
}

void ParserTest::dummySuccess() {

}

Q_DECLARE_METATYPE(FileAST)
void ParserTest::expectedAST_data() {
    QTest::addColumn<QString>("input"); //QRC file
    //QTest::addColumn<FileAST>("expected");

    QTest::newRow("Sample 1") << ":/sample_1_tokens.json";

}

void ParserTest::expectedAST() {
    QFETCH(QString, input);
    try {
        QFile file(input);
        QVERIFY(file.open(QFile::ReadOnly));
        QByteArray data = file.readAll();
        auto doc = QJsonDocument::fromJson(data);
        auto tokens = Scanner::fromJson(doc);
        //Now that we have the tokens, we can compare to expected AST (TODO)

        qDebug() << "Number of tokens : " << tokens.tokens().size();
    }
    catch (MyException& e) {
        QFAIL(QString("Exception catched in test : %1").arg(e.msg).toStdString().data());
    }
}

#include "parsertest.h"
#include "fileast.h"
#include "parser.h"
#include "scanner.h"
#include "myexception.h"
#include <QtTest/QtTest>

ParserTest::ParserTest(QObject *parent) : QObject(parent)
{

}

void ParserTest::initTestCase() {
}

void ParserTest::cleanupTestCase() {
}

void ParserTest::dummySuccess() {

}

Q_DECLARE_METATYPE(FileAST)
void ParserTest::expectedAST_data() {
    QTest::addColumn<QString>("input"); //QRC file
    //QTest::addColumn<FileAST>("expected");

    QTest::newRow("Sample 1") << ":/sample_1_tokens.json";

}

void ParserTest::expectedAST() {
    QFETCH(QString, input);
    try {
        QFile file(input);
        QVERIFY(file.open(QFile::ReadOnly));
        QByteArray data = file.readAll();
        auto doc = QJsonDocument::fromJson(data);
        auto scanner = Scanner::fromJson(doc);
        auto tokens = scanner.tokens();

        //Now that we have the tokens, we can parse then compare to expected AST (TODO)

        Parser parser(tokens);

        qDebug() << "Log of parser : " << parser.getLog();
    }
    catch (MyException& e) {
        QFAIL(QString("Exception catched in test : %1").arg(e.msg).toStdString().data());
    }
}

Test now outputs the log


#include <iostream>

#include <Sequence/variant_matrix/msformat.hpp>
#include <Sequence/summstats.hpp>

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    std::cerr.tie(nullptr);
    std::cout.setf(std::ios::fixed);
    std::cout.precision(6);
    std::cout << "pi\tS\tD\tthetaH\tH\n";
    do {
        const auto vm = Sequence::from_msformat(std::cin);
        Sequence::AlleleCountMatrix ac(vm);
        const double pi = Sequence::thetapi(ac);
        const double tH = Sequence::thetah(ac, 0);
        std::cout << pi << '\t'
                  << Sequence::nvariable_sites(ac) << '\t'
                  << Sequence::tajd(ac) << '\t'
                  << tH << '\t'
                  << pi - tH << '\n';
    } while (!std::cin.eof());
    return 0;
}

#include <iostream>

#include <Sequence/variant_matrix/msformat.hpp>
#include <Sequence/summstats.hpp>

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    std::cerr.tie(nullptr);
    std::cout.setf(std::ios::fixed);
    std::cout.precision(6);
    std::cout << "pi\tS\tD\ttH\n";
    do {
        const auto vm = Sequence::from_msformat(std::cin);
        Sequence::AlleleCountMatrix ac(vm);
        std::cout << Sequence::thetapi(ac) << '\t'
                  << Sequence::nvariable_sites(ac) << '\t'
                  << Sequence::tajd(ac) << '\t'
                  << Sequence::thetah(ac, 0) << '\n';
    } while (!std::cin.eof());
    return 0;
}

Rename columns to be compatible with sample_stats++


#include "casexponent.h"

// CasExpression CasExponent::getE(){
//   return e;
}

#include "casexponent.h"

// CasExpression CasExponent::getE(){
//   return e;
//}

Fix problem with broken }


// Regression test for http://llvm.org/bugs/show_bug.cgi?id=21621
// This test relies on timing between threads, so any failures will be flaky.
// RUN: %clangxx_lsan %s -o %t
// RUN: LSAN_OPTIONS="log_pointers=1:log_threads=1" %run %t
#include <assert.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

void *func(void *arg) {
  sleep(1);
  free(arg);
  return 0;
}

void create_detached_thread() {
  pthread_t thread_id;
  pthread_attr_t attr;

  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

  void *arg = malloc(1337);
  assert(arg);
  int res = pthread_create(&thread_id, &attr, func, arg);
  assert(res == 0);
}

int main() {
  create_detached_thread();
}

// Regression test for http://llvm.org/bugs/show_bug.cgi?id=21621
// This test relies on timing between threads, so any failures will be flaky.
// RUN: %clangxx_lsan %s -o %t
// RUN: LSAN_OPTIONS="log_pointers=1:log_threads=1" %run %t
#include <assert.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
bool flag = false;

void *func(void *arg) {
  // This mutex will never be grabbed.
  fprintf(stderr, "entered func()\n");
  pthread_mutex_lock(&mutex);
  free(arg);
  pthread_mutex_unlock(&mutex);
  return 0;
}

void create_detached_thread() {
  pthread_t thread_id;
  pthread_attr_t attr;

  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

  void *arg = malloc(1337);
  assert(arg);
  // This mutex is never unlocked by the main thread.
  pthread_mutex_lock(&mutex);
  int res = pthread_create(&thread_id, &attr, func, arg);
  assert(res == 0);
}

int main() {
  create_detached_thread();
}

Test case fix: mode debug output, synchronization instead of sleep().


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

// <random>

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

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

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

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

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

// <random>

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

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

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

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

Fix bug in test; found by AddressSanitizer


#include <iostream>
#include <system_error>

#include "controllers/main/MainModule.hpp"
#include "network/bsdsocket/Manager.hpp"
#include "network/sniffer/SnifferManager.hpp"

int main()
{
    tin::controllers::main::ControllerQueue ctrlQueue;
    tin::network::bsdsocket::ManagerQueue netManagerQueue;

    tin::controllers::main::MainModule mainCtrl(ctrlQueue, netManagerQueue);
    tin::network::bsdsocket::Manager networkManager(netManagerQueue, ctrlQueue, 3333);
    tin::network::sniffer::SnifferManager sniffManager(ctrlQueue, "lo", "src 127.0.0.1");

    std::cout << "Hello agent!\n";

    auto mainCtrlThread = mainCtrl.createThread();
    auto netManager = networkManager.createThread();

    try
    {
        mainCtrlThread.join();
        netManager.join();
    }
    catch (std::system_error& e)
    {
        // Could not join one of the threads
    }

    return 0;
}

#include <iostream>
#include <system_error>

#include "controllers/main/MainModule.hpp"
#include "network/bsdsocket/Manager.hpp"
#include "network/sniffer/Manager.hpp"

#include "network/sniffer/events/ChangeFilter.hpp"

int main()
{
    tin::controllers::main::ControllerQueue ctrlQueue;
    tin::network::bsdsocket::ManagerQueue netManagerQueue;
    tin::network::sniffer::ManagerQueue snifferManagerQueue;

    tin::controllers::main::MainModule mainCtrl(ctrlQueue, netManagerQueue);
    tin::network::bsdsocket::Manager networkManager(netManagerQueue, ctrlQueue, 3333);
    tin::network::sniffer::Manager sniffManager(
        snifferManagerQueue,
        ctrlQueue,
        "lo",
        "src 127.0.0.1"
    );

    std::cout << "Hello agent!\n";

    auto mainCtrlThread = mainCtrl.createThread();
    auto netManager = networkManager.createThread();
    auto sniffThread = sniffManager.createThread();

    std::this_thread::sleep_for (std::chrono::seconds(1));

    snifferManagerQueue.push(
        std::make_shared<tin::network::sniffer::events::ChangeFilter>(
            "lo",
            "src 127.0.0.1"
        )
    );

    try
    {
        mainCtrlThread.join();
        netManager.join();
        sniffThread.join();
    }
    catch (std::system_error& e)
    {
        // Could not join one of the threads
    }

    return 0;
}

Add a simple example of sniffer manager


#include <lug/System/Exception.hpp>
#include <sstream>

lug::System::Exception::Exception(const char *typeName, const std::string &description, const char* file, const char* function, uint32_t line)
    : _typeName{typeName}, _description{description}, _file{file}, _function{function}, _line{line} {}

const std::string& lug::System::Exception::getTypeName() const {
    return _typeName;
}

const std::string& lug::System::Exception::getDescription() const {
    return _description;
}

const std::string& lug::System::Exception::getFile() const {
    return _file;
}

const std::string& lug::System::Exception::getFunction() const {
    return _function;
}

const uint32_t lug::System::Exception::getLine() const {
    return _line;
}

const char* lug::System::Exception::what() const noexcept {
    std::stringstream msg;

    msg << _typeName << ": " << _description << std::endl;
    msg << "In " << _file;
    msg << " at " << _function << " line " << _line;

    _fullDesc = msg.str();
    return _fullDesc.c_str();
}

#include <lug/System/Exception.hpp>
#include <sstream>

lug::System::Exception::Exception(const char *typeName, const std::string &description, const char* file, const char* function, uint32_t line)
    : _typeName{typeName}, _description{description}, _file{file}, _function{function}, _line{line} {}

const std::string& lug::System::Exception::getTypeName() const {
    return _typeName;
}

const std::string& lug::System::Exception::getDescription() const {
    return _description;
}

const std::string& lug::System::Exception::getFile() const {
    return _file;
}

const std::string& lug::System::Exception::getFunction() const {
    return _function;
}

const uint32_t lug::System::Exception::getLine() const {
    return _line;
}

const char* lug::System::Exception::what() const noexcept {
    std::stringstream msg;

    msg << _typeName << ": " << _description << std::endl;
    msg << "In " << _file;
    msg << " at `" << _function << "` line " << _line;

    _fullDesc = msg.str();
    return _fullDesc.c_str();
}

Change style of function display to match Debug.hpp


#include "imageprovider.h"

matrix::ImageProvider::ImageProvider() : QQuickImageProvider{QQuickImageProvider::Pixmap}
{
  if (!default_image_.load(":/img/res/img/default.png")) {
    default_image_ = QPixmap{256, 256};
    default_image_.fill(QColor{"#ff00ff"});
  }
}

QPixmap matrix::ImageProvider::requestPixmap(const QString& id, QSize* size,
    [[maybe_unused]] const QSize& requested_size)
{
  if (size)
    *size = QSize(32, 32);

  QPixmap p;
  if (images_.contains(id)) {
    return images_[id];
  }

  return default_image_;
}

#include "imageprovider.h"

matrix::ImageProvider::ImageProvider() : QQuickImageProvider{QQuickImageProvider::Pixmap}
{
  if (!default_image_.load(":/img/res/img/default.png")) {
    default_image_ = QPixmap{256, 256};
    default_image_.fill(QColor{"#ff00ff"});
  }
}

QPixmap matrix::ImageProvider::requestPixmap(const QString& id, QSize* size,
    [[maybe_unused]] const QSize& requested_size)
{
  if (images_.contains(id)) {
    const auto& p = images_[id];
    if (size)
      *size = QSize{p.size()};
    return p;
  }

  if (size)
    *size = QSize{default_image_.size()};

  return default_image_;
}

FIx handling of image size


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

#include "config.h"

FNET_Config::FNET_Config()
    : _minEventTimeOut(0),
      _pingInterval(0),
      _iocTimeOut(0),
      _maxInputBufferSize(0x10000),
      _maxOutputBufferSize(0x10000),
      _tcpNoDelay(true),
      _logStats(false),
      _directWrite(true)
{ }

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

#include "config.h"

FNET_Config::FNET_Config()
    : _minEventTimeOut(0),
      _pingInterval(0),
      _iocTimeOut(0),
      _maxInputBufferSize(0x10000),
      _maxOutputBufferSize(0x10000),
      _tcpNoDelay(true),
      _logStats(false),
      _directWrite(false)
{ }

Disable direct write by default.