//===- tools/seec-trace-view/Annotations.cpp ------------------------------===//
//
//                                    SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
//===----------------------------------------------------------------------===//

#include "seec/Util/MakeUnique.hpp"

#include <wx/archive.h>
#include <wx/xml/xml.h>

#include "Annotations.hpp"

AnnotationCollection::
AnnotationCollection(std::unique_ptr<wxXmlDocument> XmlDocument)
: m_XmlDocument(std::move(XmlDocument))
{}

AnnotationCollection::AnnotationCollection()
{
  m_XmlDocument = seec::makeUnique<wxXmlDocument>();

  auto const Root = new wxXmlNode(nullptr, wxXML_ELEMENT_NODE, "annotations");

  m_XmlDocument->SetRoot(Root);
}

AnnotationCollection::~AnnotationCollection() = default;

seec::Maybe<AnnotationCollection>
AnnotationCollection::fromDoc(std::unique_ptr<wxXmlDocument> Doc)
{
  return AnnotationCollection(std::move(Doc));
}

bool AnnotationCollection::writeToArchive(wxArchiveOutputStream &Stream)
{
  return Stream.PutNextEntry("annotations.xml")
      && m_XmlDocument->Save(Stream);
}

//===- tools/seec-trace-view/Annotations.cpp ------------------------------===//
//
//                                    SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
//===----------------------------------------------------------------------===//

#include "seec/Util/MakeUnique.hpp"

#include <wx/archive.h>
#include <wx/xml/xml.h>

#include "Annotations.hpp"

namespace {

bool isAnnotationCollection(wxXmlDocument &Doc)
{
  if (!Doc.IsOk())
    return false;

  auto const RootNode = Doc.GetRoot();
  if (!RootNode || RootNode->GetName() != "annotations")
    return false;

  return true;
}

} // anonymous namespace

AnnotationCollection::
AnnotationCollection(std::unique_ptr<wxXmlDocument> XmlDocument)
: m_XmlDocument(std::move(XmlDocument))
{}

AnnotationCollection::AnnotationCollection()
{
  m_XmlDocument = seec::makeUnique<wxXmlDocument>();

  auto const Root = new wxXmlNode(nullptr, wxXML_ELEMENT_NODE, "annotations");

  m_XmlDocument->SetRoot(Root);
}

AnnotationCollection::~AnnotationCollection() = default;

seec::Maybe<AnnotationCollection>
AnnotationCollection::fromDoc(std::unique_ptr<wxXmlDocument> Doc)
{
  if (!isAnnotationCollection(*Doc))
    return seec::Maybe<AnnotationCollection>();

  return AnnotationCollection(std::move(Doc));
}

bool AnnotationCollection::writeToArchive(wxArchiveOutputStream &Stream)
{
  return Stream.PutNextEntry("annotations.xml")
      && m_XmlDocument->Save(Stream);
}

Check that annotations.xml documents match our expectations.


/*
 * Copyright © 2017 Collabora Ltd.
 *
 * This file is part of vkmark.
 *
 * vkmark is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation, either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * vkmark is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with vkmark. If not, see <http://www.gnu.org/licenses/>.
 *
 * Authors:
 *   Alexandros Frantzis <alexandros.frantzis@collabora.com>
 */

#include "default_benchmarks.h"

std::vector<std::string> DefaultBenchmarks::get()
{
    return std::vector<std::string>{
        "vertex",
        "shading:shading=gouraud",
        "shading:shading=blinn-phong-inf",
        "shading:shading=phong",
        "cube",
        "clear"
    };
}

/*
 * Copyright © 2017 Collabora Ltd.
 *
 * This file is part of vkmark.
 *
 * vkmark is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation, either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * vkmark is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with vkmark. If not, see <http://www.gnu.org/licenses/>.
 *
 * Authors:
 *   Alexandros Frantzis <alexandros.frantzis@collabora.com>
 */

#include "default_benchmarks.h"

std::vector<std::string> DefaultBenchmarks::get()
{
    return std::vector<std::string>{
        "vertex",
        "shading:shading=gouraud",
        "shading:shading=blinn-phong-inf",
        "shading:shading=phong",
        "shading:shading=cel",
        "cube",
        "clear"
    };
}

Add cel shading scene to default bencharks


#include "webview.h"

#include <QPaintEvent>

WebView::WebView(QWidget *parent)
    : QWebView(parent)
    , inLoading(false)
{
    connect(this, SIGNAL(loadStarted()), this, SLOT(newPageLoading()));
    connect(this, SIGNAL(loadFinished(bool)), this, SLOT(pageLoaded(bool)));
}

void WebView::paintEvent(QPaintEvent *event)
{
    if (inLoading && loadingTime.elapsed() < 750) {
        QPainter painter(this);
        painter.setBrush(Qt::white);
        painter.setPen(Qt::NoPen);
        foreach (const QRect &rect, event->region().rects()) {
            painter.drawRect(rect);
        }
    } else {
        QWebView::paintEvent(event);
    }
}

void WebView::newPageLoading()
{
    inLoading = true;
    loadingTime.start();
}

void WebView::pageLoaded(bool)
{
    inLoading = false;
    update();
}

#include "webview.h"

#include <QPaintEvent>
#include <QWebFrame>

WebView::WebView(QWidget *parent)
    : QWebView(parent)
    , inLoading(false)
{
    connect(this, SIGNAL(loadStarted()), this, SLOT(newPageLoading()));
    connect(this, SIGNAL(loadFinished(bool)), this, SLOT(pageLoaded(bool)));
    page()->setPreferredContentsSize(QSize(1024, 768));
}

void WebView::paintEvent(QPaintEvent *event)
{
    if (inLoading && loadingTime.elapsed() < 750) {
        QPainter painter(this);
        painter.setBrush(Qt::white);
        painter.setPen(Qt::NoPen);
        foreach (const QRect &rect, event->region().rects()) {
            painter.drawRect(rect);
        }
    } else {
        QWebView::paintEvent(event);
    }
}

void WebView::newPageLoading()
{
    inLoading = true;
    loadingTime.start();
}

void WebView::pageLoaded(bool)
{
    inLoading = false;
    update();
}

Change the prefered content size of the anomaly browser


#include <iostream>
#include <vector>
#include <assert.h>
using namespace std;

class ImageDithering {
public:
  int count(string dithered, vector<string> screen) {
    unsigned d[26];
    for (int i = 0; i < 26; i++) {
      d[i] = 0;
    }
    for (unsigned i = 0; i < dithered.length(); i++) {
      d[dithered[i] - '0'] = 1;
    }
    int count = 0;

    for (vector<string>::iterator str = screen.begin(); str != screen.end(); ++str) {
      for (unsigned i = 0; i < str->length(); i++) {
        count += d[(*str)[i] - '0'];
      }
    }

    return count;
  }
};

int main()
{
  ImageDithering id;
  string sc[] = {
    "AAAAAAAA",
    "ABWBWBWA",
    "AWBWBWBA",
    "ABWBWBWA",
    "AWBWBWBA",
    "AAAAAAAA"
  };
  vector<string> scr1(sc, sc + 6);
  assert( id.count("BW", scr1) == 24);

  return 0;
}

#include <iostream>
#include <vector>
#include <assert.h>
using namespace std;

class ImageDithering {
public:
  int count(string dithered, vector<string> screen) {
    unsigned d[26];
    for (int i = 0; i < 26; i++) {
      d[i] = 0;
    }
    for (unsigned i = 0; i < dithered.length(); i++) {
      d[dithered[i] - 'A'] = 1;
    }
    int count = 0;

    for (vector<string>::iterator str = screen.begin(); str != screen.end(); ++str) {
      for (unsigned i = 0; i < str->length(); i++) {
        count += d[(*str)[i] - 'A'];
      }
    }

    return count;
  }
};

int main()
{
  ImageDithering id;
  string sc1[] = {
    "AAAAAAAA",
    "ABWBWBWA",
    "AWBWBWBA",
    "ABWBWBWA",
    "AWBWBWBA",
    "AAAAAAAA"
  };
  vector<string> scr1(sc1, sc1 + 6);
  assert( id.count("BW", scr1) == 24);

  string sc2[] = {"OT", "QF", "KD", "HR", "VV", "XB"};
  vector<string> scr2(sc2, sc2 + 6);
  assert( id.count("JSPQKYRME", scr2) == 3);
  cout << id.count("JSPQKYRME", scr2);

  return 0;
}

Fix SRM 144, Div 2, Problem ImageDithering


#include <libclientserver.h>

ScopedLock::ScopedLock(Mutex *m) {
    m_mutex = m;
    m_mutex->Lock();
    m_locked = true;
}

ScopedLock::ScopedLock(Mutex *m, std::function<void()> ErrorHandler) :
    m_mutex(m)
{
    if (m->TryLock()) {
        ErrorHandler();
    }
    m_locked = true;
}

ScopedLock::~ScopedLock() {
    if (m_locked)
    {
        m_mutex->Unlock();
        m_locked = false;
    }
}

void ScopedLock::Lock()
{
    if (m_locked)
        abort();
    m_mutex->Lock();
    m_locked = true;
}

void ScopedLock::Unlock()
{
    if (m_locked == false)
        abort();
    m_mutex->Unlock();
    m_locked = false;
}

#include <libclientserver.h>

ScopedLock::ScopedLock(Mutex *m) :
    m_mutex(m)
{
    m_mutex->Lock();
    m_locked = true;
}

ScopedLock::ScopedLock(Mutex *m, std::function<void()> ErrorHandler) :
    m_mutex(m)
{
    if (m->TryLock()) {
        ErrorHandler();
    }
    m_locked = true;
}

ScopedLock::~ScopedLock() {
    if (m_locked)
    {
        m_mutex->Unlock();
        m_locked = false;
    }
}

void ScopedLock::Lock()
{
    if (m_locked)
        abort();
    m_mutex->Lock();
    m_locked = true;
}

void ScopedLock::Unlock()
{
    if (m_locked == false)
        abort();
    m_mutex->Unlock();
    m_locked = false;
}

Move m_mutex to init list


ll rotatingCalipers(){
	int ans = 0;

	int i = 0, j = dn.size()-1;

	while(i < (int)up.size() - 1 || j > 0){
		// Entrou aqui: up[i] e dn[j] eh um antipodal pair
		ans = max(ans, dist2(up[i],dn[j]));

		if(i == (int)up.size()-1) j--;
		else if(j == 0) i++;
		else{
			// Verifica qual o menor angulo a ser rotacionado p utilizar na rotacao
			if(ccw(point(0,0), toVec(up[i], up[i+1]), toVec(dn[j],dn[j-1])))
				i++;
			else
				j--;
		}
	}
	return ans;
}

ll rotatingCalipers(){
	int ans = 0;

	int i = 0, j = dn.size()-1;

	while(i < (int)up.size() - 1 || j > 0){
		// Entrou aqui: up[i] e dn[j] eh um antipodal pair
		ans = max(ans, dist2(up[i],dn[j]));

		if(i == (int)up.size()-1) j--;
		else if(j == 0) i++;
		else{
			// Verifica qual o menor angulo a ser rotacionado p utilizar na rotacao
			if((up[i+1].second - up[i].second) * (dn[j].first - dn[j-1].first)
				> (dn[j].second - dn[j-1].second) * (up[i+1].first - up[i].first ))
				i++;
			else
				j--;
		}
	}
	return ans;
}

Revert "Alterando uma func (usando funcoes do CP3)"


/* mbed Microcontroller Library
 * Copyright (c) 2021 ARM Limited
 * Copyright (c) 2021 Embedded Planet, Inc.
 * SPDX-License-Identifier: Apache-2.0
 *
 * 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 "USBSerial.h"
#include "platform/mbed_retarget.h"

#ifndef MBED_CONF_EP_ATLAS_ENABLE_USB_STDIO_CONSOLE
#define MBED_CONF_EP_ATLAS_ENABLE_USB_STDIO_CONSOLE 0
#endif

#if MBED_CONF_EP_ATLAS_ENABLE_USB_STDIO_CONSOLE

/* Retarget stdio to USBSerial */
mbed::FileHandle *mbed::mbed_target_override_console(int fd)
{
    static USBSerial usb_serial;
    return &usb_serial;
}

