#include "instr.h"

#define MIPS_JTYPE_EXTRACT_TARGET(Instr) (Instr & ((1 << 26) - 1))

namespace sasm { namespace instr { namespace mips { namespace jtype {

jtype_instr::jtype_instr(const sasm::elf::elf& elf, uint64 addr)
  : mips_instr(elf, addr)
{
  auto instr = elf.image.read<uint32>(addr);

  _target_val = MIPS_JTYPE_EXTRACT_TARGET(instr);
}

void jtype_instr::dump_asm(std::ostream& out) const
{
  _dump_addr(out);
  out << _name << " " << _get_abs_addr(_target_val << 2) << std::endl;
}

}}}}

#include "instr.h"

#define MIPS_JTYPE_EXTRACT_TARGET(Instr) (Instr & ((1 << 26) - 1))

namespace sasm { namespace instr { namespace mips { namespace jtype {

jtype_instr::jtype_instr(const sasm::elf::elf& elf, uint64 addr)
  : mips_instr(elf, addr)
{
  auto instr = elf.image.read<uint32>(addr);

  _target_val = MIPS_JTYPE_EXTRACT_TARGET(instr);
}

void jtype_instr::dump_asm(std::ostream& out) const
{
  _dump_addr(out);
  uint32 dst_addr = (_target_val << 2) + ((_addr >> 28) << 28);
  out << _name << " " << _get_abs_addr(dst_addr) << std::endl;
}

}}}}

Fix a bug with J-type target address calculation.


#include <stan/math/prim/mat.hpp>
#include <gtest/gtest.h>

TEST(MathMatrixPrimMat, singular_values) {
  stan::math::matrix_d m0(1, 1);
  m0 << 1.0;

  using stan::math::singular_values;
  EXPECT_NO_THROW(singular_values(m0));
}

#include <stan/math/prim/mat.hpp>
#include <gtest/gtest.h>

TEST(MathMatrixPrimMat, singular_values) {
  using stan::math::singular_values;

  stan::math::matrix_d m0(0, 0);
  EXPECT_NO_THROW(singular_values(m0));

  stan::math::matrix_d m1(1, 1);
  m1 << 1.0;
  EXPECT_NO_THROW(singular_values(m1));
}

Add prim test for size zero input

Add prim test for size zero input


#include <functional>
#include "apsp.h"
#include "cuda/cuda_apsp.cuh"

/**
 * Naive implementation algorithm Floyd Wharshall for APSP
 *
 * @param data: unique ptr to graph data with allocated fields
 */
static void naiveFW(const std::unique_ptr<graphAPSPTopology>& data) {
    int newPath = 0;
    int n = data->nvertex;

    for(int u=0; u < n; ++u) {
        for(int v1=0; v1 < n; ++v1) {
            for(int v2=0; v2 < n; ++v2) {
                newPath = data->graph[v1 * n + u] + data->graph[u * n + v2];
                if (data->graph[v1 * n + v2] > newPath) {
                    data->graph[v1 * n + v2] = newPath;
                    data->pred[v1 * n + v2] = data->pred[u * n + v2];
                }
            }
        }
    }
}

/**
 * APSP API to compute all pairs shortest paths in graph
 *
 * @param data: unique ptr to graph data with allocated fields
 * @param algorithm: algorithm type for APSP
 */
void apsp(const std::unique_ptr<graphAPSPTopology>& data, graphAPSPAlgorithm algorithm) {
    std::function<int(const std::unique_ptr<graphAPSPTopology>&)> algorithms[] = {
            naiveFW,
            cudaNaiveFW,
            cudaBlockedFW
    };
    algorithms[algorithm](data);
}

#include <functional>
#include "apsp.h"
#include "cuda/cuda_apsp.cuh"

/**
 * Naive implementation algorithm Floyd Wharshall for APSP
 *
 * @param data: unique ptr to graph data with allocated fields
 */
static void naiveFW(const std::unique_ptr<graphAPSPTopology>& data) {
    int newPath = 0;
    int n = data->nvertex;

    for(int u=0; u < n; ++u) {
        for(int v1=0; v1 < n; ++v1) {
            for(int v2=0; v2 < n; ++v2) {
                newPath = data->graph[v1 * n + u] + data->graph[u * n + v2];
                if (data->graph[v1 * n + v2] > newPath) {
                    data->graph[v1 * n + v2] = newPath;
                    data->pred[v1 * n + v2] = data->pred[u * n + v2];
                }
            }
        }
    }
}

/**
 * APSP API to compute all pairs shortest paths in graph
 *
 * @param data: unique ptr to graph data with allocated fields
 * @param algorithm: algorithm type for APSP
 */
void apsp(const std::unique_ptr<graphAPSPTopology>& data, graphAPSPAlgorithm algorithm) {
    std::function<void(const std::unique_ptr<graphAPSPTopology>&)> algorithms[] = {
            naiveFW,
            cudaNaiveFW,
            cudaBlockedFW
    };
    algorithms[algorithm](data);
}

Change type of function pointer

Change type of function pointer


#include <iostream>

#include <tightdb/util/terminate.hpp>

using namespace std;

namespace tightdb {
namespace util {

TIGHTDB_NORETURN void terminate(string message, const char* file, long line) TIGHTDB_NOEXCEPT
{
    cerr << file << ":" << line << ": " << message << endl;
    abort();
}

} // namespace util
} // namespace tightdb

#include <iostream>

#ifdef __APPLE__
#include <execinfo.h>
#endif

#include <tightdb/util/terminate.hpp>

using namespace std;

namespace tightdb {
namespace util {

TIGHTDB_NORETURN void terminate(string message, const char* file, long line) TIGHTDB_NOEXCEPT
{
    cerr << file << ":" << line << ": " << message << endl;

#ifdef __APPLE__
    void* callstack[128];
    int frames = backtrace(callstack, 128);
    char** strs = backtrace_symbols(callstack, frames);
    for (int i = 0; i < frames; ++i) {
        cerr << strs[i] << endl;
    }
    free(strs);
#endif

    abort();
}

} // namespace util
} // namespace tightdb

Print a backtrace before terminating on supported platforms


#include "MainWindow.h"
#include <QApplication>

namespace cygnus {

class MainApp : public QApplication {
  QString fileName_{};

  MainWindow *mainWindow_;

public:
  MainApp(int argc, char *argv[])
      : QApplication(argc, argv), mainWindow_(new MainWindow()) {
    mainWindow_->showMaximized();

    if (argc > 1 && argv[1]) {
      fileName_ = argv[1];
    }

    if (!fileName_.isEmpty()) {
      mainWindow_->setFileName(fileName_);
      mainWindow_->loadFile();
    } else {
      mainWindow_->open();
    }
  }

protected:
  bool event(QEvent *event) override {
    switch (event->type()) {
    case QEvent::FileOpen: {
      QFileOpenEvent *fileOpenEvent = static_cast<QFileOpenEvent *>(event);
      if (fileOpenEvent) {
        fileName_ = fileOpenEvent->file();
        if (!fileName_.isEmpty()) {
          if (mainWindow_) {
            mainWindow_->setFileName(fileName_);
          }
          return true;
        }
      }
    }
    default:
      break;
    }
    return QApplication::event(event);
  }
};
}

int main(int argc, char *argv[]) {
  QCoreApplication::setOrganizationName("Cygnus Crosswords");

  cygnus::MainApp a(argc, argv);
  QApplication::processEvents();
  return a.exec();
}

#include "MainWindow.h"
#include <QApplication>

namespace cygnus {

class MainApp : public QApplication {
  QString fileName_{};

  MainWindow *mainWindow_;

public:
  MainApp(int argc, char *argv[])
      : QApplication(argc, argv), mainWindow_(new MainWindow()) {
    mainWindow_->showMaximized();
    QApplication::processEvents();

    if (argc > 1 && argv[1]) {
      fileName_ = argv[1];
    }

    if (!fileName_.isEmpty()) {
      mainWindow_->setFileName(fileName_);
      mainWindow_->loadFile();
    } else {
      mainWindow_->open();
    }
  }

protected:
  bool event(QEvent *event) override {
    switch (event->type()) {
    case QEvent::FileOpen: {
      QFileOpenEvent *fileOpenEvent = static_cast<QFileOpenEvent *>(event);
      if (fileOpenEvent) {
        fileName_ = fileOpenEvent->file();
        if (!fileName_.isEmpty()) {
          if (mainWindow_) {
            mainWindow_->setFileName(fileName_);
          }
          return true;
        }
      }
    }
    default:
      break;
    }
    return QApplication::event(event);
  }
};

} // namespace cygnus

int main(int argc, char *argv[]) {
  QCoreApplication::setOrganizationName("Cygnus Crosswords");

  cygnus::MainApp a(argc, argv);
  return a.exec();
}

Move processEvents call to properly maximize.


#include "../include/parser.h"
#include "../include/exceptions.h"

int main(int argc, const char** argv)
{
    if(argc != 2)
    {
        printf("Arguments: file name.\n");
        exit(1);
    }
    else
    {
        try
        {
           FileAccess * file = new FileAccess(argv[1]);
           TextCursor cursor(file);
           parse_file(cursor);
        }
        catch(FileNotExistsError)
        {
            printf("File not exists.\n");
            exit(2);
        }
    }
}

#include "../include/parser.h"
#include "../include/exceptions.h"

int main(int argc, const char** argv)
{
    if(argc != 2)
    {
        printf("Arguments: file name.\n");
        return 1;
    }
    else
    {
        try
        {
           FileAccess * file = new FileAccess(argv[1]);
           TextCursor cursor(file);
           parse_file(cursor);
        }
        catch(FileNotExistsError)
        {
            printf("File not exists.\n");
            return 2;
        }
    }
    return 0;
}

Use return instead of exit.

Use return instead of exit.


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

struct A {}; // expected-note {{candidate is the implicit copy constructor}}

struct BASE {
  operator A(); // expected-note {{candidate function}}
};

struct BASE1 {
 operator A();  // expected-note {{candidate function}}
};

class B : public BASE , public BASE1
{
  public:
  B();
} b;

extern B f();

const int& ri = (void)0; // expected-error {{reference to type 'int const' could not bind to an rvalue of type 'void'}}

int main() {
        const A& rca = f(); // expected-error {{reference initialization of type 'struct A const &' with initializer of type 'class B' is ambiguous}}
        A& ra = f(); // expected-error {{non-const lvalue reference to type 'struct A' cannot bind to a temporary of type 'class B'}}
}

struct PR6177 { A (&x)[1]; };
PR6177 x = {{A()}}; // expected-error{{non-const lvalue reference to type 'struct A [1]' cannot bind to a temporary of type 'struct A'}}

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

struct A {}; // expected-note {{candidate is the implicit copy constructor}}

struct BASE {
  operator A(); // expected-note {{candidate function}}
};

struct BASE1 {
 operator A();  // expected-note {{candidate function}}
};

class B : public BASE , public BASE1
{
  public:
  B();
} b;

extern B f();

const int& ri = (void)0; // expected-error {{reference to type 'int const' could not bind to an rvalue of type 'void'}}

