<commit_before>#include <array>
#include <cstdio>
#include <cstring>
#include <functional>
#include <iostream>
#include <set>

#include "block.hpp"
#include "hash.hpp"
#include "slice.hpp"
#include "threadpool.hpp"

// XXX: no locking for fwrite if sizeof(wbuf) < PIPE_BUF (4096 bytes)

// BLOCK_HEADER
void dumpHeaders (Slice data) {
	fwrite(data.begin, 80, 1, stdout);
}

// BLOCK_HASH | TX_HASH | SHA1(OUTPUT_SCRIPT)
void dumpOutputHashs (Slice data) {
	const auto block = Block(data.take(80), data.drop(80));
	uint8_t wbuf[32 + 32 + 20] = {};

	hash256(wbuf, block.header);

	auto transactions = block.transactions();
	while (!transactions.empty()) {
		const auto& transaction = transactions.front();

		hash256(wbuf + 32, transaction.data);

		for (const auto& output : transaction.outputs) {
			sha1(wbuf + 64, output.script);
			fwrite(wbuf, sizeof(wbuf), 1, stdout);
		}

		transactions.popFront();
	}
}

// SCRIPT_LENGTH | SCRIPT
void dumpScripts (Slice data) {
	const auto block = Block(data.take(80), data.drop(80));
	uint8_t wbuf[4096];

	auto transactions = block.transactions();
	while (!transactions.empty()) {
		const auto& transaction = transactions.front();

		for (const auto& input : transaction.inputs) {
			if (input.script.length() > sizeof(wbuf) - sizeof(uint16_t)) continue;
			const auto scriptLength = static_cast<uint16_t>(input.script.length());

			Slice(wbuf, wbuf + sizeof(uint16_t)).put<uint16_t>(scriptLength, 0);
			memcpy(wbuf + sizeof(uint16_t), input.script.begin, scriptLength);
			fwrite(wbuf, sizeof(uint16_t) + scriptLength, 1, stdout);
		}

		for (const auto& output : transaction.outputs) {
			if (output.script.length() > sizeof(wbuf) - sizeof(uint16_t)) continue;
			const auto scriptLength = static_cast<uint16_t>(output.script.length());

			Slice(wbuf, wbuf + sizeof(uint16_t)).put<uint16_t>(scriptLength, 0);
			memcpy(wbuf + sizeof(uint16_t), output.script.begin, scriptLength);
			fwrite(wbuf, sizeof(uint16_t) + scriptLength, 1, stdout);
		}

		transactions.popFront();
	}
}

typedef void(*processFunction_t)(Slice);
processFunction_t FUNCTIONS[] = {
	&dumpHeaders,
	&dumpOutputHashs,
	&dumpScripts
};

typedef std::array<uint8_t, 32> hash_t;

auto importWhitelist (const std::string& fileName) {
	std::set<hash_t> set;

	auto file = fopen(fileName.c_str(), "r");
	if (file == nullptr) return set;

	while (true) {
		hash_t hash;
		const auto read = fread(&hash[0], 32, 1, file);

		// EOF?
		if (read == 0) break;

		set.emplace(hash);
	}

	return set;
}

static size_t memoryAlloc = 100 * 1024 * 1024;
static size_t nThreads = 1;
static size_t functionIndex = 0;
static std::string whitelistFileName;

auto parseArg (char* argv) {
	if (sscanf(argv, "-f%lu", &functionIndex) == 1) return true;
	if (sscanf(argv, "-m%lu", &memoryAlloc) == 1) return true;
	if (sscanf(argv, "-n%lu", &nThreads) == 1) return true;
	if (strncmp(argv, "-w", 2) == 0) {
		whitelistFileName = std::string(argv + 2);
		return true;
	}

	return false;
}

int main (int argc, char** argv) {
	for (auto i = 1; i < argc; ++i) {
		if (!parseArg(argv[i])) return 1;
	}

	const auto delegate = FUNCTIONS[functionIndex];

	// if specified, import the whitelist
	const auto doWhitelist = !whitelistFileName.empty();
	std::set<hash_t> whitelist;
	if (doWhitelist) {
		whitelist = importWhitelist(whitelistFileName);
		if (whitelist.empty()) return 1;

		std::cerr << "Initialized whitelist (" << whitelist.size() << " entries)" << std::endl;
	}

	// pre-allocate buffers
	UniqueSlice iobuffer(memoryAlloc / 2);
	UniqueSlice buffer(memoryAlloc / 2);
	ThreadPool<std::function<void(void)>> pool(nThreads);

	std::cerr << "Initialized buffers (2 * " << memoryAlloc / 2 << " bytes)" << std::endl;
	std::cerr << "Initialized " << nThreads << " threads in the thread pool" << std::endl;

	uint64_t remainder = 0;
	size_t count = 0;

	while (true) {
		const auto rdbuf = iobuffer.drop(remainder);
		const auto read = fread(rdbuf.begin, 1, rdbuf.length(), stdin);
		const auto eof = static_cast<size_t>(read) < rdbuf.length();

		// wait for all workers before overwrite
		pool.wait();

		// swap the buffers
		std::swap(buffer, iobuffer);

		auto data = buffer.take(remainder + read);
		std::cerr << "-- " << count << " Blocks (processing " << data.length() / 1024 << " KiB)" << std::endl;

		while (data.length() >= 88) {
			// skip bad data (e.g bitcoind zero pre-allocations)
			if (data.peek<uint32_t>() != 0xd9b4bef9) {
				data.popFrontN(1);
				continue;
			}

			// skip bad data cont.
			const auto header = data.drop(8).take(80);
			if (!Block(header).verify()) {
				data.popFrontN(1);
				continue;
			}

			// do we have enough data?
			const auto length = data.drop(4).peek<uint32_t>();
			const auto total = 8 + length;
			if (total > data.length()) break;

			// is whitelisting in effect?
			if (doWhitelist) {
				hash_t hash;
				hash256(&hash[0], header);

				// skip if not found
				if (whitelist.find(hash) == whitelist.end()) {
					data.popFrontN(total);

					std::cerr << "--- Skipped block" << std::endl;
					continue;
				}
			}

			// lets do it, send the block data to the threadpool
			const auto block = data.drop(8).take(length);

			pool.push([block, delegate]() { delegate(block); });
			count++;

			data.popFrontN(total);
		}

		if (eof) break;

		// assign remainder to front of iobuffer (rdbuf is offset to avoid overwrite on rawRead)
		remainder = data.length();
		memcpy(iobuffer.begin, data.begin, remainder);
	}

	return 0;
}
<commit_msg>parser: remove unnecessary offsets<commit_after>#include <array>
#include <cstdio>
#include <cstring>
#include <functional>
#include <iostream>
#include <set>

#include "block.hpp"
#include "hash.hpp"
#include "slice.hpp"
#include "threadpool.hpp"

// XXX: no locking for fwrite if sizeof(wbuf) < PIPE_BUF (4096 bytes)

// BLOCK_HEADER
void dumpHeaders (Slice data) {
	fwrite(data.begin, 80, 1, stdout);
}

// BLOCK_HASH | TX_HASH | SHA1(OUTPUT_SCRIPT)
void dumpOutputHashs (Slice data) {
	const auto block = Block(data.take(80), data.drop(80));
	uint8_t wbuf[32 + 32 + 20] = {};

	hash256(wbuf, block.header);

	auto transactions = block.transactions();
	while (!transactions.empty()) {
		const auto& transaction = transactions.front();

		hash256(wbuf + 32, transaction.data);

		for (const auto& output : transaction.outputs) {
			sha1(wbuf + 64, output.script);
			fwrite(wbuf, sizeof(wbuf), 1, stdout);
		}

		transactions.popFront();
	}
}

// SCRIPT_LENGTH | SCRIPT
void dumpScripts (Slice data) {
	const auto block = Block(data.take(80), data.drop(80));
	uint8_t wbuf[4096];

	auto transactions = block.transactions();
	while (!transactions.empty()) {
		const auto& transaction = transactions.front();

		for (const auto& input : transaction.inputs) {
			if (input.script.length() > sizeof(wbuf) - sizeof(uint16_t)) continue;
			const auto scriptLength = static_cast<uint16_t>(input.script.length());

			Slice(wbuf, wbuf + sizeof(uint16_t)).put<uint16_t>(scriptLength);
			memcpy(wbuf + sizeof(uint16_t), input.script.begin, scriptLength);
			fwrite(wbuf, sizeof(uint16_t) + scriptLength, 1, stdout);
		}

		for (const auto& output : transaction.outputs) {
			if (output.script.length() > sizeof(wbuf) - sizeof(uint16_t)) continue;
			const auto scriptLength = static_cast<uint16_t>(output.script.length());

			Slice(wbuf, wbuf + sizeof(uint16_t)).put<uint16_t>(scriptLength);
			memcpy(wbuf + sizeof(uint16_t), output.script.begin, scriptLength);
			fwrite(wbuf, sizeof(uint16_t) + scriptLength, 1, stdout);
		}

		transactions.popFront();
	}
}

typedef void(*processFunction_t)(Slice);
processFunction_t FUNCTIONS[] = {
	&dumpHeaders,
	&dumpOutputHashs,
	&dumpScripts
};

typedef std::array<uint8_t, 32> hash_t;

auto importWhitelist (const std::string& fileName) {
	std::set<hash_t> set;

	auto file = fopen(fileName.c_str(), "r");
	if (file == nullptr) return set;

	while (true) {
		hash_t hash;
		const auto read = fread(&hash[0], 32, 1, file);

		// EOF?
		if (read == 0) break;

		set.emplace(hash);
	}

	return set;
}

static size_t memoryAlloc = 100 * 1024 * 1024;
static size_t nThreads = 1;
static size_t functionIndex = 0;
static std::string whitelistFileName;

