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

#include "Benchmark.h"
#include "Resources.h"
#include "SkBitmap.h"
#include "SkData.h"
#include "SkImageEncoder.h"

#include "sk_tool_utils.h"

class EncodeBench : public Benchmark {
public:
    EncodeBench(const char* filename, SkEncodedImageFormat type, int quality)
        : fFilename(filename)
        , fType(type)
        , fQuality(quality)
    {
        // Set the name of the bench
        SkString name("Encode_");
        name.append(filename);
        name.append("_");
        switch (type) {
            case SkEncodedImageFormat::kJPEG:
                name.append("JPEG");
                break;
            case SkEncodedImageFormat::kPNG:
                name.append("PNG");
                break;
            case SkEncodedImageFormat::kWEBP:
                name.append("WEBP");
                break;
            default:
                name.append("Unknown");
                break;
        }

        fName = name;
    }

    bool isSuitableFor(Backend backend) override { return backend == kNonRendering_Backend; }

    const char* onGetName() override { return fName.c_str(); }

    void onPreDraw(SkCanvas*) override {
#ifdef SK_DEBUG
        bool result =
#endif
        GetResourceAsBitmap(fFilename, &fBitmap);
        SkASSERT(result);
    }

    void onDraw(int loops, SkCanvas*) override {
        for (int i = 0; i < loops; i++) {
            sk_sp<SkData> data(sk_tool_utils::EncodeImageToData(fBitmap, fType, fQuality));
            SkASSERT(data);
        }
    }

private:
    const char*                fFilename;
    const SkEncodedImageFormat fType;
    const int                  fQuality;
    SkString                   fName;
    SkBitmap                   fBitmap;
};

// The Android Photos app uses a quality of 90 on JPEG encodes
DEF_BENCH(return new EncodeBench("mandrill_512.png", SkEncodedImageFormat::kJPEG, 90));
DEF_BENCH(return new EncodeBench("color_wheel.jpg", SkEncodedImageFormat::kJPEG, 90));

// PNG encodes are lossless so quality should be ignored
DEF_BENCH(return new EncodeBench("mandrill_512.png", SkEncodedImageFormat::kPNG, 90));
DEF_BENCH(return new EncodeBench("color_wheel.jpg", SkEncodedImageFormat::kPNG, 90));

// TODO: What is the appropriate quality to use to benchmark WEBP encodes?
DEF_BENCH(return new EncodeBench("mandrill_512.png", SkEncodedImageFormat::kWEBP, 90));
DEF_BENCH(return new EncodeBench("color_wheel.jpg", SkEncodedImageFormat::kWEBP, 90));
<commit_msg>Roll external/skia 1b0126b01..05784d9b1 (1 commits)<commit_after>/*
 * Copyright 2016 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "Benchmark.h"
#include "Resources.h"
#include "SkBitmap.h"
#include "SkJpegEncoder.h"
#include "SkPngEncoder.h"
#include "SkWebpEncoder.h"
#include "SkStream.h"

class EncodeBench : public Benchmark {
public:
    using Encoder = bool (*)(SkWStream*, const SkPixmap&);
    EncodeBench(const char* filename, Encoder encoder, const char* encoderName)
        : fSourceFilename(filename)
        , fEncoder(encoder)
        , fName(SkStringPrintf("Encode_%s_%s", filename, encoderName)) {}

    bool isSuitableFor(Backend backend) override { return backend == kNonRendering_Backend; }

    const char* onGetName() override { return fName.c_str(); }

    void onPreDraw(SkCanvas*) override {
        SkAssertResult(GetResourceAsBitmap(fSourceFilename, &fBitmap));
    }

    void onDraw(int loops, SkCanvas*) override {
        while (loops-- > 0) {
            SkPixmap pixmap;
            SkAssertResult(fBitmap.peekPixels(&pixmap));
            SkNullWStream dst;
            SkAssertResult(fEncoder(&dst, pixmap));
            SkASSERT(dst.bytesWritten() > 0);
        }
    }

private:
    const char* fSourceFilename;
    Encoder     fEncoder;
    SkString    fName;
    SkBitmap    fBitmap;
};

static bool encode_jpeg(SkWStream* dst, const SkPixmap& src) {
    SkJpegEncoder::Options opts;
    opts.fQuality = 90;
    return SkJpegEncoder::Encode(dst, src, opts);
}

static bool encode_webp_lossy(SkWStream* dst, const SkPixmap& src) {
    SkWebpEncoder::Options opts;
    opts.fCompression = SkWebpEncoder::Compression::kLossy;
    opts.fQuality = 90;
    opts.fUnpremulBehavior = SkTransferFunctionBehavior::kIgnore;
    return SkWebpEncoder::Encode(dst, src, opts);
}

static bool encode_webp_lossless(SkWStream* dst, const SkPixmap& src) {
    SkWebpEncoder::Options opts;
    opts.fCompression = SkWebpEncoder::Compression::kLossless;
    opts.fQuality = 90;
    opts.fUnpremulBehavior = SkTransferFunctionBehavior::kIgnore;
    return SkWebpEncoder::Encode(dst, src, opts);
}

static bool encode_png(SkWStream* dst,
                       const SkPixmap& src,
                       SkPngEncoder::FilterFlag filters,
                       int zlibLevel) {
    SkPngEncoder::Options opts;
    opts.fFilterFlags = filters;
    opts.fUnpremulBehavior = SkTransferFunctionBehavior::kIgnore;
    opts.fZLibLevel = zlibLevel;
    return SkPngEncoder::Encode(dst, src, opts);
}

#define PNG(FLAG, ZLIBLEVEL) [](SkWStream* d, const SkPixmap& s) { \
           return encode_png(d, s, SkPngEncoder::FilterFlag::FLAG, ZLIBLEVEL); }

static const char* srcs[2] = {"mandrill_512.png", "color_wheel.jpg"};

// The Android Photos app uses a quality of 90 on JPEG encodes
DEF_BENCH(return new EncodeBench(srcs[0], &encode_jpeg, "JPEG"));
DEF_BENCH(return new EncodeBench(srcs[1], &encode_jpeg, "JPEG"));

// TODO: What is the appropriate quality to use to benchmark WEBP encodes?
DEF_BENCH(return new EncodeBench(srcs[0], encode_webp_lossy, "WEBP"));
DEF_BENCH(return new EncodeBench(srcs[1], encode_webp_lossy, "WEBP"));

DEF_BENCH(return new EncodeBench(srcs[0], encode_webp_lossless, "WEBP_LL"));
DEF_BENCH(return new EncodeBench(srcs[1], encode_webp_lossless, "WEBP_LL"));

DEF_BENCH(return new EncodeBench(srcs[0], PNG(kAll, 6), "PNG"));
DEF_BENCH(return new EncodeBench(srcs[0], PNG(kAll, 3), "PNG_3"));
DEF_BENCH(return new EncodeBench(srcs[0], PNG(kAll, 1), "PNG_1"));

DEF_BENCH(return new EncodeBench(srcs[0], PNG(kSub, 6), "PNG_6s"));
DEF_BENCH(return new EncodeBench(srcs[0], PNG(kSub, 3), "PNG_3s"));
DEF_BENCH(return new EncodeBench(srcs[0], PNG(kSub, 1), "PNG_1s"));

DEF_BENCH(return new EncodeBench(srcs[0], PNG(kNone, 6), "PNG_6n"));
DEF_BENCH(return new EncodeBench(srcs[0], PNG(kNone, 3), "PNG_3n"));
DEF_BENCH(return new EncodeBench(srcs[0], PNG(kNone, 1), "PNG_1n"));

DEF_BENCH(return new EncodeBench(srcs[1], PNG(kAll, 6), "PNG"));
DEF_BENCH(return new EncodeBench(srcs[1], PNG(kAll, 3), "PNG_3"));
DEF_BENCH(return new EncodeBench(srcs[1], PNG(kAll, 1), "PNG_1"));

DEF_BENCH(return new EncodeBench(srcs[1], PNG(kSub, 6), "PNG_6s"));
DEF_BENCH(return new EncodeBench(srcs[1], PNG(kSub, 3), "PNG_3s"));
DEF_BENCH(return new EncodeBench(srcs[1], PNG(kSub, 1), "PNG_1s"));

DEF_BENCH(return new EncodeBench(srcs[1], PNG(kNone, 6), "PNG_6n"));
DEF_BENCH(return new EncodeBench(srcs[1], PNG(kNone, 3), "PNG_3n"));
DEF_BENCH(return new EncodeBench(srcs[1], PNG(kNone, 1), "PNG_1n"));

#undef PNG
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * Version: MPL 1.1 / GPLv3+ / LGPLv3+
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License or as specified alternatively below. You may obtain a copy of
 * the License at http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Major Contributor(s):
 * [ Copyright (C) 2011 Markus Mohrhard <markus.mohrhard@googlemail.com> (initial developer) ]
 *
 * All Rights Reserved.
 *
 * For minor contributions see the git repository.
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 3 or later (the "GPLv3+"), or
 * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
 * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
 * instead of those above.
 */

/**
 * Print nicely formatted sheet content to stdout.  Indispensable when
 * debugging the unit test code involving testing of sheet contents.
 */

#include <rtl/strbuf.hxx>
#include <rtl/ustring.hxx>
#include "document.hxx"

#ifdef WNT
#define NOMINMAX
#include <prewin.h>
#include <postwin.h>
#undef NOMINMAX
#endif

#define MDDS_HASH_CONTAINER_BOOST 1
#include <mdds/mixed_type_matrix.hpp>

#include <iostream>

using namespace ::com::sun::star;
using ::rtl::OUString;
using ::rtl::OUStringBuffer;
using ::std::cout;
using ::std::cerr;
using ::std::endl;
using ::std::vector;

namespace {

::std::ostream& operator<< (::std::ostream& os, const rtl::OUString& str)
{
    return os << ::rtl::OUStringToOString(str, RTL_TEXTENCODING_UTF8).getStr();
}

}

class SheetPrinter
{
    typedef ::mdds::mixed_type_matrix<OUString, bool> MatrixType;
public:
    SheetPrinter(size_t rows, size_t cols) :
        maMatrix(rows, cols, ::mdds::matrix_density_sparse_empty) {}

    void set(size_t row, size_t col, const OUString& aStr)
    {
        maMatrix.set_string(row, col, new OUString(aStr));
    }

#if CALC_DEBUG_OUTPUT
    void print(const char* header) const
    {
        if (header)
            cout << header << endl;

        MatrixType::size_pair_type ns = maMatrix.size();
        vector<sal_Int32> aColWidths(ns.second, 0);

        // Calculate column widths first.
        for (size_t row = 0; row < ns.first; ++row)
        {
            for (size_t col = 0; col < ns.second; ++col)
            {
                const OUString* p = maMatrix.get_string(row, col);
                if (aColWidths[col] < p->getLength())
                    aColWidths[col] = p->getLength();
            }
        }

        // Make the row separator string.
        OUStringBuffer aBuf;
        aBuf.appendAscii("+");
        for (size_t col = 0; col < ns.second; ++col)
        {
            aBuf.appendAscii("-");
            for (sal_Int32 i = 0; i < aColWidths[col]; ++i)
                aBuf.append(sal_Unicode('-'));
            aBuf.appendAscii("-+");
        }

        OUString aSep = aBuf.makeStringAndClear();

        // Now print to stdout.
        cout << aSep << endl;
        for (size_t row = 0; row < ns.first; ++row)
        {
            cout << "| ";
            for (size_t col = 0; col < ns.second; ++col)
            {
                const OUString* p = maMatrix.get_string(row, col);
                size_t nPadding = aColWidths[col] - p->getLength();
                aBuf.append(*p);
                for (size_t i = 0; i < nPadding; ++i)
                    aBuf.append(sal_Unicode(' '));
                cout << aBuf.makeStringAndClear() << " | ";
            }
            cout << endl;
            cout << aSep << endl;
        }
    }
#else
    void print(const char*) const {}
#endif