#endif

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

#ifndef MBED_CONF_EP_ATLAS_ENABLE_USB_STDIO_CONSOLE
#define MBED_CONF_EP_ATLAS_ENABLE_USB_STDIO_CONSOLE 0
#endif

#if MBED_CONF_EP_ATLAS_ENABLE_USB_STDIO_CONSOLE

#include "USBSerial.h"
#include "platform/mbed_retarget.h"

/* Retarget stdio to USBSerial */
mbed::FileHandle *mbed::mbed_target_override_console(int fd)
{
    static USBSerial usb_serial;
    return &usb_serial;
}

#endif

Remove requirement for USB library if not required


Fix case in name of included header


#include "capu/util/ConsoleLogAppender.h"
#include "capu/util/LogMessage.h"
#include "capu/os/Console.h"
#include <stdio.h>

namespace capu
{
    ConsoleLogAppender::~ConsoleLogAppender()
    {
    }

    void ConsoleLogAppender::logMessage(const LogMessage& logMessage)
    {
        m_logMutex.lock();

        switch(logMessage.getLogLevel())
        {
        case LL_TRACE:
            Console::Print(Console::WHITE, "[  Trace  ] ");
            break;
        default:
        case LL_DEBUG :
            Console::Print(Console::WHITE, "[  Debug  ] ");
            break;
        case LL_INFO :
            Console::Print(Console::GREEN, "[  Info   ] ");
            break;
        case LL_WARN :
            Console::Print(Console::YELLOW, "[  Warn   ] ");
            break;
        case LL_ERROR :
            Console::Print(Console::RED, "[  Error  ] ");
            break;
        case LL_FATAL :
            Console::Print(Console::RED, "[  Fatal  ] ");
            break;
        }

        Console::Print(Console::AQUA, logMessage.getContext().getContextName().c_str());
        Console::Print(" | %s\n", logMessage.getLogMessage());
        Console::Flush();
        m_logMutex.unlock();
    }
}

#include "capu/util/ConsoleLogAppender.h"
#include "capu/util/LogMessage.h"
#include "capu/os/Console.h"
#include "capu/os/Time.h"
#include <stdio.h>

namespace capu
{
    ConsoleLogAppender::~ConsoleLogAppender()
    {
    }

    void ConsoleLogAppender::logMessage(const LogMessage& logMessage)
    {
        m_logMutex.lock();

        const uint64_t now = Time::GetMilliseconds();
        Console::Print(Console::WHITE, "%.3f ", now/1000.0);

        switch(logMessage.getLogLevel())
        {
        case LL_TRACE:
            Console::Print(Console::WHITE, "[  Trace  ] ");
            break;
        default:
        case LL_DEBUG :
            Console::Print(Console::WHITE, "[  Debug  ] ");
            break;
        case LL_INFO :
            Console::Print(Console::GREEN, "[  Info   ] ");
            break;
        case LL_WARN :
            Console::Print(Console::YELLOW, "[  Warn   ] ");
            break;
        case LL_ERROR :
            Console::Print(Console::RED, "[  Error  ] ");
            break;
        case LL_FATAL :
            Console::Print(Console::RED, "[  Fatal  ] ");
            break;
        }

        Console::Print(Console::AQUA, logMessage.getContext().getContextName().c_str());
        Console::Print(" | %s\n", logMessage.getLogMessage());
        Console::Flush();
        m_logMutex.unlock();
    }
}

Add timestamp to console log output


#include <cstdint>

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

#include "utils.cc"

#define FUZZ_ENCODER_STRING_LITERAL_X(name) FUZZ_ENCODER_STRING_LITERAL(name)
#define FUZZ_ENCODER_STRING_LITERAL(name) #name
#ifndef FUZZ_ENCODER
#define FUZZ_ENCODER FUZZ_ENCODER_STRING_LITERAL_X(FUZZ_IMAGEMAGICK_ENCODER)
#endif

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

#if FUZZ_IMAGEMAGICK_ENCODER_WRITE || BUILD_MAIN

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

#include "travis.cc"

#include <cstdint>

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

#include "utils.cc"

#define FUZZ_ENCODER_STRING_LITERAL_X(name) FUZZ_ENCODER_STRING_LITERAL(name)
#define FUZZ_ENCODER_STRING_LITERAL(name) #name
#ifndef FUZZ_ENCODER
#define FUZZ_ENCODER FUZZ_ENCODER_STRING_LITERAL_X(FUZZ_IMAGEMAGICK_ENCODER)
#endif

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
  std::string encoder = FUZZ_ENCODER;
  // Due to macro foolishness, if we pass -DFUZZ_IMAGEMAGICK_ENCODER=NULL,
  // FUZZ_ENCODER ends up being "__null".
  if (encoder == "__null") {
    encoder = "NULL";
  }

  const Magick::Blob blob(Data, Size);
  Magick::Image image;
  image.magick(encoder);
  image.fileName(std::string(encoder) + ":");
  try {
    image.read(blob);
  }
  catch (Magick::Exception &e) {
    return 0;
  }

#if FUZZ_IMAGEMAGICK_ENCODER_WRITE || BUILD_MAIN

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

#include "travis.cc"

Handle the null encoder properly in the encoder fuzz


#include <stdio.h>

#include "../excercise04/make_random_data/make_random_data.hpp"
#include "../excercise04/sort/quicksort.hpp"

int get_index_smallest(const int k, int *data, const int start, const int end)
{
    if(k < 0 || k > end) return -1; /* Base case */
    int p = partition(data, start, end);

    if(k == 0) return data[start];
    else if(p - start == k) return data[p];
    else if(p - start > k) return get_index_smallest(k, data, start, p - 1);
    else return get_index_smallest(k - p - 1, data, p + 1, end);
}

int main(void)
{
    int k;
    printf("Enter k= ");
    scanf("%d", &k);

    const int size = 100000;
    int *data = make_random_data(size);
    printf("%d\n", get_index_smallest(k, data, 0, size - 1));

    free_random_data(data);
    return 0;
}

#include <stdio.h>

#include "../excercise04/make_random_data/make_random_data.hpp"
#include "../excercise04/sort/quicksort.hpp"

int quickselection(const int k, int *data, const int start, const int end)
{
    if(start >= end) return data[start];
    int pivot = partition(data, start, end);

    int p = pivot - start;
    if(p > k - 1) return quickselection(k, data, start, pivot - 1);
    if(p < k - 1) return quickselection(k - (p + 1), data, pivot + 1, end);
    return data[pivot];
}

int main(void)
{
    const int size = 100000;
    int *data = make_random_data(size);

    int k;
    printf("Enter k= ");
    scanf("%d", &k);

    if(k <= 0 || k > size)
    {
        printf("Error: Out of range.\n");
        return 1;
    }

    printf("%d\n", quickselection(k, data, 0, size - 1));

    free_random_data(data);
    return 0;
}

Change the entire logic of Quickselect


