<commit_before>/*
 * AttentionalFocusCB.cc
 *
 * Copyright (C) 2014 Misgana Bayetta
 *
 * Author: Misgana Bayetta <misgana.bayetta@gmail.com>  July 2014
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "AttentionalFocusCB.h"
#include <opencog/attentionbank/AttentionBank.h>

using namespace opencog;

AttentionalFocusCB::AttentionalFocusCB(AtomSpace* as) :
	DefaultPatternMatchCB(as)
{
}

bool AttentionalFocusCB::node_match(const Handle& node1, const Handle& node2)
{
	return attentionbank(_as).atom_is_in_AF(node2) and node1 == node2;
}

bool AttentionalFocusCB::link_match(const PatternTermPtr& ptm, const Handle& lsoln)
{
	return attentionbank(_as).atom_is_in_AF(lsoln) and
           DefaultPatternMatchCB::link_match(ptm, lsoln);
}

IncomingSet AttentionalFocusCB::get_incoming_set(const Handle& h)
{
	const IncomingSet &incoming_set = h->getIncomingSet();

	// Discard the part of the incoming set that is below the
	// AF boundary.  The PM will look only at those links that
	// this callback returns; thus we avoid searching the low-AF
	// parts of the hypergraph.
    IncomingSet filtered_set;
    for (const auto& l : incoming_set){
        if(attentionbank(_as).atom_is_in_AF(Handle(l)))
            filtered_set.push_back(l);
    }

	// If nothing is in AF
	if (filtered_set.empty())
	{
		// Returning the empty set abandons the search in this direction.
		// Search will then backtrack and try a different direction.
		// ... and that is exactly what should be happening.
		return filtered_set;
	}

	auto compare_sti = [&](const LinkPtr& lptr1, const LinkPtr& lptr2)->bool
	{
		return attentionbank(_as).get_sti(Handle(lptr1)) >
			attentionbank(_as).get_sti(Handle(lptr2));
	};

	// The exploration of the set of patterns proceeds by going through
	// the incoming set, one by one.  So sorting the incoming set will
	// cause the exploration to look at the highest STI atoms first.
	std::sort(filtered_set.begin(), filtered_set.end(), compare_sti);

	return filtered_set;
}
<commit_msg>More api changes<commit_after>/*
 * AttentionalFocusCB.cc
 *
 * Copyright (C) 2014 Misgana Bayetta
 *
 * Author: Misgana Bayetta <misgana.bayetta@gmail.com>  July 2014
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "AttentionalFocusCB.h"
#include <opencog/attentionbank/AttentionBank.h>

using namespace opencog;

AttentionalFocusCB::AttentionalFocusCB(AtomSpace* as) :
	DefaultPatternMatchCB(as)
{
}

bool AttentionalFocusCB::node_match(const Handle& node1, const Handle& node2)
{
	return attentionbank(_as).atom_is_in_AF(node2) and node1 == node2;
}

bool AttentionalFocusCB::link_match(const PatternTermPtr& ptm, const Handle& lsoln)
{
	return attentionbank(_as).atom_is_in_AF(lsoln) and
           DefaultPatternMatchCB::link_match(ptm, lsoln);
}

IncomingSet AttentionalFocusCB::get_incoming_set(const Handle& h)
{
	const IncomingSet &incoming_set = h->getIncomingSet();

	// Discard the part of the incoming set that is below the
	// AF boundary.  The PM will look only at those links that
	// this callback returns; thus we avoid searching the low-AF
	// parts of the hypergraph.
    IncomingSet filtered_set;
    for (const auto& l : incoming_set){
        if(attentionbank(_as).atom_is_in_AF(Handle(l)))
            filtered_set.push_back(l);
    }

	// If nothing is in AF
	if (filtered_set.empty())
	{
		// Returning the empty set abandons the search in this direction.
		// Search will then backtrack and try a different direction.
		// ... and that is exactly what should be happening.
		return filtered_set;
	}

	auto compare_sti = [&](const LinkPtr& lptr1, const LinkPtr& lptr2)->bool
	{
		return get_sti(Handle(lptr1)) > get_sti(Handle(lptr2));
	};

	// The exploration of the set of patterns proceeds by going through
	// the incoming set, one by one.  So sorting the incoming set will
	// cause the exploration to look at the highest STI atoms first.
	std::sort(filtered_set.begin(), filtered_set.end(), compare_sti);

	return filtered_set;
}
<|endoftext|>


<commit_before>/** \brief Utility for displaying various bits of info about a collection of MARC records.
 *  \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
 *
 *  \copyright 2015-2017 Universitätsbibliothek Tübingen.  All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <algorithm>
#include <iostream>
#include <map>
#include <stdexcept>
#include <string>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include "Compiler.h"
#include "FileUtil.h"
#include "StringUtil.h"
#include "util.h"

static void Usage() __attribute__((noreturn));

static void Usage() {
    std::cerr << "Usage: " << ::progname << " [--verbose] marc_data\n";
    std::exit(EXIT_FAILURE);
}

class Record {
public:
    class Field {
        std::string tag_;
        std::string contents_;
    public:
        Field(const std::string &tag, const std::string &contents): tag_(tag), contents_(contents) { }
        inline const std::string &getTag() const { return tag_; }
        inline const std::string &getContents() const { return contents_; }
        inline std::string getContents() { return contents_; }
        inline bool isControlField() const __attribute__ ((pure)) { return tag_ <= "009"; }
        inline bool isDataField() const __attribute__ ((pure)) { return tag_ > "009"; }
    };
private:
    friend class Reader;
    size_t record_size_; // in bytes
    std::string leader_;
    std::vector<Field> fields_;
public:
    enum RecordType { AUTHORITY, UNKNOWN, BIBLIOGRAPHIC, CLASSIFICATION };
    typedef std::vector<Field>::iterator iterator;
    typedef std::vector<Field>::const_iterator const_iterator;
public:
    explicit Record(const size_t record_size, char * const record_start);

    inline Record(Record &&other) {
        std::swap(record_size_, other.record_size_);
        leader_.swap(other.leader_);
        fields_.swap(other.fields_);
    }

    operator bool () const { return not fields_.empty(); }
    inline size_t size() const { return record_size_; }
    inline size_t getNumberOfFields() const { return fields_.size(); }
    inline const std::string &getLeader() const { return leader_; }
    inline std::string getControlNumber() const
        { return likely(fields_.front().getTag() == "001") ? fields_.front().getContents() : ""; }
    ssize_t getFirstFieldIndex(const std::string &tag) const;
    RecordType getRecordType() const;
    inline const std::string &getFieldData(const size_t field_index) const
        { return fields_[field_index].getContents(); }

    inline iterator begin() { return fields_.begin(); }
    inline iterator end() { return fields_.end(); }
    inline const_iterator begin() const { return fields_.cbegin(); }
    inline const_iterator end() const { return fields_.cend(); }

    /** \brief Finds local ("LOK") block boundaries.
     *  \param local_block_boundaries  Each entry contains the index of the first field of a local block in "first"
     *                                 and the index of the last field + 1 of a local block in "second".
     */
    size_t findAllLocalDataBlocks(std::vector<std::pair<size_t, size_t>> * const local_block_boundaries) const;
private:
    Record() { }
};

inline unsigned ToUnsigned(const char *cp, const unsigned count) {
    unsigned retval(0);
    for (unsigned i(0); i < count; ++i)
        retval = retval * 10 + (*cp++ - '0');

    return retval;
}

const unsigned LEADER_LENGTH(24);

Record::Record(const size_t record_size, char * const record_start)
    : record_size_(record_size), leader_(record_start, record_size)
{
    const char * const base_address_of_data(record_start + ToUnsigned(record_start + 12, 5));

    // Process directory:
    const char *directory_entry(record_start + LEADER_LENGTH);
    while (directory_entry != base_address_of_data - 1) {
        if (unlikely(directory_entry > base_address_of_data))
            Error("in Record::Record: directory_entry > base_address_of_data!");
        std::string tag;
        tag += directory_entry[0];
        tag += directory_entry[1];
        tag += directory_entry[2];
        const unsigned field_length(ToUnsigned(directory_entry + 3, 4));
        const unsigned field_offset(ToUnsigned(directory_entry + 7, 5));
        const std::string field_contents(base_address_of_data + field_offset, field_length - 1);
        fields_.emplace_back(tag, field_contents);
        directory_entry += 3 /* tag */ + 4 /* field length */ + 5 /* field offset */;
    }
}

Record::RecordType Record::getRecordType() const {
    if (leader_[6] == 'z')
        return AUTHORITY;
    if (leader_[6] == 'w')
        return CLASSIFICATION;
    return std::strchr("acdefgijkmoprt", leader_[6]) == nullptr ? UNKNOWN : BIBLIOGRAPHIC;
}

ssize_t Record::getFirstFieldIndex(const std::string &tag) const {
    const auto iter(std::find_if(fields_.cbegin(), fields_.cend(),
                                 [&tag](const Field &field){ return field.getTag() == tag; }));
    return (iter == fields_.cend()) ? -1 : std::distance(fields_.cbegin(), iter);
}

size_t Record::findAllLocalDataBlocks(std::vector<std::pair<size_t, size_t>> *const local_block_boundaries) const
{
    local_block_boundaries->clear();

    size_t local_block_start(getFirstFieldIndex("LOK"));
    if (static_cast<ssize_t>(local_block_start) == -1)
        return 0;

    size_t local_block_end(local_block_start + 1);
    while (local_block_end < fields_.size()) {
        if (StringUtil::StartsWith(fields_[local_block_end].getContents(), "  ""\x1F""0000")) {
            local_block_boundaries->emplace_back(std::make_pair(local_block_start, local_block_end));
            local_block_start = local_block_end;
        }
        ++local_block_end;
    }
    local_block_boundaries->emplace_back(std::make_pair(local_block_start, local_block_end));

    return local_block_boundaries->size();
}

class Subfields {
    const std::string &field_contents_;
public:
    explicit Subfields(const Record::Field &field): field_contents_(field.getContents()) { }
    inline char getIndicator1() const { return unlikely(field_contents_.empty()) ? '\0' : field_contents_[0]; }
    inline char getIndicator2() const { return unlikely(field_contents_.size() < 2) ? '\0' : field_contents_[1]; }
    unsigned size() const __attribute__ ((pure))
        { return std::count(field_contents_.cbegin(), field_contents_.cend(), '\x1F');}
};

class Reader {
    std::unique_ptr<File> input_;
public:
    explicit Reader(const std::string &input_filename);
    Record read();
};

Reader::Reader(const std::string &input_filename): input_(FileUtil::OpenInputFileOrDie(input_filename)) {
}

Record Reader::read() {
    char buf[99999];
    size_t bytes_read;
    if (unlikely((bytes_read = input_->read(buf, 5)) == 0))
        return Record();

    if (unlikely(bytes_read != 5))
        Error("in Reader::read: failed to read record length!");
    const unsigned record_length(ToUnsigned(buf, 5));

    bytes_read = input_->read(buf + 5, record_length - 5);
    if (unlikely(bytes_read != record_length - 5))
        Error("Reader::read: failed to read a record!");

    return Record(record_length, buf);
}