    /**
     * Print nested string array which can be copy-n-pasted into the test code
     * for content verification.
     */
    void printArray() const
    {
#if CALC_DEBUG_OUTPUT
        MatrixType::size_pair_type ns = maMatrix.size();
        for (size_t row = 0; row < ns.first; ++row)
        {
            cout << "    { ";
            for (size_t col = 0; col < ns.second; ++col)
            {
                const OUString* p = maMatrix.get_string(row, col);
                if (p->getLength())
                    cout << "\"" << *p << "\"";
                else
                    cout << "0";
                if (col < ns.second - 1)
                    cout << ", ";
            }
            cout << " }";
            if (row < ns.first - 1)
                cout << ",";
            cout << endl;
        }
#endif
    }

    void clear() { maMatrix.clear(); }
    void resize(size_t rows, size_t cols) { maMatrix.resize(rows, cols); }

private:
    MatrixType maMatrix;
};

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>WaE: unused function<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * Version: MPL 1.1 / GPLv3+ / LGPLv3+
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License or as specified alternatively below. You may obtain a copy of
 * the License at http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Major Contributor(s):
 * [ Copyright (C) 2011 Markus Mohrhard <markus.mohrhard@googlemail.com> (initial developer) ]
 *
 * All Rights Reserved.
 *
 * For minor contributions see the git repository.
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 3 or later (the "GPLv3+"), or
 * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
 * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
 * instead of those above.
 */

/**
 * Print nicely formatted sheet content to stdout.  Indispensable when
 * debugging the unit test code involving testing of sheet contents.
 */

#include <rtl/strbuf.hxx>
#include <rtl/ustring.hxx>
#include "document.hxx"

#ifdef WNT
#define NOMINMAX
#include <prewin.h>
#include <postwin.h>
#undef NOMINMAX
#endif

#define MDDS_HASH_CONTAINER_BOOST 1
#include <mdds/mixed_type_matrix.hpp>

#include <iostream>

using namespace ::com::sun::star;
using ::rtl::OUString;
using ::rtl::OUStringBuffer;
using ::std::cout;
using ::std::cerr;
using ::std::endl;
using ::std::vector;

namespace {

#ifdef __GNUC__
__attribute__((used))
#endif
::std::ostream& operator<< (::std::ostream& os, const rtl::OUString& str)
{
    return os << ::rtl::OUStringToOString(str, RTL_TEXTENCODING_UTF8).getStr();
}

}

class SheetPrinter
{
    typedef ::mdds::mixed_type_matrix<OUString, bool> MatrixType;
public:
    SheetPrinter(size_t rows, size_t cols) :
        maMatrix(rows, cols, ::mdds::matrix_density_sparse_empty) {}

    void set(size_t row, size_t col, const OUString& aStr)
    {
        maMatrix.set_string(row, col, new OUString(aStr));
    }

#if CALC_DEBUG_OUTPUT
    void print(const char* header) const
    {
        if (header)
            cout << header << endl;

        MatrixType::size_pair_type ns = maMatrix.size();
        vector<sal_Int32> aColWidths(ns.second, 0);

        // Calculate column widths first.
        for (size_t row = 0; row < ns.first; ++row)
        {
            for (size_t col = 0; col < ns.second; ++col)
            {
                const OUString* p = maMatrix.get_string(row, col);
                if (aColWidths[col] < p->getLength())
                    aColWidths[col] = p->getLength();
            }
        }

        // Make the row separator string.
        OUStringBuffer aBuf;
        aBuf.appendAscii("+");
        for (size_t col = 0; col < ns.second; ++col)
        {
            aBuf.appendAscii("-");
            for (sal_Int32 i = 0; i < aColWidths[col]; ++i)
                aBuf.append(sal_Unicode('-'));
            aBuf.appendAscii("-+");
        }

        OUString aSep = aBuf.makeStringAndClear();

        // Now print to stdout.
        cout << aSep << endl;
        for (size_t row = 0; row < ns.first; ++row)
        {
            cout << "| ";
            for (size_t col = 0; col < ns.second; ++col)
            {
                const OUString* p = maMatrix.get_string(row, col);
                size_t nPadding = aColWidths[col] - p->getLength();
                aBuf.append(*p);
                for (size_t i = 0; i < nPadding; ++i)
                    aBuf.append(sal_Unicode(' '));
                cout << aBuf.makeStringAndClear() << " | ";
            }
            cout << endl;
            cout << aSep << endl;
        }
    }
#else
    void print(const char*) const {}
#endif

    /**
     * Print nested string array which can be copy-n-pasted into the test code
     * for content verification.
     */
    void printArray() const
    {
#if CALC_DEBUG_OUTPUT
        MatrixType::size_pair_type ns = maMatrix.size();
        for (size_t row = 0; row < ns.first; ++row)
        {
            cout << "    { ";
            for (size_t col = 0; col < ns.second; ++col)
            {
                const OUString* p = maMatrix.get_string(row, col);
                if (p->getLength())
                    cout << "\"" << *p << "\"";
                else
                    cout << "0";
                if (col < ns.second - 1)
                    cout << ", ";
            }
            cout << " }";
            if (row < ns.first - 1)
                cout << ",";
            cout << endl;
        }
#endif
    }

    void clear() { maMatrix.clear(); }
    void resize(size_t rows, size_t cols) { maMatrix.resize(rows, cols); }

private:
    MatrixType maMatrix;
};

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#include <sys/time.h>
#include <sys/types.h>
#include <sys/syscall.h>
#define gettid() syscall(__NR_gettid)

#include "thread_private.h"
#include "parameters.h"

#define NUM_PAGES (40960 * nthreads)

extern bool verify_read_content;

void check_read_content(char *buf, int size, off_t off)
{
	// I assume the space in the buffer is larger than 8 bytes.
	off_t aligned_off = off & (~(sizeof(off_t) - 1));
	long data[2];
	data[0] = aligned_off / sizeof(off_t);
	data[1] = aligned_off / sizeof(off_t) + 1;
	long expected = 0;
	int copy_size = size < (int) sizeof(off_t) ? size : (int) sizeof(off_t);
	memcpy(&expected, ((char *) data) + (off - aligned_off), copy_size);
	long read_value = 0;
	memcpy(&read_value, buf, copy_size);
	if(read_value != expected)
		printf("%ld %ld\n", read_value, expected);
	assert(read_value == expected);
}

void create_write_data(char *buf, int size, off_t off)
{
	off_t aligned_start = off & (~(sizeof(off_t) - 1));
	off_t aligned_end = (off + size) & (~(sizeof(off_t) - 1));
	long start_data = aligned_start / sizeof(off_t);
	long end_data = aligned_end / sizeof(off_t);

	int first_size =  (int)(sizeof(off_t) - (off - aligned_start));
	if (first_size == sizeof(off_t))
		first_size = 0;
	if (first_size)
		memcpy(buf, ((char *) &start_data) + (off - aligned_start),
				first_size);
	for (int i = first_size; i < size; i += sizeof(off_t)) {
		*((long *) (buf + i)) = (off + i) / sizeof(off_t);
	}
	if (aligned_end > aligned_start) {
		int last_size = (int) (off + size - aligned_end);
		if (last_size)
			memcpy(buf + (aligned_end - off), (char *) &end_data, last_size);
	}

	check_read_content(buf, size, off);
}

class cleanup_callback: public callback
{
	rand_buf *buf;
	ssize_t read_bytes;
	int thread_id;
public:
	cleanup_callback(rand_buf *buf, int idx) {
		this->buf = buf;
		read_bytes = 0;
		this->thread_id = idx;
	}

	int invoke(io_request *rq) {
		extern bool verify_read_content;
		if (rq->get_access_method() == READ && verify_read_content) {
			off_t off = rq->get_offset();
			for (int i = 0; i < rq->get_num_bufs(); i++) {
				check_read_content(rq->get_buf(i), rq->get_buf_size(i), off);
				off += rq->get_buf_size(i);
			}
		}
		for (int i = 0; i < rq->get_num_bufs(); i++)
			buf->free_entry(rq->get_buf(i));
		read_bytes += rq->get_size();
		return 0;
	}

	ssize_t get_size() {
		return read_bytes;
	}
};

ssize_t thread_private::get_read_bytes() {
	if (cb)
		return cb->get_size();
	else
		return read_bytes;
}

int thread_private::thread_init() {
	attach2cpu();
	io->init();

	extern int buf_size;
	rand_buf *buf = new rand_buf(NUM_PAGES / (nthreads
				// TODO maybe I should set the right entry size for a buffer.
				// If each access size is irregular, I'll break each access
				// into pages so each access is no larger than a page, so it
				// should workl fine.
				/ NUM_NODES) * PAGE_SIZE, buf_size);
	this->buf = buf;
	if (io->support_aio()) {
		cb = new cleanup_callback(buf, idx);
		io->set_callback(cb);
	}
	return 0;
}

int thread_private::run()
{
	ssize_t ret = -1;
	gettimeofday(&start_time, NULL);
	io_request reqs[NUM_REQS_BY_USER];
	char *entry = NULL;
	if (!io->support_aio()) {
		extern int buf_size;
		entry = (char *) valloc(buf_size);
	}
	while (gen->has_next()) {
		if (io->support_aio()) {
			int i;
			for (i = 0; i < NUM_REQS_BY_USER && gen->has_next(); ) {
				workload_t workload = gen->next();
				int access_method = workload.read ? READ : WRITE;
				off_t off = workload.off;
				int size = workload.size;
				/*
				 * If the size of the request is larger than a page size,
				 * and the user explicitly wants to use multibuf requests.
				 */
				if (buf_type == MULTI_BUF) {
					assert(off % PAGE_SIZE == 0);
					int num_vecs = size / PAGE_SIZE;
					reqs[i].init(off, io, access_method);
					assert(buf->get_entry_size() >= PAGE_SIZE);
					for (int k = 0; k < num_vecs; k++) {
						reqs[i].add_buf(buf->next_entry(PAGE_SIZE), PAGE_SIZE);
					}
					i++;
				}
				else if (buf_type == SINGLE_SMALL_BUF) {
again:
					while (size > 0 && i < NUM_REQS_BY_USER) {
						off_t next_off = ROUNDUP_PAGE(off + 1);
						if (next_off > off + size)
							next_off = off + size;
						char *p = buf->next_entry(next_off - off);
						if (access_method == WRITE)
							create_write_data(p, next_off - off, off);
						reqs[i].init(p, off, next_off - off, access_method, io);
						size -= next_off - off;
						off = next_off;
						i++;
					}
					if (size > 0) {
						ret = io->access(reqs, i);
						i = 0;
						goto again;
					}
				}
				else {
					assert(buf->get_entry_size() >= size);
					char *p = buf->next_entry(size);
					if (access_method == WRITE)
						create_write_data(p, size, off);
					reqs[i++].init(p, off, size, access_method, io);
				}
			}
			ret = io->access(reqs, i);
			if (ret < 0) {
				perror("access_vector");
				exit(1);
			}
		}
		else {
			workload_t workload = gen->next();
			off_t off = workload.off;
			// TODO let's just read data first.
			int access_method = workload.read ? READ : WRITE;
			int entry_size = workload.size;

			if (buf_type == SINGLE_SMALL_BUF) {
				while (entry_size > 0) {
					/*
					 * generate the data for writing the file,
					 * so the data in the file isn't changed.
					 */
					if (access_method == WRITE) {
						create_write_data(entry, entry_size, off);
					}
					// There is at least one byte we need to access in the page.
					// By adding 1 and rounding up the offset, we'll get the next page
					// behind the current offset.
					off_t next_off = ROUNDUP_PAGE(off + 1);
					if (next_off > off + entry_size)
						next_off = off + entry_size;
					ret = io->access(entry, off, next_off - off, access_method);
					if (ret > 0) {
						if (access_method == READ && verify_read_content) {
							check_read_content(entry, next_off - off, off);
						}
						read_bytes += ret;
					}
					if (ret < 0) {
						perror("access");
						exit(1);
					}
					entry_size -= next_off - off;
					off = next_off;
				}
			}
			else {
				if (access_method == WRITE) {
					create_write_data(entry, entry_size, off);
				}
				ret = io->access(entry, off, entry_size, access_method);
				if (ret > 0) {
					if (access_method == READ && verify_read_content) {
						check_read_content(entry, entry_size, off);
					}
					read_bytes += ret;
				}
				if (ret < 0) {
					perror("access");
					exit(1);
				}
			}
		}
	}
	io->cleanup();
	printf("thread %d exits\n", idx);
	gettimeofday(&end_time, NULL);
	return 0;
}