/*
 *  Copyright (c) 2020 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 "test/testsupport/perf_test_histogram_writer.h"

namespace webrtc {
namespace test {

PerfTestResultWriter* CreateHistogramWriter() {
  RTC_NOTREACHED() << "Cannot run perf tests with rtc_enable_protobuf = false. "
                      "Perf write results as protobufs.";
}

}  // namespace test
}  // namespace webrtc

/*
 *  Copyright (c) 2020 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 "test/testsupport/perf_test_histogram_writer.h"

namespace webrtc {
namespace test {

PerfTestResultWriter* CreateHistogramWriter() {
  RTC_NOTREACHED() << "Cannot run perf tests with rtc_enable_protobuf = false. "
                      "Perf write results as protobufs.";
  return nullptr;
}

}  // namespace test
}  // namespace webrtc

Fix compile error when rtc_enable_protobuf is false


#include "findTypeVariables.h"
#include "type.h"
#include "symbol.h"
#include "symtab.h"

FindVariableType::FindVariableType(Vec<VariableType*>* init_variableTypes) {
  variableTypes = init_variableTypes;
}

void FindVariableType::preProcessSymbol(Symbol* symbol) {
  if (dynamic_cast<TypeSymbol*>(symbol)) {
    forv_Vec(VariableType, variableType, *variableTypes) {
      if (variableType == symbol->type) {
        found = true;
      }
    }
  }
}

void FindVariableType::preProcessType(Type* type) {
  if (dynamic_cast<VariableType*>(type)) {
    forv_Vec(VariableType, variableType, *variableTypes) {
      if (variableType == type) {
        found = true;
      }
    }
  }
}

bool functionContainsVariableType(FnSymbol* fn,
                                  Vec<VariableType*>* variableTypes) {
  FindVariableType* traversal = new FindVariableType(variableTypes);
  TRAVERSE(fn, traversal, true);
  return traversal->found;
}

#include "findTypeVariables.h"
#include "type.h"
#include "symbol.h"
#include "symtab.h"

FindVariableType::FindVariableType(Vec<VariableType*>* init_variableTypes) {
  found = false;
  variableTypes = init_variableTypes;
}

void FindVariableType::preProcessSymbol(Symbol* symbol) {
  if (dynamic_cast<TypeSymbol*>(symbol)) {
    forv_Vec(VariableType, variableType, *variableTypes) {
      if (variableType == symbol->type) {
        found = true;
      }
    }
  }
}

void FindVariableType::preProcessType(Type* type) {
  if (dynamic_cast<VariableType*>(type)) {
    forv_Vec(VariableType, variableType, *variableTypes) {
      if (variableType == type) {
        found = true;
      }
    }
  }
}

bool functionContainsVariableType(FnSymbol* fn,
                                  Vec<VariableType*>* variableTypes) {
  FindVariableType* traversal = new FindVariableType(variableTypes);
  TRAVERSE(fn, traversal, true);
  return traversal->found;
}

Fix uninitialized variable which was causing valgrind failures. (the "found" variable was not initialised to "false").


#include "./SDACalculatePositions.h"

SDACalculatePositions::SDACalculatePositions(const char* name, const char* title,
               const char* in_file_suffix, const char* out_file_suffix, const double threshold,
	       const double positionCut)
: JPetCommonAnalysisModule( name, title, in_file_suffix, out_file_suffix), fCut(positionCut)
{
        fSelectedThreshold = threshold;
}

SDACalculatePositions::~SDACalculatePositions(){}

void SDACalculatePositions::begin()
{
}

void SDACalculatePositions::exec()
{
        fReader->getEntry(fEvent);

        JPetLOR& fLOR = dynamic_cast< JPetLOR& > ( fReader->getData() );

        JPetHit hit = fLOR.getFirstHit();
        hit.setPosAlongStrip( hit.getTimeDiff()/2.0 * 12.6/1000.0  );
        fLOR.setFirstHit( hit );

        hit = fLOR.getSecondHit();
        hit.setPosAlongStrip( hit.getTimeDiff()/2.0 * 12.6/1000.0  );
        fLOR.setSecondHit( hit );

	if( fLOR.getFirstHit().getPosAlongStrip() > fCut )
	{
	  fEvent++;
	  return;
	}

	fWriter->write(fLOR);

        fEvent++;
}

void SDACalculatePositions::end()
{
}

#include "./SDACalculatePositions.h"

SDACalculatePositions::SDACalculatePositions(const char* name, const char* title,
               const char* in_file_suffix, const char* out_file_suffix, const double threshold,
	       const double positionCut)
: JPetCommonAnalysisModule( name, title, in_file_suffix, out_file_suffix), fCut(positionCut)
{
        fSelectedThreshold = threshold;
}

SDACalculatePositions::~SDACalculatePositions(){}

void SDACalculatePositions::begin()
{
}

void SDACalculatePositions::exec()
{
        fReader->getEntry(fEvent);

        JPetLOR& fLOR = dynamic_cast< JPetLOR& > ( fReader->getData() );

        JPetHit hit = fLOR.getFirstHit();
        hit.setPosAlongStrip( hit.getTimeDiff()/2.0 * 12.6/1000.0  );
        fLOR.setFirstHit( hit );

        hit = fLOR.getSecondHit();
        hit.setPosAlongStrip( hit.getTimeDiff()/2.0 * 12.6/1000.0  );
        fLOR.setSecondHit( hit );

	if( fabs(fLOR.getFirstHit().getPosAlongStrip()) > fCut && fabs(fLOR.getSecondHit().getPosAlongStrip()) > fCut )
	{
	  fEvent++;
	  return;
	}

	fWriter->write(fLOR);

        fEvent++;
}

void SDACalculatePositions::end()
{
}

Add proper cut on position


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

#include "browser/browser_main_parts.h"

#include "browser/browser_context.h"
#include "browser/web_ui_controller_factory.h"
#include "net/proxy/proxy_resolver_v8.h"

namespace brightray {

BrowserMainParts::BrowserMainParts() {
}

BrowserMainParts::~BrowserMainParts() {
}

void BrowserMainParts::PreMainMessageLoopRun() {
  browser_context_.reset(CreateBrowserContext());
  browser_context_->Initialize();

  web_ui_controller_factory_.reset(
      new WebUIControllerFactory(browser_context_.get()));
  content::WebUIControllerFactory::RegisterFactory(
      web_ui_controller_factory_.get());
}

void BrowserMainParts::PostMainMessageLoopRun() {
  browser_context_.reset();
}

int BrowserMainParts::PreCreateThreads() {
#if defined(OS_WIN)
  net::ProxyResolverV8::CreateIsolate();
#else
  net::ProxyResolverV8::RememberDefaultIsolate();
#endif
  return 0;
}

BrowserContext* BrowserMainParts::CreateBrowserContext() {
  return new BrowserContext;
}

}  // namespace brightray

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

#include "browser/browser_main_parts.h"

#include "browser/browser_context.h"
#include "browser/web_ui_controller_factory.h"
#include "net/proxy/proxy_resolver_v8.h"
#include "ui/gfx/screen.h"
#include "ui/views/widget/desktop_aura/desktop_screen.h"

namespace brightray {

BrowserMainParts::BrowserMainParts() {
}

BrowserMainParts::~BrowserMainParts() {
}

void BrowserMainParts::PreMainMessageLoopRun() {
  browser_context_.reset(CreateBrowserContext());
  browser_context_->Initialize();

  web_ui_controller_factory_.reset(
      new WebUIControllerFactory(browser_context_.get()));
  content::WebUIControllerFactory::RegisterFactory(
      web_ui_controller_factory_.get());

#if defined(OS_WIN)
  gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE, views::CreateDesktopScreen());
#endif
}

void BrowserMainParts::PostMainMessageLoopRun() {
  browser_context_.reset();
}

int BrowserMainParts::PreCreateThreads() {
#if defined(OS_WIN)
  net::ProxyResolverV8::CreateIsolate();
#else
  net::ProxyResolverV8::RememberDefaultIsolate();
#endif
  return 0;
}

BrowserContext* BrowserMainParts::CreateBrowserContext() {
  return new BrowserContext;
}

}  // namespace brightray

Set up a native screen on Windows


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

// UNSUPPORTED: c++98, c++03, c++11, c++14

// aligned allocation functions are not provided prior to macosx10.13
// XFAIL: availability=macosx10.12
// XFAIL: availability=macosx10.11
// XFAIL: availability=macosx10.10
// XFAIL: availability=macosx10.9
// XFAIL: availability=macosx10.8
// XFAIL: availability=macosx10.7

#include <new>

#ifdef _LIBCPP_HAS_NO_ALIGNED_ALLOCATION
#   error "libc++ should have aligned allocation in C++17 and up when targeting a platform that supports it"
#endif

int main() { }

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

// UNSUPPORTED: c++98, c++03, c++11, c++14

// Aligned allocation functions are not provided prior to macosx10.13, but
// AppleClang <= 10 does not know about this restriction and always enables them.
// XFAIL: !(apple-clang-9 || apple-clang-10) && availability=macosx10.12
// XFAIL: !(apple-clang-9 || apple-clang-10) && availability=macosx10.11
// XFAIL: !(apple-clang-9 || apple-clang-10) && availability=macosx10.10
// XFAIL: !(apple-clang-9 || apple-clang-10) && availability=macosx10.9
// XFAIL: !(apple-clang-9 || apple-clang-10) && availability=macosx10.8
// XFAIL: !(apple-clang-9 || apple-clang-10) && availability=macosx10.7

#include <new>

#ifdef _LIBCPP_HAS_NO_ALIGNED_ALLOCATION
#   error "libc++ should have aligned allocation in C++17 and up when targeting a platform that supports it"
#endif

int main() { }

Handle AppleClang 9 and 10 in XFAILs for aligned allocation tests


#include "generator.h"

#include <iostream>
#include <fstream>

using namespace Mugen;

CharacterGenerator::CharacterGenerator(const std::string & filename):
filename(filename){
}

CharacterGenerator::~CharacterGenerator(){
}

void CharacterGenerator::output(const std::string & file){
    Mugen::PythonStream out;
    out.open(file);
    out << "import mugen" << PythonStream::endl;
    out <<  "class TestCharacter(mugen.Character):" << PythonStream::endl;
    out << PythonStream::indent;
    out << "def __init__(self):" << PythonStream::endl;
    out << PythonStream::indent;
    out << "self.setName('TestCharacter')" << PythonStream::endl;
    out.clearIndents();
    out << "char = TestCharacter()" << PythonStream::endl;
    out << "print char.name" << PythonStream::endl;
    out.close();
}

Indent code to more or less visualize the indentation of the outputed python code.


// Copyright 2019 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 "quic/masque/masque_utils.h"

namespace quic {

ParsedQuicVersionVector MasqueSupportedVersions() {
  QuicVersionInitializeSupportForIetfDraft();
  ParsedQuicVersion version = UnsupportedQuicVersion();
  for (const ParsedQuicVersion& vers : AllSupportedVersions()) {
    // Find the first version that supports IETF QUIC.
    if (vers.HasIetfQuicFrames() && vers.UsesTls()) {
      version = vers;
      break;
    }
  }
  QUICHE_CHECK(version.IsKnown());
  QuicEnableVersion(version);
  return {version};
}

QuicConfig MasqueEncapsulatedConfig() {
  QuicConfig config;
  config.SetMaxPacketSizeToSend(kMasqueMaxEncapsulatedPacketSize);
  return config;
}

std::string MasqueModeToString(MasqueMode masque_mode) {
  switch (masque_mode) {
    case MasqueMode::kInvalid:
      return "Invalid";
    case MasqueMode::kLegacy:
      return "Legacy";
    case MasqueMode::kOpen:
      return "Open";
  }
  return absl::StrCat("Unknown(", static_cast<int>(masque_mode), ")");
}

std::ostream& operator<<(std::ostream& os, const MasqueMode& masque_mode) {
  os << MasqueModeToString(masque_mode);
  return os;
}

}  // namespace quic

// Copyright 2019 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 "quic/masque/masque_utils.h"

namespace quic {

ParsedQuicVersionVector MasqueSupportedVersions() {
  QuicVersionInitializeSupportForIetfDraft();
  ParsedQuicVersionVector versions;
  for (const ParsedQuicVersion& version : AllSupportedVersions()) {
    // Use all versions that support IETF QUIC.
    if (version.UsesHttp3()) {
      QuicEnableVersion(version);
      versions.push_back(version);
    }
  }
  QUICHE_CHECK(!versions.empty());
  return versions;
}

QuicConfig MasqueEncapsulatedConfig() {
  QuicConfig config;
  config.SetMaxPacketSizeToSend(kMasqueMaxEncapsulatedPacketSize);
  return config;
}

std::string MasqueModeToString(MasqueMode masque_mode) {
  switch (masque_mode) {
    case MasqueMode::kInvalid:
      return "Invalid";
    case MasqueMode::kLegacy:
      return "Legacy";
    case MasqueMode::kOpen:
      return "Open";
  }
  return absl::StrCat("Unknown(", static_cast<int>(masque_mode), ")");
}

std::ostream& operator<<(std::ostream& os, const MasqueMode& masque_mode) {
  os << MasqueModeToString(masque_mode);
  return os;
}

}  // namespace quic

Support all HTTP/3 versions in MASQUE


// RUN: %clang_cc1 -pedantic -fixit %s -o - | %clang_cc1 -fsyntax-only -pedantic -Werror -x c++ -

/* This is a test of the various code modification hints that are
   provided as part of warning or extension diagnostics. All of the
   warnings will be fixed by -fixit, and the resulting file should
   compile cleanly with -Werror -pedantic. */

struct C1 {
  virtual void f();
  static void g();
};
struct C2 : virtual public virtual C1 { }; // expected-error{{duplicate}}

virtual void C1::f() { } // expected-error{{'virtual' can only be specified inside the class definition}}

static void C1::g() { } // expected-error{{'static' can only be specified inside the class definition}}

template<int Value> struct CT { }; // expected-note{{previous use is here}}

CT<10 >> 2> ct; // expected-warning{{require parentheses}}

class C3 {
public:
  C3(C3, int i = 0); // expected-error{{copy constructor must pass its first argument by reference}}
};

struct CT<0> { }; // expected-error{{'template<>'}}

template<> class CT<1> { }; // expected-error{{tag type}}

// PR5444
namespace PR5444 {
  void foo(int x, int y = 0);
  void foo(int x, int y = 0) { }

  void foo(int  = 0);
  void foo(int  = 0) { }
}

// RUN: %clang_cc1 -pedantic -Wall -fixit %s -o - | %clang_cc1 -fsyntax-only -pedantic -Wall -Werror -x c++ -

/* This is a test of the various code modification hints that are
   provided as part of warning or extension diagnostics. All of the
   warnings will be fixed by -fixit, and the resulting file should
   compile cleanly with -Werror -pedantic. */

struct C1 {
  virtual void f();
  static void g();
};
struct C2 : virtual public virtual C1 { }; // expected-error{{duplicate}}

virtual void C1::f() { } // expected-error{{'virtual' can only be specified inside the class definition}}

static void C1::g() { } // expected-error{{'static' can only be specified inside the class definition}}

template<int Value> struct CT { }; // expected-note{{previous use is here}}

CT<10 >> 2> ct; // expected-warning{{require parentheses}}

class C3 {
public:
  C3(C3, int i = 0); // expected-error{{copy constructor must pass its first argument by reference}}
};

struct CT<0> { }; // expected-error{{'template<>'}}

template<> class CT<1> { }; // expected-error{{tag type}}

// Access declarations
class A {
protected:
  int foo();
};

class B : public A {
  A::foo; // expected-warning{{access declarations are deprecated}}
};

Make this fix-it test case actually fail when there is a problem; add a test for access declarations and remove a (broken) test for removal of default arguments.


#include<ros/ros.h>
#include<ics3/ics>
#include<servo_msgs/IdBased.h>

ics::ICS3* driver {nullptr};
ros::Publisher pub;

void move(const servo_msgs::IdBased::ConstPtr& msg) {
  servo_msgs::IdBased result;
  result.id = msg->id;
  try {
    result.angle = driver->move(msg->id, ics::Angle::newDegree(msg->angle));
    pub.publish(result);
  } catch (std::runtime_error e) {
    ROS_INFO("Communicate error: %s", e.what());
  }
}

int main(int argc, char** argv) {
  ros::init(argc, argv, "servo_krs_node");
  ros::NodeHandle n {};
  ros::NodeHandle pn {"~"};
  std::string path {"/dev/ttyUSB0"};
  pn.param<std::string>("path", path, path);
  ics::ICS3 ics {path.c_str()};
  driver = &ics;
  ros::Subscriber sub = n.subscribe("cmd_krs", 100, move);
  pub = n.advertise<servo_msgs::IdBased>("pose_krs", 10);
  ros::spin();
  return 0;
}

#include<ros/ros.h>
#include<servo_msgs/IdBased.h>
#include<ics3/ics>

ics::ICS3* driver {nullptr};
ros::Publisher pub;