int main(int argc, char *argv[]) {
    ::progname = argv[0];

    if (argc < 2)
        Usage();

    const bool verbose(std::strcmp(argv[1], "--verbose") == 0);
    if (verbose)
        --argc, ++argv;

    if (argc != 2)
        Usage();

    Reader reader(argv[1]);

    try {
        unsigned record_count(0);
        size_t max_record_size(0), max_field_count(0), max_local_block_count(0), max_subfield_count(0);
        std::map<Record::RecordType, unsigned> record_types_and_counts;
        while (const Record record = reader.read()) {
            ++record_count;
            if (record.size() > max_record_size)
                max_record_size = record.size();
            if (record.getNumberOfFields() > max_field_count)
                max_field_count = record.getNumberOfFields();

            const Record::RecordType record_type(record.getRecordType());
            ++record_types_and_counts[record_type];
            if (record_type == Record::RecordType::UNKNOWN)
                std::cerr << "Unknown record type '" << record.getLeader()[6] << "' for control number "
                          << record.getControlNumber() << ".\n";

            for (const auto &field : record) {
                if (field.isDataField()) {
                    const Subfields subfields(field);
                    if (unlikely(subfields.size() > max_subfield_count))
                        max_subfield_count = subfields.size();
                }
            }

            std::vector<std::pair<size_t, size_t>> local_block_boundaries;
            const size_t local_block_count(record.findAllLocalDataBlocks(&local_block_boundaries));
            if (local_block_count > max_local_block_count)
                max_local_block_count = local_block_count;
        }

        std::cerr << "Read " << record_count << " record(s).\n";
        std::cerr << "The largest record contains " << max_record_size << " bytes.\n";
        std::cerr << "The record with the largest number of fields contains " << max_field_count << " field(s).\n";
        std::cerr << "The record with the most local data blocks has " << max_local_block_count
                  << " local block(s).\n";
        std::cerr << "Counted " << record_types_and_counts[Record::RecordType::BIBLIOGRAPHIC]
                  << " bibliographic record(s), " << record_types_and_counts[Record::RecordType::AUTHORITY]
                  << " classification record(s), " << record_types_and_counts[Record::RecordType::CLASSIFICATION]
                  << " authority record(s), and " << record_types_and_counts[Record::RecordType::UNKNOWN]
                  << " record(s) of unknown record type.\n";
        std::cerr << "The field with the most subfields has " << max_subfield_count << " subfield(s).\n";
    } catch (const std::exception &e) {
        Error("Caught exception: " + std::string(e.what()));
    }
}
<commit_msg>Another small optimisation.<commit_after>/** \brief Utility for displaying various bits of info about a collection of MARC records.
 *  \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
 *
 *  \copyright 2015-2017 Universitätsbibliothek Tübingen.  All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <algorithm>
#include <iostream>
#include <map>
#include <stdexcept>
#include <string>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include "Compiler.h"
#include "FileUtil.h"
#include "StringUtil.h"
#include "util.h"

static void Usage() __attribute__((noreturn));

static void Usage() {
    std::cerr << "Usage: " << ::progname << " [--verbose] marc_data\n";
    std::exit(EXIT_FAILURE);
}

class Record {
public:
    class Field {
        std::string tag_;
        std::string contents_;
    public:
        Field(const std::string &tag, const std::string &contents): tag_(tag), contents_(contents) { }
        inline const std::string &getTag() const { return tag_; }
        inline const std::string &getContents() const { return contents_; }
        inline std::string getContents() { return contents_; }
        inline bool isControlField() const __attribute__ ((pure)) { return tag_ <= "009"; }
        inline bool isDataField() const __attribute__ ((pure)) { return tag_ > "009"; }
    };
private:
    friend class Reader;
    size_t record_size_; // in bytes
    std::string leader_;
    std::vector<Field> fields_;
public:
    enum RecordType { AUTHORITY, UNKNOWN, BIBLIOGRAPHIC, CLASSIFICATION };
    typedef std::vector<Field>::iterator iterator;
    typedef std::vector<Field>::const_iterator const_iterator;
public:
    explicit Record(const size_t record_size, char * const record_start);

    inline Record(Record &&other) {
        std::swap(record_size_, other.record_size_);
        leader_.swap(other.leader_);
        fields_.swap(other.fields_);
    }

    operator bool () const { return not fields_.empty(); }
    inline size_t size() const { return record_size_; }
    inline size_t getNumberOfFields() const { return fields_.size(); }
    inline const std::string &getLeader() const { return leader_; }
    inline std::string getControlNumber() const
        { return likely(fields_.front().getTag() == "001") ? fields_.front().getContents() : ""; }
    ssize_t getFirstFieldIndex(const std::string &tag) const;

    RecordType getRecordType() const {
        if (leader_[6] == 'z')
            return AUTHORITY;
        if (leader_[6] == 'w')
            return CLASSIFICATION;
        return __builtin_strchr("acdefgijkmoprt", leader_[6]) == nullptr ? UNKNOWN : BIBLIOGRAPHIC;
    }

    inline const std::string &getFieldData(const size_t field_index) const
        { return fields_[field_index].getContents(); }

    inline iterator begin() { return fields_.begin(); }
    inline iterator end() { return fields_.end(); }
    inline const_iterator begin() const { return fields_.cbegin(); }
    inline const_iterator end() const { return fields_.cend(); }

    /** \brief Finds local ("LOK") block boundaries.
     *  \param local_block_boundaries  Each entry contains the index of the first field of a local block in "first"
     *                                 and the index of the last field + 1 of a local block in "second".
     */
    size_t findAllLocalDataBlocks(std::vector<std::pair<size_t, size_t>> * const local_block_boundaries) const;
private:
    Record() { }
};

inline unsigned ToUnsigned(const char *cp, const unsigned count) {
    unsigned retval(0);
    for (unsigned i(0); i < count; ++i)
        retval = retval * 10 + (*cp++ - '0');

    return retval;
}

const unsigned LEADER_LENGTH(24);

Record::Record(const size_t record_size, char * const record_start)
    : record_size_(record_size), leader_(record_start, record_size)
{
    const char * const base_address_of_data(record_start + ToUnsigned(record_start + 12, 5));

    // Process directory:
    const char *directory_entry(record_start + LEADER_LENGTH);
    while (directory_entry != base_address_of_data - 1) {
        if (unlikely(directory_entry > base_address_of_data))
            Error("in Record::Record: directory_entry > base_address_of_data!");
        std::string tag;
        tag += directory_entry[0];
        tag += directory_entry[1];
        tag += directory_entry[2];
        const unsigned field_length(ToUnsigned(directory_entry + 3, 4));
        const unsigned field_offset(ToUnsigned(directory_entry + 7, 5));
        const std::string field_contents(base_address_of_data + field_offset, field_length - 1);
        fields_.emplace_back(tag, field_contents);
        directory_entry += 3 /* tag */ + 4 /* field length */ + 5 /* field offset */;
    }
}

ssize_t Record::getFirstFieldIndex(const std::string &tag) const {
    const auto iter(std::find_if(fields_.cbegin(), fields_.cend(),
                                 [&tag](const Field &field){ return field.getTag() == tag; }));
    return (iter == fields_.cend()) ? -1 : std::distance(fields_.cbegin(), iter);
}

size_t Record::findAllLocalDataBlocks(std::vector<std::pair<size_t, size_t>> *const local_block_boundaries) const
{
    local_block_boundaries->clear();

    size_t local_block_start(getFirstFieldIndex("LOK"));
    if (static_cast<ssize_t>(local_block_start) == -1)
        return 0;

    size_t local_block_end(local_block_start + 1);
    while (local_block_end < fields_.size()) {
        if (StringUtil::StartsWith(fields_[local_block_end].getContents(), "  ""\x1F""0000")) {
            local_block_boundaries->emplace_back(std::make_pair(local_block_start, local_block_end));
            local_block_start = local_block_end;
        }
        ++local_block_end;
    }
    local_block_boundaries->emplace_back(std::make_pair(local_block_start, local_block_end));

    return local_block_boundaries->size();
}

class Subfields {
    const std::string &field_contents_;
public:
    explicit Subfields(const Record::Field &field): field_contents_(field.getContents()) { }
    inline char getIndicator1() const { return unlikely(field_contents_.empty()) ? '\0' : field_contents_[0]; }
    inline char getIndicator2() const { return unlikely(field_contents_.size() < 2) ? '\0' : field_contents_[1]; }
    unsigned size() const __attribute__ ((pure))
        { return std::count(field_contents_.cbegin(), field_contents_.cend(), '\x1F');}
};

class Reader {
    std::unique_ptr<File> input_;
public:
    explicit Reader(const std::string &input_filename);
    Record read();
};

Reader::Reader(const std::string &input_filename): input_(FileUtil::OpenInputFileOrDie(input_filename)) {
}

Record Reader::read() {
    char buf[99999];
    size_t bytes_read;
    if (unlikely((bytes_read = input_->read(buf, 5)) == 0))
        return Record();

    if (unlikely(bytes_read != 5))
        Error("in Reader::read: failed to read record length!");
    const unsigned record_length(ToUnsigned(buf, 5));

    bytes_read = input_->read(buf + 5, record_length - 5);
    if (unlikely(bytes_read != record_length - 5))
        Error("Reader::read: failed to read a record!");

    return Record(record_length, buf);
}

int main(int argc, char *argv[]) {
    ::progname = argv[0];

    if (argc < 2)
        Usage();

    const bool verbose(std::strcmp(argv[1], "--verbose") == 0);
    if (verbose)
        --argc, ++argv;

    if (argc != 2)
        Usage();

    Reader reader(argv[1]);

    try {
        unsigned record_count(0);
        size_t max_record_size(0), max_field_count(0), max_local_block_count(0), max_subfield_count(0);
        std::map<Record::RecordType, unsigned> record_types_and_counts;
        while (const Record record = reader.read()) {
            ++record_count;
            if (record.size() > max_record_size)
                max_record_size = record.size();
            if (record.getNumberOfFields() > max_field_count)
                max_field_count = record.getNumberOfFields();

            const Record::RecordType record_type(record.getRecordType());
            ++record_types_and_counts[record_type];
            if (record_type == Record::RecordType::UNKNOWN)
                std::cerr << "Unknown record type '" << record.getLeader()[6] << "' for control number "
                          << record.getControlNumber() << ".\n";

            for (const auto &field : record) {
                if (field.isDataField()) {
                    const Subfields subfields(field);
                    if (unlikely(subfields.size() > max_subfield_count))
                        max_subfield_count = subfields.size();
                }
            }

            std::vector<std::pair<size_t, size_t>> local_block_boundaries;
            const size_t local_block_count(record.findAllLocalDataBlocks(&local_block_boundaries));
            if (local_block_count > max_local_block_count)
                max_local_block_count = local_block_count;
        }

        std::cerr << "Read " << record_count << " record(s).\n";
        std::cerr << "The largest record contains " << max_record_size << " bytes.\n";
        std::cerr << "The record with the largest number of fields contains " << max_field_count << " field(s).\n";
        std::cerr << "The record with the most local data blocks has " << max_local_block_count
                  << " local block(s).\n";
        std::cerr << "Counted " << record_types_and_counts[Record::RecordType::BIBLIOGRAPHIC]
                  << " bibliographic record(s), " << record_types_and_counts[Record::RecordType::AUTHORITY]
                  << " classification record(s), " << record_types_and_counts[Record::RecordType::CLASSIFICATION]
                  << " authority record(s), and " << record_types_and_counts[Record::RecordType::UNKNOWN]
                  << " record(s) of unknown record type.\n";
        std::cerr << "The field with the most subfields has " << max_subfield_count << " subfield(s).\n";
    } catch (const std::exception &e) {
        Error("Caught exception: " + std::string(e.what()));
    }
}
<|endoftext|>


