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

package org.openqa.selenium.interactions;

import org.openqa.selenium.interactions.internal.MouseAction;
import org.openqa.selenium.internal.Locatable;

import java.util.Arrays;
import java.util.List;

/**
 * clicks an element.
 *
 */
public class ClickAction extends MouseAction implements Action {
  public ClickAction(Mouse mouse, Locatable locationProvider) {
    super(mouse, locationProvider);
  }

  public void perform() {
    moveToLocation();
    mouse.click(getActionLocation());
  }

  public List<Object> asList() {
    return Arrays.<Object>asList("click", getTargetId(), Button.LEFT, 1);
  }
}


text:
set -eu

echo "Run dotfiles init scripts.\n"

for file in `ls -1 ./init/*.zsh`; do
    echo "Load : ${file}"
    source ${file}
    echo "Loaded : ${file}\n"
done

echo "Loaded init scripts."

redpajama_set_name: RedPajamaGithub


text:
package secret

import (
	"crypto/subtle"
	"fmt"
	"testing"

	"github.com/mailgun/lemma/random"
)

var _ = fmt.Printf // for testing

func TestEncryptDecryptCycle(t *testing.T) {
	randomProvider = &random.FakeRNG{}

	key, err := NewKey()
	if err != nil {
		t.Errorf("Got unexpected response from NewKey: %v", err)
	}

	s, err := New(&Config{KeyBytes: key})
	if err != nil {
		t.Errorf("Got unexpected response from NewWithKeyBytes: %v", err)
	}

	message := []byte("hello, box!")
	sealed, err := s.Seal(message)
	if err != nil {
		t.Errorf("Got unexpected response from Seal: %v", err)
	}

	out, err := s.Open(sealed)
	if err != nil {
		t.Errorf("Got unexpected response from Open: %v", err)
	}

	// compare the messages
	if subtle.ConstantTimeCompare(message, out) != 1 {
		t.Errorf("Contents do not match: %v, %v", message, out)
	}
}

func TestEncryptDecryptCyclePackage(t *testing.T) {
	randomProvider = &random.FakeRNG{}

	key, err := NewKey()
	if err != nil {
		t.Errorf("Got unexpected response from NewKey: %v", err)
	}

	message := []byte("hello, box!")
	sealed, err := Seal(message, key)
	if err != nil {
		t.Errorf("Got unexpected response from Seal: %v", err)
	}

	out, err := Open(sealed, key)
	if err != nil {
		t.Errorf("Got unexpected response from Open: %v", err)
	}

	// compare the messages
	if subtle.ConstantTimeCompare(message, out) != 1 {
		t.Errorf("Contents do not match: %v, %v", message, out)
	}
}


text:
@class SChartOHLCSeriesStyle;

@interface SChartLegendSymbolOHLCSeries : SChartLegendSymbol
{
    SChartOHLCSeriesStyle *style;
}

@property(readonly, nonatomic) SChartOHLCSeriesStyle *style; // @synthesize style;
- (void)drawRect:(struct CGRect)arg1;
- (void)dealloc;
- (id)initWithSeries:(id)arg1;

@end


text:
import unittest

import vdb.stalker as v_stalker
import vtrace.tests as vt_tests

breakpoints = {
    'windows':'ntdll.NtTerminateProcess',
    'linux':'libc.exit',
    'freebsd':'libc.exit',
}

class VdbStalkerTest(vt_tests.VtraceProcessTest):

    def test_vdb_stalker(self):
        plat = self.trace.getMeta('Platform')
        symname = breakpoints.get( plat )

        entry = self.trace.parseExpression(symname)
        v_stalker.addStalkerEntry(self.trace, entry)

        self.runUntilExit()
        self.assertTrue( v_stalker.getStalkerHits(self.trace) > 2)


text:
// Copyright (c) Christof Senn. All rights reserved. See license.txt in the project root for license information.

namespace Aqua.ProtoBuf
{
    using Aqua.Dynamic;
    using Aqua.EnumerableExtensions;
    using Aqua.ProtoBuf.Dynamic;
    using Aqua.TypeSystem;
    using global::ProtoBuf;
    using System;
    using System.Diagnostics.CodeAnalysis;

    [ProtoContract]
    [ProtoInclude(1, typeof(Values))]
    [ProtoInclude(2, typeof(NullValue))]
    [ProtoInclude(3, typeof(EmptyArray))]
    public abstract class Value
    {
        [ProtoIgnore]
        public virtual object? ObjectValue { get; protected set; }

        [return: NotNullIfNotNull("value")]
        public static Value? Wrap(object? value) => Wrap(value, null);

        [return: NotNullIfNotNull("value")]
        internal static Value? Wrap(object? value, Type? type)
            => value is null
            ? null
            : value is Value v
            ? v
            : value is DynamicObject dynamicObject
            ? new Value<DynamicObjectSurrogate>(DynamicObjectSurrogate.Convert(dynamicObject))
            : value.IsCollection(out var collection)
            ? Values.Wrap(collection!, TypeHelper.GetElementType(type) ?? TypeHelper.GetElementType(collection.GetType()))
            : (Value?)Activator.CreateInstance(typeof(Value<>).MakeGenericType(value.GetType()), new[] { value });

        [return: NotNullIfNotNull("value")]
        public static object? Unwrap(Value? value)
            => value is null || value is NullValue
            ? null
            : value is EmptyArray
            ? Array.Empty<object>()
            : value is Value<DynamicObjectSurrogate> dynamicObject
            ? DynamicObjectSurrogate.Convert(dynamicObject.TypedValue)
            : value is Values values
            ? Values.Unwrap(values)
            : value.ObjectValue;
    }
}


text:
#define LOG_TAG "RefBase"
// #define LOG_NDEBUG 0

#include <memory>

#include <android-base/macros.h>

#include <log/log.h>

#include <utils/RefBase.h>

#include <utils/Mutex.h>

#ifndef __unused
#define __unused __attribute__((__unused__))
#endif

// Compile with refcounting debugging enabled.
#define DEBUG_REFS 0

// The following three are ignored unless DEBUG_REFS is set.

// whether ref-tracking is enabled by default, if not, trackMe(true, false)
// needs to be called explicitly
#define DEBUG_REFS_ENABLED_BY_DEFAULT 0

// whether callstack are collected (significantly slows things down)
#define DEBUG_REFS_CALLSTACK_ENABLED 1

// folder where stack traces are saved when DEBUG_REFS is enabled
// this folder needs to exist and be writable
#define DEBUG_REFS_CALLSTACK_PATH "/data/debug"

// log all reference counting operations
#define PRINT_REFS 0

// Continue after logging a stack trace if ~RefBase discovers that reference
// count has never been incremented. Normally we conspicuously crash in that
// case.
#define DEBUG_REFBASE_DESTRUCTION 1

#if !defined(_WIN32) && !defined(__APPLE__)
// CallStack is only supported on linux type platforms.
#define CALLSTACK_ENABLED 1
#else
#define CALLSTACK_ENABLED 0
#endif

#if CALLSTACK_ENABLED
#include <utils/CallStack.h>
#endif

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

namespace android {

// Observations, invariants, etc:

// By default, obects are destroyed when the last strong reference disappears
// or, if the object never had a strong reference, when the last weak reference
// disappears.
//
// OBJECT_LIFETIME_WEAK changes this behavior to retain the object
// unconditionally until the last reference of either kind disappears.  The
// client ensures that the extendObjectLifetime call happens before the dec
// call that would otherwise have deallocated the object, or before an
// attemptIncStrong call that might rely on it.  We do not worry about
// concurrent changes to the object lifetime.
//
// AttemptIncStrong will succeed if the object has a strong reference, or if it
// has a weak reference and has never had a strong reference.
// AttemptIncWeak really does succeed only if there is already a WEAK
// reference, and thus may fail when attemptIncStrong would succeed.
//
// mStrong is the strong reference count.  mWeak is the weak reference count.
// Between calls, and ignoring memory ordering effects, mWeak includes strong
// references, and is thus >= mStrong.
//
// A weakref_impl holds all the information, including both reference counts,
// required to perform wp<> operations.  Thus these can continue to be performed
// after the RefBase object has been destroyed.
//
// A weakref_impl is allocated as the value of mRefs in a RefBase object on
// construction.
// In the OBJECT_LIFETIME_STRONG case, it is normally deallocated in decWeak,
// and hence lives as long as the last weak reference. (It can also be
// deallocated in the RefBase destructor iff the strong reference count was
// never incremented and the weak count is zero, e.g.  if the RefBase object is
// explicitly destroyed without decrementing the strong count.  This should be
// avoided.) In this case, the RefBase destructor should be invoked from
// decStrong.
// In the OBJECT_LIFETIME_WEAK case, the weakref_impl is always deallocated in
// the RefBase destructor, which is always invoked by decWeak. DecStrong
// explicitly avoids the deletion in this case.
//
// Memory ordering:
// The client must ensure that every inc() call, together with all other
// accesses to the object, happens before the corresponding dec() call.
//
// We try to keep memory ordering constraints on atomics as weak as possible,
// since memory fences or ordered memory accesses are likely to be a major
// performance cost for this code. All accesses to mStrong, mWeak, and mFlags
// explicitly relax memory ordering in some way.
//
// The only operations that are not memory_order_relaxed are reference count
// decrements. All reference count decrements are release operations.  In
// addition, the final decrement leading the deallocation is followed by an
// acquire fence, which we can view informally as also turning it into an
// acquire operation.  (See 29.8p4 [atomics.fences] for details. We could
// alternatively use acq_rel operations for all decrements. This is probably
// slower on most current (2016) hardware, especially on ARMv7, but that may
// not be true indefinitely.)
//
// This convention ensures that the second-to-last decrement synchronizes with
// (in the language of 1.10 in the C++ standard) the final decrement of a
// reference count. Since reference counts are only updated using atomic
// read-modify-write operations, this also extends to any earlier decrements.
// (See "release sequence" in 1.10.)
//
// Since all operations on an object happen before the corresponding reference
// count decrement, and all reference count decrements happen before the final
// one, we are guaranteed that all other object accesses happen before the
// object is destroyed.

#define INITIAL_STRONG_VALUE (1<<28)

#define MAX_COUNT 0xfffff

// Test whether the argument is a clearly invalid strong reference count.
// Used only for error checking on the value before an atomic decrement.
// Intended to be very cheap.
// Note that we cannot just check for excess decrements by comparing to zero
// since the object would be deallocated before that.
#define BAD_STRONG(c) \
        ((c) == 0 || ((c) & (~(MAX_COUNT | INITIAL_STRONG_VALUE))) != 0)

// Same for weak counts.
#define BAD_WEAK(c) ((c) == 0 || ((c) & (~MAX_COUNT)) != 0)

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

class RefBase::weakref_impl : public RefBase::weakref_type
{
public:
    std::atomic<int32_t>    mStrong;
    std::atomic<int32_t>    mWeak;
    RefBase* const          mBase;
    std::atomic<int32_t>    mFlags;

#if !DEBUG_REFS

    explicit weakref_impl(RefBase* base)
        : mStrong(INITIAL_STRONG_VALUE)
        , mWeak(0)
        , mBase(base)
        , mFlags(0)
    {
    }

    void addStrongRef(const void* /*id*/) { }
    void removeStrongRef(const void* /*id*/) { }
    void renameStrongRefId(const void* /*old_id*/, const void* /*new_id*/) { }
    void addWeakRef(const void* /*id*/) { }
    void removeWeakRef(const void* /*id*/) { }
    void renameWeakRefId(const void* /*old_id*/, const void* /*new_id*/) { }
    void printRefs() const { }
    void trackMe(bool, bool) { }

#else

    weakref_impl(RefBase* base)
        : mStrong(INITIAL_STRONG_VALUE)
        , mWeak(0)
        , mBase(base)
        , mFlags(0)
        , mStrongRefs(NULL)
        , mWeakRefs(NULL)
        , mTrackEnabled(!!DEBUG_REFS_ENABLED_BY_DEFAULT)
        , mRetain(false)
    {
    }