int thread_private::attach2cpu()
{
#if NCPUS > 0
	cpu_set_t cpuset;
	pthread_t thread = pthread_self();
	CPU_ZERO(&cpuset);
	int cpu_num = idx % NCPUS;
	CPU_SET(cpu_num, &cpuset);
	int ret = pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset);
	if (ret != 0) {
		perror("pthread_setaffinity_np");
		exit(1);
	}
	printf("attach thread %d to CPU %d\n", idx, cpu_num);
	return ret;
#else
	return -1;
#endif
}

static void *rand_read(void *arg)
{
	thread_private *priv = (thread_private *) arg;

	printf("rand_read: pid: %d, tid: %ld\n", getpid(), gettid());
	priv->thread_init();
	priv->run();
	return NULL;
}

#ifdef USE_PROCESS
static int process_create(pid_t *pid, void (*func)(void *), void *priv)
{
	pid_t id = fork();

	if (id < 0)
		return -1;

	if (id == 0) {	// child
		func(priv);
		exit(0);
	}

	if (id > 0)
		*pid = id;
	return 0;
}

static int process_join(pid_t pid)
{
	int status;
	pid_t ret = waitpid(pid, &status, 0);
	return ret < 0 ? ret : 0;
}
#endif

int thread_private::start_thread()
{
	int ret;
#ifdef USE_PROCESS
	ret = process_create(&id, rand_read, (void *) this);
#else
	ret = pthread_create(&id, NULL, rand_read, (void *) this);
#endif
	return ret;
}

int thread_private::wait_thread_end()
{
	int ret;
#ifdef USE_PROCESS
	ret = process_join(id);
#else
	ret = pthread_join(id, NULL);
#endif
	return ret;
}
<commit_msg>fix bugs in creating data for writing.<commit_after>#include <sys/time.h>
#include <sys/types.h>
#include <sys/syscall.h>
#define gettid() syscall(__NR_gettid)

#include "thread_private.h"
#include "parameters.h"

#define NUM_PAGES (40960 * nthreads)

extern bool verify_read_content;

void check_read_content(char *buf, int size, off_t off)
{
	// I assume the space in the buffer is larger than 8 bytes.
	off_t aligned_off = off & (~(sizeof(off_t) - 1));
	long data[2];
	data[0] = aligned_off / sizeof(off_t);
	data[1] = aligned_off / sizeof(off_t) + 1;
	long expected = 0;
	int copy_size = size < (int) sizeof(off_t) ? size : (int) sizeof(off_t);
	memcpy(&expected, ((char *) data) + (off - aligned_off), copy_size);
	long read_value = 0;
	memcpy(&read_value, buf, copy_size);
	if(read_value != expected)
		printf("%ld %ld\n", read_value, expected);
	assert(read_value == expected);
}

void create_write_data(char *buf, int size, off_t off)
{
	off_t aligned_start = off & (~(sizeof(off_t) - 1));
	off_t aligned_end = (off + size) & (~(sizeof(off_t) - 1));
	long start_data = aligned_start / sizeof(off_t);
	long end_data = aligned_end / sizeof(off_t);

	/* If all data is in one 8-byte word. */
	if (aligned_start == aligned_end) {
		memcpy(buf, ((char *) &start_data) + (off - aligned_start), size);
		return;
	}

	int first_size =  (int)(sizeof(off_t) - (off - aligned_start));
	int last_size = (int) (off + size - aligned_end);

	if (first_size == sizeof(off_t))
		first_size = 0;
	if (first_size)
		memcpy(buf, ((char *) &start_data) + (off - aligned_start),
				first_size);
	for (int i = first_size; i < aligned_end - off; i += sizeof(off_t)) {
		*((long *) (buf + i)) = (off + i) / sizeof(off_t);
	}
	if (aligned_end > aligned_start
			|| (aligned_end == aligned_start && first_size == 0)) {
		if (last_size)
			memcpy(buf + (aligned_end - off), (char *) &end_data, last_size);
	}

	check_read_content(buf, size, off);
}

class cleanup_callback: public callback
{
	rand_buf *buf;
	ssize_t read_bytes;
	int thread_id;
public:
	cleanup_callback(rand_buf *buf, int idx) {
		this->buf = buf;
		read_bytes = 0;
		this->thread_id = idx;
	}

	int invoke(io_request *rq) {
		extern bool verify_read_content;
		if (rq->get_access_method() == READ && verify_read_content) {
			off_t off = rq->get_offset();
			for (int i = 0; i < rq->get_num_bufs(); i++) {
				check_read_content(rq->get_buf(i), rq->get_buf_size(i), off);
				off += rq->get_buf_size(i);
			}
		}
		for (int i = 0; i < rq->get_num_bufs(); i++)
			buf->free_entry(rq->get_buf(i));
		read_bytes += rq->get_size();
		return 0;
	}

	ssize_t get_size() {
		return read_bytes;
	}
};

ssize_t thread_private::get_read_bytes() {
	if (cb)
		return cb->get_size();
	else
		return read_bytes;
}

int thread_private::thread_init() {
	attach2cpu();
	io->init();

	extern int buf_size;
	rand_buf *buf = new rand_buf(NUM_PAGES / (nthreads
				// TODO maybe I should set the right entry size for a buffer.
				// If each access size is irregular, I'll break each access
				// into pages so each access is no larger than a page, so it
				// should workl fine.
				/ NUM_NODES) * PAGE_SIZE, buf_size);
	this->buf = buf;
	if (io->support_aio()) {
		cb = new cleanup_callback(buf, idx);
		io->set_callback(cb);
	}
	return 0;
}

int thread_private::run()
{
	ssize_t ret = -1;
	gettimeofday(&start_time, NULL);
	io_request reqs[NUM_REQS_BY_USER];
	char *entry = NULL;
	if (!io->support_aio()) {
		extern int buf_size;
		entry = (char *) valloc(buf_size);
	}
	while (gen->has_next()) {
		if (io->support_aio()) {
			int i;
			for (i = 0; i < NUM_REQS_BY_USER && gen->has_next(); ) {
				workload_t workload = gen->next();
				int access_method = workload.read ? READ : WRITE;
				off_t off = workload.off;
				int size = workload.size;
				/*
				 * If the size of the request is larger than a page size,
				 * and the user explicitly wants to use multibuf requests.
				 */
				if (buf_type == MULTI_BUF) {
					assert(off % PAGE_SIZE == 0);
					int num_vecs = size / PAGE_SIZE;
					reqs[i].init(off, io, access_method);
					assert(buf->get_entry_size() >= PAGE_SIZE);
					for (int k = 0; k < num_vecs; k++) {
						reqs[i].add_buf(buf->next_entry(PAGE_SIZE), PAGE_SIZE);
					}
					i++;
				}
				else if (buf_type == SINGLE_SMALL_BUF) {
again:
					while (size > 0 && i < NUM_REQS_BY_USER) {
						off_t next_off = ROUNDUP_PAGE(off + 1);
						if (next_off > off + size)
							next_off = off + size;
						char *p = buf->next_entry(next_off - off);
						if (access_method == WRITE)
							create_write_data(p, next_off - off, off);
						reqs[i].init(p, off, next_off - off, access_method, io);
						size -= next_off - off;
						off = next_off;
						i++;
					}
					if (size > 0) {
						ret = io->access(reqs, i);
						i = 0;
						goto again;
					}
				}
				else {
					assert(buf->get_entry_size() >= size);
					char *p = buf->next_entry(size);
					if (access_method == WRITE)
						create_write_data(p, size, off);
					reqs[i++].init(p, off, size, access_method, io);
				}
			}
			ret = io->access(reqs, i);
			if (ret < 0) {
				perror("access_vector");
				exit(1);
			}
		}
		else {
			workload_t workload = gen->next();
			off_t off = workload.off;
			// TODO let's just read data first.
			int access_method = workload.read ? READ : WRITE;
			int entry_size = workload.size;

			if (buf_type == SINGLE_SMALL_BUF) {
				while (entry_size > 0) {
					/*
					 * generate the data for writing the file,
					 * so the data in the file isn't changed.
					 */
					if (access_method == WRITE) {
						create_write_data(entry, entry_size, off);
					}
					// There is at least one byte we need to access in the page.
					// By adding 1 and rounding up the offset, we'll get the next page
					// behind the current offset.
					off_t next_off = ROUNDUP_PAGE(off + 1);
					if (next_off > off + entry_size)
						next_off = off + entry_size;
					ret = io->access(entry, off, next_off - off, access_method);
					if (ret > 0) {
						if (access_method == READ && verify_read_content) {
							check_read_content(entry, next_off - off, off);
						}
						read_bytes += ret;
					}
					if (ret < 0) {
						perror("access");
						exit(1);
					}
					entry_size -= next_off - off;
					off = next_off;
				}
			}
			else {
				if (access_method == WRITE) {
					create_write_data(entry, entry_size, off);
				}
				ret = io->access(entry, off, entry_size, access_method);
				if (ret > 0) {
					if (access_method == READ && verify_read_content) {
						check_read_content(entry, entry_size, off);
					}
					read_bytes += ret;
				}
				if (ret < 0) {
					perror("access");
					exit(1);
				}
			}
		}
	}
	io->cleanup();
	printf("thread %d exits\n", idx);
	gettimeofday(&end_time, NULL);
	return 0;
}

int thread_private::attach2cpu()
{
#if NCPUS > 0
	cpu_set_t cpuset;
	pthread_t thread = pthread_self();
	CPU_ZERO(&cpuset);
	int cpu_num = idx % NCPUS;
	CPU_SET(cpu_num, &cpuset);
	int ret = pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset);
	if (ret != 0) {
		perror("pthread_setaffinity_np");
		exit(1);
	}
	printf("attach thread %d to CPU %d\n", idx, cpu_num);
	return ret;