<commit_before>/**
 * @file    TaggedPointer.hpp
 * @author  niob
 * @date    Oct 21, 2016
 * @brief   Declares and defines the {@link TaggedPointer} class.
 */

#ifndef TAGGEDPOINTER_HPP_
#define TAGGEDPOINTER_HPP_
#pragma once

#include <cassert>
#include <cstdint>
#include <type_traits>
#include <utility>

namespace ssw {

template <typename T, typename = std::enable_if_t<alignof(T) >= 2>>
class TaggedPointer
{
	static constexpr std::uintptr_t sMaskMark{1};
	static constexpr std::uintptr_t sMaskAll{sMaskMark};

	std::uintptr_t mPointer;

public:
	/**
	 * Default construct a TaggedPointer with a null pointer.
	 */
	constexpr TaggedPointer() noexcept
			: mPointer(reinterpret_cast<std::uintptr_t>(nullptr)) {
	}

	/**
	 * Construct a TaggedPointer from a null pointer.
	 *
	 * @param A null pointer.
	 */
	constexpr TaggedPointer(std::nullptr_t) noexcept
			: mPointer(reinterpret_cast<std::uintptr_t>(nullptr)) {
	}

	/**
	 * Construct a TaggedPointer from the specified pointer.
	 *
	 * @param ptr The value of the pointer.
	 * @param mark (optional) Whether the mark should be set, defaults to `false`.
	 */
	explicit TaggedPointer(T* ptr, bool mark = false) noexcept
			: mPointer(reinterpret_cast<std::uintptr_t>(ptr)) {
		assert(!(mPointer & sMaskAll));
		this->mark(mark);
	}

	/**
	 * Copy construct a TaggedPointer from another one.
	 *
	 * @param The TaggedPointer to copy.
	 */
	TaggedPointer(const TaggedPointer&) = default;

	/**
	 * Move construct a TaggedPointer from another one.
	 *
	 * @param The TaggedPointer to move from.
	 */
	TaggedPointer(TaggedPointer&&) = default;

	/**
	 * Destroy this TaggedPointer.
	 */
	~TaggedPointer() = default;

	/**
	 * Assign the specified pointer to this TaggedPointer.
	 *
	 * @param ptr The value to assign.
	 * @return A reference to this object.
	 */
	TaggedPointer& operator=(T* ptr) noexcept {
		assert(!(mPointer & sMaskAll));
		mPointer = reinterpret_cast<std::uintptr_t>(ptr);
		return *this;
	}

	/**
	 * Copy assign this TaggedPointer from another one.
	 *
	 * @param The TaggedPointer to copy.
	 * @return A reference to this object.
	 */
	TaggedPointer& operator=(const TaggedPointer&) = default;

	/**
	 * Move assign this TaggedPointer from another one.
	 *
	 * @param The TaggedPointer to move from.
	 * @return A reference to this object.
	 */
	TaggedPointer& operator=(TaggedPointer&&) = default;

	/**
	 * Set or clear the mark.
	 *
	 * @param mark `true` to set the mark, `false` to clear it.
	 */
	void mark(bool mark) noexcept {
		if(mark) {
			mPointer |= sMaskMark;
		} else {
			mPointer &= ~sMaskMark;
		}
	}

	/**
	 * Get the mark.
	 *
	 * @return `true` if the mark is set, `false` otherwise.
	 */
	bool mark() const noexcept {
		return (mPointer & sMaskMark);
	}

	/**
	 * Get the wrapped pointer value.
	 *
	 * @return The value of this pointer.
	 */
	T* get() const noexcept {
		return reinterpret_cast<T*>(mPointer & ~sMaskAll);
	}

	/**
	 * Test whether this pointer contains a value (is not `null`).
	 */
	explicit operator bool() const noexcept {
		return this->get() != nullptr;
	}

	/**
	 * Dereference this TaggedPointer. This pointer must contain a value (i.e. must not be `null`).
	 *
	 * @return A reference to the pointed-to object. Equivalent to `*get()`.
	 */
	auto operator*() const {
		return *(this->get());
	}

	/**
	 * Get the wrapped pointer value.
	 *
	 * @return The value of this pointer.
	 */
	T* operator->() const noexcept {
		return this->get();
	}

	/**
	 * Swap the values of this TaggedPointer and another one.
	 *
	 * @param other The TaggedPointer to swap values with.
	 */
	void swap(TaggedPointer &other) noexcept {
		std::swap(mPointer, other.mPointer);
	}
};

} // namespace ssw

namespace std {

/**
 * Swap the specified {@link TaggedPointer TaggedPointers}. Calls `lhs.swap(rhs)`.
 *
 * @param lhs The first TaggedPointer to swap.
 * @param rhs The other TaggedPointer to swap.
 */
template <typename T>
void swap(ssw::TaggedPointer<T> &lhs, ssw::TaggedPointer<T> &rhs) noexcept {
	lhs.swap(rhs);
}

} // namespace std

#endif /* TAGGEDPOINTER_HPP_ */
<commit_msg>Add assertion when dereferencing TaggedPointer.<commit_after>/**
 * @file    TaggedPointer.hpp
 * @author  niob
 * @date    Oct 21, 2016
 * @brief   Declares and defines the {@link TaggedPointer} class.
 */

#ifndef TAGGEDPOINTER_HPP_
#define TAGGEDPOINTER_HPP_
#pragma once

#include <cassert>
#include <cstdint>
#include <type_traits>
#include <utility>

namespace ssw {

template <typename T, typename = std::enable_if_t<alignof(T) >= 2>>
class TaggedPointer
{
	static constexpr std::uintptr_t sMaskMark{1};
	static constexpr std::uintptr_t sMaskAll{sMaskMark};

	std::uintptr_t mPointer;

public:
	/**
	 * Default construct a TaggedPointer with a null pointer.
	 */
	constexpr TaggedPointer() noexcept
			: mPointer(reinterpret_cast<std::uintptr_t>(nullptr)) {
	}

	/**
	 * Construct a TaggedPointer from a null pointer.
	 *
	 * @param A null pointer.
	 */
	constexpr TaggedPointer(std::nullptr_t) noexcept
			: mPointer(reinterpret_cast<std::uintptr_t>(nullptr)) {
	}

	/**
	 * Construct a TaggedPointer from the specified pointer.
	 *
	 * @param ptr The value of the pointer.
	 * @param mark (optional) Whether the mark should be set, defaults to `false`.
	 */
	explicit TaggedPointer(T* ptr, bool mark = false) noexcept
			: mPointer(reinterpret_cast<std::uintptr_t>(ptr)) {
		assert(!(mPointer & sMaskAll));
		this->mark(mark);
	}

	/**
	 * Copy construct a TaggedPointer from another one.
	 *
	 * @param The TaggedPointer to copy.
	 */
	TaggedPointer(const TaggedPointer&) = default;

	/**
	 * Move construct a TaggedPointer from another one.
	 *
	 * @param The TaggedPointer to move from.
	 */
	TaggedPointer(TaggedPointer&&) = default;

	/**
	 * Destroy this TaggedPointer.
	 */
	~TaggedPointer() = default;

	/**
	 * Assign the specified pointer to this TaggedPointer.
	 *
	 * @param ptr The value to assign.
	 * @return A reference to this object.
	 */
	TaggedPointer& operator=(T* ptr) noexcept {
		assert(!(mPointer & sMaskAll));
		mPointer = reinterpret_cast<std::uintptr_t>(ptr);
		return *this;
	}

	/**
	 * Copy assign this TaggedPointer from another one.
	 *
	 * @param The TaggedPointer to copy.
	 * @return A reference to this object.
	 */
	TaggedPointer& operator=(const TaggedPointer&) = default;

	/**
	 * Move assign this TaggedPointer from another one.
	 *
	 * @param The TaggedPointer to move from.
	 * @return A reference to this object.
	 */
	TaggedPointer& operator=(TaggedPointer&&) = default;

	/**
	 * Set or clear the mark.
	 *
	 * @param mark `true` to set the mark, `false` to clear it.
	 */
	void mark(bool mark) noexcept {
		if(mark) {
			mPointer |= sMaskMark;
		} else {
			mPointer &= ~sMaskMark;
		}
	}

	/**
	 * Get the mark.
	 *
	 * @return `true` if the mark is set, `false` otherwise.
	 */
	bool mark() const noexcept {
		return (mPointer & sMaskMark);
	}

	/**
	 * Get the wrapped pointer value.
	 *
	 * @return The value of this pointer.
	 */
	T* get() const noexcept {
		return reinterpret_cast<T*>(mPointer & ~sMaskAll);
	}

	/**
	 * Test whether this pointer contains a value (is not `null`).
	 */
	explicit operator bool() const noexcept {
		return this->get() != nullptr;
	}

	/**
	 * Dereference this TaggedPointer. This pointer must contain a value (i.e. must not be `null`).
	 *
	 * @return A reference to the pointed-to object. Equivalent to `*get()`.
	 */
	auto operator*() const {
		assert(static_cast<bool>(*this));
		return *(this->get());
	}

	/**
	 * Get the wrapped pointer value.
	 *
	 * @return The value of this pointer.
	 */
	T* operator->() const noexcept {
		return this->get();
	}

	/**
	 * Swap the values of this TaggedPointer and another one.
	 *
	 * @param other The TaggedPointer to swap values with.
	 */
	void swap(TaggedPointer &other) noexcept {
		std::swap(mPointer, other.mPointer);
	}
};

} // namespace ssw

namespace std {

/**
 * Swap the specified {@link TaggedPointer TaggedPointers}. Calls `lhs.swap(rhs)`.
 *
 * @param lhs The first TaggedPointer to swap.
 * @param rhs The other TaggedPointer to swap.
 */
template <typename T>
void swap(ssw::TaggedPointer<T> &lhs, ssw::TaggedPointer<T> &rhs) noexcept {
	lhs.swap(rhs);
}

} // namespace std