    ~weakref_impl()
    {
        bool dumpStack = false;
        if (!mRetain && mStrongRefs != NULL) {
            dumpStack = true;
            ALOGE("Strong references remain:");
            ref_entry* refs = mStrongRefs;
            while (refs) {
                char inc = refs->ref >= 0 ? '+' : '-';
                ALOGD("\t%c ID %p (ref %d):", inc, refs->id, refs->ref);
#if DEBUG_REFS_CALLSTACK_ENABLED && CALLSTACK_ENABLED
                CallStack::logStack(LOG_TAG, refs->stack.get());
#endif
                refs = refs->next;
            }
        }

        if (!mRetain && mWeakRefs != NULL) {
            dumpStack = true;
            ALOGE("Weak references remain!");
            ref_entry* refs = mWeakRefs;
            while (refs) {
                char inc = refs->ref >= 0 ? '+' : '-';
                ALOGD("\t%c ID %p (ref %d):", inc, refs->id, refs->ref);
#if DEBUG_REFS_CALLSTACK_ENABLED && CALLSTACK_ENABLED
                CallStack::logStack(LOG_TAG, refs->stack.get());
#endif
                refs = refs->next;
            }
        }
        if (dumpStack) {
            ALOGE("above errors at:");
#if CALLSTACK_ENABLED
            CallStack::logStack(LOG_TAG);
#endif
        }
    }

    void addStrongRef(const void* id) {
        //ALOGD_IF(mTrackEnabled,
        //        "addStrongRef: RefBase=%p, id=%p", mBase, id);
        addRef(&mStrongRefs, id, mStrong.load(std::memory_order_relaxed));
    }

    void removeStrongRef(const void* id) {
        //ALOGD_IF(mTrackEnabled,
        //        "removeStrongRef: RefBase=%p, id=%p", mBase, id);
        if (!mRetain) {
            removeRef(&mStrongRefs, id);
        } else {
            addRef(&mStrongRefs, id, -mStrong.load(std::memory_order_relaxed));
        }
    }

    void renameStrongRefId(const void* old_id, const void* new_id) {
        //ALOGD_IF(mTrackEnabled,
        //        "renameStrongRefId: RefBase=%p, oid=%p, nid=%p",
        //        mBase, old_id, new_id);
        renameRefsId(mStrongRefs, old_id, new_id);
    }

    void addWeakRef(const void* id) {
        addRef(&mWeakRefs, id, mWeak.load(std::memory_order_relaxed));
    }

    void removeWeakRef(const void* id) {
        if (!mRetain) {
            removeRef(&mWeakRefs, id);
        } else {
            addRef(&mWeakRefs, id, -mWeak.load(std::memory_order_relaxed));
        }
    }

    void renameWeakRefId(const void* old_id, const void* new_id) {
        renameRefsId(mWeakRefs, old_id, new_id);
    }

    void trackMe(bool track, bool retain) {
        mTrackEnabled = track;
        mRetain = retain;
    }

    void printRefs() const
    {
        String8 text;

        {
            Mutex::Autolock _l(mMutex);
            char buf[128];
            snprintf(buf, sizeof(buf),
                     "Strong references on RefBase %p (weakref_type %p):\n",
                     mBase, this);
            text.append(buf);
            printRefsLocked(&text, mStrongRefs);
            snprintf(buf, sizeof(buf),
                     "Weak references on RefBase %p (weakref_type %p):\n",
                     mBase, this);
            text.append(buf);
            printRefsLocked(&text, mWeakRefs);
        }

        {
            char name[100];
            snprintf(name, sizeof(name), DEBUG_REFS_CALLSTACK_PATH "/%p.stack",
                     this);
            int rc = open(name, O_RDWR | O_CREAT | O_APPEND, 644);
            if (rc >= 0) {
                (void)write(rc, text.string(), text.length());
                close(rc);
                ALOGD("STACK TRACE for %p saved in %s", this, name);
            }
            else ALOGE("FAILED TO PRINT STACK TRACE for %p in %s: %s", this,
                      name, strerror(errno));
        }
    }

private:
    struct ref_entry
    {
        ref_entry* next;
        const void* id;
#if DEBUG_REFS_CALLSTACK_ENABLED && CALLSTACK_ENABLED
        CallStack::CallStackUPtr stack;
#endif
        int32_t ref;
    };

    void addRef(ref_entry** refs, const void* id, int32_t mRef)
    {
        if (mTrackEnabled) {
            AutoMutex _l(mMutex);

            ref_entry* ref = new ref_entry;
            // Reference count at the time of the snapshot, but before the
            // update.  Positive value means we increment, negative--we
            // decrement the reference count.
            ref->ref = mRef;
            ref->id = id;
#if DEBUG_REFS_CALLSTACK_ENABLED && CALLSTACK_ENABLED
            ref->stack = CallStack::getCurrent(2);
#endif
            ref->next = *refs;
            *refs = ref;
        }
    }

    void removeRef(ref_entry** refs, const void* id)
    {
        if (mTrackEnabled) {
            AutoMutex _l(mMutex);

            ref_entry* const head = *refs;
            ref_entry* ref = head;
            while (ref != NULL) {
                if (ref->id == id) {
                    *refs = ref->next;
                    delete ref;
                    return;
                }
                refs = &ref->next;
                ref = *refs;
            }

            ALOGE("RefBase: removing id %p on RefBase %p"
                    "(weakref_type %p) that doesn't exist!",
                    id, mBase, this);

            ref = head;
            while (ref) {
                char inc = ref->ref >= 0 ? '+' : '-';
                ALOGD("\t%c ID %p (ref %d):", inc, ref->id, ref->ref);
                ref = ref->next;
            }

#if CALLSTACK_ENABLED
            CallStack::logStack(LOG_TAG);
#endif
        }
    }

    void renameRefsId(ref_entry* r, const void* old_id, const void* new_id)
    {
        if (mTrackEnabled) {
            AutoMutex _l(mMutex);
            ref_entry* ref = r;
            while (ref != NULL) {
                if (ref->id == old_id) {
                    ref->id = new_id;
                }
                ref = ref->next;
            }
        }
    }

    void printRefsLocked(String8* out, const ref_entry* refs) const
    {
        char buf[128];
        while (refs) {
            char inc = refs->ref >= 0 ? '+' : '-';
            snprintf(buf, sizeof(buf), "\t%c ID %p (ref %d):\n",
                     inc, refs->id, refs->ref);
            out->append(buf);
#if DEBUG_REFS_CALLSTACK_ENABLED && CALLSTACK_ENABLED
            out->append(CallStack::stackToString("\t\t", refs->stack.get()));
#else
            out->append("\t\t(call stacks disabled)");
#endif
            refs = refs->next;
        }
    }

    mutable Mutex mMutex;
    ref_entry* mStrongRefs;
    ref_entry* mWeakRefs;

    bool mTrackEnabled;
    // Collect stack traces on addref and removeref, instead of deleting the stack references
    // on removeref that match the address ones.
    bool mRetain;

#endif
};

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

void RefBase::incStrong(const void* id) const
{
    weakref_impl* const refs = mRefs;
    refs->incWeak(id);

    refs->addStrongRef(id);
    const int32_t c = refs->mStrong.fetch_add(1, std::memory_order_relaxed);
    ALOG_ASSERT(c > 0, "incStrong() called on %p after last strong ref", refs);
#if PRINT_REFS
    ALOGD("incStrong of %p from %p: cnt=%d\n", this, id, c);
#endif
    if (c != INITIAL_STRONG_VALUE)  {
        return;
    }

    int32_t old __unused = refs->mStrong.fetch_sub(INITIAL_STRONG_VALUE, std::memory_order_relaxed);
    // A decStrong() must still happen after us.
    ALOG_ASSERT(old > INITIAL_STRONG_VALUE, "0x%x too small", old);
    refs->mBase->onFirstRef();
}

void RefBase::incStrongRequireStrong(const void* id) const {
    weakref_impl* const refs = mRefs;
    refs->incWeak(id);

    refs->addStrongRef(id);
    const int32_t c = refs->mStrong.fetch_add(1, std::memory_order_relaxed);

    LOG_ALWAYS_FATAL_IF(c <= 0 || c == INITIAL_STRONG_VALUE,
                        "incStrongRequireStrong() called on %p which isn't already owned", refs);
#if PRINT_REFS
    ALOGD("incStrong (requiring strong) of %p from %p: cnt=%d\n", this, id, c);
#endif
}

void RefBase::decStrong(const void* id) const
{
    weakref_impl* const refs = mRefs;
    refs->removeStrongRef(id);
    const int32_t c = refs->mStrong.fetch_sub(1, std::memory_order_release);
#if PRINT_REFS
    ALOGD("decStrong of %p from %p: cnt=%d\n", this, id, c);
#endif
    LOG_ALWAYS_FATAL_IF(BAD_STRONG(c), "decStrong() called on %p too many times",
            refs);
    if (c == 1) {
        std::atomic_thread_fence(std::memory_order_acquire);
        refs->mBase->onLastStrongRef(id);
        int32_t flags = refs->mFlags.load(std::memory_order_relaxed);
        if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
            delete this;
            // The destructor does not delete refs in this case.
        }
    }
    // Note that even with only strong reference operations, the thread
    // deallocating this may not be the same as the thread deallocating refs.
    // That's OK: all accesses to this happen before its deletion here,
    // and all accesses to refs happen before its deletion in the final decWeak.
    // The destructor can safely access mRefs because either it's deleting
    // mRefs itself, or it's running entirely before the final mWeak decrement.
    //
    // Since we're doing atomic loads of `flags`, the static analyzer assumes
    // they can change between `delete this;` and `refs->decWeak(id);`. This is
    // not the case. The analyzer may become more okay with this patten when
    // https://bugs.llvm.org/show_bug.cgi?id=34365 gets resolved. NOLINTNEXTLINE
    refs->decWeak(id);
}

void RefBase::forceIncStrong(const void* id) const
{
    // Allows initial mStrong of 0 in addition to INITIAL_STRONG_VALUE.
    // TODO: Better document assumptions.
    weakref_impl* const refs = mRefs;
    refs->incWeak(id);

    refs->addStrongRef(id);
    const int32_t c = refs->mStrong.fetch_add(1, std::memory_order_relaxed);
    ALOG_ASSERT(c >= 0, "forceIncStrong called on %p after ref count underflow",
               refs);
#if PRINT_REFS
    ALOGD("forceIncStrong of %p from %p: cnt=%d\n", this, id, c);
#endif

    switch (c) {
    case INITIAL_STRONG_VALUE:
        refs->mStrong.fetch_sub(INITIAL_STRONG_VALUE,
                std::memory_order_relaxed);
        FALLTHROUGH_INTENDED;
    case 0:
        refs->mBase->onFirstRef();
    }
}

int32_t RefBase::getStrongCount() const
{
    // Debugging only; No memory ordering guarantees.
    return mRefs->mStrong.load(std::memory_order_relaxed);
}

RefBase* RefBase::weakref_type::refBase() const
{
    return static_cast<const weakref_impl*>(this)->mBase;
}

void RefBase::weakref_type::incWeak(const void* id)
{
    weakref_impl* const impl = static_cast<weakref_impl*>(this);
    impl->addWeakRef(id);
    const int32_t c __unused = impl->mWeak.fetch_add(1,
            std::memory_order_relaxed);
    ALOG_ASSERT(c >= 0, "incWeak called on %p after last weak ref", this);
}

void RefBase::weakref_type::incWeakRequireWeak(const void* id)
{
    weakref_impl* const impl = static_cast<weakref_impl*>(this);
    impl->addWeakRef(id);
    const int32_t c __unused = impl->mWeak.fetch_add(1,
            std::memory_order_relaxed);
    LOG_ALWAYS_FATAL_IF(c <= 0, "incWeakRequireWeak called on %p which has no weak refs", this);
}