#else
	return -1;
#endif
}

static void *rand_read(void *arg)
{
	thread_private *priv = (thread_private *) arg;

	printf("rand_read: pid: %d, tid: %ld\n", getpid(), gettid());
	priv->thread_init();
	priv->run();
	return NULL;
}

#ifdef USE_PROCESS
static int process_create(pid_t *pid, void (*func)(void *), void *priv)
{
	pid_t id = fork();

	if (id < 0)
		return -1;

	if (id == 0) {	// child
		func(priv);
		exit(0);
	}

	if (id > 0)
		*pid = id;
	return 0;
}

static int process_join(pid_t pid)
{
	int status;
	pid_t ret = waitpid(pid, &status, 0);
	return ret < 0 ? ret : 0;
}
#endif

int thread_private::start_thread()
{
	int ret;
#ifdef USE_PROCESS
	ret = process_create(&id, rand_read, (void *) this);
#else
	ret = pthread_create(&id, NULL, rand_read, (void *) this);
#endif
	return ret;
}

int thread_private::wait_thread_end()
{
	int ret;
#ifdef USE_PROCESS
	ret = process_join(id);
#else
	ret = pthread_join(id, NULL);
#endif
	return ret;
}
<|endoftext|>


<commit_before>#include "otc/otcli.h"
using namespace otc;

// Note that the "taxonomy" data member here will be the first tree (the supertree)
struct DistanceState : public TaxonomyDependentTreeProcessor<TreeMappedWithSplits> {
    unsigned long totalRF;
    unsigned long totalNumNotDisplayed;
    unsigned long totalNumInternals;
    unsigned long totalNumDisplayed;
    bool showRF;
    bool showNumNotDisplayed;
    bool showNumInternals;
    bool showNumDisplayed;
    std::string prevTreeFilename;
    std::size_t numComparisons;
    std::size_t numTreesInThisTreefile;

    virtual ~DistanceState(){}
    DistanceState()
        :totalRF(0U),
        totalNumNotDisplayed(0U),
        totalNumInternals(0U),
        totalNumDisplayed(0U),
        showRF(false),
        showNumNotDisplayed(false),
        showNumInternals(false),
        showNumDisplayed(false),
        numComparisons(0U),
        numTreesInThisTreefile(0U) {
    }

    bool processSourceTree(OTCLI & otCLI, std::unique_ptr<TreeMappedWithSplits> tree) {
        numComparisons += 1;
        std::string nameToPrint = otCLI.currentFilename;
        if (nameToPrint == prevTreeFilename) {
            numTreesInThisTreefile += 1;
            nameToPrint += "-tree#" + std::to_string(numTreesInThisTreefile);
        } else {
            prevTreeFilename = nameToPrint;
            numTreesInThisTreefile = 1;
        }
        assert(tree != nullptr);
        assert(taxonomy != nullptr);
        std::set<std::set<long> > inducedSplits;
        std::set<std::set<long> > tree2Splits;
        inducedCladeSets(*taxonomy, *tree, inducedSplits, tree2Splits, true);
        unsigned long rf = 0;
        unsigned long numNotDisplayed = 0;
        const unsigned long numInternals = tree2Splits.size();
        unsigned long numDisplayed = 0;
        totalNumInternals += numInternals;
        if (showRF) {
            rf = sizeOfSymmetricDifference(tree2Splits, inducedSplits);
            totalRF += rf;
        }
        if (showNumDisplayed || showNumNotDisplayed) {
            for (auto ics : tree2Splits) {
                if (contains(inducedSplits, ics)) {
                    numDisplayed += 1;
                } else {
                    numNotDisplayed += 1;
                }
            }
            totalNumNotDisplayed += numNotDisplayed;
        }
        // display
        // header if first comparison
        if (numComparisons == 1) {
            otCLI.out << "treename";
            if (showRF) {
                otCLI.out << "\tRF";
            }
            if (showNumNotDisplayed) {
                otCLI.out << "\tNumNotDisplayed";
            }
            if (showNumDisplayed) {
                otCLI.out << "\tNumDisplayed";
            }
            if (showNumNotDisplayed) {
                otCLI.out << "\tNumInternals";
            }
            otCLI.out << '\n';
        }
        otCLI.out << nameToPrint;
        if (showRF) {
            otCLI.out << '\t' << rf;
        }
        if (showNumNotDisplayed) {
            otCLI.out << '\t' << numNotDisplayed;
        }
        if (showNumDisplayed) {
            otCLI.out << '\t' << numDisplayed;
        }
        if (showNumNotDisplayed) {
            otCLI.out << '\t' << numInternals;
        }
        otCLI.out << '\n';
        return true;
    }
    bool summarize(OTCLI & otCLI) override {
        otCLI.out << "TOTALS";
        if (showRF) {
            otCLI.out << '\t' << totalRF;
        }
        if (showNumNotDisplayed) {
            otCLI.out << '\t' << totalNumNotDisplayed;
        }
        if (showNumDisplayed) {
            otCLI.out << '\t' << totalNumDisplayed;
        }
        if (showNumNotDisplayed) {
            otCLI.out << '\t' << totalNumInternals;
        }
        otCLI.out << '\n';
        return true;
    }

};

int main(int argc, char *argv[]) {
    OTCLI otCLI("otc-distance",
                "takes at least 2 newick file paths: a supertree and some number of input trees. Writes one line for each input tree with the statistics requested for the comparison of the supertree to each input tree.",
                "synth.tre inp1.tre inp2.tre");
    DistanceState proc;
    auto rc = taxDependentTreeProcessingMain(otCLI, argc, argv, proc, 2, true);
    return rc;
}
<commit_msg>flags for otc-distance<commit_after>#include "otc/otcli.h"
using namespace otc;

// Note that the "taxonomy" data member here will be the first tree (the supertree)
struct DistanceState : public TaxonomyDependentTreeProcessor<TreeMappedWithSplits> {
    unsigned long totalRF;
    unsigned long totalNumNotDisplayed;
    unsigned long totalNumInternals;
    unsigned long totalNumDisplayed;
    bool showRF;
    bool showNumNotDisplayed;
    bool showNumInternals;
    bool showNumDisplayed;
    std::string prevTreeFilename;
    std::size_t numComparisons;
    std::size_t numTreesInThisTreefile;

    virtual ~DistanceState(){}
    DistanceState()
        :totalRF(0U),
        totalNumNotDisplayed(0U),
        totalNumInternals(0U),
        totalNumDisplayed(0U),
        showRF(false),
        showNumNotDisplayed(false),
        showNumInternals(false),
        showNumDisplayed(false),
        numComparisons(0U),
        numTreesInThisTreefile(0U) {
    }

    bool processSourceTree(OTCLI & otCLI, std::unique_ptr<TreeMappedWithSplits> tree) {
        numComparisons += 1;
        std::string nameToPrint = otCLI.currentFilename;
        if (nameToPrint == prevTreeFilename) {
            numTreesInThisTreefile += 1;
            nameToPrint += "-tree#" + std::to_string(numTreesInThisTreefile);
        } else {
            prevTreeFilename = nameToPrint;
            numTreesInThisTreefile = 1;
        }
        assert(tree != nullptr);
        assert(taxonomy != nullptr);
        std::set<std::set<long> > inducedSplits;
        std::set<std::set<long> > tree2Splits;
        inducedCladeSets(*taxonomy, *tree, inducedSplits, tree2Splits, true);
        unsigned long rf = 0;
        unsigned long numNotDisplayed = 0;
        const unsigned long numInternals = tree2Splits.size();
        unsigned long numDisplayed = 0;
        totalNumInternals += numInternals;
        if (showRF) {
            rf = sizeOfSymmetricDifference(tree2Splits, inducedSplits);
            totalRF += rf;
        }
        if (showNumDisplayed || showNumNotDisplayed) {
            for (auto ics : tree2Splits) {
                if (contains(inducedSplits, ics)) {
                    numDisplayed += 1;
                } else {
                    numNotDisplayed += 1;
                }
            }
            totalNumNotDisplayed += numNotDisplayed;
            totalNumDisplayed += numDisplayed;

        }
        // display
        // header if first comparison
        if (numComparisons == 1) {
            otCLI.out << "treename";
            if (showRF) {
                otCLI.out << "\tRF";
            }
            if (showNumNotDisplayed) {
                otCLI.out << "\tNumNotDisplayed";
            }
            if (showNumDisplayed) {
                otCLI.out << "\tNumDisplayed";
            }
            if (showNumNotDisplayed) {
                otCLI.out << "\tNumInternals";
            }
            otCLI.out << '\n';
        }
        otCLI.out << nameToPrint;
        if (showRF) {
            otCLI.out << '\t' << rf;
        }
        if (showNumNotDisplayed) {
            otCLI.out << '\t' << numNotDisplayed;
        }
        if (showNumDisplayed) {
            otCLI.out << '\t' << numDisplayed;
        }
        if (showNumNotDisplayed) {
            otCLI.out << '\t' << numInternals;
        }
        otCLI.out << '\n';
        return true;
    }
    bool summarize(OTCLI & otCLI) override {
        otCLI.out << "TOTALS";
        if (showRF) {
            otCLI.out << '\t' << totalRF;
        }
        if (showNumNotDisplayed) {
            otCLI.out << '\t' << totalNumNotDisplayed;
        }
        if (showNumDisplayed) {
            otCLI.out << '\t' << totalNumDisplayed;
        }
        if (showNumNotDisplayed) {
            otCLI.out << '\t' << totalNumInternals;
        }
        otCLI.out << '\n';
        return true;
    }

};

bool handleShowRF(OTCLI & otCLI, const std::string &);
bool handleShowNumDisplayed(OTCLI & otCLI, const std::string &);
bool handleShowShowNumNotDisplayed(OTCLI & otCLI, const std::string &);
bool handleShowInternals(OTCLI & otCLI, const std::string &);

bool handleShowRF(OTCLI & otCLI, const std::string &) {
    DistanceState * proc = static_cast<DistanceState *>(otCLI.blob);
    assert(proc != nullptr);
    proc->showRF = true;
    return true;
}

bool handleShowNumDisplayed(OTCLI & otCLI, const std::string &) {
    DistanceState * proc = static_cast<DistanceState *>(otCLI.blob);
    assert(proc != nullptr);
    proc->showNumDisplayed = true;
    return true;
}

bool handleShowShowNumNotDisplayed(OTCLI & otCLI, const std::string &) {
    DistanceState * proc = static_cast<DistanceState *>(otCLI.blob);
    assert(proc != nullptr);
    proc->showNumNotDisplayed = true;
    return true;
}

bool handleShowInternals(OTCLI & otCLI, const std::string &) {
    DistanceState * proc = static_cast<DistanceState *>(otCLI.blob);
    assert(proc != nullptr);
    proc->showNumInternals = true;
    return true;
}

