text:
using namespace realm;

namespace {
template<typename Derived>
struct MarkDirtyMixin  {
    bool mark_dirty(size_t row, size_t col, _impl::Instruction instr=_impl::instr_Set)
    {
        // Ignore SetDefault and SetUnique as those conceptually cannot be
        // changes to existing rows
        if (instr == _impl::instr_Set)
            static_cast<Derived *>(this)->mark_dirty(row, col);
        return true;
    }

    bool set_int(size_t c, size_t r, int_fast64_t, _impl::Instruction i, size_t) { return mark_dirty(r, c, i); }
    bool set_bool(size_t c, size_t r, bool, _impl::Instruction i) { return mark_dirty(r, c, i); }
    bool set_float(size_t c, size_t r, float, _impl::Instruction i) { return mark_dirty(r, c, i); }
    bool set_double(size_t c, size_t r, double, _impl::Instruction i) { return mark_dirty(r, c, i); }
    bool set_string(size_t c, size_t r, StringData, _impl::Instruction i, size_t) { return mark_dirty(r, c, i); }
    bool set_binary(size_t c, size_t r, BinaryData, _impl::Instruction i) { return mark_dirty(r, c, i); }
    bool set_olddatetime(size_t c, size_t r, OldDateTime, _impl::Instruction i) { return mark_dirty(r, c, i); }
    bool set_timestamp(size_t c, size_t r, Timestamp, _impl::Instruction i) { return mark_dirty(r, c, i); }
    bool set_table(size_t c, size_t r, _impl::Instruction i) { return mark_dirty(r, c, i); }
    bool set_mixed(size_t c, size_t r, const Mixed&, _impl::Instruction i) { return mark_dirty(r, c, i); }
    bool set_link(size_t c, size_t r, size_t, size_t, _impl::Instruction i) { return mark_dirty(r, c, i); }
    bool set_null(size_t c, size_t r, _impl::Instruction i, size_t) { return mark_dirty(r, c, i); }

    bool add_int(size_t col, size_t row, int_fast64_t) { return mark_dirty(row, col); }
    bool nullify_link(size_t col, size_t row, size_t) { return mark_dirty(row, col); }
    bool insert_substring(size_t col, size_t row, size_t, StringData) { return mark_dirty(row, col); }
    bool erase_substring(size_t col, size_t row, size_t, size_t) { return mark_dirty(row, col); }

    bool set_int_unique(size_t, size_t, size_t, int_fast64_t) { return true; }
    bool set_string_unique(size_t, size_t, size_t, StringData) { return true; }
};

class TransactLogValidationMixin {
    // Index of currently selected table
    size_t m_current_table = 0;

    // Tables which were created during the transaction being processed, which
    // can have columns inserted without a schema version bump
    std::vector<size_t> m_new_tables;

    REALM_NORETURN
    REALM_NOINLINE
    void schema_error()
    {
        throw std::logic_error("Schema mismatch detected: another process has modified the Realm file's schema in an incompatible way");
    }

    // Throw an exception if the currently modified table already existed before
    // the current set of modifications
    bool schema_error_unless_new_table()
    {
        if (schema_mode == SchemaMode::Additive) {
            return true;
        }
        if (std::find(begin(m_new_tables), end(m_new_tables), m_current_table) != end(m_new_tables)) {
            return true;
        }
        schema_error();
    }

protected:
    size_t current_table() const noexcept { return m_current_table; }

public:
    SchemaMode schema_mode;

    // Schema changes which don't involve a change in the schema version are
    // allowed
    bool add_search_index(size_t) { return true; }
    bool remove_search_index(size_t) { return true; }

    // Creating entirely new tables without a schema version bump is allowed, so
    // we need to track if new columns are being added to a new table or an
    // existing one
    bool insert_group_level_table(size_t table_ndx, size_t, StringData)
    {
        // Shift any previously added tables after the new one
        for (auto& table : m_new_tables) {
            if (table >= table_ndx)
                ++table;
        }
        m_new_tables.push_back(table_ndx);
        m_current_table = table_ndx;
        return true;
    }
    bool insert_column(size_t, DataType, StringData, bool) { return schema_error_unless_new_table(); }
    bool insert_link_column(size_t, DataType, StringData, size_t, size_t) { return schema_error_unless_new_table(); }
    bool set_link_type(size_t, LinkType) { return schema_error_unless_new_table(); }
    bool move_column(size_t, size_t) { return schema_error_unless_new_table(); }
    bool move_group_level_table(size_t, size_t) { return schema_error_unless_new_table(); }

    // Removing or renaming things while a Realm is open is never supported
    bool erase_group_level_table(size_t, size_t) { schema_error(); }
    bool rename_group_level_table(size_t, StringData) { schema_error(); }
    bool erase_column(size_t) { schema_error(); }
    bool erase_link_column(size_t, size_t, size_t) { schema_error(); }
    bool rename_column(size_t, StringData) { schema_error(); }

    bool select_descriptor(int levels, const size_t*)
    {
        // subtables not supported
        return levels == 0;
    }

    bool select_table(size_t group_level_ndx, int, const size_t*) noexcept
    {
        m_current_table = group_level_ndx;
        return true;
    }

    bool select_link_list(size_t, size_t, size_t) { return true; }

    // Non-schema changes are all allowed
    void parse_complete() { }
    bool insert_empty_rows(size_t, size_t, size_t, bool) { return true; }
    bool erase_rows(size_t, size_t, size_t, bool) { return true; }
    bool swap_rows(size_t, size_t) { return true; }
    bool clear_table() noexcept { return true; }
    bool link_list_set(size_t, size_t, size_t) { return true; }
    bool link_list_insert(size_t, size_t, size_t) { return true; }
    bool link_list_erase(size_t, size_t) { return true; }
    bool link_list_nullify(size_t, size_t) { return true; }
    bool link_list_clear(size_t) { return true; }
    bool link_list_move(size_t, size_t) { return true; }
    bool link_list_swap(size_t, size_t) { return true; }
    bool merge_rows(size_t, size_t) { return true; }
    bool optimize_table() { return true; }

};

// A transaction log handler that just validates that all operations made are
// ones supported by the object store
struct TransactLogValidator : public TransactLogValidationMixin, public MarkDirtyMixin<TransactLogValidator> {
    TransactLogValidator(SchemaMode schema_mode) { this->schema_mode = schema_mode; }
    void mark_dirty(size_t, size_t) { }
};

// Move the value at container[from] to container[to], shifting everything in
// between, or do nothing if either are out of bounds
template<typename Container>
void rotate(Container& container, size_t from, size_t to)
{
    REALM_ASSERT(from != to);
    if (from >= container.size() && to >= container.size())
        return;
    if (from >= container.size() || to >= container.size())
        container.resize(std::max(from, to) + 1);
    if (from < to)
        std::rotate(begin(container) + from, begin(container) + to, begin(container) + to + 1);
    else
        std::rotate(begin(container) + to, begin(container) + from, begin(container) + from + 1);
}

// Insert a default-initialized value at pos if there is anything after pos in the container.
template<typename Container>
void insert_empty_at(Container& container, size_t pos)
{
    if (pos < container.size())
        container.insert(container.begin() + pos, typename Container::value_type{});
}

// Shift `value` to reflect a move from `from` to `to`
void adjust_for_move(size_t& value, size_t from, size_t to)
{
    if (value == from)
        value = to;
    else if (value > from && value < to)
        --value;
    else if (value < from && value >= to)
        ++value;
}

// Extends TransactLogValidator to also track changes and report it to the
// binding context if any properties are being observed
class TransactLogObserver : public TransactLogValidationMixin, public MarkDirtyMixin<TransactLogObserver> {
    using ColumnInfo = BindingContext::ColumnInfo;
    using ObserverState = BindingContext::ObserverState;

    // Observed table rows which need change information
    std::vector<ObserverState> m_observers;
    // Userdata pointers for rows which have been deleted
    std::vector<void *> invalidated;
    // Delegate to send change information to
    BindingContext* m_context;

    // Change information for the currently selected LinkList, if any
    ColumnInfo* m_active_linklist = nullptr;

    // Get the change info for the given column, creating it if needed
    static ColumnInfo& get_change(ObserverState& state, size_t i)
    {
        expand_to(state, i);
        return state.changes[i];
    }

    static void expand_to(ObserverState& state, size_t i)
    {
        auto old_size = state.changes.size();
        if (old_size <= i) {
            auto new_size = std::max(state.changes.size() * 2, i + 1);
            state.changes.resize(new_size);
            size_t base = old_size == 0 ? 0 : state.changes[old_size - 1].initial_column_index + 1;
            for (size_t i = old_size; i < new_size; ++i)
                state.changes[i].initial_column_index = i - old_size + base;
        }
    }

    // Remove the given observer from the list of observed objects and add it
    // to the listed of invalidated objects
    void invalidate(ObserverState *o)
    {
        invalidated.push_back(o->info);
        m_observers.erase(m_observers.begin() + (o - &m_observers[0]));
    }

public:
    template<typename Func>
    TransactLogObserver(BindingContext* context, SharedGroup& sg, Func&& func, util::Optional<SchemaMode> schema_mode)
    : m_context(context)
    {
        auto old_version = sg.get_version_of_current_transaction();
        if (context) {
            m_observers = context->get_observed_rows();
        }
        if (m_observers.empty()) {
            if (schema_mode) {
                func(TransactLogValidator(*schema_mode));
            }
            else {
                func();
            }
            if (context && old_version != sg.get_version_of_current_transaction()) {
                context->did_change({}, {});
            }
            return;
        }

        std::sort(begin(m_observers), end(m_observers));
        func(*this);
        context->did_change(m_observers, invalidated);
    }

    // Mark the given row/col as needing notifications sent
    void mark_dirty(size_t row_ndx, size_t col_ndx)
    {
        auto it = lower_bound(begin(m_observers), end(m_observers), ObserverState{current_table(), row_ndx, nullptr});
        if (it != end(m_observers) && it->table_ndx == current_table() && it->row_ndx == row_ndx) {
            get_change(*it, col_ndx).kind = ColumnInfo::Kind::Set;
        }
    }

    // Called at the end of the transaction log immediately before the version
    // is advanced
    void parse_complete()
    {
        m_context->will_change(m_observers, invalidated);
    }

    bool insert_group_level_table(size_t table_ndx, size_t prior_size, StringData name)
    {
        for (auto& observer : m_observers) {
            if (observer.table_ndx >= table_ndx)
                ++observer.table_ndx;
        }
        TransactLogValidationMixin::insert_group_level_table(table_ndx, prior_size, name);
        return true;
    }

    bool insert_empty_rows(size_t row_ndx, size_t num_rows, size_t prior_size, bool)
    {
        if (row_ndx != prior_size) {
            for (auto& observer : m_observers) {
                if (observer.table_ndx == current_table() && observer.row_ndx >= row_ndx)
                    observer.row_ndx += num_rows;
            }
        }
        return true;
    }

    bool erase_rows(size_t row_ndx, size_t rows_to_erase, size_t prior_size, bool unordered)
    {
        REALM_ASSERT(unordered || rows_to_erase == 1);
        size_t last_row_ndx = prior_size - 1;

        if (unordered) {
            auto end = m_observers.end();
            auto row_it = lower_bound(begin(m_observers), end, ObserverState{current_table(), row_ndx, nullptr});
            auto last_it = lower_bound(row_it, end, ObserverState{current_table(), last_row_ndx, nullptr});
            bool have_row = row_it != end && row_it->table_ndx == current_table() && row_it->row_ndx == row_ndx;
            bool have_last = last_it != end && last_it->table_ndx == current_table() && last_it->row_ndx == last_row_ndx;
            if (have_row && have_last) {
                invalidated.push_back(row_it->info);
                row_it->info = last_it->info;
                row_it->changes = std::move(last_it->changes);
                m_observers.erase(last_it);
            }
            else if (have_row) {
                invalidated.push_back(row_it->info);
                m_observers.erase(row_it);
            }
            else if (have_last) {
                last_it->row_ndx = row_ndx;
                std::rotate(row_it, last_it, end);
            }
        }
        else {
            for (size_t i = 0; i < m_observers.size(); ++i) {
                auto& o = m_observers[i];
                if (o.table_ndx == current_table()) {
                    if (o.row_ndx == row_ndx) {
                        invalidate(&o);
                        --i;
                    }
                    else if (o.row_ndx > row_ndx) {
                        o.row_ndx -= rows_to_erase;
                    }
                }
            }
        }
        return true;
    }

