#include <windows.h>
#include <tchar.h>
#include <stdio.h>

int _tmain(int argc, TCHAR * argv[])
{
	if(1 >= argc)
	{
		_tprintf(_T("DummLoader.exe <DllName>*\n"));
		return 0;
	}

	for(int i=1; i<argc; i++)
	{
		_tprintf(_T("Loading: \"%s\" "), argv[i]);
		HMODULE hm = LoadLibrary(argv[i]);
		_tprintf(_T("[ %s ]\n"), hm ? _T("OK") : _T("FAIL"));
	}

	return 0;
}

#include <windows.h>
#include <tchar.h>
#include <stdio.h>

int _tmain(int argc, TCHAR * argv[])
{
	if(1 >= argc)
	{
		_tprintf(_T("DummLoader.exe <DllName>*\n"));
		return 0;
	}

	for(int i=1; i<argc; i++)
	{
		_tprintf(_T("Loading: \"%s\" "), argv[i]);
		HMODULE hm = LoadLibrary(argv[i]);
		DWORD lastError = GetLastError();
		_tprintf(_T("[ %s ] GetLastError = %u\n"), hm ? _T("OK") : _T("FAIL"), lastError);
	}

	return 0;
}

Add GetLastError info to DummyLoader test


#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "functions.h"
#include "main-screen.h"
#include "models/profile.h"

int main(int argc, char *argv[])
{
	QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

	QGuiApplication app(argc, argv);
	app.setApplicationName("Grabber");
	app.setApplicationVersion(VERSION);
	app.setOrganizationName("Bionus");
	app.setOrganizationDomain("bionus.fr.cr");

	const QUrl url(QStringLiteral("qrc:/main-screen.qml"));

	QQmlApplicationEngine engine;
	QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) {
		if (!obj && url == objUrl) {
			QCoreApplication::exit(-1);
		}
	}, Qt::QueuedConnection);

	Profile profile(savePath());
	MainScreen mainScreen(&profile);
	engine.rootContext()->setContextProperty("backend", &mainScreen);

	engine.load(url);

	return app.exec();
}

#include <QDir>
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "functions.h"
#include "main-screen.h"
#include "models/profile.h"

int main(int argc, char *argv[])
{
	QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

	QGuiApplication app(argc, argv);
	app.setApplicationName("Grabber");
	app.setApplicationVersion(VERSION);
	app.setOrganizationName("Bionus");
	app.setOrganizationDomain("bionus.fr.cr");

	// Copy settings files to writable directory
	const QStringList toCopy { "sites/", "themes/", "webservices/" };
	for (const QString &tgt : toCopy) {
		const QString from = savePath(tgt, true, false);
		const QString to = savePath(tgt, true, true);
		if (!QDir(to).exists() && QDir(from).exists()) {
			copyRecursively(from, to);
		}
	}

	const QUrl url(QStringLiteral("qrc:/main-screen.qml"));

	QQmlApplicationEngine engine;
	QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) {
		if (!obj && url == objUrl) {
			QCoreApplication::exit(-1);
		}
	}, Qt::QueuedConnection);

	Profile profile(savePath());
	MainScreen mainScreen(&profile);
	engine.rootContext()->setContextProperty("backend", &mainScreen);

	engine.load(url);

	return app.exec();
}

Copy necessary assets on Android QML startup


/* The Halfling Project - A Graphics Engine and Projects
 *
 * The Halfling Project is the legal property of Adrian Astley
 * Copyright Adrian Astley 2013
 */

#include "obj_loader_demo/obj_loader_demo.h"

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
	ObjLoaderDemo::ObjLoaderDemo app(hInstance);
	DBG_UNREFERENCED_PARAMETER(hPrevInstance);
	DBG_UNREFERENCED_PARAMETER(lpCmdLine);
	DBG_UNREFERENCED_PARAMETER(nCmdShow);

	app.Initialize(L"OBJ Loader Demo", 800, 600, false);
	app.Run();

	app.Shutdown();

	return 0;
}

/* The Halfling Project - A Graphics Engine and Projects
 *
 * The Halfling Project is the legal property of Adrian Astley
 * Copyright Adrian Astley 2013
 */

#include "obj_loader_demo/obj_loader_demo.h"

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
	ObjLoaderDemo::ObjLoaderDemo app(hInstance);
	DBG_UNREFERENCED_PARAMETER(hPrevInstance);
	DBG_UNREFERENCED_PARAMETER(lpCmdLine);
	DBG_UNREFERENCED_PARAMETER(nCmdShow);

	app.Initialize(L"OBJ Loader Demo", 1280, 720, false);
	app.Run();

	app.Shutdown();

	return 0;
}

OBJ_LOADER_DEMO: Use 1280 x 720 as the default resolution


// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "mmap_file_allocator_factory.h"
#include "mmap_file_allocator.h"
#include <vespa/vespalib/stllike/asciistream.h>

namespace vespalib::alloc {

MmapFileAllocatorFactory::MmapFileAllocatorFactory()
    : _dir_name(),
      _generation(0)
{
}

MmapFileAllocatorFactory::~MmapFileAllocatorFactory()
{
}

void
MmapFileAllocatorFactory::setup(const vespalib::string& dir_name)
{
    _dir_name = dir_name;
    _generation = 0;
}

std::unique_ptr<MemoryAllocator>
MmapFileAllocatorFactory::make_memory_allocator(const vespalib::string& name)
{
    if (_dir_name.empty()) {
        return {};
    }
    vespalib::asciistream os;
    os << _dir_name << "/" << _generation.fetch_add(1) << "." << name;
    return std::make_unique<MmapFileAllocator>(os.str());
};

MmapFileAllocatorFactory&
MmapFileAllocatorFactory::instance()
{
    static MmapFileAllocatorFactory instance;
    return instance;
}

}

// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "mmap_file_allocator_factory.h"
#include "mmap_file_allocator.h"
#include <vespa/vespalib/io/fileutil.h>
#include <vespa/vespalib/stllike/asciistream.h>

namespace vespalib::alloc {

MmapFileAllocatorFactory::MmapFileAllocatorFactory()
    : _dir_name(),
      _generation(0)
{
}

MmapFileAllocatorFactory::~MmapFileAllocatorFactory()
{
}

void
MmapFileAllocatorFactory::setup(const vespalib::string& dir_name)
{
    _dir_name = dir_name;
    _generation = 0;
    if (!_dir_name.empty()) {
        rmdir(_dir_name, true);
    }
}

std::unique_ptr<MemoryAllocator>
MmapFileAllocatorFactory::make_memory_allocator(const vespalib::string& name)
{
    if (_dir_name.empty()) {
        return {};
    }
    vespalib::asciistream os;
    os << _dir_name << "/" << _generation.fetch_add(1) << "." << name;
    return std::make_unique<MmapFileAllocator>(os.str());
};

MmapFileAllocatorFactory&
MmapFileAllocatorFactory::instance()
{
    static MmapFileAllocatorFactory instance;
    return instance;
}

}

Remove old swap files when setting up mmap file allocator.


// TODO: remove this later, hack for include order issues
#include "GLBlaat/GL.h"

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

int main(int argc, char *argv[])
{
	// Set up Qt application
	QApplication app(argc, argv);

	VFE::MainWindow *window = new VFE::MainWindow();

	// Go!
	window->show();
	app.exec();

	// Clean up and exit
	delete window;
	return 0;
}

// TODO: remove this later, hack for include order issues
#include "GLBlaat/GL.h"

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

#include <vtkWin32ProcessOutputWindow.h>

int main(int argc, char *argv[])
{
#ifdef WIN32
	// Use a more useful output window for VTK
	vtkWin32ProcessOutputWindow *ow = vtkWin32ProcessOutputWindow::New();
	vtkWin32ProcessOutputWindow::SetInstance(ow);
	ow->Delete();
#endif

	// Set up Qt application
	QApplication app(argc, argv);

	VFE::MainWindow *window = new VFE::MainWindow();

	// Go!
	window->show();
	app.exec();

	// Clean up and exit
	delete window;
	return 0;
}

Use a VTK output window we can actually read if the app crashes.


/** @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 <osvr/ClientKit/ContextC.h>
#include <osvr/Client/ClientContext.h>
#include <osvr/Client/CreateContext.h>

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

// Standard includes
// - none

OSVR_ClientContext osvrClientInit(const char applicationIdentifier[],
                                  uint32_t /*flags*/) {
    return ::osvr::client::createContext(applicationIdentifier);
}
OSVR_ReturnCode osvrClientUpdate(OSVR_ClientContext ctx) {
    ctx->update();
    return OSVR_RETURN_SUCCESS;
}

OSVR_ReturnCode osvrClientShutdown(OSVR_ClientContext ctx) {
    delete ctx;
    return OSVR_RETURN_SUCCESS;
}

/** @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 <osvr/ClientKit/ContextC.h>
#include <osvr/Client/ClientContext.h>
#include <osvr/Client/CreateContext.h>

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

// Standard includes
// - none

static const char HOST_ENV_VAR[] = "OSVR_HOST";

OSVR_ClientContext osvrClientInit(const char applicationIdentifier[],
                                  uint32_t /*flags*/) {
    char *host = ::getenv(HOST_ENV_VAR);
    if (nullptr != host) {
        return ::osvr::client::createContext(applicationIdentifier, host);
    } else {
        return ::osvr::client::createContext(applicationIdentifier);
    }
}
OSVR_ReturnCode osvrClientUpdate(OSVR_ClientContext ctx) {
    ctx->update();
    return OSVR_RETURN_SUCCESS;
}

OSVR_ReturnCode osvrClientShutdown(OSVR_ClientContext ctx) {
    delete ctx;
    return OSVR_RETURN_SUCCESS;
}

Add a quick and dirty way to access a remote OSVR server: using the environment variable OSVR_HOST.


#include "ShadingLanguageIncludeImplementation_ShadingLanguageIncludeARB.h"

#include <glbinding/gl/functions.h>

#include <globjects/Shader.h>

#include <globjects/base/AbstractStringSource.h>

using namespace gl;

namespace globjects
{

void ShadingLanguageIncludeImplementation_ARB::updateSources(const Shader * shader) const
{
    std::string source;
    if (shader->source()) {
        source = shader->source()->string();
    }

    const char* sourcePtr = source.c_str();
    glShaderSource(shader->id(), static_cast<GLint>(1), &sourcePtr, nullptr);
}

void ShadingLanguageIncludeImplementation_ARB::compile(const Shader * shader) const
{
    std::vector<const char*> cStrings = collectCStrings(shader->includePaths());
    glCompileShaderIncludeARB(shader->id(), static_cast<GLint>(cStrings.size()), cStrings.data(), nullptr);
}

} // namespace globjects

#include "ShadingLanguageIncludeImplementation_ShadingLanguageIncludeARB.h"

#include <glbinding/gl/functions.h>

#include <globjects/Shader.h>

#include <globjects/base/AbstractStringSource.h>

using namespace gl;

namespace globjects
{

void ShadingLanguageIncludeImplementation_ARB::updateSources(const Shader * shader) const
{
    std::string source;
    if (shader->source()) {
        source = shader->source()->string();
    }

    const char* sourcePtr = source.c_str();
    glShaderSource(shader->id(), static_cast<GLint>(1), &sourcePtr, nullptr);
}

void ShadingLanguageIncludeImplementation_ARB::compile(const Shader * shader) const
{
    if (!shader->includePaths().empty())
    {
        std::vector<const char*> cStrings = collectCStrings(shader->includePaths());
        glCompileShaderIncludeARB(shader->id(), static_cast<GLint>(cStrings.size()), cStrings.data(), nullptr);
    }
    else
    {
        glCompileShaderIncludeARB(shader->id(), 0, nullptr, nullptr);
    }

}

} // namespace globjects