int main() {
        const A& rca = f(); // expected-error {{reference initialization of type 'struct A const &' with initializer of type 'class B' is ambiguous}}
        A& ra = f(); // expected-error {{non-const lvalue reference to type 'struct A' cannot bind to a temporary of type 'class B'}}
}

struct PR6139 { A (&x)[1]; };
PR6139 x = {{A()}}; // expected-error{{non-const lvalue reference to type 'struct A [1]' cannot bind to a temporary of type 'struct A'}}

Fix PR number in test case

Fix PR number in test case

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


#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;
  try {
    image.magick(FUZZ_ENCODER);
    image.fileName(std::string(FUZZ_ENCODER) + ":");
    image.read(blob);
  }
  catch (Magick::Exception &e) {
    return 0;
  }

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

#include <cstdint>

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

#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;
  }

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

Move these calls otuside the try block, they should never fail


#include "Hostname.hpp"

Hostname::Hostname()
{
}

Hostname::Hostname(const ci_string& hostname)
{
    create(hostname);
}

bool Hostname::isValid()
{
    return !data.empty();
}

void Hostname::create(const ci_string & hostname)
{
    if (isValid())
    {
        throw std::runtime_error("Hostname is defined!");
    }

    data = hostname;

    std::transform(data.begin(), data.end(), data.begin(), std::tolower);
}

void Hostname::destroy()
{
    data.clear();
}

bool Hostname::operator==(const Hostname & other) const
{
    return data == other.data;
}

bool Hostname::operator!=(const Hostname & other) const
{
    return !(*this == other);
}

std::ostream& operator<<(std::ostream& output, const Hostname & hostname)
{
    output << hostname.data.c_str();

    return output;
}

std::istream& operator>>(std::istream& input, Hostname & hostname)
{
    ci_string str;

    std::copy(
        std::istreambuf_iterator<char>(input),
        std::istreambuf_iterator<char>(),
        std::back_inserter(str));

    if (hostname.isValid())
    {
        hostname.destroy();
    }

    hostname.create(str);

    return input;
}

#include "Hostname.hpp"

Hostname::Hostname()
{
}

Hostname::Hostname(const ci_string& hostname)
{
    create(hostname);
}

bool Hostname::isValid()
{
    return !data.empty();
}

void Hostname::create(const ci_string & hostname)
{
    if (isValid())
    {
        throw std::runtime_error("Hostname is defined!");
    }

    data = hostname;

    std::for_each(data.begin(), data.end(),
        [](char& c)
    {
        c = std::tolower(c);
    });
}

void Hostname::destroy()
{
    data.clear();
}

bool Hostname::operator==(const Hostname & other) const
{
    return data == other.data;
}

bool Hostname::operator!=(const Hostname & other) const
{
    return !(*this == other);
}

std::ostream& operator<<(std::ostream& output, const Hostname & hostname)
{
    output << hostname.data.c_str();

    return output;
}

std::istream& operator>>(std::istream& input, Hostname & hostname)
{
    ci_string str;

    std::copy(
        std::istreambuf_iterator<char>(input),
        std::istreambuf_iterator<char>(),
        std::back_inserter(str));

    if (hostname.isValid())
    {
        hostname.destroy();
    }

    hostname.create(str);

    return input;
}

Convert std::transform to std::for_each (not supported by GCC 4.6)


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

#include "Test.h"

// This is a GPU-backend specific test
#if SK_SUPPORT_GPU

#include "GrContextFactory.h"

DEF_GPUTEST(GLInterfaceValidation, reporter, factory) {
    for (int i = 0; i <= GrContextFactory::kLastGLContextType; ++i) {
        GrContextFactory::GLContextType glCtxType = (GrContextFactory::GLContextType)i;
        // this forces the factory to make the context if it hasn't yet
        GrContextFactory::ContextInfo* contextInfo = factory->getContextInfo(glCtxType);
        SkGLContext* glCtx = contextInfo->fGLContext;

        // We're supposed to fail the NVPR context type when we the native context that does not
        // support the NVPR extension.
        if (GrContextFactory::kNVPR_GLContextType == glCtxType &&
            factory->getContextInfo(GrContextFactory::kNative_GLContextType) &&
            !factory->getContextInfo(GrContextFactory::kNative_GLContextType)->fGLContext->gl()->hasExtension("GL_NV_path_rendering")) {
            REPORTER_ASSERT(reporter, nullptr == glCtx);
            continue;
        }

        REPORTER_ASSERT(reporter, glCtx);
        if (glCtx) {
            const GrGLInterface* interface = glCtx->gl();
            REPORTER_ASSERT(reporter, interface->validate());
        }
    }
}

#endif

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

#include "Test.h"

// This is a GPU-backend specific test
#if SK_SUPPORT_GPU

#include "GrContextFactory.h"

DEF_GPUTEST(GLInterfaceValidation, reporter, factory) {
    for (int i = 0; i <= GrContextFactory::kLastGLContextType; ++i) {
        GrContextFactory::GLContextType glCtxType = (GrContextFactory::GLContextType)i;
        // this forces the factory to make the context if it hasn't yet
        GrContextFactory::ContextInfo* contextInfo = factory->getContextInfo(glCtxType);
        SkGLContext* glCtx = contextInfo ? contextInfo->fGLContext : nullptr;

        // We're supposed to fail the NVPR context type when we the native context that does not
        // support the NVPR extension.
        if (GrContextFactory::kNVPR_GLContextType == glCtxType &&
            factory->getContextInfo(GrContextFactory::kNative_GLContextType) &&
            !factory->getContextInfo(GrContextFactory::kNative_GLContextType)->fGLContext->gl()->hasExtension("GL_NV_path_rendering")) {
            REPORTER_ASSERT(reporter, nullptr == glCtx);
            continue;
        }

        REPORTER_ASSERT(reporter, glCtx);
        if (glCtx) {
            const GrGLInterface* interface = glCtx->gl();
            REPORTER_ASSERT(reporter, interface->validate());
        }
    }
}

#endif

Fix GLInterfaceValidation test after "Remove GrContextFactory::getGLContext"

Fix GLInterfaceValidation test crash after "Remove
GrContextFactory::getGLContext" commit.

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