    bool swap_rows(size_t row_ndx_1, size_t row_ndx_2)
    {
        REALM_ASSERT(row_ndx_1 < row_ndx_2); // this is enforced by core

        auto end = m_observers.end();
        auto it_1 = lower_bound(begin(m_observers), end, ObserverState{current_table(), row_ndx_1, nullptr});
        auto it_2 = lower_bound(it_1, end, ObserverState{current_table(), row_ndx_2, nullptr});
        bool have_row_1 = it_1 != end && it_1->table_ndx == current_table() && it_1->row_ndx == row_ndx_1;
        bool have_row_2 = it_2 != end && it_2->table_ndx == current_table() && it_2->row_ndx == row_ndx_2;

        if (have_row_1 && have_row_2) {
            std::swap(it_1->info, it_2->info);
            std::swap(it_1->changes, it_2->changes);
        }
        else if (have_row_1) {
            it_1->row_ndx = row_ndx_2;
            std::rotate(it_1, it_1 + 1, it_2);
        }
        else if (have_row_2) {
            it_2->row_ndx = row_ndx_1;
            std::rotate(it_1, it_2, end);
        }

        return true;
    }

    bool merge_rows(size_t from, size_t to)
    {
        REALM_ASSERT(from != to);

        auto end = m_observers.end();
        auto from_it = lower_bound(begin(m_observers), end, ObserverState{current_table(), from, nullptr});
        if (from_it == end || from_it->table_ndx != current_table() || from_it->row_ndx != from)
            return true;

        auto to_it = lower_bound(begin(m_observers), end, ObserverState{current_table(), to, nullptr});
        // an observer for the subsuming row should not already exist
        REALM_ASSERT_DEBUG(to_it == end || (ObserverState{current_table(), to, nullptr}) < *to_it);

        from_it->row_ndx = to;
        if (from < to)
            std::rotate(from_it, from_it + 1, to_it);
        else
            std::rotate(to_it, from_it, from_it + 1);
        return true;
    }

    bool clear_table()
    {
        for (size_t i = 0; i < m_observers.size(); ) {
            auto& o = m_observers[i];
            if (o.table_ndx == current_table()) {
                invalidate(&o);
            }
            else {
                ++i;
            }
        }
        return true;
    }

    bool select_link_list(size_t col, size_t row, size_t)
    {
        m_active_linklist = nullptr;
        for (auto& o : m_observers) {
            if (o.table_ndx == current_table() && o.row_ndx == row) {
                m_active_linklist = &get_change(o, col);
                break;
            }
        }
        return true;
    }

    void append_link_list_change(ColumnInfo::Kind kind, size_t index) {
        ColumnInfo *o = m_active_linklist;
        if (!o || o->kind == ColumnInfo::Kind::SetAll) {
            // Active LinkList isn't observed or already has multiple kinds of changes
            return;
        }

        if (o->kind == ColumnInfo::Kind::None) {
            o->kind = kind;
            o->indices.add(index);
        }
        else if (o->kind == kind) {
            if (kind == ColumnInfo::Kind::Remove) {
                o->indices.add_shifted(index);
            }
            else if (kind == ColumnInfo::Kind::Insert) {
                o->indices.insert_at(index);
            }
            else {
                o->indices.add(index);
            }
        }
        else {
            // Array KVO can only send a single kind of change at a time, so
            // if there are multiple just give up and send "Set"
            o->indices.set(0);
            o->kind = ColumnInfo::Kind::SetAll;
        }
    }

    bool link_list_set(size_t index, size_t, size_t)
    {
        append_link_list_change(ColumnInfo::Kind::Set, index);
        return true;
    }

    bool link_list_insert(size_t index, size_t, size_t)
    {
        append_link_list_change(ColumnInfo::Kind::Insert, index);
        return true;
    }

    bool link_list_erase(size_t index, size_t)
    {
        append_link_list_change(ColumnInfo::Kind::Remove, index);
        return true;
    }

    bool link_list_nullify(size_t index, size_t)
    {
        append_link_list_change(ColumnInfo::Kind::Remove, index);
        return true;
    }

    bool link_list_swap(size_t index1, size_t index2)
    {
        append_link_list_change(ColumnInfo::Kind::Set, index1);
        append_link_list_change(ColumnInfo::Kind::Set, index2);
        return true;
    }

    bool link_list_clear(size_t old_size)
    {
        ColumnInfo *o = m_active_linklist;
        if (!o || o->kind == ColumnInfo::Kind::SetAll) {
            return true;
        }

        if (o->kind == ColumnInfo::Kind::Remove)
            old_size += o->indices.count();
        else if (o->kind == ColumnInfo::Kind::Insert)
            old_size -= o->indices.count();

        o->indices.set(old_size);

        o->kind = ColumnInfo::Kind::Remove;
        return true;
    }

    bool link_list_move(size_t from, size_t to)
    {
        ColumnInfo *o = m_active_linklist;
        if (!o || o->kind == ColumnInfo::Kind::SetAll) {
            return true;
        }
        if (from > to) {
            std::swap(from, to);
        }

        if (o->kind == ColumnInfo::Kind::None) {
            o->kind = ColumnInfo::Kind::Set;
        }
        if (o->kind == ColumnInfo::Kind::Set) {
            for (size_t i = from; i <= to; ++i)
                o->indices.add(i);
        }
        else {
            o->indices.set(0);
            o->kind = ColumnInfo::Kind::SetAll;
        }
        return true;
    }

    bool insert_column(size_t ndx, DataType, StringData, bool)
    {
        for (auto& observer : m_observers) {
            if (observer.table_ndx == current_table()) {
                expand_to(observer, ndx);
                insert_empty_at(observer.changes, ndx);
            }
        }
        return true;
    }

    bool move_column(size_t from, size_t to)
    {
        for (auto& observer : m_observers) {
            if (observer.table_ndx == current_table()) {
                // have to initialize the columns one past the moved one so that
                // we can later initialize any more columns after that
                expand_to(observer, std::max(from, to) + 1);
                rotate(observer.changes, from, to);
            }
        }
        return true;
    }

    bool move_group_level_table(size_t from, size_t to)
    {
        for (auto& observer : m_observers)
            adjust_for_move(observer.table_ndx, from, to);
        return true;
    }

    bool insert_link_column(size_t ndx, DataType type, StringData name, size_t, size_t) { return insert_column(ndx, type, name, false); }

};

// Extends TransactLogValidator to track changes made to LinkViews
class LinkViewObserver : public TransactLogValidationMixin, public MarkDirtyMixin<LinkViewObserver> {
    _impl::TransactionChangeInfo& m_info;
    _impl::CollectionChangeBuilder* m_active = nullptr;

    _impl::CollectionChangeBuilder* get_change()
    {
        auto tbl_ndx = current_table();
        if (!m_info.track_all && (tbl_ndx >= m_info.table_modifications_needed.size() || !m_info.table_modifications_needed[tbl_ndx]))
            return nullptr;
        if (m_info.tables.size() <= tbl_ndx) {
            m_info.tables.resize(std::max(m_info.tables.size() * 2, tbl_ndx + 1));
        }
        return &m_info.tables[tbl_ndx];
    }

    bool need_move_info() const
    {
        auto tbl_ndx = current_table();
        return m_info.track_all || (tbl_ndx < m_info.table_moves_needed.size() && m_info.table_moves_needed[tbl_ndx]);
    }

public:
    LinkViewObserver(_impl::TransactionChangeInfo& info)
    : m_info(info) { }

    void mark_dirty(size_t row, size_t)
    {
        if (auto change = get_change())
            change->modify(row);
    }

    void parse_complete()
    {
        for (auto& table : m_info.tables) {
            table.parse_complete();
        }
        for (auto& list : m_info.lists) {
            list.changes->clean_up_stale_moves();
        }
    }

    bool select_link_list(size_t col, size_t row, size_t)
    {
        mark_dirty(row, col);

        m_active = nullptr;
        // When there are multiple source versions there could be multiple
        // change objects for a single LinkView, in which case we need to use
        // the last one
        for (auto it = m_info.lists.rbegin(), end = m_info.lists.rend(); it != end; ++it) {
            if (it->table_ndx == current_table() && it->row_ndx == row && it->col_ndx == col) {
                m_active = it->changes;
                break;
            }
        }
        return true;
    }

    bool link_list_set(size_t index, size_t, size_t)
    {
        if (m_active)
            m_active->modify(index);
        return true;
    }

    bool link_list_insert(size_t index, size_t, size_t)
    {
        if (m_active)
            m_active->insert(index);
        return true;
    }

    bool link_list_erase(size_t index, size_t)
    {
        if (m_active)
            m_active->erase(index);
        return true;
    }

    bool link_list_nullify(size_t index, size_t prior_size)
    {
        return link_list_erase(index, prior_size);
    }

    bool link_list_swap(size_t index1, size_t index2)
    {
        link_list_set(index1, 0, npos);
        link_list_set(index2, 0, npos);
        return true;
    }

    bool link_list_clear(size_t old_size)
    {
        if (m_active)
            m_active->clear(old_size);
        return true;
    }

    bool link_list_move(size_t from, size_t to)
    {
        if (m_active)
            m_active->move(from, to);
        return true;
    }

    bool insert_empty_rows(size_t row_ndx, size_t num_rows_to_insert, size_t, bool unordered)
    {
        REALM_ASSERT(!unordered);
        if (auto change = get_change())
            change->insert(row_ndx, num_rows_to_insert, need_move_info());
        for (auto& list : m_info.lists) {
            if (list.table_ndx == current_table() && list.row_ndx >= row_ndx)
                list.row_ndx += num_rows_to_insert;
        }

        return true;
    }

    bool erase_rows(size_t row_ndx, size_t, size_t prior_num_rows, bool unordered)
    {
        REALM_ASSERT(unordered);
        size_t last_row = prior_num_rows - 1;

        for (auto it = begin(m_info.lists); it != end(m_info.lists); ) {
            if (it->table_ndx == current_table()) {
                if (it->row_ndx == row_ndx) {
                    *it = std::move(m_info.lists.back());
                    m_info.lists.pop_back();
                    continue;
                }
                if (it->row_ndx == last_row)
                    it->row_ndx = row_ndx;
            }
            ++it;
        }

        if (auto change = get_change())
            change->move_over(row_ndx, last_row, need_move_info());
        return true;
    }

    bool swap_rows(size_t row_ndx_1, size_t row_ndx_2) {
        REALM_ASSERT(row_ndx_1 < row_ndx_2);
        for (auto& list : m_info.lists) {
            if (list.table_ndx == current_table()) {
                if (list.row_ndx == row_ndx_1)
                    list.row_ndx = row_ndx_2;
                else if (list.row_ndx == row_ndx_2)
                    list.row_ndx = row_ndx_1;
            }
        }
        if (auto change = get_change())
            change->swap(row_ndx_1, row_ndx_2, need_move_info());
        return true;
    }

    bool merge_rows(size_t from, size_t to)
    {
        for (auto& list : m_info.lists) {
            if (list.table_ndx == current_table() && list.row_ndx == from)
                list.row_ndx = to;
        }
        if (auto change = get_change())
            change->subsume(from, to, need_move_info());
        return true;
    }

    bool clear_table()
    {
        auto tbl_ndx = current_table();
        auto it = remove_if(begin(m_info.lists), end(m_info.lists),
                            [&](auto const& lv) { return lv.table_ndx == tbl_ndx; });
        m_info.lists.erase(it, end(m_info.lists));
        if (auto change = get_change())
            change->clear(std::numeric_limits<size_t>::max());
        return true;
    }

    bool insert_column(size_t ndx, DataType, StringData, bool)
    {
        for (auto& list : m_info.lists) {
            if (list.table_ndx == current_table() && list.col_ndx >= ndx)
                ++list.col_ndx;
        }
        return true;
    }

    bool insert_group_level_table(size_t ndx, size_t, StringData)
    {
        for (auto& list : m_info.lists) {
            if (list.table_ndx >= ndx)
                ++list.table_ndx;
        }
        insert_empty_at(m_info.tables, ndx);
        insert_empty_at(m_info.table_moves_needed, ndx);
        insert_empty_at(m_info.table_modifications_needed, ndx);
        return true;
    }