Fix shading language include paths

Fix shading language include paths


/// Copyright 2019 Pinterest Inc.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0

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

#include "common/kafka/stats_enum.h"

#include <string>
#include <utility>
#include <vector>

#include "gflags/gflags.h"

DEFINE_string(kafka_stats_prefix, "", "Prefix for the kafka stats");
DEFINE_string(kafka_stats_suffix, "", "Suffix for the kafka stats");

std::string getFullStatsName(const std::string& metric_name,
                             const std::initializer_list<std::string>& tags) {
  std::string full_metric_name;
  full_metric_name.append(FLAGS_kafka_stats_prefix)
      .append(metric_name)
      .append(FLAGS_kafka_stats_suffix);
  for (const auto& tag : tags) {
    full_metric_name.append(" ").append(tag);
  }
  return full_metric_name;
}

/// Copyright 2019 Pinterest Inc.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0

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

#include "common/kafka/stats_enum.h"

#include <string>
#include <utility>
#include <vector>

#include "gflags/gflags.h"

DEFINE_string(kafka_stats_prefix, "", "Prefix for the kafka stats");
DEFINE_string(kafka_stats_suffix, "", "Suffix for the kafka stats");
DEFINE_string(kafka_cluster_name, "", "Cluster consuming the kafka messages");

std::string getFullStatsName(const std::string& metric_name,
                             const std::initializer_list<std::string>& tags) {
  std::string full_metric_name;
  full_metric_name.append(FLAGS_kafka_stats_prefix)
      .append(metric_name)
      .append("_")
      .append(FLAGS_kafka_stats_suffix)
      .append(" cluster=")
      .append(FLAGS_kafka_cluster_name);
  for (const auto& tag : tags) {
    full_metric_name.append(" ").append(tag);
  }
  return full_metric_name;
}

Add a new flag for cluster name

[kafka] Add a new flag for cluster name

It's cleaner for the cluster name to be a separate flag (than being included
in the suffix). Separating it out in this diff.


/******************************************************************************\
 * gloperate
 *
 * Copyright (C) 2014 Computer Graphics Systems Group at the
 * Hasso-Plattner-Institut (HPI), Potsdam, Germany.
\******************************************************************************/
#include <gloperate/capabilities/TypedRenderTargetCapability.h>

namespace gloperate {

/**
*  @brief
*    Constructor
*/
TypedRenderTargetCapability::TypedRenderTargetCapability()
:AbstractTypedRenderTargetCapability()
{
}

/**
*  @brief
*    Destructor
*/
TypedRenderTargetCapability::~TypedRenderTargetCapability()
{
}

const RenderTarget & TypedRenderTargetCapability::renderTarget(RenderTargetType type)
{
    return *(m_renderTargets.at(type));
}

bool TypedRenderTargetCapability::hasRenderTarget(RenderTargetType type)
{
    return (m_renderTargets.count(type) > 0);
}

void TypedRenderTargetCapability::setRenderTarget(
    RenderTargetType type,
    globjects::ref_ptr<globjects::Framebuffer> framebuffer,
    gl::GLenum attachment,
    gl::GLenum format)
{
    if (hasRenderTarget(type))
    {
        delete m_renderTargets.at(type);
    }

    m_renderTargets[type] = new RenderTarget(framebuffer, attachment, format);
}

} // namespace gloperate

/******************************************************************************\
 * gloperate
 *
 * Copyright (C) 2014 Computer Graphics Systems Group at the
 * Hasso-Plattner-Institut (HPI), Potsdam, Germany.
\******************************************************************************/
#include <gloperate/capabilities/TypedRenderTargetCapability.h>

namespace gloperate {

/**
*  @brief
*    Constructor
*/
TypedRenderTargetCapability::TypedRenderTargetCapability()
:AbstractTypedRenderTargetCapability()
{
}

/**
*  @brief
*    Destructor
*/
TypedRenderTargetCapability::~TypedRenderTargetCapability()
{
    m_renderTargets.clear();
}

const RenderTarget & TypedRenderTargetCapability::renderTarget(RenderTargetType type)
{
    return *(m_renderTargets.at(type));
}

bool TypedRenderTargetCapability::hasRenderTarget(RenderTargetType type)
{
    return (m_renderTargets.count(type) > 0);
}

void TypedRenderTargetCapability::setRenderTarget(
    RenderTargetType type,
    globjects::ref_ptr<globjects::Framebuffer> framebuffer,
    gl::GLenum attachment,
    gl::GLenum format)
{
    if (hasRenderTarget(type))
    {
        delete m_renderTargets.at(type);
    }

    m_renderTargets[type] = new RenderTarget(framebuffer, attachment, format);
}

} // namespace gloperate

Add clear map on destruction

Add clear map on destruction


#include "stdafx.h"
#include <string>
#include "Listener.h"

using namespace DShowLib;

// Increments the number of processed frames
void    CListener::frameReady(Grabber& caller, smart_ptr<MemBuffer> pBuffer, DWORD currFrame)
{
	done++;
}

#include "stdafx.h"
#include <string>
#include "Listener.h"

using namespace DShowLib;

// Increments the number of processed frames
void    CListener::frameReady(Grabber& caller, smart_ptr<MemBuffer> pBuffer, DWORD currFrame)
{
	MessageBeep(-1);
	done++;
}

Add sound when frame is ready

Add sound when frame is ready


/* mbed Microcontroller Library
 * Copyright (c) 2013-2014 ARM Limited
 *
 * 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 "mbed.h"
#include "test_env.h"

DigitalOut myled(LED1);
uint32_t count = 20;

void blink() {
    if (count) {
    	if (count == 1) {
    		printf("{{success}}\r\n");
    	}
    	count--;
    }
    myled = !myled;
}

void app_start(int, char*[]) {
    MBED_HOSTTEST_TIMEOUT(20);
    MBED_HOSTTEST_SELECT(default_auto);
    MBED_HOSTTEST_DESCRIPTION(Blinky);
    MBED_HOSTTEST_START("MBED_BLINKY");
    minar::Scheduler::postCallback(&blink).period(minar::milliseconds(200));
}

/* mbed Microcontroller Library
 * Copyright (c) 2013-2014 ARM Limited
 *
 * 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 "mbed.h"
#include "test_env.h"

DigitalOut myled(LED1);
uint32_t count = 20;

void blink() {
    if (count) {
    	if (count == 1) {
    		MBED_HOSTTEST_RESULT(true);
    	}
    	count--;
    }
    myled = !myled;
}

void app_start(int, char*[]) {
    MBED_HOSTTEST_TIMEOUT(20);
    MBED_HOSTTEST_SELECT(default_auto);
    MBED_HOSTTEST_DESCRIPTION(Blinky);
    MBED_HOSTTEST_START("MBED_BLINKY");
    minar::Scheduler::postCallback(&blink).period(minar::milliseconds(200));
}

Test - fix blinky test - print host test result


#include <cstdlib>

#include <libport/backtrace.hh>
#include <libport/config.h>

#if LIBPORT_HAVE_EXECINFO_H
# include <execinfo.h>

namespace libport
{
  std::vector<const char*>
  backtrace()
  {
    enum { size = 128 };
    void* callstack[size];
    size_t frames = ::backtrace(callstack, size);
    char** strs = backtrace_symbols(callstack, frames);

    std::vector<const char*> res(frames, 0);
    for (size_t i = 0; i < frames; ++i)
      res[i] = strs[i];

    free(strs);
    return res;
  }
}

#else // ! LIBPORT_HAVE_EXECINFO_H

namespace libport
{
  std::vector<const char*>
  backtrace()
  {
    std::vector<const char*> res;
    res.push_back("(no avaible backtrace)");
  }
}

#endif

#include <cstdlib>

#include <libport/backtrace.hh>
#include <libport/config.h>

#if LIBPORT_HAVE_EXECINFO_H
# include <execinfo.h>
# include <cstdlib>

namespace libport
{
  std::vector<const char*>
  backtrace()
  {
    enum { size = 128 };
    void* callstack[size];
    size_t frames = ::backtrace(callstack, size);
    char** strs = backtrace_symbols(callstack, frames);

    std::vector<const char*> res(frames, 0);
    for (size_t i = 0; i < frames; ++i)
      res[i] = strs[i];

    free(strs);
    return res;
  }
}

#else // ! LIBPORT_HAVE_EXECINFO_H

namespace libport
{
  std::vector<const char*>
  backtrace()
  {
    std::vector<const char*> res;
    res.push_back("(no avaible backtrace)");
    return res;
  }
}

#endif

Add forgotten include and return.

Add forgotten include and return.

	* lib/libport/backtrace.cc: Here.


#include "instr.h"

namespace sasm { namespace instr {

instr::instr(const sasm::elf::elf& elf, uint64 addr)
  : _elf(elf), _addr(addr)
{
}

void instr::_dump_addr(std::ostream& out) const
{
  out << "0x" << std::hex << _addr << std::dec << ": ";
}

}}

#include "instr.h"

namespace sasm { namespace instr {

instr::instr(const sasm::elf::elf& elf, uint64 addr)
  : _elf(elf), _addr(addr)
{
}

void instr::_dump_addr(std::ostream& out) const
{
  try
  {
    auto sym = _elf.symtab[_addr];

    if (sym.type == sasm::elf::symtab::symbol::sym_type::func)
      out << std::endl << sym.name << ":" << std::endl;
  }
  catch (std::out_of_range& e) {}

  out << "  0x" << std::hex << _addr << std::dec << ": ";
}

}}

Print function symbols when dumping asm.


// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2015-2017 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "nodestate.h"

/**
* Default constructor initializing all local member variables to "null" values
*/
CNodeState::CNodeState()
{
    pindexBestKnownBlock = nullptr;
    hashLastUnknownBlock.SetNull();
    pindexLastCommonBlock = nullptr;
    pindexBestHeaderSent = nullptr;
    fSyncStarted = false;
    nDownloadingSince = 0;
    nBlocksInFlight = 0;
    nBlocksInFlightValidHeaders = 0;
    fPreferredDownload = false;
    fPreferHeaders = false;
    fRequestedInitialBlockAvailability = false;
}

/**
* Gets the CNodeState for the specified NodeId.
*
* @param[in] pnode  The NodeId to return CNodeState* for
* @return CNodeState* matching the NodeId, or NULL if NodeId is not matched
*/
CNodeState *State(NodeId pnode)
{
    std::map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
    if (it == mapNodeState.end())
        return nullptr;
    return &it->second;
}

// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2015-2017 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "nodestate.h"

/**
* Default constructor initializing all local member variables to "null" values
*/
CNodeState::CNodeState()
{
    pindexBestKnownBlock = nullptr;
    hashLastUnknownBlock.SetNull();
    pindexLastCommonBlock = nullptr;
    pindexBestHeaderSent = nullptr;
    fSyncStarted = false;
    fSyncStartTime = -1;
    fFirstHeadersReceived = false;
    nFirstHeadersExpectedHeight = -1;
    fRequestedInitialBlockAvailability = false;
    nDownloadingSince = 0;
    nBlocksInFlight = 0;
    nBlocksInFlightValidHeaders = 0;
    fPreferredDownload = false;
    fPreferHeaders = true;
}

/**
* Gets the CNodeState for the specified NodeId.
*
* @param[in] pnode  The NodeId to return CNodeState* for
* @return CNodeState* matching the NodeId, or NULL if NodeId is not matched
*/
CNodeState *State(NodeId pnode)
{
    std::map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
    if (it == mapNodeState.end())
        return nullptr;
    return &it->second;
}