auto parseArg (char* argv) {
	if (sscanf(argv, "-f%lu", &functionIndex) == 1) return true;
	if (sscanf(argv, "-m%lu", &memoryAlloc) == 1) return true;
	if (sscanf(argv, "-n%lu", &nThreads) == 1) return true;
	if (strncmp(argv, "-w", 2) == 0) {
		whitelistFileName = std::string(argv + 2);
		return true;
	}

	return false;
}

int main (int argc, char** argv) {
	for (auto i = 1; i < argc; ++i) {
		if (!parseArg(argv[i])) return 1;
	}

	const auto delegate = FUNCTIONS[functionIndex];

	// if specified, import the whitelist
	const auto doWhitelist = !whitelistFileName.empty();
	std::set<hash_t> whitelist;
	if (doWhitelist) {
		whitelist = importWhitelist(whitelistFileName);
		if (whitelist.empty()) return 1;

		std::cerr << "Initialized whitelist (" << whitelist.size() << " entries)" << std::endl;
	}

	// pre-allocate buffers
	UniqueSlice iobuffer(memoryAlloc / 2);
	UniqueSlice buffer(memoryAlloc / 2);
	ThreadPool<std::function<void(void)>> pool(nThreads);

	std::cerr << "Initialized buffers (2 * " << memoryAlloc / 2 << " bytes)" << std::endl;
	std::cerr << "Initialized " << nThreads << " threads in the thread pool" << std::endl;

	uint64_t remainder = 0;
	size_t count = 0;

	while (true) {
		const auto rdbuf = iobuffer.drop(remainder);
		const auto read = fread(rdbuf.begin, 1, rdbuf.length(), stdin);
		const auto eof = static_cast<size_t>(read) < rdbuf.length();

		// wait for all workers before overwrite
		pool.wait();

		// swap the buffers
		std::swap(buffer, iobuffer);

		auto data = buffer.take(remainder + read);
		std::cerr << "-- " << count << " Blocks (processing " << data.length() / 1024 << " KiB)" << std::endl;

		while (data.length() >= 88) {
			// skip bad data (e.g bitcoind zero pre-allocations)
			if (data.peek<uint32_t>() != 0xd9b4bef9) {
				data.popFrontN(1);
				continue;
			}

			// skip bad data cont.
			const auto header = data.drop(8).take(80);
			if (!Block(header).verify()) {
				data.popFrontN(1);
				continue;
			}

			// do we have enough data?
			const auto length = data.drop(4).peek<uint32_t>();
			const auto total = 8 + length;
			if (total > data.length()) break;

			// is whitelisting in effect?
			if (doWhitelist) {
				hash_t hash;
				hash256(&hash[0], header);

				// skip if not found
				if (whitelist.find(hash) == whitelist.end()) {
					data.popFrontN(total);

					std::cerr << "--- Skipped block" << std::endl;
					continue;
				}
			}

			// lets do it, send the block data to the threadpool
			const auto block = data.drop(8).take(length);

			pool.push([block, delegate]() { delegate(block); });
			count++;

			data.popFrontN(total);
		}

		if (eof) break;

		// assign remainder to front of iobuffer (rdbuf is offset to avoid overwrite on rawRead)
		remainder = data.length();
		memcpy(iobuffer.begin, data.begin, remainder);
	}

	return 0;
}
<|endoftext|>


<commit_before>/**
1. Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

*/
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> m;
        vector<int> result;
        for(int i=0; i<nums.size(); i++){
        // not found the second one
            if (m.find(nums[i])==m.end() ) {
            // store the first one poisition into the second one's key
                m[target - nums[i]] = i;
            }else {
            // found the second one
                result.push_back(m[nums[i]]);
                result.push_back(i);
                break;
            }
        }
        return result;
    }
};<commit_msg>refactor 1<commit_after>/**
1. Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

*/
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> m;
        vector<int> result;
        for(int i = 0; i < nums.size(); i++){
        // not found the second one
            if (m.find(nums[i]) == m.end() ) {
            // store the first one poisition into the second one's key
                m[target - nums[i]] = i;
            }else {
            // found the second one
                result.push_back(m[nums[i]]);
                result.push_back(i);
                break;
            }
        }
        return result;
    }
};<|endoftext|>


<commit_before>/*************************************
** Tsunagari Tile Engine            **
** window.cpp                       **
** Copyright 2016-2019 Paul Merrill **
*************************************/

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

#include "av/sdl2/window.h"

#include "av/sdl2/error.h"
#include "av/sdl2/sdl2.h"
#include "core/client-conf.h"
#include "core/display-list.h"
#include "core/log.h"
#include "core/measure.h"
#include "core/world.h"
#include "util/noexcept.h"
#include "util/optional.h"

SDL_Renderer* SDL2GameWindow::renderer = nullptr;
rvec2 SDL2GameWindow::translation = {0.0, 0.0};
rvec2 SDL2GameWindow::scaling = {0.0, 0.0};

static TimePoint start = SteadyClock::nowMS();

static SDL_Window* window = nullptr;
static Transform transform = Transform::identity();

static int
getRefreshRate(SDL_Window* window) noexcept {
    // SDL_GetWindowDisplayIndex computes which display the window is on each
    // time.
    int display = SDL_GetWindowDisplayIndex(window);
    SDL_DisplayMode mode;
    SDL_GetCurrentDisplayMode(display, &mode);
    return mode.refresh_rate;
}

static void
handleEvent(const SDL_Event& event) noexcept {
    KeyboardKey key;

    switch (event.type) {
    case SDL_KEYUP:
    case SDL_KEYDOWN:
        switch (event.key.keysym.sym) {
        case SDLK_ESCAPE:
            key = KBEscape;
            break;
        case SDLK_LCTRL:
            key = KBLeftControl;
            break;
        case SDLK_RCTRL:
            key = KBRightControl;
            break;
        case SDLK_LSHIFT:
            key = KBLeftShift;
            break;
        case SDLK_RSHIFT:
            key = KBRightShift;
            break;
        case SDLK_SPACE:
            key = KBSpace;
            break;
        case SDLK_LEFT:
            key = KBLeftArrow;
            break;
        case SDLK_RIGHT:
            key = KBRightArrow;
            break;
        case SDLK_UP:
            key = KBUpArrow;
            break;
        case SDLK_DOWN:
            key = KBDownArrow;
            break;
        default:
            return;
        }
        if (event.type == SDL_KEYUP) {
            GameWindow::emitKeyUp(key);
        }
        else if (event.type == SDL_KEYDOWN) {
            GameWindow::emitKeyDown(key);
        }
        break;

    case SDL_QUIT:
        SDL_DestroyWindow(window);
        exit(0);
        return;

    default:
        return;
    }
}

static void
handleEvents() noexcept {
    SDL_Event event;

    while (SDL_PollEvent(&event)) {
        handleEvent(event);
    }
}

static void
updateTransform() noexcept {
    int w, h;

    SDL_GetWindowSize(window, &w, &h);

    float xScale = transform[0];
    float yScale = transform[5];
    float x = transform[12];
    float y = transform[13];

    SDL2GameWindow::translation = {x / xScale, y / yScale};
    SDL2GameWindow::scaling = {xScale, yScale};
}

time_t
GameWindow::time() noexcept {
    return SteadyClock::nowMS() - start;
}

void
GameWindow::create() noexcept {
    {
        TimeMeasure m("Initialized the SDL2 video subsystem");
        if (SDL_Init(SDL_INIT_VIDEO) < 0) {
            sdlDie("SDL2GameWindow", "SDL_Init(SDL_INIT_VIDEO)");
        }
    }

    {
        TimeMeasure m("Created SDL2 window");

        int width = Conf::windowSize.x;
        int height = Conf::windowSize.y;

        uint32_t flags = SDL_WINDOW_HIDDEN;
        if (Conf::fullscreen) {
            flags |= SDL_WINDOW_FULLSCREEN;
        }

        window = SDL_CreateWindow("Tsunagari",
                                  SDL_WINDOWPOS_UNDEFINED,
                                  SDL_WINDOWPOS_UNDEFINED,
                                  width,
                                  height,
                                  flags);

        if (window == nullptr) {
            sdlDie("SDL2GameWindow", "SDL_CreateWindow");
        }
    }

    {
        TimeMeasure m("Created SDL2 renderer");

        SDL2GameWindow::renderer = SDL_CreateRenderer(
                window,
                -1,
                SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);

        if (SDL2GameWindow::renderer == nullptr) {
            sdlDie("SDL2GameWindow", "SDL_CreateRenderer");
        }
    }

    SDL_RendererInfo info;

    if (SDL_GetRendererInfo(SDL2GameWindow::renderer, &info) < 0) {
        sdlDie("SDL2GameWindow", "SDL_GetRendererInfo");
    }

    StringView name = info.name;
    bool vsync = info.flags & SDL_RENDERER_PRESENTVSYNC;

    Log::info("SDL2GameWindow",
              String("Rendering will be done with ")
                      << name
                      << (vsync ? " with vsync" : " without vsync"));

    SDL_SetRenderDrawColor(SDL2GameWindow::renderer, 0x00, 0x00, 0x00, 0xFF);
}

unsigned
GameWindow::width() noexcept {
    int w, h;
    SDL_GetWindowSize(window, &w, &h);
    return static_cast<unsigned>(w);
}

unsigned
GameWindow::height() noexcept {
    int w, h;
    SDL_GetWindowSize(window, &w, &h);
    return static_cast<unsigned>(h);
}

void
GameWindow::setCaption(StringView caption) noexcept {
    SDL_SetWindowTitle(window, String(caption).null());
}