    bool move_column(size_t from, size_t to)
    {
        for (auto& list : m_info.lists) {
            if (list.table_ndx == current_table())
                adjust_for_move(list.col_ndx, from, to);
        }
        return true;
    }

    bool move_group_level_table(size_t from, size_t to)
    {
        for (auto& list : m_info.lists)
            adjust_for_move(list.table_ndx, from, to);
        rotate(m_info.tables, from, to);
        rotate(m_info.table_modifications_needed, from, to);
        rotate(m_info.table_moves_needed, from, to);
        return true;
    }

    bool insert_link_column(size_t ndx, DataType type, StringData name, size_t, size_t) { return insert_column(ndx, type, name, false); }

};
} // anonymous namespace

namespace realm {
namespace _impl {
namespace transaction {
void advance(SharedGroup& sg, BindingContext* context, SchemaMode schema_mode, VersionID version)
{
    TransactLogObserver(context, sg, [&](auto&&... args) {
        LangBindHelper::advance_read(sg, std::move(args)..., version);
    }, schema_mode);
}

void begin_without_validation(SharedGroup& sg)
{
    LangBindHelper::promote_to_write(sg);
}

void begin(SharedGroup& sg, BindingContext* context, SchemaMode schema_mode)
{
    TransactLogObserver(context, sg, [&](auto&&... args) {
        LangBindHelper::promote_to_write(sg, std::move(args)...);
    }, schema_mode);
}

void commit(SharedGroup& sg, BindingContext* context)
{
    LangBindHelper::commit_and_continue_as_read(sg);

    if (context) {
        context->did_change({}, {});
    }
}

void cancel(SharedGroup& sg, BindingContext* context)
{
    TransactLogObserver(context, sg, [&](auto&&... args) {
        LangBindHelper::rollback_and_continue_as_read(sg, std::move(args)...);
    }, util::none);
}

void advance(SharedGroup& sg,
             TransactionChangeInfo& info,
             VersionID version)
{
    if (!info.track_all && info.table_modifications_needed.empty() && info.lists.empty()) {
        LangBindHelper::advance_read(sg, version);
    }
    else {
        LangBindHelper::advance_read(sg, LinkViewObserver(info), version);
    }

}

} // namespace transaction
} // namespace _impl
} // namespace realm


text:
package gin

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

func init() {
	SetMode(TestMode)
}

func TestSetMode(t *testing.T) {
	SetMode(DebugMode)
	assert.Equal(t, ginMode, debugCode)
	assert.Equal(t, Mode(), DebugMode)

	SetMode(ReleaseMode)
	assert.Equal(t, ginMode, releaseCode)
	assert.Equal(t, Mode(), ReleaseMode)

	SetMode(TestMode)
	assert.Equal(t, ginMode, testCode)
	assert.Equal(t, Mode(), TestMode)

	assert.Panics(t, func() { SetMode("unknown") })
}

redpajama_set_name: RedPajamaGithub


text:
function [ message ] = get_raw_measurement(db_id, coll_id, data_id)
% GET_RAW_MEASUREMENT Get a raw measurment for the evaluation fo RF-based
% indoor loclaization algorithms.
% Check the documentation: https://github.com/flemic/R2DM-EVARILOS

% author = "Filip Lemic"
% copyright = "Copyright 2015, EVARILOS Project"

% version = "1.0.0"
% maintainer = "Filip Lemic"
% email = "lemic@tkn.tu-berlin.de"
% status = "Development"

    apiURL = 'http://ebp.evarilos.eu:5000/';

    req = urlread([apiURL 'evarilos/raw_data/v1.0/database/' db_id '/collection/' coll_id '/message/' data_id]);
    message = strrep(req, '_id', 'id');
    message = strrep(message, 'dataid', 'data_id');
    message = strrep(message, 'erid', 'er_id');
    message = JSON.parse(message);

end


text:
Tool to manage debian repositories.

## This project is really new and not completely tested. Use it at your own risk.

## The idea

The idea was to create a small, leightweight and easy to use debian repository management tool that provides a staging area for jenkins package builds using fpm-cookery, basic gpg support and some custom features.

Every destructive action can be reverted.

It's roughly not finished yet!

### Package lifecycle

As mentioned before, RepoMate has a staging area. Every package you are trying to add through the commandline interface will be copied to the staging area. This action will not affect your production pool.
You have to publish a package or a set of packages to bring them into production. When you do, the selected packages will be moved from "stage" to "pool" (This is like an archive) and linked from the "pool" to "dists".
Note that "dists"" normally contains just all the metafiles like Packages or Packages.gz.
We like to have all what apt needs in just one directory.

newpackage -> (add) -> stage -> (publish) -> production

## Features

### Checkpoints

Checkpoints may help if you accidently published a bunch of packages to the wrong suite (lenny, squeeze,…) or component (main, contrib, non-free,…).

If you did:

    repomate load

Choose the last checkpoint and be happy again.

Note that checkpoints will be auto-saved before each publish sequence.

## Installation

### Repository server

dpkg is used to compare package versions. I tried to do it on my own, but debian uses very annoying version strings with a couple of variants.

Please make sure you have the following packages installed:

* ruby
* dpkg
* libsqlite3-dev

#### Get RepoMate

    gem install repomate

#### Configure RepoMate

Create your own config file.

    vi ~/.repomate

Default config:

    ---
    :rootdir: /var/lib/repomate/repository
    :dpkg: /usr/bin/dpkg
    :suites:
        - lenny
        - squeeze
    :components:
        - main
        - contrib
    :architectures:
        - all
        - amd64
    :origin: Repository
    :label: Repository
    :gpg: false
    :gpg_email: someone@example.net
    :gpg_password: secret

I recommend you to enable GPG support. I'm sure you will find a lot of tutorials which describe the process of creating a GPG keypair.

#### Configure webserver

Configure your favorite webserver by adding RepoMate's rootdirectory to a site or vhost.

Pretty basic apache2 example:

    <VirtualHost *:80>
        ServerAdmin webmaster@example.net
        ServerName  repository.example.net
        DocumentRoot /var/lib/repomate

        <Directory /var/lib/repomate/>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride None
            Order allow,deny
            allow from all
        </Directory>

        ErrorLog  /var/log/apache2/error.log
        CustomLog /var/log/apache2/access.log combined
    </VirtualHost>

#### Adding packages

    repomate add -s squeeze package.deb
    repomate publish

### Client

Add something like this to your machines /etc/apt/sources.list:

    deb [arch=all,amd64] http://server/repository squeeze main

### Examples

Setup base directory structure (optional):

    repomate setup -s squeeze [ -c main ]

Add a package to the staging area:

    repomate add -s squeeze <path_to_packagefile>

Publish all packages from the staging area. That means they will be linked to production:

    repomate publish

Load a checkpoint:

    repomate load

Save a checkpoint:

    repomate save

List all packages in pool:

    repomate listpackages -r pool

List all packages in stage:

    repomate listpackages -r stage

Choose a package to you want to activate (The package will be linked from the pool to the dists directory):

    repomate activate

Choose a package to you want to deactivate (The package will be unlinked from the dists directory but still kept in the pool):

    repomate deactivate

Remove/Purge a package:

    repomate remove


text:
<!DOCTYPE html>

	<meta charset="utf-8">

	<title>AWSDynamoDBAttributeDefinition Class Reference</title>

	<link rel="stylesheet" href="../css/style.css">
	<meta name="viewport" content="initial-scale=1, maximum-scale=1.4">
	<meta name="generator" content="appledoc 2.2.1 (build 1333)">

				AWS Mobile SDK for iOS v2.4.1

				Amazon Web Services, Inc.

Index

Hierarchy

							On This Page

							<select id="jump-to">
	<option value="top">Jump To…</option>

	<option value="overview">Overview</option>

	<option value="tasks">Tasks</option>

	<optgroup label="Properties">

		<option value="//api/name/attributeName">attributeName</option>

		<option value="//api/name/attributeType">attributeType</option>

	</optgroup>

</select>

AWSDynamoDBAttributeDefinition Class Reference

	Inherits from
	AWSModel : AWSMTLModel

	Declared in
	AWSDynamoDBModel.h
AWSDynamoDBModel.m

Overview

Represents an attribute for describing the key schema for the table and indexes.

Required parameters: [AttributeName, AttributeType]

  attributeName

A name for the attribute.

@property (nonatomic, strong) NSString *attributeName

Declared In

AWSDynamoDBModel.h

  attributeType

The data type for the attribute.

@property (nonatomic, assign) AWSDynamoDBScalarAttributeType attributeType

Declared In

AWSDynamoDBModel.h

Copyright © 2016 Amazon Web Services, Inc. All rights reserved. Updated: 2016-04-28

Generated by appledoc 2.2.1 (build 1333).


text:
<?xml version="1.0" encoding="UTF-8"?>
<metadata>
  <groupId>com.metservice</groupId>
  <artifactId>kanban-app</artifactId>
  <versioning>
    <versions>
      <version>0.46-SNAPSHOT</version>
    </versions>
    <lastUpdated>20140919182408</lastUpdated>
  </versioning>
</metadata>


text:
package com.restfb.types.oembed;

import com.restfb.Facebook;
import com.restfb.types.AbstractFacebookType;

import lombok.Getter;
import lombok.Setter;

public abstract class BaseOEmbed extends AbstractFacebookType {

  /**
   * The HTML used to display the page.
   */
  @Getter
  @Setter
  @Facebook
  private String html;

  /**
   * The height in pixels required to display the HTML.
   */
  @Getter
  @Setter
  @Facebook
  private Long height;

  /**
   * The width in pixels required to display the HTML.
   */
  @Getter
  @Setter
  @Facebook
  private Long width;

  /**
   * Name of the provider (Facebook)
   */
  @Getter
  @Setter
  @Facebook("provider_name")
  private String providerName;

  /**
   * URL of the provider (Facebook)
   */
  @Getter
  @Setter
  @Facebook("provider_url")
  private String providerUrl;

  /**
   * The oEmbed resource type. See https://oembed.com/.
   */
  @Getter
  @Setter
  @Facebook
  private String type;

  /**
   * Always 1.0. See https://oembed.com/
   */
  @Getter
  @Setter
  @Facebook
  private String version;

}


text:
describe Tychus::ParserSelector do
  subject(:parser_selector) { Tychus::ParserSelector }

  context "allrecipes.com uris" do
    before {
      VCR.use_cassette(cassette) do
        @m = Tychus::MetaParser.new(uri).parse
      end
    }
    let(:uri) { "http://allrecipes.com/Recipe/Chicken-Pot-Pie-IX/Detail.aspx?soid=recs_recipe_2" }
    let(:cassette) { "parser_selector_allrecipes_1" }

    specify "resolve to the AllrecipesParser" do
      expect(subject.resolve_parser(@m)).to eq(Tychus::Parsers::AllrecipesParser)
    end

  end

  context "when specific parser doesn't exist but uri uses schema org's microformat" do
    before do
      VCR.use_cassette(cassette) do
        @m = Tychus::MetaParser.new(uri).parse
      end
    end

    context "for 'cookingquinoa.net'" do

      let(:uri) { "http://www.cookingquinoa.net/quinoa-bacon-club-wrap/" }
      let(:cassette) { "cooking_quinoa" }

      it "resolves to the Schema Org Parser" do
        expect(subject.resolve_parser(@m)).to eq(Tychus::Parsers::SchemaOrgParser)
      end
    end

    context "for 'asideofsweet.com'" do

      let(:uri) { "http://asideofsweet.com/black-cherry-buttermilk-ice-cream/" }
      let(:cassette) { "a_side_of_sweet" }

      it "resolves to the Schema Org Parser" do
        expect(subject.resolve_parser(@m)).to eq(Tychus::Parsers::SchemaOrgParser)
      end
    end

  end

end


text:
<resources>

    <style name="BaseTheme" parent="Theme.AppCompat.NoActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:windowBackground">@color/colorPrimary</item>
        <item name="android:statusBarColor">@color/mdBlack</item>
    </style>

    <style name="AppTheme" parent="BaseTheme" />

    <style name="Toolbar" parent="ThemeOverlay.AppCompat.ActionBar">
        <item name="android:textColorPrimary">@color/toolbar_items</item>
        <item name="android:colorBackground">@color/mdWhite</item>
    </style>

</resources>