#endif /* TAGGEDPOINTER_HPP_ */
<|endoftext|>


<commit_before>//
// Created by manuel on 21.06.15.
//

#include "ArgsCommand.h"
#include <iostream>
#include <plog/Log.h>
#include <unistd.h>
#include <string>
#include <libgen.h>
#include <stdexcept>

using namespace std;

static const string ZMACHINE_EXT_V8 = ".z8";
static const string ZAP_EXT = ".zap";
static const string DEFAULT_PROGRAM_NAME = "twzcc";

string GetProperFileName(string fullPath) {
    string fileName;

    char *base;
    char *fileCStr = new char[fullPath.length() +
                              1]; // need to copy because c_str return const val (on linux but apparently not darwin???)
    copy(fullPath.begin(), fullPath.end(), fileCStr);
    fileCStr[fullPath.length()] = '\0';

    if ((base = basename(fileCStr)) != NULL) {
        char *pointPos = strrchr(base, '.');
        if (pointPos)
            pointPos[0] = '\0';

        fileName = string(base);
    }

    delete[] fileCStr;

    if (base == NULL) {
        throw invalid_argument("unable to resolve basename for " + fullPath);
    }

    return fileName;
}

void ArgsCommand::printHelpMessage(string invocation) {
    string properInvocationName = "";
    try {
        properInvocationName = GetProperFileName(invocation);
    } catch (const invalid_argument &e) { }

    cout << "Usage: " <<
    (properInvocationName.empty() ? DEFAULT_PROGRAM_NAME : properInvocationName) << " " <<
    "[-d] [-o outputfile] [-a] <inputfile>" << endl << endl <<
    "  -d"                  << "\t\t\t\t" << "print debug logs to console" << endl <<
    "  -o <outputfile>"     << "\t"       << "use specified output instead of default (name of input file with .z8 extension)" << endl <<
    "  -a"                  << "\t\t\t\t" << "treat input file as Z-machine assembly instead of Twee source (cannot be used in conjunction with -s)" << endl <<
    "  -s"                  << "\t\t\t\t" << "generate readable Z-machine assembly instead of Z-program (cannot be used in conjunction with -a)" << endl;
}

ArgsCommand::ArgsCommand(int argc, char **argv) {
    int opt;
    debugInConsole = false;
    inputIsAssembly = false;
    valid = true;

    size_t findPosition;

    int longIndex = 0;

    while ((opt = getopt(argc, argv, "o:ads")) != -1) {
        switch (opt) {
            default:
                cerr << "unknown argument: " << (char) opt << endl;
                valid = false;
                return;
            case 'd':
                debugInConsole = true;
                break;
            case 'a': //source file is Z-Assembly
                inputIsAssembly = true;
                break;
            case 's':
                outputIsAssembly = true;
                break;
            case 'o':
                outputFile = optarg;
                break;
        }
    }

    if (inputIsAssembly && outputIsAssembly) {
        cerr << "Both -a and -s flag provided." << endl;
        valid = false;
        return;
    }

    if (optind == argc - 1) {
        sourceFile = argv[optind];

        // define standard output file if necessary
        if (outputFile.empty()) { // assuming empty string means not set yet
            try {
                outputFile = GetProperFileName(sourceFile) + (outputIsAssembly ? ZAP_EXT : ZMACHINE_EXT_V8);
            } catch (const invalid_argument &e) {
                valid = false;
            }
        }
    } else {
        cerr << "invalid number of non-option arguments" << endl;
        valid = false;
    }
}

string ArgsCommand::getSourceFileName() const {
    return sourceFile;
}

string ArgsCommand::getOutputFileName() const {
    return outputFile;
}

bool ArgsCommand::sourceFileIsTwee() const {
    return !inputIsAssembly;
}

bool ArgsCommand::sourceFileIsAssembly() const {
    return inputIsAssembly;
}

bool ArgsCommand::isDebugInConsole() const {
    return debugInConsole;
}

bool ArgsCommand::isValid() const {
    return valid;
}

bool ArgsCommand::outputToAssembly() const {
    return outputIsAssembly;
}
<commit_msg>add check if input is directory<commit_after>//
// Created by manuel on 21.06.15.
//

#include "ArgsCommand.h"
#include <iostream>
#include <plog/Log.h>
#include <unistd.h>
#include <string>
#include <libgen.h>
#include <stdexcept>

using namespace std;

static const string ZMACHINE_EXT_V8 = ".z8";
static const string ZAP_EXT = ".zap";
static const string DEFAULT_PROGRAM_NAME = "twzcc";

string GetProperFileName(string fullPath) {
    string fileName;

    char *base;
    char *fileCStr = new char[fullPath.length() +
                              1]; // need to copy because c_str return const val (on linux but apparently not darwin???)
    copy(fullPath.begin(), fullPath.end(), fileCStr);
    fileCStr[fullPath.length()] = '\0';

    if ((base = basename(fileCStr)) != NULL) {
        char *pointPos = strrchr(base, '.');
        if (pointPos)
            pointPos[0] = '\0';

        fileName = string(base);
    }

    delete[] fileCStr;

    if (base == NULL) {
        throw invalid_argument("unable to resolve basename for " + fullPath);
    }

    return fileName;
}

void ArgsCommand::printHelpMessage(string invocation) {
    string properInvocationName = "";
    try {
        properInvocationName = GetProperFileName(invocation);
    } catch (const invalid_argument &e) { }

    cout << "Usage: " <<
    (properInvocationName.empty() ? DEFAULT_PROGRAM_NAME : properInvocationName) << " " <<
    "[-d] [-o outputfile] [-a] <inputfile>" << endl << endl <<
    "  -d"                  << "\t\t\t\t" << "print debug logs to console" << endl <<
    "  -o <outputfile>"     << "\t"       << "use specified output instead of default (name of input file with .z8 extension)" << endl <<
    "  -a"                  << "\t\t\t\t" << "treat input file as Z-machine assembly instead of Twee source (cannot be used in conjunction with -s)" << endl <<
    "  -s"                  << "\t\t\t\t" << "generate readable Z-machine assembly instead of Z-program (cannot be used in conjunction with -a)" << endl;
}

ArgsCommand::ArgsCommand(int argc, char **argv) {
    int opt;
    debugInConsole = false;
    inputIsAssembly = false;
    valid = true;

    size_t findPosition;

    int longIndex = 0;

    while ((opt = getopt(argc, argv, "o:ads")) != -1) {
        switch (opt) {
            default:
                cerr << "unknown argument: " << (char) opt << endl;
                valid = false;
                return;
            case 'd':
                debugInConsole = true;
                break;
            case 'a': //source file is Z-Assembly
                inputIsAssembly = true;
                break;
            case 's':
                outputIsAssembly = true;
                break;
            case 'o':
                outputFile = optarg;
                break;
        }
    }

    if (inputIsAssembly && outputIsAssembly) {
        cerr << "Both -a and -s flag provided." << endl;
        valid = false;
        return;
    }

    if (optind == argc - 1) {
        sourceFile = argv[optind];

        int status;
        struct stat st_buf;

        status = stat(sourceFile.c_str(), &st_buf);
        if(status != 0) {
            cerr << "error checking file status: " << strerror(errno) << endl;
            valid = false;
        }

        if (S_ISDIR(st_buf.st_mode)) {
            cerr << "error: specified input is a directory" << endl;
            valid = false;
        }

        // define standard output file if necessary
        if (outputFile.empty()) { // assuming empty string means not set yet
            try {
                outputFile = GetProperFileName(sourceFile) + (outputIsAssembly ? ZAP_EXT : ZMACHINE_EXT_V8);
            } catch (const invalid_argument &e) {
                valid = false;
            }
        }
    } else {
        cerr << "invalid number of non-option arguments" << endl;
        valid = false;
    }
}

string ArgsCommand::getSourceFileName() const {
    return sourceFile;
}

string ArgsCommand::getOutputFileName() const {
    return outputFile;
}

bool ArgsCommand::sourceFileIsTwee() const {
    return !inputIsAssembly;
}

bool ArgsCommand::sourceFileIsAssembly() const {
    return inputIsAssembly;
}

bool ArgsCommand::isDebugInConsole() const {
    return debugInConsole;
}

bool ArgsCommand::isValid() const {
    return valid;
}

bool ArgsCommand::outputToAssembly() const {
    return outputIsAssembly;
}
<|endoftext|>


<commit_before>#include <math.h>

#include "network_model_hop_counter.h"
#include "config.h"

NetworkModelHopCounter::NetworkModelHopCounter(Network *net)
   : NetworkModel(net)
   , _enabled(true)
   , _bytesSent(0)
   , _cyclesLatency(0)
   , _hopLatency(1)
{
   SInt32 total_cores = Config::getSingleton()->getTotalCores();

   _meshWidth = (SInt32) sqrt(total_cores);
   _meshHeight = (SInt32) (1.0 * total_cores / _meshWidth + 0.5);

   assert(total_cores <= _meshWidth * _meshHeight);
   assert(total_cores > (_meshWidth - 1) * _meshHeight);
   assert(total_cores > _meshWidth * (_meshHeight - 1));
}

NetworkModelHopCounter::~NetworkModelHopCounter()
{
}

void NetworkModelHopCounter::computePosition(core_id_t core,
                                             SInt32 &x, SInt32 &y)
{
   x = core % _meshWidth;
   y = core / _meshWidth;
}

SInt32 NetworkModelHopCounter::computeDistance(SInt32 x1, SInt32 y1, SInt32 x2, SInt32 y2)
{
   return abs(x1 - x2) + abs(y1 - y2);
}

void NetworkModelHopCounter::routePacket(const NetPacket &pkt,
                                         std::vector<Hop> &nextHops)
{
   SInt32 sx, sy, dx, dy;

   computePosition(pkt.sender, sx, sy);
   computePosition(pkt.receiver, dx, dy);

   UInt64 latency = computeDistance(sx, sy, dx, dy) * _hopLatency;

   Hop h;
   h.dest = pkt.receiver;
   h.time = pkt.time + latency;

   nextHops.push_back(h);

   if (!_enabled)
      return;

   _lock.acquire();
   _bytesSent += pkt.length;
   _cyclesLatency += latency;
   _lock.release();
}

void NetworkModelHopCounter::outputSummary(std::ostream &out)
{
   out << "    bytes sent: " << _bytesSent << std::endl;
   out << "    cycles spent latency: " << _cyclesLatency << std::endl;
}
<commit_msg>[network/hop_counter] Fix calculation of network topology.<commit_after>#include <math.h>

#include "network_model_hop_counter.h"
#include "config.h"

NetworkModelHopCounter::NetworkModelHopCounter(Network *net)
   : NetworkModel(net)
   , _enabled(true)
   , _bytesSent(0)
   , _cyclesLatency(0)
   , _hopLatency(1)
{
   SInt32 total_cores = Config::getSingleton()->getTotalCores();

   _meshWidth = (SInt32) floor (sqrt(total_cores));
   _meshHeight = (SInt32) ceil (1.0 * total_cores / _meshWidth);

   assert(total_cores <= _meshWidth * _meshHeight);
   assert(total_cores > (_meshWidth - 1) * _meshHeight);
   assert(total_cores > _meshWidth * (_meshHeight - 1));
}