/******************************************************************************
 * Copyright 2017 The Apollo 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 "modules/common/time/time.h"

#include "gmock/gmock.h"
#include "gtest/gtest.h"

namespace apollo {
namespace common {
namespace time {

TEST(TimeTest, MockTime) {
  EXPECT_EQ(Clock::SYSTEM, Clock::mode());
  Clock::SetMode(Clock::MOCK);
  EXPECT_EQ(Clock::MOCK, Clock::mode());

  EXPECT_EQ(0, absl::ToUnixMicros(Clock::Now()));
  Clock::SetNow(absl::FromUnixMicros(123));

  EXPECT_EQ(123, absl::ToUnixMicros(Clock::Now()));

  Clock::SetNowInSeconds(123.456);
  EXPECT_EQ(123.456, Clock::NowInSeconds());
}

}  // namespace time
}  // namespace common
}  // namespace apollo

/******************************************************************************
 * Copyright 2017 The Apollo 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 "modules/common/time/time.h"

#include "gmock/gmock.h"
#include "gtest/gtest.h"

namespace apollo {
namespace common {
namespace time {

TEST(TimeTest, MockTime) {
  EXPECT_EQ(Clock::SYSTEM, Clock::mode());
  Clock::SetMode(Clock::MOCK);
  EXPECT_EQ(Clock::MOCK, Clock::mode());
  EXPECT_EQ(0, absl::ToUnixMicros(Clock::Now()));

  Clock::SetNow(absl::FromUnixNanos(1));
  EXPECT_EQ(1, absl::ToUnixNanos(Clock::Now()));

  Clock::SetNowInSeconds(123.456);
  EXPECT_DOUBLE_EQ(123.456, Clock::NowInSeconds());
}

}  // namespace time
}  // namespace common
}  // namespace apollo

Test SetNow in nano seconds.

Common: Test SetNow in nano seconds.


// RUN: %clang_cc1 -emit-llvm -std=c++11 -g %s -o - | FileCheck %s
// CHECK: metadata !"_ZN1A3fooEiS_3$_0", {{.*}}, i32 258
// CHECK: ""{{.*}}DW_TAG_arg_variable
// CHECK: ""{{.*}}DW_TAG_arg_variable
// CHECK: ""{{.*}}DW_TAG_arg_variable
union {
  int a;
  float b;
} u;

class A {
protected:
  void foo(int, A, decltype(u));
};

void A::foo(int, A, decltype(u)) {
}

A a;

// RUN: %clang_cc1 -emit-llvm -std=c++11 -g %s -o - | FileCheck %s
// CHECK: metadata !"_ZN1A3fooEiS_3$_0", {{.*}} [protected]
// CHECK: ""{{.*}}DW_TAG_arg_variable
// CHECK: ""{{.*}}DW_TAG_arg_variable
// CHECK: ""{{.*}}DW_TAG_arg_variable
union {
  int a;
  float b;
} u;

class A {
protected:
  void foo(int, A, decltype(u));
};

void A::foo(int, A, decltype(u)) {
}

A a;

Make checking for 'protected' access in debug info more legible.

Based on code review feedback for r171604 from Chandler Carruth &
Eric Christopher. Enabled by improvements to LLVM made in r171636.

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


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

#include "mitkVtkShaderProgram.h"
#include "vtkShader2.h"

mitk::VtkShaderProgram::VtkShaderProgram()
{
}

mitk::VtkShaderProgram::~VtkShaderProgram()
{
}

void mitk::VtkShaderProgram::SetVtkShaderProgram(vtkShaderProgram2* p) { m_VtkShaderProgram = p; }

vtkShaderProgram2*mitk::VtkShaderProgram::GetVtkShaderProgram() const { return m_VtkShaderProgram; }

itk::TimeStamp&mitk::VtkShaderProgram::GetShaderTimestampUpdate(){return m_ShaderTimestampUpdate;}

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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

#include "mitkVtkShaderProgram.h"
#include "vtkShader2.h"

mitk::VtkShaderProgram::VtkShaderProgram()
  : m_VtkShaderProgram(NULL)
{
}

mitk::VtkShaderProgram::~VtkShaderProgram()
{
}

void mitk::VtkShaderProgram::SetVtkShaderProgram(vtkShaderProgram2* p) { m_VtkShaderProgram = p; }

vtkShaderProgram2*mitk::VtkShaderProgram::GetVtkShaderProgram() const { return m_VtkShaderProgram; }

itk::TimeStamp&mitk::VtkShaderProgram::GetShaderTimestampUpdate(){return m_ShaderTimestampUpdate;}

Initialize shader program member to with NULL.


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

#include "SkSGImage.h"

#include "SkCanvas.h"
#include "SkImage.h"

namespace sksg {

Image::Image(sk_sp<SkImage> image) : fImage(std::move(image)) {}

void Image::onRender(SkCanvas* canvas) const {
    SkPaint paint;
    paint.setAntiAlias(fAntiAlias);
    paint.setFilterQuality(fQuality);

    canvas->drawImage(fImage, 0, 0);
}

SkRect Image::onRevalidate(InvalidationController*, const SkMatrix& ctm) {
    return SkRect::Make(fImage->bounds());
}

} // namespace sksg

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

#include "SkSGImage.h"

#include "SkCanvas.h"
#include "SkImage.h"

namespace sksg {

Image::Image(sk_sp<SkImage> image) : fImage(std::move(image)) {}

void Image::onRender(SkCanvas* canvas) const {
    SkPaint paint;
    paint.setAntiAlias(fAntiAlias);
    paint.setFilterQuality(fQuality);

    canvas->drawImage(fImage, 0, 0, &paint);
}

SkRect Image::onRevalidate(InvalidationController*, const SkMatrix& ctm) {
    return SkRect::Make(fImage->bounds());
}

} // namespace sksg

Fix image filter quality handling

[sksg] Fix image filter quality handling

TBR=

Change-Id: I06bd30650f1a9d70225b3e3374313f672dae3a8d
Reviewed-on: https://skia-review.googlesource.com/144343
Reviewed-by: Florin Malita <a8262bf13ea8c26821e91ea9bca6740a77c96dcd@chromium.org>
Commit-Queue: Florin Malita <a8262bf13ea8c26821e91ea9bca6740a77c96dcd@chromium.org>


#include "document.hpp"

Document::Document(const std::string & filename) : _filename(filename) {}

Document::~Document() {}

std::string Document::filename(void) const {
	return _filename;
}

void Document::append_paragraph(Paragraph * p) {
	_paragraph.push_back(p);
}

size_t Document::size(void) const {
	return _paragraph.size();
}

Paragraph* Document::operator[](size_t index) const {
	if (index < _paragraph.size()) {
		return _paragraph[index];
	} else {
		return nullptr;
	}
}

#include "document.hpp"

Document::Document(const std::string & filename) : _filename(filename) {}

Document::~Document() {}

std::string Document::filename(void) const {
	return _filename;
}

void Document::append_paragraph(Paragraph * p) {
	if (p and p->size()) {
		_paragraph.push_back(p);
	}
}

size_t Document::size(void) const {
	return _paragraph.size();
}

Paragraph* Document::operator[](size_t index) const {
	if (index < _paragraph.size()) {
		return _paragraph[index];
	} else {
		return nullptr;
	}
}

Check the paragraph for its existence and size


//===-- GCMetadataPrinter.cpp - Garbage collection infrastructure ---------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the abstract base class GCMetadataPrinter.
//
//===----------------------------------------------------------------------===//

#include "llvm/CodeGen/GCMetadataPrinter.h"
class MCAsmInfo;
using namespace llvm;

GCMetadataPrinter::GCMetadataPrinter() { }

GCMetadataPrinter::~GCMetadataPrinter() { }

void GCMetadataPrinter::beginAssembly(raw_ostream &OS, AsmPrinter &AP,
                                      const MCAsmInfo &MAI) {
  // Default is no action.
}

void GCMetadataPrinter::finishAssembly(raw_ostream &OS, AsmPrinter &AP,
                                       const MCAsmInfo &MAI) {
  // Default is no action.
}

//===-- GCMetadataPrinter.cpp - Garbage collection infrastructure ---------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the abstract base class GCMetadataPrinter.
//
//===----------------------------------------------------------------------===//

#include "llvm/CodeGen/GCMetadataPrinter.h"
using namespace llvm;

GCMetadataPrinter::GCMetadataPrinter() { }

GCMetadataPrinter::~GCMetadataPrinter() { }

void GCMetadataPrinter::beginAssembly(raw_ostream &OS, AsmPrinter &AP,
                                      const MCAsmInfo &MAI) {
  // Default is no action.
}

void GCMetadataPrinter::finishAssembly(raw_ostream &OS, AsmPrinter &AP,
                                       const MCAsmInfo &MAI) {
  // Default is no action.
}

Remove pointless forward declaration, MSVC got confused by this.

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


#include "common.h"

uint8_t packet[64];

int main(void)
{
	DCO::init();
	ACLK::init();
	SMCLK::init();
	MCLK::init();
	WDT::init();
	WDT::enable_irq();

	PORT1::init();
	PORT2::init();
	LED_RED::set_high();
#ifndef __MSP430_HAS_USCI__
	TIMER::init();
#endif
	UART::init();
	printf<UART>("CC110X example start.\n");

	SPI::init();
	CC1101::reset();
	CC1101::init(cc110x_default_init_values, ARRAY_COUNT(cc110x_default_init_values));
	LED_RED::set_low();
	while (1) {
		CC1101::rx_buffer(packet, sizeof(packet));
		LED_RED::set_high();
		TIMEOUT::set_and_wait(50);
		LED_RED::set_low();
	}
}

#include "common.h"

uint8_t packet[64];

int main(void)
{
	DCO::init();
	ACLK::init();
	SMCLK::init();
	MCLK::init();
	WDT::init();
	WDT::enable_irq();

	PORT1::init();
	PORT2::init();
	LED_RED::set_high();
#ifndef __MSP430_HAS_USCI__
	TIMER::init();
#endif
	UART::init();
	printf<UART>("CC110X example start.\n");

	SPI::init();
	CC1101::reset();
	CC1101::init(cc110x_default_init_values, ARRAY_COUNT(cc110x_default_init_values));
	CC1101::start_rx();
	LED_RED::set_low();
	while (1) {
		CC1101::rx_buffer<TIMEOUT_NEVER>(packet, sizeof(packet));
		LED_RED::set_high();
		TIMEOUT::set_and_wait(50);
		LED_RED::set_low();
	}
}

Fix CC1101 example to start RX and use timeouts


#include "YarpStateDirector.hpp"

const int rd::YarpStateDirector::DEFAULT_RATE_MS = 100;

rd::YarpStateDirector::YarpStateDirector(rd::State *state) : StateDirector(state), RateThread(DEFAULT_RATE_MS)
{

}

bool rd::YarpStateDirector::Start()
{
    RD_DEBUG("Starting StateDirector for id %s\n", state->getStateId().c_str());
    active = true;
    state->setup();

    return yarp::os::RateThread::start();
}

bool rd::YarpStateDirector::Stop()
{
    RD_DEBUG("Stopping StateDirector for id %s\n", state->getStateId().c_str());

    active = false;

    yarp::os::RateThread::askToStop();
    yarp::os::RateThread::stop();

    state->cleanup();

    return true;
}

void rd::YarpStateDirector::run()
{
    //RD_DEBUG("Entering loop in StateDirector with id %s\n", state->getStateId().c_str());
    state->loop();
    int condition = state->evaluateConditions();

    if (nextStates.find(condition) != nextStates.end())
    {
        this->Stop();
        nextStates.find(condition)->second->Start();
    }

}

#include "YarpStateDirector.hpp"

const int rd::YarpStateDirector::DEFAULT_RATE_MS = 100;

rd::YarpStateDirector::YarpStateDirector(rd::State *state) : StateDirector(state), RateThread(DEFAULT_RATE_MS)
{

}

bool rd::YarpStateDirector::Start()
{
    RD_DEBUG("Starting StateDirector for id %s\n", state->getStateId().c_str());
    active = true;
    state->setup();

    return yarp::os::RateThread::start();
}

bool rd::YarpStateDirector::Stop()
{
    RD_DEBUG("Stopping StateDirector for id %s\n", state->getStateId().c_str());

    active = false;

    yarp::os::RateThread::askToStop();
    yarp::os::RateThread::stop();

    state->cleanup();

    return true;
}

void rd::YarpStateDirector::run()
{
    //RD_DEBUG("Entering loop in StateDirector with id %s\n", state->getStateId().c_str());
    if ( !state->loop() )
    {
        RD_ERROR("Error in loop. Stopping this state...\n");
        this->Stop();
    }
    int condition = state->evaluateConditions();

    if (nextStates.find(condition) != nextStates.end())
    {
        this->Stop();
        nextStates.find(condition)->second->Start();
    }

}

Check loop return value to stop the FSM if false


// Copyright (c) 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 "config.h"
#include "PluginData.h"

#include "PluginInfoStore.h"

#undef LOG
#include "webkit/glue/glue_util.h"
#include "webkit/glue/webkit_glue.h"

namespace WebCore {

static bool refreshData = false;

void PluginData::initPlugins()
{
    std::vector<WebPluginInfo> plugins;
    if (!webkit_glue::GetPlugins(refreshData, &plugins))
        return;
    refreshData = false;

    PluginInfoStore c;
    for (size_t i = 0; i < plugins.size(); ++i) {
        PluginInfo* info = c.createPluginInfoForPluginAtIndex(i);
        m_plugins.append(info);
    }
}

void PluginData::refresh()
{
    // When next we initialize a PluginData, it'll be fresh.
    refreshData = true;
}

}

// Copyright (c) 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "config.h"
#include "PluginData.h"

#include "PluginInfoStore.h"

namespace WebCore {

void PluginData::initPlugins()
{
    PluginInfoStore c;
    for (size_t i = 0; i < c.pluginCount(); ++i)
        m_plugins.append(c.createPluginInfoForPluginAtIndex(i));
}

void PluginData::refresh()
{
    refreshPlugins(true);
}

}

Fix plugin data refreshing to work again.

R=ojan

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

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


#include <cstdio>
#include <cstdlib>
#include <signal.h>
#include <unistd.h>

#include "Updater.h"

static int DaemonPID = -1;

int RunDaemon(void *Arg) {
  while (1) {
    printf("daemon is running...\n");
    sleep(1);
  }
  return 0;
}

int StartDaemon() {
	static const int ChildStackSize = 1024 * 1024;
	char *ChildStack = (char *)malloc(ChildStackSize);
	if (!ChildStack) {
		perror("malloc");
		return -1;
	}

	DaemonPID = clone(RunDaemon, ChildStack + ChildStackSize, CLONE_VM, NULL);
  if (DaemonPID == -1) {
    perror("clone");
    return -1;
  }

	fprintf(stderr, "Daemon PID = %d\n", DaemonPID);
	return 0;
}

int StopDaemon() {
  if (DaemonPID != -1) {
    if (kill(DaemonPID, SIGTERM) == -1) {
      perror("kill");
      return -1;
    }
  }
  return 0;
}

#include <cstdio>
#include <cstdlib>
#include <signal.h>
#include <unistd.h>
#include <sys/prctl.h>

#include "Updater.h"

static int DaemonPID = -1;

int RunDaemon(void *Arg) {
  if (prctl(PR_SET_NAME, "loom-daemon", 0, 0, 0) == -1) {
    perror("prctl");
  }
  while (1) {
    fprintf(stderr, "daemon is running...\n");
    sleep(1);
  }
  return 0;
}

int StartDaemon() {
	static const int ChildStackSize = 1024 * 1024;
	char *ChildStack = (char *)malloc(ChildStackSize);
	if (!ChildStack) {
		perror("malloc");
		return -1;
	}

	DaemonPID = clone(RunDaemon, ChildStack + ChildStackSize, CLONE_VM, NULL);
  if (DaemonPID == -1) {
    perror("clone");
    return -1;
  }

	fprintf(stderr, "Daemon PID = %d\n", DaemonPID);
	return 0;
}

int StopDaemon() {
  if (DaemonPID != -1) {
    if (kill(DaemonPID, SIGTERM) == -1) {
      perror("kill");
      return -1;
    }
  }
  return 0;
}

Change the process name to loom-daemon

Change the process name to loom-daemon


//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// transaction_manager_factory.h
//
// Identification: src/backend/concurrency/transaction_manager_factory.h
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "transaction_manager_factory.h"

namespace peloton {
namespace concurrency {
ConcurrencyType TransactionManagerFactory::protocol_ =
    CONCURRENCY_TYPE_PESSIMISTIC;
IsolationLevelType TransactionManagerFactory::isolation_level_ =
    ISOLATION_LEVEL_TYPE_FULL;
}
}

//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// transaction_manager_factory.h
//
// Identification: src/backend/concurrency/transaction_manager_factory.h
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "transaction_manager_factory.h"

namespace peloton {
namespace concurrency {
ConcurrencyType TransactionManagerFactory::protocol_ =
    CONCURRENCY_TYPE_OPTIMISTIC;
IsolationLevelType TransactionManagerFactory::isolation_level_ =
    ISOLATION_LEVEL_TYPE_FULL;
}
}

Change default txn manager to occ

Change default txn manager to occ


#include "platform.hpp"

#ifndef WIN32

namespace Mirb
{
	namespace Platform
	{
		std::string BenchmarkResult::format()
		{
			std::stringstream result;

			result << ((double)time / 1000) << " ms";

			return result.str();
		}

		void *allocate_region(size_t bytes)
		{
			void *result = mmap(0, bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);

			mirb_runtime_assert(result != 0);

			return result;
		}

		void free_region(void *region, size_t bytes)
		{
			munmap(region, bytes);
		}

		void initialize()
		{
		}
	};
};

#endif

#include "platform.hpp"
#include "../collector.hpp"
#include <signal.h>

#ifndef WIN32

namespace Mirb
{
	namespace Platform
	{
		std::string BenchmarkResult::format()
		{
			std::stringstream result;

			result << ((double)time / 1000) << " ms";

			return result.str();
		}

		void *allocate_region(size_t bytes)
		{
			void *result = mmap(0, bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);

			mirb_runtime_assert(result != 0);

			return result;
		}

		void free_region(void *region, size_t bytes)
		{
			munmap(region, bytes);
		}

		void signal_handler(int)
		{
			Collector::signal();
		}

		void initialize()
		{
			signal(SIGINT, signal_handler);
		}
	};
};

#endif

Interrupt signal handler for POSIX.

Interrupt signal handler for POSIX.


/* 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/xla/legacy_flags/debug_options_flags.h"
#include "tensorflow/core/platform/test.h"

GTEST_API_ int main(int argc, char** argv) {
  std::vector<tensorflow::Flag> flag_list;
  xla::legacy_flags::AppendDebugOptionsFlags(&flag_list);
  string usage = tensorflow::Flags::Usage(argv[0], flag_list);
  if (!tensorflow::Flags::Parse(&argc, argv, flag_list)) {
    LOG(ERROR) << "\n" << usage;
    return 2;
  }

  testing::InitGoogleTest(&argc, argv);
  if (argc > 1) {
    LOG(ERROR) << "Unknown argument " << argv[1] << "\n" << usage;
    return 2;
  }
  return RUN_ALL_TESTS();
}

/* 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/xla/legacy_flags/debug_options_flags.h"
#include "tensorflow/core/platform/test.h"

GTEST_API_ int main(int argc, char** argv) {
  std::vector<tensorflow::Flag> flag_list;
  xla::legacy_flags::AppendDebugOptionsFlags(&flag_list);
  auto usage = tensorflow::Flags::Usage(argv[0], flag_list);
  if (!tensorflow::Flags::Parse(&argc, argv, flag_list)) {
    LOG(ERROR) << "\n" << usage;
    return 2;
  }

  testing::InitGoogleTest(&argc, argv);
  if (argc > 1) {
    LOG(ERROR) << "Unknown argument " << argv[1] << "\n" << usage;
    return 2;
  }
  return RUN_ALL_TESTS();
}

Change type to appease GPU builds.

[XLA] Change type to appease GPU builds.

PiperOrigin-RevId: 163384927


/*
 * This file is part of Peli - universal JSON interaction library
 * Copyright (C) 2014  Alexey Chernov <4ernov@gmail.com>
 *
 * Peli 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 3 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
 *
 */