text:
package org.apache.pulsar.broker.admin;

import static org.testng.Assert.assertEquals;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import lombok.Cleanup;
import org.apache.pulsar.broker.BrokerTestUtil;
import org.apache.pulsar.broker.admin.AdminApiTest.MockedPulsarService;
import org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest;
import org.apache.pulsar.client.api.Consumer;
import org.apache.pulsar.client.api.MessageId;
import org.apache.pulsar.client.api.Producer;
import org.apache.pulsar.client.api.Reader;
import org.apache.pulsar.client.api.Schema;
import org.apache.pulsar.common.naming.TopicName;
import org.apache.pulsar.common.policies.data.ClusterData;
import org.apache.pulsar.common.policies.data.TenantInfoImpl;
import org.awaitility.Awaitility;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

@Test(groups = "broker-admin")
public class IncrementPartitionsTest extends MockedPulsarServiceBaseTest {

    private MockedPulsarService mockPulsarSetup;

    @BeforeMethod
    @Override
    public void setup() throws Exception {
        conf.setLoadBalancerEnabled(true);
        super.internalSetup();

        // create otherbroker to test redirect on calls that need
        // namespace ownership
        mockPulsarSetup = new MockedPulsarService(this.conf);
        mockPulsarSetup.setup();

        // Setup namespaces
        admin.clusters().createCluster("use", ClusterData.builder().serviceUrl(pulsar.getWebServiceAddress()).build());
        TenantInfoImpl tenantInfo = new TenantInfoImpl(Set.of("role1", "role2"), Set.of("use"));
        admin.tenants().createTenant("prop-xyz", tenantInfo);
        admin.namespaces().createNamespace("prop-xyz/use/ns1");
    }

    @AfterMethod(alwaysRun = true)
    @Override
    public void cleanup() throws Exception {
        super.internalCleanup();
        mockPulsarSetup.cleanup();
    }

    @Test
    public void testIncrementPartitionsOfTopicOnUnusedTopic() throws Exception {
        final String partitionedTopicName = "persistent://prop-xyz/use/ns1/test-topic";

        admin.topics().createPartitionedTopic(partitionedTopicName, 10);
        assertEquals(admin.topics().getPartitionedTopicMetadata(partitionedTopicName).partitions, 10);

        admin.topics().updatePartitionedTopic(partitionedTopicName, 20);
        assertEquals(admin.topics().getPartitionedTopicMetadata(partitionedTopicName).partitions, 20);
    }

    @Test
    public void testIncrementPartitionsOfTopic() throws Exception {
        final String partitionedTopicName = "persistent://prop-xyz/use/ns1/test-topic-2";

        admin.topics().createPartitionedTopic(partitionedTopicName, 1);
        assertEquals(admin.topics().getPartitionedTopicMetadata(partitionedTopicName).partitions, 1);

        Consumer<byte[]> consumer = pulsarClient.newConsumer().topic(partitionedTopicName).subscriptionName("sub-1")
          .subscribe();

        admin.topics().updatePartitionedTopic(partitionedTopicName, 2);
        assertEquals(admin.topics().getPartitionedTopicMetadata(partitionedTopicName).partitions, 2);

        admin.topics().updatePartitionedTopic(partitionedTopicName, 10);
        assertEquals(admin.topics().getPartitionedTopicMetadata(partitionedTopicName).partitions, 10);

        admin.topics().updatePartitionedTopic(partitionedTopicName, 20);
        assertEquals(admin.topics().getPartitionedTopicMetadata(partitionedTopicName).partitions, 20);

        assertEquals(admin.topics().getSubscriptions(
                TopicName.get(partitionedTopicName).getPartition(15).toString()), List.of("sub-1"));

        consumer.close();
    }

    @Test
    public void testIncrementPartitionsWithNoSubscriptions() throws Exception {
        final String partitionedTopicName =
                BrokerTestUtil.newUniqueName("persistent://prop-xyz/use/ns1/test-topic");

        admin.topics().createPartitionedTopic(partitionedTopicName, 1);
        assertEquals(admin.topics().getPartitionedTopicMetadata(partitionedTopicName).partitions, 1);

        @Cleanup
        Producer<String> consumer = pulsarClient.newProducer(Schema.STRING)
                .topic(partitionedTopicName)
                .create();

        admin.topics().updatePartitionedTopic(partitionedTopicName, 2);
        //zk update takes some time
        Awaitility.await().untilAsserted(() ->
                assertEquals(admin.topics().getPartitionedTopicMetadata(partitionedTopicName).partitions, 2));

        admin.topics().updatePartitionedTopic(partitionedTopicName, 10);
        Awaitility.await().untilAsserted(() ->
                assertEquals(admin.topics().getPartitionedTopicMetadata(partitionedTopicName).partitions, 10));

        admin.topics().updatePartitionedTopic(partitionedTopicName, 20);
        Awaitility.await().untilAsserted(() ->
                assertEquals(admin.topics().getPartitionedTopicMetadata(partitionedTopicName).partitions, 20));
    }

    @Test
    public void testIncrementPartitionsWithReaders() throws Exception {
        TopicName partitionedTopicName = TopicName.get(
                BrokerTestUtil.newUniqueName("persistent://prop-xyz/use/ns1/test-topic"));

        admin.topics().createPartitionedTopic(partitionedTopicName.toString(), 1);
        assertEquals(admin.topics().getPartitionedTopicMetadata(partitionedTopicName.toString()).partitions, 1);

        @Cleanup
        Producer<String> consumer = pulsarClient.newProducer(Schema.STRING)
                .topic(partitionedTopicName.toString())
                .create();

        @Cleanup
        Reader<String> reader = pulsarClient.newReader(Schema.STRING)
                .topic(partitionedTopicName.getPartition(0).toString())
                .startMessageId(MessageId.earliest)
            .create();

        admin.topics().updatePartitionedTopic(partitionedTopicName.toString(), 2);
        assertEquals(admin.topics().getPartitionedTopicMetadata(partitionedTopicName.toString()).partitions, 2);

        assertEquals(admin.topics().getSubscriptions(partitionedTopicName.getPartition(0).toString()).size(), 1);

        // Partition-1 should not have subscriptions
        assertEquals(admin.topics().getSubscriptions(partitionedTopicName.getPartition(1).toString()),
                Collections.emptyList());
    }
}


text:
// independent from idl_parser, since this code is not needed for most clients

#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"

namespace flatbuffers {

static void GenStruct(const StructDef &struct_def, const Table *table,
                      int indent, const GeneratorOptions &opts,
                      std::string *_text);

// If indentation is less than 0, that indicates we don't want any newlines
// either.
const char *NewLine(const GeneratorOptions &opts) {
  return opts.indent_step >= 0 ? "\n" : "";
}

int Indent(const GeneratorOptions &opts) {
  return std::max(opts.indent_step, 0);
}

// Output an identifier with or without quotes depending on strictness.
void OutputIdentifier(const std::string &name, const GeneratorOptions &opts,
                      std::string *_text) {
  std::string &text = *_text;
  if (opts.strict_json) text += "\"";
  text += name;
  if (opts.strict_json) text += "\"";
}

// Print (and its template specialization below for pointers) generate text
// for a single FlatBuffer value into JSON format.
// The general case for scalars:
template<typename T> void Print(T val, Type type, int /*indent*/,
                                StructDef * /*union_sd*/,
                                const GeneratorOptions &opts,
                                std::string *_text) {
  std::string &text = *_text;
  if (type.enum_def && opts.output_enum_identifiers) {
    AUTO_VAR(enum_val, type.enum_def->ReverseLookup(static_cast<int>(val)));
    if (enum_val) {
      OutputIdentifier(enum_val->name, opts, _text);
      return;
    }
  }
  text += NumToString(val);
}

// Print a vector a sequence of JSON values, comma separated, wrapped in "[]".
template<typename T> void PrintVector(const Vector<T> &v, Type type,
                                      int indent, const GeneratorOptions &opts,
                                      std::string *_text) {
  std::string &text = *_text;
  text += "[";
  text += NewLine(opts);
  for (uoffset_t i = 0; i < v.size(); i++) {
    if (i) {
      text += ",";
      text += NewLine(opts);
    }
    text.append(indent + Indent(opts), ' ');
    if (IsStruct(type))
      Print(v.GetStructFromOffset(i * type.struct_def->bytesize), type,
            indent + Indent(opts), nullptr, opts, _text);
    else
      Print(v.Get(i), type, indent + Indent(opts), nullptr,
            opts, _text);
  }
  text += NewLine(opts);
  text.append(indent, ' ');
  text += "]";
}

static void EscapeString(const String &s, std::string *_text) {
  std::string &text = *_text;
  text += "\"";
  for (uoffset_t i = 0; i < s.size(); i++) {
    char c = s.Get(i);
    switch (c) {
      case '\n': text += "\\n"; break;
      case '\t': text += "\\t"; break;
      case '\r': text += "\\r"; break;
      case '\b': text += "\\b"; break;
      case '\f': text += "\\f"; break;
      case '\"': text += "\\\""; break;
      case '\\': text += "\\\\"; break;
      default:
        if (c >= ' ' && c <= '~') {
          text += c;
        } else {
          // Not printable ASCII data. Let's see if it's valid UTF-8 first:
          const char *utf8 = s.c_str() + i;
          int ucc = FromUTF8(&utf8);
          if (ucc >= 0x80 && ucc <= 0xFFFF) {
            // Parses as Unicode within JSON's \uXXXX range, so use that.
            text += "\\u";
            text += IntToStringHex(ucc, 4);
            // Skip past characters recognized.
            i = static_cast<uoffset_t>(utf8 - s.c_str() - 1);
          } else {
            // It's either unprintable ASCII, arbitrary binary, or Unicode data
            // that doesn't fit \uXXXX, so use \xXX escape code instead.
            text += "\\x";
            text += IntToStringHex(static_cast<uint8_t>(c), 2);
          }
        }
        break;
    }
  }
  text += "\"";
}

// Specialization of Print above for pointer types.
template<> void Print<const void *>(const void *val,
                                    Type type, int indent,
                                    StructDef *union_sd,
                                    const GeneratorOptions &opts,
                                    std::string *_text) {
  switch (type.base_type) {
    case BASE_TYPE_UNION:
      // If this assert hits, you have an corrupt buffer, a union type field
      // was not present or was out of range.
      assert(union_sd);
      GenStruct(*union_sd,
                reinterpret_cast<const Table *>(val),
                indent,
                opts,
                _text);
      break;
    case BASE_TYPE_STRUCT:
      GenStruct(*type.struct_def,
                reinterpret_cast<const Table *>(val),
                indent,
                opts,
                _text);
      break;
    case BASE_TYPE_STRING: {
      EscapeString(*reinterpret_cast<const String *>(val), _text);
      break;
    }
    case BASE_TYPE_VECTOR:
      type = type.VectorType();
      // Call PrintVector above specifically for each element type:
      switch (type.base_type) {
        #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) \
          case BASE_TYPE_ ## ENUM: \
            PrintVector<CTYPE >( \
              *reinterpret_cast<const Vector<CTYPE > *>(val), \
              type, indent, opts, _text); break;
          FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
        #undef FLATBUFFERS_TD
      }
      break;
    default: assert(0);
  }
}

// Generate text for a scalar field.
template<typename T> static void GenField(const FieldDef &fd,
                                          const Table *table, bool fixed,
                                          const GeneratorOptions &opts,
                                          int indent,
                                          std::string *_text) {
  Print(fixed ?
    reinterpret_cast<const Struct *>(table)->GetField<T>(fd.value.offset) :
    table->GetField<T>(fd.value.offset, 0), fd.value.type, indent, nullptr,
                                            opts, _text);
}

// Generate text for non-scalar field.
static void GenFieldOffset(const FieldDef &fd, const Table *table, bool fixed,
                           int indent, StructDef *union_sd,
                           const GeneratorOptions &opts, std::string *_text) {
  const void *val = nullptr;
  if (fixed) {
    // The only non-scalar fields in structs are structs.
    assert(IsStruct(fd.value.type));
    val = reinterpret_cast<const Struct *>(table)->
            GetStruct<const void *>(fd.value.offset);
  } else {
    val = IsStruct(fd.value.type)
      ? table->GetStruct<const void *>(fd.value.offset)
      : table->GetPointer<const void *>(fd.value.offset);
  }
  Print(val, fd.value.type, indent, union_sd, opts, _text);
}

// Generate text for a struct or table, values separated by commas, indented,
// and bracketed by "{}"
static void GenStruct(const StructDef &struct_def, const Table *table,
                      int indent, const GeneratorOptions &opts,
                      std::string *_text) {
  std::string &text = *_text;
  text += "{";
  int fieldout = 0;
  StructDef *union_sd = nullptr;
  for (AUTO_VAR(it, struct_def.fields.vec.begin());
       it != struct_def.fields.vec.end();
       ++it) {
    FieldDef &fd = **it;
    if (struct_def.fixed || table->CheckField(fd.value.offset)) {
      // The field is present.
      if (fieldout++) {
        text += ",";
      }
      text += NewLine(opts);
      text.append(indent + Indent(opts), ' ');
      OutputIdentifier(fd.name, opts, _text);
      text += ": ";
      switch (fd.value.type.base_type) {
         #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) \
           case BASE_TYPE_ ## ENUM: \
              GenField<CTYPE>(fd, table, struct_def.fixed, \
                              opts, indent + Indent(opts), _text); \
              break;
          FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD)
        #undef FLATBUFFERS_TD
        // Generate drop-thru case statements for all pointer types:
        #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) \
          case BASE_TYPE_ ## ENUM:
          FLATBUFFERS_GEN_TYPES_POINTER(FLATBUFFERS_TD)
        #undef FLATBUFFERS_TD
            GenFieldOffset(fd, table, struct_def.fixed, indent + Indent(opts),
                           union_sd, opts, _text);
            break;
      }
      if (fd.value.type.base_type == BASE_TYPE_UTYPE) {
        AUTO_VAR(enum_val, fd.value.type.enum_def->ReverseLookup(
                          table->GetField<uint8_t>(fd.value.offset, 0)));
        assert(enum_val);
        union_sd = enum_val->struct_def;
      }
    }
  }
  text += NewLine(opts);
  text.append(indent, ' ');
  text += "}";
}