void RefBase::weakref_type::decWeak(const void* id)
{
    weakref_impl* const impl = static_cast<weakref_impl*>(this);
    impl->removeWeakRef(id);
    const int32_t c = impl->mWeak.fetch_sub(1, std::memory_order_release);
    LOG_ALWAYS_FATAL_IF(BAD_WEAK(c), "decWeak called on %p too many times",
            this);
    if (c != 1) return;
    atomic_thread_fence(std::memory_order_acquire);

    int32_t flags = impl->mFlags.load(std::memory_order_relaxed);
    if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
        // This is the regular lifetime case. The object is destroyed
        // when the last strong reference goes away. Since weakref_impl
        // outlives the object, it is not destroyed in the dtor, and
        // we'll have to do it here.
        if (impl->mStrong.load(std::memory_order_relaxed)
                == INITIAL_STRONG_VALUE) {
            // Decrementing a weak count to zero when object never had a strong
            // reference.  We assume it acquired a weak reference early, e.g.
            // in the constructor, and will eventually be properly destroyed,
            // usually via incrementing and decrementing the strong count.
            // Thus we no longer do anything here.  We log this case, since it
            // seems to be extremely rare, and should not normally occur. We
            // used to deallocate mBase here, so this may now indicate a leak.
            ALOGW("RefBase: Object at %p lost last weak reference "
                    "before it had a strong reference", impl->mBase);
        } else {
            // ALOGV("Freeing refs %p of old RefBase %p\n", this, impl->mBase);
            delete impl;
        }
    } else {
        // This is the OBJECT_LIFETIME_WEAK case. The last weak-reference
        // is gone, we can destroy the object.
        impl->mBase->onLastWeakRef(id);
        delete impl->mBase;
    }
}

bool RefBase::weakref_type::attemptIncStrong(const void* id)
{
    incWeak(id);

    weakref_impl* const impl = static_cast<weakref_impl*>(this);
    int32_t curCount = impl->mStrong.load(std::memory_order_relaxed);

    ALOG_ASSERT(curCount >= 0,
            "attemptIncStrong called on %p after underflow", this);

    while (curCount > 0 && curCount != INITIAL_STRONG_VALUE) {
        // we're in the easy/common case of promoting a weak-reference
        // from an existing strong reference.
        if (impl->mStrong.compare_exchange_weak(curCount, curCount+1,
                std::memory_order_relaxed)) {
            break;
        }
        // the strong count has changed on us, we need to re-assert our
        // situation. curCount was updated by compare_exchange_weak.
    }

    if (curCount <= 0 || curCount == INITIAL_STRONG_VALUE) {
        // we're now in the harder case of either:
        // - there never was a strong reference on us
        // - or, all strong references have been released
        int32_t flags = impl->mFlags.load(std::memory_order_relaxed);
        if ((flags&OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_STRONG) {
            // this object has a "normal" life-time, i.e.: it gets destroyed
            // when the last strong reference goes away
            if (curCount <= 0) {
                // the last strong-reference got released, the object cannot
                // be revived.
                decWeak(id);
                return false;
            }

            // here, curCount == INITIAL_STRONG_VALUE, which means
            // there never was a strong-reference, so we can try to
            // promote this object; we need to do that atomically.
            while (curCount > 0) {
                if (impl->mStrong.compare_exchange_weak(curCount, curCount+1,
                        std::memory_order_relaxed)) {
                    break;
                }
                // the strong count has changed on us, we need to re-assert our
                // situation (e.g.: another thread has inc/decStrong'ed us)
                // curCount has been updated.
            }

            if (curCount <= 0) {
                // promote() failed, some other thread destroyed us in the
                // meantime (i.e.: strong count reached zero).
                decWeak(id);
                return false;
            }
        } else {
            // this object has an "extended" life-time, i.e.: it can be
            // revived from a weak-reference only.
            // Ask the object's implementation if it agrees to be revived
            if (!impl->mBase->onIncStrongAttempted(FIRST_INC_STRONG, id)) {
                // it didn't so give-up.
                decWeak(id);
                return false;
            }
            // grab a strong-reference, which is always safe due to the
            // extended life-time.
            curCount = impl->mStrong.fetch_add(1, std::memory_order_relaxed);
            // If the strong reference count has already been incremented by
            // someone else, the implementor of onIncStrongAttempted() is holding
            // an unneeded reference.  So call onLastStrongRef() here to remove it.
            // (No, this is not pretty.)  Note that we MUST NOT do this if we
            // are in fact acquiring the first reference.
            if (curCount != 0 && curCount != INITIAL_STRONG_VALUE) {
                impl->mBase->onLastStrongRef(id);
            }
        }
    }

    impl->addStrongRef(id);

#if PRINT_REFS
    ALOGD("attemptIncStrong of %p from %p: cnt=%d\n", this, id, curCount);
#endif

    // curCount is the value of mStrong before we incremented it.
    // Now we need to fix-up the count if it was INITIAL_STRONG_VALUE.
    // This must be done safely, i.e.: handle the case where several threads
    // were here in attemptIncStrong().
    // curCount > INITIAL_STRONG_VALUE is OK, and can happen if we're doing
    // this in the middle of another incStrong.  The subtraction is handled
    // by the thread that started with INITIAL_STRONG_VALUE.
    if (curCount == INITIAL_STRONG_VALUE) {
        impl->mStrong.fetch_sub(INITIAL_STRONG_VALUE,
                std::memory_order_relaxed);
    }

    return true;
}

bool RefBase::weakref_type::attemptIncWeak(const void* id)
{
    weakref_impl* const impl = static_cast<weakref_impl*>(this);

    int32_t curCount = impl->mWeak.load(std::memory_order_relaxed);
    ALOG_ASSERT(curCount >= 0, "attemptIncWeak called on %p after underflow",
               this);
    while (curCount > 0) {
        if (impl->mWeak.compare_exchange_weak(curCount, curCount+1,
                std::memory_order_relaxed)) {
            break;
        }
        // curCount has been updated.
    }

    if (curCount > 0) {
        impl->addWeakRef(id);
    }

    return curCount > 0;
}

int32_t RefBase::weakref_type::getWeakCount() const
{
    // Debug only!
    return static_cast<const weakref_impl*>(this)->mWeak
            .load(std::memory_order_relaxed);
}

void RefBase::weakref_type::printRefs() const
{
    static_cast<const weakref_impl*>(this)->printRefs();
}

void RefBase::weakref_type::trackMe(bool enable, bool retain)
{
    static_cast<weakref_impl*>(this)->trackMe(enable, retain);
}

RefBase::weakref_type* RefBase::createWeak(const void* id) const
{
    mRefs->incWeak(id);
    return mRefs;
}

RefBase::weakref_type* RefBase::getWeakRefs() const
{
    return mRefs;
}

RefBase::RefBase()
    : mRefs(new weakref_impl(this))
{
}

RefBase::~RefBase()
{
    int32_t flags = mRefs->mFlags.load(std::memory_order_relaxed);
    // Life-time of this object is extended to WEAK, in
    // which case weakref_impl doesn't out-live the object and we
    // can free it now.
    if ((flags & OBJECT_LIFETIME_MASK) == OBJECT_LIFETIME_WEAK) {
        // It's possible that the weak count is not 0 if the object
        // re-acquired a weak reference in its destructor
        if (mRefs->mWeak.load(std::memory_order_relaxed) == 0) {
            delete mRefs;
        }
    } else if (mRefs->mStrong.load(std::memory_order_relaxed) == INITIAL_STRONG_VALUE) {
        // We never acquired a strong reference on this object.
#if DEBUG_REFBASE_DESTRUCTION
        // Treating this as fatal is prone to causing boot loops. For debugging, it's
        // better to treat as non-fatal.
        ALOGD("RefBase: Explicit destruction, weak count = %d (in %p)", mRefs->mWeak.load(), this);

#if CALLSTACK_ENABLED
        CallStack::logStack(LOG_TAG);
#endif
#else
        LOG_ALWAYS_FATAL("RefBase: Explicit destruction, weak count = %d", mRefs->mWeak.load());
#endif
    }
    // For debugging purposes, clear mRefs.  Ineffective against outstanding wp's.
    const_cast<weakref_impl*&>(mRefs) = nullptr;
}

void RefBase::extendObjectLifetime(int32_t mode)
{
    // Must be happens-before ordered with respect to construction or any
    // operation that could destroy the object.
    mRefs->mFlags.fetch_or(mode, std::memory_order_relaxed);
}

void RefBase::onFirstRef()
{
}

void RefBase::onLastStrongRef(const void* /*id*/)
{
}

bool RefBase::onIncStrongAttempted(uint32_t flags, const void* /*id*/)
{
    return (flags&FIRST_INC_STRONG) ? true : false;
}

void RefBase::onLastWeakRef(const void* /*id*/)
{
}

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

#if DEBUG_REFS
void RefBase::renameRefs(size_t n, const ReferenceRenamer& renamer) {
    for (size_t i=0 ; i<n ; i++) {
        renamer(i);
    }
}
#else
void RefBase::renameRefs(size_t /*n*/, const ReferenceRenamer& /*renamer*/) { }
#endif

void RefBase::renameRefId(weakref_type* ref,
        const void* old_id, const void* new_id) {
    weakref_impl* const impl = static_cast<weakref_impl*>(ref);
    impl->renameStrongRefId(old_id, new_id);
    impl->renameWeakRefId(old_id, new_id);
}

void RefBase::renameRefId(RefBase* ref,
        const void* old_id, const void* new_id) {
    ref->mRefs->renameStrongRefId(old_id, new_id);
    ref->mRefs->renameWeakRefId(old_id, new_id);
}

}; // namespace android


text:
* Install node modules required for the benchmark you wish to run
* Use `npm run bench -- --help` for options

For example, let's say you like to know how the performance of `equals`
compares to what it was at version 2.x.x:

```console
$ (cd bench && npm install sanctuary-type-classes@2.x.x)
$ npm run bench -- --benchmark old-vs-new --match methods.equals.*
```


text:
<?php

namespace PH7;

use PFBC\Element\Button;
use PFBC\Element\Checkbox;
use PFBC\Element\File;
use PFBC\Element\Hidden;
use PFBC\Element\HTMLExternal;
use PFBC\Element\Radio;
use PFBC\Element\Textarea;
use PFBC\Element\Textbox;
use PFBC\Element\Token;
use PFBC\Validation\Str;
use PH7\Framework\Mvc\Router\Uri;
use PH7\Framework\Url\Header;

class AdminBlogForm
{
    const MAX_CATEGORIES = 300;