void
GameWindow::mainLoop() noexcept {
    SDL_ShowWindow(window);

    DisplayList display;

    int refreshRate = getRefreshRate(window);
    const Duration idealFrameTime = s_to_ns(1) / refreshRate;

    // Block until the start of a frame.
    SDL_SetRenderDrawColor(SDL2GameWindow::renderer, 0, 0, 0, 0xFF);
    SDL_RenderClear(SDL2GameWindow::renderer);
    SDL_RenderPresent(SDL2GameWindow::renderer);

    TimePoint frameStart = SteadyClock::now();
    TimePoint previousFrameStart =
            frameStart - idealFrameTime;  // Bogus initial value.

    TimePoint nextFrameStart = frameStart + idealFrameTime;

    while (window != nullptr) {
        handleEvents();

        //
        // Simulate world and draw frame.
        //
        time_t dt = ns_to_ms(frameStart - previousFrameStart);

        assert_(dt >= 0);

        if (dt > 0) {
            World::tick(dt);
        } else {
            Log::info("SDL2GameWindow", "dt == 0");
        }

        bool drew = false;
        if (World::needsRedraw()) {
            drew = true;

            World::draw(&display);

            SDL_SetRenderDrawColor(SDL2GameWindow::renderer, 0, 0, 0, 0xFF);
            SDL_RenderClear(SDL2GameWindow::renderer);
            displayListPresent(&display);
            SDL_RenderPresent(SDL2GameWindow::renderer);

            display.items.clear();
        }

        TimePoint frameEnd = SteadyClock::now();
        Duration timeTaken = frameEnd - frameStart;

        //
        // Sleep until next frame.
        //
        Duration sleepDuration = nextFrameStart - frameEnd;
        if (sleepDuration < 0) {
            sleepDuration = 0;
        }

        if (!drew && sleepDuration) {
            SleepFor(sleepDuration);
        }

        previousFrameStart = frameStart;
        frameStart = SteadyClock::now();
        nextFrameStart += idealFrameTime;

        if (frameStart > nextFrameStart) {
            int framesDropped = 0;
            while (frameStart > nextFrameStart) {
                nextFrameStart += idealFrameTime;
                framesDropped += 1;
            }
            Log::info("GameWindow",
                      String() << "Dropped " << framesDropped << " frames");
        }
    }
}

void
GameWindow::drawRect(float x1,
                     float x2,
                     float y1,
                     float y2,
                     uint32_t argb) noexcept {
    auto a = static_cast<uint8_t>((argb >> 24) & 0xFF);
    auto r = static_cast<uint8_t>((argb >> 16) & 0xFF);
    auto g = static_cast<uint8_t>((argb >> 8) & 0xFF);
    auto b = static_cast<uint8_t>((argb >> 0) & 0xFF);

    SDL_Rect rect{static_cast<int>(x1),
                  static_cast<int>(y1),
                  static_cast<int>(x2 - x1),
                  static_cast<int>(y2 - y1)};

    SDL_SetRenderDrawColor(SDL2GameWindow::renderer, r, g, b, a);
    SDL_SetRenderDrawBlendMode(SDL2GameWindow::renderer, SDL_BLENDMODE_BLEND);
    SDL_RenderFillRect(SDL2GameWindow::renderer, &rect);
}

void
GameWindow::scale(float x, float y, Function<void()> op) noexcept {
    assert_(x == y);

    Transform prev = transform;

    auto factor = static_cast<float>(x);

    transform = Transform::scale(factor) * transform;
    updateTransform();

    op();

    transform = prev;
    updateTransform();
}

void
GameWindow::translate(float x, float y, Function<void()> op) noexcept {
    Transform prev = transform;

    transform =
            Transform::translate(static_cast<float>(x), static_cast<float>(y)) *
            transform;
    updateTransform();

    op();

    transform = prev;
    updateTransform();
}

void
GameWindow::clip(float x,
                 float y,
                 float width,
                 float height,
                 Function<void()> op) noexcept {
    op();
}

void
GameWindow::close() noexcept {
    SDL_DestroyWindow(window);
    window = nullptr;
}
<commit_msg>av/sdl2/window: Disable debug log statement<commit_after>/*************************************
** Tsunagari Tile Engine            **
** window.cpp                       **
** Copyright 2016-2019 Paul Merrill **
*************************************/

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

#include "av/sdl2/window.h"

#include "av/sdl2/error.h"
#include "av/sdl2/sdl2.h"
#include "core/client-conf.h"
#include "core/display-list.h"
#include "core/log.h"
#include "core/measure.h"
#include "core/world.h"
#include "util/noexcept.h"
#include "util/optional.h"

SDL_Renderer* SDL2GameWindow::renderer = nullptr;
rvec2 SDL2GameWindow::translation = {0.0, 0.0};
rvec2 SDL2GameWindow::scaling = {0.0, 0.0};

static TimePoint start = SteadyClock::nowMS();

static SDL_Window* window = nullptr;
static Transform transform = Transform::identity();

static int
getRefreshRate(SDL_Window* window) noexcept {
    // SDL_GetWindowDisplayIndex computes which display the window is on each
    // time.
    int display = SDL_GetWindowDisplayIndex(window);
    SDL_DisplayMode mode;
    SDL_GetCurrentDisplayMode(display, &mode);
    return mode.refresh_rate;
}

static void
handleEvent(const SDL_Event& event) noexcept {
    KeyboardKey key;

    switch (event.type) {
    case SDL_KEYUP:
    case SDL_KEYDOWN:
        switch (event.key.keysym.sym) {
        case SDLK_ESCAPE:
            key = KBEscape;
            break;
        case SDLK_LCTRL:
            key = KBLeftControl;
            break;
        case SDLK_RCTRL:
            key = KBRightControl;
            break;
        case SDLK_LSHIFT:
            key = KBLeftShift;
            break;
        case SDLK_RSHIFT:
            key = KBRightShift;
            break;
        case SDLK_SPACE:
            key = KBSpace;
            break;
        case SDLK_LEFT:
            key = KBLeftArrow;
            break;
        case SDLK_RIGHT:
            key = KBRightArrow;
            break;
        case SDLK_UP:
            key = KBUpArrow;
            break;
        case SDLK_DOWN:
            key = KBDownArrow;
            break;
        default:
            return;
        }
        if (event.type == SDL_KEYUP) {
            GameWindow::emitKeyUp(key);
        }
        else if (event.type == SDL_KEYDOWN) {
            GameWindow::emitKeyDown(key);
        }
        break;

    case SDL_QUIT:
        SDL_DestroyWindow(window);
        exit(0);
        return;

    default:
        return;
    }
}

static void
handleEvents() noexcept {
    SDL_Event event;

    while (SDL_PollEvent(&event)) {
        handleEvent(event);
    }
}

static void
updateTransform() noexcept {
    int w, h;

    SDL_GetWindowSize(window, &w, &h);

    float xScale = transform[0];
    float yScale = transform[5];
    float x = transform[12];
    float y = transform[13];

    SDL2GameWindow::translation = {x / xScale, y / yScale};
    SDL2GameWindow::scaling = {xScale, yScale};
}

time_t
GameWindow::time() noexcept {
    return SteadyClock::nowMS() - start;
}

void
GameWindow::create() noexcept {
    {
        TimeMeasure m("Initialized the SDL2 video subsystem");
        if (SDL_Init(SDL_INIT_VIDEO) < 0) {
            sdlDie("SDL2GameWindow", "SDL_Init(SDL_INIT_VIDEO)");
        }
    }

    {
        TimeMeasure m("Created SDL2 window");

        int width = Conf::windowSize.x;
        int height = Conf::windowSize.y;

        uint32_t flags = SDL_WINDOW_HIDDEN;
        if (Conf::fullscreen) {
            flags |= SDL_WINDOW_FULLSCREEN;
        }

        window = SDL_CreateWindow("Tsunagari",
                                  SDL_WINDOWPOS_UNDEFINED,
                                  SDL_WINDOWPOS_UNDEFINED,
                                  width,
                                  height,
                                  flags);

        if (window == nullptr) {
            sdlDie("SDL2GameWindow", "SDL_CreateWindow");
        }
    }

    {
        TimeMeasure m("Created SDL2 renderer");

        SDL2GameWindow::renderer = SDL_CreateRenderer(
                window,
                -1,
                SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);

        if (SDL2GameWindow::renderer == nullptr) {
            sdlDie("SDL2GameWindow", "SDL_CreateRenderer");
        }
    }

    SDL_RendererInfo info;

    if (SDL_GetRendererInfo(SDL2GameWindow::renderer, &info) < 0) {
        sdlDie("SDL2GameWindow", "SDL_GetRendererInfo");
    }

    StringView name = info.name;
    bool vsync = info.flags & SDL_RENDERER_PRESENTVSYNC;

    Log::info("SDL2GameWindow",
              String("Rendering will be done with ")
                      << name
                      << (vsync ? " with vsync" : " without vsync"));

    SDL_SetRenderDrawColor(SDL2GameWindow::renderer, 0x00, 0x00, 0x00, 0xFF);
}

unsigned
GameWindow::width() noexcept {
    int w, h;
    SDL_GetWindowSize(window, &w, &h);
    return static_cast<unsigned>(w);
}

unsigned
GameWindow::height() noexcept {
    int w, h;
    SDL_GetWindowSize(window, &w, &h);
    return static_cast<unsigned>(h);
}

void
GameWindow::setCaption(StringView caption) noexcept {
    SDL_SetWindowTitle(window, String(caption).null());
}