NetworkModelHopCounter::~NetworkModelHopCounter()
{
}

void NetworkModelHopCounter::computePosition(core_id_t core,
                                             SInt32 &x, SInt32 &y)
{
   x = core % _meshWidth;
   y = core / _meshWidth;
}

SInt32 NetworkModelHopCounter::computeDistance(SInt32 x1, SInt32 y1, SInt32 x2, SInt32 y2)
{
   return abs(x1 - x2) + abs(y1 - y2);
}

void NetworkModelHopCounter::routePacket(const NetPacket &pkt,
                                         std::vector<Hop> &nextHops)
{
   SInt32 sx, sy, dx, dy;

   computePosition(pkt.sender, sx, sy);
   computePosition(pkt.receiver, dx, dy);

   UInt64 latency = computeDistance(sx, sy, dx, dy) * _hopLatency;

   Hop h;
   h.dest = pkt.receiver;
   h.time = pkt.time + latency;

   nextHops.push_back(h);

   if (!_enabled)
      return;

   _lock.acquire();
   _bytesSent += pkt.length;
   _cyclesLatency += latency;
   _lock.release();
}

void NetworkModelHopCounter::outputSummary(std::ostream &out)
{
   out << "    bytes sent: " << _bytesSent << std::endl;
   out << "    cycles spent latency: " << _cyclesLatency << std::endl;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: fumorph.hxx,v $
 *
 *  $Revision: 1.1.1.1 $
 *
 *  last change: $Author: hr $ $Date: 2000-09-18 16:48:39 $
 *
 *  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 _SD_FUMORPH_HXX
#define _SD_FUMORPH_HXX

#ifndef _SD_FUPOOR_HXX
#include "fupoor.hxx"
#endif

#include <math.h>

/*************************************************************************
|*
\************************************************************************/
class PolyPolygon3D;
class Polygon3D;
class Vector3D;

class FuMorph : public FuPoor
{
    void ImpInsertPolygons(List& rPolyPolyList3D, BOOL bAttributeFade,
        const SdrObject* pObj1, const SdrObject* pObj2);
    PolyPolygon3D* ImpCreateMorphedPolygon(
        const PolyPolygon3D& rPolyPolyStart,
        const PolyPolygon3D& rPolyPolyEnd,
        const double fMorphingFactor);
    BOOL ImpMorphPolygons(
        const PolyPolygon3D& rPolyPoly1, const PolyPolygon3D& rPolyPoly2,
        const USHORT nSteps, List& rPolyPolyList3D);
    void ImpAddPolys(PolyPolygon3D& rSmaller, const PolyPolygon3D& rBigger);
    void ImpEqualizePolyPointCount(Polygon3D& rSmall, const Polygon3D& rBig);
    sal_uInt16 ImpGetNearestIndex(const Polygon3D& rPoly, const Vector3D& rPos);

public:
    TYPEINFO();

    FuMorph(SdViewShell* pViewSh, SdWindow* pWin, SdView* pView,
        SdDrawDocument* pDoc, SfxRequest& rReq);
    ~FuMorph() {}
};

#endif // _SD_FUMORPH_HXX

<commit_msg>INTEGRATION: CWS impress1 (1.1.1.1.262); FILE MERGED 2003/09/16 13:36:00 af 1.1.1.1.262.1: #111996# Introduction of namespace sd. Use of sub-shells.<commit_after>/*************************************************************************
 *
 *  $RCSfile: fumorph.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: obo $ $Date: 2004-01-20 12:04:33 $
 *
 *  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 SD_FU_MORPH_HXX
#define SD_FU_MORPH_HXX

#ifndef SD_FU_POOR_HXX
#include "fupoor.hxx"
#endif

#include <math.h>

/*************************************************************************
|*
\************************************************************************/
class List;
class PolyPolygon3D;
class Polygon3D;
class Vector3D;

namespace sd {

class FuMorph
    : public FuPoor
{
public:
    TYPEINFO();

    FuMorph (
        ViewShell* pViewSh,
        ::sd::Window* pWin,
        ::sd::View* pView,
        SdDrawDocument* pDoc,
        SfxRequest& rReq);
    virtual ~FuMorph (void) {}

private:
    void ImpInsertPolygons(List& rPolyPolyList3D, BOOL bAttributeFade,
        const SdrObject* pObj1, const SdrObject* pObj2);
    PolyPolygon3D* ImpCreateMorphedPolygon(
        const PolyPolygon3D& rPolyPolyStart,
        const PolyPolygon3D& rPolyPolyEnd,
        const double fMorphingFactor);
    BOOL ImpMorphPolygons(
        const PolyPolygon3D& rPolyPoly1, const PolyPolygon3D& rPolyPoly2,
        const USHORT nSteps, List& rPolyPolyList3D);
    void ImpAddPolys(PolyPolygon3D& rSmaller, const PolyPolygon3D& rBigger);
    void ImpEqualizePolyPointCount(Polygon3D& rSmall, const Polygon3D& rBig);
    sal_uInt16 ImpGetNearestIndex(const Polygon3D& rPoly, const Vector3D& rPos);
};

} // end of namespace sd

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: clview.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: ka $ $Date: 2001-10-22 13:36:57 $
 *
 *  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 _SFXAPP_HXX
#include <sfx2/app.hxx>
#endif

#pragma hdrstop

#include "clview.hxx"
#include "drawview.hxx"
#include "sdpage.hxx"

class SdDrawDocShell;
class SdDrawViewShell;

/*************************************************************************
|*
|* Ctor: Die SdClientView wird fuer SdDrawDocShell::Draw() verwendet
|*
\************************************************************************/

SdClientView::SdClientView(SdDrawDocShell* pDocSh, OutputDevice* pOutDev,
                           SdDrawViewShell* pShell) :
    SdDrawView(pDocSh, pOutDev, pShell)
{
}

/*************************************************************************
|*
|* Dtor
|*
\************************************************************************/

SdClientView::~SdClientView()
{
}

/*************************************************************************
|*
|* Wenn die View kein Invalidate() an den Fenstern durchfuehren soll, muss
|* man diese Methode ueberladen und entsprechend anders reagieren.
|*
\************************************************************************/

void SdClientView::InvalidateOneWin(Window& rWin)
{
    Region aRegion;
    InitRedraw(&rWin, aRegion);
}

/*************************************************************************
|*
|* Wenn die View kein Invalidate() an den Fenstern durchfuehren soll, muss
|* man diese Methode ueberladen und entsprechend anders reagieren.
|*
\************************************************************************/

void SdClientView::InvalidateOneWin(Window& rWin, const Rectangle& rRect)
{
    InitRedraw(&rWin, rRect);
}

/*************************************************************************
|*
|*
|*
\************************************************************************/

void SdClientView::InitRedraw(OutputDevice* pOutDev, const Region& rReg)
{
    SdDrawView::InitRedraw(pOutDev, rReg);

    // Stets Demo-Output auf dem ganzen Fenster ausgeben
    Rectangle aRect( Point(0, 0), pOutDev->GetOutputSize() );
    SFX_APP()->SpoilDemoOutput(*pOutDev, aRect );
}

<commit_msg>INTEGRATION: CWS impress1 (1.2.238); FILE MERGED 2004/01/09 16:32:45 af 1.2.238.2: #111996# Renamed header files DrawView.hxx, Fader.hxx, and ShowView.hxx back to lowercase version. 2003/09/17 08:13:54 af 1.2.238.1: #111996# Transition to stacked sub-shells. Introduction of namespace sd.<commit_after>/*************************************************************************
 *
 *  $RCSfile: clview.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2004-01-20 12:41:27 $
 *
 *  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 _SFXAPP_HXX
#include <sfx2/app.hxx>
#endif

#pragma hdrstop

#ifndef SD_CLIENT_VIEW_HXX
#include "ClientView.hxx"
#endif
#ifndef SD_DRAW_VIEW_HXX
#include "drawview.hxx"
#endif
#include "sdpage.hxx"

class DrawDocShell;

namespace sd {

class DrawViewShell;

/*************************************************************************
|*
|* Ctor: Die ClientView wird fuer DrawDocShell::Draw() verwendet
|*
\************************************************************************/

ClientView::ClientView(
    DrawDocShell* pDocSh,
    OutputDevice* pOutDev,
    DrawViewShell* pShell)
    : DrawView (pDocSh, pOutDev, pShell)
{
}

/*************************************************************************
|*
|* Dtor
|*
\************************************************************************/

ClientView::~ClientView()
{
}

/*************************************************************************
|*
|* Wenn die View kein Invalidate() an den Fenstern durchfuehren soll, muss
|* man diese Methode ueberladen und entsprechend anders reagieren.
|*
\************************************************************************/

void ClientView::InvalidateOneWin(::Window& rWin)
{
    Region aRegion;
    InitRedraw(&rWin, aRegion);
}

/*************************************************************************
|*
|* Wenn die View kein Invalidate() an den Fenstern durchfuehren soll, muss
|* man diese Methode ueberladen und entsprechend anders reagieren.
|*
\************************************************************************/

void ClientView::InvalidateOneWin(::Window& rWin, const Rectangle& rRect)
{
    InitRedraw(&rWin, rRect);
}

/*************************************************************************
|*
|*
|*
\************************************************************************/

void ClientView::InitRedraw(OutputDevice* pOutDev, const Region& rReg)
{
    DrawView::InitRedraw(pOutDev, rReg);

    // Stets Demo-Output auf dem ganzen Fenster ausgeben
    Rectangle aRect( Point(0, 0), pOutDev->GetOutputSize() );
    SFX_APP()->SpoilDemoOutput(*pOutDev, aRect );
}

} // end of namespace sd
<|endoftext|>


<commit_before>/** \file    add_superior_flag.cc
 *  \author  Oliver Obenland
 *
 *  A tool for marking superior records that have associated inferior records in our data sets.
 */

/*
    Copyright (C) 2016, Library of the University of Tübingen

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <fstream>
#include <iostream>
#include <memory>
#include <unordered_map>
#include <cstdlib>
#include <cstring>
#include "DirectoryEntry.h"
#include "File.h"
#include "Leader.h"
#include "MarcUtil.h"
#include "MarcXmlWriter.h"
#include "StringUtil.h"
#include "Subfields.h"
#include "util.h"

static unsigned modified_count(0);
static std::set<std::string> superior_ppns;
static std::string superior_subfield_data;

void Usage() {
    std::cerr << "Usage: " << progname << " marc_input marc_output superior_ppns\n";
    std::exit(EXIT_FAILURE);
}

void ProcessRecord(XmlWriter * const xml_writer, MarcUtil::Record * const record) {
    record->setRecordWillBeWrittenAsXml(true);

    // Don't add the flag twice
    if (record->getFieldIndex("SPR") != -1) {
        record->write(xml_writer);
        return;
    }

    const std::vector<std::string> &field_data(record->getFields());
    const auto iter(superior_ppns.find(field_data.at(0)));
    if (iter != superior_ppns.end()) {
        if (not record->insertField("SPR", superior_subfield_data))
            Warning("Not enough room to add a SPR field! (Control number: " + field_data[0] + ")");
        ++modified_count;
    }

    record->write(xml_writer);
}

void AddSuperiorFlag(File * const input, File * const output) {
    MarcXmlWriter xml_writer(output);

    while (MarcUtil::Record record = MarcUtil::Record::XmlFactory(input))
        ProcessRecord(&xml_writer, &record);

    std::cerr << "Modified " << modified_count << " record(s).\n";
}

void LoadSuperiorPPNs(File * const input) {
    unsigned line_no(0);
    std::string line;
    while (input->getline(&line)) {
        ++line_no;
        superior_ppns.emplace(line);
    }

    if (unlikely(superior_ppns.empty()))
        Error("Found no data in \"" + input->getPath() + "\"!");
    std::cerr << "Read " << line_no << " superior PPNs.\n";
}

int main(int argc, char **argv) {
    progname = argv[0];

    if (argc != 4)
        Usage();

    const std::string marc_input_filename(argv[1]);
    File marc_input(marc_input_filename, "r");
    if (not marc_input)
        Error("can't open \"" + marc_input_filename + "\" for reading!");

    const std::string marc_output_filename(argv[2]);
    File marc_output(marc_output_filename, "w");
    if (not marc_output)
        Error("can't open \"" + marc_output_filename + "\" for writing!");

    const std::string superior_ppns_filename(argv[3]);
    File superior_ppns_input(superior_ppns_filename, "r");
    if (not superior_ppns_input)
        Error("can't open \"" + superior_ppns_filename + "\" for reading!");

    try {
        LoadSuperiorPPNs(&superior_ppns_input);

        Subfields superior_subfield(/* indicator1 = */' ', /* indicator2 = */' ');
        superior_subfield.addSubfield('a', "1"); // Could be anything but we can't have an empty field.
        superior_subfield_data = superior_subfield.toString();

        AddSuperiorFlag(&marc_input, &marc_output);
    } catch (const std::exception &x) {
        Error("caught exception: " + std::string(x.what()));
    }
}
<commit_msg>Fixed accounting.<commit_after>/** \file    add_superior_flag.cc
 *  \author  Oliver Obenland
 *
 *  A tool for marking superior records that have associated inferior records in our data sets.
 */