int main(int argc, char *argv[]) {
    OTCLI otCLI("otc-distance",
                "takes at least 2 newick file paths: a supertree and some number of input trees. Writes one line for each input tree with the statistics requested for the comparison of the supertree to each input tree.",
                "synth.tre inp1.tre inp2.tre");
    DistanceState proc;
    otCLI.addFlag('r',
                  "Show RF symmetric distance",
                  handleShowRF,
                  false);
    otCLI.addFlag('d',
                  "Show number of grouping in each input displayed on full tree",
                  handleShowNumDisplayed,
                  false);
    otCLI.addFlag('n',
                  "Show number of grouping in each input NOT displayed on full tree",
                  handleShowShowNumNotDisplayed,
                  false);
    otCLI.addFlag('i',
                  "Show the number of internal groupings in each input tree",
                  handleShowInternals,
                  false);

    auto rc = taxDependentTreeProcessingMain(otCLI, argc, argv, proc, 2, true);
    return rc;
}
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Copyright 2015 Cloudius Systems
 *
 * Modified by Cloudius Systems
 */

#pragma once

#include "gms/inet_address.hh"

#include <seastar/core/sstring.hh>
#include <seastar/net/api.hh>

#include <experimental/optional>

namespace transport {

class event {
public:
    enum class event_type { TOPOLOGY_CHANGE, STATUS_CHANGE, SCHEMA_CHANGE };

    const event_type type;

private:
    event(const event_type& type_)
        : type{type_}
    { }
public:

#if 0
    public static Event deserialize(ByteBuf cb, int version)
    {
        switch (CBUtil.readEnumValue(Type.class, cb))
        {
            case TOPOLOGY_CHANGE:
                return TopologyChange.deserializeEvent(cb, version);
            case STATUS_CHANGE:
                return StatusChange.deserializeEvent(cb, version);
            case SCHEMA_CHANGE:
                return SchemaChange.deserializeEvent(cb, version);
        }
        throw new AssertionError();
    }

    public void serialize(ByteBuf dest, int version)
    {
        CBUtil.writeEnumValue(type, dest);
        serializeEvent(dest, version);
    }

    public int serializedSize(int version)
    {
        return CBUtil.sizeOfEnumValue(type) + eventSerializedSize(version);
    }

    protected abstract void serializeEvent(ByteBuf dest, int version);
    protected abstract int eventSerializedSize(int version);
#endif
    class topology_change;
    class status_change;
    class schema_change;
};

    class event::topology_change : public event {
    public:
        enum class change_type { NEW_NODE, REMOVED_NODE, MOVED_NODE };

        const change_type change;
        const ipv4_addr node;

        topology_change(change_type change, const ipv4_addr& node)
            : event{event_type::TOPOLOGY_CHANGE}
            , change{change}
            , node{node}
        { }

        static topology_change new_node(const gms::inet_address& host, uint16_t port)
        {
            return topology_change{change_type::NEW_NODE, ipv4_addr{host.raw_addr(), port}};
        }

        static topology_change removed_node(const gms::inet_address& host, uint16_t port)
        {
            return topology_change{change_type::REMOVED_NODE, ipv4_addr{host.raw_addr(), port}};
        }

        static topology_change moved_node(const gms::inet_address& host, uint16_t port)
        {
            return topology_change{change_type::MOVED_NODE, ipv4_addr{host.raw_addr(), port}};
        }

#if 0
        // Assumes the type has already been deserialized
        private static TopologyChange deserializeEvent(ByteBuf cb, int version)
        {
            Change change = CBUtil.readEnumValue(Change.class, cb);
            InetSocketAddress node = CBUtil.readInet(cb);
            return new TopologyChange(change, node);
        }

        protected void serializeEvent(ByteBuf dest, int version)
        {
            CBUtil.writeEnumValue(change, dest);
            CBUtil.writeInet(node, dest);
        }

        protected int eventSerializedSize(int version)
        {
            return CBUtil.sizeOfEnumValue(change) + CBUtil.sizeOfInet(node);
        }

        @Override
        public String toString()
        {
            return change + " " + node;
        }

        @Override
        public int hashCode()
        {
            return Objects.hashCode(change, node);
        }

        @Override
        public boolean equals(Object other)
        {
            if (!(other instanceof TopologyChange))
                return false;

            TopologyChange tpc = (TopologyChange)other;
            return Objects.equal(change, tpc.change)
                && Objects.equal(node, tpc.node);
        }
#endif
    };

    class event::status_change : public event {
    public:
        enum class status_type { UP, DOWN };

        const status_type status;
        const ipv4_addr node;

        status_change(status_type status, const ipv4_addr& node)
            : event{event_type::STATUS_CHANGE}
            , status{status}
            , node{node}
        { }

        static status_change node_up(const gms::inet_address& host, uint16_t port)
        {
            return status_change{status_type::UP, ipv4_addr{host.raw_addr(), port}};
        }

        static status_change node_down(const gms::inet_address& host, uint16_t port)
        {
            return status_change{status_type::DOWN, ipv4_addr{host.raw_addr(), port}};
        }

#if 0
        // Assumes the type has already been deserialized
        private static StatusChange deserializeEvent(ByteBuf cb, int version)
        {
            Status status = CBUtil.readEnumValue(Status.class, cb);
            InetSocketAddress node = CBUtil.readInet(cb);
            return new StatusChange(status, node);
        }

        protected void serializeEvent(ByteBuf dest, int version)
        {
            CBUtil.writeEnumValue(status, dest);
            CBUtil.writeInet(node, dest);
        }

        protected int eventSerializedSize(int version)
        {
            return CBUtil.sizeOfEnumValue(status) + CBUtil.sizeOfInet(node);
        }

        @Override
        public String toString()
        {
            return status + " " + node;
        }

        @Override
        public int hashCode()
        {
            return Objects.hashCode(status, node);
        }

        @Override
        public boolean equals(Object other)
        {
            if (!(other instanceof StatusChange))
                return false;

            StatusChange stc = (StatusChange)other;
            return Objects.equal(status, stc.status)
                && Objects.equal(node, stc.node);
        }
#endif
    };

    class event::schema_change : public event {
    public:
        enum class change_type { CREATED, UPDATED, DROPPED };
        enum class target_type { KEYSPACE, TABLE, TYPE };

        const change_type change;
        const target_type target;
        const sstring keyspace;
        const std::experimental::optional<sstring> table_or_type_or_function;

        schema_change(const change_type change_, const target_type target_, const sstring& keyspace_, const std::experimental::optional<sstring>& table_or_type_or_function_)
            : event{event_type::SCHEMA_CHANGE}
            , change{change_}
            , target{target_}
            , keyspace{keyspace_}
            , table_or_type_or_function{table_or_type_or_function_}
        {
#if 0
            if (target != Target.KEYSPACE)
                assert this.tableOrTypeOrFunction != null : "Table or type should be set for non-keyspace schema change events";
#endif
        }

        schema_change(const change_type change_, const sstring keyspace_)
            : schema_change{change_, target_type::KEYSPACE, keyspace_, std::experimental::optional<sstring>{}}
        { }
#if 0
        // Assumes the type has already been deserialized
        public static SchemaChange deserializeEvent(ByteBuf cb, int version)
        {
            Change change = CBUtil.readEnumValue(Change.class, cb);
            if (version >= 3)
            {
                Target target = CBUtil.readEnumValue(Target.class, cb);
                String keyspace = CBUtil.readString(cb);
                String tableOrType = target == Target.KEYSPACE ? null : CBUtil.readString(cb);
                return new SchemaChange(change, target, keyspace, tableOrType);
            }
            else
            {
                String keyspace = CBUtil.readString(cb);
                String table = CBUtil.readString(cb);
                return new SchemaChange(change, table.isEmpty() ? Target.KEYSPACE : Target.TABLE, keyspace, table.isEmpty() ? null : table);
            }
        }

        public void serializeEvent(ByteBuf dest, int version)
        {
            if (version >= 3)
            {
                CBUtil.writeEnumValue(change, dest);
                CBUtil.writeEnumValue(target, dest);
                CBUtil.writeString(keyspace, dest);
                if (target != Target.KEYSPACE)
                    CBUtil.writeString(tableOrTypeOrFunction, dest);
            }
            else
            {
                if (target == Target.TYPE)
                {
                    // For the v1/v2 protocol, we have no way to represent type changes, so we simply say the keyspace
                    // was updated.  See CASSANDRA-7617.
                    CBUtil.writeEnumValue(Change.UPDATED, dest);
                    CBUtil.writeString(keyspace, dest);
                    CBUtil.writeString("", dest);
                }
                else
                {
                    CBUtil.writeEnumValue(change, dest);
                    CBUtil.writeString(keyspace, dest);
                    CBUtil.writeString(target == Target.KEYSPACE ? "" : tableOrTypeOrFunction, dest);
                }
            }
        }

        public int eventSerializedSize(int version)
        {
            if (version >= 3)
            {
                int size = CBUtil.sizeOfEnumValue(change)
                         + CBUtil.sizeOfEnumValue(target)
                         + CBUtil.sizeOfString(keyspace);

                if (target != Target.KEYSPACE)
                    size += CBUtil.sizeOfString(tableOrTypeOrFunction);

                return size;
            }
            else
            {
                if (target == Target.TYPE)
                {
                    return CBUtil.sizeOfEnumValue(Change.UPDATED)
                         + CBUtil.sizeOfString(keyspace)
                         + CBUtil.sizeOfString("");
                }
                return CBUtil.sizeOfEnumValue(change)
                     + CBUtil.sizeOfString(keyspace)
                     + CBUtil.sizeOfString(target == Target.KEYSPACE ? "" : tableOrTypeOrFunction);
            }
        }

        @Override
        public String toString()
        {
            return change + " " + target + " " + keyspace + (tableOrTypeOrFunction == null ? "" : "." + tableOrTypeOrFunction);
        }

        @Override
        public int hashCode()
        {
            return Objects.hashCode(change, target, keyspace, tableOrTypeOrFunction);
        }

        @Override
        public boolean equals(Object other)
        {
            if (!(other instanceof SchemaChange))
                return false;

            SchemaChange scc = (SchemaChange)other;
            return Objects.equal(change, scc.change)
                && Objects.equal(target, scc.target)
                && Objects.equal(keyspace, scc.keyspace)
                && Objects.equal(tableOrTypeOrFunction, scc.tableOrTypeOrFunction);
        }
#endif
    };

}
<commit_msg>transport/event: Eliminate ifdef'd code<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Copyright 2015 Cloudius Systems
 *
 * Modified by Cloudius Systems
 */

#pragma once

#include "gms/inet_address.hh"

#include <seastar/core/sstring.hh>
#include <seastar/net/api.hh>

#include <experimental/optional>

namespace transport {

class event {
public:
    enum class event_type { TOPOLOGY_CHANGE, STATUS_CHANGE, SCHEMA_CHANGE };

    const event_type type;

private:
    event(const event_type& type_)
        : type{type_}
    { }
public:

    class topology_change;
    class status_change;
    class schema_change;
};

    class event::topology_change : public event {
    public:
        enum class change_type { NEW_NODE, REMOVED_NODE, MOVED_NODE };

        const change_type change;
        const ipv4_addr node;

        topology_change(change_type change, const ipv4_addr& node)
            : event{event_type::TOPOLOGY_CHANGE}
            , change{change}
            , node{node}
        { }

        static topology_change new_node(const gms::inet_address& host, uint16_t port)
        {
            return topology_change{change_type::NEW_NODE, ipv4_addr{host.raw_addr(), port}};
        }

        static topology_change removed_node(const gms::inet_address& host, uint16_t port)
        {
            return topology_change{change_type::REMOVED_NODE, ipv4_addr{host.raw_addr(), port}};
        }

        static topology_change moved_node(const gms::inet_address& host, uint16_t port)
        {
            return topology_change{change_type::MOVED_NODE, ipv4_addr{host.raw_addr(), port}};
        }
    };