void
GameWindow::mainLoop() noexcept {
    SDL_ShowWindow(window);

    DisplayList display;

    int refreshRate = getRefreshRate(window);
    const Duration idealFrameTime = s_to_ns(1) / refreshRate;

    // Block until the start of a frame.
    SDL_SetRenderDrawColor(SDL2GameWindow::renderer, 0, 0, 0, 0xFF);
    SDL_RenderClear(SDL2GameWindow::renderer);
    SDL_RenderPresent(SDL2GameWindow::renderer);

    TimePoint frameStart = SteadyClock::now();
    TimePoint previousFrameStart =
            frameStart - idealFrameTime;  // Bogus initial value.

    TimePoint nextFrameStart = frameStart + idealFrameTime;

    while (window != nullptr) {
        handleEvents();

        //
        // Simulate world and draw frame.
        //
        time_t dt = ns_to_ms(frameStart - previousFrameStart);

        assert_(dt >= 0);

        if (dt > 0) {
            World::tick(dt);
        } else {
            //Log::info("SDL2GameWindow", "dt == 0");
        }

        bool drew = false;
        if (World::needsRedraw()) {
            drew = true;

            World::draw(&display);

            SDL_SetRenderDrawColor(SDL2GameWindow::renderer, 0, 0, 0, 0xFF);
            SDL_RenderClear(SDL2GameWindow::renderer);
            displayListPresent(&display);
            SDL_RenderPresent(SDL2GameWindow::renderer);

            display.items.clear();
        }

        TimePoint frameEnd = SteadyClock::now();
        Duration timeTaken = frameEnd - frameStart;

        //
        // Sleep until next frame.
        //
        Duration sleepDuration = nextFrameStart - frameEnd;
        if (sleepDuration < 0) {
            sleepDuration = 0;
        }

        if (!drew && sleepDuration) {
            SleepFor(sleepDuration);
        }

        previousFrameStart = frameStart;
        frameStart = SteadyClock::now();
        nextFrameStart += idealFrameTime;

        if (frameStart > nextFrameStart) {
            int framesDropped = 0;
            while (frameStart > nextFrameStart) {
                nextFrameStart += idealFrameTime;
                framesDropped += 1;
            }
            Log::info("GameWindow",
                      String() << "Dropped " << framesDropped << " frames");
        }
    }
}

void
GameWindow::drawRect(float x1,
                     float x2,
                     float y1,
                     float y2,
                     uint32_t argb) noexcept {
    auto a = static_cast<uint8_t>((argb >> 24) & 0xFF);
    auto r = static_cast<uint8_t>((argb >> 16) & 0xFF);
    auto g = static_cast<uint8_t>((argb >> 8) & 0xFF);
    auto b = static_cast<uint8_t>((argb >> 0) & 0xFF);

    SDL_Rect rect{static_cast<int>(x1),
                  static_cast<int>(y1),
                  static_cast<int>(x2 - x1),
                  static_cast<int>(y2 - y1)};

    SDL_SetRenderDrawColor(SDL2GameWindow::renderer, r, g, b, a);
    SDL_SetRenderDrawBlendMode(SDL2GameWindow::renderer, SDL_BLENDMODE_BLEND);
    SDL_RenderFillRect(SDL2GameWindow::renderer, &rect);
}

void
GameWindow::scale(float x, float y, Function<void()> op) noexcept {
    assert_(x == y);

    Transform prev = transform;

    auto factor = static_cast<float>(x);

    transform = Transform::scale(factor) * transform;
    updateTransform();

    op();

    transform = prev;
    updateTransform();
}

void
GameWindow::translate(float x, float y, Function<void()> op) noexcept {
    Transform prev = transform;

    transform =
            Transform::translate(static_cast<float>(x), static_cast<float>(y)) *
            transform;
    updateTransform();

    op();

    transform = prev;
    updateTransform();
}

void
GameWindow::clip(float x,
                 float y,
                 float width,
                 float height,
                 Function<void()> op) noexcept {
    op();
}

void
GameWindow::close() noexcept {
    SDL_DestroyWindow(window);
    window = nullptr;
}
<|endoftext|>


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

#include "perfetto/ext/base/file_utils.h"

#include <sys/stat.h>
#include <sys/types.h>

#include <algorithm>
#include <deque>
#include <string>
#include <vector>

#include "perfetto/base/build_config.h"
#include "perfetto/base/logging.h"
#include "perfetto/base/platform_handle.h"
#include "perfetto/base/status.h"
#include "perfetto/ext/base/scoped_file.h"
#include "perfetto/ext/base/utils.h"

#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
#include <Windows.h>
#include <direct.h>
#include <io.h>
#else
#include <dirent.h>
#include <unistd.h>
#endif

namespace perfetto {
namespace base {
namespace {
constexpr size_t kBufSize = 2048;
}  // namespace

ssize_t Read(int fd, void* dst, size_t dst_size) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
  return _read(fd, dst, static_cast<unsigned>(dst_size));
#else
  return PERFETTO_EINTR(read(fd, dst, dst_size));
#endif
}

bool ReadFileDescriptor(int fd, std::string* out) {
  // Do not override existing data in string.
  size_t i = out->size();

  struct stat buf {};
  if (fstat(fd, &buf) != -1) {
    if (buf.st_size > 0)
      out->resize(i + static_cast<size_t>(buf.st_size));
  }

  ssize_t bytes_read;
  for (;;) {
    if (out->size() < i + kBufSize)
      out->resize(out->size() + kBufSize);

    bytes_read = Read(fd, &((*out)[i]), kBufSize);
    if (bytes_read > 0) {
      i += static_cast<size_t>(bytes_read);
    } else {
      out->resize(i);
      return bytes_read == 0;
    }
  }
}

bool ReadPlatformHandle(PlatformHandle h, std::string* out) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
  // Do not override existing data in string.
  size_t i = out->size();

  for (;;) {
    if (out->size() < i + kBufSize)
      out->resize(out->size() + kBufSize);
    DWORD bytes_read = 0;
    auto res = ::ReadFile(h, &((*out)[i]), kBufSize, &bytes_read, nullptr);
    if (res && bytes_read > 0) {
      i += static_cast<size_t>(bytes_read);
    } else {
      out->resize(i);
      const bool is_eof = res && bytes_read == 0;
      auto err = res ? 0 : GetLastError();
      // The "Broken pipe" error on Windows is slighly different than Unix:
      // On Unix: a "broken pipe" error can happen only on the writer side. On
      // the reader there is no broken pipe, just a EOF.
      // On windows: the reader also sees a broken pipe error.
      // Here we normalize on the Unix behavior, treating broken pipe as EOF.
      return is_eof || err == ERROR_BROKEN_PIPE;
    }
  }
#else
  return ReadFileDescriptor(h, out);
#endif
}

bool ReadFileStream(FILE* f, std::string* out) {
  return ReadFileDescriptor(fileno(f), out);
}

bool ReadFile(const std::string& path, std::string* out) {
  base::ScopedFile fd = base::OpenFile(path, O_RDONLY);
  if (!fd)
    return false;

  return ReadFileDescriptor(*fd, out);
}

ssize_t WriteAll(int fd, const void* buf, size_t count) {
  size_t written = 0;
  while (written < count) {
    // write() on windows takes an unsigned int size.
    uint32_t bytes_left = static_cast<uint32_t>(
        std::min(count - written, static_cast<size_t>(UINT32_MAX)));
    ssize_t wr = PERFETTO_EINTR(
        write(fd, static_cast<const char*>(buf) + written, bytes_left));
    if (wr == 0)
      break;
    if (wr < 0)
      return wr;
    written += static_cast<size_t>(wr);
  }
  return static_cast<ssize_t>(written);
}

ssize_t WriteAllHandle(PlatformHandle h, const void* buf, size_t count) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
  DWORD wsize = 0;
  if (::WriteFile(h, buf, static_cast<DWORD>(count), &wsize, nullptr)) {
    return wsize;
  } else {
    return -1;
  }
#else
  return WriteAll(h, buf, count);
#endif
}

bool FlushFile(int fd) {
  PERFETTO_DCHECK(fd != 0);
#if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \
    PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
  return !PERFETTO_EINTR(fdatasync(fd));
#elif PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
  return !PERFETTO_EINTR(_commit(fd));
#else
  return !PERFETTO_EINTR(fsync(fd));
#endif
}

bool Mkdir(const std::string& path) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
  return _mkdir(path.c_str()) == 0;
#else
  return mkdir(path.c_str(), 0755) == 0;
#endif
}

bool Rmdir(const std::string& path) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
  return _rmdir(path.c_str()) == 0;
#else
  return rmdir(path.c_str()) == 0;
#endif
}

int CloseFile(int fd) {
  return close(fd);
}

ScopedFile OpenFile(const std::string& path, int flags, FileOpenMode mode) {
  PERFETTO_DCHECK((flags & O_CREAT) == 0 || mode != kFileModeInvalid);
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
  // Always use O_BINARY on Windows, to avoid silly EOL translations.
  ScopedFile fd(_open(path.c_str(), flags | O_BINARY, mode));
#else
  // Always open a ScopedFile with O_CLOEXEC so we can safely fork and exec.
  ScopedFile fd(open(path.c_str(), flags | O_CLOEXEC, mode));
#endif
  return fd;
}

bool FileExists(const std::string& path) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
  return _access(path.c_str(), 0) == 0;
#else
  return access(path.c_str(), F_OK) == 0;
#endif
}

// Declared in base/platform_handle.h.
int ClosePlatformHandle(PlatformHandle handle) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
  // Make the return value UNIX-style.
  return CloseHandle(handle) ? 0 : -1;
#else
  return close(handle);
#endif
}