void move(const servo_msgs::IdBased::ConstPtr& msg) {
  servo_msgs::IdBased result;
  result.id = msg->id;
  try {
    result.angle = driver->move(msg->id, ics::Angle::newDegree(msg->angle));
    pub.publish(result);
  } catch (std::runtime_error e) {
    ROS_INFO("Communicate error: %s", e.what());
  }
}

int main(int argc, char** argv) {
  ros::init(argc, argv, "servo_krs_node");
  ros::NodeHandle pn {"~"};
  std::string path {"/dev/ttyUSB0"};
  pn.param<std::string>("path", path, path);
  ics::ICS3 ics {std::move(path)};
  driver = &ics;
  ros::NodeHandle n {};
  ros::Subscriber sub {n.subscribe("cmd_krs", 100, move)};
  pub = n.advertise<servo_msgs::IdBased>("pose_krs", 10);
  ros::spin();
  return 0;
}

Update servo_krs for runtime speed


// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "WatermarkDataFactory.h"

namespace ExampleApp
{
    namespace Watermark
    {
        namespace View
        {
            WatermarkDataFactory::WatermarkDataFactory(const std::string& appName,
                                                       const std::string& googleAnalyticsReferrerToken)
            : m_appName(appName)
            , m_googleAnalyticsReferrerToken(googleAnalyticsReferrerToken)
            {

            }

            WatermarkData WatermarkDataFactory::Create(const std::string& imageAssetUrl,
                                                       const std::string& popupTitle,
                                                       const std::string& popupBody,
                                                       const std::string& webUrl,
                                                       const bool shouldShowShadow)
            {
                return WatermarkData(imageAssetUrl,
                                     popupTitle,
                                     popupBody,
                                     webUrl,
                                     shouldShowShadow);
            }

            WatermarkData WatermarkDataFactory::CreateDefaultEegeo()
            {
                std::string imageAssetName = "eegeo_logo";
                std::string popupTitle = "Maps by eeGeo";
                std::string popupBody = "The " + m_appName + " app is open source. It's built using the eeGeo maps SDK, a cross platform API for building engaging, customizable apps.";
                std::string webUrl = "http://eegeo.com/?utm_source=" + m_googleAnalyticsReferrerToken + "&utm_medium=referral&utm_campaign=eegeo";

                return Create(imageAssetName,
                              popupTitle,
                              popupBody,
                              webUrl);
            }
        }
    }
}

// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "WatermarkDataFactory.h"

namespace ExampleApp
{
    namespace Watermark
    {
        namespace View
        {
            WatermarkDataFactory::WatermarkDataFactory(const std::string& appName,
                                                       const std::string& googleAnalyticsReferrerToken)
            : m_appName(appName)
            , m_googleAnalyticsReferrerToken(googleAnalyticsReferrerToken)
            {

            }

            WatermarkData WatermarkDataFactory::Create(const std::string& imageAssetUrl,
                                                       const std::string& popupTitle,
                                                       const std::string& popupBody,
                                                       const std::string& webUrl,
                                                       const bool shouldShowShadow)
            {
                return WatermarkData(imageAssetUrl,
                                     popupTitle,
                                     popupBody,
                                     webUrl,
                                     shouldShowShadow);
            }

            WatermarkData WatermarkDataFactory::CreateDefaultEegeo()
            {
                std::string imageAssetName = "eegeo_logo";
                std::string popupTitle = "Maps by eeGeo";
                std::string popupBody = "This app is open source. It's built using the eeGeo maps SDK, a cross platform API for building engaging, customizable apps.";
                std::string webUrl = "http://eegeo.com/?utm_source=" + m_googleAnalyticsReferrerToken + "&utm_medium=referral&utm_campaign=eegeo";

                return Create(imageAssetName,
                              popupTitle,
                              popupBody,
                              webUrl);
            }
        }
    }
}

Fix for MPLY-7058. Buddy: Paul


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

#include "chrome/browser/app_modal_dialog_queue.h"

#include "chrome/browser/browser_list.h"

void AppModalDialogQueue::AddDialog(AppModalDialog* dialog) {
  if (!active_dialog_) {
    ShowModalDialog(dialog);
    return;
  }
  app_modal_dialog_queue_.push(dialog);
}

void AppModalDialogQueue::ShowNextDialog() {
  if (!app_modal_dialog_queue_.empty()) {
    AppModalDialog* dialog = app_modal_dialog_queue_.front();
    app_modal_dialog_queue_.pop();
    ShowModalDialog(dialog);
  } else {
    active_dialog_ = NULL;
  }
}

void AppModalDialogQueue::ActivateModalDialog() {
  if (active_dialog_)
    active_dialog_->ActivateModalDialog();
}

void AppModalDialogQueue::ShowModalDialog(AppModalDialog* dialog) {
  dialog->ShowModalDialog();
  active_dialog_ = dialog;
}

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

#include "chrome/browser/app_modal_dialog_queue.h"

#include "chrome/browser/browser_list.h"

void AppModalDialogQueue::AddDialog(AppModalDialog* dialog) {
  if (!active_dialog_) {
    ShowModalDialog(dialog);
    return;
  }
  app_modal_dialog_queue_.push(dialog);
}

void AppModalDialogQueue::ShowNextDialog() {
  if (!app_modal_dialog_queue_.empty()) {
    AppModalDialog* dialog = app_modal_dialog_queue_.front();
    app_modal_dialog_queue_.pop();
    ShowModalDialog(dialog);
  } else {
    active_dialog_ = NULL;
  }
}

void AppModalDialogQueue::ActivateModalDialog() {
  if (active_dialog_)
    active_dialog_->ActivateModalDialog();
}

void AppModalDialogQueue::ShowModalDialog(AppModalDialog* dialog) {
  // Set active_dialog_ before showing it, because ShowModalDialog can wind up
  // calling ShowNextDialog in some cases, which will change active_dialog_.
  active_dialog_ = dialog;
  dialog->ShowModalDialog();
}

Set active_dialog_ before showing it, since showing a dialog can sometimes actually move to the next one in the queue instead.


#include<ros/ros.h>
#include<servo_msgs/IdBased.h>
#include<ics3/ics>

ics::ICS3* driver {nullptr};
ros::Publisher pub;

void move(const servo_msgs::IdBased::ConstPtr& msg) {
  servo_msgs::IdBased result;
  try {
    result.angle = driver->move(msg->id, ics::Angle::newDegree(msg->angle));
    result.id = msg->id;
    pub.publish(result);
  } catch (std::runtime_error e) {
    ROS_INFO("Communicate error: %s", e.what());
  }
}

int main(int argc, char** argv) {
  ros::init(argc, argv, "servo_krs_node");
  ros::NodeHandle pn {"~"};
  std::string path {"/dev/ttyUSB0"};
  pn.param<std::string>("path", path, path);
  ics::ICS3 ics {std::move(path)};
  driver = &ics;
  ros::NodeHandle n {};
  ros::Subscriber sub {n.subscribe("cmd_krs", 100, move)};
  pub = n.advertise<servo_msgs::IdBased>("pose_krs", 10);
  ros::spin();
  return 0;
}

#include<ros/ros.h>
#include<servo_msgs/IdBased.h>
#include<ics3/ics>

ics::ICS3* driver {nullptr};
ros::Publisher pub;

void move(const servo_msgs::IdBased::ConstPtr& msg) {
  servo_msgs::IdBased result;
  try {
    result.angle = driver->move(msg->id, ics::Angle::newDegree(msg->angle));
    result.id = msg->id;
    pub.publish(result);
  } catch (std::runtime_error e) {
    ROS_INFO("Communicate error: %s", e.what());
  }
}

int main(int argc, char** argv) {
  ros::init(argc, argv, "servo_krs_node");
  ros::NodeHandle pn {"~"};
  std::string path {"/dev/ttyUSB0"};
  pn.param<std::string>("path", path, path);
  ROS_INFO("Open servo motor path: %s", path.c_str());
  ics::ICS3 ics {std::move(path)};
  driver = &ics;
  ros::NodeHandle n {};
  ros::Subscriber sub {n.subscribe("cmd_krs", 100, move)};
  pub = n.advertise<servo_msgs::IdBased>("pose_krs", 10);
  ros::spin();
  return 0;
}

Add message of reading path


/**
 * Appcelerator Titanium - licensed under the Apache Public License 2
 * see LICENSE in the root folder for details on the license.
 * Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.
 */

#include <kroll/kroll.h>
#include "../app_binding.h"

namespace ti
{

void AppBinding::Restart(const ValueList& args, KValueRef result)
{
	Host* host = Host::GetInstance();
	std::string cmdline(host->GetApplication()->arguments.at(0));

	// Remove all quotes.
	size_t i = cmdline.find('\"');
	while (i != std::string::npos)
	{
		cmdline.replace(i, 1, "");
		i = cmdline.find('\"');
	}

	std::string script = "\"" + cmdline + "\" &";
	system(script.c_str());

	host->Exit(0);
}

}

/**
 * Appcelerator Titanium - licensed under the Apache Public License 2
 * see LICENSE in the root folder for details on the license.
 * Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.
 */

#include <kroll/kroll.h>
#include "../app_binding.h"

namespace ti
{

void AppBinding::Restart(const ValueList& args, KValueRef result)
{
	Host* host = Host::GetInstance();
	std::string cmdline(host->GetApplication()->arguments.at(0));

	// Remove all quotes.
	size_t i = cmdline.find('\"');
	while (i != std::string::npos)
	{
		cmdline.replace(i, 1, "");
		i = cmdline.find('\"');
	}

	std::string script = "\"" + cmdline + "\" &";
	if (system(script.c_str()) == -1)
		throw ValueException::FromString("Failed to start new process.");

	host->Exit(0);
}

}

Throw an exception when App.restart fails on Linux.


#include <wangle/client/persistence/test/TestUtil.h>

namespace wangle {

std::string getPersistentCacheFilename() {
  char filename[] = "/tmp/fbtls.XXXXXX";
  int fd = mkstemp(filename);
  close(fd);
  EXPECT_TRUE(unlink(filename) != -1);
  return std::string(filename);
}

}

/*
 *  Copyright (c) 2016, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */
#include <wangle/client/persistence/test/TestUtil.h>

#include <folly/experimental/TestUtil.h>

namespace wangle {

std::string getPersistentCacheFilename() {
  folly::test::TemporaryFile file("fbtls");
  return file.path().string();
}

}

Handle tmp dir on Android


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

#include "base/thread_local.h"

#include <pthread.h>

#include "base/logging.h"

namespace base {

// static
void ThreadLocalPlatform::AllocateSlot(SlotType& slot) {
  int error = pthread_key_create(&slot, NULL);
  CHECK(error == 0);
}

// static
void ThreadLocalPlatform::FreeSlot(SlotType& slot) {
  int error = pthread_key_delete(slot);
  DCHECK(error == 0);
}

// static
void* ThreadLocalPlatform::GetValueFromSlot(SlotType& slot) {
  return pthread_getspecific(slot_);
}

// static
void ThreadLocalPlatform::SetValueInSlot(SlotType& slot, void* value) {
  int error = pthread_setspecific(slot, value);
  CHECK(error == 0);
}

}  // namespace base

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

#include "base/thread_local.h"

#include <pthread.h>

#include "base/logging.h"

namespace base {

// static
void ThreadLocalPlatform::AllocateSlot(SlotType& slot) {
  int error = pthread_key_create(&slot, NULL);
  CHECK(error == 0);
}

// static
void ThreadLocalPlatform::FreeSlot(SlotType& slot) {
  int error = pthread_key_delete(slot);
  DCHECK(error == 0);
}

// static
void* ThreadLocalPlatform::GetValueFromSlot(SlotType& slot) {
  return pthread_getspecific(slot);
}

// static
void ThreadLocalPlatform::SetValueInSlot(SlotType& slot, void* value) {
  int error = pthread_setspecific(slot, value);
  CHECK(error == 0);
}

}  // namespace base

Fix a typo that broke the posix build.


#include <kernel/rng.hpp>
#include <kernel/cpuid.hpp>
#include <kernel/os.hpp>
#include <arch.hpp>
#include <kprint>
extern "C" void intel_rdrand(uint64_t*);
extern "C" void intel_rdseed(uint64_t*);