// Generate a text representation of a flatbuffer in JSON format.
void GenerateText(const Parser &parser, const void *flatbuffer,
                  const GeneratorOptions &opts, std::string *_text) {
  std::string &text = *_text;
  assert(parser.root_struct_def);  // call SetRootType()
  text.reserve(1024);   // Reduce amount of inevitable reallocs.
  GenStruct(*parser.root_struct_def,
            GetRoot<Table>(flatbuffer),
            0,
            opts,
            _text);
  text += NewLine(opts);
}

std::string TextFileName(const std::string &path,
                         const std::string &file_name) {
  return path + file_name + ".json";
}

bool GenerateTextFile(const Parser &parser,
                      const std::string &path,
                      const std::string &file_name,
                      const GeneratorOptions &opts) {
  if (!parser.builder_.GetSize() || !parser.root_struct_def) return true;
  std::string text;
  GenerateText(parser, parser.builder_.GetBufferPointer(), opts,
               &text);
  return flatbuffers::SaveFile(TextFileName(path, file_name).c_str(),
                               text,
                               false);
}

std::string TextMakeRule(const Parser &parser,
                         const std::string &path,
                         const std::string &file_name,
                         const GeneratorOptions & /*opts*/) {
  if (!parser.builder_.GetSize() || !parser.root_struct_def) return "";
  std::string filebase = flatbuffers::StripPath(
      flatbuffers::StripExtension(file_name));
  std::string make_rule = TextFileName(path, filebase) + ": " + file_name;
  AUTO_VAR(included_files,
    parser.GetIncludedFilesRecursive(parser.root_struct_def->file));
  for (AUTO_VAR(it, included_files.begin());
       it != included_files.end(); ++it) {
    make_rule += " " + *it;
  }
  return make_rule;
}

}  // namespace flatbuffers


text:
import * as path from 'path';
import * as ts from 'typescript';

export function makeProgram(files: {name: string, contents: string}[]): ts.Program {
  const host = new InMemoryHost();
  files.forEach(file => host.writeFile(file.name, file.contents));

  const rootNames = files.map(file => host.getCanonicalFileName(file.name));
  const program = ts.createProgram(rootNames, {noLib: true, experimentalDecorators: true}, host);
  const diags = [...program.getSyntacticDiagnostics(), ...program.getSemanticDiagnostics()];
  if (diags.length > 0) {
    fail(diags.map(diag => diag.messageText).join(', '));
    throw new Error(`Typescript diagnostics failed!`);
  }
  return program;
}

export class InMemoryHost implements ts.CompilerHost {
  private fileSystem = new Map<string, string>();

  getSourceFile(
      fileName: string, languageVersion: ts.ScriptTarget,
      onError?: ((message: string) => void)|undefined,
      shouldCreateNewSourceFile?: boolean|undefined): ts.SourceFile|undefined {
    const contents = this.fileSystem.get(this.getCanonicalFileName(fileName));
    if (contents === undefined) {
      onError && onError(`File does not exist: ${this.getCanonicalFileName(fileName)})`);
      return undefined;
    }
    return ts.createSourceFile(fileName, contents, languageVersion, undefined, ts.ScriptKind.TS);
  }

  getDefaultLibFileName(options: ts.CompilerOptions): string { return '/lib.d.ts'; }

  writeFile(
      fileName: string, data: string, writeByteOrderMark?: boolean,
      onError?: ((message: string) => void)|undefined,
      sourceFiles?: ReadonlyArray<ts.SourceFile>): void {
    this.fileSystem.set(this.getCanonicalFileName(fileName), data);
  }

  getCurrentDirectory(): string { return '/'; }

  getDirectories(dir: string): string[] {
    const fullDir = this.getCanonicalFileName(dir) + '/';
    const dirSet = new Set(Array
                               // Look at all paths known to the host.
                               .from(this.fileSystem.keys())
                               // Filter out those that aren't under the requested directory.
                               .filter(candidate => candidate.startsWith(fullDir))
                               // Relativize the rest by the requested directory.
                               .map(candidate => candidate.substr(fullDir.length))
                               // What's left are dir/.../file.txt entries, and file.txt entries.
                               // Get the dirname, which
                               // yields '.' for the latter and dir/... for the former.
                               .map(candidate => path.dirname(candidate))
                               // Filter out the '.' entries, which were files.
                               .filter(candidate => candidate !== '.')
                               // Finally, split on / and grab the first entry.
                               .map(candidate => candidate.split('/', 1)[0]));

    // Get the resulting values out of the Set.
    return Array.from(dirSet);
  }

  getCanonicalFileName(fileName: string): string {
    return path.posix.normalize(`${this.getCurrentDirectory()}/${fileName}`);
  }

  useCaseSensitiveFileNames(): boolean { return true; }

  getNewLine(): string { return '\n'; }

  fileExists(fileName: string): boolean { return this.fileSystem.has(fileName); }

  readFile(fileName: string): string|undefined { return this.fileSystem.get(fileName); }
}

function bindingNameEquals(node: ts.BindingName, name: string): boolean {
  if (ts.isIdentifier(node)) {
    return node.text === name;
  }
  return false;
}

export function getDeclaration<T extends ts.Declaration>(
    program: ts.Program, fileName: string, name: string, assert: (value: any) => value is T): T {
  const sf = program.getSourceFile(fileName);
  if (!sf) {
    throw new Error(`No such file: ${fileName}`);
  }

  let chosenDecl: ts.Declaration|null = null;

  sf.statements.forEach(stmt => {
    if (chosenDecl !== null) {
      return;
    } else if (ts.isVariableStatement(stmt)) {
      stmt.declarationList.declarations.forEach(decl => {
        if (bindingNameEquals(decl.name, name)) {
          chosenDecl = decl;
        }
      });
    } else if (ts.isClassDeclaration(stmt) || ts.isFunctionDeclaration(stmt)) {
      if (stmt.name !== undefined && stmt.name.text === name) {
        chosenDecl = stmt;
      }
    }
  });

  chosenDecl = chosenDecl as ts.Declaration | null;

  if (chosenDecl === null) {
    throw new Error(`No such symbol: ${name} in ${fileName}`);
  }
  if (!assert(chosenDecl)) {
    throw new Error(`Symbol ${name} from ${fileName} is a ${ts.SyntaxKind[chosenDecl.kind]}`);
  }

  return chosenDecl;
}


text:
package client

import (
	"fmt"

	"github.com/keybase/cli"
	"github.com/keybase/client/go/install"
	"github.com/keybase/client/go/launchd"
	"github.com/keybase/client/go/libcmdline"
	"github.com/keybase/client/go/libkb"
	"github.com/keybase/client/go/protocol/keybase1"
	"golang.org/x/net/context"
)

// NewCmdCtlStop constructs ctl start command
func NewCmdCtlStop(cl *libcmdline.CommandLine, g *libkb.GlobalContext) cli.Command {
	return cli.Command{
		Name:  "stop",
		Usage: "Stop Keybase",
		Flags: []cli.Flag{
			cli.StringFlag{
				Name:  "include",
				Usage: fmt.Sprintf("Stop only specified components, comma separated. Specify %v.", availableCtlComponents),
			},
			cli.StringFlag{
				Name:  "exclude",
				Usage: fmt.Sprintf("Stop all except excluded components, comma separated. Specify %v.", availableCtlComponents),
			},
			cli.BoolFlag{
				Name:  "shutdown",
				Usage: "Only shutdown the service",
			},
		},
		Action: func(c *cli.Context) {
			cl.ChooseCommand(newCmdCtlStop(g), "stop", c)
			cl.SetForkCmd(libcmdline.NoFork)
			cl.SetLogForward(libcmdline.LogForwardNone)
			cl.SetNoStandalone()
		},
	}
}

type CmdCtlStop struct {
	libkb.Contextified
	components map[string]bool
	shutdown   bool
}

func newCmdCtlStop(g *libkb.GlobalContext) *CmdCtlStop {
	return &CmdCtlStop{
		Contextified: libkb.NewContextified(g),
	}
}

func (s *CmdCtlStop) ParseArgv(ctx *cli.Context) error {
	s.shutdown = ctx.Bool("shutdown")
	s.components = ctlParseArgv(ctx)
	return nil
}

func ctlBrewStop(g *libkb.GlobalContext) error {
	_, err := launchd.Stop(install.DefaultServiceLabel(g.Env.GetRunMode()), defaultLaunchdWait, g.Log)
	return err
}

func ctlStop(g *libkb.GlobalContext, components map[string]bool) error {
	if libkb.IsBrewBuild {
		return ctlBrewStop(g)
	}
	g.Log.Debug("ctlStop: Components: %v", components)
	errs := []error{}
	if ok := components[install.ComponentNameApp.String()]; ok {
		if err := install.TerminateApp(g, g.Log); err != nil {
			errs = append(errs, err)
		}
	}
	if ok := components[install.ComponentNameService.String()]; ok {
		if err := install.UninstallKeybaseServices(g, g.Log); err != nil {
			errs = append(errs, err)
		}
	}
	if ok := components[install.ComponentNameKBFS.String()]; ok {
		if err := install.UninstallKBFSOnStop(g, g.Log); err != nil {
			errs = append(errs, err)
		}
	}
	if ok := components[install.ComponentNameUpdater.String()]; ok {
		if err := install.UninstallUpdaterService(g, g.Log); err != nil {
			errs = append(errs, err)
		}
	}
	if err := rpcStop(g); err != nil {
		g.Log.Info("ctlStop: expected error when trying to shutdown service post-uninstall: %s", err)
	} else {
		g.Log.Info("ctlStop: no error when shutting down service post-uninstall")
	}
	return libkb.CombineErrors(errs...)
}

func rpcStop(g *libkb.GlobalContext) error {
	cli, err := GetCtlClient(g)
	if err != nil {
		return err
	}
	return cli.StopService(context.TODO(), keybase1.StopServiceArg{ExitCode: keybase1.ExitCode_OK})
}

func (s *CmdCtlStop) Run() error {
	if s.shutdown {
		return rpcStop(s.G())
	}
	return ctlStop(s.G(), s.components)
}

func (s *CmdCtlStop) GetUsage() libkb.Usage {
	return libkb.Usage{}
}


text:
love = {}
require "src/client/conf"
conf = {}
conf.modules = {}
conf.window = {}
love.conf(conf)
print(conf.title)