Initialize all variables for CNodeState

Initialize all variables for CNodeState


#include <iostream>
#include <conio.h>
#include <cstdlib>
#include <cmath>
#include <iomanip>

using namespace std;

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char** argv) {
	cout << "Szymon Blaszczynski" << endl;
	cout << setprecision(8) << M_PI << endl;
	cout << "\"Ala\"" << endl;
	getch();
	// system("PAUSE"); // work on linux? no.
	return 0;
}

#include <iostream>
// #include <conio.h> // getch
// #include <cstdlib> # system
#include <cmath>
#include <iomanip>

using namespace std;

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char** argv) {
	cout << "Szymon Blaszczynski" << endl;
	cout << setprecision(8) << M_PI << endl;
	cout << "\"Ala\"" << endl;
	cout << "'" << endl;
	int number_0 = 0;
	int number_1 = 0;
	cout << "Podaj dwie liczby: ";
	cin >> number_0 >> number_1;
	cout << "Liczba pierwsza: " << number_0 << ", liczba druga: " << number_1 \
		<< "." << endl;
	// system("PAUSE"); // works on linux? no.
	return 0;
}

Read two integers and write them out

Read two integers and write them out


/**
 ** \file object/delegate-class.cc
 ** \brief Creation of the URBI object delegate.
 */

#include "object/delegate-class.hh"
#include "object/object.hh"
#include "object/primitives.hh"

#include "runner/runner.hh"
namespace object
{
  rObject delegate_class;

  /*-----------------------.
  | Primitive primitives.  |
  `-----------------------*/

  void
  delegate_class_initialize ()
  {
#define DECLARE(Name)                           \
        DECLARE_PRIMITIVE(delegate, Name)
#undef DECLARE
  }

} // namespace object

/**
 ** \file object/delegate-class.cc
 ** \brief Creation of the URBI object delegate.
 */

#include "object/delegate-class.hh"
#include "object/object.hh"
#include "object/primitives.hh"

#include "runner/runner.hh"

namespace object
{
  rObject delegate_class;

  /*-----------------------.
  | Primitive primitives.  |
  `-----------------------*/

  static rObject
  delegate_class_apply (runner::Runner& r, objects_type args)
  {
    CHECK_ARG_COUNT (2);
    FETCH_ARG (1, List);
    return r.apply (args[0], arg1);
  }

  void
  delegate_class_initialize ()
  {
#define DECLARE(Name)				\
    DECLARE_PRIMITIVE(delegate, Name)
    DECLARE (apply);
#undef DECLARE
  }

} // namespace object

Add apply to Delegate type.

Add apply to Delegate type.

	* src/object/delegate-class.cc (delegate_class_apply): New.


// RUN: %clang_cc1 %s -triple x86_64-apple-darwin10 -emit-llvm -o - | FileCheck %s

struct A {
  virtual ~A();
};

struct B : A { };

struct C {
  int i;
  B b;
};

// CHECK: _Z15test_value_initv
void test_value_init() {
  // This value initialization requires zero initialization of the 'B'
  // subobject followed by a call to its constructor.
  // PR5800

  // CHECK: store i32 17
  // CHECK: call void @llvm.memset.i64
  // CHECK: call void @_ZN1BC1Ev(%struct.A* %tmp1)
  C c = { 17 } ;
  // CHECK: call void @_ZN1CD1Ev(%struct.C* %c)
}

// RUN: %clang_cc1 %s -triple x86_64-apple-darwin10 -emit-llvm -o - | FileCheck %s

struct A {
  virtual ~A();
};

struct B : A { };

struct C {
  int i;
  B b;
};

// CHECK: _Z15test_value_initv
void test_value_init() {
  // This value initialization requires zero initialization of the 'B'
  // subobject followed by a call to its constructor.
  // PR5800

  // CHECK: store i32 17
  // CHECK: call void @llvm.memset.i64
  // CHECK: call void @_ZN1BC1Ev
  C c = { 17 } ;
  // CHECK: call void @_ZN1CD1Ev
}

Fix test case to unbreak testing

Fix test case to unbreak testing

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


#include "insertion.hpp"
#include "swap.hpp"

void insertion(int *data, int size_of_data)
{
    for(int i = 0; i < size_of_data; ++i)
    {
        int j;
        for(j = i; data[j] < data[i]; --j);
        swap(data[i], data[j]);
    }
}

#include "insertion.hpp"
#include "swap.hpp"

void insertion(int *data, int size_of_data)
{
    for(int i = 0; i < size_of_data; ++i)
    {
        int j;
        for(j = i; j >= 0 && data[j] < data[i]; --j);
        swap(data[i], data[j]);
    }
}

Add boundary value in loop expression

Add boundary value in loop expression


#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <iterator>
using namespace std;

int getMinHelper(vector<int> DesiredArray, int Moves)
{
    if(all_of(begin(DesiredArray), end(DesiredArray), [] (const int & element) {return element==0;}))
    {
        return Moves;
    }

    if(all_of(begin(DesiredArray), end(DesiredArray), [] (int & element) {return element%2==0;}))
    {
        for(auto & element : DesiredArray)
        {
            element/=2;
        }

        Moves++;
    }
    else
    {
        for(auto & element : DesiredArray)
        {
            if(element%2==1)
            {
                element--;

                Moves++;
            }
        }
    }

    return getMinHelper(DesiredArray, Moves);
}

int getMin(vector<int> DesiredArray)
{
    int moves{};

    int result=getMinHelper(DesiredArray, moves);

    return result;
}

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <iterator>
using namespace std;

class IncrementAndDoubling
{
    public:
        int getMinHelper(vector<int> DesiredArray, int Moves)
        {
            if(all_of(begin(DesiredArray), end(DesiredArray), [] (const int & element) {return element==0;}))
            {
                return Moves;
            }

            if(all_of(begin(DesiredArray), end(DesiredArray), [] (int & element) {return element%2==0;}))
            {
                for(auto & element : DesiredArray)
                {
                    element/=2;
                }

                Moves++;
            }
            else
            {
                for(auto & element : DesiredArray)
                {
                    if(element%2==1)
                    {
                        element--;

                        Moves++;
                    }
                }
            }

            return getMinHelper(DesiredArray, Moves);
        }

        int getMin(vector<int> DesiredArray)
        {
            int moves{};

            int result=getMinHelper(DesiredArray, moves);

            return result;
        }
};

Put functions in the required class

Put functions in the required class


#include "embedded.h"

#include <QtCore>
#include <QVBoxLayout>
#include <QApplication>
#include <QDesktopWidget>

#include <maliit/namespace.h>
#include <maliit/inputmethod.h>

MainWindow::MainWindow()
    : QMainWindow()
{
    initUI();
}

MainWindow::~MainWindow()
{}

void MainWindow::initUI()
{
    setWindowTitle("Maliit embedded demo");

    setCentralWidget(new QWidget);
    QVBoxLayout *vbox = new QVBoxLayout;

    QPushButton *closeApp = new QPushButton("Close application");
    vbox->addWidget(closeApp);
    connect(closeApp, SIGNAL(clicked()),
            this,     SLOT(close()));

    // Clicking the button will steal focus from the text edit, thus hiding
    // the virtual keyboard:
    QPushButton *hideVkb = new QPushButton("Hide virtual keyboard");
    vbox->addWidget(hideVkb);

    QTextEdit *textEdit = new QTextEdit;
    vbox->addWidget(textEdit);

    QWidget *imWidget = Maliit::InputMethod::instance()->widget();
    if (imWidget) {
        imWidget->setParent(centralWidget());
        vbox->addWidget(imWidget);

        // FIXME: hack to work around the fact that plugins expect a desktop sized widget
        QSize desktopSize = QApplication::desktop()->size();
        imWidget->setMinimumSize(desktopSize.width(), desktopSize.height() - 150);
    } else {
        qCritical() << "Unable to embedded Maliit input method widget";
    }

    centralWidget()->setLayout(vbox);
    show();
    imWidget->hide();
}

#include "embedded.h"

#include <QtCore>
#include <QVBoxLayout>
#include <QApplication>
#include <QDesktopWidget>

#include <maliit/namespace.h>
#include <maliit/inputmethod.h>

MainWindow::MainWindow()
    : QMainWindow()
{
    initUI();
}

MainWindow::~MainWindow()
{}

void MainWindow::initUI()
{
    setWindowTitle("Maliit embedded demo");

    setCentralWidget(new QWidget);
    QVBoxLayout *vbox = new QVBoxLayout;

    QPushButton *closeApp = new QPushButton("Close application");
    vbox->addWidget(closeApp);
    connect(closeApp, SIGNAL(clicked()),
            this,     SLOT(close()));

    // Clicking the button will steal focus from the text edit, thus hiding
    // the virtual keyboard:
    QPushButton *hideVkb = new QPushButton("Hide virtual keyboard");
    vbox->addWidget(hideVkb);

    QTextEdit *textEdit = new QTextEdit;
    vbox->addWidget(textEdit);

    QWidget *imWidget = Maliit::InputMethod::instance()->widget();
    if (imWidget) {
        imWidget->setParent(centralWidget());
        vbox->addWidget(imWidget);
    } else {
        qCritical() << "Unable to embedded Maliit input method widget";
    }

    centralWidget()->setLayout(vbox);
    show();
}

Remove now unneded hack from embedding example.

RevBy: Jon Nordby, Michael Hasselmann, Jan Arne Petersen


#include "messmer/cpp-utils/tempfile/TempDir.h"
#include "messmer/fspp/fuse/Fuse.h"
#include "messmer/fspp/impl/FilesystemImpl.h"
#include "CopyDevice.h"

using cpputils::TempDir;
using copyfs::CopyDevice;
using fspp::FilesystemImpl;
using fspp::fuse::Fuse;

int main (int argc, char *argv[])
{
  TempDir dir;
  CopyDevice device(dir.path().c_str());
  FilesystemImpl fsimpl(&device);
  Fuse fuse(&fsimpl);
  printf("CopyFS initialized\nBase directory: %s\n", dir.path().c_str());
  fuse.run(argc, argv);
  return 0;
}

#include "messmer/cpp-utils/tempfile/TempDir.h"
#include "messmer/fspp/fuse/Fuse.h"
#include "messmer/fspp/impl/FilesystemImpl.h"
#include "CopyDevice.h"
#include <iostream>

using cpputils::TempDir;
using copyfs::CopyDevice;
using fspp::FilesystemImpl;
using fspp::fuse::Fuse;

int main (int argc, char *argv[])
{
  TempDir dir;
  CopyDevice device(dir.path().c_str());
  FilesystemImpl fsimpl(&device);
  Fuse fuse(&fsimpl);
  std::cout << "CopyFS initialized\nBase directory: " << dir.path().c_str() << std::endl;
  fuse.run(argc, argv);
  return 0;
}

Use cout instead of printf

Use cout instead of printf


// Copyright 2013-2015 Eric Schkufza, Rahul Sharma, Berkeley Churchill, Stefan Heule
//
// 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 "tools/args/verifier.h"

using namespace cpputil;

namespace stoke {

Heading& verifier_heading =
  Heading::create("Verifier Options:");

ValueArg<Strategy, StrategyReader, StrategyWriter>& strategy_arg =
  ValueArg<Strategy, StrategyReader, StrategyWriter>::create("strategy")
  .usage("(none|hold_out|extension)")
  .description("Verification strategy")
  .default_val(Strategy::NONE);

} // namespace stoke