static void fallback_entropy(uint64_t* res)
{
  uint64_t clock = (uint64_t) res;
  // this is horrible, better solution needed here
  for (int i = 0; i < 64; ++i) {
    clock += OS::cycles_since_boot();
    asm volatile("cpuid" ::: "memory", "eax", "ebx", "ecx", "edx");
  }
  // here we need to add our own bits
  *res = clock;
}

// used to generate initial
// entropy for a cryptographic randomness generator
void RNG::init()
{
  if (CPUID::has_feature(CPUID::Feature::RDSEED)) {
    rng_reseed_init(intel_rdseed, 2);
  }
  else if (CPUID::has_feature(CPUID::Feature::RDRAND)) {
    rng_reseed_init(intel_rdrand, 65);
  }
  else {
    rng_reseed_init(fallback_entropy, 64*16);
    return;
  }
  assert(0 && "No randomness fallback");
}

#include <kernel/rng.hpp>
#include <kernel/cpuid.hpp>
#include <kernel/os.hpp>
#include <arch.hpp>
#include <kprint>
extern "C" void intel_rdrand(uint64_t*);
extern "C" void intel_rdseed(uint64_t*);

static void fallback_entropy(uint64_t* res)
{
  uint64_t clock = (uint64_t) res;
  // this is horrible, better solution needed here
  for (int i = 0; i < 64; ++i) {
    clock += OS::cycles_since_boot();
    asm volatile("cpuid" ::: "memory", "eax", "ebx", "ecx", "edx");
  }
  // here we need to add our own bits
  *res = clock;
}

// used to generate initial
// entropy for a cryptographic randomness generator
void RNG::init()
{
  if (CPUID::has_feature(CPUID::Feature::RDSEED)) {
    rng_reseed_init(intel_rdseed, 2);
    return;
  }
  else if (CPUID::has_feature(CPUID::Feature::RDRAND)) {
    rng_reseed_init(intel_rdrand, 65);
    return;
  }
#ifndef PLATFORM_x86_solo5
  rng_reseed_init(fallback_entropy, 64*16);
  return;
#endif
  assert(0 && "No randomness fallback");
}

Add missing returns in RNG init, and fail avoid TSC with solo5


// RUN: clang -fsyntax-only -verify %s
namespace A { // expected-error {{error: previous definition is here}}
  int A;
  void f() { A = 0; }
}

void f() { A = 0; } // expected-error {{error: unexpected namespace name 'A': expected expression}}
int A; // expected-error {{error: redefinition of 'A' as different kind of symbol}}
class A; // expected-error {{error: redefinition of 'A' as different kind of symbol}}

class B; // expected-error {{error: previous definition is here}}
namespace B {} // expected-error {{error: redefinition of 'B' as different kind of symbol}}

void C(); // expected-error {{error: previous definition is here}}
namespace C {} // expected-error {{error: redefinition of 'C' as different kind of symbol}}

Convert CFLF to LF. CRLF was causing this test to fail under Mac OS X.


#include <unistd.h>
#include <gtest/gtest.h>
#include "getusername.h"

TEST(GetUserName,simple)
{
	// allocate a WCHAR_T buffer to receive username
	DWORD lpnSize = 64;
	WCHAR_T lpBuffer[lpnSize];

	BOOL result = GetUserName(lpBuffer, &lpnSize);

	// GetUserName returns 1 on success
	ASSERT_EQ(1, result);

	// get expected username
	const char *username = getlogin();

	// GetUserName sets lpnSize to length of username including null
	ASSERT_EQ(strlen(username)+1, lpnSize);

	// TODO: ASSERT_STREQ(username, Utf16leToUtf8(lpBuffer))
}

#include <string>
#include <vector>
#include <unistd.h>
#include <gtest/gtest.h>
#include <scxcorelib/scxstrencodingconv.h>
#include "getusername.h"

using std::string;
using std::vector;
using SCXCoreLib::Utf16leToUtf8;

TEST(GetUserName,simple)
{
	// allocate a WCHAR_T buffer to receive username
	DWORD lpnSize = 64;
	WCHAR_T lpBuffer[lpnSize];

	BOOL result = GetUserName(lpBuffer, &lpnSize);

	// GetUserName returns 1 on success
	ASSERT_EQ(1, result);

	// get expected username
	string username = string(getlogin());

	// GetUserName sets lpnSize to length of username including null
	ASSERT_EQ(username.size()+1, lpnSize);

	// copy UTF-16 bytes from lpBuffer to vector for conversion
	vector<unsigned char> input(reinterpret_cast<unsigned char *>(&lpBuffer[0]),
	                            reinterpret_cast<unsigned char *>(&lpBuffer[lpnSize-1]));
	// convert to UTF-8 for assertion
	string output;
	Utf16leToUtf8(input, output);

	EXPECT_EQ(username, output);
}

Test UTF-16 output of GetUserName


//===-- ubsan_init_standalone.cc ------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Initialization of standalone UBSan runtime.
//
//===----------------------------------------------------------------------===//

#include "ubsan_platform.h"
#if !CAN_SANITIZE_UB
# error "UBSan is not supported on this platform!"
#endif

#include "ubsan_init.h"

#if SANITIZER_CAN_USE_PREINIT_ARRAY
__attribute__((section(".preinit_array"), used))
void (*__local_ubsan_preinit)(void) = __ubsan::InitAsStandalone;
#else
// Use a dynamic initializer.
class UbsanStandaloneInitializer {
 public:
  UbsanStandaloneInitializer() {
    __ubsan::InitAsStandalone();
  }
};
static UbsanStandaloneInitializer ubsan_standalone_initializer;
#endif  // SANITIZER_CAN_USE_PREINIT_ARRAY

//===-- ubsan_init_standalone.cc ------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Initialization of standalone UBSan runtime.
//
//===----------------------------------------------------------------------===//

#include "ubsan_platform.h"
#if !CAN_SANITIZE_UB
# error "UBSan is not supported on this platform!"
#endif

#include "sanitizer_common/sanitizer_internal_defs.h"
#include "ubsan_init.h"

#if SANITIZER_CAN_USE_PREINIT_ARRAY
__attribute__((section(".preinit_array"), used))
void (*__local_ubsan_preinit)(void) = __ubsan::InitAsStandalone;
#else
// Use a dynamic initializer.
class UbsanStandaloneInitializer {
 public:
  UbsanStandaloneInitializer() {
    __ubsan::InitAsStandalone();
  }
};
static UbsanStandaloneInitializer ubsan_standalone_initializer;
#endif  // SANITIZER_CAN_USE_PREINIT_ARRAY

Add missing header that defines SANITIZER_CAN_USE_PREINIT_ARRAY


#include "binary_threshold.h"

namespace TooManyPeeps {

  BinaryThreshold::BinaryThreshold(const cv::Mat& original, cv::Mat& result, int threshold)
    : ProcessFilter(original, result) {
    this->threshold = threshold;
  }

  BinaryThreshold::BinaryThreshold(cv::Mat& image, int threshold)
    : BinaryThreshold(original, result, threshold) {
  }

  void BinaryThreshold::execute(void) {
    cv::threshold(get_original(), get_result(), threshold, MAX_OUTPUT_VALUE, cv::THRESH_BINARY);
  }

};

#include "binary_threshold.h"

namespace TooManyPeeps {

  BinaryThreshold::BinaryThreshold(const cv::Mat& original, cv::Mat& result, int threshold)
    : ProcessFilter(original, result) {
    this->threshold = threshold;
  }

  BinaryThreshold::BinaryThreshold(cv::Mat& image, int threshold)
    : BinaryThreshold(image, image, threshold) {
  }

  void BinaryThreshold::execute(void) {
    cv::threshold(get_original(), get_result(), threshold, MAX_OUTPUT_VALUE, cv::THRESH_BINARY);
  }

};

Fix wrong constructor argument in binary thresh


/**
 * Appcelerator Titanium - licensed under the Apache Public License 2
 * see LICENSE in the root folder for details on the license.
 * Copyright (c) 2009, 2010 Appcelerator, Inc. All Rights Reserved.
 */

#include "../network_status.h"
#include <SystemConfiguration/SCNetworkReachability.h>

namespace ti
{

void NetworkStatus::InitializeLoop()
{
}

void NetworkStatus::CleanupLoop()
{
}

bool NetworkStatus::GetStatus()
{
	static SCNetworkReachabilityRef primaryTarget =
		SCNetworkReachabilityCreateWithName(0, "www.google.com");
	if (!primaryTarget)
		return true;

	SCNetworkConnectionFlags flags;
	SCNetworkReachabilityGetFlags(primaryTarget, &flags);
	if ((flags & kSCNetworkFlagsReachable) &&
		!(flags & kSCNetworkFlagsConnectionRequired))
		return true;

	static SCNetworkReachabilityRef secondaryTarget =
		SCNetworkReachabilityCreateWithName(0, "www.yahoo.com");
	if (!secondaryTarget)
		return true;

	SCNetworkReachabilityGetFlags(secondaryTarget, &flags);
	if ((flags & kSCNetworkFlagsReachable) &&
		!(flags & kSCNetworkFlagsConnectionRequired))
		return true;

	return false;
}

}

/**
 * Appcelerator Titanium - licensed under the Apache Public License 2
 * see LICENSE in the root folder for details on the license.
 * Copyright (c) 2009, 2010 Appcelerator, Inc. All Rights Reserved.
 */

#include "../network_status.h"
#include <SystemConfiguration/SCNetworkReachability.h>

namespace ti
{

static SCNetworkReachabilityRef primaryTarget = 0;
static SCNetworkReachabilityRef secondaryTarget = 0;

void NetworkStatus::InitializeLoop()
{
	primaryTarget = SCNetworkReachabilityCreateWithName(0, "www.google.com");
	secondaryTarget = SCNetworkReachabilityCreateWithName(0, "www.yahoo.com");
}

void NetworkStatus::CleanupLoop()
{
	if (primaryTarget)
		CFRelease(primaryTarget);
	if (secondaryTarget)
		CFRelease(secondaryTarget);
}

bool NetworkStatus::GetStatus()
{
	if (!primaryTarget)
		return true;

	SCNetworkConnectionFlags flags;
	SCNetworkReachabilityGetFlags(primaryTarget, &flags);
	if ((flags & kSCNetworkFlagsReachable) &&
		!(flags & kSCNetworkFlagsConnectionRequired))
		return true;

	if (!secondaryTarget)
		return true;

	SCNetworkReachabilityGetFlags(secondaryTarget, &flags);
	if ((flags & kSCNetworkFlagsReachable) &&
		!(flags & kSCNetworkFlagsConnectionRequired))
		return true;

	return false;
}

}

Clean up allocated memory during shutdown in OS X NetworkStatus.


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

#include "common/content_client.h"

#include "common/application_info.h"

#include "base/stringprintf.h"
#include "base/string_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "webkit/user_agent/user_agent_util.h"

namespace brightray {

ContentClient::ContentClient() {
}

ContentClient::~ContentClient() {
}

std::string ContentClient::GetProduct() const {
  auto name = GetApplicationName();
  RemoveChars(name, kWhitespaceASCII, &name);
  return base::StringPrintf("%s/%s", name.c_str(), GetApplicationVersion().c_str());
}

std::string ContentClient::GetUserAgent() const {
  return webkit_glue::BuildUserAgentFromProduct(GetProduct());
}

base::StringPiece ContentClient::GetDataResource(int resource_id, ui::ScaleFactor scale_factor) const {
  return ui::ResourceBundle::GetSharedInstance().GetRawDataResourceForScale(resource_id, scale_factor);
}

gfx::Image& ContentClient::GetNativeImageNamed(int resource_id) const {
  return ui::ResourceBundle::GetSharedInstance().GetNativeImageNamed(resource_id);
}

}

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

#include "common/content_client.h"

#include "common/application_info.h"

#include "base/stringprintf.h"
#include "base/string_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "webkit/common/user_agent/user_agent_util.h"