base::Status ListFilesRecursive(const std::string& dir_path,
                                std::vector<std::string>& output) {
  std::string root_dir_path = dir_path;
  if (root_dir_path.back() == '\\') {
    root_dir_path.back() = '/';
  } else if (root_dir_path.back() != '/') {
    root_dir_path.push_back('/');
  }

  // dir_queue contains full paths to the directories. The paths include the
  // root_dir_path at the beginning and the trailing slash at the end.
  std::deque<std::string> dir_queue;
  dir_queue.push_back(root_dir_path);

  while (!dir_queue.empty()) {
    const std::string cur_dir = std::move(dir_queue.front());
    dir_queue.pop_front();
#if PERFETTO_BUILDFLAG(PERFETTO_OS_NACL)
    return base::ErrStatus("ListFilesRecursive not supported yet");
#elif PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
    std::string glob_path = cur_dir + "*";
    // + 1 because we also have to count the NULL terminator.
    if (glob_path.length() + 1 > MAX_PATH)
      return base::ErrStatus("Directory path %s is too long", dir_path.c_str());
    WIN32_FIND_DATAA ffd;

    // Wrap FindClose to: (1) make the return unix-style; (2) deal w/ stdcall.
    static auto find_close = [](HANDLE h) { return FindClose(h) ? 0 : -1; };
    base::ScopedResource<HANDLE, find_close, nullptr, false,
                         base::PlatformHandleChecker>
        hFind(FindFirstFileA(glob_path.c_str(), &ffd));
    if (!hFind) {
      // For empty directories, there should be at least one entry '.'.
      // If FindFirstFileA returns INVALID_HANDLE_VALUE, this means directory
      // couldn't be accessed.
      return base::ErrStatus("Failed to open directory %s", cur_dir.c_str());
    }
    do {
      if (strcmp(ffd.cFileName, ".") == 0 || strcmp(ffd.cFileName, "..") == 0)
        continue;
      if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
        std::string subdir_path = cur_dir + ffd.cFileName + '/';
        dir_queue.push_back(subdir_path);
      } else {
        const std::string full_path = cur_dir + ffd.cFileName;
        PERFETTO_CHECK(full_path.length() > root_dir_path.length());
        output.push_back(full_path.substr(root_dir_path.length()));
      }
    } while (FindNextFileA(*hFind, &ffd));
#else
    ScopedDir dir = ScopedDir(opendir(cur_dir.c_str()));
    if (!dir) {
      return base::ErrStatus("Failed to open directory %s", cur_dir.c_str());
    }
    for (auto* dirent = readdir(dir.get()); dirent != nullptr;
         dirent = readdir(dir.get())) {
      if (strcmp(dirent->d_name, ".") == 0 ||
          strcmp(dirent->d_name, "..") == 0) {
        continue;
      }
      if (dirent->d_type == DT_DIR) {
        dir_queue.push_back(cur_dir + dirent->d_name + '/');
      } else if (dirent->d_type == DT_REG) {
        const std::string full_path = cur_dir + dirent->d_name;
        PERFETTO_CHECK(full_path.length() > root_dir_path.length());
        output.push_back(full_path.substr(root_dir_path.length()));
      }
    }
#endif
  }
  return base::OkStatus();
}

std::string GetFileExtension(const std::string& filename) {
  auto ext_idx = filename.rfind('.');
  if (ext_idx == std::string::npos)
    return std::string();
  return filename.substr(ext_idx);
}

base::Optional<size_t> GetFileSize(const std::string& file_path) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
  HANDLE file =
      CreateFileA(file_path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr,
                  OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  if (file == INVALID_HANDLE_VALUE) {
    return nullopt;
  }
  LARGE_INTEGER file_size;
  file_size.QuadPart = 0;
  BOOL ok = GetFileSizeEx(file, &file_size);
  CloseHandle(file);
  if (!ok) {
    return nullopt;
  }
  return static_cast<size_t>(file_size.QuadPart);
#else
  base::ScopedFile fd(base::OpenFile(file_path, O_RDONLY | O_CLOEXEC));
  if (!fd) {
    return nullopt;
  }
  struct stat buf{};
  if (fstat(*fd, &buf) == -1) {
    return nullopt;
  }
  return static_cast<size_t>(buf.st_size);
#endif
}

}  // namespace base
}  // namespace perfetto
<commit_msg>base: Fix Windows standalone build am: 02aa3eada2<commit_after>/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "perfetto/ext/base/file_utils.h"

#include <sys/stat.h>
#include <sys/types.h>

#include <algorithm>
#include <deque>
#include <string>
#include <vector>

#include "perfetto/base/build_config.h"
#include "perfetto/base/logging.h"
#include "perfetto/base/platform_handle.h"
#include "perfetto/base/status.h"
#include "perfetto/ext/base/scoped_file.h"
#include "perfetto/ext/base/utils.h"

#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
#include <Windows.h>
#include <direct.h>
#include <io.h>
#else
#include <dirent.h>
#include <unistd.h>
#endif

namespace perfetto {
namespace base {
namespace {
constexpr size_t kBufSize = 2048;

#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
// Wrap FindClose to: (1) make the return unix-style; (2) deal with stdcall.
int CloseFindHandle(HANDLE h) {
  return FindClose(h) ? 0 : -1;
};
#endif

}  // namespace

ssize_t Read(int fd, void* dst, size_t dst_size) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
  return _read(fd, dst, static_cast<unsigned>(dst_size));
#else
  return PERFETTO_EINTR(read(fd, dst, dst_size));
#endif
}

bool ReadFileDescriptor(int fd, std::string* out) {
  // Do not override existing data in string.
  size_t i = out->size();

  struct stat buf {};
  if (fstat(fd, &buf) != -1) {
    if (buf.st_size > 0)
      out->resize(i + static_cast<size_t>(buf.st_size));
  }

  ssize_t bytes_read;
  for (;;) {
    if (out->size() < i + kBufSize)
      out->resize(out->size() + kBufSize);

    bytes_read = Read(fd, &((*out)[i]), kBufSize);
    if (bytes_read > 0) {
      i += static_cast<size_t>(bytes_read);
    } else {
      out->resize(i);
      return bytes_read == 0;
    }
  }
}

bool ReadPlatformHandle(PlatformHandle h, std::string* out) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
  // Do not override existing data in string.
  size_t i = out->size();

  for (;;) {
    if (out->size() < i + kBufSize)
      out->resize(out->size() + kBufSize);
    DWORD bytes_read = 0;
    auto res = ::ReadFile(h, &((*out)[i]), kBufSize, &bytes_read, nullptr);
    if (res && bytes_read > 0) {
      i += static_cast<size_t>(bytes_read);
    } else {
      out->resize(i);
      const bool is_eof = res && bytes_read == 0;
      auto err = res ? 0 : GetLastError();
      // The "Broken pipe" error on Windows is slighly different than Unix:
      // On Unix: a "broken pipe" error can happen only on the writer side. On
      // the reader there is no broken pipe, just a EOF.
      // On windows: the reader also sees a broken pipe error.
      // Here we normalize on the Unix behavior, treating broken pipe as EOF.
      return is_eof || err == ERROR_BROKEN_PIPE;
    }
  }
#else
  return ReadFileDescriptor(h, out);
#endif
}

bool ReadFileStream(FILE* f, std::string* out) {
  return ReadFileDescriptor(fileno(f), out);
}

bool ReadFile(const std::string& path, std::string* out) {
  base::ScopedFile fd = base::OpenFile(path, O_RDONLY);
  if (!fd)
    return false;

  return ReadFileDescriptor(*fd, out);
}

ssize_t WriteAll(int fd, const void* buf, size_t count) {
  size_t written = 0;
  while (written < count) {
    // write() on windows takes an unsigned int size.
    uint32_t bytes_left = static_cast<uint32_t>(
        std::min(count - written, static_cast<size_t>(UINT32_MAX)));
    ssize_t wr = PERFETTO_EINTR(
        write(fd, static_cast<const char*>(buf) + written, bytes_left));
    if (wr == 0)
      break;
    if (wr < 0)
      return wr;
    written += static_cast<size_t>(wr);
  }
  return static_cast<ssize_t>(written);
}

ssize_t WriteAllHandle(PlatformHandle h, const void* buf, size_t count) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
  DWORD wsize = 0;
  if (::WriteFile(h, buf, static_cast<DWORD>(count), &wsize, nullptr)) {
    return wsize;
  } else {
    return -1;
  }
#else
  return WriteAll(h, buf, count);
#endif
}

bool FlushFile(int fd) {
  PERFETTO_DCHECK(fd != 0);
#if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \
    PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
  return !PERFETTO_EINTR(fdatasync(fd));
#elif PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
  return !PERFETTO_EINTR(_commit(fd));
#else
  return !PERFETTO_EINTR(fsync(fd));
#endif
}

bool Mkdir(const std::string& path) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
  return _mkdir(path.c_str()) == 0;
#else
  return mkdir(path.c_str(), 0755) == 0;
#endif
}

bool Rmdir(const std::string& path) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
  return _rmdir(path.c_str()) == 0;
#else
  return rmdir(path.c_str()) == 0;
#endif
}

int CloseFile(int fd) {
  return close(fd);
}

ScopedFile OpenFile(const std::string& path, int flags, FileOpenMode mode) {
  PERFETTO_DCHECK((flags & O_CREAT) == 0 || mode != kFileModeInvalid);
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
  // Always use O_BINARY on Windows, to avoid silly EOL translations.
  ScopedFile fd(_open(path.c_str(), flags | O_BINARY, mode));
#else
  // Always open a ScopedFile with O_CLOEXEC so we can safely fork and exec.
  ScopedFile fd(open(path.c_str(), flags | O_CLOEXEC, mode));
#endif
  return fd;
}

bool FileExists(const std::string& path) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
  return _access(path.c_str(), 0) == 0;
#else
  return access(path.c_str(), F_OK) == 0;
#endif
}

// Declared in base/platform_handle.h.
int ClosePlatformHandle(PlatformHandle handle) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
  // Make the return value UNIX-style.
  return CloseHandle(handle) ? 0 : -1;
#else
  return close(handle);
#endif
}