// Copyright 2013-2015 Eric Schkufza, Rahul Sharma, Berkeley Churchill, Stefan Heule
//
// 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 "tools/args/verifier.h"

using namespace cpputil;

namespace stoke {

Heading& verifier_heading =
  Heading::create("Verifier Options:");

ValueArg<Strategy, StrategyReader, StrategyWriter>& strategy_arg =
  ValueArg<Strategy, StrategyReader, StrategyWriter>::create("strategy")
  .usage("(none|hold_out|formal|extension)")
  .description("Verification strategy")
  .default_val(Strategy::NONE);

} // namespace stoke

Add command line help for --strategy formal


#include "mainwindow.h"
#include <QApplication>
#include <QFile>
#include "applicationdata.h"
#include "blocktype.h"
#include <QJsonDocument>
#include <QJsonArray>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QString appDir = a.applicationDirPath();

    QString xmlPath = appDir + "/blocks.json";
    QFile xmlFile(xmlPath);
    if (!xmlFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        // error message
        return 1;
    }
    QByteArray bytes = xmlFile.readAll();
    QJsonDocument doc = QJsonDocument::fromJson(bytes);
    QJsonArray nodeArray = doc.array();
    ApplicationData appData;
    appData.blockTypes = BlockTypes_fromJson(nodeArray);

    MainWindow w(appData);
    w.show();

    return a.exec();
}

#include "mainwindow.h"
#include <QApplication>
#include <QFile>
#include "applicationdata.h"
#include "blocktype.h"
#include <QJsonDocument>
#include <QJsonArray>
#include <QMessageBox>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QString appDir = a.applicationDirPath();

    QString xmlPath = appDir + "/blocks.json";
    QFile xmlFile(xmlPath);
    if (!xmlFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QMessageBox::critical(0, "SignalCraft failed to open blocks.json",
                              "The block.json file could not be opened. Ensure that it exists.");
        return 1;
    }
    QByteArray bytes = xmlFile.readAll();
    QJsonParseError parseErr;
    QJsonDocument doc = QJsonDocument::fromJson(bytes, &parseErr);
    if (parseErr.error != QJsonParseError::NoError) {
        QMessageBox::critical(0, "SignalCraft failed to parse blocks.json",
                              "The block.json file could not be parsed as valid JSON. The parser reported: \"" +
                              parseErr.errorString() +
                              "\" at offset " +
                              QString::number(parseErr.offset) +
                              ".");
        return 1;
    }
    QJsonArray nodeArray = doc.array();
    ApplicationData appData;
    bool success;
    appData.blockTypes = BlockTypes_fromJson(nodeArray, &success);
    if (!success) {
        QMessageBox::critical(0, "SignalCraft failed to interpret blocks.json",
                              "The block.json file did not fit the required structure.");
        return 1;
    }

    MainWindow w(appData);
    w.show();

    return a.exec();
}

Handle errors loading block types

Handle errors loading block types


#include <pybind11/pybind11.h>

#include "basics.hpp"
#include "containers.hpp"

namespace py = pybind11;

PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>);

namespace containers {

PYBIND11_PLUGIN(containers) {
    py::module m("containers", "wrapped C++ containers module");

    py::class_<containers::DoodadSet>(m, "DoodadSet")
        .def(py::init<>())
        .def("__len__", &containers::DoodadSet::size)
        .def("add", [](containers::DoodadSet &ds, std::shared_ptr<basics::Doodad> &d) { ds.add(d); });

    return m.ptr();
}

} // namespace containers

#include <pybind11/pybind11.h>
#include <pybind11/stl.h>

#include "basics.hpp"
#include "containers.hpp"

namespace py = pybind11;

PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>);

namespace containers {

PYBIND11_PLUGIN(containers) {
    py::module m("containers", "wrapped C++ containers module");

    py::class_<containers::DoodadSet>(m, "DoodadSet")
        .def(py::init<>())
        .def("__len__", &containers::DoodadSet::size)
        .def("add", [](containers::DoodadSet &ds, std::shared_ptr<basics::Doodad> &d) { ds.add(d); })
        .def("add", [](containers::DoodadSet &ds, std::pair<std::string, int> p) { ds.add(basics::WhatsIt{p.first, p.second}) ; })
        .def("as_dict", &containers::DoodadSet::as_map)
        .def("as_list", &containers::DoodadSet::as_vector)
        .def("assign", &containers::DoodadSet::assign);

    return m.ptr();
}

} // namespace containers

Support assignment and conversion to lists and dicts.


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

#include "datastore.h"
#include "transaction.h"
#include "internal/operations/post_operation.h"
#include "dummy_values.h"

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

namespace You {
namespace DataStore {
namespace UnitTests {
TEST_CLASS(DataStoreApiTest) {
public:
	TEST_METHOD(pushOperationToTransaction) {
		Transaction sut;
		Internal::PostOperation postOp(0, task1);
		sut.push(std::shared_ptr<Internal::IOperation>(&postOp));
		Assert::AreEqual(boost::lexical_cast<size_t>(1), sut.operationsQueue.size());
	}
};

}  // namespace UnitTests
}  // namespace DataStore
}  // namespace You

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

#include "datastore.h"
#include "transaction.h"
#include "internal/operations/post_operation.h"
#include "dummy_values.h"

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

namespace You {
namespace DataStore {
namespace UnitTests {
TEST_CLASS(DataStoreApiTest) {
public:
	TEST_METHOD(pushOperationToTransaction) {
		Transaction sut;
		std::shared_ptr<Internal::IOperation> postOp =
			std::make_shared<Internal::PostOperation>(0, task1);
		sut.push(postOp);
		Assert::AreEqual(boost::lexical_cast<size_t>(1), sut.operationsQueue.size());
	}
};

}  // namespace UnitTests
}  // namespace DataStore
}  // namespace You

Modify test to be correct

Modify test to be correct


// RUN: rm -rf %t
// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -I %S/Inputs/self-referencing-lambda %s -verify -emit-obj -o %t2.o
// expected-no-diagnostics

#include "a.h"

// RUN: rm -rf %t
// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -I %S/Inputs/self-referencing-lambda %s -verify -emit-obj -std=c++14 -o %t2.o
// expected-no-diagnostics

#include "a.h"

[Modules] Update test to mention it requires C++14.

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@328283 91177308-0d34-0410-b5e6-96231b3b80d8
(cherry picked from commit e8d80b7dba2329bb4ee2e507bfd6496053df542b)


#include "gtest/gtest.h"

#include "PrologInterface.h"
#include <iostream>

namespace {

static int glob_argc;
static char **glob_argv;

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

TEST_F(PrologLifetimeTest, BeginInitializesProlog) {
  PrologLifetime::begin(glob_argc, glob_argv);
  ASSERT_TRUE(PL_is_initialised(&glob_argc, &glob_argv));
  PrologLifetime::end();
}

}

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  glob_argc = argc;
  glob_argv = argv;
  return RUN_ALL_TESTS();
}

#include "gtest/gtest.h"

#include "PrologInterface.h"
#include <iostream>

namespace {

static int glob_argc;
static char **glob_argv;

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

TEST_F(PrologLifetimeTest, BeginInitializesProlog) {
  PrologLifetime::begin(glob_argc, glob_argv);
  ASSERT_TRUE(PL_is_initialised(&glob_argc, &glob_argv));
  PrologLifetime::end();
}

TEST_F(PrologLifetimeTest, MultipleInitialization) {
  PrologLifetime::begin(glob_argc, glob_argv);
  ASSERT_TRUE(PL_is_initialised(&glob_argc, &glob_argv));
  PrologLifetime::end();

  ASSERT_FALSE(PL_is_initialised(&glob_argc, &glob_argv));

  PrologLifetime::begin(glob_argc, glob_argv);
  ASSERT_TRUE(PL_is_initialised(&glob_argc, &glob_argv));
  PrologLifetime::end();
}

}

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  glob_argc = argc;
  glob_argv = argv;
  return RUN_ALL_TESTS();
}

Test multiple initialization for SWI-Prolog


#include"ics3/eepparam.hpp"

#include<stdexcept>

constexpr int byteSize {4};
constexpr uint16_t mask {0xF};

void ics::EepParam::write(std::array<uint8_t, 64>& dest) const noexcept {
  uint16_t nowData {data};
  for (size_t i {offset + length - 1}; i >= offset; --i) {
    dest[i] = nowData & mask;
    nowData >>= byteSize;
  }
}

void ics::EepParam::read(const std::array<uint8_t, 64>& src) {
  uint16_t result {0};
  for (size_t i {0}; i < length; ++i)
    result |= (src[offset + length - 1 - i] & mask) << (i * byteSize);
  set(result); // throw std::invalid_argument
}

#include"ics3/eepparam.hpp"

#include<stdexcept>

constexpr int byteSize {4};
constexpr uint16_t mask {0xF};

void ics::EepParam::write(std::array<uint8_t, 64>& dest) const noexcept {
  uint16_t nowData {data};
  for (size_t i {offset + length - 1}; i >= offset; --i) {
    dest[i] = nowData & mask;
    nowData >>= byteSize;
  }
}

void ics::EepParam::read(const std::array<uint8_t, 64>& src) {
  uint16_t result {0};
  const size_t loopend = offset + length;
  for (size_t i {offset}; i < loopend; ++i) {
    result <<= byteSize;
    result |= src[i] & mask;
  }
  set(result); // throw std::invalid_argument
}

Update read method for readability

Update read method for readability


#include <Headers\Native IO Board\MainStream IO\Native MainInput\IO Board.h>

using namespace std;

int main()
{

}

#include <Headers\Native IO Board\MainStream IO\Native MainInput\IO Board.h>

int main()
{

}

Remove standard namespace from source file.

The standard namespace is included in the Native IO Board header. So it
does not need to be included in the main source file.


// RUN: %clang_cc1 %s -triple i386-unknown-unknown -emit-llvm -o - | FileCheck %s

struct A {
  virtual int operator-() = 0;
};

void f(A *a) {
  // CHECK: call i32 %
  -*a;
}

// RUN: %clang_cc1 %s -triple i386-unknown-unknown -emit-llvm -o - | FileCheck %s

struct A {
  virtual int operator-();
};

void f(A a, A *ap) {
  // CHECK: call i32 @_ZN1AngEv(%struct.A* %a)
  -a;

  // CHECK: call i32 %
  -*ap;
}

Add a test for devirtualization of virtual operator calls.

There was no test coverage for this before: Modifiying
EmitCXXOperatorMemberCallee() to not call CanDevirtualizeMemberFunctionCall()
didn't make any test fail.

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


Update Binary tree preorder inorder successor


#include <stdio.h>

#include <Logging.h>
#include <ZipFile.h>

int main()
{
	v::Log::Level = v::Log::LogLevel_Trace;

	v::Log::Debug("Creating zip file");

	{
		v::ZipFile zip;
		zip.Read("meow.zip");

		s::StackArray<v::ZipEntry> entries;
		zip.GetEntries(entries);

		for (auto &entry : entries) {
			v::Log::Debug("Zip entry %1: %2", FVAR(entry.GetIndex()), FVAR(entry.GetName()));

			s::MemoryStream strm;
			entry.Read(strm);
			v::Log::Debug("Contents at %1 with size %2", FVAR(strm.strm_pubBuffer), FVAR(strm.Size()));
		}
	}

	v::Log::Debug("Meow.zip created");

	getchar();
	return 0;
}

#include <stdio.h>

#include <Logging.h>
#include <ZipFile.h>