/*
    Copyright (C) 2016, Library of the University of Tübingen

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <fstream>
#include <iostream>
#include <memory>
#include <unordered_map>
#include <cstdlib>
#include <cstring>
#include "DirectoryEntry.h"
#include "File.h"
#include "Leader.h"
#include "MarcUtil.h"
#include "MarcXmlWriter.h"
#include "StringUtil.h"
#include "Subfields.h"
#include "util.h"

static unsigned modified_count(0);
static std::set<std::string> superior_ppns;
static std::string superior_subfield_data;

void Usage() {
    std::cerr << "Usage: " << progname << " marc_input marc_output superior_ppns\n";
    std::exit(EXIT_FAILURE);
}

void ProcessRecord(XmlWriter * const xml_writer, MarcUtil::Record * const record) {
    record->setRecordWillBeWrittenAsXml(true);

    // Don't add the flag twice
    if (record->getFieldIndex("SPR") != -1) {
        record->write(xml_writer);
        return;
    }

    const std::vector<std::string> &field_data(record->getFields());
    const auto iter(superior_ppns.find(field_data.at(0)));
    if (iter != superior_ppns.end()) {
        if (not record->insertField("SPR", superior_subfield_data))
            Warning("Not enough room to add a SPR field! (Control number: " + field_data[0] + ")");
        else
            ++modified_count;
    }

    record->write(xml_writer);
}

void AddSuperiorFlag(File * const input, File * const output) {
    MarcXmlWriter xml_writer(output);

    while (MarcUtil::Record record = MarcUtil::Record::XmlFactory(input))
        ProcessRecord(&xml_writer, &record);

    std::cerr << "Modified " << modified_count << " record(s).\n";
}

void LoadSuperiorPPNs(File * const input) {
    unsigned line_no(0);
    std::string line;
    while (input->getline(&line)) {
        ++line_no;
        superior_ppns.emplace(line);
    }

    if (unlikely(superior_ppns.empty()))
        Error("Found no data in \"" + input->getPath() + "\"!");
    std::cerr << "Read " << line_no << " superior PPNs.\n";
}

int main(int argc, char **argv) {
    progname = argv[0];

    if (argc != 4)
        Usage();

    const std::string marc_input_filename(argv[1]);
    File marc_input(marc_input_filename, "r");
    if (not marc_input)
        Error("can't open \"" + marc_input_filename + "\" for reading!");

    const std::string marc_output_filename(argv[2]);
    File marc_output(marc_output_filename, "w");
    if (not marc_output)
        Error("can't open \"" + marc_output_filename + "\" for writing!");

    const std::string superior_ppns_filename(argv[3]);
    File superior_ppns_input(superior_ppns_filename, "r");
    if (not superior_ppns_input)
        Error("can't open \"" + superior_ppns_filename + "\" for reading!");

    try {
        LoadSuperiorPPNs(&superior_ppns_input);

        Subfields superior_subfield(/* indicator1 = */' ', /* indicator2 = */' ');
        superior_subfield.addSubfield('a', "1"); // Could be anything but we can't have an empty field.
        superior_subfield_data = superior_subfield.toString();

        AddSuperiorFlag(&marc_input, &marc_output);
    } catch (const std::exception &x) {
        Error("caught exception: " + std::string(x.what()));
    }
}
<|endoftext|>


<commit_before>#include "game/lane_scorer.h"

#include "game/race_tracker.h"

DECLARE_bool(log_overtaking);

namespace game {

LaneScorer::LaneScorer(const Race& race,
                       CarTracker& car_tracker,
                       RaceTracker& race_tracker,
                       std::vector<EnemyTracker>& enemies,
                       const string& color)
  : race_(race), car_tracker_(car_tracker), enemies_(enemies), color_(color),
    race_tracker_(race_tracker), kCarLength(race.cars()[0].length()) {
}

int LaneScorer::ScoreLane(int from, int to, int lane) {
  using std::max; using std::min;
  auto& me = *std::find_if(enemies_.begin(), enemies_.end(), [this](const EnemyTracker& e){ return e.color() == this->color_; });

  Position end_position(to, 0);
  end_position.set_start_lane(lane);
  end_position.set_end_lane(lane);

  if (FLAGS_log_overtaking)
    printf ("(%d,%.2lf,<%d,%d>) CEL\n", end_position.piece(),
                                        end_position.piece_distance(),
                                        end_position.start_lane(),
                                        end_position.end_lane());

  int lane_score = 0;
  for (auto& enemy : enemies_) {
    if (enemy.color() == color_) continue;  // Me
    int score = ScoreEnemy(me, enemy, end_position);

    if (FLAGS_log_overtaking)
      printf("Score of %s is %d\n",enemy.color().c_str(), score);

    if (score < 0)  // If we should overtake someone
      lane_score = min(lane_score, score);

    if (score > 0 && lane_score >= 0)  // If there is s1 worth bumping
      lane_score = max(lane_score, score);
  }
  return lane_score;
}

int LaneScorer::ScoreEnemy(const EnemyTracker& me, const EnemyTracker& enemy, const Position& end_position) {
  // TODO if im on the edge of that difference, I can switch into him.
  // TODO2 - I should also check the end so I wont hit him at the end
  if (FLAGS_log_overtaking)
    printf ("(%d,%.2lf,<%d,%d> =%.2lf) (%d,%.2lf,<%d,%d> =%.2lf) ",
        me.state().position().piece(),
        me.state().position().piece_distance(),
        me.state().position().start_lane(),
        me.state().position().end_lane(),
        car_tracker_.DistanceBetween(me.state().position(), end_position),
        enemy.state().position().piece(),
        enemy.state().position().piece_distance(),
        enemy.state().position().start_lane(),
        enemy.state().position().end_lane(),
        car_tracker_.DistanceBetween(enemy.state().position(), end_position));

  // if im closer to the end, then im ahead, so ignore the guy
  //
  // Clarification in case of switching into him:
  // Its If we are closer to target, in case of switching into him,
  // we will most probably land ahead of him.
  // If we would take such car seriously, we would never have safe switch
  // if there is s1 on another lane
  if (car_tracker_.DistanceBetween(me.state().position(), end_position) <
      car_tracker_.DistanceBetween(enemy.state().position(), end_position))
    return 0;

  if (enemy.has_finished()) {
    return 0;
  }
  else if (enemy.is_dead()) {
    return ScoreDeadEnemy(me, enemy, end_position);
  }
  else {
    return ScoreLivingEnemy(me, enemy, end_position);
  }
}

int LaneScorer::ScoreDeadEnemy(const EnemyTracker& me, const EnemyTracker& enemy, const Position& end_position) {
  auto safe_position = car_tracker_.PredictPosition(enemy.state().position(), 3 * kCarLength);

  // Wont reach safe_position before spawn
  if (!me.IsReady() || me.TimeToPosition(safe_position) > enemy.time_to_spawn()) {
    return (int) kDeadCrash;
  } else {
    return 0;
  }
}

int LaneScorer::ScoreLivingEnemy(const EnemyTracker& me, const EnemyTracker& enemy, const Position& end_position) {
  // If models are ready try to predict if we will actually hit
  if (enemy.IsReady() && me.IsReady()) {
    Position bump_position;
    bool will_bump = BumpPosition(me, enemy, end_position, &bump_position);

    if (will_bump) {
      return EnemyBumpScore(enemy, me.ExpectedVelocity(bump_position), enemy.ExpectedVelocity(bump_position));
    } else {
      return 0;
    }
  } else {
    return EnemyBumpScore(enemy, me.state().velocity(), enemy.state().velocity());
  }
}

int LaneScorer::EnemyBumpScore(const EnemyTracker& enemy, double my_speed, double his_speed) {
  if (his_speed < 0.95 * my_speed) {
    return (-kDeadCrash) * (1 - his_speed / my_speed);
  } else {
    return 0;
  }
  //if (race_tracker_.IsCompetitive(enemy.color()))
  //  return 10;
}

bool LaneScorer::BumpPosition(const EnemyTracker& me, const EnemyTracker& enemy, const Position& end_position, Position* bump_position) {
  int my_time = me.TimeToPosition(end_position);
  int enemy_time = enemy.TimeToPosition(
      car_tracker_.PredictPosition(end_position, kCarLength * 1.1));

  if (my_time > enemy_time)
    return false;

  // TODO OPTIMIZE - steps ^ 2
  for (int i = 0; i < enemy_time; i++) {
    auto my_position = me.PositionAfterTime(i, end_position.end_lane());
    auto enemy_position = enemy.PositionAfterTime(i, end_position.end_lane());

    if (car_tracker_.DistanceBetween(my_position, enemy_position) < kCarLength) {
      *bump_position = enemy_position;
      return true;
    }
  }

  // We havent found bump (shouldnt happen)
  return false;
}

}  // namespace game
<commit_msg>Fix sign error<commit_after>#include "game/lane_scorer.h"