namespace brightray {

ContentClient::ContentClient() {
}

ContentClient::~ContentClient() {
}

std::string ContentClient::GetProduct() const {
  auto name = GetApplicationName();
  RemoveChars(name, kWhitespaceASCII, &name);
  return base::StringPrintf("%s/%s", name.c_str(), GetApplicationVersion().c_str());
}

std::string ContentClient::GetUserAgent() const {
  return webkit_glue::BuildUserAgentFromProduct(GetProduct());
}

base::StringPiece ContentClient::GetDataResource(int resource_id, ui::ScaleFactor scale_factor) const {
  return ui::ResourceBundle::GetSharedInstance().GetRawDataResourceForScale(resource_id, scale_factor);
}

gfx::Image& ContentClient::GetNativeImageNamed(int resource_id) const {
  return ui::ResourceBundle::GetSharedInstance().GetNativeImageNamed(resource_id);
}

}

Update for webkit header moves


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

#include "chrome/browser/ui/webui/print_preview_ui.h"

#include "base/values.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/print_preview_handler.h"
#include "chrome/browser/ui/webui/print_preview_ui_html_source.h"
#include "content/browser/browser_thread.h"
#include "content/browser/tab_contents/tab_contents.h"

PrintPreviewUI::PrintPreviewUI(TabContents* contents)
    : WebUI(contents),
      html_source_(new PrintPreviewUIHTMLSource()) {
  // PrintPreviewUI owns |handler|.
  PrintPreviewHandler* handler = new PrintPreviewHandler();
  AddMessageHandler(handler->Attach(this));

  // Set up the chrome://print/ source.
  contents->profile()->GetChromeURLDataManager()->AddDataSource(html_source_);
}

PrintPreviewUI::~PrintPreviewUI() {
}

PrintPreviewUIHTMLSource* PrintPreviewUI::html_source() {
  return html_source_.get();
}

void PrintPreviewUI::PreviewDataIsAvailable(int expected_pages_count) {
  FundamentalValue pages_count(expected_pages_count);
  CallJavascriptFunction("createPDFPlugin", pages_count);
}

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

#include "chrome/browser/ui/webui/print_preview_ui.h"

#include "base/values.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/print_preview_handler.h"
#include "chrome/browser/ui/webui/print_preview_ui_html_source.h"
#include "content/browser/browser_thread.h"
#include "content/browser/tab_contents/tab_contents.h"

PrintPreviewUI::PrintPreviewUI(TabContents* contents)
    : WebUI(contents),
      html_source_(new PrintPreviewUIHTMLSource()) {
  // PrintPreviewUI owns |handler|.
  PrintPreviewHandler* handler = new PrintPreviewHandler();
  AddMessageHandler(handler->Attach(this));

  // Set up the chrome://print/ source.
  contents->profile()->GetChromeURLDataManager()->AddDataSource(html_source_);
}

PrintPreviewUI::~PrintPreviewUI() {
}

PrintPreviewUIHTMLSource* PrintPreviewUI::html_source() {
  return html_source_.get();
}

void PrintPreviewUI::PreviewDataIsAvailable(int expected_pages_count) {
  FundamentalValue pages_count(expected_pages_count);
  CallJavascriptFunction("updatePrintPreview", pages_count);
}

Print Preview: Fix typo from r78639.


#include <patlms/util/remove_file.h>
#include <patlms/util/detail/cant_remove_file_exception.h>

#include <string>
#include <cstring>
#include <cerrno>
#include <boost/log/trivial.hpp>

using namespace std;

namespace util
{

void RemoveFile(const std::string &path, detail::SystemInterfacePtr system) {
  BOOST_LOG_TRIVIAL(debug) << "libpatlms::util::RemovePidFile: Function call with (path=" << path << ")";

  int ret = system->unlink(path.c_str());
  if (ret < 0) {
    BOOST_LOG_TRIVIAL(error) << "libpatlms::util::RemovePidFile: Couldn't remove pid file: " << strerror(errno);
    throw detail::CantRemoveFileException();
  }

  BOOST_LOG_TRIVIAL(debug) << "libpatlms::util::RemovePidFile: Done";
}

}

#include <patlms/util/remove_file.h>
#include <patlms/util/detail/cant_remove_file_exception.h>

#include <string>
#include <cstring>
#include <cerrno>
#include <boost/log/trivial.hpp>

using namespace std;

namespace util
{

void RemoveFile(const std::string &path, detail::SystemInterfacePtr system) {
  BOOST_LOG_TRIVIAL(debug) << "libpatlms::util::RemoveFile: Function call with (path=" << path << ")";

  int ret = system->unlink(path.c_str());
  if (ret < 0) {
    BOOST_LOG_TRIVIAL(error) << "libpatlms::util::RemoveFile: Couldn't remove file: " << strerror(errno);
    throw detail::CantRemoveFileException();
  }

  BOOST_LOG_TRIVIAL(debug) << "libpatlms::util::RemoveFile: Done";
}

}

Fix debug messages in library when removing file


// This file is part of MorphoDiTa <http://github.com/ufal/morphodita/>.
//
// Copyright 2016 Institute of Formal and Applied Linguistics, Faculty of
// Mathematics and Physics, Charles University in Prague, Czech Republic.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "generic_tokenizer.h"
#include "generic_tokenizer_factory.h"

namespace ufal {
namespace morphodita {

tokenizer* generic_tokenizer_factory::new_tokenizer() const {
  return new generic_tokenizer(version);
}

bool generic_tokenizer_factory::load(istream& is) {
  version = is.get();

  return is;
}

} // namespace morphodita
} // namespace ufal

// This file is part of MorphoDiTa <http://github.com/ufal/morphodita/>.
//
// Copyright 2016 Institute of Formal and Applied Linguistics, Faculty of
// Mathematics and Physics, Charles University in Prague, Czech Republic.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "generic_tokenizer.h"
#include "generic_tokenizer_factory.h"

namespace ufal {
namespace morphodita {

tokenizer* generic_tokenizer_factory::new_tokenizer() const {
  return new generic_tokenizer(version);
}

bool generic_tokenizer_factory::load(istream& is) {
  version = is.get();

  return bool(is);
}

} // namespace morphodita
} // namespace ufal

Add explicit conversion to bool.


#include "impl_send_posture.hpp"

#include "servo_msgs/KrsServoDegree.h"

std::map<std::string, const SendPosture*> SendPostureFactory::sends;

const SendPosture* SendPostureFactory::get(const std::string& name, ros::NodeHandle& nh) {
  std::map<std::string, const SendPosture*>::const_iterator found_it = sends.find(name);
  if (found_it != sends.end()) return create(name, nh);
  return found_it->second;
}

const SendPosture* SendPostureFactory::create(const std::string& name, ros::NodeHandle& nh) {
  if (name == "krs") {
    sends["krs"] = new KrsSendPosture(nh);
    return sends.at("krs");
  }
  return NULL;
}

KrsSendPosture::KrsSendPosture(ros::NodeHandle& nh) : nh(nh) {
  pub = nh.advertise<servo_msgs::KrsServoDegree>("cmd_krs", 16);
  nh.getParam("id_vec", id_vec);
}

void KrsSendPosture::sendPosture(std::vector<double>& posture) {

}

#include "impl_send_posture.hpp"

#include "algorithm"

#include "servo_msgs/KrsServoDegree.h"

std::map<std::string, const SendPosture*> SendPostureFactory::sends;

const SendPosture* SendPostureFactory::get(const std::string& name, ros::NodeHandle& nh) {
  std::map<std::string, const SendPosture*>::const_iterator found_it = sends.find(name);
  if (found_it != sends.end()) return create(name, nh);
  return found_it->second;
}

const SendPosture* SendPostureFactory::create(const std::string& name, ros::NodeHandle& nh) {
  if (name == "krs") {
    sends["krs"] = new KrsSendPosture(nh);
    return sends.at("krs");
  }
  return NULL;
}

KrsSendPosture::KrsSendPosture(ros::NodeHandle& nh) : nh(nh) {
  pub = nh.advertise<servo_msgs::KrsServoDegree>("cmd_krs", 16);
  nh.getParam("id_vec", id_vec);
}

void KrsSendPosture::sendPosture(std::vector<double>& posture) {
  servo_msgs::KrsServoDegree msg;
  std::vector<double>::size_type length = std::min(posture.size(), id_vec.size());
  for (std::vector<double>::size_type i = 0; i < length; i++) {
    msg.id = id_vec[i];
    msg.angle = posture[i];
    pub.publish(msg);
  }
}

Implement krs send posture method.


#include "reg_language_translator.h"
#include "orz/types.h"

namespace Reg {
	namespace Internal {
		// TODO: Centralize (de)serialization the same way as for keyboard events

		boost::optional<LanguageTranslator::external_type> LanguageTranslator::get_value(internal_type const sval) {
			if (sval == "English") {
				return Intl::Language::English;
			}
			if (sval == "Swedish") {
				return Intl::Language::Swedish;
			}
			auto val = FromAString<int>(sval);
			if (val == 0) return Intl::Language::English;
			if (val == 1) return Intl::Language::Swedish;
			return boost::none;
		}

		boost::optional<LanguageTranslator::internal_type> LanguageTranslator::put_value(external_type const& val) {
			if (val == Intl::Language::English) {
				return "English";
			}
			if (val == Intl::Language::Swedish) {
				return "Swedish";
			}
			return boost::none;
		}
	}
}

#include "reg_language_translator.h"
#include "orz/types.h"

namespace Reg {
	namespace Internal {
		// TODO: Centralize (de)serialization the same way as for keyboard events

		boost::optional<LanguageTranslator::external_type> LanguageTranslator::get_value(internal_type const sval) {
			if (sval == "English") {
				return Intl::Language::English;
			}
			if (sval == "Swedish") {
				return Intl::Language::Swedish;
			}
			auto val = FromAString<int>(sval);
			if (val == 0) return Intl::Language::English;
			if (val == 1) return Intl::Language::Swedish;
			return boost::none;
		}

		boost::optional<LanguageTranslator::internal_type> LanguageTranslator::put_value(external_type const& val) {
			if (val == Intl::Language::English) {
				return std::string("English");
			}
			if (val == Intl::Language::Swedish) {
				return std::string("Swedish");
			}
			return boost::none;
		}
	}
}

Fix compile errors on Linux


#include "./mesh_node.h"
#include <string>
#include "./graphics/gl.h"

MeshNode::MeshNode(std::string assetFilename, int meshIndex,
                   std::shared_ptr<Graphics::Mesh> mesh,
                   Eigen::Matrix4f transformation)
  : assetFilename(assetFilename), meshIndex(meshIndex), mesh(mesh),
    transformation(transformation)
{
  obb = mesh->obb * transformation;
}

MeshNode::~MeshNode()
{
}

void MeshNode::render(Graphics::Gl *gl,
                      std::shared_ptr<Graphics::Managers> managers,
                      RenderData renderData)
{
  if (!isVisible)
    return;

  renderData.modelMatrix = transformation;
  mesh->render(gl, managers, renderData);
}

Eigen::Matrix4f MeshNode::getTransformation()
{
  return this->transformation;
}

void MeshNode::setTransformation(Eigen::Matrix4f transformation)
{
  this->transformation = transformation;
}

#include "./mesh_node.h"
#include <string>
#include "./graphics/gl.h"

MeshNode::MeshNode(std::string assetFilename, int meshIndex,
                   std::shared_ptr<Graphics::Mesh> mesh,
                   Eigen::Matrix4f transformation)
  : assetFilename(assetFilename), meshIndex(meshIndex), mesh(mesh),
    transformation(transformation)
{
  obb = mesh->obb * transformation;
}

MeshNode::~MeshNode()
{
}

void MeshNode::render(Graphics::Gl *gl,
                      std::shared_ptr<Graphics::Managers> managers,
                      RenderData renderData)
{
  if (!isVisible)
    return;

  renderData.modelMatrix = transformation;
  mesh->render(gl, managers, renderData);
}

Eigen::Matrix4f MeshNode::getTransformation()
{
  return this->transformation;
}

void MeshNode::setTransformation(Eigen::Matrix4f transformation)
{
  this->transformation = transformation;
  obb = mesh->obb * transformation;
}