int main()
{
	v::Log::Level = v::Log::LogLevel_Trace;

	v::Log::Debug("Reading zip file test.zip");

	try {
		v::ZipFile zip;
		zip.Read("test.zip");

		s::StackArray<v::ZipEntry> entries;
		zip.GetEntries(entries);

		for (auto &entry : entries) {
			v::Log::Debug("Zip entry %1: %2", FVAR(entry.GetIndex()), FVAR(entry.GetName()));

			s::MemoryStream strm;
			entry.Read(strm);
			v::Log::Debug("Contents at %1 with size %2", FVAR(strm.strm_pubBuffer), FVAR(strm.Size()));
		}
	} catch (s::Exception ex) {
		v::Log::Fatal("Error: %1", FVAR(ex.Message));
	}

	getchar();
	return 0;
}

Clean up and error example

Clean up and error example


/* This file is part of python_mapnik (c++/python mapping toolkit)
 * Copyright (C) 2005 Artem Pavlenko, Jean-Francois Doyon
 *
 * Mapnik is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

//$Id$

#include <boost/python.hpp>
#include <mapnik.hpp>

using mapnik::text_symbolizer;
using mapnik::Color;

void export_text_symbolizer()
{
    using namespace boost::python;

    class_<text_symbolizer>("TextSymbolizer",
			    init<std::string const&,unsigned,Color const&>("TODO"))
	;
}

/* This file is part of python_mapnik (c++/python mapping toolkit)
 * Copyright (C) 2005 Artem Pavlenko, Jean-Francois Doyon
 *
 * Mapnik is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

//$Id$

#include <boost/python.hpp>
#include <mapnik.hpp>

using mapnik::text_symbolizer;
using mapnik::Color;

void export_text_symbolizer()
{
    using namespace boost::python;

    class_<text_symbolizer>("TextSymbolizer",
			    init<std::string const&,unsigned,Color const&>())
        .add_property("halo_fill",make_function(
                      &text_symbolizer::get_halo_fill,return_value_policy<copy_const_reference>()),
                      &text_symbolizer::set_halo_fill)
        .add_property("halo_radius",&text_symbolizer::get_halo_radius, &text_symbolizer::set_halo_radius)
	;
}

Add support for halo's to TextSymbolizer().

git-svn-id: 06a2cde72a096d93ff72b88e3e6711b8f00772a4@184 d397654b-2ff0-0310-9e29-ba003691a0f9


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

#include "allocators/page_heap.h"

#include "common.h"
#include "log.h"
#include "system-alloc.h"

namespace scalloc {

PageHeap PageHeap::page_heap_ cache_aligned;

void PageHeap::InitModule() {
  DistributedQueue::InitModule();

  page_heap_.page_pool_.Init(kPageHeapBackends);
}

void PageHeap::AsyncRefill() {
  uintptr_t ptr = reinterpret_cast<uintptr_t>(SystemAlloc_Mmap(
      kPageSize * kPageRefill, NULL));
  if (UNLIKELY(ptr == 0)) {
    ErrorOut("SystemAlloc failed");
  }
  for (size_t i = 0; i < kPageRefill; i++) {
    page_pool_.Enqueue(reinterpret_cast<void*>(ptr));
    ptr += kPageSize;
  }
}

}  // namespace scalloc

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

#include "allocators/page_heap.h"

#include "common.h"
#include "log.h"
#include "system-alloc.h"

namespace scalloc {

PageHeap PageHeap::page_heap_ cache_aligned;

void PageHeap::InitModule() {
  DistributedQueue::InitModule();

  page_heap_.page_pool_.Init(kPageHeapBackends);
}

void PageHeap::AsyncRefill() {
  uintptr_t ptr = reinterpret_cast<uintptr_t>(SystemAlloc_Mmap(
      kPageSize * kPageRefill, NULL));
  if (UNLIKELY(ptr == 0)) {
    ErrorOut("SystemAlloc failed");
  }
  for (size_t i = 0; i < kPageRefill; i++) {
    Put(reinterpret_cast<void*>(ptr));
    ptr += kPageSize;
  }
}

}  // namespace scalloc

Use public API for inserting a block in refill.

Signed-off-by: Michael Lippautz <0d543840881a2c189b4f7636b15eebd6a8f60ace@gmail.com>


//===-- main.cpp ------------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// This test verifies the correct handling of program counter jumps.

int otherfn();

template<typename T>
T min(T a, T b)
{
    if (a < b)
    {
        return a; // 1st marker
    } else {
        return b; // 2nd marker
    }
}

int main ()
{
    int i;
    double j;

    i = min(4, 5); // 3rd marker
    j = min(7.0, 8.0); // 4th marker

    return 0;
}

//===-- main.cpp ------------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// This test verifies the correct handling of program counter jumps.

int otherfn();

template<typename T>
T min(T a, T b)
{
    if (a < b)
    {
        return a; // 1st marker
    } else {
        return b; // 2nd marker
    }
}

int main ()
{
    int i;
    double j;
    int min_i_a = 4, min_i_b = 5;
    double min_j_a = 7.0, min_j_b = 8.0;
    i = min(min_i_a, min_i_b); // 3rd marker
    j = min(min_j_a, min_j_b); // 4th marker

    return 0;
}

Fix the thread jump test case for 32-bit inferiors. A jump was going back to a function call using a source line number. However, the parameters being passed to the function were setup before the instruction we jumped to. In other words, the source line was associated with assembly after the function parameters had been setup for the function to be called.

git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@191457 91177308-0d34-0410-b5e6-96231b3b80d8


// RUN: rm -rf %t
// RUN: %clang_cc1 -fmodule-cache-path %t -fauto-module-import -I %S/Inputs/submodules %s -verify

__import_module__ std.vector;
__import_module__ std.typetraits; // expected-error{{no submodule named 'typetraits' in module 'std'; did you mean 'type_traits'?}}
__import_module__ std.vector.compare; // expected-error{{no submodule named 'compare' in module 'std.vector'}}

// RUN: rm -rf %t
// RUN: %clang_cc1 -Eonly -fmodule-cache-path %t -fauto-module-import -I %S/Inputs/submodules %s -verify
// RUN: %clang_cc1 -fmodule-cache-path %t -fauto-module-import -I %S/Inputs/submodules %s -verify

__import_module__ std.vector;
__import_module__ std.typetraits; // expected-error{{no submodule named 'typetraits' in module 'std'; did you mean 'type_traits'?}}
__import_module__ std.vector.compare; // expected-error{{no submodule named 'compare' in module 'std.vector'}}

Add preprocessor-only test for submodule imports

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


#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "applications.h"
#include "iconprovider.h"
#include "process.h"

/**
 * @todo: Config file in ~/.config/qmldmenu/
 * @todo: SHIFT(ENTER) for sudo
 * @todo: TAB For command (term /{usr}/bin/) / app (.desktop) mode
 */
int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;

    qmlRegisterType<Process>("Process", 1, 0, "Process");
    qmlRegisterType<Applications>("Applications", 1, 0, "Applications");
    engine.addImageProvider(QLatin1String("appicon"), new IconProvider);
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QtQml>
#include "applications.h"
#include "iconprovider.h"
#include "process.h"

/**
 * @todo: Config file in ~/.config/qmldmenu/
 * @todo: SHIFT(ENTER) for sudo
 * @todo: TAB For command (term /{usr}/bin/) / app (.desktop) mode
 */
int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;

    qmlRegisterType<Process>("Process", 1, 0, "Process");
    qmlRegisterType<Applications>("Applications", 1, 0, "Applications");
    engine.addImageProvider(QLatin1String("appicon"), new IconProvider);
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}

Fix compilation on Ubuntu 16.04

Fix compilation on Ubuntu 16.04


/** @file main.cpp
 * 	@brief Главный файл сервера репозитория
 * */
#include <QCoreApplication>
#include <QTextCodec>

#include "server.h"

int main(int argc, char *argv[])
{
	QTextCodec *codec = QTextCodec::codecForName("UTF-8");
	QTextCodec::setCodecForCStrings(codec);

	QCoreApplication app(argc, argv);

	int port = 6666;
	if (argc == 2) {
		port = QString(argv[1]).toInt();
	}

	repoServer::QRealRepoServer repo(port);

	return app.exec();
}

/** @file main.cpp
 * 	@brief Главный файл сервера репозитория
 * */
#include <QCoreApplication>
#include <QTextCodec>
#include <QFile>

#include "server.h"

int main(int argc, char *argv[])
{
	QTextCodec *codec = QTextCodec::codecForName("UTF-8");
	QTextCodec::setCodecForCStrings(codec);

	QCoreApplication app(argc, argv);

	int port = 6666;
	while (argc > 1)
	{
		argc--;
		if (!strcmp(argv[argc], "-e"))
		{
			QFile::remove("repothread_log.txt");
			continue;
		}
		port = QString(argv[argc]).toInt();
		if (port == 0)
			port = 6666;
	}

	repoServer::QRealRepoServer repo(port);

	return app.exec();
}

Add '-e' cmd key to reposerver which means 'immediate exterminatus'.


#include <QGuiApplication>
#include <QQuickView>

#include "sailfishapplication.h"

Q_DECL_EXPORT int main(int argc, char *argv[])
{
    QScopedPointer<QGuiApplication> app(Sailfish::createApplication(argc, argv));
    QScopedPointer<QQuickView> view(Sailfish::createView("main.qml"));

    Sailfish::showView(view.data());

    return app->exec();
}

#include <QGuiApplication>
#include <QQuickView>
#include <QQmlContext>

#include "sailfishapplication.h"
#include "servercomm.h"

Q_DECL_EXPORT int main(int argc, char *argv[])
{
    QScopedPointer<QGuiApplication> app(Sailfish::createApplication(argc, argv));
    QScopedPointer<QQuickView> view(Sailfish::createView("main.qml"));

    ServerComm sc;
    view->rootContext()->setContextProperty("serverComm", &sc);

    Sailfish::showView(view.data());

    return app->exec();
}

Connect the C++ classes with QML

Connect the C++ classes with QML


//===-- llvm/CodeGen/GlobalISel/EmptyFile.cpp ------ EmptyFile ---*- C++ -*-==//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// The purpose of this file is to please cmake by not creating an
/// empty library when we do not build GlobalISel.
/// \todo This file should be removed when GlobalISel is not optional anymore.
//===----------------------------------------------------------------------===//

#include "llvm/Support/Compiler.h"

// Anonymous namespace so that we do not step on anyone's toes.
namespace {
LLVM_ATTRIBUTE_UNUSED void foo(void) {
}
}

//===-- llvm/CodeGen/GlobalISel/EmptyFile.cpp ------ EmptyFile ---*- C++ -*-==//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// The purpose of this file is to please cmake by not creating an
/// empty library when we do not build GlobalISel.
/// \todo This file should be removed when GlobalISel is not optional anymore.
//===----------------------------------------------------------------------===//

#include "llvm/Support/Compiler.h"

namespace llvm {
// Export a global symbol so that ranlib does not complain
// about the TOC being empty for the global-isel library when
// we do not build global-isel.
LLVM_ATTRIBUTE_UNUSED void DummyFunctionToSilenceRanlib(void) {
}
}

Fix a ranlib warning about empty TOC.

[GlobalISel] Fix a ranlib warning about empty TOC.

Fixes PR26733

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


#include "OptionsManager.h"

#include <fstream>
#include <iostream>

#include <boost/filesystem.hpp>

#include <spotify/json.hpp>

#include "codecs/OptionsCodec.h"
#include "logging/Logging.h"

OptionsManager::OptionsManager(std::string optionsFilename)
{
    loadOptions(optionsFilename);
}