    public static function display()
    {
        if (isset($_POST['submit_blog'])) {
            if (\PFBC\Form::isValid($_POST['submit_blog'])) {
                new AdminBlogFormProcess();
            }

            Header::redirect();
        }

        $oCategoryData = (new BlogModel)->getCategory(
            null,
            0,
            self::MAX_CATEGORIES
        );

        $aCategoryNames = [];
        foreach ($oCategoryData as $oCategory) {
            $aCategoryNames[$oCategory->categoryId] = $oCategory->name;
        }

        $oForm = new \PFBC\Form('form_blog');
        $oForm->configure(['action' => '']);
        $oForm->addElement(new Hidden('submit_blog', 'form_blog'));
        $oForm->addElement(new Token('blog'));
        $oForm->addElement(
            new Textbox(
                t('Article name:'),
                'title',
                [
                    'validation' => new Str(2, 60),
                    'required' => 1
                ]
            )
        );
        $oForm->addElement(
            new Textbox(
                t('Article ID:'),
                'post_id',
                [
                    'description' => Uri::get('blog', 'main', 'index') . '/' . t('your-address') . '',
                    'title' => t('Article ID will be the name of the URL.'),
                    'id' => 'post_id',
                    'validation' => new Str(2, 60),
                    'required' => 1
                ]
            )
        );
        $oForm->addElement(new HTMLExternal('
'));
        $oForm->addElement(
            new Checkbox(
                t('Categories:'),
                'category_id',
                $aCategoryNames,
                ['description' => t('Select a category that fits the best for your article.'), 'required' => 1]
            )
        );
        $oForm->addElement(new HTMLExternal('
'));
        $oForm->addElement(
            new Textarea(t('Body:'), 'content', ['validation' => new Str(30), 'rows' => 8, 'required' => 1])
        );
        $oForm->addElement(
            new Textbox(
                t('Language of the article:'),
                'lang_id',
                [
                    'description' => t('e.g., "en", "fr", "es", "js"'),
                    'value' => PH7_LANG_CODE,
                    'pattern' => '[a-z]{2}',
                    'validation' => new Str(2, 2),
                    'required' => 1
                ]
            )
        );
        $oForm->addElement(
            new Textbox(
                t('Slogan:'),
                'slogan',
                ['validation' => new Str(Form::MIN_STRING_FIELD_LENGTH, Form::MAX_STRING_FIELD_LENGTH)]
            )
        );
        $oForm->addElement(new File(t('Thumbnail:'), 'thumb', ['accept' => 'image/*']));
        $oForm->addElement(
            new Textbox(
                t('Tags:'),
                'tags',
                [
                    'description' => t('Separate keywords by commas and without spaces between the commas.'),
                    'validation' => new Str(Form::MIN_STRING_FIELD_LENGTH, Form::MAX_STRING_FIELD_LENGTH)
                ]
            )
        );
        $oForm->addElement(
            new Textbox(
                t('Title (meta tag):'),
                'page_title',
                ['validation' => new Str(Form::MIN_STRING_FIELD_LENGTH, Form::MAX_STRING_FIELD_LENGTH), 'required' => 1]
            )
        );
        $oForm->addElement(
            new Textbox(
                t('Description (meta tag):'),
                'meta_description',
                ['validation' => new Str(Form::MIN_STRING_FIELD_LENGTH, Form::MAX_STRING_FIELD_LENGTH)]
            )
        );
        $oForm->addElement(
            new Textbox(
                t('Keywords (meta tag):'),
                'meta_keywords',
                [
                    'description' => t('Separate keywords by commas.'),
                    'validation' => new Str(Form::MIN_STRING_FIELD_LENGTH, Form::MAX_STRING_FIELD_LENGTH)
                ]
            )
        );
        $oForm->addElement(new Textbox(t('Robots (meta tag):'), 'meta_robots', ['validation' => new Str(2, 50)]));
        $oForm->addElement(new Textbox(t('Author (meta tag):'), 'meta_author', ['validation' => new Str(2, 50)]));
        $oForm->addElement(new Textbox(t('Copyright (meta tag):'), 'meta_copyright', ['validation' => new Str(2, 50)]));
        $oForm->addElement(
            new Radio(
                t('Enable Comment:'),
                'enable_comment',
                ['1' => t('Enable'), '0' => t('Disable')],
                ['value' => '1', 'required' => 1]
            )
        );
        $oForm->addElement(new Button);
        $oForm->addElement(
            new HTMLExternal(
                ''
            )
        );
        $oForm->render();
    }
}


text:
StronglyUniversalStringHashing
==============================
[![Build Status](https://travis-ci.org/lemire/StronglyUniversalStringHashing.png)](https://travis-ci.org/lemire/StronglyUniversalStringHashing)

Very fast [universal hash
families](https://en.wikipedia.org/wiki/Universal_hashing) on strings.

Sample results on a regular x64 (Skylake) processor:
```
Google's City                        CPU cycle/byte = 0.216047
64-bit VHASH                         CPU cycle/byte = 0.215097
64-bit CLHASH                        CPU cycle/byte = 0.091786
SipHash                              CPU cycle/byte = 1.414069
```

This software includes the experimental code from the following research papers...

* Daniel Lemire and Owen
Kaser, [Faster 64-bit universal hashing using carry-less
multiplications](http://arxiv.org/abs/1503.03465), Journal of Cryptographic Engineering 6 (3), 2016.
* Dmytro Ivanchykhin, Sergey Ignatchenko, Daniel Lemire, [Regular and almost universal hashing: an efficient implementation](https://arxiv.org/abs/1609.09840), Software: Practice and Experience (to appear).
* Owen Kaser and Daniel Lemire, [Strongly universal string hashing is fast](http://arxiv.org/abs/1202.4961), Computer Journal (2014) 57 (11): 1624-1638.

Acknowledgements
==================

Thanks to Nathan Kurz for noticing that GCC 4.7 requires
no-tree-vectorize to produce correct results.

Usage
======

To test speed:

    make benchmark-target
    # disable some processor features that add noise to benchmarks:
    cd scripts/; sudo ./master.sh; cd ..
    ./benchmark/benchmark.exe
    ./benchmark/variablelengthbenchmark.exe

To test correctness of hash functions using PCLMULQDQ:

    make test-target
    for test in ./test/correctness/*.exe; do $test; done

Or more simply...

    ./run_unit.sh

Related projects
=================

There is a very simple clhash library in C: https://github.com/lemire/clhash

For a project with similar goals, see: https://github.com/lemire/fasthashing

Licensing
==========

This project is licenced as described in the LICENSE file, with the
following exceptions for code written by other authors:

  * smhasher and CityHash are MIT licensed.

  * VHASH and siphash are public domain.


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

<ValueSet xmlns="http://hl7.org/fhir">
  <text>
    <status value="generated"/>

Document Reference Service Types

Known Service types that can be referred to from a Document Reference

This value set defines its own terms in the system http://hl7.org/fhir/document-reference-service-types

            Code

            Display

            Definition

            XDS

          IHE XDS

            RLUS

          OMG RLUS

  </text>
  <identifier value="http://hl7.org/fhir/vs/documentreference-service-types"/>
  <name value="Document Reference Service Types"/>
  <publisher value="HL7 FHIR"/>
  <telecom>
    <system value="url"/>
    <value value="http://hl7.org/fhir"/>
  </telecom>
  <description value="Known Service types that can be referred to from a Document Reference"/>
  <status value="draft"/>
  <define>
    <system value="http://hl7.org/fhir/document-reference-service-types"/>
    <caseSensitive value="true"/>
    <concept>

      <display value="IHE XDS"/>
    </concept>
    <concept>

      <display value="OMG RLUS"/>
    </concept>
  </define>
</ValueSet>


text:
#include "gtest/gtest.h"

#include <memory>

#include "wabt/intrusive-list.h"
#include "wabt/make-unique.h"

using namespace wabt;

namespace {

struct TestObject : intrusive_list_base<TestObject> {
  static int creation_count;

  TestObject(int data = 0, int data2 = 0) : data(data), data2(data2) {
    ++creation_count;
  }

  // Allow move.
  TestObject(TestObject&& other) {
    // Don't increment creation_count; we're moving from other.
    *this = std::move(other);
  }

  TestObject& operator=(TestObject&& other) {
    data = other.data;
    data2 = other.data2;
    other.moved = true;
    return *this;
  }

  // Disallow copy.
  TestObject(const TestObject&) = delete;
  TestObject& operator=(const TestObject&) = delete;

  ~TestObject() {
    if (!moved) {
      creation_count--;
    }
  }

  int data;
  int data2;
  bool moved = false;
};

// static
int TestObject::creation_count = 0;

using TestObjectList = intrusive_list<TestObject>;

class IntrusiveListTest : public ::testing::Test {
 protected:
  virtual void SetUp() {
    // Reset to 0 even if the previous test leaked objects to keep the tests
    // independent.
    TestObject::creation_count = 0;
  }

  virtual void TearDown() { ASSERT_EQ(0, TestObject::creation_count); }

  TestObjectList NewList(const std::vector<int>& data_values) {
    TestObjectList result;
    for (auto data_value : data_values)
      result.emplace_back(data_value);
    return result;
  }

  void AssertListEq(const TestObjectList& list,
                    const std::vector<int>& expected) {
    size_t count = 0;
    for (const TestObject& node : list) {
      ASSERT_EQ(expected[count++], node.data);
    }
    ASSERT_EQ(count, expected.size());
  }

  void AssertListEq(const TestObjectList& list,
                    const std::vector<int>& expected,
                    const std::vector<int>& expected2) {
    assert(expected.size() == expected2.size());
    size_t count = 0;
    for (const TestObject& node : list) {
      ASSERT_EQ(expected[count], node.data);
      ASSERT_EQ(expected2[count], node.data2);
      count++;
    }
    ASSERT_EQ(count, expected.size());
  }
};

}  // end anonymous namespace

TEST_F(IntrusiveListTest, default_constructor) {
  TestObjectList list;
}

TEST_F(IntrusiveListTest, node_constructor) {
  TestObjectList list(MakeUnique<TestObject>(1));
  AssertListEq(list, {1});
}

TEST_F(IntrusiveListTest, node_move_constructor) {
  TestObjectList list(TestObject(1));
  AssertListEq(list, {1});
}

TEST_F(IntrusiveListTest, move_constructor) {
  TestObjectList list1 = NewList({1, 2, 3});
  TestObjectList list2(std::move(list1));
  AssertListEq(list1, {});
  AssertListEq(list2, {1, 2, 3});
}

TEST_F(IntrusiveListTest, move_assignment_operator) {
  TestObjectList list1 = NewList({1, 2, 3});
  TestObjectList list2;

  list2 = std::move(list1);
  AssertListEq(list1, {});
  AssertListEq(list2, {1, 2, 3});
}

namespace {

class IntrusiveListIteratorTest : public IntrusiveListTest {
 protected:
  virtual void SetUp() {
    IntrusiveListTest::SetUp();

    list_.emplace_back(1);
    list_.emplace_back(2);
    list_.emplace_back(3);
  }

  virtual void TearDown() {
    list_.clear();

    IntrusiveListTest::TearDown();
  }

  template <typename Iter>
  void TestForward(Iter first, Iter last, const std::vector<int>& expected) {
    size_t count = 0;
    while (first != last) {
      ASSERT_EQ(expected[count], first->data);
      ++first;
      ++count;
    }
    ASSERT_EQ(count, expected.size());
  }

  template <typename Iter>
  void TestBackward(Iter first, Iter last, const std::vector<int>& expected) {
    size_t count = 0;
    while (first != last) {
      --last;
      ASSERT_EQ(expected[count], last->data);
      ++count;
    }
    ASSERT_EQ(count, expected.size());
  }

  TestObjectList list_;
  const TestObjectList& clist_ = list_;
};

}  // end of anonymous namespace

TEST_F(IntrusiveListIteratorTest, begin_end_forward) {
  TestForward(list_.begin(), list_.end(), {1, 2, 3});
  TestForward(clist_.begin(), clist_.end(), {1, 2, 3});
}

TEST_F(IntrusiveListIteratorTest, rbegin_rend_forward) {
  TestForward(list_.rbegin(), list_.rend(), {3, 2, 1});
  TestForward(clist_.rbegin(), clist_.rend(), {3, 2, 1});
}

TEST_F(IntrusiveListIteratorTest, cbegin_cend_forward) {
  TestForward(list_.cbegin(), list_.cend(), {1, 2, 3});
  TestForward(clist_.cbegin(), clist_.cend(), {1, 2, 3});
}

TEST_F(IntrusiveListIteratorTest, crbegin_crend_forward) {
  TestForward(list_.crbegin(), list_.crend(), {3, 2, 1});
  TestForward(clist_.crbegin(), clist_.crend(), {3, 2, 1});
}

TEST_F(IntrusiveListIteratorTest, begin_end_backward) {
  TestBackward(list_.begin(), list_.end(), {3, 2, 1});
  TestBackward(clist_.begin(), clist_.end(), {3, 2, 1});
}

TEST_F(IntrusiveListIteratorTest, rbegin_rend_backward) {
  TestBackward(list_.rbegin(), list_.rend(), {1, 2, 3});
  TestBackward(clist_.rbegin(), clist_.rend(), {1, 2, 3});
}

TEST_F(IntrusiveListIteratorTest, cbegin_cend_backward) {
  TestBackward(list_.cbegin(), list_.cend(), {3, 2, 1});
  TestBackward(clist_.cbegin(), clist_.cend(), {3, 2, 1});
}

TEST_F(IntrusiveListIteratorTest, crbegin_crend_backward) {
  TestBackward(list_.crbegin(), list_.crend(), {1, 2, 3});
  TestBackward(clist_.crbegin(), clist_.crend(), {1, 2, 3});
}

TEST_F(IntrusiveListTest, size_empty) {
  TestObjectList list;
  ASSERT_EQ(0U, list.size());
  ASSERT_TRUE(list.empty());

  list.emplace_back(1);
  ASSERT_EQ(1U, list.size());
  ASSERT_FALSE(list.empty());
}

TEST_F(IntrusiveListTest, front_back) {
  TestObjectList list;

  list.emplace_back(1);
  ASSERT_EQ(1, list.front().data);
  ASSERT_EQ(1, list.back().data);

  list.emplace_back(2);
  ASSERT_EQ(1, list.front().data);
  ASSERT_EQ(2, list.back().data);

  const TestObjectList& clist = list;
  ASSERT_EQ(1, clist.front().data);
  ASSERT_EQ(2, clist.back().data);
}

TEST_F(IntrusiveListTest, emplace_front) {
  TestObjectList list;

  // Pass an additional arg to show that forwarding works properly.
  list.emplace_front(1, 100);
  list.emplace_front(2, 200);
  list.emplace_front(3, 300);
  list.emplace_front(4, 400);

  AssertListEq(list, {4, 3, 2, 1}, {400, 300, 200, 100});
}

TEST_F(IntrusiveListTest, emplace_back) {
  TestObjectList list;

  // Pass an additional arg to show that forwarding works properly.
  list.emplace_back(1, 100);
  list.emplace_back(2, 200);
  list.emplace_back(3, 300);
  list.emplace_back(4, 400);

  AssertListEq(list, {1, 2, 3, 4}, {100, 200, 300, 400});
}

TEST_F(IntrusiveListTest, push_front_pointer) {
  TestObjectList list;

  list.push_front(MakeUnique<TestObject>(1));
  list.push_front(MakeUnique<TestObject>(2));
  list.push_front(MakeUnique<TestObject>(3));

  AssertListEq(list, {3, 2, 1});
}

TEST_F(IntrusiveListTest, push_back_pointer) {
  TestObjectList list;

  list.push_back(MakeUnique<TestObject>(1));
  list.push_back(MakeUnique<TestObject>(2));
  list.push_back(MakeUnique<TestObject>(3));

  AssertListEq(list, {1, 2, 3});
}

TEST_F(IntrusiveListTest, push_front_move) {
  TestObjectList list;

  list.push_front(TestObject(1));
  list.push_front(TestObject(2));
  list.push_front(TestObject(3));

  AssertListEq(list, {3, 2, 1});
}

TEST_F(IntrusiveListTest, push_back_move) {
  TestObjectList list;

  list.push_back(TestObject(1));
  list.push_back(TestObject(2));
  list.push_back(TestObject(3));

  AssertListEq(list, {1, 2, 3});
}

TEST_F(IntrusiveListTest, pop_front) {
  TestObjectList list = NewList({1, 2, 3, 4});

  list.pop_front();
  AssertListEq(list, {2, 3, 4});
  list.pop_front();
  AssertListEq(list, {3, 4});
  list.pop_front();
  AssertListEq(list, {4});
  list.pop_front();
  AssertListEq(list, {});
}

TEST_F(IntrusiveListTest, pop_back) {
  TestObjectList list = NewList({1, 2, 3, 4});

  list.pop_back();
  AssertListEq(list, {1, 2, 3});
  list.pop_back();
  AssertListEq(list, {1, 2});
  list.pop_back();
  AssertListEq(list, {1});
  list.pop_back();
  AssertListEq(list, {});
}

TEST_F(IntrusiveListTest, extract_front) {
  TestObjectList list = NewList({1, 2, 3});

  std::unique_ptr<TestObject> t1(list.extract_front());
  ASSERT_EQ(1, t1->data);
  AssertListEq(list, {2, 3});

  std::unique_ptr<TestObject> t2(list.extract_front());
  ASSERT_EQ(2, t2->data);
  AssertListEq(list, {3});

  std::unique_ptr<TestObject> t3(list.extract_front());
  ASSERT_EQ(3, t3->data);
  AssertListEq(list, {});
}

TEST_F(IntrusiveListTest, extract_back) {
  TestObjectList list = NewList({1, 2, 3});

  std::unique_ptr<TestObject> t1(list.extract_back());
  ASSERT_EQ(3, t1->data);
  AssertListEq(list, {1, 2});

  std::unique_ptr<TestObject> t2(list.extract_back());
  ASSERT_EQ(2, t2->data);
  AssertListEq(list, {1});

  std::unique_ptr<TestObject> t3(list.extract_back());
  ASSERT_EQ(1, t3->data);
  AssertListEq(list, {});
}

TEST_F(IntrusiveListTest, emplace) {
  TestObjectList list;

  // Pass an additional arg to show that forwarding works properly.
  list.emplace(list.begin(), 2, 200);
  list.emplace(list.end(), 4, 400);
  list.emplace(std::next(list.begin()), 3, 300);
  list.emplace(list.begin(), 1, 100);

  AssertListEq(list, {1, 2, 3, 4}, {100, 200, 300, 400});
}

TEST_F(IntrusiveListTest, insert_pointer) {
  TestObjectList list;

  list.insert(list.begin(), MakeUnique<TestObject>(2));
  list.insert(list.end(), MakeUnique<TestObject>(4));
  list.insert(std::next(list.begin()), MakeUnique<TestObject>(3));
  list.insert(list.begin(), MakeUnique<TestObject>(1));

  AssertListEq(list, {1, 2, 3, 4});
}

TEST_F(IntrusiveListTest, insert_move) {
  TestObjectList list;

  list.insert(list.begin(), TestObject(2));
  list.insert(list.end(), TestObject(4));
  list.insert(std::next(list.begin()), TestObject(3));
  list.insert(list.begin(), TestObject(1));

  AssertListEq(list, {1, 2, 3, 4});
}

TEST_F(IntrusiveListTest, extract) {
  TestObjectList list = NewList({1, 2, 3, 4});

  TestObjectList::iterator t1_iter = std::next(list.begin(), 0);
  TestObjectList::iterator t2_iter = std::next(list.begin(), 1);
  TestObjectList::iterator t3_iter = std::next(list.begin(), 2);
  TestObjectList::iterator t4_iter = std::next(list.begin(), 3);

  std::unique_ptr<TestObject> t2(list.extract(t2_iter));
  ASSERT_EQ(2, t2->data);
  AssertListEq(list, {1, 3, 4});

  std::unique_ptr<TestObject> t4(list.extract(t4_iter));
  ASSERT_EQ(4, t4->data);
  AssertListEq(list, {1, 3});

  std::unique_ptr<TestObject> t1(list.extract(t1_iter));
  ASSERT_EQ(1, t1->data);
  AssertListEq(list, {3});

  std::unique_ptr<TestObject> t3(list.extract(t3_iter));
  ASSERT_EQ(3, t3->data);
  AssertListEq(list, {});
}

TEST_F(IntrusiveListTest, erase) {
  TestObjectList list = NewList({1, 2, 3, 4});

  TestObjectList::iterator t1_iter = std::next(list.begin(), 0);
  TestObjectList::iterator t2_iter = std::next(list.begin(), 1);
  TestObjectList::iterator t3_iter = std::next(list.begin(), 2);
  TestObjectList::iterator t4_iter = std::next(list.begin(), 3);

  // erase returns an iterator to the following node.
  ASSERT_EQ(3, list.erase(t2_iter)->data);
  AssertListEq(list, {1, 3, 4});

  ASSERT_EQ(list.end(), list.erase(t4_iter));
  AssertListEq(list, {1, 3});

  ASSERT_EQ(3, list.erase(t1_iter)->data);
  AssertListEq(list, {3});

  ASSERT_EQ(list.end(), list.erase(t3_iter));
  AssertListEq(list, {});
}

TEST_F(IntrusiveListTest, erase_range) {
  TestObjectList list = NewList({1, 2, 3, 4, 5, 6});

  // OK to erase an empty range.
  list.erase(list.begin(), list.begin());
  list.erase(list.end(), list.end());

  // Erase the first element (1).
  list.erase(list.begin(), std::next(list.begin()));
  AssertListEq(list, {2, 3, 4, 5, 6});

  // Erase the last element (6).
  list.erase(std::prev(list.end()), list.end());
  AssertListEq(list, {2, 3, 4, 5});

  // Erase [3, 4] => [2, 5]
  list.erase(std::next(list.begin()), std::prev(list.end()));
  AssertListEq(list, {2, 5});

  // Erase the rest.
  list.erase(list.begin(), list.end());
  AssertListEq(list, {});
}

TEST_F(IntrusiveListTest, swap) {
  TestObjectList list1 = NewList({1, 2, 3, 4});

  TestObjectList list2 = NewList({100, 200, 300});

  AssertListEq(list1, {1, 2, 3, 4});
  AssertListEq(list2, {100, 200, 300});

  list1.swap(list2);

  AssertListEq(list1, {100, 200, 300});
  AssertListEq(list2, {1, 2, 3, 4});
}

TEST_F(IntrusiveListTest, clear) {
  TestObjectList list = NewList({1, 2, 3, 4});

  ASSERT_FALSE(list.empty());

  list.clear();

  ASSERT_EQ(0U, list.size());
  ASSERT_TRUE(list.empty());
}

TEST_F(IntrusiveListTest, splice_list) {
  TestObjectList list1 = NewList({1, 2, 3});

  // Splice at beginning.
  TestObjectList list2 = NewList({100, 200});
  list1.splice(list1.begin(), list2);
  AssertListEq(list1, {100, 200, 1, 2, 3});
  AssertListEq(list2, {});

  // Splice at end.
  TestObjectList list3 = NewList({500, 600, 700});
  list1.splice(list1.end(), list3);
  AssertListEq(list1, {100, 200, 1, 2, 3, 500, 600, 700});
  AssertListEq(list3, {});

  // Splice in the middle.
  TestObjectList list4 = NewList({400});
  list1.splice(std::next(list1.begin(), 4), list4);
  AssertListEq(list1, {100, 200, 1, 2, 400, 3, 500, 600, 700});
  AssertListEq(list4, {});
}

TEST_F(IntrusiveListTest, splice_list_move) {
  TestObjectList list1 = NewList({1, 2, 3});

  // Splice at beginning.
  list1.splice(list1.begin(), NewList({100, 200}));
  AssertListEq(list1, {100, 200, 1, 2, 3});

  // Splice at end.
  list1.splice(list1.end(), NewList({500, 600, 700}));
  AssertListEq(list1, {100, 200, 1, 2, 3, 500, 600, 700});

  // Splice in the middle.
  list1.splice(std::next(list1.begin(), 4), NewList({400}));
  AssertListEq(list1, {100, 200, 1, 2, 400, 3, 500, 600, 700});
}

TEST_F(IntrusiveListTest, splice_node) {
  TestObjectList list1 = NewList({1, 2, 3});

  // Splice at beginning.
  TestObjectList list2 = NewList({100, 200});
  list1.splice(list1.begin(), list2, list2.begin());
  AssertListEq(list1, {100, 1, 2, 3});
  AssertListEq(list2, {200});

  // Splice at end.
  TestObjectList list3 = NewList({500, 600, 700});
  list1.splice(list1.end(), list3, std::next(list3.begin(), 2));
  AssertListEq(list1, {100, 1, 2, 3, 700});
  AssertListEq(list3, {500, 600});

  // Splice in the middle.
  TestObjectList list4 = NewList({400});
  list1.splice(std::next(list1.begin(), 3), list4, list4.begin());
  AssertListEq(list1, {100, 1, 2, 400, 3, 700});
  AssertListEq(list4, {});
}

TEST_F(IntrusiveListTest, splice_range) {
  TestObjectList list1 = NewList({1, 2, 3});

  // Splice at beginning.
  TestObjectList list2 = NewList({100, 200, 300});
  list1.splice(list1.begin(), list2, list2.begin(), std::prev(list2.end()));
  AssertListEq(list1, {100, 200, 1, 2, 3});
  AssertListEq(list2, {300});

  // Splice at end.
  TestObjectList list3 = NewList({500, 600, 700});
  list1.splice(list1.end(), list3, std::next(list3.begin()), list3.end());
  AssertListEq(list1, {100, 200, 1, 2, 3, 600, 700});
  AssertListEq(list3, {500});

  // Splice in the middle.
  TestObjectList list4 = NewList({400});
  list1.splice(std::next(list1.begin(), 4), list4, list4.begin(), list4.end());
  AssertListEq(list1, {100, 200, 1, 2, 400, 3, 600, 700});
  AssertListEq(list4, {});
}


text: The oauth code for oauth.yian.org.pe


text:
// =====================================================================================
//
//       Filename:  myutil.h
//
//    Description:
//
//        Version:  1.0
//        Created:  04/12/2017 04:26:31 PM
//       Revision:  none
//       Compiler:  g++
//
//         Author:  Baoxing Song (songbx.me), songbaoxing168@163.com
//
// =====================================================================================
/*************************************************************************

 ************************************************************************/

#ifndef _MYUTIL_H
#define _MYUTIL_H
#include <algorithm>
#include "../model/model.h"
#include <string>
#include <vector>
#include <map>
#include "nucleotideCodeSubstitutionMatrix.h"

void split(const std::string &s, char& delim,std::vector<std::string> &elems);
//std::vector<std::string> split(const std::string &s, char delim);

////input a string, the string could be trasformed to uppercas
//void songToUpCase( std::string& str );
///*  input a string, the transformed would also be returned */
//void songToLowCase( std::string& str);
std::string songStrRemoveBlank(std::string& str);
std::string songStrReplaceAll(std::string& str, const std::string& pattern, const std::string& pattern2);

bool if_file_exists (const std::string& name);
long GetFileSize(const std::string& filename);

bool createdFolder(const std::string & path);
bool ifFileExists (const std::string& list_file);
bool ifAFolder(const std::string & folder);
void getMafftResultListFromFolder( std::string& folder, std::vector<std::string>& fileNameList);
void getListFromTextFile(const std::string& list_file, std::vector<std::string>& list);
void getSetFromTextFile(const std::string& list_file, std::set<std::string>& set);
bool caseInsensitiveStringCompare(const std::string& str1, const std::string& str2);
//for MSA
void getSdiList(const std::string& list_file, std::map<std::string, std::string>& sdiLists);

void overlapGenomeAndGene(std::map <std::string, std::vector<Gene>> & geneMap, std::map <std::string, Fasta> & sequences);

#endif


text:
<?php declare(strict_types=1);

namespace Gitilicious\GitClient\Test\Unit\Cli;

use Gitilicious\GitClient\Cli\Client;
use Gitilicious\GitClient\Cli\Input\Binary;
use Gitilicious\GitClient\Cli\Input\PlainArgument;
use Gitilicious\GitClient\FileSystem\Directory;

class ClientTest extends \PHPUnit_Framework_TestCase
{
    public function testRunReturnsSuccessResult()
    {
        $binary = new class extends Binary {
            public function __construct() {}

            public function getExecutable(): string
            {
                return 'cd';
            }
        };

        $client = new Client($binary);

        $result = $client->run(new Directory(DATA_DIR), new PlainArgument(DATA_DIR . '/existing-directory'));

        $this->assertTrue($result->isSuccess());
    }

    public function testRunReturnsFailedResult()
    {
        $binary = new class extends Binary {
            public function __construct() {}

            public function getExecutable(): string
            {
                return 'invalidcommand';
            }
        };

        $client = new Client($binary);

        $result = $client->run(new Directory(DATA_DIR), new PlainArgument(DATA_DIR . '/existing-directory'));

        $this->assertFalse($result->isSuccess());
    }
}


text:
using System;
using System.Collections.Generic;
using Autofac;

namespace WhiteRabbit.Autofac.Scoping
{
    public class ScopedHandlerChain : HandlerChain
    {
        private string _innerHandlerName;

        internal ScopedHandlerChain(ContainerBuilder builder)
            :base(builder)
        {
        }

        public override HandlerChain StartWith<T>()
        {
            if (ChainStarted)
                throw new InvalidOperationException("Chain has already been started with 'ScopedMessageHandler'");

            _innerHandlerName = Guid.NewGuid().ToString();

            Builder
                .RegisterType<T>()
                .Named<T>(_innerHandlerName);

            Builder
                .RegisterType<ScopedMessageHandler>()
                .WithParameter("innerHandlerName", _innerHandlerName)
                .WithParameter("innerHandlerType", typeof(T))
                .As<IMessageHandler>();

            Handlers = new List<Type> { typeof(ScopedMessageHandler), typeof(T) };

            ChainStarted = true;

            return this;
        }

        public override HandlerChain Then<THandler>()
        {
            if (!ChainStarted)
                throw new InvalidOperationException("StartWith<T> must be called before adding additional handlers to the chain");

            Then(typeof(THandler), Handlers.Count == 2 ? _innerHandlerName : "");

            return this;
        }
    }
}


text:
class FTLibraryTest : public CppUnit::TestCase
{
    CPPUNIT_TEST_SUITE( FTLibraryTest);
        CPPUNIT_TEST( testConstructor);
        CPPUNIT_TEST( testError);
    CPPUNIT_TEST_SUITE_END();

    public:
        FTLibraryTest() : CppUnit::TestCase( "FTLibrary Test")
        {}

        FTLibraryTest( const std::string& name) : CppUnit::TestCase(name) {}

        void testConstructor()
        {
            const FTLibrary& libraryOne = FTLibrary::Instance();
            const FTLibrary& libraryTwo = FTLibrary::Instance();

            CPPUNIT_ASSERT( &libraryOne == &libraryTwo);
            CPPUNIT_ASSERT( &libraryOne == &FTLibrary::Instance());
        }

        void testError()
        {
            const FTLibrary& library = FTLibrary::Instance();

            CPPUNIT_ASSERT( library.Error() == 0);
        }

        void setUp()
        {}

        void tearDown()
        {}

    private:

};

CPPUNIT_TEST_SUITE_REGISTRATION( FTLibraryTest);


text:
package boa.datagen.scm;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.hadoop.io.SequenceFile.Writer;

import boa.types.Code.Revision;

/**
 * @author rdyer
 */
public abstract class AbstractConnector implements AutoCloseable {
	protected List<AbstractCommit> revisions = null;
	protected HashMap<String, Integer> nameIndices = new HashMap<String, Integer>();

	public abstract String getLastCommitId();
	public abstract void setLastSeenCommitId(final String id);

	public List<Revision> getCommits(final boolean parse) {
		if (revisions == null) {
			revisions = new ArrayList<AbstractCommit>();
			setRevisions();
		}
		final List<Revision> revs = new ArrayList<Revision>();
		for (final AbstractCommit rev : revisions)
			revs.add(rev.asProtobuf(parse));

		return revs;
	}

	protected abstract void setRevisions();

	public abstract void getTags(final List<String> names, final List<String> commits);

	public abstract void getBranches(final List<String> names, final List<String> commits);

	protected Map<String, Integer> revisionMap;

	public List<Revision> getCommits(final boolean parse, final Writer astWriter, final String repoKey, final String keyDelim) {
		if (revisions == null) {
			revisions = new ArrayList<AbstractCommit>();
			setRevisions();
		}
		final List<Revision> revs = new ArrayList<Revision>();
		int i = 0;
		for (final AbstractCommit rev : revisions)
			revs.add(rev.asProtobuf(parse, astWriter, repoKey + keyDelim + (++i), keyDelim));

		return revs;
	}

}


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

#import "IQNetworkQueue.h"

@implementation IQNetworkQueue
{
    NSMutableSet *_networkTasks;
}

- (instancetype)init
{
    self = [super init];
    if (self)
    {
        _networkTasks = [[NSMutableSet alloc] init];
    }
    return self;
}

-(NSSet*)tasks
{
    return [_networkTasks copy];
}

+(IQNetworkQueue*)sharedQueue
{
    static IQNetworkQueue *manager;

    if (manager == nil)
    {
        manager = [[self alloc] init];
    }

    return manager;
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)appendToQueueAndStartTask:(IQNetworkTask*)task
{
    if ([_networkTasks containsObject:task] == NO)
    {
        [_networkTasks addObject:task];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidCompleteNotification:) name:IQNetworkTaskDidCompleteNotification object:task];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidFailedNotification:) name:IQNetworkTaskDidFailedNotification object:task];

        [task start];
    }
}

-(void)removeTaskFromQueue:(IQNetworkTask*)task
{
    if ([_networkTasks containsObject:task] == YES)
    {
        [_networkTasks removeObject:task];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:IQNetworkTaskDidCompleteNotification object:task];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:IQNetworkTaskDidFailedNotification object:task];
    }
}

/* Creates a data task with the given request. */
- (IQNetworkTask *)dataTaskWithRequest:(NSURLRequest *)request
{
    IQNetworkTask *task = [self existingTaskForRequest:request];

    if (task == nil)
    {
        task = [[IQNetworkDataTask alloc] initWithRequest:request];
        [task start];
    }

    return task;
}

/* Creates a data task to retrieve the contents of the given URL. */
- (IQNetworkTask *)dataTaskWithURL:(NSURL *)url
{
    NSURLRequest *request = [IQNetworkDataTask expectedRequestForURL:url];

    IQNetworkTask *task = [self existingTaskForRequest:request];

    if (task == nil)
    {
        task = [[IQNetworkDataTask alloc] initWithRequest:request];
        [self appendToQueueAndStartTask:task];
    }

    return task;
}

/* Creates an upload task with the given request.  The body of the request will be created from the file referenced by fileURL */
- (IQNetworkTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL
{
    NSURLRequest *expectedRequest = [IQNetworkUploadTask expectedRequestForRequest:request fromFile:fileURL];

    IQNetworkTask *task = [self existingTaskForRequest:expectedRequest];

    if (task == nil)
    {
        task = [[IQNetworkUploadTask alloc] initWithRequest:request fromFile:fileURL];
        [self appendToQueueAndStartTask:task];
    }

    return task;
}

/* Creates an upload task with the given request.  The body of the request is provided from the bodyData. */
- (IQNetworkTask *)uploadTaskWithRequest:(NSURLRequest *)request bodyData:(NSData *)bodyData
{
    NSURLRequest *expectedRequest = [IQNetworkUploadTask expectedRequestForRequest:request bodyData:bodyData];

    IQNetworkTask *task = [self existingTaskForRequest:expectedRequest];

    if (task == nil)
    {
        task = [[IQNetworkUploadTask alloc] initWithRequest:request bodyData:bodyData];
        [self appendToQueueAndStartTask:task];
    }

    return task;
}

/* Creates a download task with the given request. */
- (IQNetworkTask *)downloadTaskWithRequest:(NSURLRequest *)request
{
    IQNetworkTask *task = [self existingTaskForRequest:request];

    if (task == nil)
    {
        task = [[IQNetworkDownloadTask alloc] initWithRequest:request];
        [self appendToQueueAndStartTask:task];
    }

    return task;
}

/* Creates a download task to download the contents of the given URL. */
- (IQNetworkTask *)downloadTaskWithURL:(NSURL *)url
{
    NSURLRequest *expectedRequest = [IQNetworkDownloadTask expectedRequestForURL:url];

    IQNetworkTask *task = [self existingTaskForRequest:expectedRequest];

    if (task == nil)
    {
        task = [[IQNetworkDownloadTask alloc] initWithURL:url];
        [self appendToQueueAndStartTask:task];
    }

    return task;
}

/* Creates a download task with the resume data.  If the download cannot be successfully resumed, URLSession:task:didCompleteWithError: will be called. */
- (IQNetworkTask *)downloadTaskWithRequest:(NSURLRequest*)request resumeData:(NSData *)resumeData
{
    IQNetworkTask *task = [self existingTaskForRequest:request];

    if (task == nil)
    {
        task = [[IQNetworkDownloadTask alloc] initWithRequest:request resumeData:resumeData];
        [self appendToQueueAndStartTask:task];
    }

    return task;
}

-(IQNetworkTask*)existingTaskForRequest:(NSURLRequest*)request
{
    for (IQNetworkTask *task in _networkTasks)
        if ([task.request isEqual:request])
            return task;

    return nil;
}

-(void)taskDidCompleteNotification:(NSNotification*)notification
{
    if (notification.object)
    {
        [self removeTaskFromQueue:notification.object];
    }
}

-(void)taskDidFailedNotification:(NSNotification*)notification
{
    if (notification.object)
    {
        [self removeTaskFromQueue:notification.object];
    }
}

@end


text:
module Mutiny
  module Mutants
    class Mutant
      class Location
        attr_reader :old_position, :new_position, :content

        def initialize(position:, content:)
          position ||= {}
          @old_position = position[:old].freeze
          @new_position = position[:new].freeze
          @content = content
        end

        def lines
          Range.new(
            line_number_of_offset(new_position.begin),
            line_number_of_offset(new_position.end)
          )
        end

        private

        def line_number_of_offset(offset)
          content[0..offset].lines.size
        end
      end
    end
  end
end


text:
  Sidebar Menu

			<?php get_template_part('templates/content-single', get_post_type()); ?>


text:
/**
  @file         pixel_format.h
  @brief        represents the format of a pixel.
  @author       HRYKY
  @version      $Id: pixel_format.h 337 2014-03-23 14:12:33Z hryky.private@gmail.com $
 */
#ifndef PIXEL_FORMAT_H_20120204091312050
#define PIXEL_FORMAT_H_20120204091312050
#include "hryky/definition.h"
#include "hryky/without_copy.h"
#include "hryky/sdl/sdl_common.h"
#include "hryky/stdint.h"
#include "hryky/with_stream_out.h"
#include "hryky/with_swap.h"
//------------------------------------------------------------------------------
// disables warnings
//------------------------------------------------------------------------------
#pragma hryky_pragma_push_warning
#pragma hryky_pragma_disable_warning_padded
//------------------------------------------------------------------------------
// defines macros
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// declares types
//------------------------------------------------------------------------------
namespace hryky
{
namespace pixel
{
	/// represents the format of a pixel.
	class Format;

}
}
//------------------------------------------------------------------------------
// declares classes
//------------------------------------------------------------------------------
/**
  @brief represents the format of a pixel.
 */
class hryky::pixel::Format :
	public WithStreamOut<Format>,
	public WithSwap<Format>
{
public :

	/// self.
	typedef hryky::pixel::Format this_type;

	/// kind of pixel format
	struct Kind
	{
		enum Raw
		{
			invalid,
			r8g8b8x8,
			b8g8r8x8,
			r8g8b8a8,
			b8g8r8a8,
			a8r8g8b8,
			a8b8g8r8,
			r8g8b8,
			b8g8r8,
			r5g6b5,
			b5g6r5,
			num,
		};
	};
	typedef Kind::Raw kind_type;

	/// trait of pixel format
	struct Traits
	{
		typedef Traits          this_type;
		typedef uint8_t         bytes_type;
		typedef char const *    name_type;

		struct Order
		{
			enum Kind
			{
				invalid,
				rgbx,
				bgrx,
				rgba,
				bgra,
				rgb,
				bgr,
				argb,
				abgr,
				num,
			};
		};
		typedef Order::Kind     order_type;

		/// retrieves the name of pixel format
		name_type name() const
		{
			return this->name_;
		}

		/// retrieves the order of each color element
		order_type order() const
		{
			return this->order_;
		}

		/// retrieves the size of pixel format in bytes
		bytes_type bytes() const
		{
			return this->bytes_;
		}

		name_type       name_;
		order_type      order_;
		bytes_type      bytes_;
	};

	/// default constructor.
	Format()
		: kind_()
	{};

	/// constructor with parameter
	Format(kind_type const kind)
		: kind_(kind)
	{
	}

#if HRYKY_USE_SDL
	struct SDLFormat
	{
		explicit SDLFormat(uint32_t raw)
			: raw_(raw)
		{
		}

		uint32_t raw_;
	};

	/// constructor with SDL_PIXELFORMAT.
	Format(SDLFormat const & sdl_format);

	/// retrieves SDL_PIXELFORMAT.
	uint32_t sdl_format() const;
#endif // HRYKY_USE_SDL

	/// destructor.
	~Format() {};

	/// copy constructor.
	Format(Format const & rhs)
		: hryky_copy_member(kind)
	{
	};

	/// assignment operator.
	Format & operator=(Format const & rhs)
	{
		this->kind_ = rhs.kind_;
		return *this;
	};

	/// retrieves the characteristic of a pixel format.
	Traits const & traits() const;

	/// retrieves the identifier of format
	kind_type kind() const
	{
		return this->kind_;
	}

	/// outputs the information through stream.
	template <typename StreamT>
	StreamT & write_to(StreamT & out) const;

	/// interchanges the each internal resources of two instances.
	void swap(this_type & src);

protected :

private :

	kind_type kind_;

};
//------------------------------------------------------------------------------
// defines public member functions
//------------------------------------------------------------------------------
/**
  @brief outputs the information through stream.
 */
template <typename StreamT>
StreamT & hryky::pixel::Format::write_to(StreamT & out) const
{
	stream::map::Scope<StreamT> const map(out);
	hryky_write_member(kind);
	return out;
}
//------------------------------------------------------------------------------
// defines protected member functions
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// defines private member functions
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// restores the warnings
//------------------------------------------------------------------------------
#pragma hryky_pragma_pop_warning
#endif // PIXEL_FORMAT_H_20120204091312050
// end of file


text:
function show_help() {

    echo "
    ###################################################################################################################
    #
    # This script allows to run small examples showing Omid functionality and APIs. These are the examples provided:
    #
    # 1) basic -> Executes a transaction encompassing a multi-row modification in HBase
    # 2) si -> Shows how Omid preserves Snapshot Isolation guarantees when concurrent transactions access shared data
    # 3) conf -> Basic example showing Omid client configuration options
    #
    # See the source-code to get more details about each example.
    #
    # The Omid examples can be executed with the following command pattern:
    #
    # $ $0 <example> [ tablename ] [column family name]
    #
    # where:
    # - <example> can be [ basic | si | conf | parallel ]
    #
    # Example execution:
    # ------------------
    #
    # $0 basic
    #
    # will run the basic example with the default options
    #
    # $ $0 basic myHBaseTable myCF
    #
    # will run the basic example using 'myHBaseTable' as table name and 'myCF' as column family.
    # All Omid client-related configuration settings assume their default values. The default values for the settings
    # can be found in 'omid-client-config.yml' and 'default-hbase-omid-client-config.yml' files in the source code.
    #
    ###################################################################################################################
    "

}

fileNotFound(){
    echo "omid-examples.jar not found!";
    exit 1;
}

# ---------------------------------------------------------------------------------------------------------------------
# --------------------------------------------- SCRIPT STARTS HERE ----------------------------------------------------
# ---------------------------------------------------------------------------------------------------------------------

SCRIPTDIR=`dirname $0`
cd $SCRIPTDIR;
SCRIPTDIR=`pwd`

# ---------------------------------------------------------------------------------------------------------------------
# Check if HADOOP_CONF_DIR and HBASE_CONF_DIR are set
# ---------------------------------------------------------------------------------------------------------------------

if [ -z ${HADOOP_CONF_DIR+x} ]; then echo "WARNING: HADOOP_CONF_DIR is unset"; else echo "HADOOP_CONF_DIR is set to '$HADOOP_CONF_DIR'"; fi
if [ -z ${HBASE_CONF_DIR+x} ]; then echo "WARNING: HBASE_CONF_DIR is unset"; else echo "HBASE_CONF_DIR is set to '$HBASE_CONF_DIR'"; fi

# ---------------------------------------------------------------------------------------------------------------------
# Check if jar exists and configure classpath
# ---------------------------------------------------------------------------------------------------------------------

[ ! -f "omid-examples.jar" ] && fileNotFound

KLASSPATH=omid-examples.jar:${HBASE_CONF_DIR}:${HADOOP_CONF_DIR}:${SCRIPTDIR}/conf

for jar in ./lib/*.jar; do
    if [ -f "$jar" ]; then
        KLASSPATH=$KLASSPATH:$jar
    fi
done

# ---------------------------------------------------------------------------------------------------------------------
# Parse CLI user args
# ---------------------------------------------------------------------------------------------------------------------

USER_OPTION=$1
shift
case ${USER_OPTION} in
    basic)
        java -cp $KLASSPATH -Dlog4j.configuration=file:${SCRIPTDIR}/conf/log4j.properties org.apache.omid.examples.BasicExample "$@"
        ;;
    si)
        java -cp $KLASSPATH -Dlog4j.configuration=file:${SCRIPTDIR}/conf/log4j.properties org.apache.omid.examples.SnapshotIsolationExample "$@"
        ;;
    parallel)
        java -cp $KLASSPATH -Dlog4j.configuration=file:${SCRIPTDIR}/conf/log4j.properties org.apache.omid.examples.ParallelExecution "$@"
        ;;
    conf)
        java -cp $KLASSPATH -Dlog4j.configuration=file:${SCRIPTDIR}/conf/log4j.properties org.apache.omid.examples.ConfigurationExample "$@"
        ;;
    *)
        show_help
        ;;
esac


text:
namespace Microsoft.Azure.Management.AppService.Fluent.Models
{
    using Microsoft.Rest;
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// Contact information for domain registration. If 'Domain Privacy' option
    /// is not selected then the contact information is made publicly available
    /// through the Whois
    /// directories as per ICANN requirements.
    /// </summary>
    public partial class Contact
    {
        /// <summary>
        /// Initializes a new instance of the Contact class.
        /// </summary>
        public Contact()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the Contact class.
        /// </summary>
        /// <param name="email">Email address.</param>
        /// <param name="nameFirst">First name.</param>
        /// <param name="nameLast">Last name.</param>
        /// <param name="phone">Phone number.</param>
        /// <param name="addressMailing">Mailing address.</param>
        /// <param name="fax">Fax number.</param>
        /// <param name="jobTitle">Job title.</param>
        /// <param name="nameMiddle">Middle name.</param>
        /// <param name="organization">Organization contact belongs to.</param>
        public Contact(string email, string nameFirst, string nameLast, string phone, Address addressMailing = default(Address), string fax = default(string), string jobTitle = default(string), string nameMiddle = default(string), string organization = default(string))
        {
            AddressMailing = addressMailing;
            Email = email;
            Fax = fax;
            JobTitle = jobTitle;
            NameFirst = nameFirst;
            NameLast = nameLast;
            NameMiddle = nameMiddle;
            Organization = organization;
            Phone = phone;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets mailing address.
        /// </summary>
        [JsonProperty(PropertyName = "addressMailing")]
        public Address AddressMailing { get; set; }

        /// <summary>
        /// Gets or sets email address.
        /// </summary>
        [JsonProperty(PropertyName = "email")]
        public string Email { get; set; }

        /// <summary>
        /// Gets or sets fax number.
        /// </summary>
        [JsonProperty(PropertyName = "fax")]
        public string Fax { get; set; }

        /// <summary>
        /// Gets or sets job title.
        /// </summary>
        [JsonProperty(PropertyName = "jobTitle")]
        public string JobTitle { get; set; }

        /// <summary>
        /// Gets or sets first name.
        /// </summary>
        [JsonProperty(PropertyName = "nameFirst")]
        public string NameFirst { get; set; }

        /// <summary>
        /// Gets or sets last name.
        /// </summary>
        [JsonProperty(PropertyName = "nameLast")]
        public string NameLast { get; set; }

        /// <summary>
        /// Gets or sets middle name.
        /// </summary>
        [JsonProperty(PropertyName = "nameMiddle")]
        public string NameMiddle { get; set; }

        /// <summary>
        /// Gets or sets organization contact belongs to.
        /// </summary>
        [JsonProperty(PropertyName = "organization")]
        public string Organization { get; set; }

        /// <summary>
        /// Gets or sets phone number.
        /// </summary>
        [JsonProperty(PropertyName = "phone")]
        public string Phone { get; set; }

        /// <summary>
        /// Validate the object.
        /// </summary>
        /// <exception cref="ValidationException">
        /// Thrown if validation fails
        /// </exception>
        public virtual void Validate()
        {
            if (Email == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "Email");
            }
            if (NameFirst == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "NameFirst");
            }
            if (NameLast == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "NameLast");
            }
            if (Phone == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "Phone");
            }
            if (AddressMailing != null)
            {
                AddressMailing.Validate();
            }
        }
    }
}


text:
// Autogenerated from vk-api-schema. Please don't edit it manually.
package com.vk.api.sdk.objects.widgets.responses;

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import com.vk.api.sdk.objects.Validable;
import com.vk.api.sdk.objects.annotations.Required;
import com.vk.api.sdk.objects.widgets.WidgetPage;
import java.util.List;
import java.util.Objects;

/**
 * GetPagesResponse object
 */
public class GetPagesResponse implements Validable {
    /**
     * Total number
     */
    @SerializedName("count")
    @Required
    private Integer count;

    @SerializedName("pages")
    @Required
    private List<WidgetPage> pages;

    public Integer getCount() {
        return count;
    }

    public GetPagesResponse setCount(Integer count) {
        this.count = count;
        return this;
    }

    public List<WidgetPage> getPages() {
        return pages;
    }

    public GetPagesResponse setPages(List<WidgetPage> pages) {
        this.pages = pages;
        return this;
    }

    @Override
    public int hashCode() {
        return Objects.hash(pages, count);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        GetPagesResponse getPagesResponse = (GetPagesResponse) o;
        return Objects.equals(pages, getPagesResponse.pages) &&
                Objects.equals(count, getPagesResponse.count);
    }

    @Override
    public String toString() {
        final Gson gson = new Gson();
        return gson.toJson(this);
    }

    public String toPrettyString() {
        final StringBuilder sb = new StringBuilder("GetPagesResponse{");
        sb.append("pages=").append(pages);
        sb.append(", count=").append(count);
        sb.append('}');
        return sb.toString();
    }
}


text:
`jju` - a set of utilities to work with JSON / JSON5 documents

[![npm version badge](https://img.shields.io/npm/v/jju.svg)](https://www.npmjs.org/package/jju)
[![travis badge](http://img.shields.io/travis/rlidwka/jju.svg)](https://travis-ci.org/rlidwka/jju)
[![downloads badge](http://img.shields.io/npm/dm/jju.svg)](https://www.npmjs.org/package/jju)

## Installation

```
npm install jju
```

## Usage

This module provides following functions:

1. [jju.parse()](#jjuparse-function) parses json/json5 text and returns a javascript value it corresponds to
2. [jju.stringify()](#jjustringify-function) converts javascript value to an appropriate json/json5 text
3. [jju.tokenize()](#jjutokenize-function) parses json/json5 text and returns an array of tokens it consists of ([see demo](http://rlidwka.github.io/jju/tokenizer.html))
4. [jju.analyze()](#jjuanalyze-function) parses json/json5 text and tries to guess indentation, quoting style, etc.
5. [jju.update()](#jjuupdate-function) changes json/json5 text, preserving original formatting as much as possible ([see demo](http://rlidwka.github.io/jju/editor.html))

All functions are able to work with a standard JSON documents. `jju.parse()` and `jju.stringify()` are better in some cases, but slower than native `JSON.parse()` and `JSON.stringify()` versions. Detailed description see below.

### jju.parse() function

```javascript
/*
 * Main syntax:
 *
 * `text` - text to parse, type: String
 * `options` - parser options, type: Object
 */
jju.parse(text[, options])

// compatibility syntax
jju.parse(text[, reviver])
```

Options:

 - reserved\_keys - what to do with reserved keys (String, default="ignore")
   - "ignore" - ignore reserved keys
   - "throw" - throw SyntaxError in case of reserved keys
   - "replace" - replace reserved keys, this is the default JSON.parse behaviour, unsafe

     Reserved keys are keys that exist in an empty object (`hasOwnProperty`, `__proto__`, etc.).

```javascript
// 'ignore' will cause reserved keys to be ignored:
parse('{hasOwnProperty: 1}', {reserved_keys: 'ignore'}) == {}
parse('{hasOwnProperty: 1, x: 2}', {reserved_keys: 'ignore'}).hasOwnProperty('x') == true

// 'throw' will cause SyntaxError in these cases:
parse('{hasOwnProperty: 1}', {reserved_keys: 'throw'}) == SyntaxError

// 'replace' will replace reserved keys with new ones:
parse('{hasOwnProperty: 1}', {reserved_keys: 'throw'}) == {hasOwnProperty: 1}
parse('{hasOwnProperty: 1, x: 2}', {reserved_keys: 'ignore'}).hasOwnProperty('x') == TypeError
```

 - null\_prototype - create object as Object.create(null) instead of '{}' (Boolean)

   if `reserved_keys != 'replace'`, default is **false**

   if `reserved_keys == 'replace'`, default is **true**

   It is usually unsafe and not recommended to change this option to false in the last case.

 - reviver - reviver function - Function

   This function should follow JSON specification

 - mode - operation mode, set it to 'json' if you want to throw on non-strict json files (String)

### jju.stringify() function

```javascript
/*
 * Main syntax:
 *
 * `value` - value to serialize, type: *
 * `options` - serializer options, type: Object
 */
jju.stringify(value[, options])

// compatibility syntax
jju.stringify(value[, replacer [, indent])
```

Options:

 - ascii - output ascii only (Boolean, default=false)
   If this option is enabled, output will not have any characters except of 0x20-0x7f.

 - indent - indentation (String, Number or Boolean, default='\t')
   This option follows JSON specification.

 - quote - enquoting char (String, "'" or '"', default="'")
 - quote\_keys - whether keys quoting in objects is required or not (String, default=false)
   If you want `{"q": 1}` instead of `{q: 1}`, set it to true.

 - sort\_keys - sort all keys while stringifying (Boolean or Function, default=false)
   By default sort order will depend on implementation, with v8 it's insertion order. If set to `true`, all keys (but not arrays) will be sorted alphabetically. You can provide your own sorting function as well.

 - replacer - replacer function or array (Function or Array)
   This option follows JSON specification.

 - no\_trailing\_comma = don't output trailing comma (Boolean, default=false)
   If this option is set, arrays like this `[1,2,3,]` will never be generated. Otherwise they may be generated for pretty printing.

 - mode - operation mode, set it to 'json' if you want correct json in the output (String)

   Currently it's either 'json' or something else. If it is 'json', following options are implied:

   - options.quote = '"'
   - options.no\_trailing\_comma = true
   - options.quote\_keys = true
   - '\x' literals are not used

### jju.tokenize() function

```javascript
/*
 * Main syntax:
 *
 * `text` - text to tokenize, type: String
 * `options` - parser options, type: Object
 */
jju.tokenize(text[, options])
```

Options are the same as for the `jju.parse` function.

Return value is an array of tokens, where each token is an object:

 - raw (String) - raw text of this token, if you join all raw's, you will get the original document
 - type (String) - type of the token, can be `whitespace`, `comment`, `key`, `literal`, `separator` or `newline`
 - stack (Array) - path to the current token in the syntax tree
 - value - value of the token if token is a `key` or `literal`

You can check tokenizer for yourself using [this demo](http://rlidwka.github.io/jju/tokenizer.html).

### jju.analyze() function

```javascript
/*
 * Main syntax:
 *
 * `text` - text to analyze, type: String
 * `options` - parser options, type: Object
 */
jju.analyze(text[, options])
```

Options are the same as for the `jju.parse` function.

Return value is an object defining a programming style in which the document was written.

 - indent (String) - preferred indentation
 - newline (String) - preferred newline
 - quote (String) - `"` or `'` depending on which quote is preferred
 - quote\_keys (Boolean) - `true` if unquoted keys were used at least once
 - has\_whitespace (Boolean) - `true` if input has a whitespace token
 - has\_comments (Boolean) - `true` if input has a comment token
 - has\_newlines (Boolean) - `true` if input has a newline token
 - has\_trailing\_comma (Boolean) - `true` if input has at least one trailing comma

### jju.update() function

```javascript
/*
 * Main syntax:
 *
 * `text` - original text, type: String
 * `new_value` - new value you want to set
 * `options` - parser or stringifier options, type: Object
 */
jju.update(text, new_value[, options])
```

If you want to update a JSON document, here is the general approach:

```javascript
// here is your original JSON document:
var input = '{"foo": "bar", "baz": 123}'

// you need to parse it first:
var json = jju.parse(input, {mode: 'json'})
// json is { foo: 'bar', baz: 123 }

// then you can change it as you like:
json.foo = 'quux'
json.hello = 'world'

// then you run an update function to change the original json:
var output = jju.update(input, json, {mode: 'json'})
// output is '{"foo": "quux", "baz": 123, "hello": "world"}'
```

Look at [this demo](http://rlidwka.github.io/jju/editor.html) to test various types of json.

## Advantages over existing JSON libraries

In a few cases it makes sense to use this module instead of built-in JSON methods.

Parser:
 - better error reporting with source code and line numbers

In case of syntax error, JSON.parse does not return any good information to the user. This module does:

```
$ node -e 'require("jju").parse("[1,1,1,1,invalid]")'

SyntaxError: Unexpected token 'i' at 0:9
[1,1,1,1,invalid]
         ^
```

This module is about 5 times slower, so if user experience matters to you more than performance, use this module. If you're working with a lot of machine-generated data, use JSON.parse instead.

Stringifier:
 - util.inspect-like pretty printing

This module behaves more smart when dealing with object and arrays, and does not always print newlines in them:

```
$ node -e 'console.log(require("./").stringify([[,,,],,,[,,,,]], {mode:"json"}))'
[
        [null, null, null],
        null,
        null,
        [null, null, null, null]
]
```

JSON.stringify will split this into 15 lines, and it's hard to read.

Yet again, this feature comes with a performance hit, so if user experience matters to you more than performance, use this module. If your JSON will be consumed by machines, use JSON.stringify instead.

As a rule of thumb, if you use "space" argument to indent your JSON, you'd better use this module instead.


text:
/**
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
 */
package com.codeup.pagination;

import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class PaginationTest {
    private PaginationStorage<Object> storage;
    private int pageSize;

    @Before
    public void createStorage() {
        storage = mock(PaginationStorage.class);
        pageSize = 10;
    }

    @Test
    public void it_knows_when_there_is_no_pages_to_show() {
        int page = 1;
        when(storage.itemsCount()).thenReturn(0L);
        Pagination<Object> pagination = new Pagination<>(pageSize, storage, page);

        assertFalse(pagination.hasPages());
    }

    @Test
    public void it_calculates_number_of_pages() {
        int page = 1;
        when(storage.itemsCount()).thenReturn(23L);
        Pagination<Object> pagination = new Pagination<>(pageSize, storage, page);

        assertEquals(3, pagination.pagesCount());
    }

    @Test
    public void it_knows_when_it_is_the_final_page() {
        int page = 3;
        when(storage.itemsCount()).thenReturn(23L);
        Pagination<Object> pagination = new Pagination<>(pageSize, storage, page);

        assertFalse(pagination.hasNextPage());
    }

    @Test
    public void it_knows_when_it_is_the_first_page() {
        int page = 1;
        when(storage.itemsCount()).thenReturn(23L);
        Pagination<Object> pagination = new Pagination<>(pageSize, storage, page);

        assertFalse(pagination.hasPreviousPage());
    }

    @Test
    public void it_knows_the_next_page() {
        int page = 2;
        when(storage.itemsCount()).thenReturn(23L);
        Pagination<Object> pagination = new Pagination<>(pageSize, storage, page);

        assertEquals(3, pagination.nextPage());
    }

    @Test
    public void it_knows_the_previous_page() {
        int page = 3;
        when(storage.itemsCount()).thenReturn(23L);
        Pagination<Object> pagination = new Pagination<>(pageSize, storage, page);

        assertEquals(2, pagination.previousPage());
    }

    @Test
    public void it_normalize_the_page_value_if_its_bigger_than_the_count_of_pages() {
        int page = 100;
        int offset = 20;
        List<Object> items = new ArrayList<>(
            Arrays.asList(new Object(), new Object(), new Object())
        );
        when(storage.itemsCount()).thenReturn(23L);
        when(storage.slice(offset, pageSize)).thenReturn(items);
        Pagination<Object> pagination = new Pagination<>(pageSize, storage, page);

        assertFalse(pagination.hasNextPage());
        assertEquals(2, pagination.previousPage());
        assertEquals(3, pagination.pageItems().size());
    }

    @Test
    public void it_normalizes_the_page_value_if_its_negative_or_zero() {
        int page = -2;
        when(storage.itemsCount()).thenReturn(23L);
        Pagination<Object> pagination = new Pagination<>(pageSize, storage, page);

        assertFalse(pagination.hasPreviousPage());
        assertEquals(2, pagination.nextPage());
    }
}