text:
\hypertarget{_o_p_label_8h}{}\section{O\+P\+Label.\+h File Reference}
\label{_o_p_label_8h}\index{O\+P\+Label.\+h@{O\+P\+Label.\+h}}

\hyperlink{class_o_p_label}{O\+P\+Label} class.

{\ttfamily \#include $<$iostream$>$}\\*
{\ttfamily \#include $<$Operand.\+h$>$}\\*
{\ttfamily \#include $<$Enum\+\_\+type.\+h$>$}\\*
{\ttfamily \#include $<$string$>$}\\*
\subsection*{Classes}
\begin{DoxyCompactItemize}
\item
class \hyperlink{class_o_p_label}{O\+P\+Label}
\begin{DoxyCompactList}\small\item\em class representing a \hyperlink{class_label}{Label} herited by \hyperlink{class_operand}{Operand} \end{DoxyCompactList}\end{DoxyCompactItemize}
\subsection*{Functions}
\begin{DoxyCompactItemize}
\item
\hypertarget{_o_p_label_8h_a2a54dc70e5071ab362bb95d472986203}{}\hyperlink{class_o_p_label}{O\+P\+Label} $\ast$ \hyperlink{_o_p_label_8h_a2a54dc70e5071ab362bb95d472986203}{get\+O\+P\+Label} (\hyperlink{class_operand}{Operand} $\ast$)\label{_o_p_label_8h_a2a54dc70e5071ab362bb95d472986203}

\begin{DoxyCompactList}\small\item\em returns the \hyperlink{class_o_p_label}{O\+P\+Label} associated to the \hyperlink{class_operand}{Operand} if it is an \hyperlink{class_o_p_label}{O\+P\+Label}, otherwise returns N\+U\+L\+L \end{DoxyCompactList}\end{DoxyCompactItemize}

\subsection{Detailed Description}
\hyperlink{class_o_p_label}{O\+P\+Label} class.

\begin{DoxyAuthor}{Author}
Hajjem
\end{DoxyAuthor}


text:
Template.postEdit.helpers({
  post: function() {
    return Posts.findOne(Session.get('currentPostId'));
  }
});

Template.postEdit.events({
  'submit form': function(e) {
    e.preventDefault();

    var currentPostId = Session.get('currentPostId');

    var postProperties = {
      url: $(e.target).find('[name=url]').val(),
      title: $(e.target).find('[name=title]').val()
    }

    Posts.update(currentPostId, {$set: postProperties}, function(error) {
      if (error) {
        // display the error to the user
        alert(error.reason);
      } else {
        Meteor.Router.to('postPage', currentPostId);
      }
    });
  },

  'click .delete': function(e) {
    e.preventDefault();

    if (confirm("Delete this post?")) {
      var currentPostId = Session.get('currentPostId');
      Posts.remove(currentPostId);
      Meteor.Router.to('postsList');
    }
  }
});


text:
package parser;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import slogoEnums.ErrorMessage;
import exceptions.*;
import Constants.*;

/** The parser analyzes the the command that the user types in
 * to build a syntax tree consisted of nodes with command names.
 *
 * @author Yancheng, Sierra
 *
 */
public class Parser {

	/** The Constant USER_DEFINED. */
	public static final String USER_DEFINED = "UserDefined";

	/** The Constant OPEN_BRACKET. */
	public static final String OPEN_BRACKET = "[";

	/** The Constant CLOSED_BRACKET. */
	public static final String CLOSED_BRACKET = "]";

	/** The Constant GROUP. */
	public static final String GROUP = "Group";

	/** The Constant REPCOUNT. */
	public static final String REPCOUNT = ":repcount";

	/** The Constant TO. */
	public static final String TO = "MakeUserInstruction";

	/** The Constant MAKEVARIABLE. */
	public static final String MAKEVARIABLE = "MakeVariable";

	/** The Constant REPEAT. */
	public static final String REPEAT = "Repeat";

	/** The Constant CONSTANT. */
	public static final String CONSTANT = "Constant";

	/** The Constant VARIABLE. */
	public static final String VARIABLE = "Variable";

	/** The Constant COMMAND. */
	public static final String COMMAND = "Command";

	/** The Constant FOR. */
	public static final String FOR = "For";

	/** The my regex. */
	private Regex myRegex;

	/** The my cur index. */
	private int myCurIndex;

	/** The my cur program array. */
	private String[] myCurProgramArray;

	/** The my program variables. */
	private Set<String> myProgramVariables;

	/** The my prog methods and params. */
	private Map<String, Integer> myProgMethodsAndParams;

	/**
	 * Instantiates a new parser.
	 */
	public Parser() {
		myRegex = new Regex(Constants.SYNTAX, Constants.DEFAULT_LANGUAGE);
		myCurIndex = -1;
		myProgramVariables = new HashSet<>();
		myProgMethodsAndParams = new HashMap<>();
	}

	/**
	 * Gets the regex.
	 *
	 * @return the regex
	 */
	public Regex getRegex() {
		return myRegex;
	}

	/**
	 * Increment the current index.
	 */
	public void incrementCurIndex(){
		myCurIndex += 1;
	}

	/**
	 * Gets the current index.
	 *
	 * @return the current index
	 */
	public int getCurIndex(){
		return myCurIndex;
	}

	/**
	 * Gets the current element.
	 *
	 * @return the current element
	 */
	public String getCurrentElement(){
		return myCurProgramArray[myCurIndex];
	}

	/**
	 * Gets the element at index.
	 *
	 * @param index the index
	 * @return the element at index
	 */
	public String getElementAtIndex(int index){
		return myCurProgramArray[index];
	}

	/**
	 * Gets the next element.
	 *
	 * @return the next element
	 */
	public String getNextElement() {
		if(!atEndOfString()){
			return myCurProgramArray[myCurIndex+1];
		}
		return null;
	}

	/**
	 * Adds the variable to table.
	 *
	 * @param var the var
	 */
	public void addVariableToTable(String var){
		myProgramVariables.add(var);
	}

	/**
	 * Variable exists.
	 *
	 * @param var the var
	 * @return true, if successful
	 */
	public boolean variableExists(String var){
		return myProgramVariables.contains(var);
	}

	/**
	 * Adds the method.
	 *
	 * @param name the name
	 * @param numParams the num params
	 */
	public void addMethod(String name, int numParams){
		myProgMethodsAndParams.put(name, numParams);
	}

	/**
	 * Method exists.
	 *
	 * @param name the name
	 * @return true, if successful
	 */
	public boolean methodExists(String name){
		return myProgMethodsAndParams.containsKey(name);
	}

	/**
	 * Gets the user method params.
	 *
	 * @param methodName the method name
	 * @return the user method params
	 */
	public int getUserMethodParams(String methodName){
		return myProgMethodsAndParams.get(methodName);
	}

	/**
	 * This method starts the parsing process and creates a head node for each
	 * independent command
	 *
	 * @param program the program
	 * @return a list of independent command nodes
	 * @throws ParserException the parser exception
	 */
	public List<ParseNode> parse(String program) throws ParserException {
		myCurIndex = -1;
		String processed = preProcessString(program);
		if (processed == null) {
			return null;
		}
		List<ParseNode> topNodes = new ArrayList<>();
		while (myCurIndex < myCurProgramArray.length - 1) {
			ParseNode curNode = NodeFactory.createNode(myRegex, myCurProgramArray[++myCurIndex], this);
			ParseNode processedNode = recursiveCommandBuilder(curNode);
			topNodes.add(processedNode);
		}
		return topNodes;
	}

	/**
	 * Change language.
	 *
	 * @param language the language
	 */
	public void changeLanguage(String language) {
		myRegex.changeLanguagePattern(language);
	}

	/**
	 * This method pre-processes the user-typed command string and get rids of
	 * comments and new lines in the string. It also splits up the string into
	 * a string array based on white spaces.
	 *
	 * @param user-typed command string
	 * @return the pre-processed string
	 */
	public String preProcessString(String program) {
		String[] splitProgram = program.split(" ");
		if (splitProgram.length < 1 | program.length() < 1) {
			return null;
		}
		List<Character> programArray = new ArrayList<Character>();
		List<Character> correctArray = new ArrayList<Character>();
		for (char c : program.toCharArray()) {
			programArray.add(c);
		}

		deleteComments(programArray, correctArray);
		StringBuilder builder = new StringBuilder(correctArray.size());
		for (Character c : correctArray) {
			builder.append(c);
		}
		String toDeleteWhiteSpace = builder.toString();
		ArrayList<String> voidOfSpace = new ArrayList<>();
		List<String> spaceProcessing = Arrays.asList(toDeleteWhiteSpace.split(" "));
		for(String e: spaceProcessing){
			if(!e.equals("")){
				voidOfSpace.add(e);
			}
		}
		String[] validCommand = new String[voidOfSpace.size()];
		for(int i = 0; i < voidOfSpace.size(); i++){
			validCommand[i] = voidOfSpace.get(i);
		}
		myCurProgramArray = validCommand;
		return builder.toString();
	}

	/**
	 * This method deletes the comments in the command string.
	 *
	 * @param originalArray the original array
	 * @param processedArray the processed array
	 */
	private void deleteComments(List<Character> originalArray, List<Character> processedArray){
		boolean check = false;
		for (int i = 0; i < originalArray.size(); i++) {
			if (originalArray.get(i) == '#') {
				check = true;
			}
			if (originalArray.get(i) == '\n') {
				check = false;
				continue;
			}
			if (!check) {
				processedArray.add(originalArray.get(i));
			}
		}
		return;
	}

	/**
	 * A generic call the triggers the parsing process on the current node.
	 *
	 * @param current the current
	 * @return the parses the node
	 * @throws ParserException the parser exception
	 */
	public ParseNode recursiveCommandBuilder(ParseNode current)
			throws ParserException {
			return current.finishProcessing();
	}

	/**
	 * In the syntax tree, if a node is a group then it will
	 * process its child nodes here.
	 *
	 * @param groupLeader the group leader
	 * @return the group kids
	 * @throws ParserException the parser exception
	 */
	public void getGroupKids(ParseNode groupLeader) throws ParserException {
		boolean groupComplete = false;
		while (!groupComplete) {
			checkStringEndsEarly(ErrorMessage.MISSING_END_BRACKET.getVal());
			String next = myCurProgramArray[++myCurIndex];
			if (next.equals(CLOSED_BRACKET)) {
				groupComplete = true;
			}
			else{
				retrieveGenericKids(groupLeader, next);
			}
		}
	}

	/**
	 * This is the generic method for nodes to add their child nodes and calls the
	 * method on the child nodes to recursively build the tree.
	 *
	 * @param current the current
	 * @param next the next
	 * @throws ParserException the parser exception
	 */
	public void retrieveGenericKids(ParseNode current, String next) throws ParserException{
		if (next.equals(OPEN_BRACKET)) {
			ParseNode newGroup = NodeFactory.createNode(myRegex, GROUP, this);
			ParseNode processedNode = recursiveCommandBuilder(newGroup);
			current.addChild(processedNode);
		}
		else {
			ParseNode newNode = NodeFactory.createNode(myRegex, next, this);
			ParseNode processedNode = recursiveCommandBuilder(newNode);
			current.addChild(processedNode);
		}
	}

	/**
	 * This method retrieves a node's expected number of child nodes and detects
	 * end bracket syntax error.
	 *
	 * @param current the current
	 * @param loopTimes the loop times
	 * @throws ParserException the parser exception
	 */
	public void retrieveChildren(ParseNode current, int loopTimes)
			throws ParserException {
		while (current.getChildCount() < loopTimes) {
			checkStringEndsEarly(ErrorMessage.MISSING_PARAMETER.getVal()
						+ current.getName());
			String next = myCurProgramArray[++myCurIndex];
			if (next.equals(CLOSED_BRACKET)) {
				throw new ParserException(ErrorMessage.MISSING_PARAMETER.getVal()
						+ current.getName()
						+ ErrorMessage.BEFORE_END_BRACKET);
			} else {
				retrieveGenericKids(current, next);
			}
		}
	}

	/**
	 * Check if the command string reaches the end before expected command
	 * elements are processed.
	 *
	 * @param error the error
	 * @throws ParserException the parser exception
	 */
	public void checkStringEndsEarly(String error) throws ParserException{
		if (atEndOfString()) {
			throw new ParserException(error);
		}
	}

	/**
	 * Check if it has reached the end of the command string.
	 *
	 * @return true, if at the end
	 */
	public boolean atEndOfString() {
		return (myCurIndex == myCurProgramArray.length - 1);
	}
}


text:
extern int foo (void) __attribute__((section (".gnu.linkonce.t.1"), weak));

int
foo (void)
{
  return 1;
}


text:
package org.scalastyle.scalariform

import org.junit.Test
import org.scalastyle.file.CheckerTest
import org.scalatest.junit.AssertionsForJUnit

// scalastyle:off magic.number

class NoFinalizeCheckerTest extends AssertionsForJUnit with CheckerTest {
  val key = "no.finalize"
  val classUnderTest = classOf[NoFinalizeChecker]

  @Test def testClassOK(): Unit = {
    val source = """
package foobar

class OK {
  def finalize(o: java.lang.Integer): Unit = {}
}
"""

    assertErrors(List(), source)
  }

  @Test def testClassCovariantEqualsNoObjectKO(): Unit = {
    val source = """
package foobar

class CloneKO {
  def finalize(): Unit = {}
}
"""

    assertErrors(List(columnError(4, 6)), source)
  }

  @Test def testObjectOK(): Unit = {
    val source = """
package foobar

object OK {
  def finalize(o: java.lang.Integer): Unit = {}
}
"""

    assertErrors(List(), source)
  }

  @Test def testObjectCovariantEqualsNoObjectKO(): Unit = {
    val source = """
package foobar

object CloneKO {
  def finalize(): Unit = {}
}
"""

    assertErrors(List(columnError(4, 7)), source)
  }
}


text:
<?php
namespace Empresas\Model\Dao;
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Expression;
use Empresas\Model\Entity\DetalleContacto;

class DetalleContactoDao {

    protected $tableGateway;

    public function __construct(TableGateway $tableGateway){
    	$this->tableGateway = $tableGateway;
    }

    public function traerTodos(){
    	$resultSet = $this->tableGateway->select();
         return $resultSet;
    }

    public function traer($det_con_id){

    	$det_con_id = (int) $det_con_id;
    	$resultSet = $this->tableGateway->select(array('DET_CON_ID' => $det_con_id));
    	$row =  $resultSet->current();

    	if(!$row){
    		throw new \Exception('No se encontro el ID del Detalle de Contacto');
    	}
    	return $row;

    }

    public function getDetallePorEmpresa($emp_id){
        $sql = new Sql($this->tableGateway->getAdapter());
        $select = $sql->select();
        $select->from($this->tableGateway->table);
        $select->join(array('E' => 'EMPRESA'),'DETALLE_CONTACTO.EMP_ID = E.EMP_ID');
        $select->where(array('DETALLE_CONTACTO.EMP_ID' => $emp_id));

        $statement = $sql->prepareStatementForSqlObject($select);
        $results = $statement->execute();

        $detalles = new \ArrayObject();
        $result = array();

        foreach ($results as $row){
            $detalle = new DetalleContacto();
            $detalle->exchangeArray($row);
            $detalles->append($detalle);
        }

        return $detalles;
    }

    public function guardar(DetalleContacto $detalleContacto){

        $data=array(
            'det_con_id'=>$detalleContacto->getDet_con_id(),
            'emp_id'=>$detalleContacto->getEmp_id(),
            'con_id'=>$detalleContacto->getCon_id(),
            'tip_tel_id'=>$detalleContacto->getTip_tel_id(),
            'det_con_codigo_pais'=>$detalleContacto->getDet_con_codigo_pais(),
            'det_con_codigo_ciudad'=>$detalleContacto->getDet_con_codigo_ciudad(),
            'det_con_valor'=>$detalleContacto->getDet_con_valor(),
            'det_con_extension'=>$detalleContacto->getDet_con_extension()
        );

        if(empty($data['det_con_id']) || is_null($data['det_con_id'])){
            $data['det_con_id'] = new \Zend\Db\Sql\Expression('s_detalle_contacto.nextVal');
            if(empty($data['emp_id']) || is_null($data['emp_id'])){
                $data['emp_id'] = new \Zend\Db\Sql\Expression('s_empresa.currVal');
            }
            $data=array_change_key_case($data,CASE_UPPER);

            $this->tableGateway->insert($data);
        }
     }

     public function eliminarPorEmpresa($emp_id){
        $adapter=$this->tableGateway->getAdapter();
        $query="DELETE FROM DETALLE_CONTACTO WHERE EMP_ID=$emp_id";
        $state=$adapter->query($query);
        $state->execute();
     }

}


text:
namespace history {

// filenames
const base::FilePath::CharType kFaviconsFilename[] =
    FILE_PATH_LITERAL("Favicons");
const base::FilePath::CharType kHistoryFilename[] =
    FILE_PATH_LITERAL("History");
const base::FilePath::CharType kTopSitesFilename[] =
    FILE_PATH_LITERAL("Top Sites");

const int kMaxTitleChanges = 10;

base::TimeDelta GetTitleSettingWindow() {
  const auto value = base::TimeDelta::FromSeconds(5);
  return value;
}

}  // namespace history


text: Gerrit plugin to send reminders to reviewers for timely completion/closing of open reviews


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration>
<configuration scan="true" scanPeriod="30 seconds" debug="false">

    <contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator">
        <!-- reset all previous level configurations of all j.u.l. loggers -->
        <resetJUL>true</resetJUL>
    </contextListener>

    <springProperty scope="context" name="loggingDir" source="logging.dir" defaultValue="strongbox-vault/logs"/>
    <springProperty scope="context" name="debug" source="logging.debug" defaultValue="false"/>

    <springProperty scope="context" name="console" source="logging.console.enabled" defaultValue="true"/>

    <springProperty scope="context" name="file" source="logging.file.enabled" defaultValue="true"/>
    <springProperty scope="context" name="loggingFile" source="logging.file" defaultValue="strongbox-vault/logs/strongbox.log"/>
    <springProperty scope="context" name="fileSizeSingle" source="logging.file.size.single" defaultValue="128MB"/>
    <springProperty scope="context" name="fileSizeTotal" source="logging.file.size.total" defaultValue="1GB"/>
    <springProperty scope="context" name="fileHisotry" source="logging.file.history" defaultValue="31"/>

    <if condition="${console:-true}">
    <then>
        <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
            <filter class="org.carlspring.strongbox.log.CronTaskContextDeclineFilter"/>
            <filter class="org.carlspring.strongbox.log.JaninoClassLoaderLogDeclineFilter"/>

            <encoder>
                <pattern>%d{HH:mm:ss.SSS dd-MM-yyyy} | %-5.5p | %-20.20t | %-50.50logger{50} | %m%n</pattern>
            </encoder>
        </appender>
        <root>
            <appender-ref ref="CONSOLE"/>
        </root>
    </then>
    </if>

    <if condition="${file:-true}">
    <then>
        <appender name="FILE"
            class="ch.qos.logback.core.rolling.RollingFileAppender">
            <filter class="org.carlspring.strongbox.log.CronTaskContextDeclineFilter"/>
            <filter class="org.carlspring.strongbox.log.JaninoClassLoaderLogDeclineFilter"/>

            <file>${loggingFile}</file>
            <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
                <fileNamePattern>${loggingDir}/strongbox-%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
                <maxFileSize>${fileSizeSingle}</maxFileSize>
                <maxHistory>${fileHistory}</maxHistory>
                <totalSizeCap>${fileSizeTotal}</totalSizeCap>
            </rollingPolicy>

            <encoder>
                <charset>UTF-8</charset>
                <pattern>%d{HH:mm:ss.SSS dd-MM-yyyy} | %-5.5p | %-20.20t | %-50.50logger{50} | %m%n</pattern>
            </encoder>
        </appender>

        <appender name="CRON-JOB-FILE" class="ch.qos.logback.classic.sift.SiftingAppender">

            <discriminator
                class="ch.qos.logback.classic.sift.MDCBasedDiscriminator">
                <key>strongbox-cron-context-name</key>
                <defaultValue>strongbox-empty-cron-job</defaultValue>
            </discriminator>
            <sift>
                <appender name="CRON-JOB-CONTEXT-SIFT-FILE-APPENDER"
                    class="ch.qos.logback.core.rolling.RollingFileAppender">
                    <filter class="org.carlspring.strongbox.log.CronTaskContextAcceptFilter"/>
                    <filter class="org.carlspring.strongbox.log.JaninoClassLoaderLogDeclineFilter"/>

                    <file>${loggingDir}/${strongbox-cron-context-name}/${strongbox-cron-context-name}.log</file>
                    <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
                        <fileNamePattern>${loggingDir}/${strongbox-cron-context-name}/${strongbox-cron-context-name}-%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
                        <maxFileSize>${fileSizeSingle}</maxFileSize>
                        <maxHistory>${fileHistory}</maxHistory>
                        <totalSizeCap>${fileSizeTotal}</totalSizeCap>
                    </rollingPolicy>

                    <encoder>
                        <charset>UTF-8</charset>
                        <pattern>%d{HH:mm:ss.SSS dd-MM-yyyy} | %-5.5p | %-20.20t | %-50.50logger{50} | %m%n</pattern>
                    </encoder>
                </appender>
            </sift>
        </appender>
        <root>
            <appender-ref ref="FILE"/>
            <appender-ref ref="CRON-JOB-FILE"/>
        </root>
    </then>
    </if>

    <if condition="${debug:-false}">
    <then>
        <!-- ApacheDS: Used for testing -->
        <logger name="org.apache.directory" level="ERROR"/>
        <logger name="org.apache.mina" level="ERROR"/>
        <logger name="JdbmTable" level="ERROR"/>
        <logger name="JdbmIndex" level="ERROR"/>
        <logger name="LOG_CHANGES" level="ERROR"/>
        <!-- ApacheDS -->

        <!-- Strongbox packages -->
        <logger name="org.carlspring.strongbox" level="DEBUG"/>
        <logger name="org.carlspring.strongbox.security.authentication" level="DEBUG"/>
        <logger name="org.carlspring.strongbox.security.vote" level="DEBUG"/>
        <logger name="org.carlspring.strongbox.data" level="WARN"/>
        <logger name="org.carlspring.strongbox.data.tx" level="WARN"/>
        <logger name="org.carlspring.strongbox.data.criteria" level="DEBUG"/>
        <logger name="org.carlspring.strongbox.data.server" level="DEBUG"/>
        <!-- Strongbox packages -->

        <!-- Third-party packages -->
        <logger name="ch.qos.logback" level="ERROR"/>

        <logger name="com.orientechnologies.orient" level="ERROR"/>

        <logger name="org.apache.commons.beanutils" level="ERROR"/>
        <logger name="org.apache.http" level="ERROR"/>

        <logger name="org.glassfish.jersey" level="ERROR"/>

        <logger name="org.quartz" level="INFO"/>

        <logger name="org.reflections" level="ERROR"/>

        <logger name="org.springframework" level="ERROR"/>
        <logger name="org.springframework.web" level="DEBUG"/>

        <logger name="com.hazelcast" level="INFO"/>

        <logger name="org.springframework.cache" level="TRACE"/>

        <logger name ="org.eclipse.jetty" level="INFO" />
        <logger name ="jndi"  level="INFO" />

        <logger name ="liquibase.parser.core.xml"  level="INFO" />
        <logger name ="javax.xml.bind" level="INFO" />
        <logger name="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" level="DEBUG" />
        <!-- Third-party packages -->

        <root level="DEBUG"/>
    </then>
    <else>
        <!-- Strongbox packages -->
        <logger name="org.carlspring.strongbox" level="INFO"/>
        <logger name="org.carlspring.strongbox.security.authentication" level="INFO"/>
        <logger name="org.carlspring.strongbox.security.vote" level="INFO"/>
        <logger name="org.carlspring.strongbox.data" level="WARN"/>
        <logger name="org.carlspring.strongbox.data.tx" level="WARN"/>
        <logger name="org.carlspring.strongbox.data.criteria" level="INFO"/>
        <logger name="org.carlspring.strongbox.data.server" level="INFO"/>
        <!-- Strongbox packages -->

        <!-- Third-party packages -->
        <logger name="liquibase" level="WARN"/>

        <logger name="ch.qos.logback" level="ERROR"/>

        <logger name="com.orientechnologies.orient" level="ERROR"/>

        <logger name="org.apache.commons.beanutils" level="ERROR"/>
        <logger name="org.apache.http" level="ERROR"/>

        <logger name="org.glassfish.jersey" level="ERROR"/>

        <logger name="org.quartz" level="INFO"/>

        <logger name="org.reflections" level="ERROR"/>

        <logger name="org.springframework" level="ERROR"/>
        <logger name="org.springframework.web" level="INFO"/>

        <logger name ="org.eclipse.jetty" level="INFO" />
        <logger name ="jndi"  level="INFO" />

        <logger name ="liquibase.parser.core.xml"  level="INFO" />
        <logger name ="javax.xml.bind" level="INFO" />
        <logger name="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" level="INFO" />
        <!-- Third-party packages -->

        <root level="INFO"/>
    </else>
    </if>

</configuration>


text:
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height" />
        <title>File API</title>
    </head>
    <body>
        Hello, assuming all's well, the prompts will appear saying a file has been written with some json...
        <script type="text/javascript" src="cordova.js"></script>
        <script type="text/javascript" src="filePersist.js"></script>
        <script type="text/javascript" src="index.js"></script>
    </body>
</html>


text:
{{ .Site.Params.counters.title | markdownify }}

			{{ range .Site.Params.counters.item }}

						{{ .to }}
						{{ .description }}

			{{ end }}


text:
'use strict';

var requiredFunc = require( '../lib/types' ).requiredFunc;

module.exports = {

    on:       requiredFunc,

    emit:     requiredFunc,

    status:   requiredFunc,

    id:       requiredFunc,

    stream:   requiredFunc,

    init:     requiredFunc,

    start:    requiredFunc,

    stop:     requiredFunc,

    restart:  requiredFunc,

    uiConfig: requiredFunc,

    settings: requiredFunc,

    format:         requiredFunc,

    updateSettings: requiredFunc,

    fetchSettings:  requiredFunc,

    setSetting:     requiredFunc,

    onAuth:         requiredFunc,

    moduleName:     requiredFunc,

    name: {
      type: 'string'
    }

};


text:
CC		= gcc -g -Wall
CFLAGS		= -O2
PROG		= timerbench usleepbench timedwait
LDFLAGS		= -lpthread

all:		$(PROG)

clean:
		rm -rf *~ *.o timerbench cbench randbench usleepbench timedwait *.dSYM


text:
/* global describe:true it:true */
/* eslint-disable prefer-arrow-callback */
/* eslint-disable max-nested-callbacks */
/* eslint-disable no-unused-expressions */
import { Map, OrderedSet } from 'immutable';
import { expect } from 'chai';
import Series from './Series';
import Point from './Point';

const seriesAttributes = {
  id: 'GOOGL',
}

const pointPayload = [
  { myBandKey: 5, value: 10 },
  { myBandKey: 3, value: 6 },
];

const pointDimensions = {
  x: 'myBandKey',
  y: 'value',
};

const fancyPayload = [{ myX: 1, doubleY: 2 }];
const fancyDimensions = { x: 'myX', y: (it) => (it.get('doubleY') / 2) };

describe('Types: Series', () => {
  const s = Series.fromPayload(seriesAttributes, pointPayload, pointDimensions);
  describe('#fromPayload()', () => {
    it('returns a series', () => {
      expect(s).to.be.instanceOf(Series);
    });
    it('initializes .data as an Map of points', () => {
      expect(s.data).to.be.instanceOf(Map);
      expect(s.data.first()).to.be.instanceOf(Point);
    });
    it('sets keys to x dimension of points', () => {
      expect(s.data.first().x).to.equal(3);
    });
    it('supports fancy transforms for dimensions', () => {
      const fancyS = Series.fromPayload(seriesAttributes, fancyPayload, fancyDimensions)
      expect(fancyS.data.first().x).to.equal(1);
      expect(fancyS.data.first().y).to.equal(1);
    })
  });

  describe('#at()', () => {
    it('Gets data for a given band', () => {
      expect(s.at(3).y).to.equal(6);
    });
    it('Gets an empty point when accessing nonexistant index', () => {
      expect(s.at(4)).to.eql(new Point());
    });
  })

  describe('#bands, #addBands()', () => {
    const s1 = s.addBands(OrderedSet.of(11));
    it('Provides getter for current bands', () => {
      expect(s.bands).to.eql(OrderedSet.of(3, 5));
    });
    it('Adds dummy points in empty bands through #addBands()', () => {
      expect(s1.size).to.equal(3);
      expect(s1.at(11).y).to.equal(0);
    });
  });

  describe('#equals()', () => {
    const s1 = Series.fromPayload(seriesAttributes, pointPayload, pointDimensions);
    it('considers two series with same data and attributes as equal', function() {
      expect(s.equals(s1)).to.be.true;
    });
  })

  describe('#segments', () => {
    const s1 = s.addBands(OrderedSet.of(11, 13));
    it('Returns subsets containing contiguous non-dummy Points', () => {
      expect(s1.segments).to.have.length.of(1);
      expect(s1.segments[0]).to.have.length.of(2);
    });
  });

});


text:
namespace browser_sync {

HistoryDeleteDirectivesDataTypeController::
    HistoryDeleteDirectivesDataTypeController(
        const scoped_refptr<base::SingleThreadTaskRunner>& ui_thread,
        const base::Closure& error_callback,
        sync_driver::SyncClient* sync_client)
    : sync_driver::UIDataTypeController(ui_thread,
                                        error_callback,
                                        syncer::HISTORY_DELETE_DIRECTIVES,
                                        sync_client),
      sync_client_(sync_client) {}

HistoryDeleteDirectivesDataTypeController::
    ~HistoryDeleteDirectivesDataTypeController() {
}

bool HistoryDeleteDirectivesDataTypeController::ReadyForStart() const {
  return !sync_client_->GetSyncService()->IsEncryptEverythingEnabled();
}

bool HistoryDeleteDirectivesDataTypeController::StartModels() {
  if (DisableTypeIfNecessary())
    return false;
  sync_client_->GetSyncService()->AddObserver(this);
  return true;
}

void HistoryDeleteDirectivesDataTypeController::StopModels() {
  if (sync_client_->GetSyncService()->HasObserver(this))
    sync_client_->GetSyncService()->RemoveObserver(this);
}

void HistoryDeleteDirectivesDataTypeController::OnStateChanged() {
  DisableTypeIfNecessary();
}

bool HistoryDeleteDirectivesDataTypeController::DisableTypeIfNecessary() {
  if (!sync_client_->GetSyncService()->IsSyncActive())
    return false;

  if (ReadyForStart())
    return false;

  if (sync_client_->GetSyncService()->HasObserver(this))
    sync_client_->GetSyncService()->RemoveObserver(this);
  syncer::SyncError error(
      FROM_HERE,
      syncer::SyncError::DATATYPE_POLICY_ERROR,
      "Delete directives not supported with encryption.",
      type());
  OnSingleDataTypeUnrecoverableError(error);
  return true;
}

}  // namespace browser_sync


text:
<?xml version="1.0" encoding="utf-8"?>

<set xmlns:android="http://schemas.android.com/apk/res/android">

    <alpha android:fromAlpha="1.0"
        android:toAlpha="0.0"
        android:interpolator="@android:anim/accelerate_decelerate_interpolator"
        android:duration="300"
        android:repeatCount="0"/>

    <translate android:fromYDelta="0"
        android:toYDelta="700"
        android:duration="300"
        android:interpolator="@android:anim/accelerate_decelerate_interpolator"
        android:repeatCount="0"
        />

</set>


text:
<?php

namespace FSi\Bundle\GalleryBundle\Model;

interface GalleryManagerInterface
{
    /**
     * @param int $id
     * @return GalleryInterface
     */
    public function findGallery($id);

    /**
     * @return \Pagerfanta\Adapter\AdapterInterface
     */
    public function createPagerfantaAdapter();
}


text:
package com.paypal.risk.hadoopjt.util

import org.jsoup.Jsoup
import scala.io.Source

/**
 * Helper class for testing
 */
object NetUtilsTest {

  def getTidyHtmlFromFile(path: String) = {
    if(path.endsWith("jobtracker.jsp")){
    	Jsoup.parse(Source.fromFile("src/test/resources/jobtracker.jsp").mkString).html
    }else if(path.endsWith("scheduler")){
    	Jsoup.parse(Source.fromFile("src/test/resources/scheduler").mkString).html
    }else if(path.endsWith("jobqueue_details.jsp")){
    	Jsoup.parse(Source.fromFile("src/test/resources/jobqueue_details.jsp").mkString).html
    }else{
    	Jsoup.parse(Source.fromFile("src/test/resources/jobdetails.jsp").mkString).html
    }
  }

  def mockHttpGet(url:String): String ={
    if (url.endsWith("ws/v1/cluster/apps")){
      Source.fromFile("src/test/resources/rm_applications.json").mkString
    }else{
      null
    }

  }

}


text:
var MAX_MESSAGE_SIZE = 1088
var MINIMAL_PADDING = 16
var HEADER_SIZE = 48
var MESSAGE_BODY = MAX_MESSAGE_SIZE - HEADER_SIZE - MINIMAL_PADDING

var MAX_OUTGOING = 128
var MAX_INCOMING = 64

var MAXIMUM_UNPROCESSED_SEND_BYTES = 1024 * 1024

var MILLISECOND = 1000000
var SECOND = MILLISECOND * 1000

var MAX_SECONDS_IN_DURATION = (Number.MAX_SAFE_INTEGER / SECOND) - 1

var MAX_RETRANSMISSIONS = 15

module.exports = {
  MAX_MESSAGE_SIZE: MAX_MESSAGE_SIZE,
  MINIMAL_PADDING: MINIMAL_PADDING,
  HEADER_SIZE: HEADER_SIZE,
  MESSAGE_BODY: MESSAGE_BODY,
  MAX_OUTGOING: MAX_OUTGOING,
  MAX_INCOMING: MAX_INCOMING,
  MAXIMUM_UNPROCESSED_SEND_BYTES: MAXIMUM_UNPROCESSED_SEND_BYTES,
  MILLISECOND: MILLISECOND,
  SECOND: SECOND,
  MAX_SECONDS_IN_DURATION: MAX_SECONDS_IN_DURATION,
  MAX_RETRANSMISSIONS: MAX_RETRANSMISSIONS
}


text:
UPDATE mysql.user SET {{cfg.password_column_name}}=PASSWORD('{{cfg.root_password}}'), password_expired='N', host='127.0.0.1' WHERE user = 'root';
DELETE FROM mysql.user WHERE USER LIKE '';
DELETE FROM mysql.user WHERE user = 'root' and host NOT IN ('127.0.0.1', 'localhost');
{{#if cfg.app_username}}
CREATE USER '{{cfg.app_username}}'@'%' IDENTIFIED BY '{{cfg.app_password}}';
GRANT ALL PRIVILEGES ON *.* TO '{{cfg.app_username}}'@'%';
{{/if}}
FLUSH PRIVILEGES;
DELETE FROM mysql.db WHERE db LIKE 'test%';
DROP DATABASE IF EXISTS test ;


text:
HelpString:

db 'TEST_PPU_READ_BUFFER -- Secret Reference Emulation Mode',13,10
db 'Commandline options:',13,10
db '  /D',9,'Do disassembly trace (note: does not set /T automatically)',13,10
db '  /T',9,'Text only: Do not do graphics mode',13,10
db '  /P',9,'Palette only: No NTSC simulation, no borders, no correct aspect ratio',13,10
db '  /M',9,'Mode-X only: Do not use VESA to provide NTSC in RGB32 without dithering',13,10
db '  /H,/?',9,'This help',13,10
db 10
db "The assembler trace, and the test ROM's console output, will",13,10
db 'both be output to STDOUT. Suggest redirecting with "> file.txt".',13,10
db 10
db 'I.e. like this: program /D /T > trace.log', 13,10
db 10
db 'If you do not redirect the output, there will be minor artifacts on the',13,10
db 'screen while the test runs; this is because the text is rendered on the',13,10
db 'graphical screen, but the BIOS does not support the Mode-X graphics used.',13,10
db 10
db 'Thank you for using this self-testing NES emulator.',13,10
db 'Written in April 2012 by Joel Yliluoma - http://iki.fi/bisqwit/',13,10
db 10
db 'P.S. Load any sub-40k NROM/CNROM/GxROM cart with :filename',13,10
db 0