Update bounding box in MeshNode::setTransformation.


#include <fstream>
#include <iostream>
#include "person.pb.h"
//#include "../pb2json.h"
#include <pb2json.h>

using namespace std;

int main(int argc,char *argv[])
{
 	// Test 1: read binary PB from a file and convert it to JSON
	ifstream fin("dump",ios::binary);
	fin.seekg(0,ios_base::end);
	size_t len = fin.tellg();
	fin.seekg(0,ios_base::beg);
	char *buf = new char [len];

	fin.read(buf,len);
	google::protobuf::Message *p = new Person();
	char *json = pb2json(p,buf,len);
	cout<<json<<endl;
	free(json);
	delete p;

	// Test 2: convert PB to JSON directly
	Person p2;
	char *json2 = pb2json(p2);
	cout<<json2<<endl;
	free(json2);

	return 0;
}

#include <fstream>
#include <iostream>
#include "person.pb.h"
//#include "../pb2json.h"
#include <pb2json.h>

using namespace std;

int main(int argc,char *argv[])
{
 	// Test 1: read binary PB from a file and convert it to JSON
	ifstream fin("dump",ios::binary);
	fin.seekg(0,ios_base::end);
	size_t len = fin.tellg();
	fin.seekg(0,ios_base::beg);
	char *buf = new char [len];

	fin.read(buf,len);
	google::protobuf::Message *p = new Person();
	char *json = pb2json(p,buf,len);
	cout<<json<<endl;
	free(json);
	delete p;

	// Test 2: convert PB to JSON directly
	Person p2;
    p2.set_name("Shafreeck Sea");
    p2.set_id(2);
    p2.set_email("renenglish@gmail.com");
	Person_PhoneNumber *pn1 = p2.add_phone();
	pn1->set_number("1234567");
	pn1->set_type(Person::HOME);
	char *json2 = pb2json(p2);
	cout<<json2<<endl;
	free(json2);

	return 0;
}

Add test translate protobuf object to json directly


#include "log4qt/dailyfileappender.h"

#include "log4qt/simplelayout.h"

#include <QTemporaryDir>
#include <QtTest/QtTest>

using Log4Qt::DailyFileAppender;

class DailyFileAppenderTest : public QObject
{
    Q_OBJECT

private Q_SLOTS:
    void init();
    void cleanup();

    void testFileCreation();

private:
    QTemporaryDir *mLogDirectory;
    DailyFileAppender *mAppender;
};

void DailyFileAppenderTest::init()
{
    mLogDirectory = new QTemporaryDir;

    mAppender = new DailyFileAppender;
    mAppender->setLayout(Log4Qt::LayoutSharedPtr(new Log4Qt::SimpleLayout));
}

void DailyFileAppenderTest::cleanup()
{
    delete mAppender;
    delete mLogDirectory;  // destructor will remove temporary directory
}

void DailyFileAppenderTest::testFileCreation()
{
    mAppender->setDatePattern(QStringLiteral("_yyyy_MM_dd"));
    mAppender->setFile(mLogDirectory->filePath(QStringLiteral("app.log")));

    mAppender->activateOptions();

    QVERIFY(QFileInfo::exists(mAppender->file()));
}

QTEST_GUILESS_MAIN(DailyFileAppenderTest)

#include "dailyfileappendertest.moc"

#include "log4qt/dailyfileappender.h"

#include "log4qt/loggingevent.h"
#include "log4qt/simplelayout.h"

#include <QTemporaryDir>
#include <QtTest/QtTest>

using Log4Qt::DailyFileAppender;

class DailyFileAppenderTest : public QObject
{
    Q_OBJECT

private Q_SLOTS:
    void init();
    void cleanup();

    void testFileCreation();
    void testAppend();

private:
    QTemporaryDir *mLogDirectory;
    DailyFileAppender *mAppender;
};

void DailyFileAppenderTest::init()
{
    mLogDirectory = new QTemporaryDir;

    mAppender = new DailyFileAppender;
    mAppender->setLayout(Log4Qt::LayoutSharedPtr(new Log4Qt::SimpleLayout));
}

void DailyFileAppenderTest::cleanup()
{
    delete mAppender;
    delete mLogDirectory;  // destructor will remove temporary directory
}

void DailyFileAppenderTest::testFileCreation()
{
    mAppender->setDatePattern(QStringLiteral("_yyyy_MM_dd"));
    mAppender->setFile(mLogDirectory->filePath(QStringLiteral("app.log")));

    mAppender->activateOptions();

    QVERIFY(QFileInfo::exists(mAppender->file()));
}

void DailyFileAppenderTest::testAppend()
{
    mAppender->setFile(mLogDirectory->filePath(QStringLiteral("app.log")));

    mAppender->activateOptions();

    const auto fileName = mAppender->file();

    QVERIFY(QFileInfo::exists(fileName));

    const QFile logFile(fileName);

    // nothing written yet
    QCOMPARE(logFile.size(), 0);

    mAppender->append(Log4Qt::LoggingEvent());

    QVERIFY(logFile.size() > 0);
}

QTEST_GUILESS_MAIN(DailyFileAppenderTest)

#include "dailyfileappendertest.moc"

Add test for simple append using DailyFileAppender


#include <fstream>
#include "rang.hpp"

int main()
{
	std::cout << rang::fg::blue << "\nShould be blue";
	std::ofstream out("out.txt");
	std::streambuf *coutbuf = std::cout.rdbuf();
	std::cout.rdbuf(out.rdbuf());

	std::string word = "not blue";
	std::cout << "START " << rang::fg::blue << word << " END";

	std::cout.rdbuf(coutbuf);
	std::cout << "\nShould again be blue" << rang::style::reset << std::endl;
	return 0;
}

#define CATCH_CONFIG_MAIN
#include "catch.hpp"

#include "rang.hpp"

#include <fstream>
#include <string>

std::string RCB(std::string input)
{
	std::ofstream out("out.txt");
	std::streambuf *coutbuf = std::cout.rdbuf();
	std::cout.rdbuf(out.rdbuf());

	std::cout << rang::fg::blue << input << rang::style::reset;

	std::cout.rdbuf(coutbuf);
	out.close();

	std::ifstream in("out.txt");
	std::string output;
	std::getline(in,output);
	return output;

}

TEST_CASE("Redirected cout buffer", "RCB")
{
	REQUIRE(RCB("HelloWorld") == "HelloWorld");
}

Add a simple write-then-read test


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

#include "remoting/host/event_executor_mac.h"

namespace remoting {

EventExecutorMac::EventExecutorMac(Capturer* capturer)
  : EventExecutor(capturer) {
}

EventExecutorMac::~EventExecutorMac() {
}

void EventExecutorMac::HandleInputEvent(ChromotingClientMessage* message) {
  delete message;
}

}  // namespace remoting

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

#include "remoting/host/event_executor_mac.h"

#include "remoting/protocol/messages_decoder.h"

namespace remoting {

EventExecutorMac::EventExecutorMac(Capturer* capturer)
  : EventExecutor(capturer) {
}

EventExecutorMac::~EventExecutorMac() {
}

void EventExecutorMac::HandleInputEvent(ChromotingClientMessage* message) {
  delete message;
}

}  // namespace remoting

Fix build break on mac. TBR=ajwong


// Copyright (c) 2011 The Native Client 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 "native_client/src/shared/platform/nacl_check.h"
#include "native_client/tests/ppapi_test_lib/test_interface.h"

namespace {

// This will crash a PPP_Messaging function.
void CrashViaExitCall() {
  printf("--- CrashViaExitCall\n");
  _exit(0);
}

}  // namespace

void SetupTests() {
  RegisterTest("CrashViaExitCall", CrashViaExitCall);
}

void SetupPluginInterfaces() {
  // none
}

// Copyright (c) 2011 The Native Client 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 <unistd.h>

#include "native_client/src/shared/platform/nacl_check.h"
#include "native_client/tests/ppapi_test_lib/test_interface.h"

namespace {

// This will crash a PPP_Messaging function.
void CrashViaExitCall() {
  printf("--- CrashViaExitCall\n");
  _exit(0);
}

}  // namespace

void SetupTests() {
  RegisterTest("CrashViaExitCall", CrashViaExitCall);
}

void SetupPluginInterfaces() {
  // none
}

Add include for unistd.h for _exit. Otherwise, the exit test won't build w/ pnacl.


//===----------------------------------------------------------------------===//
//
//                     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.
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads
// UNSUPPORTED: c++98, c++03

// <future>

// class packaged_task<R(ArgTypes...)>
// template <class F, class Allocator>
//   packaged_task(allocator_arg_t, const Allocator& a, F&& f);
// These constructors shall not participate in overload resolution if
//    decay<F>::type is the same type as std::packaged_task<R(ArgTypes...)>.

#include <future>
#include <cassert>

#include "test_allocator.h"

struct A {};
typedef std::packaged_task<A(int, char)> PT;
typedef volatile std::packaged_task<A(int, char)> VPT;

int main()
{
    PT p { std::allocator_arg_t{}, test_allocator<A>{}, VPT {}}; // expected-error {{no matching constructor for initialization of 'PT' (aka 'packaged_task<A (int, char)>')}}
    // expected-note@future:* 1 {{candidate template ignored: disabled by 'enable_if'}}
}

//===----------------------------------------------------------------------===//
//
//                     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.
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads
// UNSUPPORTED: c++98, c++03

// <future>

// class packaged_task<R(ArgTypes...)>
// template <class F, class Allocator>
//   packaged_task(allocator_arg_t, const Allocator& a, F&& f);
// These constructors shall not participate in overload resolution if
//    decay<F>::type is the same type as std::packaged_task<R(ArgTypes...)>.

#include <future>
#include <cassert>

#include "test_allocator.h"

struct A {};
typedef std::packaged_task<A(int, char)> PT;
typedef volatile std::packaged_task<A(int, char)> VPT;

int main()
{
    PT p { std::allocator_arg_t{}, test_allocator<A>{}, VPT {}}; // expected-error {{no matching constructor for initialization of 'PT' (aka 'packaged_task<A (int, char)>')}}
    // expected-note-re@future:* 1 {{candidate template ignored: {{(disabled by 'enable_if')|(requirement '.*' was not satisfied)}}}}
}

Fix diagnostic in verify test to match new Clang output


// RUN: %clang_cc1 -emit-llvm %s -o - -triple=i386-pc-win32 -mconstructor-aliases -fcxx-exceptions -fexceptions -fno-rtti -DTRY   | FileCheck %s -check-prefix=TRY
// RUN: %clang_cc1 -emit-llvm %s -o - -triple=i386-pc-win32 -mconstructor-aliases -fcxx-exceptions -fexceptions -fno-rtti -DTHROW | FileCheck %s -check-prefix=THROW

void external();

inline void not_emitted() {
  throw int(13); // no error
}

int main() {
  int rv = 0;
#ifdef TRY
  try {
    external(); // TRY: invoke void @"\01?external@@YAXXZ"
  } catch (int) {
    rv = 1;
    // TRY: call i8* @llvm.eh.begincatch
    // TRY: call void @llvm.eh.endcatch
  }
#endif
#ifdef THROW
  // THROW: call void @"\01?terminate@@YAXXZ"
  throw int(42);
#endif
  return rv;
}

// RUN: %clang_cc1 -emit-llvm %s -o - -triple=i386-pc-win32 -mconstructor-aliases -fcxx-exceptions -fexceptions -fno-rtti -DTRY   | FileCheck %s -check-prefix=TRY
// FIXME: Disabled until catch IRgen change lands.
// RUNX: %clang_cc1 -emit-llvm %s -o - -triple=i386-pc-win32 -mconstructor-aliases -fcxx-exceptions -fexceptions -fno-rtti -DTHROW | FileCheck %s -check-prefix=THROW

void external();

inline void not_emitted() {
  throw int(13); // no error
}

int main() {
  int rv = 0;
#ifdef TRY
  try {
    external(); // TRY: invoke void @"\01?external@@YAXXZ"
  } catch (int) {
    rv = 1;
    // TRY: call i8* @llvm.eh.begincatch
    // TRY: call void @llvm.eh.endcatch
  }
#endif
#ifdef THROW
  // THROW: call void @"\01?terminate@@YAXXZ"
  throw int(42);
#endif
  return rv;
}