#include "game/race_tracker.h"

DECLARE_bool(log_overtaking);

namespace game {

LaneScorer::LaneScorer(const Race& race,
                       CarTracker& car_tracker,
                       RaceTracker& race_tracker,
                       std::vector<EnemyTracker>& enemies,
                       const string& color)
  : race_(race), car_tracker_(car_tracker), enemies_(enemies), color_(color),
    race_tracker_(race_tracker), kCarLength(race.cars()[0].length()) {
}

int LaneScorer::ScoreLane(int from, int to, int lane) {
  using std::max; using std::min;
  auto& me = *std::find_if(enemies_.begin(), enemies_.end(), [this](const EnemyTracker& e){ return e.color() == this->color_; });

  Position end_position(to, 0);
  end_position.set_start_lane(lane);
  end_position.set_end_lane(lane);

  if (FLAGS_log_overtaking)
    printf ("(%d,%.2lf,<%d,%d>) CEL\n", end_position.piece(),
                                        end_position.piece_distance(),
                                        end_position.start_lane(),
                                        end_position.end_lane());

  int lane_score = 0;
  for (auto& enemy : enemies_) {
    if (enemy.color() == color_) continue;  // Me
    int score = ScoreEnemy(me, enemy, end_position);

    if (FLAGS_log_overtaking)
      printf("Score of %s is %d\n",enemy.color().c_str(), score);

    if (score < 0)  // If we should overtake someone
      lane_score = min(lane_score, score);

    if (score > 0 && lane_score >= 0)  // If there is s1 worth bumping
      lane_score = max(lane_score, score);
  }
  return lane_score;
}

int LaneScorer::ScoreEnemy(const EnemyTracker& me, const EnemyTracker& enemy, const Position& end_position) {
  // TODO if im on the edge of that difference, I can switch into him.
  // TODO2 - I should also check the end so I wont hit him at the end
  if (FLAGS_log_overtaking)
    printf ("(%d,%.2lf,<%d,%d> =%.2lf) (%d,%.2lf,<%d,%d> =%.2lf) ",
        me.state().position().piece(),
        me.state().position().piece_distance(),
        me.state().position().start_lane(),
        me.state().position().end_lane(),
        car_tracker_.DistanceBetween(me.state().position(), end_position),
        enemy.state().position().piece(),
        enemy.state().position().piece_distance(),
        enemy.state().position().start_lane(),
        enemy.state().position().end_lane(),
        car_tracker_.DistanceBetween(enemy.state().position(), end_position));

  // if im closer to the end, then im ahead, so ignore the guy
  //
  // Clarification in case of switching into him:
  // Its If we are closer to target, in case of switching into him,
  // we will most probably land ahead of him.
  // If we would take such car seriously, we would never have safe switch
  // if there is s1 on another lane
  if (car_tracker_.DistanceBetween(me.state().position(), end_position) <
      car_tracker_.DistanceBetween(enemy.state().position(), end_position))
    return 0;

  if (enemy.has_finished()) {
    return 0;
  }
  else if (enemy.is_dead()) {
    return ScoreDeadEnemy(me, enemy, end_position);
  }
  else {
    return ScoreLivingEnemy(me, enemy, end_position);
  }
}

int LaneScorer::ScoreDeadEnemy(const EnemyTracker& me, const EnemyTracker& enemy, const Position& end_position) {
  auto safe_position = car_tracker_.PredictPosition(enemy.state().position(), 3 * kCarLength);

  // Wont reach safe_position before spawn
  if (!me.IsReady() || me.TimeToPosition(safe_position) > enemy.time_to_spawn()) {
    return (int) kDeadCrash;
  } else {
    return 0;
  }
}

int LaneScorer::ScoreLivingEnemy(const EnemyTracker& me, const EnemyTracker& enemy, const Position& end_position) {
  // If models are ready try to predict if we will actually hit
  if (enemy.IsReady() && me.IsReady()) {
    Position bump_position;
    bool will_bump = BumpPosition(me, enemy, end_position, &bump_position);

    if (will_bump) {
      return EnemyBumpScore(enemy, me.ExpectedVelocity(bump_position), enemy.ExpectedVelocity(bump_position));
    } else {
      return 0;
    }
  } else {
    return EnemyBumpScore(enemy, me.state().velocity(), enemy.state().velocity());
  }
}

int LaneScorer::EnemyBumpScore(const EnemyTracker& enemy, double my_speed, double his_speed) {
  if (his_speed < 0.95 * my_speed) {
    return (kDeadCrash) * (1 - his_speed / my_speed);
  } else {
    return 0;
  }
  //if (race_tracker_.IsCompetitive(enemy.color()))
  //  return 10;
}

bool LaneScorer::BumpPosition(const EnemyTracker& me, const EnemyTracker& enemy, const Position& end_position, Position* bump_position) {
  int my_time = me.TimeToPosition(end_position);
  int enemy_time = enemy.TimeToPosition(
      car_tracker_.PredictPosition(end_position, kCarLength * 1.1));

  if (my_time > enemy_time)
    return false;

  // TODO OPTIMIZE - steps ^ 2
  for (int i = 0; i < enemy_time; i++) {
    auto my_position = me.PositionAfterTime(i, end_position.end_lane());
    auto enemy_position = enemy.PositionAfterTime(i, end_position.end_lane());

    if (car_tracker_.DistanceBetween(my_position, enemy_position) < kCarLength) {
      *bump_position = enemy_position;
      return true;
    }
  }

  // We havent found bump (shouldnt happen)
  return false;
}

}  // namespace game
<|endoftext|>


<commit_before>#include <Arduino.h>
#include "MFRC522.h"

//------------------MFRC522 register ---------------
#define         COMMAND_WAIT        0x02
#define         COMMAND_READBLOCK   0x03
#define         COMMAND_WRITEBLOCK  0x04
#define         MFRC522_HEADER      0xAB

#define         STATUS_ERROR        0
#define         STATUS_OK           1

#define         MIFARE_KEYA         0x00
#define         MIFARE_KEYB         0x01

/**
 * Constructor.
 */
MFRC522::MFRC522() {
    _Serial = NULL;
}

/**
 * Description： Obtiene control del Serial para controlar MFRC522.
 * Ademas, pone MFRC522 en modo de espera.
 */
void MFRC522::begin(HardwareSerial *serial) {
    _Serial = serial;
    _Serial->begin(9600);
    wait();
}

/**
 * Description：Pone MFRC522 en modo espera.
 */
void MFRC522::wait() {
    _Serial->write(COMMAND_WAIT);
}

/**
 * Description：Returns true if detect card in MFRC522.
 */
bool MFRC522::available() {
    return (_Serial->available() > 0);
}

/**
 * Description：Read the serial number of the card.
 */
void MFRC522::readCardSerial() {
    for (int i = 0; i < sizeof(cardSerial); ){
        if (available()){
            cardSerial[i] = read();
            i++;
        }
    }
}

/**
 * Description：Returns a pointer to array with card serial.
 */
byte *MFRC522::getCardSerial() {
    return cardSerial;
}

/**
 * Description：Read a block data of the card.
 * Return：Return STATUS_OK if success.
 */
bool MFRC522::getBlock(byte block, byte keyType, byte *key, byte *returnBlock) {
    byte sendData[8] = {
        block,      // block
        keyType,    // key type
        0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF  // key
    };
    byte returnBlockLength;

    for (int i = 0; i < 6; ++i) {
        sendData[2 + i] = key[i];
    }

    return communicate(
        COMMAND_READBLOCK,  // command
        sendData,           // sendData
        0x0A,               // length
        returnBlock,        // returnData
        &returnBlockLength  // returnDataLength
    );
}

/**
 * Description：Write a block data in the card.
 * Return：Return STATUS_OK if success.
 */
bool MFRC522::writeBlock(byte block, byte keyType, byte *key, byte *data) {
    byte sendData[24] = {
        block,      // block
        keyType,    // key type
        0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,  // key
        0x00, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00  // Data
    };
    byte returnBlock[3];
    byte returnBlockLength;

    for (int i = 0; i < 6; ++i) {
        sendData[2 + i] = key[i];
    }

    for (int i = 0; i < 16; ++i) {
        sendData[8 + i] = data[i];
    }

    byte result = communicate(
        COMMAND_WRITEBLOCK, // command
        sendData,           // sendData
        0x1A,               // length
        returnBlock,        // returnData
        &returnBlockLength  // returnDataLength
    );

    return result;
}

/**
 * Description：Comunication between MFRC522 and ISO14443.
 * Return：Return STATUS_OK if success.
 */
bool MFRC522::communicate(byte command, byte *sendData, byte sendDataLength, byte *returnData, byte *returnDataLength) {
    // Send instruction to MFRC522
    write(MFRC522_HEADER);      // Header
    write(sendDataLength);      // Length (Length + Command + Data)
    write(command);             // Command

    for (int i = 0; i < sendDataLength - 2; i++) {
        write(sendData[i]);     // Data
    }

    // Read response to MFRC522
    while (!available());
    byte header = read();           // Header
    while (!available());
    *returnDataLength = read();     // Length (Length + Command + Data)
    while (!available());
    byte commandResult = read();    // Command result

    for (int i = 0; i < *returnDataLength - 2; i=i) {
        if (available()) {
            returnData[i] = read(); // Data
            i++;
        }
    }

    // Return
    if (command != commandResult) {
        return STATUS_ERROR;
    }

    return STATUS_OK;
}

/*
 * Description：Write a byte data into MFRC522.
 */
void MFRC522::write(byte value) {
    _Serial->write(value);
}

/*
 * Description：Read a byte data of MFRC522
 * Return：Return the read value.
 */
byte MFRC522::read() {
    return _Serial->read();
}
<commit_msg>Update MFRC522.cpp<commit_after>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "driver/uart.h"
#include "freertos/queue.h"
#include "esp_log.h"
#include "soc/uart_struct.h"

#include "MFRC522.h"

//------------------MFRC522 register ---------------
#define         COMMAND_WAIT        0x02
#define         COMMAND_READBLOCK   0x03
#define         COMMAND_WRITEBLOCK  0x04
#define         MFRC522_HEADER      0xAB

#define         STATUS_ERROR        0
#define         STATUS_OK           1

#define         MIFARE_KEYA         0x00
#define         MIFARE_KEYB         0x01

/**
 * Constructor.
 */
MFRC522::MFRC522() {
    _Serial = NULL;
}