#include <cassert>

#include "peli/json/value.h"

using namespace std;

using namespace peli;

int main(int argc, char* argv[])
{
	json::value v1(json::make_value<json::object>());
	json::object& obj1(v1);
	obj1["test"] = json::value(52);

	json::value v2(v1);

	assert(v1 == v2);

	json::object& obj2(v2);
	obj2["test"] = json::value(53);

	assert(v1 != v2);

	return 0;
}

/*
 * This file is part of Peli - universal JSON interaction library
 * Copyright (C) 2014  Alexey Chernov <4ernov@gmail.com>
 *
 * Peli 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 3 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
 *
 */

#include <cassert>

#include "peli/json/value.h"

using namespace std;

using namespace peli;

int main(int argc, char* argv[])
{
	json::object a;
	json::value v1(a);
	json::object& obj1(v1);
	obj1["test"] = json::value(52);

	json::value v2(v1);

	assert(v1 == v2);

	json::object& obj2(v2);
	obj2["test"] = json::value(53);

	assert(v1 != v2);

	return 0;
}

Copy constructor test minor fixes

Copy constructor test minor fixes


// An empty test as a placeholder

#include "gtest/gtest.h"

#include <opencv2/core.hpp>
using namespace cv;

#include "AprilTags/Corners.h"
#include "AprilTags/TagFamily.h"
#include "AprilTags/Tag36h11.h"
using namespace AprilTags;

TEST( CornersTest, MakeTagMat ) {
  const int WhichTag = 34;
  const TagCodes &code( AprilTags::tagCodes36h11 );

  const int edge = (int)std::sqrt((float)code.bits);

  Mat tag( Corners::makeTagMat( code.codes[ WhichTag ], edge ));

  EXPECT_EQ( 6, edge );
  EXPECT_EQ( 10, tag.rows );
  EXPECT_EQ( 10, tag.cols );

  Mat huge;
  const double scale = 10.0;
  cv::resize(tag, huge, Size(), scale, scale );

  imwrite("/tmp/tag.jpg", huge);
}

// An empty test as a placeholder

#include "gtest/gtest.h"

#include <opencv2/core.hpp>
using namespace cv;

#include "AprilTags/Corners.h"
#include "AprilTags/TagFamily.h"
#include "AprilTags/Tag36h11.h"
using namespace AprilTags;

TEST( CornersTest, MakeTagMat ) {
  const int WhichTag = 34;
  const TagCodes &code( AprilTags::tagCodes36h11 );

  const int edge = (int)std::sqrt((float)code.bits);

  Mat tag( Corners::makeTagMat( code.codes[ WhichTag ], edge ));

  EXPECT_EQ( 6, edge );
  EXPECT_EQ( 10, tag.rows );
  EXPECT_EQ( 10, tag.cols );

  Mat huge;
  const double scale = 10.0;
  cv::resize( 255*tag, huge, Size(), scale, scale );

  imwrite("/tmp/tag.jpg", huge);
}

Scale tag by 255 when saving sample image.


// RUN: %clang_cc1 -fsyntax-only %s 2>&1|FileCheck %s

// <rdar://problem/9221993>