base::Status ListFilesRecursive(const std::string& dir_path,
                                std::vector<std::string>& output) {
  std::string root_dir_path = dir_path;
  if (root_dir_path.back() == '\\') {
    root_dir_path.back() = '/';
  } else if (root_dir_path.back() != '/') {
    root_dir_path.push_back('/');
  }

  // dir_queue contains full paths to the directories. The paths include the
  // root_dir_path at the beginning and the trailing slash at the end.
  std::deque<std::string> dir_queue;
  dir_queue.push_back(root_dir_path);

  while (!dir_queue.empty()) {
    const std::string cur_dir = std::move(dir_queue.front());
    dir_queue.pop_front();
#if PERFETTO_BUILDFLAG(PERFETTO_OS_NACL)
    return base::ErrStatus("ListFilesRecursive not supported yet");
#elif PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
    std::string glob_path = cur_dir + "*";
    // + 1 because we also have to count the NULL terminator.
    if (glob_path.length() + 1 > MAX_PATH)
      return base::ErrStatus("Directory path %s is too long", dir_path.c_str());
    WIN32_FIND_DATAA ffd;

    base::ScopedResource<HANDLE, CloseFindHandle, nullptr, false,
                         base::PlatformHandleChecker>
        hFind(FindFirstFileA(glob_path.c_str(), &ffd));
    if (!hFind) {
      // For empty directories, there should be at least one entry '.'.
      // If FindFirstFileA returns INVALID_HANDLE_VALUE, this means directory
      // couldn't be accessed.
      return base::ErrStatus("Failed to open directory %s", cur_dir.c_str());
    }
    do {
      if (strcmp(ffd.cFileName, ".") == 0 || strcmp(ffd.cFileName, "..") == 0)
        continue;
      if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
        std::string subdir_path = cur_dir + ffd.cFileName + '/';
        dir_queue.push_back(subdir_path);
      } else {
        const std::string full_path = cur_dir + ffd.cFileName;
        PERFETTO_CHECK(full_path.length() > root_dir_path.length());
        output.push_back(full_path.substr(root_dir_path.length()));
      }
    } while (FindNextFileA(*hFind, &ffd));
#else
    ScopedDir dir = ScopedDir(opendir(cur_dir.c_str()));
    if (!dir) {
      return base::ErrStatus("Failed to open directory %s", cur_dir.c_str());
    }
    for (auto* dirent = readdir(dir.get()); dirent != nullptr;
         dirent = readdir(dir.get())) {
      if (strcmp(dirent->d_name, ".") == 0 ||
          strcmp(dirent->d_name, "..") == 0) {
        continue;
      }
      if (dirent->d_type == DT_DIR) {
        dir_queue.push_back(cur_dir + dirent->d_name + '/');
      } else if (dirent->d_type == DT_REG) {
        const std::string full_path = cur_dir + dirent->d_name;
        PERFETTO_CHECK(full_path.length() > root_dir_path.length());
        output.push_back(full_path.substr(root_dir_path.length()));
      }
    }
#endif
  }
  return base::OkStatus();
}

std::string GetFileExtension(const std::string& filename) {
  auto ext_idx = filename.rfind('.');
  if (ext_idx == std::string::npos)
    return std::string();
  return filename.substr(ext_idx);
}

base::Optional<size_t> GetFileSize(const std::string& file_path) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
  HANDLE file =
      CreateFileA(file_path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr,
                  OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  if (file == INVALID_HANDLE_VALUE) {
    return nullopt;
  }
  LARGE_INTEGER file_size;
  file_size.QuadPart = 0;
  BOOL ok = GetFileSizeEx(file, &file_size);
  CloseHandle(file);
  if (!ok) {
    return nullopt;
  }
  return static_cast<size_t>(file_size.QuadPart);
#else
  base::ScopedFile fd(base::OpenFile(file_path, O_RDONLY | O_CLOEXEC));
  if (!fd) {
    return nullopt;
  }
  struct stat buf{};
  if (fstat(*fd, &buf) == -1) {
    return nullopt;
  }
  return static_cast<size_t>(buf.st_size);
#endif
}

}  // namespace base
}  // namespace perfetto
<|endoftext|>


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

#include "perfetto/ext/base/file_utils.h"

#include <sys/stat.h>
#include <sys/types.h>

#include <algorithm>

#include "perfetto/base/build_config.h"
#include "perfetto/base/logging.h"
#include "perfetto/ext/base/scoped_file.h"
#include "perfetto/ext/base/utils.h"

#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
#include <Windows.h>
#include <direct.h>
#include <io.h>
#else
#include <dirent.h>
#include <unistd.h>
#endif

namespace perfetto {
namespace base {
namespace {
constexpr size_t kBufSize = 2048;
}

ssize_t Read(int fd, void* dst, size_t dst_size) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
  return _read(fd, dst, static_cast<unsigned>(dst_size));
#else
  return PERFETTO_EINTR(read(fd, dst, dst_size));
#endif
}

bool ReadFileDescriptor(int fd, std::string* out) {
  // Do not override existing data in string.
  size_t i = out->size();

  struct stat buf {};
  if (fstat(fd, &buf) != -1) {
    if (buf.st_size > 0)
      out->resize(i + static_cast<size_t>(buf.st_size));
  }

  ssize_t bytes_read;
  for (;;) {
    if (out->size() < i + kBufSize)
      out->resize(out->size() + kBufSize);

    bytes_read = Read(fd, &((*out)[i]), kBufSize);
    if (bytes_read > 0) {
      i += static_cast<size_t>(bytes_read);
    } else {
      out->resize(i);
      return bytes_read == 0;
    }
  }
}

bool ReadFileStream(FILE* f, std::string* out) {
  return ReadFileDescriptor(fileno(f), out);
}

bool ReadFile(const std::string& path, std::string* out) {
  base::ScopedFile fd = base::OpenFile(path, O_RDONLY);
  if (!fd)
    return false;

  return ReadFileDescriptor(*fd, out);
}

ssize_t WriteAll(int fd, const void* buf, size_t count) {
  size_t written = 0;
  while (written < count) {
    // write() on windows takes an unsigned int size.
    uint32_t bytes_left = static_cast<uint32_t>(
        std::min(count - written, static_cast<size_t>(UINT32_MAX)));
    ssize_t wr = PERFETTO_EINTR(
        write(fd, static_cast<const char*>(buf) + written, bytes_left));
    if (wr == 0)
      break;
    if (wr < 0)
      return wr;
    written += static_cast<size_t>(wr);
  }
  return static_cast<ssize_t>(written);
}

bool FlushFile(int fd) {
  PERFETTO_DCHECK(fd != 0);
#if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \
    PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
  return !PERFETTO_EINTR(fdatasync(fd));
#elif PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
  return !PERFETTO_EINTR(_commit(fd));
#else
  return !PERFETTO_EINTR(fsync(fd));
#endif
}

bool Mkdir(const std::string& path) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
  return _mkdir(path.c_str()) == 0;
#else
  return mkdir(path.c_str(), 0755) == 0;
#endif
}

bool Rmdir(const std::string& path) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
  return _rmdir(path.c_str()) == 0;
#else
  return rmdir(path.c_str()) == 0;
#endif
}

int CloseFile(int fd) {
  return close(fd);
}

ScopedFile OpenFile(const std::string& path, int flags, mode_t mode) {
  PERFETTO_DCHECK((flags & O_CREAT) == 0 || mode != kFileModeInvalid);
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
  // Always use O_BINARY on Windows, to avoid silly EOL translations.
  ScopedFile fd(_open(path.c_str(), flags | O_BINARY, mode));
#else
  // Always open a ScopedFile with O_CLOEXEC so we can safely fork and exec.
  ScopedFile fd(open(path.c_str(), flags | O_CLOEXEC, mode));
#endif
  return fd;
}

bool FileExists(const std::string& path) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
  return _access(path.c_str(), 0) == 0;
#else
  return access(path.c_str(), F_OK) == 0;
#endif
}

}  // namespace base
}  // namespace perfetto
<commit_msg>Fix mismatching signature in base::OpenFile am: e0c5f91c5c am: dcfe196b5e<commit_after>/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "perfetto/ext/base/file_utils.h"

#include <sys/stat.h>
#include <sys/types.h>

#include <algorithm>

#include "perfetto/base/build_config.h"
#include "perfetto/base/logging.h"
#include "perfetto/ext/base/scoped_file.h"
#include "perfetto/ext/base/utils.h"

#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
#include <Windows.h>
#include <direct.h>
#include <io.h>
#else
#include <dirent.h>
#include <unistd.h>
#endif

namespace perfetto {
namespace base {
namespace {
constexpr size_t kBufSize = 2048;
}

ssize_t Read(int fd, void* dst, size_t dst_size) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
  return _read(fd, dst, static_cast<unsigned>(dst_size));
#else
  return PERFETTO_EINTR(read(fd, dst, dst_size));
#endif
}

bool ReadFileDescriptor(int fd, std::string* out) {
  // Do not override existing data in string.
  size_t i = out->size();

  struct stat buf {};
  if (fstat(fd, &buf) != -1) {
    if (buf.st_size > 0)
      out->resize(i + static_cast<size_t>(buf.st_size));
  }

  ssize_t bytes_read;
  for (;;) {
    if (out->size() < i + kBufSize)
      out->resize(out->size() + kBufSize);

    bytes_read = Read(fd, &((*out)[i]), kBufSize);
    if (bytes_read > 0) {
      i += static_cast<size_t>(bytes_read);
    } else {
      out->resize(i);
      return bytes_read == 0;
    }
  }
}

bool ReadFileStream(FILE* f, std::string* out) {
  return ReadFileDescriptor(fileno(f), out);
}

bool ReadFile(const std::string& path, std::string* out) {
  base::ScopedFile fd = base::OpenFile(path, O_RDONLY);
  if (!fd)
    return false;

  return ReadFileDescriptor(*fd, out);
}

ssize_t WriteAll(int fd, const void* buf, size_t count) {
  size_t written = 0;
  while (written < count) {
    // write() on windows takes an unsigned int size.
    uint32_t bytes_left = static_cast<uint32_t>(
        std::min(count - written, static_cast<size_t>(UINT32_MAX)));
    ssize_t wr = PERFETTO_EINTR(
        write(fd, static_cast<const char*>(buf) + written, bytes_left));
    if (wr == 0)
      break;
    if (wr < 0)
      return wr;
    written += static_cast<size_t>(wr);
  }
  return static_cast<ssize_t>(written);
}

bool FlushFile(int fd) {
  PERFETTO_DCHECK(fd != 0);
#if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \
    PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
  return !PERFETTO_EINTR(fdatasync(fd));
#elif PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
  return !PERFETTO_EINTR(_commit(fd));
#else
  return !PERFETTO_EINTR(fsync(fd));
#endif
}

bool Mkdir(const std::string& path) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
  return _mkdir(path.c_str()) == 0;
#else
  return mkdir(path.c_str(), 0755) == 0;
#endif
}

bool Rmdir(const std::string& path) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
  return _rmdir(path.c_str()) == 0;
#else
  return rmdir(path.c_str()) == 0;