    class event::status_change : public event {
    public:
        enum class status_type { UP, DOWN };

        const status_type status;
        const ipv4_addr node;

        status_change(status_type status, const ipv4_addr& node)
            : event{event_type::STATUS_CHANGE}
            , status{status}
            , node{node}
        { }

        static status_change node_up(const gms::inet_address& host, uint16_t port)
        {
            return status_change{status_type::UP, ipv4_addr{host.raw_addr(), port}};
        }

        static status_change node_down(const gms::inet_address& host, uint16_t port)
        {
            return status_change{status_type::DOWN, ipv4_addr{host.raw_addr(), port}};
        }
    };

    class event::schema_change : public event {
    public:
        enum class change_type { CREATED, UPDATED, DROPPED };
        enum class target_type { KEYSPACE, TABLE, TYPE };

        const change_type change;
        const target_type target;
        const sstring keyspace;
        const std::experimental::optional<sstring> table_or_type_or_function;

        schema_change(const change_type change_, const target_type target_, const sstring& keyspace_, const std::experimental::optional<sstring>& table_or_type_or_function_)
            : event{event_type::SCHEMA_CHANGE}
            , change{change_}
            , target{target_}
            , keyspace{keyspace_}
            , table_or_type_or_function{table_or_type_or_function_}
        {
#if 0
            if (target != Target.KEYSPACE)
                assert this.tableOrTypeOrFunction != null : "Table or type should be set for non-keyspace schema change events";
#endif
        }

        schema_change(const change_type change_, const sstring keyspace_)
            : schema_change{change_, target_type::KEYSPACE, keyspace_, std::experimental::optional<sstring>{}}
        { }
    };

}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _PROPREAD_HXX_
#define _PROPREAD_HXX_

#include <map>
#include <boost/ptr_container/ptr_vector.hpp>

#include <tools/solar.h>
#include <sot/storage.hxx>
#include <tools/gen.hxx>
#include <tools/list.hxx>
#include <tools/stream.hxx>
#include <tools/datetime.hxx>

#include <tools/string.hxx>

// SummaryInformation
#define PID_TITLE               0x02
#define PID_SUBJECT             0x03
#define PID_AUTHOR              0x04
#define PID_KEYWORDS            0x05
#define PID_COMMENTS            0x06
#define PID_TEMPLATE            0x07
#define PID_LASTAUTHOR          0x08
#define PID_REVNUMBER           0x09
#define PID_EDITTIME            0x0a
#define PID_LASTPRINTED_DTM     0x0b
#define PID_CREATE_DTM          0x0c
#define PID_LASTSAVED_DTM       0x0d

// DocumentSummaryInformation
#define PID_CATEGORY            0x02
#define PID_PRESFORMAT          0x03
#define PID_BYTECOUNT           0x04
#define PID_LINECOUNT           0x05
#define PID_PARACOUNT           0x06
#define PID_SLIDECOUNT          0x07
#define PID_NOTECOUNT           0x08
#define PID_HIDDENCOUNT         0x09
#define PID_MMCLIPCOUNT         0x0a
#define PID_SCALE               0x0b
#define PID_HEADINGPAIR         0x0c
#define PID_DOCPARTS            0x0d
#define PID_MANAGER             0x0e
#define PID_COMPANY             0x0f
#define PID_LINKSDIRTY          0x10

#define VT_EMPTY            0
#define VT_NULL             1
#define VT_I2               2
#define VT_I4               3
#define VT_R4               4
#define VT_R8               5
#define VT_CY               6
#define VT_DATE             7
#define VT_BSTR             8
#define VT_UI4              9
#define VT_ERROR            10
#define VT_BOOL             11
#define VT_VARIANT          12
#define VT_DECIMAL          14
#define VT_I1               16
#define VT_UI1              17
#define VT_UI2              18
#define VT_I8               20
#define VT_UI8              21
#define VT_INT              22
#define VT_UINT             23
#define VT_LPSTR            30
#define VT_LPWSTR           31
#define VT_FILETIME         64
#define VT_BLOB             65
#define VT_STREAM           66
#define VT_STORAGE          67
#define VT_STREAMED_OBJECT  68
#define VT_STORED_OBJECT    69
#define VT_BLOB_OBJECT      70
#define VT_CF               71
#define VT_CLSID            72
#define VT_VECTOR           0x1000
#define VT_ARRAY            0x2000
#define VT_BYREF            0x4000
#define VT_TYPEMASK         0xFFF

// ------------------------------------------------------------------------

typedef std::map<String,sal_uInt32> Dictionary;

struct PropEntry
{
    sal_uInt32  mnId;
    sal_uInt32  mnSize;
    sal_uInt16  mnTextEnc;
    sal_uInt8*  mpBuf;

    PropEntry( sal_uInt32 nId, const sal_uInt8* pBuf, sal_uInt32 nBufSize, sal_uInt16 nTextEnc );
    PropEntry( const PropEntry& rProp );
    ~PropEntry() { delete[] mpBuf; } ;

    const PropEntry& operator=(const PropEntry& rPropEntry);
};

class PropItem : public SvMemoryStream
{
        sal_uInt16      mnTextEnc;

    public :
                        PropItem(){};
        void            Clear();

        void            SetTextEncoding( sal_uInt16 nTextEnc ){ mnTextEnc = nTextEnc; };
        sal_Bool        Read( String& rString, sal_uInt32 nType = VT_EMPTY, sal_Bool bDwordAlign = sal_True );
        PropItem&       operator=( PropItem& rPropItem );

    using SvStream::Read;
};

// ------------------------------------------------------------------------

class Section
{
        sal_uInt16              mnTextEnc;
        boost::ptr_vector<PropEntry> maEntries;

    protected:

        sal_uInt8                   aFMTID[ 16 ];

        void                    AddProperty( sal_uInt32 nId, const sal_uInt8* pBuf, sal_uInt32 nBufSize );

    public:
                                Section( const sal_uInt8* pFMTID );
                                Section( const Section& rSection );

        Section&                operator=( const Section& rSection );
        sal_Bool                GetProperty( sal_uInt32 nId, PropItem& rPropItem );
        sal_Bool                GetDictionary( Dictionary& rDict );
        const sal_uInt8*        GetFMTID() const { return aFMTID; };
        void                    Read( SvStorageStream* pStrm );
};

// ------------------------------------------------------------------------

class PropRead
{
        sal_Bool                mbStatus;
        SvStorageStreamRef      mpSvStream;

        sal_uInt16              mnByteOrder;
        sal_uInt16              mnFormat;
        sal_uInt16              mnVersionLo;
        sal_uInt16              mnVersionHi;
        sal_uInt8               mApplicationCLSID[ 16 ];
        boost::ptr_vector<Section> maSections;

        void                    AddSection( Section& rSection );

    public:
                                PropRead( SvStorage& rSvStorage, const String& rName );

        PropRead&               operator=( const PropRead& rPropRead );
        const Section*          GetSection( const sal_uInt8* pFMTID );
        sal_Bool                IsValid() const { return mbStatus; };
        void                    Read();
};

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Remove tools/list.hxx include<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _PROPREAD_HXX_
#define _PROPREAD_HXX_

#include <map>
#include <boost/ptr_container/ptr_vector.hpp>

#include <tools/solar.h>
#include <sot/storage.hxx>
#include <tools/gen.hxx>
#include <tools/stream.hxx>
#include <tools/datetime.hxx>

#include <tools/string.hxx>

// SummaryInformation
#define PID_TITLE               0x02
#define PID_SUBJECT             0x03
#define PID_AUTHOR              0x04
#define PID_KEYWORDS            0x05
#define PID_COMMENTS            0x06
#define PID_TEMPLATE            0x07
#define PID_LASTAUTHOR          0x08
#define PID_REVNUMBER           0x09
#define PID_EDITTIME            0x0a
#define PID_LASTPRINTED_DTM     0x0b
#define PID_CREATE_DTM          0x0c
#define PID_LASTSAVED_DTM       0x0d

// DocumentSummaryInformation
#define PID_CATEGORY            0x02
#define PID_PRESFORMAT          0x03
#define PID_BYTECOUNT           0x04
#define PID_LINECOUNT           0x05
#define PID_PARACOUNT           0x06
#define PID_SLIDECOUNT          0x07
#define PID_NOTECOUNT           0x08
#define PID_HIDDENCOUNT         0x09
#define PID_MMCLIPCOUNT         0x0a
#define PID_SCALE               0x0b
#define PID_HEADINGPAIR         0x0c
#define PID_DOCPARTS            0x0d
#define PID_MANAGER             0x0e
#define PID_COMPANY             0x0f
#define PID_LINKSDIRTY          0x10

#define VT_EMPTY            0
#define VT_NULL             1
#define VT_I2               2
#define VT_I4               3
#define VT_R4               4
#define VT_R8               5
#define VT_CY               6
#define VT_DATE             7
#define VT_BSTR             8
#define VT_UI4              9
#define VT_ERROR            10
#define VT_BOOL             11
#define VT_VARIANT          12
#define VT_DECIMAL          14
#define VT_I1               16
#define VT_UI1              17
#define VT_UI2              18
#define VT_I8               20
#define VT_UI8              21
#define VT_INT              22
#define VT_UINT             23
#define VT_LPSTR            30
#define VT_LPWSTR           31
#define VT_FILETIME         64
#define VT_BLOB             65
#define VT_STREAM           66
#define VT_STORAGE          67
#define VT_STREAMED_OBJECT  68
#define VT_STORED_OBJECT    69
#define VT_BLOB_OBJECT      70
#define VT_CF               71
#define VT_CLSID            72
#define VT_VECTOR           0x1000
#define VT_ARRAY            0x2000
#define VT_BYREF            0x4000
#define VT_TYPEMASK         0xFFF

// ------------------------------------------------------------------------

typedef std::map<String,sal_uInt32> Dictionary;

struct PropEntry
{
    sal_uInt32  mnId;
    sal_uInt32  mnSize;
    sal_uInt16  mnTextEnc;
    sal_uInt8*  mpBuf;

    PropEntry( sal_uInt32 nId, const sal_uInt8* pBuf, sal_uInt32 nBufSize, sal_uInt16 nTextEnc );
    PropEntry( const PropEntry& rProp );
    ~PropEntry() { delete[] mpBuf; } ;

    const PropEntry& operator=(const PropEntry& rPropEntry);
};

class PropItem : public SvMemoryStream
{
        sal_uInt16      mnTextEnc;

    public :
                        PropItem(){};
        void            Clear();

        void            SetTextEncoding( sal_uInt16 nTextEnc ){ mnTextEnc = nTextEnc; };
        sal_Bool        Read( String& rString, sal_uInt32 nType = VT_EMPTY, sal_Bool bDwordAlign = sal_True );
        PropItem&       operator=( PropItem& rPropItem );

    using SvStream::Read;
};

// ------------------------------------------------------------------------

class Section
{
        sal_uInt16              mnTextEnc;
        boost::ptr_vector<PropEntry> maEntries;

    protected:

        sal_uInt8                   aFMTID[ 16 ];

        void                    AddProperty( sal_uInt32 nId, const sal_uInt8* pBuf, sal_uInt32 nBufSize );

    public:
                                Section( const sal_uInt8* pFMTID );
                                Section( const Section& rSection );