// We only care to chek whether the compiler crashes; the actual
// diagnostics are uninteresting.
// CHECK: 8 errors generated.
template<class _CharT>     struct char_traits;
template<typename _CharT, typename _Traits = char_traits<_CharT> >     class basic_ios;
template<typename _CharT, typename _Traits = char_traits<_CharT> >     class ostreambuf_iterator;
template<typename _CharT, typename _InIter = istreambuf_iterator<_CharT> >     class num_get;
template<typename _CharT, typename _Traits>     class basic_ostream : virtual public basic_ios<_CharT, _Traits>     {
  template<typename _CharT, typename _InIter>     _InIter     num_get<_CharT, _InIter>::     _M_extract_float(_InIter __beg, _InIter __end, ios_base& __io,        ios_base::iostate& __err, string& __xtrc) const     {
    const bool __plus = __c == __lit[__num_base::_S_iplus];
    if ((__plus || __c == __lit[__num_base::_S_iminus])        && !(__lc->_M_use_grouping && __c == __lc->_M_thousands_sep)        && !(__c == __lc->_M_decimal_point))      {

// RUN: %clang_cc1 -fsyntax-only %s 2>&1|FileCheck %s

// <rdar://problem/9221993>

// We only care to check whether the compiler crashes; the actual
// diagnostics are uninteresting.
// CHECK: 8 errors generated.
template<class _CharT>     struct char_traits;
template<typename _CharT, typename _Traits = char_traits<_CharT> >     class basic_ios;
template<typename _CharT, typename _Traits = char_traits<_CharT> >     class ostreambuf_iterator;
template<typename _CharT, typename _InIter = istreambuf_iterator<_CharT> >     class num_get;
template<typename _CharT, typename _Traits>     class basic_ostream : virtual public basic_ios<_CharT, _Traits>     {
  template<typename _CharT, typename _InIter>     _InIter     num_get<_CharT, _InIter>::     _M_extract_float(_InIter __beg, _InIter __end, ios_base& __io,        ios_base::iostate& __err, string& __xtrc) const     {
    const bool __plus = __c == __lit[__num_base::_S_iplus];
    if ((__plus || __c == __lit[__num_base::_S_iminus])        && !(__lc->_M_use_grouping && __c == __lc->_M_thousands_sep)        && !(__c == __lc->_M_decimal_point))      {

Fix a typo (chek => check)

Fix a typo (chek => check)

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


/*
Author: vpetrigo
Task:

  0.
     ,
,   ,
   .

   ,
 0 (  0    ,      ).

   .

Sample Input 1:
4
4
2
3
0
Sample Output 1:
4

Sample Input 2:
2
1
0
Sample Output 2:
1

*/

#include <iostream>

using namespace std;

int main() {
    int n;
    int max = -1;
    int s_max = -1;

    while (cin >> n && n != 0) {
        if (max <= n) {
            s_max = max;
            max = n;
        }
        else if (s_max < n) {
            s_max = n;
        }
    }

    cout << s_max;

    return 0;
}

/*
Author: vpetrigo
Task:

  0.
     ,
,   ,
   .

   ,
 0 (  0    ,      ).

   .

Sample Input 1:
4
4
2
3
0
Sample Output 1:
4

Sample Input 2:
2
1
0
Sample Output 2:
1

*/

#include <iostream>

using namespace std;

int main() {
    int n;
    int max = -1;
    int s_max = -1;

    while (cin >> n && n != 0) {
        if (max < n) {
            max = n;
        }

        if (n <= max && s_max < n) {
            s_max = n;
        }
    }

    cout << s_max;

    return 0;
}

Revert "Solution for week 3, task 9"

Revert "Solution for week 3, task 9"

This reverts commit 0c5d4740962fa5deb57512e11203fbdff9bb4cb6.


////////////////////////////////////////////////////////////////////////////////
//
// cagey-engine - Toy 3D Engine
// Copyright (c) 2014 Kyle Girard <theycallmecoach@gmail.com>
//
// The MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
////////////////////////////////////////////////////////////////////////////////

#include <cagey/window/WindowFactory.hh>
#include <gtest/gtest.h>

using namespace cagey::window;

TEST(Window, DefaultConstructor) {
  auto win = WindowFactory::createWindow("HelloWorld", VideoMode{640,480});

  SDL_Delay(2000);
}

////////////////////////////////////////////////////////////////////////////////
//
// cagey-engine - Toy 3D Engine
// Copyright (c) 2014 Kyle Girard <theycallmecoach@gmail.com>
//
// The MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
////////////////////////////////////////////////////////////////////////////////

#include <cagey/window/WindowFactory.hh>
#include <gtest/gtest.h>
#include <thread>

using namespace cagey::window;
using namespace std::literals; //need this for fancy chrono_literals

TEST(Window, DefaultConstructor) {
  auto win = WindowFactory::createWindow("HelloWorld", VideoMode{640,480});
  std::this_thread::sleep_for( 2000ms );
}

Use fancy chrono_literals with a this_thread::sleep


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

#include "chrome/renderer/renderer_main_platform_delegate.h"

#include "base/debug_util.h"

// This is a no op class because we do not have a sandbox on linux.

RendererMainPlatformDelegate::RendererMainPlatformDelegate(
    const MainFunctionParams& parameters)
        : parameters_(parameters) {
}

RendererMainPlatformDelegate::~RendererMainPlatformDelegate() {
}

void RendererMainPlatformDelegate::PlatformInitialize() {
}

void RendererMainPlatformDelegate::PlatformUninitialize() {
}

bool RendererMainPlatformDelegate::InitSandboxTests(bool no_sandbox) {
  // The sandbox is started in the zygote process: zygote_main_linux.cc
  // http://code.google.com/p/chromium/wiki/LinuxSUIDSandbox
  return true;
}

bool RendererMainPlatformDelegate::EnableSandbox() {
  // The sandbox is started in the zygote process: zygote_main_linux.cc
  // http://code.google.com/p/chromium/wiki/LinuxSUIDSandbox
  return true;
}

void RendererMainPlatformDelegate::RunSandboxTests() {
  // The sandbox is started in the zygote process: zygote_main_linux.cc
  // http://code.google.com/p/chromium/wiki/LinuxSUIDSandbox
}

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

#include "chrome/renderer/renderer_main_platform_delegate.h"

#include "base/debug_util.h"

// This is a no op class because we do not have a sandbox on linux.

RendererMainPlatformDelegate::RendererMainPlatformDelegate(
    const MainFunctionParams& parameters)
        : parameters_(parameters) {
}

RendererMainPlatformDelegate::~RendererMainPlatformDelegate() {
}

void RendererMainPlatformDelegate::PlatformInitialize() {
  // To make wcstombs/mbstowcs work in a renderer.
  const char* locale = setlocale(LC_ALL, "");
  LOG_IF(WARNING, locale == NULL) << "setlocale failed.";
}

void RendererMainPlatformDelegate::PlatformUninitialize() {
}

bool RendererMainPlatformDelegate::InitSandboxTests(bool no_sandbox) {
  // The sandbox is started in the zygote process: zygote_main_linux.cc
  // http://code.google.com/p/chromium/wiki/LinuxSUIDSandbox
  return true;
}

bool RendererMainPlatformDelegate::EnableSandbox() {
  // The sandbox is started in the zygote process: zygote_main_linux.cc
  // http://code.google.com/p/chromium/wiki/LinuxSUIDSandbox
  return true;
}

void RendererMainPlatformDelegate::RunSandboxTests() {
  // The sandbox is started in the zygote process: zygote_main_linux.cc
  // http://code.google.com/p/chromium/wiki/LinuxSUIDSandbox
}

Call setlocale(LC_ALL, "") in a renderer process for subsequent calls to
SysNativeMBToWide and WideToSysNativeMB (that use mbstowcs and wcstombs) to
work correctly.

This is a clone of http://codereview.chromium.org/155913

BUG=16860 (http://crbug.com/16860 )
TEST=Run Chrome with LC_ALL=en_US.UTF-8 and try to upload a file whose name
contains non-ASCII characters in UTF-8 (e.g. "café.txt" or "一二.txt" ) . The filename field in a form should be populated with the name (rather than empty).

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

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


#include <silicon/api.hh>
#include <silicon/remote_api.hh>
#include <silicon/backends/websocketpp.hh>
#include "symbols.hh"

using namespace s;

int main(int argc, char* argv[])
{
  using namespace sl;
  auto rclient = make_wspp_remote_api(_echo(_text));

  auto server_api = make_api(_echo(_text) = [rclient] (auto p, wspp_connection& con)
  {
    std::cout << p.text << std::endl;
    rclient(con).echo("You just said: " + p.text);
  });

  wspp_json_serve(server_api, atoi(argv[1]));

}

#include <silicon/api.hh>
#include <silicon/remote_api.hh>
#include <silicon/backends/websocketpp.hh>
#include "symbols.hh"

using namespace s;

int main(int argc, char* argv[])
{
  using namespace sl;
  auto rclient = make_wspp_remote_client(_echo(_text));

  auto server_api = make_api(_echo(_text) = [rclient] (auto p, wspp_connection& con)
  {
    std::cout << p.text << std::endl;
    rclient(con).echo("You just said: " + p.text);
  });

  wspp_json_serve(server_api, atoi(argv[1]));

}

Fix websocket echo test compilation.

Fix websocket echo test compilation.


#include "details.hpp"
#include "json/json.h"

dota2::DetailsRequest &dota2::DetailsRequest::id(MatchID id)
{
    query.insert({"match_id", std::to_string(id)});
    return *this;
}

dota2::Details::Details(const Json::Value &json)
{
    matchID = json["result"]["match_id"].asInt();
    startTime = timePoint(json["result"]["start_time"].asInt64());
    firstBloodTime = timePoint(json["result"]["first_blood_time"].asInt64());
    if(json["result"]["radiant_win"].asBool())
    {
        winningTeam = Team::RADIANT;
    }
    else
    {
        winningTeam = Team::DIRE;
    }
}

dota2::MatchID dota2::Details::getMatchID() const
{
    return matchID;
}

dota2::Team dota2::Details::getWinningTeam() const
{
    return winningTeam;
}

dota2::Details::timePoint dota2::Details::getStartTime() const
{
    return startTime;
}

dota2::Details::timePoint dota2::Details::getFirstBloodTime() const
{
    return firstBloodTime;
}

#include "details.hpp"
#include "json/json.h"

dota2::DetailsRequest &dota2::DetailsRequest::id(MatchID id)
{
    query.insert({"match_id", std::to_string(id)});
    return *this;
}

dota2::Details::Details(const Json::Value &json)
{
    const auto& result = json["result"];

    matchID = result["match_id"].asInt();
    startTime = timePoint(result["start_time"].asInt64());
    firstBloodTime = timePoint(result["first_blood_time"].asInt64());
    if(result["radiant_win"].asBool())
    {
        winningTeam = Team::RADIANT;
    }
    else
    {
        winningTeam = Team::DIRE;
    }
}

dota2::MatchID dota2::Details::getMatchID() const
{
    return matchID;
}

dota2::Team dota2::Details::getWinningTeam() const
{
    return winningTeam;
}

dota2::Details::timePoint dota2::Details::getStartTime() const
{
    return startTime;
}

dota2::Details::timePoint dota2::Details::getFirstBloodTime() const
{
    return firstBloodTime;
}

Save json lookup in variable

Save json lookup in variable


/*
 * Copyright 2011 Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 */

#include <QtDeclarative/QDeclarativeEngine>
#include <QDeclarativeContext>
#include "contacts.h"
#include "peoplemodel.h"
#include "proxymodel.h"

void contacts::registerTypes(const char *uri)
{
    qmlRegisterType<PeopleModel>(uri, 0, 0, "PeopleModel");
    qmlRegisterType<ProxyModel>(uri, 0, 0, "ProxyModel");
}

void contacts::initializeEngine(QDeclarativeEngine *engine, const char *uri)
{
    qDebug() << "MeeGo Contacts initializeEngine" << uri;
    Q_ASSERT(engine);

    mRootContext = engine->rootContext();
    Q_ASSERT(mRootContext);

    mRootContext->setContextProperty(QString::fromLatin1("settingsDataStore"),
                                     SettingsDataStore::self());
    mRootContext->setContextProperty(QString::fromLatin1("localeUtils"),
                                     LocaleUtils::self());
}

Q_EXPORT_PLUGIN(contacts);

/*
 * Copyright 2011 Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 */

#include <QtDeclarative/QDeclarativeEngine>
#include <QDeclarativeContext>
#include "contacts.h"
#include "peoplemodel.h"
#include "proxymodel.h"

void contacts::registerTypes(const char *uri)
{
    qmlRegisterType<PeopleModel>(uri, 0, 1, "PeopleModel");
    qmlRegisterType<ProxyModel>(uri, 0, 1, "ProxyModel");
}

void contacts::initializeEngine(QDeclarativeEngine *engine, const char *uri)
{
    qDebug() << "MeeGo Contacts initializeEngine" << uri;
    Q_ASSERT(engine);

    mRootContext = engine->rootContext();
    Q_ASSERT(mRootContext);

    mRootContext->setContextProperty(QString::fromLatin1("settingsDataStore"),
                                     SettingsDataStore::self());
    mRootContext->setContextProperty(QString::fromLatin1("localeUtils"),
                                     LocaleUtils::self());
}

Q_EXPORT_PLUGIN(contacts);

Fix version number of libContacts plugin

Version number was incoherent between the library and the .qml files.
Without this fix the imports in .qml files fail when Qt 4.8 is in use.


#include <node.h>
#include <v8.h>
#include <iostream>
#include <string>

using namespace v8;
using namespace std;

Handle<Value> Prompt(const Arguments& args) {
  HandleScope scope;
  string retval;
  cin >> retval;
  return scope.Close(String::New(retval.c_str()));
}

void init(Handle<Object> exports) {
  exports->Set(String::NewSymbol("prompt"),
      FunctionTemplate::New(Prompt)->GetFunction());
}

NODE_MODULE(sync_prompt, init)

#include <node.h>
#include <v8.h>
#include <iostream>
#include <string>

using namespace v8;
using namespace std;

Handle<Value> Prompt(const Arguments& args) {
  HandleScope scope;
  string retval;
  getline(cin, retval);
  return scope.Close(String::New(retval.c_str()));
}

void init(Handle<Object> exports) {
  exports->Set(String::NewSymbol("prompt"),
      FunctionTemplate::New(Prompt)->GetFunction());
}

NODE_MODULE(sync_prompt, init)

Use getline so program doesn't break functionality in javascript with multiple word inputs


//----------------------------  job_identifier.cc  ---------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 by the deal authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------  job_identifier.cc  ---------------------------

#include <base/job_identifier.h>
#include <ctime>
#include <sys/time.h>

#if HAVE_GETHOSTNAME
# include <unistd.h>
#endif

JobIdentifier dealjobid;

JobIdentifier::JobIdentifier()
{
  time_t t = std::time(0);
  id = std::string(program_id());

//TODO:[GK] try to avoid this hack
// It should be possible not to check DEBUG, but there is this
// tedious -ansi, which causes problems with linux headers

#if defined(HAVE_GETHOSTNAME) && !defined(DEBUG)
  char name[100];
  gethostname(name,99);
  id += std::string(name) + std::string(" ");
#endif

  id += std::string(std::ctime(&t));
}

const std::string
JobIdentifier::operator ()() const
{
  return id;
}

//----------------------------  job_identifier.cc  ---------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 by the deal authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------  job_identifier.cc  ---------------------------

#include <base/job_identifier.h>
#include <ctime>
#include <sys/time.h>

#if HAVE_GETHOSTNAME
# include <unistd.h>
#endif

JobIdentifier dealjobid;

JobIdentifier::JobIdentifier()
{
  time_t t = std::time(0);
  id = std::string(program_id());

//TODO:[GK] try to avoid this hack
// It should be possible not to check DEBUG, but there is this
// tedious -ansi, which causes problems with linux headers

#if defined(HAVE_GETHOSTNAME) && !defined(DEBUG)
  char name[100];
  gethostname(name,99);
  id += std::string(name) + std::string(" ");
#else
  id += std::string("unknown ");
#endif

  id += std::string(std::ctime(&t));
}

const std::string
JobIdentifier::operator ()() const
{
  return id;
}

Use an alternate string if DEBUG isn't set.

git-svn-id: 31d9d2f6432a47c86a3640814024c107794ea77c@9931 0785d39b-7218-0410-832d-ea1e28bc413d


// Chapter 16, exercise 10: function grapher: user can choose among a set of
// functions (e.g., sin() and log(), provide parameters for those functions and
// then graph them

#include "Simple_window.h"
#include "Graph.h"

int main()
try {
    Point tl(400,150);
    Fgraph_window fwin(tl,800,605,"Function Grapher");
    return gui_main();
}
catch (exception& e) {
    cerr << "exception: " << e.what() << endl;
    keep_window_open();
}
catch (...) {
    cerr << "exception\n";
    keep_window_open();
}

// Chapter 16, exercise 10: function grapher: user can choose among a set of
// functions (e.g., sin() and log(), provide parameters for those functions and
// then graph them

#include "../lib_files/Simple_window.h"
#include "../lib_files/Graph.h"

int main()
try {
    Point tl(400,150);
    Fgraph_window fwin(tl,800,605,"Function Grapher");
    return gui_main();
}
catch (exception& e) {
    cerr << "exception: " << e.what() << endl;
    keep_window_open();
}
catch (...) {
    cerr << "exception\n";
    keep_window_open();
}

Update Chapter 16, exercise 10

Update Chapter 16, exercise 10


// REQUIRES: x86-registered-target
// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -O1 -fmerge-functions -emit-llvm -o - -x c++ < %s | FileCheck %s

// Basic functionality test. Function merging doesn't kick in on functions that
// are too simple.

struct A {
  virtual int f(int x, int *p) { return x ? *p : 1; }
  virtual int g(int x, int *p) { return x ? *p : 1; }
} a;

// CHECK: define {{.*}} @_ZN1A1gEiPi
// CHECK-NEXT: tail call i32 @_ZN1A1fEiPi
// CHECK-NEXT: ret

// REQUIRES: x86-registered-target
// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -O1 -fmerge-functions -emit-llvm -o - -x c++ < %s | FileCheck %s -implicit-check-not=_ZN1A1gEiPi

// Basic functionality test. Function merging doesn't kick in on functions that
// are too simple.

struct A {
  virtual int f(int x, int *p) { return x ? *p : 1; }
  virtual int g(int x, int *p) { return x ? *p : 1; }
} a;

// CHECK: define {{.*}} @_ZN1A1fEiPi

Update clang test for r350939

[MergeFunc] Update clang test for r350939

In r350939, the MergeFunc pass learned to erase duplicate functions
which are discardable if unused.

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


#include <test.hpp>

TEST_CASE("default constructed varint_iterators are equal") {
    protozero::const_varint_iterator<uint32_t> a{};
    protozero::const_varint_iterator<uint32_t> b{};

    protozero::iterator_range<protozero::const_varint_iterator<uint32_t>> r{};

    REQUIRE(a == a);
    REQUIRE(a == b);
    REQUIRE(a == r.begin());
    REQUIRE(a == r.end());
    REQUIRE(r.empty());
    REQUIRE(r.size() == 0);
    REQUIRE(r.begin() == r.end());
}

#include <test.hpp>

TEST_CASE("default constructed varint_iterators are equal") {
    protozero::const_varint_iterator<uint32_t> a{};
    protozero::const_varint_iterator<uint32_t> b{};

    protozero::iterator_range<protozero::const_varint_iterator<uint32_t>> r{};

    REQUIRE(a == a);
    REQUIRE(a == b);
    REQUIRE(a == r.begin());
    REQUIRE(a == r.end());
    REQUIRE(r.empty());
    REQUIRE(r.size() == 0); // NOLINT(readability-container-size-empty)
    REQUIRE(r.begin() == r.end());
}

Test code must call functions that it wants to test.


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    int getDecimalValue(ListNode* head) {
        std::vector<int> v;
        while (head) {
            v.emplace_back(head->val);
            head = head->next;
        }
        int ret = 0, index = 1;
        for (int i = 0; i < v.size(); ++i) {
            ret += v[v.size()-i-1] * index;
            index *= 2;
        }
        return ret;
    }
};

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    int getDecimalValue(ListNode* head) {
        std::vector<int> nums;
        nums.reserve(30);
        while (head) {
            nums.emplace_back(head->val);
            head = head->next;
        }
        int mul = 1;
        int ret = 0;
        for (int i = nums.size()-1; i >= 0; --i) {
            ret += mul * nums[i];
            mul *= 2;
        }
        return ret;
    }
};

Convert Binary Number in a Linked List to Integer


#include <gloperate/gloperate.h>

#include <cpplocate/cpplocate.h>

namespace
{

std::string determineDataPath()
{
    std::string path = cpplocate::locatePath("data/gloperate", "share/gloperate", reinterpret_cast<void *>(&gloperate::dataPath));
    if (path.empty()) path = "./data";
    else              path = path + "/data";

    return path;
}

std::string getDirectoryPath(const std::string & fullpath)
{
    if (fullpath.empty())
    {
        return "";
    }

    auto pos           = fullpath.rfind("/");
    const auto posBack = fullpath.rfind("\\");

    if (pos == std::string::npos || (posBack != std::string::npos && posBack > pos))
    {
        pos = posBack;
    }

    return fullpath.substr(0, pos);
}

std::string determinePluginPath()
{
    std::string path = getDirectoryPath(cpplocate::getLibraryPath(reinterpret_cast<void *>(&gloperate::dataPath)));

    return path;
}

} // namespace

namespace gloperate
{

const std::string & dataPath()
{
    static const auto path = determineDataPath();

    return path;
}

const std::string & pluginPath()
{
    static const auto path = determinePluginPath();

    return path;
}

} // namespace gloperate

#include <gloperate/gloperate.h>

#include <cppassist/fs/FilePath.h>

#include <cpplocate/cpplocate.h>

namespace
{

std::string determineDataPath()
{
    std::string path = cpplocate::locatePath("data/gloperate", "share/gloperate", reinterpret_cast<void *>(&gloperate::dataPath));
    if (path.empty()) path = "./data";
    else              path = path + "/data";

    return path;
}

std::string determinePluginPath()
{
    std::string path = cppassist::FilePath(cpplocate::getLibraryPath(reinterpret_cast<void *>(&gloperate::dataPath))).directoryPath();
    path = cppassist::FilePath(path).path();

    return path;
}

} // namespace

namespace gloperate
{

const std::string & dataPath()
{
    static const auto path = determineDataPath();

    return path;
}

const std::string & pluginPath()
{
    static const auto path = determinePluginPath();

    return path;
}

} // namespace gloperate

Use cppassist to determine path

Use cppassist to determine path


#include "SkTypeface.h"

// ===== Begin Chrome-specific definitions =====

uint32_t SkTypeface::UniqueID(const SkTypeface* face)
{
    return NULL;
}

void SkTypeface::serialize(SkWStream* stream) const {
}

SkTypeface* SkTypeface::Deserialize(SkStream* stream) {
  return NULL;
}

// ===== End Chrome-specific definitions =====

#include "SkTypeface.h"

// ===== Begin Chrome-specific definitions =====

uint32_t SkTypeface::UniqueID(const SkTypeface* face)
{
    return 0;
}

void SkTypeface::serialize(SkWStream* stream) const {
}

SkTypeface* SkTypeface::Deserialize(SkStream* stream) {
  return NULL;
}

// ===== End Chrome-specific definitions =====

Return 0 instead of NULL for a non-pointer type.  Eliminates a warning in GCC.

git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@981 4ff67af0-8c30-449e-8e8b-ad334ec8d88c


/*
 *
 * Copyright 2015 gRPC authors.
 *
 * 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 <grpc/support/port_platform.h>

#include "src/core/lib/surface/init.h"

void grpc_security_pre_init(void) {}

void grpc_register_security_filters(void) {}

void grpc_security_init(void) {}

/*
 *
 * Copyright 2015 gRPC authors.
 *
 * 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 <grpc/support/port_platform.h>

#include <grpc/support/log.h>

#include "src/core/lib/surface/init.h"

void grpc_security_pre_init(void) {}

void grpc_register_security_filters(void) {}

void grpc_security_init(void) {
  gpr_log(GPR_DEBUG,
          "Using insecure gRPC build. Security handshakers will not be invoked "
          "even if secure credentials are used.");
}

Add log for insecure buils

Add log for insecure buils


#include "../quick.hpp"
#include "../swap.hpp"

void quick(int *data, const int size_of_data)
{
    return quick(data, 0, size_of_data - 1);
}

void quick(int *data, const int start, const int end)
{
    int size = end - start + 1;

    if(start >= end) return; /* Base case */

    /* Conquer */
    int pivot = partition(data, start, end);

    /* Divide */
    quick(data, start, pivot - 1);
    quick(data, pivot + 1, end);
}

int partition(int *data, const int start, const int end)
{
    int pivot = end; /* Set pivot */

    int ps = start, pe = end - 1;
    while(ps < pe)
    {
        while(ps < pe && data[ps] < data[pivot]) ++ps;
        while(ps < pe && data[pe] >= data[pivot]) --pe;

        if(ps < pe) swap(data[ps], data[pe]);
    }

    if(data[pe] > data[pivot])
        swap(data[pe], data[pivot]);
    else if(pe == end - 1)
        ++pe;

    return pe;
}

#include "../quick.hpp"
#include "../swap.hpp"

void quick(int *data, const int size_of_data)
{
    return quick(data, 0, size_of_data - 1);
}

void quick(int *data, const int start, const int end)
{
    int size = end - start + 1;

    if(start >= end) return; /* Base case */

    /* Conquer */
    int pivot = partition(data, start, end);

    /* Divide */
    quick(data, start, pivot - 1);
    quick(data, pivot + 1, end);
}

int partition(int *data, const int start, const int end)
{
    int pivot = end; /* Set pivot */

    int ps = start,
        pe = end - 1;

    while(ps != pe)
    {
        while(ps < pe && data[ps] < data[pivot]) ++ps;
        while(ps < pe && data[pe] >= data[pivot]) --pe;

        if(ps < pe) swap(data[ps], data[pe]);
    }

    if(data[pivot] < data[pe])
    {
        swap(data[pivot], data[pe]);
        pivot = pe;
    }

    return pivot;
}

Change partition() to return pivot instead of pe


#include "OI.h"
#include "RobotMap.h"
#include "Commands/ElevatorUpCommand.h"
#include "Commands/ElevatorDownCommand.h"

OI::OI() : joystick(JOYSTICK)
{
	// Process operator interface input here.
}

#include "OI.h"
#include "RobotMap.h"

OI::OI() : joystick(JOYSTICK)
{
	// Process operator interface input here.
}

Remove Elevatorup/down command from oi

Remove Elevatorup/down command from oi


#include "NOTDocumentIterator.h"

using namespace sf1r;
using namespace std;

NOTDocumentIterator::NOTDocumentIterator()
{
   setNot(true);
}

NOTDocumentIterator::~NOTDocumentIterator()
{
}

void NOTDocumentIterator::add(DocumentIterator* pDocIterator)
{
    docIteratorList_.push_back(pDocIterator);
}

bool NOTDocumentIterator::next()
{
    return do_next();
}

#include "NOTDocumentIterator.h"

using namespace sf1r;
using namespace std;

NOTDocumentIterator::NOTDocumentIterator()
{
}

NOTDocumentIterator::~NOTDocumentIterator()
{
}

void NOTDocumentIterator::add(DocumentIterator* pDocIterator)
{
    docIteratorList_.push_back(pDocIterator);
}

bool NOTDocumentIterator::next()
{
    return do_next();
}

Revert "small fix to make notQuery working proper"

This reverts commit 494a230b4e9eaab4e3b197bc6706ead2f5c0b44c.


//===-- ModuleProvider.cpp - Base implementation for module providers -----===//
//
// Minimal implementation of the abstract interface for providing a module.
//
//===----------------------------------------------------------------------===//

#include "llvm/ModuleProvider.h"
#include "llvm/Module.h"

/// ctor - always have a valid Module
///
ModuleProvider::ModuleProvider() : TheModule(0) { }

/// dtor - when we leave, we take our Module with us
///
ModuleProvider::~ModuleProvider() {
  delete TheModule;
}

/// materializeFunction - make sure the given function is fully read.
///
void ModuleProvider::materializeModule() {
  if (!TheModule) return;

  for (Module::iterator i = TheModule->begin(), e = TheModule->end();
       i != e; ++i)
    materializeFunction(i);
}

//===-- ModuleProvider.cpp - Base implementation for module providers -----===//
//
// Minimal implementation of the abstract interface for providing a module.
//
//===----------------------------------------------------------------------===//

#include "llvm/ModuleProvider.h"
#include "llvm/Module.h"

/// ctor - always have a valid Module
///
ModuleProvider::ModuleProvider() : TheModule(0) { }

/// dtor - when we leave, we take our Module with us
///
ModuleProvider::~ModuleProvider() {
  delete TheModule;
}

/// materializeFunction - make sure the given function is fully read.
///
Module* ModuleProvider::materializeModule() {
  // FIXME: throw an exception instead?
  if (!TheModule) return 0;

  for (Module::iterator i = TheModule->begin(), e = TheModule->end();
       i != e; ++i)
    materializeFunction(i);

  return TheModule;
}

Return the Module that we just materialized.

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


#include "tclap/CmdLine.h"
#include <vector>
#include <string>

using namespace TCLAP;
using namespace std;

// https://sourceforge.net/p/tclap/bugs/30/
int main(int argc, char** argv) {
  CmdLine cmd("test empty argv");
  std::vector<string> args;
  cmd.parse(args);
}

#include "tclap/CmdLine.h"
#include <vector>
#include <string>

using namespace TCLAP;
using namespace std;

// https://sourceforge.net/p/tclap/bugs/30/
int main() {
  CmdLine cmd("test empty argv");
  std::vector<string> args;
  cmd.parse(args);
}

Remove unused arguments from test (fix warnings).


#include <iostream>
#include <string>
#include "MatasanoConverter.h"
using namespace std;

int main() {
	string hexInput("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d");
	string testString = ("SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t");
	string result;
	MatasanoConverter m;

	m.loadString(hexInput, "hex");
	result = m.getBase64();

	cout << "Challenge 1: ";
	if (result.compare(testString) == 0) {
		cout << "PASSED" << endl << "Input: " << hexInput << endl << "Output: " << result << endl << "As Required.";
	} else {
		cout << "FAILED" << endl << "Input: " << hexInput << endl << "Expected: " << testString << endl << "Observed: " << result << endl;
	}
}

#include <iostream>
#include <string>
#include "MatasanoConverter.h"
using namespace std;

int main() {
	string hexInput("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d");
	string testString = ("SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t");
	string result;
	MatasanoConverter m;

	m.loadString(hexInput, "hex");
	result = m.getStringOutput("b64");

	cout << "Challenge 1: ";
	if (result.compare(testString) == 0) {
		cout << "PASSED" << endl << "Input: " << hexInput << endl << "Output: " << result << endl << "As Required." << endl;
	} else {
		cout << "FAILED" << endl << "Input: " << hexInput << endl << "Expected: " << testString << endl << "Observed: " << result << endl;
	}
}

Update to use new getStringOutput function of MatasanoConverter. Add line break after test pass message


#include "Platform.h"

#include <stdio.h>

void testRDTSC ( void )
{
  int64_t temp = rdtsc();

  printf("%d",(int)temp);
}

#if defined(_MSC_VER)

#include <windows.h>

void SetAffinity ( int cpu )
{
  SetProcessAffinityMask(GetCurrentProcess(),cpu);
  SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
}

#else

void SetAffinity ( int /*cpu*/ )
{
}

#endif

#include "Platform.h"

#include <stdio.h>

void testRDTSC ( void )
{
  int64_t temp = rdtsc();

  printf("%d",(int)temp);
}

#if defined(_MSC_VER)

#include <windows.h>

void SetAffinity ( int cpu )
{
  SetProcessAffinityMask(GetCurrentProcess(),cpu);
  SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
}

#else

#include <sched.h>

void SetAffinity ( int /*cpu*/ )
{
  cpu_set_t mask;

  CPU_ZERO(&mask);

  CPU_SET(2,&mask);

  if( sched_setaffinity(0,sizeof(mask),&mask) == -1)
  {
    printf("WARNING: Could not set CPU affinity\n");
  }
}

#endif

Add CPU affinity to gcc build

Add CPU affinity to gcc build


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

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

#if defined(TOOLKIT_VIEWS)
// Need to port ExtensionInfoBarDelegate::CreateInfoBar() to other platforms.
// See http://crbug.com/39916 for details.
#define MAYBE_Infobars Infobars
#else
#define MAYBE_Infobars DISABLED_Infobars
#endif

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

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

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

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

#if defined(TOOLKIT_VIEWS)
#if defined (OS_WIN)
#define MAYBE_Infobars Infobars
#else
// Flaky on ChromeOS, see http://crbug.com/40141.
#define MAYBE_Infobars FLAKY_Infobars
#endif

#else
// Need to port ExtensionInfoBarDelegate::CreateInfoBar() to other platforms.
// See http://crbug.com/39916 for details.
#define MAYBE_Infobars DISABLED_Infobars
#endif

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

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

Mark a test as flaky on ChromeOS.

Mark a test as flaky on ChromeOS.

BUG=40141
TEST=None

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

git-svn-id: http://src.chromium.org/svn/trunk/src@43384 4ff67af0-8c30-449e-8e8b-ad334ec8d88c

Former-commit-id: 249469713d75090125b318f6101a8e42cba15b00


// Windy - main.cpp
// Copyright (c) 2015 Arkadiusz Bokowy
//
// This file is a part of Windy.
//
// This projected is licensed under the terms of the MIT license.

#include "Application.h"

int main(int argc, char *argv[]) {
	Application app(argc, argv);
	return app.exec();
}

// Windy - main.cpp
// Copyright (c) 2015 Arkadiusz Bokowy
//
// This file is a part of Windy.
//
// This projected is licensed under the terms of the MIT license.

#include "Application.h"

#if defined(Q_OS_WIN) && !defined(_DLL)
// This sections allows static build on the Windows platform using MSVC++
// compiler. During the non-DLL build the _DLL is not defined. In such a
// case we will enforce plug-ins to be loaded, which in turn will generate
// linking errors if one omits them.
#include <QtPlugin>
Q_IMPORT_PLUGIN(QSvgIconPlugin)
Q_IMPORT_PLUGIN(QSvgPlugin)
Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin)
#endif // Q_OS_WIN && !_DLL

int main(int argc, char *argv[]) {
	Application app(argc, argv);
	return app.exec();
}

Allow static build on Windows

Allow static build on Windows


#include "motor/esra_payload_motor_mapper.hpp"

#include <array>
#include <cstddef>

#include "protocol/messages.hpp"

EsraPayloadMotorMapper::EsraPayloadMotorMapper(PWMDeviceGroup<1>& motors, Communicator& communicator)
  : motors(motors),
    throttleStream(communicator, 5) {
}

void EsraPayloadMotorMapper::run(bool armed, ActuatorSetpoint& input) {
  // We only have one motor for now, but just in case..
  std::array<float, 1> outputs;
  outputs[0] = input.throttle;
  motors.set(armed, outputs);

  if(throttleStream.ready()) {
    protocol::message::motor_throttle_message_t msg;
    msg.throttles[0] = outputs[0];
    throttleStream.publish(msg);
  }
}

#include "motor/esra_payload_motor_mapper.hpp"

#include <array>
#include <cstddef>

#include "protocol/messages.hpp"

EsraPayloadMotorMapper::EsraPayloadMotorMapper(PWMDeviceGroup<1>& motors, Communicator& communicator)
  : motors(motors),
    throttleStream(communicator, 5) {
}

void EsraPayloadMotorMapper::run(bool armed, ActuatorSetpoint& input) {
  // We only have one motor for now, but just in case..
  std::array<float, 1> outputs;
  outputs[0] = input.throttle;
  motors.set(armed, outputs);

  if(throttleStream.ready()) {
    protocol::message::motor_throttle_message_t msg;
    msg.throttles[0] = outputs[0];
    msg.throttles[1] = 0;
    msg.throttles[2] = 0;
    msg.throttles[3] = 0;
    throttleStream.publish(msg);
  }
}

Set unused throttle message fields to zero.


/** @file
    @brief Implementation

    @date 2014

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

// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)

// Internal Includes
#include <ogvr/Client/CreateContext.h>
#include "VRPNContext.h"

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

// Standard includes
// - none

namespace ogvr {
namespace client {

    ClientContext *createContext(const char appId[], const char host[]) {
        if (!appId || strlen(appId) == 0) {
            return NULL;
        }
        VRPNContext *ret = new VRPNContext(appId, host);
        return ret;
    }

} // namespace client
} // namespace ogvr

/** @file
    @brief Implementation

    @date 2014

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

// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)

// Internal Includes
#include <ogvr/Client/CreateContext.h>
#include "VRPNContext.h"

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

// Standard includes
#include <cstring>

namespace ogvr {
namespace client {

    ClientContext *createContext(const char appId[], const char host[]) {
        if (!appId || std::strlen(appId) == 0) {
            return NULL;
        }
        VRPNContext *ret = new VRPNContext(appId, host);
        return ret;
    }

} // namespace client
} // namespace ogvr

Fix build - missing header.

Fix build - missing header.


#include <bin/tests.hh>
BEGIN_TEST(removecallbacks, client, )
client.setCallback(&dump, "error"); // ping
urbi::UCallbackID i1 = client.setCallback(&dump, "output");
urbi::UCallbackID i2 = client.setCallback(&dump, "output");

SEND("output << 1;");
//= D output 1
//= D output 1
dumpSem--;
dumpSem--;
SEND("error << 1;");   //ping
//= D error 1
dumpSem--;
client.deleteCallback(i1);
SEND("output << 1;");
//= D output 1
SEND("error << 1;");   //ping
//= D error 1
dumpSem--;
dumpSem--;
client.deleteCallback(i2);
SEND("output << 1;"); //no callback left, not displayed
SEND("error << 1;");   //ping
//= D error 1
dumpSem--;
client.setCallback(&removeOnZero, "output");
SEND("output << 1;");
//= D output 1
SEND("output << 0;");
//= D output 0
SEND("output << 1;");
SEND("error << 1;");   //ping
//= D error 1
sleep(5);
END_TEST

#include <bin/tests.hh>
BEGIN_TEST(removecallbacks, client, )
client.setCallback(&dump, "error"); // ping
urbi::UCallbackID i1 = client.setCallback(&dump, "output");
urbi::UCallbackID i2 = client.setCallback(&dump, "output");

SEND("output << 1;");
//= D output 1
//= D output 1
dumpSem--;
dumpSem--;
SEND("error << 2;");   //ping
//= D error 2
dumpSem--;
client.deleteCallback(i1);
SEND("output << 3;");
//= D output 3
SEND("error << 4;");   //ping
//= D error 4
dumpSem--;
dumpSem--;
client.deleteCallback(i2);
SEND("output << 5;"); //no callback left, not displayed
SEND("error << 6;");   //ping
//= D error 6
dumpSem--;
client.setCallback(&removeOnZero, "output");
SEND("output << 7;");
//= D output 7
SEND("output << 0;");
//= D output 0
SEND("output << 9;");
SEND("error << 10;");   //ping
//= D error 10
sleep(5);
END_TEST

Make tests outcome easier to check.

Make tests outcome easier to check.

	* src/tests/checkfiles/removecallbacks.cc: Use different numbers.


#include "MessageQueue.h"

#include <vector>

MessageQueue::MessageQueue(std::string identifier, std::string serverAddr, unsigned int serverPort, std::function<void(std::string) > onMessage)
: identifier(identifier), mqConnection(&mqHandler, "amqp://" + serverAddr + ":" + std::to_string(serverPort)),
channel(&mqConnection) {
    channel.declareQueue(identifier);
    channel.declareExchange("ctlms_exchanger", AMQP::ExchangeType::direct);
    channel.bindQueue("ctlms_exchanger", identifier, "ALL");
    channel.bindQueue("ctlms_exchanger", identifier, identifier);
    channel.consume(identifier).onSuccess([]() {
        std::cout << "Starting to consume messages." << std::endl;
    }).onMessage([onMessage](const AMQP::Message &message, uint64_t deliveryTag, bool redelivered) {
        onMessage(std::string(message.body(), message.bodySize()));
    }).onError([](const char *message) {
        std::cout << "Error with the consumer: " << message << std::endl;
    });
}

MessageQueue::~MessageQueue() {
    channel.removeQueue(identifier);
}

void MessageQueue::update() {
    for (auto fd : mqHandler.fdToMonitor) {
        int count = 0;
        ioctl(fd, FIONREAD, &count);
        if (count > 0) {
            mqConnection.process(fd, AMQP::readable | AMQP::writable);
        }
    }
}

#include "MessageQueue.h"

#include <vector>

MessageQueue::MessageQueue(std::string identifier, std::string serverAddr, unsigned int serverPort, std::function<void(std::string) > onMessage)
: identifier(identifier), mqConnection(&mqHandler, "amqp://" + serverAddr + ":" + std::to_string(serverPort)),
channel(&mqConnection) {
    channel.declareQueue(identifier);
    channel.declareExchange("ctlms_exchanger", AMQP::ExchangeType::direct);
    channel.bindQueue("ctlms_exchanger", identifier, "ALL");
    channel.bindQueue("ctlms_exchanger", identifier, identifier);
    channel.consume(identifier).onSuccess([]() {
        std::cout << "Starting to consume messages." << std::endl;
    }).onMessage([onMessage, this](const AMQP::Message &message, uint64_t deliveryTag, bool redelivered) {
        onMessage(std::string(message.body(), message.bodySize()));
        channel.ack(deliveryTag); // Delete the message from the queue
    }).onError([](const char *message) {
        std::cout << "Error with the consumer: " << message << std::endl;
    });
}

MessageQueue::~MessageQueue() {
    channel.removeQueue(identifier);
}

void MessageQueue::update() {
    for (auto fd : mqHandler.fdToMonitor) {
        int count = 0;
        ioctl(fd, FIONREAD, &count);
        if (count > 0) {
            mqConnection.process(fd, AMQP::readable | AMQP::writable);
        }
    }
}

Delete messages from rabbitmq once received


#include <functional>
#include <iostream>

#include <spdlog/spdlog.h>

#include <docopt/docopt.h>

#include <iostream>

static constexpr auto USAGE =
  R"(Naval Fate.

    Usage:
          naval_fate ship new <name>...
          naval_fate ship <name> move <x> <y> [--speed=<kn>]
          naval_fate ship shoot <x> <y>
          naval_fate mine (set|remove) <x> <y> [--moored | --drifting]
          naval_fate (-h | --help)
          naval_fate --version
 Options:
          -h --help     Show this screen.
          --version     Show version.
          --speed=<kn>  Speed in knots [default: 10].
          --moored      Moored (anchored) mine.
          --drifting    Drifting mine.
)";

int main(int argc, const char **argv)
{
  std::map<std::string, docopt::value> args = docopt::docopt(USAGE,
    { std::next(argv), std::next(argv, argc) },
    true,// show help if requested
    "Naval Fate 2.0");// version string

  for (auto const &arg : args) {
    std::cout << arg.first << arg.second << std::endl;
  }

  //Use the default logger (stdout, multi-threaded, colored)
  spdlog::info("Hello, {}!", "World");

  fmt::print("Hello, from {}\n", "{fmt}");
}

#include <functional>
#include <iostream>

#include <spdlog/spdlog.h>
#include <docopt/docopt.h>

static constexpr auto USAGE =
  R"(Naval Fate.

    Usage:
          naval_fate ship new <name>...
          naval_fate ship <name> move <x> <y> [--speed=<kn>]
          naval_fate ship shoot <x> <y>
          naval_fate mine (set|remove) <x> <y> [--moored | --drifting]
          naval_fate (-h | --help)
          naval_fate --version
 Options:
          -h --help     Show this screen.
          --version     Show version.
          --speed=<kn>  Speed in knots [default: 10].
          --moored      Moored (anchored) mine.
          --drifting    Drifting mine.
)";

int main(int argc, const char **argv)
{
  std::map<std::string, docopt::value> args = docopt::docopt(USAGE,
    { std::next(argv), std::next(argv, argc) },
    true,// show help if requested
    "Naval Fate 2.0");// version string

  for (auto const &arg : args) {
    std::cout << arg.first << arg.second << std::endl;
  }

  //Use the default logger (stdout, multi-threaded, colored)
  spdlog::info("Hello, {}!", "World");

  fmt::print("Hello, from {}\n", "{fmt}");
}

Remove duplicate header in template source file


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

#include "chrome/default_plugin/plugin_main.h"
#include "webkit/plugins/npapi/plugin_list.h"

namespace chrome {

void RegisterInternalDefaultPlugin() {
#if defined(OS_WIN)
  // TODO(bauerb): On Windows the default plug-in can download and install
  // missing plug-ins, which we don't support in the browser yet, so keep
  // using the default plug-in on Windows until we do.
  const webkit::npapi::PluginEntryPoints entry_points = {
#if !defined(OS_POSIX) || defined(OS_MACOSX)
    default_plugin::NP_GetEntryPoints,
#endif
    default_plugin::NP_Initialize,
    default_plugin::NP_Shutdown
  };

  webkit::npapi::PluginList::Singleton()->RegisterInternalPlugin(
      FilePath(webkit::npapi::kDefaultPluginLibraryName),
      "Default Plug-in",
      "Provides functionality for installing third-party plug-ins",
      "*",
      entry_points);
#endif  // defined OS(WIN)
}

}  // namespace chrome

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

#include "chrome/default_plugin/plugin_main.h"
#include "webkit/plugins/npapi/plugin_list.h"

namespace chrome {

void RegisterInternalDefaultPlugin() {
#if defined(OS_WIN) && !defined(USE_AURA)
  // TODO(bauerb): On Windows the default plug-in can download and install
  // missing plug-ins, which we don't support in the browser yet, so keep
  // using the default plug-in on Windows until we do.
  // Aura isn't going to support NPAPI plugins.
  const webkit::npapi::PluginEntryPoints entry_points = {
#if !defined(OS_POSIX) || defined(OS_MACOSX)
    default_plugin::NP_GetEntryPoints,
#endif
    default_plugin::NP_Initialize,
    default_plugin::NP_Shutdown
  };

  webkit::npapi::PluginList::Singleton()->RegisterInternalPlugin(
      FilePath(webkit::npapi::kDefaultPluginLibraryName),
      "Default Plug-in",
      "Provides functionality for installing third-party plug-ins",
      "*",
      entry_points);
#endif
}

}  // namespace chrome

Disable the default plugin for aura

Disable the default plugin for aura

BUG=None
TEST=None

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

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


#include <mart-common/experimental/tmp.h>
#include <tuple>

namespace {

constexpr auto v_list1 = mart::tmp::value_list<int, 1, 2, 3, 4, 5>{};
constexpr auto v_list2 = mart::tmp::value_list<char, 'H', 'e', 'l', 'l', 'o'>{};

static_assert( mart::tmp::get_Nth_element( 2, v_list1 ) == 3 );

template<int First, char Second>
struct Type {
	static constexpr int  first  = First;
	static constexpr char second = Second;
};

template<class... T>
struct type_list
{};

auto mtype = mart::tmp::cartesian_value_product<std::tuple,int,char, Type>( v_list1, v_list2 );

} // namespace

[Test] Add a compilation test for mart::tmp::cartesian_value_product