#endif
}

int CloseFile(int fd) {
  return close(fd);
}

ScopedFile OpenFile(const std::string& path, int flags, FileOpenMode mode) {
  PERFETTO_DCHECK((flags & O_CREAT) == 0 || mode != kFileModeInvalid);
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
  // Always use O_BINARY on Windows, to avoid silly EOL translations.
  ScopedFile fd(_open(path.c_str(), flags | O_BINARY, mode));
#else
  // Always open a ScopedFile with O_CLOEXEC so we can safely fork and exec.
  ScopedFile fd(open(path.c_str(), flags | O_CLOEXEC, mode));
#endif
  return fd;
}

bool FileExists(const std::string& path) {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
  return _access(path.c_str(), 0) == 0;
#else
  return access(path.c_str(), F_OK) == 0;
#endif
}

}  // namespace base
}  // namespace perfetto
<|endoftext|>


<commit_before>#ifndef CLAMMBON_SORT_GENETIC_HPP
#define CLAMMBON_SORT_GENETIC_HPP

#include <algorithm>

int constexpr PARENT = 10;
int constexpr CHILDREN = 100;

class genetic
{
private:
    std::vector<std::vector<int>> parent_gene_;
	struct children_t { std::vector<int> children_gene; unsigned int assessment;};//子供の遺伝子と評価値
	std::vector<children_t> children_;//子供の遺伝子と評価値の配列

    question_raw_data *data_;
    compared_type *comp_;

    void shuffle(std::vector<int>& arr) const
    {
        for(int i = 0; i < arr.size(); ++i)
        {
            int j = 0; //TODO: メルセンヌでarr.size()までの値を入れる
            std::swap(arr[i], arr[j]);
        }
    }

    void shuffle_all() const
    {
        for(auto it = children_.begin(); it != children_.end(); ++it)
        {
            shuffle(it->children_gene);
        }
    }

    unsigned int assess(std::vector<int> const& arr) const
    {
        auto const sepy = data_->split_num->second;

        unsigned int ass = 0;
        for(int i = 0; i < arr.size(); ++i)
        {
            if(i + 1 < arr.size())
            {
                if(arr[j] == arr[j + 1])
                {
                    std::cout << "!!!" << arr[j] << arr[j + 1] << std::endl;
                }
                ass += *comp_[arr[j]][arr[j + 1]].right;
            }
            if(i + sepy < arr.size())
            {
                if(arr[j] == arr[j + sepy])
                {
                    std::cout << "???" << arr[j] << arr[j + sepy] << std::endl;
                }
                ass += *comp_[arr[j]][arr[j + sepy]].down;
            }
        }
        return ass;
    }

    void assess_all()
    {
        for(auto it = children_.cbegin(); it != childred_.cend(); ++it)
        {
            //for(int i = 0; i < split_total; ++i)
            //{
            //    std::cout << it->children_gene[i] << " - ";
            //}
            it->assessment = assess(it->children_gene);
		    //std::cout << "     " << it->assessment << std::endl;
        }
    }

public:
    int sort()
    {
        auto const split_total = data_->split_num->first * data_->split_num->second;

        // children_の初期化
        {
            //連番リスト(0~split_total-1)の作製
            std::vector<int> tmp_vector;
            tmp_vector.reserve(split_total);
            for(int i = 0; i < split_total; ++i) tmp_vector.push_back(i);

            //連番リストでchildren_を初期化
            children_.assign(CHILDREN, {tmp_vector, 0});
        }

        shuffle_all();
        assess_all();

        int top;
        std::vector<int> top10(10);
        std::vector<int> toppers(1000);
        for(int i = 0; i < toppers.size(); ++i)
        {
            for(int j = 0; j < 10000; ++j)
            {
                select_parent();
                cross_over();
                assess_all();

			    std::cout << "最上位遺伝子";
			    for (int i = 0; i < split_total; i++)
                {
				    std::cout << std::setw(3) << parent_gene_[0][i];
			    }

                std::cout << "番号" << top10[0] << std::endl;
                if(
                    std::all_of(
                        top10.begin(), top10.end(),
                        [base = top10[0]](int const elem){ return base == elem; }
                    )
                )
                {
                    //Top10の遺伝子がすべて同じものになったら収束したと判断する
                    break;
                }
                std::cout << "世代=" << j << "ループ" << i << std::endl;

            }
            toppers[i] = top;

            shuffle_all();
        }

	    int toptop = std::numeric_limits<int>::max();
	    int topnum = 0;
	    for(auto const elem : toppers)
        {
            if(elem < toptop)
            {
                toptop = elem;
                topnum = 0;
            }
            else if(elem == toptop)
            {
                ++topnum;
            }
		    std::cout << elem << std::endl;
        }
	    std::cout << "最適値" << toptop << "数" << topnum << std::endl;
    }

};

#endif
<commit_msg>現時点までのバグ修正<commit_after>#ifndef CLAMMBON_SORT_GENETIC_HPP
#define CLAMMBON_SORT_GENETIC_HPP

#include <algorithm>
#include <iomanip> // std::setwのみ

int constexpr PARENT = 10;
int constexpr CHILDREN = 100;

class genetic
{
private:
    typedef std::vector<std::vector<std::vector<std::vector<direction_type<uint64_t>>>>> compared_type;

    std::vector<std::vector<int>> parent_gene_;
	struct children_t { std::vector<int> children_gene; unsigned int assessment;};//子供の遺伝子と評価値
	std::vector<children_t> children_;//子供の遺伝子と評価値の配列

    question_raw_data *data_;
    compared_type *comp_;

    void shuffle(std::vector<int>& arr) const
    {
        for(int i = 0; i < arr.size(); ++i)
        {
            int j = 0; //TODO: メルセンヌでarr.size()までの値を入れる
            std::swap(arr[i], arr[j]);
        }
    }

    void shuffle_all()
    {
        for(auto it = children_.begin(); it != children_.end(); ++it)
        {
            shuffle(it->children_gene);
        }
    }

    unsigned int assess(std::vector<int> const& arr) const
    {
        auto const sepx = data_->split_num.first;
        auto const sepy = data_->split_num.second;

        unsigned int ass = 0;
        for(int i = 0; i < arr.size(); ++i)
        {
            if(i + 1 < arr.size())
            {
                if(arr[i] == arr[i + 1])
                {
                    std::cout << "!!!" << arr[i] << arr[i + 1] << std::endl;
                }
                ass += (*comp_)[arr[i] / sepx][arr[i] % sepx][arr[i + 1] / sepx][arr[i + 1] % sepx].right;
            }
            if(i + sepy < arr.size())
            {
                if(arr[i] == arr[i + sepy])
                {
                    std::cout << "???" << arr[i] << arr[i + sepy] << std::endl;
                }
                ass += (*comp_)[arr[i] / sepx][arr[i] % sepx][arr[i + sepy] / sepx][arr[i + sepy] % sepx].right;
            }
        }
        return ass;
    }

    void assess_all()
    {
        for(auto it = children_.begin(); it != children_.end(); ++it)
        {
            //for(int i = 0; i < split_total; ++i)
            //{
            //    std::cout << it->children_gene[i] << " - ";
            //}
            it->assessment = assess(it->children_gene);
		    //std::cout << "     " << it->assessment << std::endl;
        }
    }

public:
    int sort()
    {
        auto const split_total = data_->split_num.first * data_->split_num.second;

        // children_の初期化
        {
            //連番リスト(0~split_total-1)の作製
            std::vector<int> tmp_vector;
            tmp_vector.reserve(split_total);
            for(int i = 0; i < split_total; ++i) tmp_vector.push_back(i);

            //連番リストでchildren_を初期化
            children_.assign(CHILDREN, {tmp_vector, 0});
        }

        shuffle_all();
        assess_all();

        int top;
        std::vector<int> top10(10);
        std::vector<int> toppers(1000);
        for(int i = 0; i < toppers.size(); ++i)
        {
            for(int j = 0; j < 10000; ++j)
            {
                select_parent();
                cross_over();
                assess_all();

			    std::cout << "最上位遺伝子";
			    for (int i = 0; i < split_total; i++)
                {
				    std::cout << std::setw(3) << parent_gene_[0][i]; //unspecified(std::setw)
			    }

                std::cout << "番号" << top10[0] << std::endl;

                int const base = top10[0]; // VCのための苦肉の策
                if(
                    std::all_of(
                        top10.begin(), top10.end(),
                        [base](int const elem){ return base == elem; }
                        //[base = top10[0]](int const elem){ return base == elem; }
                    )
                )
                {
                    //Top10の遺伝子がすべて同じものになったら収束したと判断する
                    break;
                }
                std::cout << "世代=" << j << "ループ" << i << std::endl;

            }
            toppers[i] = top;

            shuffle_all();
        }

	    int toptop = std::numeric_limits<int>::max();
	    int topnum = 0;
	    for(auto const elem : toppers)
        {
            if(elem < toptop)
            {
                toptop = elem;
                topnum = 0;
            }
            else if(elem == toptop)
            {
                ++topnum;
            }
		    std::cout << elem << std::endl;
        }
	    std::cout << "最適値" << toptop << "数" << topnum << std::endl;
    }

};

#endif
<|endoftext|>