        Section&                operator=( const Section& rSection );
        sal_Bool                GetProperty( sal_uInt32 nId, PropItem& rPropItem );
        sal_Bool                GetDictionary( Dictionary& rDict );
        const sal_uInt8*        GetFMTID() const { return aFMTID; };
        void                    Read( SvStorageStream* pStrm );
};

// ------------------------------------------------------------------------

class PropRead
{
        sal_Bool                mbStatus;
        SvStorageStreamRef      mpSvStream;

        sal_uInt16              mnByteOrder;
        sal_uInt16              mnFormat;
        sal_uInt16              mnVersionLo;
        sal_uInt16              mnVersionHi;
        sal_uInt8               mApplicationCLSID[ 16 ];
        boost::ptr_vector<Section> maSections;

        void                    AddSection( Section& rSection );

    public:
                                PropRead( SvStorage& rSvStorage, const String& rName );

        PropRead&               operator=( const PropRead& rPropRead );
        const Section*          GetSection( const sal_uInt8* pFMTID );
        sal_Bool                IsValid() const { return mbStatus; };
        void                    Read();
};

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#define _REENTRANT

#include <cstdio>
#include "sync_objs.h"
#include "loom.h"
#include <pthread.h>
#include <semaphore.h>
using namespace std;

static pthread_mutex_t mutexes[MAX_N_FIXES];
static sem_t sems[MAX_N_FIXES];

void init_sync_objs() {
	for (int i = 0; i < MAX_N_FIXES; ++i) {
		pthread_mutex_init(&mutexes[i], NULL);
		sem_init(&sems[i], 0, 0);
	}
}

int enter_critical_region(argument_t arg) {
	long fix_id = (long)arg;
	pthread_mutex_lock(&mutexes[fix_id]);
	fprintf(stderr, "enter_critical_region %p\n", &mutexes[fix_id]);
	return 0;
}

int exit_critical_region(argument_t arg) {
	long fix_id = (long)arg;
	fprintf(stderr, "exit_critical_region %p\n", &mutexes[fix_id]);
	pthread_mutex_unlock(&mutexes[fix_id]);
	return 0;
}

int enter_atomic_region(argument_t arg) {
	return __enter_atomic_region();
}

int exit_atomic_region(argument_t arg) {
	return __exit_atomic_region();
}

int semaphore_up(argument_t arg) {
	fprintf(stderr, "semaphore_up\n");
	long fix_id = (long)arg;
	sem_post(&sems[fix_id]);
	return 0;
}

int semaphore_down(argument_t arg) {
	fprintf(stderr, "semaphore_down\n");
	long fix_id = (long)arg;
	sem_wait(&sems[fix_id]);
	return 0;
}

<commit_msg>printing enter/exit inside the critical region<commit_after>#define _REENTRANT

#include <cstdio>
#include "sync_objs.h"
#include "loom.h"
#include <pthread.h>
#include <semaphore.h>
using namespace std;

static pthread_mutex_t mutexes[MAX_N_FIXES];
static sem_t sems[MAX_N_FIXES];

void init_sync_objs() {
	for (int i = 0; i < MAX_N_FIXES; ++i) {
		pthread_mutex_init(&mutexes[i], NULL);
		sem_init(&sems[i], 0, 0);
	}
}

int enter_critical_region(argument_t arg) {
	long fix_id = (long)arg;
	pthread_mutex_lock(&mutexes[fix_id]);
	// fprintf(stderr, "enter_critical_region %p\n", &mutexes[fix_id]);
	return 0;
}

int exit_critical_region(argument_t arg) {
	long fix_id = (long)arg;
	// fprintf(stderr, "exit_critical_region %p\n", &mutexes[fix_id]);
	pthread_mutex_unlock(&mutexes[fix_id]);
	return 0;
}

int enter_atomic_region(argument_t arg) {
	return __enter_atomic_region();
}

int exit_atomic_region(argument_t arg) {
	return __exit_atomic_region();
}

int semaphore_up(argument_t arg) {
	fprintf(stderr, "semaphore_up\n");
	long fix_id = (long)arg;
	sem_post(&sems[fix_id]);
	return 0;
}

int semaphore_down(argument_t arg) {
	fprintf(stderr, "semaphore_down\n");
	long fix_id = (long)arg;
	sem_wait(&sems[fix_id]);
	return 0;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: patattr.hxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: rt $ $Date: 2004-08-23 09:25:17 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SC_SCPATATR_HXX
#define SC_SCPATATR_HXX

#ifndef _SFXPOOLITEM_HXX //autogen
#include <svtools/poolitem.hxx>
#endif

#ifndef _SFXITEMSET_HXX //autogen
#include <svtools/itemset.hxx>
#endif

#ifndef _SV_FONTCVT_HXX
#include <vcl/fontcvt.hxx>
#endif

#ifndef _SVX_SVXENUM_HXX
#include <svx/svxenum.hxx>
#endif

#ifndef INCLUDED_SCDLLAPI_H
#include "scdllapi.h"
#endif

class Font;
class OutputDevice;
class Fraction;
class ScStyleSheet;
class SvNumberFormatter;
class ScDocument;

//  how to treat COL_AUTO in GetFont:

enum ScAutoFontColorMode
{
    SC_AUTOCOL_RAW,         // COL_AUTO is returned
    SC_AUTOCOL_BLACK,       // always use black
    SC_AUTOCOL_PRINT,       // black or white, depending on background
    SC_AUTOCOL_DISPLAY,     // from style settings, or black/white if needed
    SC_AUTOCOL_IGNOREFONT,  // like DISPLAY, but ignore stored font color (assume COL_AUTO)
    SC_AUTOCOL_IGNOREBACK,  // like DISPLAY, but ignore stored background color (use configured color)
    SC_AUTOCOL_IGNOREALL    // like DISPLAY, but ignore stored font and background colors
};

class SC_DLLPUBLIC ScPatternAttr: public SfxSetItem
{
    String*         pName;
    ScStyleSheet*   pStyle;
public:
    static ScDocument* pDoc;
                            ScPatternAttr(SfxItemSet* pItemSet, const String& rStyleName);
                            ScPatternAttr(SfxItemSet* pItemSet, ScStyleSheet* pStyleSheet = NULL);
                            ScPatternAttr(SfxItemPool* pItemPool);
                            ScPatternAttr(const ScPatternAttr& rPatternAttr);

                            ~ScPatternAttr();

    virtual SfxPoolItem*    Clone( SfxItemPool *pPool = 0 ) const;
    virtual SfxPoolItem*    Create(SvStream& rStream, USHORT nVersion) const;
    virtual SvStream&       Store(SvStream& rStream, USHORT nItemVersion) const;

    virtual int             operator==(const SfxPoolItem& rCmp) const;

    const SfxPoolItem&      GetItem( USHORT nWhich ) const
                                        { return GetItemSet().Get(nWhich); }

    static const SfxPoolItem& GetItem( USHORT nWhich, const SfxItemSet& rItemSet, const SfxItemSet* pCondSet );
    const SfxPoolItem&      GetItem( USHORT nWhich, const SfxItemSet* pCondSet ) const;

                            // pWhich sind keine Ranges, sondern einzelne IDs, 0-terminiert
    BOOL                    HasItemsSet( const USHORT* pWhich ) const;
    void                    ClearItems( const USHORT* pWhich );

    void                    DeleteUnchanged( const ScPatternAttr* pOldAttrs );

    static SvxCellOrientation GetCellOrientation( const SfxItemSet& rItemSet, const SfxItemSet* pCondSet = 0 );
    SvxCellOrientation      GetCellOrientation( const SfxItemSet* pCondSet = 0 ) const;

    /** Static helper function to fill a font object from the passed item set. */
    static void             GetFont( Font& rFont, const SfxItemSet& rItemSet,
                                        ScAutoFontColorMode eAutoMode,
                                        OutputDevice* pOutDev = NULL,
                                        const Fraction* pScale = NULL,
                                        const SfxItemSet* pCondSet = NULL,
                                        BYTE nScript = 0, const Color* pBackConfigColor = NULL,
                                        const Color* pTextConfigColor = NULL );
    /** Fills a font object from the own item set. */
    void                    GetFont( Font& rFont, ScAutoFontColorMode eAutoMode,
                                        OutputDevice* pOutDev = NULL,
                                        const Fraction* pScale = NULL,
                                        const SfxItemSet* pCondSet = NULL,
                                        BYTE nScript = 0, const Color* pBackConfigColor = NULL,
                                        const Color* pTextConfigColor = NULL ) const;

    /** Converts all Calc items contained in rSrcSet to edit engine items and puts them into rEditSet. */
    static void             FillToEditItemSet( SfxItemSet& rEditSet, const SfxItemSet& rSrcSet, const SfxItemSet* pCondSet = NULL );
    /** Converts all Calc items contained in the own item set to edit engine items and puts them into pEditSet. */
    void                    FillEditItemSet( SfxItemSet* pEditSet, const SfxItemSet* pCondSet = NULL ) const;

    /** Converts all edit engine items contained in rEditSet to Calc items and puts them into rDestSet. */
    static void             GetFromEditItemSet( SfxItemSet& rDestSet, const SfxItemSet& rEditSet );
    /** Converts all edit engine items contained in pEditSet to Calc items and puts them into the own item set. */
    void                    GetFromEditItemSet( const SfxItemSet* pEditSet );

    void                    FillEditParaItems( SfxItemSet* pSet ) const;

    ScPatternAttr*          PutInPool( ScDocument* pDestDoc, ScDocument* pSrcDoc ) const;

    void                    SetStyleSheet(ScStyleSheet* pNewStyle);
    const ScStyleSheet*     GetStyleSheet() const  { return pStyle; }
    const String*           GetStyleName() const;
    void                    UpdateStyleSheet();
    void                    StyleToName();

    BOOL                    IsVisible() const;
    BOOL                    IsVisibleEqual( const ScPatternAttr& rOther ) const;

                            /** If font is an old symbol font StarBats/StarMath
                                with text encoding RTL_TEXTENC_SYMBOL */
    BOOL                    IsSymbolFont() const;

                            /** Create a FontToSubsFontConverter if needed for
                                this pattern, else return 0.

                                @param nFlags is the bit mask which shall be
                                used for CreateFontToSubsFontConverter().

                                The converter must be destroyed by the caller
                                using DestroyFontToSubsFontConverter() which
                                should be accomplished using the
                                ScFontToSubsFontConverter_AutoPtr
                             */
    FontToSubsFontConverter GetSubsFontConverter( ULONG nFlags ) const;

    ULONG                   GetNumberFormat( SvNumberFormatter* ) const;
    ULONG                   GetNumberFormat( SvNumberFormatter* pFormatter,
                                                const SfxItemSet* pCondSet ) const;

    long                    GetRotateVal( const SfxItemSet* pCondSet ) const;
    BYTE                    GetRotateDir( const SfxItemSet* pCondSet ) const;
};

class ScFontToSubsFontConverter_AutoPtr
{
            FontToSubsFontConverter h;

            void                    release()
                                    {
                                        if ( h )
                                            DestroyFontToSubsFontConverter( h );
                                    }

                                // prevent usage
                                ScFontToSubsFontConverter_AutoPtr( const ScFontToSubsFontConverter_AutoPtr& );
    ScFontToSubsFontConverter_AutoPtr& operator=( const ScFontToSubsFontConverter_AutoPtr& );

public:
                                ScFontToSubsFontConverter_AutoPtr()
                                    : h(0)
                                    {}
                                ~ScFontToSubsFontConverter_AutoPtr()
                                    {
                                        release();
                                    }

    ScFontToSubsFontConverter_AutoPtr& operator=( FontToSubsFontConverter hN )
                                    {
                                        release();
                                        h = hN;
                                        return *this;
                                    }

            operator FontToSubsFontConverter() const
                                    { return h; }
};

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.11.346); FILE MERGED 2005/09/05 15:00:53 rt 1.11.346.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: patattr.hxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 17:48:10 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SC_SCPATATR_HXX
#define SC_SCPATATR_HXX