Disable a Clang test until the begincatch change lands


#include <fastarduino/soft_uart.h>

constexpr const board::InterruptPin RX = board::InterruptPin::D0_PD0_PCI2;
#define PCI_NUM 2

REGISTER_UART_PCI_ISR(RX, PCI_NUM)

// Buffers for UARX
static const uint8_t INPUT_BUFFER_SIZE = 64;
static char input_buffer[INPUT_BUFFER_SIZE];

int main()
{
    board::init();
    sei();

    // Start UART
	typename interrupt::PCIType<RX>::TYPE pci;
	serial::soft::UARX_PCI<RX> uarx{input_buffer, pci};
	pci.enable();
	uarx.begin(115200);

    streams::istream in = uarx.in();

    // Wait for a char
    char value1;
    in >> streams::skipws >> value1;

    // Wait for an uint16_t
    uint16_t value2;
    in >> streams::skipws >> value2;

    return 0;
}

#include <fastarduino/soft_uart.h>

constexpr const board::InterruptPin RX = board::InterruptPin::D0_PD0_PCI2;
#define PCI_NUM 2

REGISTER_UARX_PCI_ISR(RX, PCI_NUM)

// Buffers for UARX
static const uint8_t INPUT_BUFFER_SIZE = 64;
static char input_buffer[INPUT_BUFFER_SIZE];

int main()
{
    board::init();
    sei();

    // Start UART
	typename interrupt::PCIType<RX>::TYPE pci;
	serial::soft::UARX_PCI<RX> uarx{input_buffer, pci};
	pci.enable();
	uarx.begin(115200);

    streams::istream in = uarx.in();

    // Wait for a char
    char value1;
    in >> streams::skipws >> value1;

    // Wait for an uint16_t
    uint16_t value2;
    in >> streams::skipws >> value2;

    return 0;
}

Fix tutorial SW UART example


// RUN: %clang_cc1 %s -fsyntax-only -verify -Wmissing-noreturn -Wno-unreachable-code

// A destructor may be marked noreturn and should still influence the CFG.
namespace PR6884 {
  struct abort_struct {
    abort_struct() {} // Make this non-POD so the destructor is invoked.
    ~abort_struct() __attribute__((noreturn));
  };

  int f() {
    abort_struct();
  }

  int f2() {
    abort_struct s;
  } // expected-warning{{control reaches end of non-void function}}
}

// RUN: %clang_cc1 %s -fsyntax-only -verify -Wmissing-noreturn -Wno-unreachable-code

// A destructor may be marked noreturn and should still influence the CFG.
namespace PR6884 {
  struct abort_struct {
    abort_struct() {} // Make this non-POD so the destructor is invoked.
    ~abort_struct() __attribute__((noreturn));
  };

  // FIXME: Should either of these actually warn, since the destructor is
  //  marked noreturn?

  int f() {
    abort_struct();
  } // expected-warning{{control reaches end of non-void function}}

  int f2() {
    abort_struct s;
  } // expected-warning{{control reaches end of non-void function}}
}

Update test case, with comment to later investigate the correct behavior. Now the behavior is at least consistent.


#include <log4cpp/Category.hh>
#include <log4cpp/Appender.hh>
#include <log4cpp/OstreamAppender.hh>
#include <log4cpp/Layout.hh>
#include <log4cpp/PatternLayout.hh>
#include <log4cpp/Priority.hh>

#include "LoggerFactory.h"

using namespace Log;

bool LoggerFactory::isCreated = false;
log4cpp::Category *LoggerFactory::instance;

LoggerFactory::LoggerFactory() {}

/* Factory for a simple log4cpp logger. */
log4cpp::Category* LoggerFactory::create() {
    log4cpp::Category *logger = &log4cpp::Category::getRoot();
    log4cpp::Appender *p_appender = new log4cpp::OstreamAppender("console", &std::cout);
    log4cpp::PatternLayout *layout = new log4cpp::PatternLayout();
    layout->setConversionPattern("%d{%Y-%m-%d %H:%M:%S} [%p] %c: %m%n");
    p_appender->setLayout(layout);

    logger->setPriority(log4cpp::Priority::DEBUG);
    logger->addAppender(p_appender);
    return logger;
}

/* Returns a singleton root logger. */
log4cpp::Category *LoggerFactory::getLogger() {
    if (!isCreated) {
        isCreated = true;
        instance = create();
    }
    return instance;
}

#include <log4cpp/Category.hh>
#include <log4cpp/Appender.hh>
#include <log4cpp/OstreamAppender.hh>
#include <log4cpp/Layout.hh>
#include <log4cpp/PatternLayout.hh>
#include <log4cpp/Priority.hh>

#include "LoggerFactory.h"

using namespace Log;

bool LoggerFactory::isCreated = false;
log4cpp::Category *LoggerFactory::instance;

LoggerFactory::LoggerFactory() {}

/* Factory for a simple log4cpp logger. */
log4cpp::Category* LoggerFactory::create() {
    log4cpp::Category *logger = &log4cpp::Category::getRoot();
    log4cpp::Appender *p_appender = new log4cpp::OstreamAppender("console", &std::cout);
    log4cpp::PatternLayout *layout = new log4cpp::PatternLayout();
    layout->setConversionPattern("%d{%Y-%m-%d %H:%M:%S} [%p] %c: %m%n");
    p_appender->setLayout(layout);

    logger->setPriority(log4cpp::Priority::INFO);
    logger->addAppender(p_appender);
    return logger;
}

/* Returns a singleton root logger. */
log4cpp::Category *LoggerFactory::getLogger() {
    if (!isCreated) {
        isCreated = true;
        instance = create();
    }
    return instance;
}

Change logging level to INFO (DEBUG is slowing down the execution too much).


// This code is in the public domain -- castano@gmail.com

#include "FileSystem.h"
#include <nvcore/nvcore.h>

#if NV_OS_WIN32
#include <direct.h>
#else
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#endif

using namespace nv;

bool FileSystem::exists(const char * path)
{
#if NV_OS_UNIX
	struct stat buf;
	return stat(path, &buf) == 0;
#else
	if (FILE * fp = fopen(path, "r"))
	{
		fclose(fp);
		return true;
	}
	return false;
#endif
}

bool FileSystem::createDirectory(const char * path)
{
#if NV_OS_WIN32
    return _mkdir(path) != -1;
#else
    return mkdir(path, 0777) != -1;
#endif
}

// This code is in the public domain -- castano@gmail.com

#include "FileSystem.h"
#include <nvcore/nvcore.h>

#if NV_OS_WIN32
#include <direct.h>
#else
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#endif

using namespace nv;

bool FileSystem::exists(const char * path)
{
#if NV_OS_UNIX
	return access(path, F_OK|R_OK) == 0;
	//struct stat buf;
	//return stat(path, &buf) == 0;
#else
	if (FILE * fp = fopen(path, "r"))
	{
		fclose(fp);
		return true;
	}
	return false;
#endif
}

bool FileSystem::createDirectory(const char * path)
{
#if NV_OS_WIN32
    return _mkdir(path) != -1;
#else
    return mkdir(path, 0777) != -1;
#endif
}

Implement exists with access instead of stat.


// Copyright (c) 2013, Facebook, Inc.  All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.

#include <atomic>

#include "rocksdb/env.h"
#include "util/thread_status_updater.h"
#include "util/thread_status_util.h"

namespace rocksdb {

#ifndef NDEBUG
// the delay for debugging purpose.
static std::atomic<int> states_delay[ThreadStatus::NUM_STATE_TYPES];

void ThreadStatusUtil::TEST_SetStateDelay(
    const ThreadStatus::StateType state, int micro) {
  states_delay[state].store(micro, std::memory_order_relaxed);
}

void ThreadStatusUtil::TEST_StateDelay(
    const ThreadStatus::StateType state) {
  Env::Default()->SleepForMicroseconds(
      states_delay[state].load(std::memory_order_relaxed));
}

#endif  // !NDEBUG

}  // namespace rocksdb

// Copyright (c) 2013, Facebook, Inc.  All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.

#include <atomic>

#include "rocksdb/env.h"
#include "util/thread_status_updater.h"
#include "util/thread_status_util.h"

namespace rocksdb {

#ifndef NDEBUG
// the delay for debugging purpose.
static std::atomic<int> states_delay[ThreadStatus::NUM_STATE_TYPES];

void ThreadStatusUtil::TEST_SetStateDelay(
    const ThreadStatus::StateType state, int micro) {
  states_delay[state].store(micro, std::memory_order_relaxed);
}

void ThreadStatusUtil::TEST_StateDelay(const ThreadStatus::StateType state) {
  auto delay = states_delay[state].load(std::memory_order_relaxed);
  if (delay > 0) {
    Env::Default()->SleepForMicroseconds(delay);
  }
}

#endif  // !NDEBUG

}  // namespace rocksdb

Fix bad performance in debug mode


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

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

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

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

#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"

namespace tensorflow {
namespace {

class XlaReplicaIdOp : public XlaOpKernel {
 public:
  explicit XlaReplicaIdOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {}
  void Compile(XlaOpKernelContext* ctx) override;

 private:
  TF_DISALLOW_COPY_AND_ASSIGN(XlaReplicaIdOp);
};

void XlaReplicaIdOp::Compile(XlaOpKernelContext* ctx) {
  ctx->SetOutput(
      0, xla::ConvertElementType(xla::ReplicaId(ctx->builder()), xla::S32));
}

REGISTER_XLA_OP(Name("XlaReplicaId"), XlaReplicaIdOp);

}  // namespace
}  // namespace tensorflow

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

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

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

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

#include "tensorflow/compiler/tf2xla/mlir_xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"

namespace tensorflow {
namespace {

REGISTER_XLA_OP(Name("XlaReplicaId"), MlirXlaOpKernel);

}  // namespace
}  // namespace tensorflow

Remove the fallback to the old bridge for tf.XlaReplicaId


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

// <vector>

// void assign(size_type n, const_reference v);

#include <vector>
#include <algorithm>
#include <cassert>
#include <iostream>

#include "min_allocator.h"
#include "asan_testing.h"

bool is6(int x) { return x == 6; }

template <typename Vec>
void test ( Vec &v )
{
    std::cout << "Size, cap: " << v.size() << " " << v.capacity() << std::endl;
    v.assign(5, 6);
    std::cout << "Size, cap: " << v.size() << " " << v.capacity() << std::endl;
    assert(v.size() == 5);
    assert(is_contiguous_container_asan_correct(v));
    assert(std::all_of(v.begin(), v.end(), is6));
}

int main()
{
    {
    typedef std::vector<int> V;
    V d1;
    V d2;
    d2.reserve(10);  // no reallocation during assign.
    test(d1);
    test(d2);
    }

#if __cplusplus >= 201103L
    {
    typedef std::vector<int, min_allocator<int>> V;
    V d1;
    V d2;
    d2.reserve(10);  // no reallocation during assign.
    test(d1);
    test(d2);
    }
#endif
}

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

// <vector>

// void assign(size_type n, const_reference v);

#include <vector>
#include <algorithm>
#include <cassert>
#include <iostream>

#include "min_allocator.h"
#include "asan_testing.h"

bool is6(int x) { return x == 6; }

template <typename Vec>
void test ( Vec &v )
{
    v.assign(5, 6);
    assert(v.size() == 5);
    assert(is_contiguous_container_asan_correct(v));
    assert(std::all_of(v.begin(), v.end(), is6));
}

int main()
{
    {
    typedef std::vector<int> V;
    V d1;
    V d2;
    d2.reserve(10);  // no reallocation during assign.
    test(d1);
    test(d2);
    }

#if __cplusplus >= 201103L
    {
    typedef std::vector<int, min_allocator<int>> V;
    V d1;
    V d2;
    d2.reserve(10);  // no reallocation during assign.
    test(d1);
    test(d2);
    }
#endif
}

Remove some debugging printout lines. No functionality change.