<commit_before>/*-
 * Copyright (c) 2016 Frederic Culot <culot@FreeBSD.org>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer
 *    in this position and unchanged.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <thread>
#include <chrono>
#include <curses.h>

#include "popupwindow.h"

namespace portal {
namespace gfx {

PopupWindow::PopupWindow(const std::string& msg, Type type, const Point& center)
  : Window() {
  Size size;
  size.setHeight(3);
  size.setWidth(msg.length() + 2);
  setSize(size);

  Point pos;
  pos.setX(center.x() - msg.length() / 2);
  pos.setY(center.y());
  setPosition(pos);

//  showBorders(false);
  print(msg);

  /*
  switch (type) {
  case Type::brief:
    pane_->colorizeCurrentLine(2);
    break;
  case Type::info:
    pane_->colorizeCurrentLine(7);
    break;
  case Type::warning:
    pane_->colorizeCurrentLine(4);
    break;
  case Type::error:
    pane_->colorizeCurrentLine(5);
    break;
  }
  */

  draw();
  refresh();

  int duration;
  switch (type) {
  case Type::brief:
    duration = 500;
    break;
  default:
    duration = 1400;
    break;
  }
  std::this_thread::sleep_for(std::chrono::milliseconds(duration));
}

}
}
<commit_msg>Add color style attribute<commit_after>/*-
 * Copyright (c) 2016 Frederic Culot <culot@FreeBSD.org>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer
 *    in this position and unchanged.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <thread>
#include <chrono>
#include <curses.h>

#include "style.h"
#include "popupwindow.h"

namespace portal {
namespace gfx {

PopupWindow::PopupWindow(const std::string& msg, Type type, const Point& center)
  : Window() {
  Size size;
  size.setHeight(1);
  size.setWidth(msg.length() + 2);
  setSize(size);

  Point pos;
  pos.setX(center.x() - msg.length() / 2);
  pos.setY(center.y());
  setPosition(pos);

  Style style;
  switch (type) {
  case Type::brief:
    style.color = Style::Color::magenta;
    break;
  case Type::info:
    style.color = Style::Color::blue;
    break;
  case Type::warning:
    style.color = Style::Color::yellow;
    break;
  case Type::error:
    style.color = Style::Color::red;
    break;
  }
  setStyle(style);

  print(msg);
  draw();
  refresh();

  int duration;
  switch (type) {
  case Type::brief:
    duration = 500;
    break;
  default:
    duration = 1400;
    break;
  }
  std::this_thread::sleep_for(std::chrono::milliseconds(duration));
}

}
}
<|endoftext|>


<commit_before>/*
    knserverinfo.cpp

    KNode, the KDE newsreader
    Copyright (c) 1999-2001 the KNode authors.
    See file AUTHORS for details

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.
    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software Foundation,
    Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, US
*/

#include "knserverinfo.h"
#include "utilities.h"

#include <kmessagebox.h>
#include <kconfig.h>
#include <klocale.h>
#include <kdebug.h>
#include <kwallet.h>
using namespace KWallet;

KNServerInfo::KNServerInfo()
  : t_ype(STnntp), i_d(-1), p_ort(119), h_old(300),
    t_imeout(60), n_eedsLogon(false)
{
}

KNServerInfo::~KNServerInfo()
{
}

void KNServerInfo::readConf(KConfig *conf)
{
  s_erver=conf->readEntry("server", "localhost");

  if(t_ype==STnntp)
    p_ort=conf->readNumEntry("port", 119);
  else
    p_ort=conf->readNumEntry("port", 25);

  h_old=conf->readNumEntry("holdTime", 300);

  if(h_old < 0) h_old=0;

  t_imeout=conf->readNumEntry("timeout", 60);

  if(t_imeout < 15) t_imeout=15;

  if(t_ype==STnntp) {
    i_d=conf->readNumEntry("id", -1);
    n_eedsLogon=conf->readBoolEntry("needsLogon",false);
    u_ser=conf->readEntry("user");
    p_ass = KNHelper::decryptStr(conf->readEntry("pass"));
    conf->deleteEntry("pass"); //first time run, don't store it in the config file

    if (Wallet::folderDoesNotExist(Wallet::NetworkWallet(), "knode") ||
        Wallet::keyDoesNotExist(Wallet::NetworkWallet(), "knode", s_erver))
      return;

    Wallet* wallet = openWallet();
    if (!wallet || wallet->readPassword(s_erver, p_ass)) {
      //Save the pass in wallet as this might be the first time it's used
      if (wallet)
        wallet->writePassword(s_erver, p_ass);
    }
  }
}

Wallet* KNServerInfo::openWallet()
{
  //I use this because I don't want to bother user with error messages when
  //he/she didn't even enable wallet.
  if (!Wallet::isEnabled())
	return 0;
  QString networkWallet = Wallet::NetworkWallet();
  Wallet* wallet = Wallet::openWallet(networkWallet);
  if (!wallet) {
    KMessageBox::error(0, i18n("The wallet couldn't be opened "
                               "This error is most probably caused "
                               "by providing a wrong password."));
    return 0;
  }

  if (wallet && !wallet->hasFolder("knode"))
    wallet->createFolder("knode");
  wallet->setFolder("knode");
  return wallet;
}

void KNServerInfo::saveConf(KConfig *conf)
{
  conf->writeEntry("server", s_erver);
  conf->writeEntry("port", p_ort);
  conf->writeEntry("holdTime", h_old);
  conf->writeEntry("timeout", t_imeout);
  if (t_ype==STnntp) {
    conf->writeEntry("id", i_d);
    conf->writeEntry("needsLogon", n_eedsLogon);
    conf->writeEntry("user", u_ser);
    //open wallet for storing only if the user actually does have the password
    if (!p_ass.isEmpty()) {
      Wallet* wallet = openWallet();
      if (!wallet || wallet->writePassword(s_erver, p_ass)) {
          KMessageBox::information(0, i18n("KWallet isn't running. We strongly recommend using "
                                           "KWallet for managing your password"),
                                   i18n("KWallet isn't running!"), "KWalletWarning" );
          conf->writeEntry("pass", KNHelper::encryptStr(p_ass));
      }
    }
  }
}

bool KNServerInfo::operator==(const KNServerInfo &s)
{
  return (  (t_ype==s.t_ype)  &&
            (s_erver==s.s_erver) &&
            (p_ort==s.p_ort) &&
            (h_old==s.h_old) &&
            (t_imeout==s.t_imeout) &&
            (n_eedsLogon==s.n_eedsLogon) &&
            (u_ser==s.u_ser) &&
            (p_ass==s.p_ass)            );
}
<commit_msg>Fixing saving of passwords for people with multiple accounts on the same server. Thanks for the report.<commit_after>/*
    knserverinfo.cpp

    KNode, the KDE newsreader
    Copyright (c) 1999-2001 the KNode authors.
    See file AUTHORS for details

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.
    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software Foundation,
    Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, US
*/

#include "knserverinfo.h"
#include "utilities.h"

#include <kmessagebox.h>
#include <kconfig.h>
#include <klocale.h>
#include <kdebug.h>
#include <kwallet.h>
using namespace KWallet;

KNServerInfo::KNServerInfo()
  : t_ype(STnntp), i_d(-1), p_ort(119), h_old(300),
    t_imeout(60), n_eedsLogon(false)
{
}

KNServerInfo::~KNServerInfo()
{
}

void KNServerInfo::readConf(KConfig *conf)
{
  s_erver=conf->readEntry("server", "localhost");

  if(t_ype==STnntp)
    p_ort=conf->readNumEntry("port", 119);
  else
    p_ort=conf->readNumEntry("port", 25);

  h_old=conf->readNumEntry("holdTime", 300);

  if(h_old < 0) h_old=0;

  t_imeout=conf->readNumEntry("timeout", 60);

  if(t_imeout < 15) t_imeout=15;

  if(t_ype==STnntp) {
    i_d=conf->readNumEntry("id", -1);
    n_eedsLogon=conf->readBoolEntry("needsLogon",false);
    u_ser=conf->readEntry("user");
    p_ass = KNHelper::decryptStr(conf->readEntry("pass"));
    conf->deleteEntry("pass"); //first time run, don't store it in the config file

    if (Wallet::folderDoesNotExist(Wallet::NetworkWallet(), "knode") ||
        Wallet::keyDoesNotExist(Wallet::NetworkWallet(), "knode", QString::number(i_d)))
      return;

    Wallet* wallet = openWallet();
    if (!wallet || wallet->readPassword(QString::number(i_d), p_ass)) {
      //Save the pass in wallet as this might be the first time it's used
      if (wallet)
        wallet->writePassword(QString::number(i_d), p_ass);
    }
  }
}

Wallet* KNServerInfo::openWallet()
{
  //I use this because I don't want to bother user with error messages when
  //he/she didn't even enable wallet.
  if (!Wallet::isEnabled())
	return 0;
  QString networkWallet = Wallet::NetworkWallet();
  Wallet* wallet = Wallet::openWallet(networkWallet);
  if (!wallet) {
    KMessageBox::error(0, i18n("The wallet couldn't be opened "
                               "This error is most probably caused "
                               "by providing a wrong password."));
    return 0;
  }

  if (wallet && !wallet->hasFolder("knode"))
    wallet->createFolder("knode");
  wallet->setFolder("knode");
  return wallet;
}

void KNServerInfo::saveConf(KConfig *conf)
{
  conf->writeEntry("server", s_erver);
  conf->writeEntry("port", p_ort);
  conf->writeEntry("holdTime", h_old);
  conf->writeEntry("timeout", t_imeout);
  if (t_ype==STnntp) {
    conf->writeEntry("id", i_d);
    conf->writeEntry("needsLogon", n_eedsLogon);
    conf->writeEntry("user", u_ser);
    //open wallet for storing only if the user actually does have the password
    if (n_eedsLogon) {
      Wallet* wallet = openWallet();
      if (!wallet || wallet->writePassword(QString::number(i_d), p_ass)) {
          KMessageBox::information(0, i18n("KWallet isn't running. We strongly recommend using "
                                           "KWallet for managing your password"),
                                   i18n("KWallet isn't running!"), "KWalletWarning" );
          conf->writeEntry("pass", KNHelper::encryptStr(p_ass));
      }
    }
  }
}

bool KNServerInfo::operator==(const KNServerInfo &s)
{
  return (  (t_ype==s.t_ype)  &&
            (s_erver==s.s_erver) &&
            (p_ort==s.p_ort) &&
            (h_old==s.h_old) &&
            (t_imeout==s.t_imeout) &&
            (n_eedsLogon==s.n_eedsLogon) &&
            (u_ser==s.u_ser) &&
            (p_ass==s.p_ass)            );
}
<|endoftext|>