void OptionsManager::loadOptions(std::string optionsFilename)
{
    std::ifstream ifs(optionsFilename);
    if (!ifs.good())
    {
        throw std::runtime_error("Could not open options file");
    }

    std::string str{std::istreambuf_iterator<char>(ifs),
        std::istreambuf_iterator<char>()};
    try
    {
        mOptions = spotify::json::decode<Options>(str.c_str());
    }
    catch (const spotify::json::decode_exception& e)
    {
        logError() << "spotify::json::decode_exception encountered at "
            << e.offset()
            << ": "
            << e.what();
        throw;
    }
    mOptions.paths.initialise(optionsFilename);
    createOutputDirectory();
}

void OptionsManager::createOutputDirectory()
{
    // TODO(hryniuk): move it elsewhere
    boost::filesystem::path p(mOptions.paths.directory);
    p.append(mOptions.outputDirectory);
    boost::filesystem::create_directories(p);
    auto relativeOutputDirectory = p.string();
    mOptions.relativeOutputDirectory = relativeOutputDirectory;
}

const Options& OptionsManager::getOptions() const
{
    return mOptions;
}

#include "OptionsManager.h"

#include <fstream>
#include <iostream>

#include <boost/filesystem.hpp>

#include <spotify/json.hpp>

#include "codecs/OptionsCodec.h"
#include "logging/Logging.h"

OptionsManager::OptionsManager(std::string optionsFilename)
{
    loadOptions(optionsFilename);
}

void OptionsManager::loadOptions(std::string optionsFilename)
{
    std::ifstream ifs(optionsFilename);
    if (!ifs.good())
    {
        throw std::runtime_error("Could not open options file");
    }

    std::string str{std::istreambuf_iterator<char>(ifs),
        std::istreambuf_iterator<char>()};
    try
    {
        mOptions = spotify::json::decode<Options>(str.c_str());
    }
    catch (const spotify::json::decode_exception& e)
    {
        logError() << "spotify::json::decode_exception encountered at "
            << e.offset()
            << ": "
            << e.what();
        throw;
    }
    mOptions.paths.initialise(optionsFilename);
    createOutputDirectory();
}

void OptionsManager::createOutputDirectory()
{
    // TODO(hryniuk): move it elsewhere
    boost::filesystem::path p(mOptions.paths.directory);
    p.append(mOptions.outputDirectory);
    auto relativeOutputDirectory = p.string();
    mOptions.relativeOutputDirectory = relativeOutputDirectory;
}

const Options& OptionsManager::getOptions() const
{
    return mOptions;
}

Remove extra call to create_directories

Remove extra call to create_directories


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

#include "WatermarkDataFactory.h"

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

            }

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

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

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

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

#include "WatermarkDataFactory.h"

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

            }

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

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

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

Update eegeo reference in company watermark info page. Buddy: Vimmy.


#include "catch.hpp"
#include "matrix.h"

TEST_CASE( "Test matrix", "[matrix]" ) {
  matrix<int> m0;
  REQUIRE( m0.rows() == 0 );
  REQUIRE( m0.columns() == 0 );

  matrix<int> m3_4(3,4);
  REQUIRE( m3_4.rows() == 3 );
  REQUIRE( m3_4.columns() == 4 );

  matrix<int> m_init_2 = {};
  REQUIRE( m_init_2.rows() == 0 );
  REQUIRE( m_init_2.columns() == 0 );

  matrix<int> m_init = {{1,2,3},{4,5,6}};
  REQUIRE( m_init.rows() == 2 );
  REQUIRE( m_init.columns() == 3 );
  REQUIRE( m_init.at(0,0) == 1 );
  REQUIRE( m_init.at(0,1) == 2 );
  REQUIRE( m_init.at(0,2) == 3 );
  REQUIRE( m_init.at(1,0) == 4 );
  REQUIRE( m_init.at(1,1) == 5 );
  REQUIRE( m_init.at(1,2) == 6 );
}

#include "catch.hpp"
#include "matrix.h"

TEST_CASE( "Test default constructor", "[matrix][constructors]" ) {
  matrix<int> m0;
  REQUIRE( m0.rows() == 0 );
  REQUIRE( m0.columns() == 0 );
}

TEST_CASE( "Test size constructor", "[matrix][constructors]" ) {
  matrix<int> m3_4(3,4);
  REQUIRE( m3_4.rows() == 3 );
  REQUIRE( m3_4.columns() == 4 );

  matrix<int> m0_0(0,0);
  REQUIRE( m0_0.rows() == 0 );
  REQUIRE( m0_0.columns() == 0 );
}

TEST_CASE( "Test initializer list constructor", "[matrix][constructors]" ) {
  matrix<int> m_init = {{1,2,3},{4,5,6}};
  REQUIRE( m_init.rows() == 2 );
  REQUIRE( m_init.columns() == 3 );
  REQUIRE( m_init.at(0,0) == 1 );
  REQUIRE( m_init.at(0,1) == 2 );
  REQUIRE( m_init.at(0,2) == 3 );
  REQUIRE( m_init.at(1,0) == 4 );
  REQUIRE( m_init.at(1,1) == 5 );
  REQUIRE( m_init.at(1,2) == 6 );

  matrix<int> m_init_2 = {};
  REQUIRE( m_init_2.rows() == 0 );
  REQUIRE( m_init_2.columns() == 0 );
}

Split tests to multiple test cases.

Split tests to multiple test cases.


#include <stdlib.h>
#include <v8.h>
#include <nan.h>
#include <node.h>

using namespace node;
using namespace v8;

extern "C" void init (Handle<Object>);

NAN_METHOD(Random) {
  NanScope();
  NanReturnValue(NanNew<Number>(rand()/((double)RAND_MAX + 1)));
}

NAN_METHOD(Rand) {
  NanScope();
  NanReturnValue(NanNew<Integer>(rand()));
}

NAN_METHOD(SRand) {
  NanScope();
  if (args.Length() == 0) {
    NanThrowError(Exception::Error(NanNew<String>("Usage: srand(n)")));
  }
  srand(args[0]->Uint32Value());
  NanReturnValue(NanUndefined());
}

extern "C" void init (Handle<Object> target) {
  NODE_SET_METHOD(target, "random", Random);
  NODE_SET_METHOD(target, "rand", Rand);
  NODE_SET_METHOD(target, "srand", SRand);
  NODE_SET_METHOD(target, "seed", SRand);
  NODE_DEFINE_CONSTANT(target, RAND_MAX);
}

NODE_MODULE(srand, init)

#include <stdlib.h>
#include <v8.h>
#include <nan.h>
#include <node.h>
#include <cstdlib>

using namespace node;
using namespace v8;

extern "C" void init (Handle<Object>);

NAN_METHOD(Random) {
  NanScope();
  NanReturnValue(NanNew<Number>(rand()/((double)RAND_MAX + 1)));
}

NAN_METHOD(Rand) {
  NanScope();
  NanReturnValue(NanNew<Integer>(rand()));
}

NAN_METHOD(SRand) {
  NanScope();
  if (args.Length() == 0) {
    NanThrowError(Exception::Error(NanNew<String>("Usage: srand(n)")));
  }
  srand(args[0]->Uint32Value());
  NanReturnValue(NanUndefined());
}

extern "C" void init (Handle<Object> target) {
  NODE_SET_METHOD(target, "random", Random);
  NODE_SET_METHOD(target, "rand", Rand);
  NODE_SET_METHOD(target, "srand", SRand);
  NODE_SET_METHOD(target, "seed", SRand);
  NODE_DEFINE_CONSTANT(target, RAND_MAX);
}

NODE_MODULE(srand, init)

Add cstdlib.h to compile in CircleCI

Add cstdlib.h to compile in CircleCI


// RUN: %clang_cc1 -fsyntax-only -verify %s

#define NODEREF __attribute__((noderef))

void Func() {
  int NODEREF i; // expected-warning{{'noderef' can only be used on an array or pointer type}}
  int NODEREF *i_ptr;

  // There should be no difference whether a macro defined type is used or not.
  auto __attribute__((noderef)) *auto_i_ptr = i_ptr;
  auto __attribute__((noderef)) auto_i = i; // expected-warning{{'noderef' can only be used on an array or pointer type}}

  auto NODEREF *auto_i_ptr2 = i_ptr;
  auto NODEREF auto_i2 = i; // expected-warning{{'noderef' can only be used on an array or pointer type}}
}

// Added test for fix for P41835
#define _LIBCPP_FLOAT_ABI __attribute__((pcs("aapcs")))
struct A {
  _LIBCPP_FLOAT_ABI int operator()() throw(); // expected-warning{{'pcs' calling convention ignored for this target}}
};

// RUN: %clang_cc1 -fsyntax-only -verify -triple x86_64-linux-gnu %s

#define NODEREF __attribute__((noderef))

void Func() {
  int NODEREF i; // expected-warning{{'noderef' can only be used on an array or pointer type}}
  int NODEREF *i_ptr;

  // There should be no difference whether a macro defined type is used or not.
  auto __attribute__((noderef)) *auto_i_ptr = i_ptr;
  auto __attribute__((noderef)) auto_i = i; // expected-warning{{'noderef' can only be used on an array or pointer type}}

  auto NODEREF *auto_i_ptr2 = i_ptr;
  auto NODEREF auto_i2 = i; // expected-warning{{'noderef' can only be used on an array or pointer type}}
}

// Added test for fix for P41835
#define _LIBCPP_FLOAT_ABI __attribute__((pcs("aapcs")))
struct A {
  _LIBCPP_FLOAT_ABI int operator()() throw(); // expected-warning{{'pcs' calling convention ignored for this target}}
};

Add target triple to test.

Add target triple to test.

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


/**
 * \file register_loader_saver_lcp.cpp
 * Defines IO for a GCSA LCPArray from stream files.
 */

#include <vg/io/registry.hpp>

#include <gcsa/gcsa.h>
#include <gcsa/algorithms.h>

namespace vg {

namespace io {

using namespace std;
using namespace vg::io;

void register_loader_saver_lcp() {
    Registry::register_bare_loader_saver<gcsa::LCPArray>("LCP", [](istream& input) -> void* {
        // Allocate an LCPArray
        gcsa::LCPArray* index = new gcsa::LCPArray();

        // Load it
        index->load(input);

        // Return it so the caller owns it.
        return (void*) index;
    }, [](const void* index_void, ostream& output) {
        // Cast to LCP and serialize to the stream.
        ((const gcsa::LCPArray*) index_void)->serialize(output);
    });

}

}

}

/**
 * \file register_loader_saver_lcp.cpp
 * Defines IO for a GCSA LCPArray from stream files.
 */

#include <vg/io/registry.hpp>

#include <gcsa/gcsa.h>
#include <gcsa/algorithms.h>

namespace vg {

namespace io {

using namespace std;
using namespace vg::io;

void register_loader_saver_lcp() {
    std::uint32_t magic_number = gcsa::LCPHeader::TAG;
    std::string magic_string(reinterpret_cast<char*>(&magic_number), sizeof(magic_number));

    Registry::register_bare_loader_saver_with_magic<gcsa::LCPArray>("LCP", magic_string, [](istream& input) -> void* {
        // Allocate an LCPArray
        gcsa::LCPArray* index = new gcsa::LCPArray();

        // Load it
        index->load(input);

        // Return it so the caller owns it.
        return (void*) index;
    }, [](const void* index_void, ostream& output) {
        // Cast to LCP and serialize to the stream.
        ((const gcsa::LCPArray*) index_void)->serialize(output);
    });

}

}

}

Use a magic number with the LCP array as well


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

#include "pc/ice_transport.h"

#include <memory>
#include <utility>