/**
 * Description： Obtiene control del Serial para controlar MFRC522.
 * Ademas, pone MFRC522 en modo de espera.
 */
void MFRC522::begin(void) {
    wait();
}

/**
 * Description：Pone MFRC522 en modo espera.
 */
void MFRC522::wait() {
}

/**
 * Description：Returns true if detect card in MFRC522.
 */
bool MFRC522::available() {
}

/**
 * Description：Read the serial number of the card.
 */
void MFRC522::readCardSerial() {
    for (int i = 0; i < sizeof(cardSerial); ){
        if (available()){
            cardSerial[i] = read();
            i++;
        }
    }
}

/**
 * Description：Returns a pointer to array with card serial.
 */
byte *MFRC522::getCardSerial() {
    return cardSerial;
}

/**
 * Description：Read a block data of the card.
 * Return：Return STATUS_OK if success.
 */
bool MFRC522::getBlock(byte block, byte keyType, byte *key, byte *returnBlock) {
    byte sendData[8] = {
        block,      // block
        keyType,    // key type
        0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF  // key
    };
    byte returnBlockLength;

    for (int i = 0; i < 6; ++i) {
        sendData[2 + i] = key[i];
    }

    return communicate(
        COMMAND_READBLOCK,  // command
        sendData,           // sendData
        0x0A,               // length
        returnBlock,        // returnData
        &returnBlockLength  // returnDataLength
    );
}

/**
 * Description：Write a block data in the card.
 * Return：Return STATUS_OK if success.
 */
bool MFRC522::writeBlock(byte block, byte keyType, byte *key, byte *data) {
    byte sendData[24] = {
        block,      // block
        keyType,    // key type
        0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,  // key
        0x00, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00  // Data
    };
    byte returnBlock[3];
    byte returnBlockLength;

    for (int i = 0; i < 6; ++i) {
        sendData[2 + i] = key[i];
    }

    for (int i = 0; i < 16; ++i) {
        sendData[8 + i] = data[i];
    }

    byte result = communicate(
        COMMAND_WRITEBLOCK, // command
        sendData,           // sendData
        0x1A,               // length
        returnBlock,        // returnData
        &returnBlockLength  // returnDataLength
    );

    return result;
}

/**
 * Description：Comunication between MFRC522 and ISO14443.
 * Return：Return STATUS_OK if success.
 */
bool MFRC522::communicate(byte command, byte *sendData, byte sendDataLength, byte *returnData, byte *returnDataLength) {
    // Send instruction to MFRC522
    write(MFRC522_HEADER);      // Header
    write(sendDataLength);      // Length (Length + Command + Data)
    write(command);             // Command

    for (int i = 0; i < sendDataLength - 2; i++) {
        write(sendData[i]);     // Data
    }

    // Read response to MFRC522
    while (!available());
    byte header = read();           // Header
    while (!available());
    *returnDataLength = read();     // Length (Length + Command + Data)
    while (!available());
    byte commandResult = read();    // Command result

    for (int i = 0; i < *returnDataLength - 2; i=i) {
        if (available()) {
            returnData[i] = read(); // Data
            i++;
        }
    }

    // Return
    if (command != commandResult) {
        return STATUS_ERROR;
    }

    return STATUS_OK;
}

/*
 * Description：Write a byte data into MFRC522.
 */
void MFRC522::write(byte value) {
}

/*
 * Description：Read a byte data of MFRC522
 * Return：Return the read value.
 */
byte MFRC522::read() {
}
<|endoftext|>


<commit_before>#include <signal.h>
#include <stdlib.h>

#include "../include/screen.h"
#include "../include/hos_api.h"

pid_t	loading_title_pid;

void add_to_load_screen(std::vector<load_t> &text_on_title, unsigned int posX, unsigned int posY, std::string sometext)
{
	load_t	temp_str = {};

	temp_str.posX	= posX;
	temp_str.posY	= posY;
	temp_str.text	= sometext;

	text_on_title.push_back(temp_str);
}

void loading_title_start(std::vector<load_t> *text_on_title)
{
	pid_t loading_pid	= fork();

	if (loading_pid == 0)
	{
		unsigned int	maxX,
						maxY;

		int				state;

		state	= 0;

		init_display();
		init_color();

		if (text_on_title != NULL)
		{
			std::vector <load_t> text_on_title_temp	= *text_on_title;

			for (unsigned int	i = 0; i < text_on_title->size(); mvprintw(text_on_title_temp[i].posY, text_on_title_temp[i].posX, "%s", text_on_title_temp[i].text.c_str()), i++);
		}

		getmaxyx(stdscr, maxY, maxX);

		while (true)
		{
			switch (state)
			{
				case 0:		mvprintw(maxY / 2 - 1, maxX / 2 - 5, "Loading...");
							break;

				case 1:		coloron(TEXT_YELLOW_BLACK);
							mvprintw(maxY / 2 - 2, maxX / 2 - 5, "L      ");
							coloroff(TEXT_YELLOW_BLACK);
							mvprintw(maxY / 2 - 1, maxX / 2 - 5, " oading...");
							break;

				case 2:		coloron(TEXT_BLUE_BLACK);
							mvprintw(maxY / 2 - 2, maxX / 2 - 5, " o");
							coloroff(TEXT_BLUE_BLACK);
							mvprintw(maxY / 2 - 1, maxX / 2 - 5, "L ading...");
							break;

				case 3:		coloron(TEXT_GREEN_BLACK);
							mvprintw(maxY / 2 - 2, maxX / 2 - 5, "  a");
							coloroff(TEXT_GREEN_BLACK);
							mvprintw(maxY / 2 - 1, maxX / 2 - 5, "Lo ding...");
							break;

				case 4:		coloron(TEXT_RED_BLACK);
							mvprintw(maxY / 2 - 2, maxX / 2 - 5, "   d");
							coloroff(TEXT_RED_BLACK);
							mvprintw(maxY / 2 - 1, maxX / 2 - 5, "Loa ing...");
							break;

				case 5:		coloron(TEXT_MAGENTA_BLACK);
							mvprintw(maxY / 2 - 2, maxX / 2 - 5, "    i");
							coloroff(TEXT_MAGENTA_BLACK);
							mvprintw(maxY / 2 - 1, maxX / 2 - 5, "Load ng...");
							break;

				case 6:		coloron(TEXT_CYAN_BLACK);
							mvprintw(maxY / 2 - 2, maxX / 2 - 5, "     n");
							coloroff(TEXT_CYAN_BLACK);
							mvprintw(maxY / 2 - 1, maxX / 2 - 5, "Loadi g...");
							break;

				case 7:		coloron(TEXT_YELLOW_BLACK);
							mvprintw(maxY / 2 - 2, maxX / 2 - 5, "      g");
							coloroff(TEXT_YELLOW_BLACK);
							mvprintw(maxY / 2 - 1, maxX / 2 - 5, "Loadin ...");
							state	= 0;
							break;
			}

			refresh();
			usleep(250000);
			state++;
		}

		endwin();
		exit(0);
	}
	else
	{
		loading_title_pid	= loading_pid;
	}
}

void kill_loading_title()
{
	endwin();
	kill(loading_title_pid, SIGTERM);
	init_display();
	init_color();
}<commit_msg>Фикс зомби-загрузочного экрана<commit_after>#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <wait.h>

#include "../include/screen.h"
#include "../include/hos_api.h"

pid_t	loading_title_pid;

void add_to_load_screen(std::vector<load_t> &text_on_title, unsigned int posX, unsigned int posY, std::string sometext)
{
	load_t	temp_str = {};

	temp_str.posX	= posX;
	temp_str.posY	= posY;
	temp_str.text	= sometext;

	text_on_title.push_back(temp_str);
}

void loading_title_start(std::vector<load_t> *text_on_title)
{
	pid_t loading_pid	= fork();

	if (loading_pid == 0)
	{
		unsigned int	maxX,
						maxY;

		int				state;

		state	= 0;

		init_display();
		init_color();

		if (text_on_title != NULL)
		{
			std::vector <load_t> text_on_title_temp	= *text_on_title;

			for (unsigned int	i = 0; i < text_on_title->size(); mvprintw(text_on_title_temp[i].posY, text_on_title_temp[i].posX, "%s", text_on_title_temp[i].text.c_str()), i++);
		}

		getmaxyx(stdscr, maxY, maxX);

		while (true)
		{
			switch (state)
			{
				case 0:		mvprintw(maxY / 2 - 1, maxX / 2 - 5, "Loading...");
							break;

				case 1:		coloron(TEXT_YELLOW_BLACK);
							mvprintw(maxY / 2 - 2, maxX / 2 - 5, "L      ");
							coloroff(TEXT_YELLOW_BLACK);
							mvprintw(maxY / 2 - 1, maxX / 2 - 5, " oading...");
							break;

				case 2:		coloron(TEXT_BLUE_BLACK);
							mvprintw(maxY / 2 - 2, maxX / 2 - 5, " o");
							coloroff(TEXT_BLUE_BLACK);
							mvprintw(maxY / 2 - 1, maxX / 2 - 5, "L ading...");
							break;

				case 3:		coloron(TEXT_GREEN_BLACK);
							mvprintw(maxY / 2 - 2, maxX / 2 - 5, "  a");
							coloroff(TEXT_GREEN_BLACK);
							mvprintw(maxY / 2 - 1, maxX / 2 - 5, "Lo ding...");
							break;

				case 4:		coloron(TEXT_RED_BLACK);
							mvprintw(maxY / 2 - 2, maxX / 2 - 5, "   d");
							coloroff(TEXT_RED_BLACK);
							mvprintw(maxY / 2 - 1, maxX / 2 - 5, "Loa ing...");
							break;

				case 5:		coloron(TEXT_MAGENTA_BLACK);
							mvprintw(maxY / 2 - 2, maxX / 2 - 5, "    i");
							coloroff(TEXT_MAGENTA_BLACK);
							mvprintw(maxY / 2 - 1, maxX / 2 - 5, "Load ng...");
							break;

				case 6:		coloron(TEXT_CYAN_BLACK);
							mvprintw(maxY / 2 - 2, maxX / 2 - 5, "     n");
							coloroff(TEXT_CYAN_BLACK);
							mvprintw(maxY / 2 - 1, maxX / 2 - 5, "Loadi g...");
							break;

				case 7:		coloron(TEXT_YELLOW_BLACK);
							mvprintw(maxY / 2 - 2, maxX / 2 - 5, "      g");
							coloroff(TEXT_YELLOW_BLACK);
							mvprintw(maxY / 2 - 1, maxX / 2 - 5, "Loadin ...");
							state	= 0;
							break;
			}

			refresh();
			usleep(250000);
			state++;
		}

		endwin();
		exit(0);
	}
	else
	{
		loading_title_pid	= loading_pid;
	}
}

void kill_loading_title()
{
	endwin();
	kill(loading_title_pid, SIGTERM);
	waitpid(loading_title_pid, NULL, WUNTRACED);
	init_display();
	init_color();
}<|endoftext|>