#ifndef _SFXPOOLITEM_HXX //autogen
#include <svtools/poolitem.hxx>
#endif

#ifndef _SFXITEMSET_HXX //autogen
#include <svtools/itemset.hxx>
#endif

#ifndef _SV_FONTCVT_HXX
#include <vcl/fontcvt.hxx>
#endif

#ifndef _SVX_SVXENUM_HXX
#include <svx/svxenum.hxx>
#endif

#ifndef INCLUDED_SCDLLAPI_H
#include "scdllapi.h"
#endif

class Font;
class OutputDevice;
class Fraction;
class ScStyleSheet;
class SvNumberFormatter;
class ScDocument;

//  how to treat COL_AUTO in GetFont:

enum ScAutoFontColorMode
{
    SC_AUTOCOL_RAW,         // COL_AUTO is returned
    SC_AUTOCOL_BLACK,       // always use black
    SC_AUTOCOL_PRINT,       // black or white, depending on background
    SC_AUTOCOL_DISPLAY,     // from style settings, or black/white if needed
    SC_AUTOCOL_IGNOREFONT,  // like DISPLAY, but ignore stored font color (assume COL_AUTO)
    SC_AUTOCOL_IGNOREBACK,  // like DISPLAY, but ignore stored background color (use configured color)
    SC_AUTOCOL_IGNOREALL    // like DISPLAY, but ignore stored font and background colors
};

class SC_DLLPUBLIC ScPatternAttr: public SfxSetItem
{
    String*         pName;
    ScStyleSheet*   pStyle;
public:
    static ScDocument* pDoc;
                            ScPatternAttr(SfxItemSet* pItemSet, const String& rStyleName);
                            ScPatternAttr(SfxItemSet* pItemSet, ScStyleSheet* pStyleSheet = NULL);
                            ScPatternAttr(SfxItemPool* pItemPool);
                            ScPatternAttr(const ScPatternAttr& rPatternAttr);

                            ~ScPatternAttr();

    virtual SfxPoolItem*    Clone( SfxItemPool *pPool = 0 ) const;
    virtual SfxPoolItem*    Create(SvStream& rStream, USHORT nVersion) const;
    virtual SvStream&       Store(SvStream& rStream, USHORT nItemVersion) const;

    virtual int             operator==(const SfxPoolItem& rCmp) const;

    const SfxPoolItem&      GetItem( USHORT nWhich ) const
                                        { return GetItemSet().Get(nWhich); }

    static const SfxPoolItem& GetItem( USHORT nWhich, const SfxItemSet& rItemSet, const SfxItemSet* pCondSet );
    const SfxPoolItem&      GetItem( USHORT nWhich, const SfxItemSet* pCondSet ) const;

                            // pWhich sind keine Ranges, sondern einzelne IDs, 0-terminiert
    BOOL                    HasItemsSet( const USHORT* pWhich ) const;
    void                    ClearItems( const USHORT* pWhich );

    void                    DeleteUnchanged( const ScPatternAttr* pOldAttrs );

    static SvxCellOrientation GetCellOrientation( const SfxItemSet& rItemSet, const SfxItemSet* pCondSet = 0 );
    SvxCellOrientation      GetCellOrientation( const SfxItemSet* pCondSet = 0 ) const;

    /** Static helper function to fill a font object from the passed item set. */
    static void             GetFont( Font& rFont, const SfxItemSet& rItemSet,
                                        ScAutoFontColorMode eAutoMode,
                                        OutputDevice* pOutDev = NULL,
                                        const Fraction* pScale = NULL,
                                        const SfxItemSet* pCondSet = NULL,
                                        BYTE nScript = 0, const Color* pBackConfigColor = NULL,
                                        const Color* pTextConfigColor = NULL );
    /** Fills a font object from the own item set. */
    void                    GetFont( Font& rFont, ScAutoFontColorMode eAutoMode,
                                        OutputDevice* pOutDev = NULL,
                                        const Fraction* pScale = NULL,
                                        const SfxItemSet* pCondSet = NULL,
                                        BYTE nScript = 0, const Color* pBackConfigColor = NULL,
                                        const Color* pTextConfigColor = NULL ) const;

    /** Converts all Calc items contained in rSrcSet to edit engine items and puts them into rEditSet. */
    static void             FillToEditItemSet( SfxItemSet& rEditSet, const SfxItemSet& rSrcSet, const SfxItemSet* pCondSet = NULL );
    /** Converts all Calc items contained in the own item set to edit engine items and puts them into pEditSet. */
    void                    FillEditItemSet( SfxItemSet* pEditSet, const SfxItemSet* pCondSet = NULL ) const;

    /** Converts all edit engine items contained in rEditSet to Calc items and puts them into rDestSet. */
    static void             GetFromEditItemSet( SfxItemSet& rDestSet, const SfxItemSet& rEditSet );
    /** Converts all edit engine items contained in pEditSet to Calc items and puts them into the own item set. */
    void                    GetFromEditItemSet( const SfxItemSet* pEditSet );

    void                    FillEditParaItems( SfxItemSet* pSet ) const;

    ScPatternAttr*          PutInPool( ScDocument* pDestDoc, ScDocument* pSrcDoc ) const;

    void                    SetStyleSheet(ScStyleSheet* pNewStyle);
    const ScStyleSheet*     GetStyleSheet() const  { return pStyle; }
    const String*           GetStyleName() const;
    void                    UpdateStyleSheet();
    void                    StyleToName();

    BOOL                    IsVisible() const;
    BOOL                    IsVisibleEqual( const ScPatternAttr& rOther ) const;

                            /** If font is an old symbol font StarBats/StarMath
                                with text encoding RTL_TEXTENC_SYMBOL */
    BOOL                    IsSymbolFont() const;

                            /** Create a FontToSubsFontConverter if needed for
                                this pattern, else return 0.

                                @param nFlags is the bit mask which shall be
                                used for CreateFontToSubsFontConverter().

                                The converter must be destroyed by the caller
                                using DestroyFontToSubsFontConverter() which
                                should be accomplished using the
                                ScFontToSubsFontConverter_AutoPtr
                             */
    FontToSubsFontConverter GetSubsFontConverter( ULONG nFlags ) const;

    ULONG                   GetNumberFormat( SvNumberFormatter* ) const;
    ULONG                   GetNumberFormat( SvNumberFormatter* pFormatter,
                                                const SfxItemSet* pCondSet ) const;

    long                    GetRotateVal( const SfxItemSet* pCondSet ) const;
    BYTE                    GetRotateDir( const SfxItemSet* pCondSet ) const;
};

class ScFontToSubsFontConverter_AutoPtr
{
            FontToSubsFontConverter h;

            void                    release()
                                    {
                                        if ( h )
                                            DestroyFontToSubsFontConverter( h );
                                    }

                                // prevent usage
                                ScFontToSubsFontConverter_AutoPtr( const ScFontToSubsFontConverter_AutoPtr& );
    ScFontToSubsFontConverter_AutoPtr& operator=( const ScFontToSubsFontConverter_AutoPtr& );

public:
                                ScFontToSubsFontConverter_AutoPtr()
                                    : h(0)
                                    {}
                                ~ScFontToSubsFontConverter_AutoPtr()
                                    {
                                        release();
                                    }

    ScFontToSubsFontConverter_AutoPtr& operator=( FontToSubsFontConverter hN )
                                    {
                                        release();
                                        h = hN;
                                        return *this;
                                    }

            operator FontToSubsFontConverter() const
                                    { return h; }
};

#endif
<|endoftext|>


<commit_before>#include <opencv2/opencv.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <vector>

using namespace cv;
using std::vector;

int main(int argc, char** argv) {
    // Display usage
    if (argc < 5) {
        printf("Usage: %s <rows> <cols> <size> [cameras...]\n", argv[0]);
        return -1;
    }

    // Parse arguments
    int rows = atoi(argv[1]);
    int cols = atoi(argv[2]);
    float size = atof(argv[3]);

    // Open video capture devices
    vector<VideoCapture> devices;
    for (int i = 4; i < argc; i++) {
        int id = atoi(argv[i]);
        VideoCapture device(id);
        if (device.isOpened()) {
            devices.push_back(device);
            device.set(CV_CAP_PROP_FRAME_WIDTH, 1280);
            device.set(CV_CAP_PROP_FRAME_HEIGHT, 720);
        }
        else {
            std::cerr << "Failed to open video capture device " << id << std::endl;
        }
    }

    Mat frame, gray;
    while (true) {
        for (size_t i = 0; i < devices.size(); i++) {
            devices[i] >> frame;
            imshow(std::to_string(i), frame);
        }

        // Quit on escape keypress
        if (waitKey(16) >= 27) {
            break;
        }
    }
}
<commit_msg>Detect checkerboard corners<commit_after>#include <opencv2/opencv.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <vector>

using namespace cv;
using std::vector;

int main(int argc, char** argv) {
    // Display usage
    if (argc < 5) {
        printf("Usage: %s <rows> <cols> <size> [cameras...]\n", argv[0]);
        return -1;
    }

    // Parse arguments
    int rows = atoi(argv[1]);
    int cols = atoi(argv[2]);
    float size = atof(argv[3]);

    // Open video capture devices
    vector<VideoCapture> devices;
    vector<vector<Point2f>> img_points;
    for (int i = 4; i < argc; i++) {
        int id = atoi(argv[i]);
        VideoCapture device(id);
        if (device.isOpened()) {
            devices.push_back(device);
            device.set(CV_CAP_PROP_FRAME_WIDTH, 1280);
            device.set(CV_CAP_PROP_FRAME_HEIGHT, 720);
            device.set(CV_CAP_PROP_FPS, 30);
            img_points.push_back(vector<Point2f>());
        }
        else {
            std::cerr << "Failed to open video capture device " << id << std::endl;
        }
    }

    // Calibration variables
    Size checkerboard_size(cols, rows);

    int key = 0;
    Mat frame, gray;
    vector<Point2f> corners;
    while (key != 27) { // Quit on escape keypress
        for (size_t i = 0; i < devices.size(); i++) {
            devices[i] >> frame;

            // Detect checkerboards on spacebar
            if (waitKey(1) == 32) {
                cvtColor(frame, gray, COLOR_BGR2GRAY);
                bool found = findChessboardCorners(gray, checkerboard_size, corners);
                if (found) {
                    std::cout << "Found checkerboard on " << i << std::endl;
                    img_points[i].insert(
                            std::end(img_points[i]), std::begin(corners), std::end(corners));
                    cornerSubPix(gray, corners, Size(11, 11), Size(-1, -1),
                            TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 30, 0.1));
                }
                drawChessboardCorners(frame, checkerboard_size, Mat(corners), found);
            }

            imshow(std::to_string(i), frame);
        }

        key = waitKey(16);
        if (key == 'W') { // Write calibration to text files
            std::cout << "TODO Write to output" << std:: endl;
        }
    }
}
<|endoftext|>