namespace webrtc {

IceTransportWithPointer::~IceTransportWithPointer() {
  // We depend on the signaling thread to call Clear() before dropping
  // its last reference to this object; if the destructor is called
  // on the signaling thread, it's OK to not have called Clear().
  if (internal_) {
    RTC_DCHECK_RUN_ON(creator_thread_);
  }
}

cricket::IceTransportInternal* IceTransportWithPointer::internal() {
  RTC_DCHECK_RUN_ON(creator_thread_);
  return internal_;
}

void IceTransportWithPointer::Clear() {
  RTC_DCHECK_RUN_ON(creator_thread_);
  internal_ = nullptr;
}

}  // namespace webrtc

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

#include "pc/ice_transport.h"

#include <memory>
#include <utility>

namespace webrtc {

IceTransportWithPointer::~IceTransportWithPointer() {
  // We depend on the networking thread to call Clear() before dropping
  // its last reference to this object; if the destructor is called
  // on the networking thread, it's OK to not have called Clear().
  if (internal_) {
    RTC_DCHECK_RUN_ON(creator_thread_);
  }
}

cricket::IceTransportInternal* IceTransportWithPointer::internal() {
  RTC_DCHECK_RUN_ON(creator_thread_);
  return internal_;
}

void IceTransportWithPointer::Clear() {
  RTC_DCHECK_RUN_ON(creator_thread_);
  internal_ = nullptr;
}

}  // namespace webrtc

Fix comment - ice transport is cleared on the networking thread.

Bug: chromium:907849
Change-Id: I15afe28d3fb2a175a6e2e7491dc33d36f9f9cd32
Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/132008
Commit-Queue: Marina Ciocea <0d7dc322100a0f119aa371866dde220cf322deae@webrtc.org>
Commit-Queue: Harald Alvestrand <ce816cd73d80f958d82de1df356058c2d2bca378@webrtc.org>
Reviewed-by: Harald Alvestrand <ce816cd73d80f958d82de1df356058c2d2bca378@webrtc.org>
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#27509}


#include "junior-simple.h"
#include <vector>

namespace junior
{
	std::vector<window> windows;

	window& create_window(const wchar_t* title)
	{
		windows.push_back(window(title));
		return windows.back();
	}

	inline window& main_window()
	{
		return windows.front();
	}

	void draw_line(const int x1, const int y1, const int x2, const int y2)
	{
		main_window().draw_line(x1, y1, x2, y2);
	}

	void draw_circle(const int x, const int y, const int radius)
	{
		main_window().draw_circle(x, y, radius);
	}

	void write(const wchar_t* text, const int x, const int y)
	{
		main_window().write(text, x, y);
	}
}

#include "junior-simple.h"
#include <vector>
#include <Windows.h>

namespace junior
{
	std::vector<window> windows;

	window& create_window(const wchar_t* title)
	{
		ShowWindow(GetConsoleWindow(), SW_HIDE);
		windows.push_back(window(title));
		return windows.back();
	}

	inline window& main_window()
	{
		return windows.front();
	}

	void draw_line(const int x1, const int y1, const int x2, const int y2)
	{
		main_window().draw_line(x1, y1, x2, y2);
	}

	void draw_circle(const int x, const int y, const int radius)
	{
		main_window().draw_circle(x, y, radius);
	}

	void write(const wchar_t* text, const int x, const int y)
	{
		main_window().write(text, x, y);
	}
}

Hide console window when creating a new window using simple API


// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// Hearthstone++ is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

#include <Rosetta/Actions/Targeting.hpp>
#include <Rosetta/Games/Game.hpp>

namespace RosettaStone::Generic
{
bool IsValidTarget(Entity* source, Entity* target)
{
    for (auto& requirement : source->card.playRequirements)
    {
        switch (requirement.first)
        {
            case +PlayReq::REQ_MINION_TARGET:
            {
                if (dynamic_cast<Minion*>(target) == nullptr)
                {
                    return false;
                }
            }
            case +PlayReq::REQ_ENEMY_TARGET:
            {
                if (&target->GetOwner() == &source->GetOwner())
                {
                    return false;
                }
            }
            case +PlayReq::REQ_TARGET_TO_PLAY:
            {
                if (dynamic_cast<Character*>(target) == nullptr)
                {
                    return false;
                }
            }
            default:
                break;
        }
    }

    return true;
}
}  // namespace RosettaStone::Generic

// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// Hearthstone++ is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

#include <Rosetta/Actions/Targeting.hpp>
#include <Rosetta/Games/Game.hpp>

namespace RosettaStone::Generic
{
bool IsValidTarget(Entity* source, Entity* target)
{
    for (auto& requirement : source->card.playRequirements)
    {
        switch (requirement.first)
        {
            case +PlayReq::REQ_MINION_TARGET:
            {
                if (dynamic_cast<Minion*>(target) == nullptr)
                {
                    return false;
                }
                break;
            }
            case +PlayReq::REQ_ENEMY_TARGET:
            {
                if (&target->GetOwner() == &source->GetOwner())
                {
                    return false;
                }
                break;
            }
            case +PlayReq::REQ_TARGET_TO_PLAY:
            {
                if (dynamic_cast<Character*>(target) == nullptr)
                {
                    return false;
                }
                break;
            }
            default:
                break;
        }
    }

    return true;
}
}  // namespace RosettaStone::Generic

Add 'break' in switch-case statement

fix: Add 'break' in switch-case statement


class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if(nums.size()==0) return 0;
        for(int i=0;i<nums.size()-1;i++){
            int j=i+1;
            while(nums[j]==nums[i] && j<nums.size()){
                j++;
            }
            nums.erase(nums.begin()+i+1,nums.begin()+j);
        }
        return nums.size();
    }
};

Remove Duplicates from Sorted Array

Remove Duplicates from Sorted Array


// main.cpp
// This file is part of the EScript programming language.
// See copyright notice in EScript.h
// ------------------------------------------------------
#ifdef ES_BUILD_APPLICATION
#include <cstdlib>
#include <iostream>
#include <string>

#include "../EScript/EScript.h"

using namespace EScript;

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

	if(argc<2){
		std::cout << ES_VERSION<<"\nNo filename given.\n";
		return EXIT_SUCCESS;
	}

	EScript::init();
	ERef<Runtime> rt(new Runtime());

	// --- Set program parameters
	declareConstant(rt->getGlobals(),"args",Array::create(argc,argv));

	// --- Load and execute script
	std::pair<bool,ObjRef> result = EScript::loadAndExecute(*rt.get(),argv[1]);

	// --- output result
	if (!result.second.isNull()) {
		std::cout << "\n\n --- "<<"\nResult: " << result.second.toString()<<"\n";
	}

	return result.first ? EXIT_SUCCESS : EXIT_FAILURE;
}
#endif // ES_BUILD_APPLICATION

// main.cpp
// This file is part of the EScript programming language.
// See copyright notice in EScript.h
// ------------------------------------------------------
#ifdef ES_BUILD_APPLICATION
#include <cstdlib>
#include <iostream>
#include <string>
#include <utility>

#include "../EScript/EScript.h"

int main(int argc, char * argv[]) {
	EScript::init();
	EScript::ERef<EScript::Runtime> rt(new EScript::Runtime());

	// --- Set program parameters
	declareConstant(rt->getGlobals(), "args", EScript::Array::create(argc, argv));

	// --- Load and execute script
	std::pair<bool, EScript::ObjRef> result;
	if(argc == 1) {
		result = EScript::executeStream(*rt.get(), std::cin);
	} else {
		result = EScript::loadAndExecute(*rt.get(), argv[1]);
	}

	// --- output result
	if(!result.second.isNull()) {
		std::cout << "\n\n --- " << "\nResult: " << result.second.toString() << "\n";
	}

	return result.first ? EXIT_SUCCESS : EXIT_FAILURE;
}

#endif // ES_BUILD_APPLICATION

Change EScript application to support executing a string from a pipe/from stdin.

git-svn-id: 5176f51f660287824ea2012221d52a93094db7fd@194 5693b1fc-3b75-4070-9b6b-3ce3692a40d5


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

void *Thread1(void *p) {
  *(int*)p = 42;
  return 0;
}

void *Thread2(void *p) {
  *(int*)p = 44;;
  return 0;
}

void *alloc() {
  return malloc(99);
}

void *AllocThread(void*) {
  return alloc();
}

int main() {
  void *p = 0;
  pthread_t t[2];
  pthread_create(&t[0], 0, AllocThread, 0);
  pthread_join(t[0], &p);
  fprintf(stderr, "addr=%p\n", p);
  pthread_create(&t[0], 0, Thread1, (char*)p + 16);
  pthread_create(&t[1], 0, Thread2, (char*)p + 16);
  pthread_join(t[0], 0);
  pthread_join(t[1], 0);
  return 0;
}

// CHECK: addr=[[ADDR:0x[0-9,a-f]+]]
// CHECK: WARNING: ThreadSanitizer: data race
//...
// CHECK:   Location is heap block of size 99 at [[ADDR]] allocated by thread 1:
// CHECK:     #0 alloc
// CHECK:     #1 AllocThread
//...
// CHECK:   Thread 1 (finished) created at:
// CHECK:     #0 pthread_create
// CHECK:     #1 main

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

void *Thread1(void *p) {
  *(int*)p = 42;
  return 0;
}

void *Thread2(void *p) {
  *(int*)p = 44;
  return 0;
}

void *alloc() {
  return malloc(99);
}

void *AllocThread(void* arg) {
  return alloc();
}

int main() {
  void *p = 0;
  pthread_t t[2];
  pthread_create(&t[0], 0, AllocThread, 0);
  pthread_join(t[0], &p);
  fprintf(stderr, "addr=%p\n", p);
  pthread_create(&t[0], 0, Thread1, (char*)p + 16);
  pthread_create(&t[1], 0, Thread2, (char*)p + 16);
  pthread_join(t[0], 0);
  pthread_join(t[1], 0);
  return 0;
}

// CHECK: addr=[[ADDR:0x[0-9,a-f]+]]
// CHECK: WARNING: ThreadSanitizer: data race
// ...
// CHECK:   Location is heap block of size 99 at [[ADDR]] allocated by thread 1:
// CHECK:     #0 alloc
// CHECK:     #1 AllocThread
// ...
// CHECK:   Thread 1 (finished) created at:
// CHECK:     #0 pthread_create
// CHECK:     #1 main

Fix style warinings in output test

[TSan] Fix style warinings in output test

git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@162980 91177308-0d34-0410-b5e6-96231b3b80d8


/*
* (C) 2016 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include "tests.h"

#if defined(BOTAN_HAS_PUBLIC_KEY_CRYPTO)
  #include <botan/workfactor.h>
#endif

namespace Botan_Tests {

class PK_Workfactor_Tests : public Text_Based_Test
   {
   public:
      PK_Workfactor_Tests() : Text_Based_Test("pubkey/workfactor.vec",
                                              {"ParamSize", "Workfactor"})
         {}

      Test::Result run_one_test(const std::string& type, const VarMap& vars) override
         {
         const size_t param_size  = get_req_sz(vars, "ParamSize");
         const size_t exp_output  = get_req_sz(vars, "Workfactor");

         size_t output = 0;

         // TODO: test McEliece strength tests also

         if(type == "RSA_Strength")
            output = Botan::if_work_factor(param_size);
         else if(type == "DL_Exponent_Size")
            output = Botan::dl_exponent_size(param_size) / 2;

         Test::Result result(type + " work factor calculation");
         result.test_eq("Calculated workfactor for " + std::to_string(param_size),
                        output, exp_output);
         return result;
         }
   };

BOTAN_REGISTER_TEST("pk_workfactor", PK_Workfactor_Tests);

}

/*
* (C) 2016 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include "tests.h"

#if defined(BOTAN_HAS_PUBLIC_KEY_CRYPTO)
  #include <botan/workfactor.h>
#endif

namespace Botan_Tests {

#if defined(BOTAN_HAS_PUBLIC_KEY_CRYPTO)
class PK_Workfactor_Tests : public Text_Based_Test
   {
   public:
      PK_Workfactor_Tests() : Text_Based_Test("pubkey/workfactor.vec",
                                              {"ParamSize", "Workfactor"})
         {}

      Test::Result run_one_test(const std::string& type, const VarMap& vars) override
         {
         const size_t param_size  = get_req_sz(vars, "ParamSize");
         const size_t exp_output  = get_req_sz(vars, "Workfactor");

         size_t output = 0;

         // TODO: test McEliece strength tests also

         if(type == "RSA_Strength")
            output = Botan::if_work_factor(param_size);
         else if(type == "DL_Exponent_Size")
            output = Botan::dl_exponent_size(param_size) / 2;

         Test::Result result(type + " work factor calculation");
         result.test_eq("Calculated workfactor for " + std::to_string(param_size),
                        output, exp_output);
         return result;
         }
   };

BOTAN_REGISTER_TEST("pk_workfactor", PK_Workfactor_Tests);
#endif

}

Add missing macro check in test

Add missing macro check in test


#include "various.hpp"

#include <fstream>
#include <iostream>
#include <memory>

std::string
utils::slurp_file(std::string const& path)
{
  std::ifstream file = std::ifstream(path);
  if (!file.is_open()) {
    std::cerr << "Failed to open \"" << path << "\"" << std::endl;
    return std::string("");
  }

  file.seekg(0, std::ios::end);
  auto const size = file.tellg();
  file.seekg(0, std::ios::beg);

  std::unique_ptr<char[]> content = std::make_unique<char[]>(static_cast<size_t>(size) + 1ll);
  file.read(content.get(), size);
  content[static_cast<size_t>(size)] = '\0';

  return std::string(content.get());
}

#include "various.hpp"

#include "core/Log.h"

#include <fstream>
#include <iostream>
#include <memory>

std::string
utils::slurp_file(std::string const& path)
{
  std::ifstream file = std::ifstream(path);
  if (!file.is_open()) {
    LogError("Failed to open \"%s\"", path.c_str());
    return std::string("");
  }

  file.seekg(0, std::ios::end);
  auto const size = file.tellg();
  file.seekg(0, std::ios::beg);

  std::unique_ptr<char[]> content = std::make_unique<char[]>(static_cast<size_t>(size) + 1ll);
  file.read(content.get(), size);
  content[static_cast<size_t>(size)] = '\0';

  return std::string(content.get());
}

Use the logging functions in `utils::slurp_file()`

Use `LogError` rather `std::cerr` as the former will also log to the
_log.txt_ file.


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

// Error.cpp: Implements the gl::Error class which encapsulates an OpenGL error
// and optional error message.

#include "libGLESv2/Error.h"

#include "common/angleutils.h"

#include <cstdarg>

namespace gl
{

Error::Error(GLenum errorCode)
    : mCode(errorCode),
      mMessage()
{
}

Error::Error(GLenum errorCode, const std::string &msg, ...)
    : mCode(errorCode),
      mMessage()
{
    va_list vararg;
    va_start(vararg, msg);
    mMessage = Format(msg, vararg);
    va_end(vararg);
}

Error::Error(const Error &other)
    : mCode(other.mCode),
      mMessage(other.mMessage)
{
}

Error &Error::operator=(const Error &other)
{
    mCode = other.mCode;
    mMessage = other.mMessage;
    return *this;
}

}

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

// Error.cpp: Implements the gl::Error class which encapsulates an OpenGL error
// and optional error message.

#include "libGLESv2/Error.h"

#include "common/angleutils.h"

#include <cstdarg>

namespace gl
{

Error::Error(GLenum errorCode)
    : mCode(errorCode),
      mMessage()
{
}

Error::Error(GLenum errorCode, const std::string &msg, ...)
    : mCode(errorCode),
      mMessage()
{
    va_list vararg;
    va_start(vararg, msg);
    mMessage = FormatString(msg, vararg);
    va_end(vararg);
}

Error::Error(const Error &other)
    : mCode(other.mCode),
      mMessage(other.mMessage)
{
}

Error &Error::operator=(const Error &other)
{
    mCode = other.mCode;
    mMessage = other.mMessage;
    return *this;
}

}

Fix compilation error due to bad merge.

Fix compilation error due to bad merge.

Change-Id: I54b3e0423e41b86b28d93fdce8d4d2d3304d56cf
Reviewed-on: https://chromium-review.googlesource.com/213822
Reviewed-by: Geoff Lang <b6fc25fe0362055230985c05cbfa8adb741ccc0f@chromium.org>
Tested-by: Geoff Lang <b6fc25fe0362055230985c05cbfa8adb741ccc0f@chromium.org>


#include "catch.hpp"

#include "libx6adc.h"

TEST_CASE("board present", "[get_num_devices]"){
	SECTION("at least one board present"){
		unsigned numDevices;
		get_num_devices(&numDevices);
		REQUIRE( numDevices >= 1);
	}
}

TEST_CASE("board temperature is sane", "[get_logic_temperature]"){

	connect_x6(0);

	SECTION("reported temperature is between 20C and 70C"){
		float logicTemp;
	    get_logic_temperature(0, &logicTemp);
		REQUIRE( logicTemp > 20 );
		REQUIRE( logicTemp < 70 );
	}

	disconnect_x6(0);
}

TEST_CASE("firmware version", "[get_firmware_version]") {

	connect_x6(0);

	SECTION("firmware version checks") {
		uint16_t ver;

		SECTION("BBN firmware is greater than 0.8"){
			get_firmware_version(0, BBN_X6, &ver);
			REQUIRE( ver >= 0x0008);
		}

		SECTION("BBN QDSP firmware is greater than 1.0"){
			get_firmware_version(0, BBN_QDSP, &ver);
			REQUIRE( ver >= 0x0100);
		}

		SECTION("BBN PG firmware is greater than 0.1"){
			get_firmware_version(0, BBN_PG, &ver);
			REQUIRE( ver >= 0x0001);
		}
	}

	disconnect_x6(0);
}

#include "catch.hpp"

#include "libx6adc.h"

TEST_CASE("board present", "[get_num_devices]"){
	SECTION("at least one board present"){
		unsigned numDevices;
		get_num_devices(&numDevices);
		REQUIRE( numDevices >= 1);
	}
}

TEST_CASE("board temperature is sane", "[get_logic_temperature]"){

	connect_x6(0);

	SECTION("reported temperature is between 20C and 70C"){
		float logicTemp;
	    get_logic_temperature(0, &logicTemp);
		REQUIRE( logicTemp > 20 );
		REQUIRE( logicTemp < 70 );
	}

	disconnect_x6(0);
}

TEST_CASE("firmware version", "[get_firmware_version]") {

	connect_x6(0);

	SECTION("firmware version checks") {
		uint16_t ver;

		get_firmware_version(0, BBN_X6, &ver);
		REQUIRE( ver >= 0x0008);
		get_firmware_version(0, BBN_QDSP, &ver);
		REQUIRE( ver >= 0x0100);
		get_firmware_version(0, BBN_PG, &ver);
		REQUIRE( ver >= 0x0001);
	}

	disconnect_x6(0);
}

Consolidate firmware version checks into single section

Save connect/disconnect time


// https://github.com/KubaO/stackoverflown/tree/master/questions/lineedit-frame-37831979
#include <QtWidgets>
#include <QtUiTools>

const char ui[] = R"EOF(
 <ui version="4.0">
  <class>Form</class>
  <widget class="QWidget" name="Form">
   <layout class="QFormLayout" name="formLayout">
    <item row="0" column="0">
     <widget class="QLabel" name="label">
      <property name="text">
       <string>TextLabel</string>
      </property>
     </widget>
    </item>
    <item row="0" column="1">
     <widget class="QLineEdit" name="lineEdit"/>
    </item>
   </layout>
  </widget>
  <resources/>
  <connections/>
 </ui>)EOF";

int main(int argc, char ** argv) {
   QApplication app{argc, argv};
   QBuffer buf;
   buf.setData(ui, sizeof(ui));
   auto w = QUiLoader().load(&buf);
   auto & layout = *static_cast<QFormLayout*>(w->layout());
   QLineEdit edit;
   layout.addRow("Edit here", &edit);
   w->show();
   return app.exec();
}

// https://github.com/KubaO/stackoverflown/tree/master/questions/lineedit-frame-37831979
#include <QtWidgets>
#include <QtUiTools>

const char ui[] = R"EOF(
 <ui version="4.0">
  <class>Form</class>
  <widget class="QWidget" name="Form">
   <layout class="QFormLayout" name="formLayout">
    <item row="0" column="0">
     <widget class="QLabel" name="label">
      <property name="text">
       <string>TextLabel</string>
      </property>
     </widget>
    </item>
    <item row="0" column="1">
     <widget class="QLineEdit" name="lineEdit"/>
    </item>
   </layout>
  </widget>
  <resources/>
  <connections/>
 </ui>)EOF";

int main(int argc, char ** argv) {
   QApplication app{argc, argv};
   QBuffer buf;
   buf.setData(ui, sizeof(ui));
   auto w = QUiLoader().load(&buf);
   auto & layout = *static_cast<QFormLayout*>(w->layout());
   QLineEdit edit;
   layout.itemAt(0)->widget()->setMinimumHeight(50);
   layout.addRow("Edit here", &edit);
   edit.setMinimumHeight(100);
   layout.activate();
   w->show();
   return app.exec();
}

Tweak to indicate that different sizes still work.


#include "./labels.h"
#include <vector>

std::function<void()>
Labels::subscribe(std::function<void(const Label &)> subscriber)
{
  int erasePosition = subscribers.size();
  subscribers.push_back(subscriber);

  return [this, erasePosition]()
  {
    subscribers.erase(subscribers.begin() + erasePosition);
  };
}

void Labels::add(Label label)
{
  labels[label.id] = label;
  notify(label);
}

std::vector<Label> Labels::getLabels()
{
  std::vector<Label> result(labels.size());
  for (auto &pair : labels)
    result.push_back(pair.second);

  return result;
}

void Labels::updateAnchor(int id, Eigen::Vector3f anchorPosition)
{
  labels[id].anchorPosition = anchorPosition;
  notify(labels[id]);
}

void Labels::notify(const Label& label)
{
  for (auto &subscriber : subscribers)
    subscriber(label);
}

#include "./labels.h"
#include <vector>

std::function<void()>
Labels::subscribe(std::function<void(const Label &)> subscriber)
{
  int erasePosition = subscribers.size();
  subscribers.push_back(subscriber);

  return [this, erasePosition]()
  {
    subscribers.erase(subscribers.begin() + erasePosition);
  };
}

void Labels::add(Label label)
{
  labels[label.id] = label;
  notify(label);
}

std::vector<Label> Labels::getLabels()
{
  std::vector<Label> result;
  for (auto &pair : labels)
    result.push_back(pair.second);

  return result;
}

void Labels::updateAnchor(int id, Eigen::Vector3f anchorPosition)
{
  labels[id].anchorPosition = anchorPosition;
  notify(labels[id]);
}

void Labels::notify(const Label& label)
{
  for (auto &subscriber : subscribers)
    subscriber(label);
}

Fix error in Labels::getLabels: Wrong constructor for vector.