text:
<?xml version="1.0" encoding="utf-8"?>
<extension version="1.7" type="plugin" group="resources">
	<name>Resources - Share</name>
	<author>HUBzero</author>
	<authorUrl>hubzero.org</authorUrl>
	<authorEmail>support@hubzero.org</authorEmail>
	<copyright>Copyright 2005-2019 HUBzero Foundation, LLC.</copyright>
	<license>http://opensource.org/licenses/MIT MIT</license>
	<description>PLG_RESOURCES_SHARE_XML_DESCRIPTION</description>
	<files>
		<filename plugin="share">share.php</filename>
	</files>
	<languages>
	</languages>
	<config>
		<fields name="params">
			<fieldset name="basic">
				<field name="icons_limit" type="text" size="5" default="7" label="PLG_RESOURCES_SHARE_LIMIT_LABEL" description="PLG_RESOURCES_SHARE_LIMIT_DESC"/>
				<field name="share_facebook" type="radio" default="1" label="PLG_RESOURCES_SHARE_SHOW_FACEBOOK_LABEL" description="PLG_RESOURCES_SHARE_SHOW_FACEBOOK_DESC">
					<option value="0">JNO</option>
					<option value="1">JYES</option>
				</field>
				<field name="share_twitter" type="radio" default="1" label="PLG_RESOURCES_SHARE_SHOW_TWITTER_LABEL" description="PLG_RESOURCES_SHARE_SHOW_TWITTER_DESC">
					<option value="0">JNO</option>
					<option value="1">JYES</option>
				</field>
				<field name="share_google" type="radio" default="1" label="PLG_RESOURCES_SHARE_SHOW_GOOGLE_LABEL" description="PLG_RESOURCES_SHARE_SHOW_GOOGLE_DESC">
					<option value="0">JNO</option>
					<option value="1">JYES</option>
				</field>
				<field name="share_delicious" type="radio" default="1" label="PLG_RESOURCES_SHARE_SHOW_DELICIOUS_LABEL" description="PLG_RESOURCES_SHARE_SHOW_DELICIOUS_DESC">
					<option value="0">JNO</option>
					<option value="1">JYES</option>
				</field>
				<field name="share_reddit" type="radio" default="1" label="PLG_RESOURCES_SHARE_SHOW_REDDIT_LABEL" description="PLG_RESOURCES_SHARE_SHOW_REDDIT_DESC">
					<option value="0">JNO</option>
					<option value="1">JYES</option>
				</field>
				<field name="share_linkedin" type="radio" default="1" label="PLG_RESOURCES_SHARE_SHOW_LINKEDIN_LABEL" description="PLG_RESOURCES_SHARE_SHOW_LINKEDIN_DESC">
					<option value="0">JNO</option>
					<option value="1">JYES</option>
				</field>
			</fieldset>
		</fields>
	</config>
</extension>

redpajama_set_name: RedPajamaGithub


text:
package org.elasticsearch.http;

import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Streamable;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentBuilderString;

import java.io.IOException;

public class HttpStats implements Streamable, ToXContent {

    private long serverOpen;
    private long totalOpen;

    HttpStats() {

    }

    public HttpStats(long serverOpen, long totalOpen) {
        this.serverOpen = serverOpen;
        this.totalOpen = totalOpen;
    }

    public long serverOpen() {
        return this.serverOpen;
    }

    public long getServerOpen() {
        return serverOpen();
    }

    public long totalOpen() {
        return this.totalOpen;
    }

    public long getTotalOpen() {
        return this.totalOpen;
    }

    public static HttpStats readHttpStats(StreamInput in) throws IOException {
        HttpStats stats = new HttpStats();
        stats.readFrom(in);
        return stats;
    }

    @Override
    public void readFrom(StreamInput in) throws IOException {
        serverOpen = in.readVLong();
        totalOpen = in.readVLong();
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        out.writeVLong(serverOpen);
        out.writeVLong(totalOpen);
    }

    static final class Fields {
        static final XContentBuilderString HTTP = new XContentBuilderString("http");
        static final XContentBuilderString CURRENT_OPEN = new XContentBuilderString("current_open");
        static final XContentBuilderString TOTAL_OPENED = new XContentBuilderString("total_opened");
    }

    @Override
    public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
        builder.startObject(Fields.HTTP);
        builder.field(Fields.CURRENT_OPEN, serverOpen);
        builder.field(Fields.TOTAL_OPENED, totalOpen);
        builder.endObject();
        return builder;
    }
}


text:
namespace Lucene
{
    TermsHashPerField::TermsHashPerField(DocInverterPerFieldPtr docInverterPerField, TermsHashPerThreadPtr perThread, TermsHashPerThreadPtr nextPerThread, FieldInfoPtr fieldInfo)
    {
        this->_docInverterPerField = docInverterPerField;
        this->_perThread = perThread;
        this->nextPerThread = nextPerThread;
        this->fieldInfo = fieldInfo;
    }

    TermsHashPerField::~TermsHashPerField()
    {
    }

    void TermsHashPerField::initialize()
    {
        this->postingsCompacted = false;
        this->numPostings = 0;
        this->postingsHashSize = 4;
        this->postingsHashHalfSize = this->postingsHashSize / 2;
        this->postingsHashMask = this->postingsHashSize - 1;
        this->postingsHash = Collection<RawPostingListPtr>::newInstance(postingsHashSize);
        this->doCall = false;
        this->doNextCall = false;
        this->intUptoStart = 0;

        TermsHashPerThreadPtr perThread(_perThread);
        intPool = perThread->intPool;
        charPool = perThread->charPool;
        bytePool = perThread->bytePool;
        docState = perThread->docState;
        DocInverterPerFieldPtr docInverterPerField(_docInverterPerField);
        fieldState = docInverterPerField->fieldState;
        this->consumer = perThread->consumer->addField(shared_from_this(), fieldInfo);
        streamCount = consumer->getStreamCount();
        numPostingInt = 2 * streamCount;
        if (nextPerThread)
            nextPerField = boost::dynamic_pointer_cast<TermsHashPerField>(nextPerThread->addField(docInverterPerField, fieldInfo));
    }

    void TermsHashPerField::shrinkHash(int32_t targetSize)
    {
        BOOST_ASSERT(postingsCompacted || numPostings == 0);

        int32_t newSize = 4;
        if (newSize != postingsHash.size())
        {
            postingsHash.resize(newSize);
            postingsHashSize = newSize;
            postingsHashHalfSize = newSize / 2;
            postingsHashMask = newSize - 1;
        }
        MiscUtils::arrayFill(postingsHash.begin(), 0, postingsHash.size(), RawPostingListPtr());
    }

    void TermsHashPerField::reset()
    {
        if (!postingsCompacted)
            compactPostings();
        BOOST_ASSERT(numPostings <= postingsHash.size());
        if (numPostings > 0)
        {
            TermsHashPtr(TermsHashPerThreadPtr(_perThread)->_termsHash)->recyclePostings(postingsHash, numPostings);
            MiscUtils::arrayFill(postingsHash.begin(), 0, numPostings, RawPostingListPtr());
            numPostings = 0;
        }
        postingsCompacted = false;
        if (nextPerField)
            nextPerField->reset();
    }

    void TermsHashPerField::abort()
    {
        SyncLock syncLock(this);
        reset();
        if (nextPerField)
            nextPerField->abort();
    }

    void TermsHashPerField::initReader(ByteSliceReaderPtr reader, RawPostingListPtr p, int32_t stream)
    {
        BOOST_ASSERT(stream < streamCount);
        IntArray ints(intPool->buffers[p->intStart >> DocumentsWriter::INT_BLOCK_SHIFT]);
        int32_t upto = (p->intStart & DocumentsWriter::INT_BLOCK_MASK);
        reader->init(bytePool, p->byteStart + stream * ByteBlockPool::FIRST_LEVEL_SIZE(), ints[upto + stream]);
    }

    void TermsHashPerField::compactPostings()
    {
        SyncLock syncLock(this);
        int32_t upto = 0;
        for (int32_t i = 0; i < postingsHashSize; ++i)
        {
            if (postingsHash[i])
            {
                if (upto < i)
                {
                    postingsHash[upto] = postingsHash[i];
                    postingsHash[i].reset();
                }
                ++upto;
            }
        }

        BOOST_ASSERT(upto == numPostings);
        postingsCompacted = true;
    }

    struct comparePostings
    {
        comparePostings(Collection<CharArray> buffers)
    {
            this->buffers = buffers;
    }

        /// Compares term text for two Posting instance
        inline bool operator()(const RawPostingListPtr& first, const RawPostingListPtr& second) const
    {
            if (first == second)
            return false;

            wchar_t* text1 = buffers[first->textStart >> DocumentsWriter::CHAR_BLOCK_SHIFT].get();
            int32_t pos1 = (first->textStart & DocumentsWriter::CHAR_BLOCK_MASK);
            wchar_t* text2 = buffers[second->textStart >> DocumentsWriter::CHAR_BLOCK_SHIFT].get();
            int32_t pos2 = (second->textStart & DocumentsWriter::CHAR_BLOCK_MASK);

        BOOST_ASSERT(text1 != text2 || pos1 != pos2);

        while (true)
        {
            wchar_t c1 = text1[pos1++];
            wchar_t c2 = text2[pos2++];
            if (c1 != c2)
            {
                if (c2 == UTF8Base::UNICODE_TERMINATOR)
                    return false;
                else if (c1 == UTF8Base::UNICODE_TERMINATOR)
                    return true;
                else
                    return (c1 < c2);
            }
            else
            {
                    // This method should never compare equal postings unless first == second
                BOOST_ASSERT(c1 != UTF8Base::UNICODE_TERMINATOR);
            }
        }
        }

        Collection<CharArray> buffers;
    };

    Collection<RawPostingListPtr> TermsHashPerField::sortPostings()
    {
        compactPostings();
        std::sort(postingsHash.begin(), postingsHash.begin() + numPostings, comparePostings(charPool->buffers));
        return postingsHash;
    }

    bool TermsHashPerField::postingEquals(const wchar_t* tokenText, int32_t tokenTextLen)
    {
        wchar_t* text = TermsHashPerThreadPtr(_perThread)->charPool->buffers[p->textStart >> DocumentsWriter::CHAR_BLOCK_SHIFT].get();
        BOOST_ASSERT(text);
        int32_t pos = (p->textStart & DocumentsWriter::CHAR_BLOCK_MASK);
        int32_t tokenPos = 0;
        for (; tokenPos < tokenTextLen; ++pos, ++tokenPos)
        {
            if (tokenText[tokenPos] != text[pos])
                return false;
        }
        return (text[pos] == UTF8Base::UNICODE_TERMINATOR);
    }

    void TermsHashPerField::start(FieldablePtr field)
    {
        termAtt = fieldState->attributeSource->addAttribute<TermAttribute>();
        consumer->start(field);
        if (nextPerField)
            nextPerField->start(field);
    }

    bool TermsHashPerField::start(Collection<FieldablePtr> fields, int32_t count)
    {
        doCall = consumer->start(fields, count);
        if (nextPerField)
            doNextCall = nextPerField->start(fields, count);
        return (doCall || doNextCall);
    }

    void TermsHashPerField::add(int32_t textStart)
    {
        // Secondary entry point (for 2nd and subsequent TermsHash), we hash by textStart
        int32_t code = textStart;

        int32_t hashPos = (code & postingsHashMask);

        BOOST_ASSERT(!postingsCompacted);

        // Locate RawPostingList in hash
        p = postingsHash[hashPos];

        if (p && p->textStart != textStart)
        {
            // Conflict: keep searching different locations in the hash table.
            int32_t inc = (((code >> 8) + code) | 1);
            do
            {
                code += inc;
                hashPos = (code & postingsHashMask);
                p = postingsHash[hashPos];
            }
            while (p && p->textStart != textStart);
        }

        if (!p)
        {
            // First time we are seeing this token since we last flushed the hash.
            TermsHashPerThreadPtr perThread(_perThread);

            // Refill?
            if (perThread->freePostingsCount == 0)
                perThread->morePostings();

            // Pull next free RawPostingList from free list
            p = perThread->freePostings[--perThread->freePostingsCount];
            BOOST_ASSERT(p);

            p->textStart = textStart;

            BOOST_ASSERT(!postingsHash[hashPos]);
            postingsHash[hashPos] = p;
            ++numPostings;

            if (numPostings == postingsHashHalfSize)
                rehashPostings(2 * postingsHashSize);

            // Init stream slices
            if (numPostingInt + intPool->intUpto > DocumentsWriter::INT_BLOCK_SIZE)
                intPool->nextBuffer();

            if (DocumentsWriter::BYTE_BLOCK_SIZE - bytePool->byteUpto < numPostingInt * ByteBlockPool::FIRST_LEVEL_SIZE())
                bytePool->nextBuffer();

            intUptos = intPool->buffer;
            intUptoStart = intPool->intUpto;
            intPool->intUpto += streamCount;

            p->intStart = intUptoStart + intPool->intOffset;

            for (int32_t i = 0; i < streamCount; ++i)
            {
                int32_t upto = bytePool->newSlice(ByteBlockPool::FIRST_LEVEL_SIZE());
                intUptos[intUptoStart + i] = upto + bytePool->byteOffset;
            }
            p->byteStart = intUptos[intUptoStart];

            consumer->newTerm(p);
        }
        else
        {
            intUptos = intPool->buffers[p->intStart >> DocumentsWriter::INT_BLOCK_SHIFT];
            intUptoStart = (p->intStart & DocumentsWriter::INT_BLOCK_MASK);
            consumer->addTerm(p);
        }
    }

    void TermsHashPerField::add()
    {
        BOOST_ASSERT(!postingsCompacted);

        // Get the text of this term.
        wchar_t* tokenText = termAtt->termBufferArray();
        int32_t tokenTextLen = termAtt->termLength();

        // Compute hashcode and replace any invalid UTF16 sequences
        int32_t downto = tokenTextLen;
        int32_t code = 0;

        while (downto > 0)
        {
            wchar_t ch = tokenText[--downto];

            #ifdef LPP_UNICODE_CHAR_SIZE_2
            if (ch >= UTF8Base::TRAIL_SURROGATE_MIN && ch <= UTF8Base::TRAIL_SURROGATE_MAX)
            {
                if (downto == 0)
                {
                    // Unpaired
                    ch = UTF8Base::UNICODE_REPLACEMENT_CHAR;
                    tokenText[downto] = ch;
                }
                else
                {
                    wchar_t ch2 = tokenText[downto - 1];
                    if (ch2 >= UTF8Base::LEAD_SURROGATE_MIN && ch2 <= UTF8Base::LEAD_SURROGATE_MAX)
                    {
                        // OK: high followed by low.  This is a valid surrogate pair.
                        code = ((code * 31) + ch) * 31 + ch2;
                        --downto;
                        continue;
                    }
                    else
                    {
                        // Unpaired
                        ch = UTF8Base::UNICODE_REPLACEMENT_CHAR;
                        tokenText[downto] = ch;
                    }
                }
            }
            else if (ch >= UTF8Base::LEAD_SURROGATE_MIN && (ch <= UTF8Base::LEAD_SURROGATE_MAX || ch == UTF8Base::UNICODE_TERMINATOR))
            {
                // Unpaired or UTF8Base::UNICODE_TERMINATOR
                ch = UTF8Base::UNICODE_REPLACEMENT_CHAR;
                tokenText[downto] = ch;
            }
            #else
            if (ch == UTF8Base::UNICODE_TERMINATOR)
            {
                // Unpaired or UTF8Base::UNICODE_TERMINATOR
                ch = UTF8Base::UNICODE_REPLACEMENT_CHAR;
                tokenText[downto] = ch;
            }
            #endif

            code = (code * 31) + ch;
        }

        int32_t hashPos = (code & postingsHashMask);

        // Locate RawPostingList in hash
        p = postingsHash[hashPos];

        if (p && !postingEquals(tokenText, tokenTextLen))
        {
            // Conflict: keep searching different locations in the hash table.
            int32_t inc = (((code >> 8) + code) | 1);
            do
            {
                code += inc;
                hashPos = (code & postingsHashMask);
                p = postingsHash[hashPos];
            }
            while (p && !postingEquals(tokenText, tokenTextLen));
        }

        if (!p)
        {
            // First time we are seeing this token since we last flushed the hash.
            int32_t textLen1 = 1 + tokenTextLen;
            if (textLen1 + charPool->charUpto > DocumentsWriter::CHAR_BLOCK_SIZE)
            {
                if (textLen1 > DocumentsWriter::CHAR_BLOCK_SIZE)
                {
                    // Just skip this term, to remain as robust as possible during indexing.  A TokenFilter
                    // can be inserted into the analyzer chain if other behavior is wanted (pruning the term
                    // to a prefix, throwing an exception, etc).

                    if (docState->maxTermPrefix.empty())
                        docState->maxTermPrefix.append(tokenText, std::min((int32_t)30, tokenTextLen));

                    consumer->skippingLongTerm();
                    return;
                }
                charPool->nextBuffer();
            }

            TermsHashPerThreadPtr perThread(_perThread);

            // Refill?
            if (perThread->freePostingsCount == 0)
                perThread->morePostings();

            // Pull next free RawPostingList from free list
            p = perThread->freePostings[--perThread->freePostingsCount];
            BOOST_ASSERT(p);

            wchar_t* text = charPool->buffer.get();
            int32_t textUpto = charPool->charUpto;

            p->textStart = textUpto + charPool->charOffset;
            charPool->charUpto += textLen1;

            MiscUtils::arrayCopy(tokenText, 0, text, textUpto, tokenTextLen);
            text[textUpto + tokenTextLen] = UTF8Base::UNICODE_TERMINATOR;

            BOOST_ASSERT(!postingsHash[hashPos]);
            postingsHash[hashPos] = p;
            ++numPostings;

            if (numPostings == postingsHashHalfSize)
                rehashPostings(2 * postingsHashSize);

            // Init stream slices
            if (numPostingInt + intPool->intUpto > DocumentsWriter::INT_BLOCK_SIZE)
                intPool->nextBuffer();

            if (DocumentsWriter::BYTE_BLOCK_SIZE - bytePool->byteUpto < numPostingInt * ByteBlockPool::FIRST_LEVEL_SIZE())
                bytePool->nextBuffer();

            intUptos = intPool->buffer;
            intUptoStart = intPool->intUpto;
            intPool->intUpto += streamCount;

            p->intStart = intUptoStart + intPool->intOffset;

            for (int32_t i = 0; i < streamCount; ++i)
            {
                int32_t upto = bytePool->newSlice(ByteBlockPool::FIRST_LEVEL_SIZE());
                intUptos[intUptoStart + i] = upto + bytePool->byteOffset;
            }
            p->byteStart = intUptos[intUptoStart];

            consumer->newTerm(p);
        }
        else
        {
            intUptos = intPool->buffers[p->intStart >> DocumentsWriter::INT_BLOCK_SHIFT];
            intUptoStart = (p->intStart & DocumentsWriter::INT_BLOCK_MASK);
            consumer->addTerm(p);
        }

        if (doNextCall)
            nextPerField->add(p->textStart);
    }

    void TermsHashPerField::writeByte(int32_t stream, int8_t b)
    {
        int32_t upto = intUptos[intUptoStart + stream];
        ByteArray bytes(bytePool->buffers[upto >> DocumentsWriter::BYTE_BLOCK_SHIFT]);
        BOOST_ASSERT(bytes);
        int32_t offset = (upto & DocumentsWriter::BYTE_BLOCK_MASK);
        if (bytes[offset] != 0)
        {
            // End of slice; allocate a new one
            offset = bytePool->allocSlice(bytes, offset);
            bytes = bytePool->buffer;
            intUptos[intUptoStart + stream] = offset + bytePool->byteOffset;
        }
        bytes[offset] = b;
        intUptos[intUptoStart + stream]++;
    }

    void TermsHashPerField::writeBytes(int32_t stream, const uint8_t* b, int32_t offset, int32_t length)
    {
        int32_t end = offset + length;
        for (int32_t i = offset; i < end; ++i)
            writeByte(stream, b[i]);
    }

    void TermsHashPerField::writeVInt(int32_t stream, int32_t i)
    {
        BOOST_ASSERT(stream < streamCount);
        while ((i & ~0x7f) != 0)
        {
            writeByte(stream, (uint8_t)((i & 0x7f) | 0x80));
            i = MiscUtils::unsignedShift(i, 7);
        }
        writeByte(stream, (uint8_t)i);
    }

    void TermsHashPerField::finish()
    {
        consumer->finish();
        if (nextPerField)
            nextPerField->finish();
    }

    void TermsHashPerField::rehashPostings(int32_t newSize)
    {
        int32_t newMask = newSize - 1;

        Collection<RawPostingListPtr> newHash(Collection<RawPostingListPtr>::newInstance(newSize));
        TermsHashPerThreadPtr perThread(_perThread);

        for (int32_t i = 0; i < postingsHashSize; ++i)
        {
            RawPostingListPtr p0(postingsHash[i]);
            if (p0)
            {
                int32_t code;
                if (perThread->primary)
                {
                    int32_t start = (p0->textStart & DocumentsWriter::CHAR_BLOCK_MASK);
                    CharArray text = charPool->buffers[p0->textStart >> DocumentsWriter::CHAR_BLOCK_SHIFT];
                    int32_t pos = start;
                    while (text[pos] != UTF8Base::UNICODE_TERMINATOR)
                        ++pos;
                    code = 0;
                    while (pos > start)
                        code = (code * 31) + text[--pos];
                }
                else
                    code = p0->textStart;

                int32_t hashPos = (code & newMask);
                BOOST_ASSERT(hashPos >= 0);
                if (newHash[hashPos])
                {
                    int32_t inc = (((code >> 8) + code) | 1);
                    do
                    {
                        code += inc;
                        hashPos = (code & newMask);
                    }
                    while (newHash[hashPos]);
                }
                newHash[hashPos] = p0;
            }
        }

        postingsHashMask = newMask;
        postingsHash = newHash;
        postingsHashSize = newSize;
        postingsHashHalfSize = (newSize >> 1);
    }
}


text:
layout: page
title: My Team
permalink: /about/my-team/
---

![Heidi Cayzer Massage Therapist](/assets/img/support/heidicayzer.png)

[https://heidicayzer.com](https://heidicayzer.com.au)

Heidi is my wife, and mother of our daughter, Annabelle. Heidi is a qualified massage therapist specialising in Remedial Massage, Pregnancy Massage, Sports Massage and Deep Tissue Therapy. She is a distance runner like myself, holding personal bests of 2:08 (800 metres) and 2:57:20 for the marathon.

![Kingsford Chiropractic Clinic](/assets/img/support/kingsfordchiropractic.jpg)

[https://kingsfordchiropractic.com.au](https://kingsfordchiropractic.com.au)

Kingsford Chiropractic Clinic has over twenty-five years of industry experience. The practice caters for all levels of rehabilitation, from everyday through to elite sports. They have affiliations with the Chiropractors' Association of Australia, Sydney FC and Stanmore Hawks FC. On more than one occassion, Stephen has been able to keep my body in one piece so I can continue to train and race.

![Posso Sports](/assets/img/support/pip.png)

[http://www.possosports.com](http://www.possosports.com)

Posso International Promotions, Inc. Is a leading sports management agency on the global stage and a division of Posso International Promotion, Inc. A corporation registered in Florida USA, Posso Sports has been in existence since 1994 and has expanded to offices in Bogota, Panama, Prague, Milan, and Nairobi. The Posso Futbol brand continues with affiliates and partners in Venezuela, Monaco, Argentina, the Netherlands, Italy, and Spain. With such a large team of experts in the sport, Posso Futbol has been responsible for placing clients in most of the top leagues all over the world.

Derek Froude manages my international race and sponsorship negotiations. He successfully negotiated my marathon debut in Beppu in 2010 which resulted in me running 2:11:00 and making my first major Australian team. He is easy to work with, is very flexible and receptive to any request I have. For any international race requests, please contact Derek [dfroude@possosports.com](mailto:dfroude@possosports.com)

![Randwick Botany Harriers](/assets/img/support/rbh.png)

[http://www.rbharriers.com](http://www.rbharriers.com)

In 1907, the Botany Harriers was founded. Within a year of forming the club had won its first long distance teams championship. According to a 1920 winter fixture card, Botany Harriers were champions in 1908,'09,'10,'11,'12,'13,'14,'15','16,'17,'18 and '19.

In 1959, Botany Harriers amalgamated with Randwick-Kensington to become the now commonly know Randwick-Botany Harriers. Randwick-Botany Harriers is a very strong distance running club, steeped in tradition and have had many athletes compete at the Olympics and Commonwealth Games. With representation at 15 Commonwealth Games, 7 World Championships and 16 Olympics Games, Randwick-Botany has had a lot of experience in major events.They provide a tremendous amount of support to me through registration, uniforms and where appropriate, financial support. I am also the current Club Captain. I am very proud to be a member of a club that is over 100 years old, where all members have a very strong passion for such a global sport.


text:
require 'formula'

module Homebrew
  def pin
    raise FormulaUnspecifiedError if ARGV.named.empty?

    ARGV.resolved_formulae.each do |f|
      if f.pinned?
        opoo "#{f.name} already pinned"
      elsif !f.pinnable?
        onoe "#{f.name} not installed"
      else
        f.pin
      end
    end
  end
end


text:
package com.lookout.borderpatrol.example

import com.lookout.borderpatrol.auth._
import com.lookout.borderpatrol.auth.keymaster._
import com.lookout.borderpatrol.auth.keymaster.Keymaster._
import com.lookout.borderpatrol.auth.keymaster.Tokens._
import com.lookout.borderpatrol.{ServiceMatcher, Manager}
import com.lookout.borderpatrol.sessionx._
import com.lookout.borderpatrol.util.Combinators._
import com.twitter.io.Buf
import com.twitter.finagle.httpx.{Method, Request, Response, Status}
import com.twitter.finagle.httpx.path._
import com.twitter.finagle.httpx.service.RoutingService
import com.twitter.finagle.Service
import com.twitter.util.Future
import io.finch.response.ResponseBuilder

object MockService {

  //  Mock Keymaster identityManager
  val mockKeymasterIdentityService = new Service[Request, Response] {

    val userMap: Map[String, String] = Map(
      ("test1@example.com" -> "password1"),
      ("test2@example.com" -> "password2"),
      ("test3@example.com" -> "password3")
    )

    def apply(request: Request): Future[Response] = {
      val tokens = Tokens(MasterToken("masterT"), ServiceTokens())
      (for {
        email <- request.getParam("e").toFuture
        pass <- request.getParam("p").toFuture
        if userMap(email) == (pass)
      } yield tap(Response(Status.Ok))(res => {
          res.contentString = TokensEncoder(tokens).toString()
          res.contentType = "application/json"
        })) handle {
        case ex => Response(Status.Unauthorized)
      }
    }
  }

  //  Mock Keymaster AccessIssuer
  val mockKeymasterAccessIssuerService = new Service[Request, Response] {
    def apply(request: Request): Future[Response] = {
      val serviceName = request.getParam("services")
      val tokens = Tokens(MasterToken("masterT"), ServiceTokens().add(
        serviceName, ServiceToken(s"SomeServiceData:${serviceName}")))
      tap(Response(Status.Ok))(res => {
        res.contentString = TokensEncoder(tokens).toString()
        res.contentType = "application/json"
      }).toFuture
    }
  }

  //  Mock Login Service
  val mockCheckpointService = new Service[Request, Response] {
    val loginForm = Buf.Utf8(
      """
        |
Example Account Service Login

        |<form action="/signin" method="post">
        |username<input type="text" name="username" />
        |password<input type="password" name="password" />
        |<input type="submit" name="login" value="login" />
        |</form>
        |
      """.stripMargin
    )

    def apply(req: Request): Future[Response] =
      req.method match {
        case Method.Get => {
          val rb = ResponseBuilder(Status.Ok).withContentType(Some("text/html"))
          rb(loginForm).toFuture
        }
        case _ => Future.value(Response(Status.NotFound))
      }
  }

  //  Mock Upstream service
  val mockUpstreamService = new Service[Request, Response] {
    def apply(request: Request): Future[Response] =
      tap(Response(Status.Ok))(res => {
        res.contentString =
          s"""
          |
          |
Welcome to Service @(${request.path})

          |
          """.stripMargin
        res.contentType = "text/html"
      }).toFuture
  }

  def getMockRoutingService(implicit config: ServerConfig): Service[Request, Response] = {
    val checkpointLoginManager = config.findLoginManager("checkpoint")
    val keymasterIdManager = config.findIdentityManager("keymaster")
    val keymasterAccessManager = config.findAccessManager("keymaster")

    val mockKeymasterPathMap = Map(keymasterAccessManager.path -> mockKeymasterAccessIssuerService,
      keymasterIdManager.path -> mockKeymasterIdentityService,
      checkpointLoginManager.path -> mockCheckpointService)

    RoutingService.byMethodAndPathObject {
      case _ -> path if mockKeymasterPathMap.contains(path) => mockKeymasterPathMap(path)
      case _ => mockUpstreamService
    }
  }
}

object service {

  /**
   * Glue that DEMUXes the chain into appropriate identityProvider or accessIssuer
   *
   * @param accessIssuerMap
   * @param identityProviderMap
   */
  case class MainGlueService(identityProviderMap: Map[String, Service[SessionIdRequest, Response]],
                             accessIssuerMap: Map[String, Service[SessionIdRequest, Response]])
  extends Service[SessionIdRequest, Response] {

    def getIdentityProviderService(identityManager: Manager): Service[SessionIdRequest, Response] =
      identityProviderMap.get(identityManager.name) match {
        case Some(s) => s
        case None => throw InvalidConfigError("Failed to find IdentityProvider Service Chain for " +
          identityManager.name)
      }

    def getAccessIssuerService(accessManager: Manager): Service[SessionIdRequest, Response] =
      accessIssuerMap.get(accessManager.name) match {
        case Some(s) => s
        case None => throw InvalidConfigError("Failed to find AccessIssuer Service Chain for " +
          accessManager.name)
      }

    def apply(req: SessionIdRequest): Future[Response] = {
      val p = Path(req.req.req.path)
      /* Upstream service path */
      if (p.startsWith(req.req.serviceId.path))
        getAccessIssuerService(req.req.serviceId.loginManager.accessManager)(req)
      /* LoginPath that processes the login response */
      else if (p.startsWith(req.req.serviceId.loginManager.loginPath))
        getIdentityProviderService(req.req.serviceId.loginManager.identityManager)(req)
      /* Path that handles the LoginManager specific routes */
      else if (p.startsWith(req.req.serviceId.loginManager.path))
        getIdentityProviderService(req.req.serviceId.loginManager.identityManager)(req)
      else tap(Response(Status.NotFound))(r => {
        r.contentString = s"${req.req.req.path}: No IdentityProvider or AccessIssuer found. " +
          s"Returning (${Status.NotFound.code})"
        r.contentType = "text/plain"
      }).toFuture
    }
  }

  /**
   * The sole entry point for all service chains
   */
  def MainServiceChain(implicit config: ServerConfig): Service[Request, Response] = {
    implicit val secretStore = config.secretStore
    val serviceMatcher = ServiceMatcher(config.serviceIdentifiers)
    val identityProviderMap = Map("keymaster" -> keymasterIdentityProviderChain(config.sessionStore))
    val accessIssuerMap = Map("keymaster" -> keymasterAccessIssuerChain(config.sessionStore))

    new ExceptionFilter andThen /* Convert exceptions to responses */
      new ServiceFilter(serviceMatcher) andThen /* Validate that its our service */
      new SessionIdFilter(config.sessionStore) andThen /* Get or allocate Session/SessionId */
      new BorderFilter andThen /* Check if SessionId and path are consistent */
      new MainGlueService(identityProviderMap, accessIssuerMap) /* Glue that connects to identity & access service */
  }
}


text:
if [ $# -ne 1 ]; then
	echo "Usage: ./install.sh PKG_NAME"
	exit 1
fi

echo "Will install $1"

hash docker &>/dev/null || {
	type yum >/dev/null 2>&1 && {
		sudo yum -y install docker
		sudo service docker start
		sudo chkconfig docker on
	}
	type apt-get >/dev/null 2>&1 && {
		sudo apt-get -y install docker
	}
}

type docker >/dev/null 2>&1 || {
	echo 'Unknown linux distribution'
	exit 1
}
sudo docker pull chonglou/$1:latest
sudo docker run -d -p 443:443 -p 80:80 -P --privileged -v /sys/fs/cgroup:/sys/fs/cgroup:ro chonglou/$1:latest /sbin/init


text:
#ifndef BOOST_ASIO_DETAIL_NULL_EVENT_HPP
#define BOOST_ASIO_DETAIL_NULL_EVENT_HPP

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)

#include <boost/asio/detail/push_options.hpp>

#include <boost/asio/detail/push_options.hpp>
#include <boost/config.hpp>
#include <boost/asio/detail/pop_options.hpp>

#if !defined(BOOST_HAS_THREADS)

#include <boost/asio/detail/noncopyable.hpp>

namespace boost {
namespace asio {
namespace detail {

class null_event
  : private noncopyable
{
public:
  // Constructor.
  null_event()
  {
  }

  // Destructor.
  ~null_event()
  {
  }

  // Signal the event.
  template <typename Lock>
  void signal(Lock&)
  {
  }

  // Reset the event.
  template <typename Lock>
  void clear(Lock&)
  {
  }

  // Wait for the event to become signalled.
  template <typename Lock>
  void wait(Lock&)
  {
  }
};

} // namespace detail
} // namespace asio
} // namespace boost

#endif // !defined(BOOST_HAS_THREADS)

#include <boost/asio/detail/pop_options.hpp>

#endif // BOOST_ASIO_DETAIL_NULL_EVENT_HPP


text:
<?php
namespace GuzzleHttp\Tests\Psr7;

use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\FnStream;
use GuzzleHttp\Psr7\NoSeekStream;

class FunctionsTest extends \PHPUnit_Framework_TestCase
{
    public function testCopiesToString()
    {
        $s = Psr7\stream_for('foobaz');
        $this->assertEquals('foobaz', Psr7\copy_to_string($s));
        $s->seek(0);
        $this->assertEquals('foo', Psr7\copy_to_string($s, 3));
        $this->assertEquals('baz', Psr7\copy_to_string($s, 3));
        $this->assertEquals('', Psr7\copy_to_string($s));
    }

    public function testCopiesToStringStopsWhenReadFails()
    {
        $s1 = Psr7\stream_for('foobaz');
        $s1 = FnStream::decorate($s1, array(
            'read' => function () { return ''; }
        ));
        $result = Psr7\copy_to_string($s1);
        $this->assertEquals('', $result);
    }

    public function testCopiesToStream()
    {
        $s1 = Psr7\stream_for('foobaz');
        $s2 = Psr7\stream_for('');
        Psr7\copy_to_stream($s1, $s2);
        $this->assertEquals('foobaz', (string) $s2);
        $s2 = Psr7\stream_for('');
        $s1->seek(0);
        Psr7\copy_to_stream($s1, $s2, 3);
        $this->assertEquals('foo', (string) $s2);
        Psr7\copy_to_stream($s1, $s2, 3);
        $this->assertEquals('foobaz', (string) $s2);
    }

    public function testStopsCopyToStreamWhenWriteFails()
    {
        $s1 = Psr7\stream_for('foobaz');
        $s2 = Psr7\stream_for('');
        $s2 = FnStream::decorate($s2, array('write' => function () { return 0; }));
        Psr7\copy_to_stream($s1, $s2);
        $this->assertEquals('', (string) $s2);
    }

    public function testStopsCopyToSteamWhenWriteFailsWithMaxLen()
    {
        $s1 = Psr7\stream_for('foobaz');
        $s2 = Psr7\stream_for('');
        $s2 = FnStream::decorate($s2, array('write' => function () { return 0; }));
        Psr7\copy_to_stream($s1, $s2, 10);
        $this->assertEquals('', (string) $s2);
    }

    public function testStopsCopyToSteamWhenReadFailsWithMaxLen()
    {
        $s1 = Psr7\stream_for('foobaz');
        $s1 = FnStream::decorate($s1, array('read' => function () { return ''; }));
        $s2 = Psr7\stream_for('');
        Psr7\copy_to_stream($s1, $s2, 10);
        $this->assertEquals('', (string) $s2);
    }

    public function testReadsLines()
    {
        $s = Psr7\stream_for("foo\nbaz\nbar");
        $this->assertEquals("foo\n", Psr7\readline($s));
        $this->assertEquals("baz\n", Psr7\readline($s));
        $this->assertEquals("bar", Psr7\readline($s));
    }

    public function testReadsLinesUpToMaxLength()
    {
        $s = Psr7\stream_for("12345\n");
        $this->assertEquals("123", Psr7\readline($s, 4));
        $this->assertEquals("45\n", Psr7\readline($s));
    }

    public function testReadsLineUntilFalseReturnedFromRead()
    {
        $s = $this->getMockBuilder('GuzzleHttp\Psr7\Stream')
            ->setMethods(array('read', 'eof'))
            ->disableOriginalConstructor()
            ->getMock();
        $s->expects($this->exactly(2))
            ->method('read')
            ->will($this->returnCallback(function () {
                static $c = false;
                if ($c) {
                    return false;
                }
                $c = true;
                return 'h';
            }));
        $s->expects($this->exactly(2))
            ->method('eof')
            ->will($this->returnValue(false));
        $this->assertEquals("h", Psr7\readline($s));
    }

    public function testCalculatesHash()
    {
        $s = Psr7\stream_for('foobazbar');
        $this->assertEquals(md5('foobazbar'), Psr7\hash($s, 'md5'));
    }

    /**
     * @expectedException \RuntimeException
     */
    public function testCalculatesHashThrowsWhenSeekFails()
    {
        $s = new NoSeekStream(Psr7\stream_for('foobazbar'));
        $s->read(2);
        Psr7\hash($s, 'md5');
    }

    public function testCalculatesHashSeeksToOriginalPosition()
    {
        $s = Psr7\stream_for('foobazbar');
        $s->seek(4);
        $this->assertEquals(md5('foobazbar'), Psr7\hash($s, 'md5'));
        $this->assertEquals(4, $s->tell());
    }

    public function testOpensFilesSuccessfully()
    {
        $r = Psr7\try_fopen(__FILE__, 'r');
        $this->assertInternalType('resource', $r);
        fclose($r);
    }

    /**
     * @expectedException \RuntimeException
     * @expectedExceptionMessage Unable to open /path/to/does/not/exist using mode r
     */
    public function testThrowsExceptionNotWarning()
    {
        Psr7\try_fopen('/path/to/does/not/exist', 'r');
    }

    public function parseQueryProvider()
    {
        return array(
            // Does not need to parse when the string is empty
            array('', array()),
            // Can parse mult-values items
            array('q=a&q=b', array('q' => array('a', 'b'))),
            // Can parse multi-valued items that use numeric indices
            array('q[0]=a&q[1]=b', array('q[0]' => 'a', 'q[1]' => 'b')),
            // Can parse duplicates and does not include numeric indices
            array('q[]=a&q[]=b', array('q[]' => array('a', 'b'))),
            // Ensures that the value of "q" is an array even though one value
            array('q[]=a', array('q[]' => 'a')),
            // Does not modify "." to "_" like PHP's parse_str()
            array('q.a=a&q.b=b', array('q.a' => 'a', 'q.b' => 'b')),
            // Can decode %20 to " "
            array('q%20a=a%20b', array('q a' => 'a b')),
            // Can parse funky strings with no values by assigning each to null
            array('q&a', array('q' => null, 'a' => null)),
            // Does not strip trailing equal signs
            array('data=abc=', array('data' => 'abc=')),
            // Can store duplicates without affecting other values
            array('foo=a&foo=b&?µ=c', array('foo' => array('a', 'b'), '?µ' => 'c')),
            // Sets value to null when no "=" is present
            array('foo', array('foo' => null)),
            // Preserves "0" keys.
            array('0', array('0' => null)),
            // Sets the value to an empty string when "=" is present
            array('0=', array('0' => '')),
            // Preserves falsey keys
            array('var=0', array('var' => '0')),
            array('a[b][c]=1&a[b][c]=2', array('a[b][c]' => array('1', '2'))),
            array('a[b]=c&a[d]=e', array('a[b]' => 'c', 'a[d]' => 'e')),
            // Ensure it doesn't leave things behind with repeated values
            // Can parse mult-values items
            array('q=a&q=b&q=c', array('q' => array('a', 'b', 'c'))),
        );
    }

    /**
     * @dataProvider parseQueryProvider
     */
    public function testParsesQueries($input, $output)
    {
        $result = Psr7\parse_query($input);
        $this->assertSame($output, $result);
    }

    public function testDoesNotDecode()
    {
        $str = 'foo%20=bar';
        $data = Psr7\parse_query($str, false);
        $this->assertEquals(array('foo%20' => 'bar'), $data);
    }

    /**
     * @dataProvider parseQueryProvider
     */
    public function testParsesAndBuildsQueries($input, $output)
    {
        $result = Psr7\parse_query($input, false);
        $this->assertSame($input, Psr7\build_query($result, false));
    }

    public function testEncodesWithRfc1738()
    {
        $str = Psr7\build_query(array('foo bar' => 'baz+'), PHP_QUERY_RFC1738);
        $this->assertEquals('foo+bar=baz%2B', $str);
    }

    public function testEncodesWithRfc3986()
    {
        $str = Psr7\build_query(array('foo bar' => 'baz+'), PHP_QUERY_RFC3986);
        $this->assertEquals('foo%20bar=baz%2B', $str);
    }

    public function testDoesNotEncode()
    {
        $str = Psr7\build_query(array('foo bar' => 'baz+'), false);
        $this->assertEquals('foo bar=baz+', $str);
    }

    public function testCanControlDecodingType()
    {
        $result = Psr7\parse_query('var=foo+bar', PHP_QUERY_RFC3986);
        $this->assertEquals('foo+bar', $result['var']);
        $result = Psr7\parse_query('var=foo+bar', PHP_QUERY_RFC1738);
        $this->assertEquals('foo bar', $result['var']);
    }

    public function testParsesRequestMessages()
    {
        $req = "GET /abc HTTP/1.0\r\nHost: foo.com\r\nFoo: Bar\r\nBaz: Bam\r\nBaz: Qux\r\n\r\nTest";
        $request = Psr7\parse_request($req);
        $this->assertEquals('GET', $request->getMethod());
        $this->assertEquals('/abc', $request->getRequestTarget());
        $this->assertEquals('1.0', $request->getProtocolVersion());
        $this->assertEquals('foo.com', $request->getHeaderLine('Host'));
        $this->assertEquals('Bar', $request->getHeaderLine('Foo'));
        $this->assertEquals('Bam, Qux', $request->getHeaderLine('Baz'));
        $this->assertEquals('Test', (string) $request->getBody());
        $this->assertEquals('http://foo.com/abc', (string) $request->getUri());
    }

    public function testParsesRequestMessagesWithHttpsScheme()
    {
        $req = "PUT /abc?baz=bar HTTP/1.1\r\nHost: foo.com:443\r\n\r\n";
        $request = Psr7\parse_request($req);
        $this->assertEquals('PUT', $request->getMethod());
        $this->assertEquals('/abc?baz=bar', $request->getRequestTarget());
        $this->assertEquals('1.1', $request->getProtocolVersion());
        $this->assertEquals('foo.com:443', $request->getHeaderLine('Host'));
        $this->assertEquals('', (string) $request->getBody());
        $this->assertEquals('https://foo.com/abc?baz=bar', (string) $request->getUri());
    }

    public function testParsesRequestMessagesWithUriWhenHostIsNotFirst()
    {
        $req = "PUT / HTTP/1.1\r\nFoo: Bar\r\nHost: foo.com\r\n\r\n";
        $request = Psr7\parse_request($req);
        $this->assertEquals('PUT', $request->getMethod());
        $this->assertEquals('/', $request->getRequestTarget());
        $this->assertEquals('http://foo.com/', (string) $request->getUri());
    }

    public function testParsesRequestMessagesWithFullUri()
    {
        $req = "GET https://www.google.com:443/search?q=foobar HTTP/1.1\r\nHost: www.google.com\r\n\r\n";
        $request = Psr7\parse_request($req);
        $this->assertEquals('GET', $request->getMethod());
        $this->assertEquals('https://www.google.com:443/search?q=foobar', $request->getRequestTarget());
        $this->assertEquals('1.1', $request->getProtocolVersion());
        $this->assertEquals('www.google.com', $request->getHeaderLine('Host'));
        $this->assertEquals('', (string) $request->getBody());
        $this->assertEquals('https://www.google.com/search?q=foobar', (string) $request->getUri());
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testValidatesRequestMessages()
    {
        Psr7\parse_request("HTTP/1.1 200 OK\r\n\r\n");
    }

    public function testParsesResponseMessages()
    {
        $res = "HTTP/1.0 200 OK\r\nFoo: Bar\r\nBaz: Bam\r\nBaz: Qux\r\n\r\nTest";
        $response = Psr7\parse_response($res);
        $this->assertEquals(200, $response->getStatusCode());
        $this->assertEquals('OK', $response->getReasonPhrase());
        $this->assertEquals('1.0', $response->getProtocolVersion());
        $this->assertEquals('Bar', $response->getHeaderLine('Foo'));
        $this->assertEquals('Bam, Qux', $response->getHeaderLine('Baz'));
        $this->assertEquals('Test', (string) $response->getBody());
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testValidatesResponseMessages()
    {
        Psr7\parse_response("GET / HTTP/1.1\r\n\r\n");
    }

    public function testDetermineMimetype()
    {
        $this->assertNull(Psr7\mimetype_from_extension('not-a-real-extension'));
        $this->assertEquals(
            'application/json',
            Psr7\mimetype_from_extension('json')
        );
        $this->assertEquals(
            'image/jpeg',
            Psr7\mimetype_from_filename('/tmp/images/IMG034821.JPEG')
        );
    }

    public function testCreatesUriForValue()
    {
        $this->assertInstanceOf('GuzzleHttp\Psr7\Uri', Psr7\uri_for('/foo'));
        $this->assertInstanceOf(
            'GuzzleHttp\Psr7\Uri',
            Psr7\uri_for(new Psr7\Uri('/foo'))
        );
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testValidatesUri()
    {
        Psr7\uri_for(array());
    }

    public function testKeepsPositionOfResource()
    {
        $h = fopen(__FILE__, 'r');
        fseek($h, 10);
        $stream = Psr7\stream_for($h);
        $this->assertEquals(10, $stream->tell());
        $stream->close();
    }

    public function testCreatesWithFactory()
    {
        $stream = Psr7\stream_for('foo');
        $this->assertInstanceOf('GuzzleHttp\Psr7\Stream', $stream);
        $this->assertEquals('foo', $stream->getContents());
        $stream->close();
    }

    public function testFactoryCreatesFromEmptyString()
    {
        $s = Psr7\stream_for();
        $this->assertInstanceOf('GuzzleHttp\Psr7\Stream', $s);
    }

    public function testFactoryCreatesFromNull()
    {
        $s = Psr7\stream_for(null);
        $this->assertInstanceOf('GuzzleHttp\Psr7\Stream', $s);
    }

    public function testFactoryCreatesFromResource()
    {
        $r = fopen(__FILE__, 'r');
        $s = Psr7\stream_for($r);
        $this->assertInstanceOf('GuzzleHttp\Psr7\Stream', $s);
        $this->assertSame(file_get_contents(__FILE__), (string) $s);
    }

    public function testFactoryCreatesFromObjectWithToString()
    {
        $r = new HasToString();
        $s = Psr7\stream_for($r);
        $this->assertInstanceOf('GuzzleHttp\Psr7\Stream', $s);
        $this->assertEquals('foo', (string) $s);
    }

    public function testCreatePassesThrough()
    {
        $s = Psr7\stream_for('foo');
        $this->assertSame($s, Psr7\stream_for($s));
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testThrowsExceptionForUnknown()
    {
        Psr7\stream_for(new \stdClass());
    }

    public function testReturnsCustomMetadata()
    {
        $s = Psr7\stream_for('foo', array('metadata' => array('hwm' => 3)));
        $this->assertEquals(3, $s->getMetadata('hwm'));
        $this->assertArrayHasKey('hwm', $s->getMetadata());
    }

    public function testCanSetSize()
    {
        $s = Psr7\stream_for('', array('size' => 10));
        $this->assertEquals(10, $s->getSize());
    }

    public function testCanCreateIteratorBasedStream()
    {
        $a = new \ArrayIterator(array('foo', 'bar', '123'));
        $p = Psr7\stream_for($a);
        $this->assertInstanceOf('GuzzleHttp\Psr7\PumpStream', $p);
        $this->assertEquals('foo', $p->read(3));
        $this->assertFalse($p->eof());
        $this->assertEquals('b', $p->read(1));
        $this->assertEquals('a', $p->read(1));
        $this->assertEquals('r12', $p->read(3));
        $this->assertFalse($p->eof());
        $this->assertEquals('3', $p->getContents());
        $this->assertTrue($p->eof());
        $this->assertEquals(9, $p->tell());
    }

    public function testConvertsRequestsToStrings()
    {
        $request = new Psr7\Request('PUT', 'http://foo.com/hi?123', array(
            'Baz' => 'bar',
            'Qux' => ' ipsum'
        ), 'hello', '1.0');
        $this->assertEquals(
            "PUT /hi?123 HTTP/1.0\r\nHost: foo.com\r\nBaz: bar\r\nQux: ipsum\r\n\r\nhello",
            Psr7\str($request)
        );
    }

    public function testConvertsResponsesToStrings()
    {
        $response = new Psr7\Response(200, array(
            'Baz' => 'bar',
            'Qux' => ' ipsum'
        ), 'hello', '1.0', 'FOO');
        $this->assertEquals(
            "HTTP/1.0 200 FOO\r\nBaz: bar\r\nQux: ipsum\r\n\r\nhello",
            Psr7\str($response)
        );
    }

    public function parseParamsProvider()
    {
        $res1 = array(
            array(
                '<http:/.../front.jpeg>',
                'rel' => 'front',
                'type' => 'image/jpeg',
            ),
            array(
                '<http://.../back.jpeg>',
                'rel' => 'back',
                'type' => 'image/jpeg',
            ),
        );
        return array(
            array(
                '<http:/.../front.jpeg>; rel="front"; type="image/jpeg", <http://.../back.jpeg>; rel=back; type="image/jpeg"',
                $res1
            ),
            array(
                '<http:/.../front.jpeg>; rel="front"; type="image/jpeg",<http://.../back.jpeg>; rel=back; type="image/jpeg"',
                $res1
            ),
            array(
                'foo="baz"; bar=123, boo, test="123", foobar="foo;bar"',
                array(
                    array('foo' => 'baz', 'bar' => '123'),
                    array('boo'),
                    array('test' => '123'),
                    array('foobar' => 'foo;bar')
                )
            ),
            array(
                '<http://.../side.jpeg?test=1>; rel="side"; type="image/jpeg",<http://.../side.jpeg?test=2>; rel=side; type="image/jpeg"',
                array(
                    array('<http://.../side.jpeg?test=1>', 'rel' => 'side', 'type' => 'image/jpeg'),
                    array('<http://.../side.jpeg?test=2>', 'rel' => 'side', 'type' => 'image/jpeg')
                )
            ),
            array(
                '',
                array()
            )
        );
    }
    /**
     * @dataProvider parseParamsProvider
     */
    public function testParseParams($header, $result)
    {
        $this->assertEquals($result, Psr7\parse_header($header));
    }

    public function testParsesArrayHeaders()
    {
        $header = array('a, b', 'c', 'd, e');
        $this->assertEquals(array('a', 'b', 'c', 'd', 'e'), Psr7\normalize_header($header));
    }

    public function testRewindsBody()
    {
        $body = Psr7\stream_for('abc');
        $res = new Psr7\Response(200, array(), $body);
        Psr7\rewind_body($res);
        $this->assertEquals(0, $body->tell());
        $body->rewind(1);
        Psr7\rewind_body($res);
        $this->assertEquals(0, $body->tell());
    }

    /**
     * @expectedException \RuntimeException
     */
    public function testThrowsWhenBodyCannotBeRewound()
    {
        $body = Psr7\stream_for('abc');
        $body->read(1);
        $body = FnStream::decorate($body, array(
            'rewind' => function () { throw new \RuntimeException('a'); }
        ));
        $res = new Psr7\Response(200, array(), $body);
        Psr7\rewind_body($res);
    }

    public function testCanModifyRequestWithUri()
    {
        $r1 = new Psr7\Request('GET', 'http://foo.com');
        $r2 = Psr7\modify_request($r1, array(
            'uri' => new Psr7\Uri('http://www.foo.com')
        ));
        $this->assertEquals('http://www.foo.com', (string) $r2->getUri());
        $this->assertEquals('www.foo.com', (string) $r2->getHeaderLine('host'));
    }

    public function testCanModifyRequestWithCaseInsensitiveHeader()
    {
        $r1 = new Psr7\Request('GET', 'http://foo.com', array('User-Agent' => 'foo'));
        $r2 = Psr7\modify_request($r1, array('set_headers' => array('User-agent' => 'bar')));
        $this->assertEquals('bar', $r2->getHeaderLine('User-Agent'));
        $this->assertEquals('bar', $r2->getHeaderLine('User-agent'));
    }

    public function testReturnsAsIsWhenNoChanges()
    {
        $request = new Psr7\Request('GET', 'http://foo.com');
        $this->assertSame($request, Psr7\modify_request($request, array()));
    }

    public function testReturnsUriAsIsWhenNoChanges()
    {
        $r1 = new Psr7\Request('GET', 'http://foo.com');
        $r2 = Psr7\modify_request($r1, array('set_headers' => array('foo' => 'bar')));
        $this->assertNotSame($r1, $r2);
        $this->assertEquals('bar', $r2->getHeaderLine('foo'));
    }

    public function testRemovesHeadersFromMessage()
    {
        $r1 = new Psr7\Request('GET', 'http://foo.com', array('foo' => 'bar'));
        $r2 = Psr7\modify_request($r1, array('remove_headers' => array('foo')));
        $this->assertNotSame($r1, $r2);
        $this->assertFalse($r2->hasHeader('foo'));
    }

    public function testAddsQueryToUri()
    {
        $r1 = new Psr7\Request('GET', 'http://foo.com');
        $r2 = Psr7\modify_request($r1, array('query' => 'foo=bar'));
        $this->assertNotSame($r1, $r2);
        $this->assertEquals('foo=bar', $r2->getUri()->getQuery());
    }
}


text: Django-powered telegram bot


text:
@echo off

:checkJava
if "%JAVA_HOME%" == "" goto noJavaHome
if not exist "%JAVA_HOME%\bin\java.exe" goto noJavaHome
goto runClient

:noJavaHome
echo "You must set the JAVA_HOME variable before running the client"
goto end

:runClient
set CLASSPATH=lib\*;target\org.wso2.carbon.identity.samples.sts-4.2.0-SNAPSHOT.jar
"%JAVA_HOME%\bin\java" -classpath %CLASSPATH% org.wso2.carbon.identity.samples.sts.Client

:end

:END


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace Orleans.Transactions
{
    public interface ITransactionOverloadDetector
    {
        bool IsOverloaded();
    }

    /// <summary>
    /// Options for load shedding based on transaction rate
    /// </summary>
    public class TransactionRateLoadSheddingOptions
    {
        /// <summary>
        /// whether to turn on transaction load shedding. Default to false;
        /// </summary>
        public bool Enabled { get; set; }

        /// <summary>
        /// Default load shedding limit
        /// </summary>
        public const double DEFAULT_LIMIT = 700;
        /// <summary>
        /// Load shedding limit for transaction
        /// </summary>
        public double Limit { get; set; } = DEFAULT_LIMIT;
    }

    public class TransactionOverloadDetector : ITransactionOverloadDetector
    {
        private readonly TransactionAgentStatistics statistics;
        private readonly TransactionRateLoadSheddingOptions options;
        private readonly PeriodicAction monitor;
        private long transactionStartedAtLastCheck;
        private double transactionStartedPerSecond;
        private DateTime lastCheckTime;
        private static readonly TimeSpan MetricsCheck = TimeSpan.FromSeconds(15);
        public TransactionOverloadDetector(TransactionAgentStatistics statistics, IOptions<TransactionRateLoadSheddingOptions> options)
        {
            this.statistics = statistics;
            this.options = options.Value;
            this.monitor = new PeriodicAction(MetricsCheck, this.RecordStatistics);
            this.transactionStartedAtLastCheck = statistics.TransactionStartedCounter;
            this.lastCheckTime = DateTime.UtcNow;
        }

        private void RecordStatistics()
        {
            long startCounter = this.statistics.TransactionStartedCounter;
            DateTime now = DateTime.UtcNow;
            this.transactionStartedPerSecond = CalculateTps(this.transactionStartedAtLastCheck, this.lastCheckTime, startCounter, now);
            this.transactionStartedAtLastCheck = startCounter;
            this.lastCheckTime = now;
        }

        public bool IsOverloaded()
        {
            if (!this.options.Enabled)
                return false;

            DateTime now = DateTime.UtcNow;
            this.monitor.TryAction(now);
            long startCounter = this.statistics.TransactionStartedCounter;
            double txPerSecondCurrently = CalculateTps(this.transactionStartedAtLastCheck, this.lastCheckTime, startCounter, now);
            //decaying utilization for tx per second
            var aggregratedTxPerSecond = (this.transactionStartedPerSecond + (2.0 * txPerSecondCurrently)) / 3.0;

            return aggregratedTxPerSecond > this.options.Limit;
        }

        private static double CalculateTps(long startCounter, DateTime startTimeUtc, long currentCounter, DateTime curentTimeUtc)
        {
            TimeSpan deltaTime = curentTimeUtc - startTimeUtc;
            long deltaCounter = currentCounter - startCounter;
            return (deltaTime.TotalMilliseconds < 1000)
                ? deltaCounter
                : (deltaCounter * 1000.0) / deltaTime.TotalMilliseconds;
        }
    }
}


text:
/* @flow */
import React, { Children, cloneElement } from 'react';
import { GridRoot as Root } from './styled';
import { ALIGN_ITEMS, GUTTER_WIDTH } from './constants';

import { gridPropTypes } from './propTypes';
import type { GridDefaultProps, GridProps } from './types';

const getGridItems = ({ breakpoints, children, columns, gutterWidth }) =>
  Children.map(children, (child) =>
    cloneElement(child, { breakpoints, columns, gutterWidth })
  );

const Grid = (props: GridProps) => (
  <Root {...props}>{getGridItems(props)}</Root>
);

Grid.displayName = 'Grid';
const defaultProps: GridDefaultProps = {
  alignItems: ALIGN_ITEMS.stretch, // Same as Flex
  columns: 12,
  gutterWidth: GUTTER_WIDTH.md // Same as Flex
};
Grid.defaultProps = defaultProps;
Grid.propTypes = gridPropTypes;

export default Grid;


text:
<!DOCTYPE HTML>

<title>Constant Field Values (LWJGL 3.1.0 - xxHash)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2016-10-30">
<link rel="stylesheet" type="text/css" href="javadoc.css" title="Style">
<link rel="stylesheet" type="text/css" href="jquery/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Deprecated

Index

Prev

Next

Frames

No Frames

All Classes

SEARCH:
<input type="text" id="search" value=" " disabled="disabled">
<input type="reset" id="reset" value=" " disabled="disabled">

JavaScript is disabled on your browser.

Constant Field Values

Contents

org.lwjgl.*

org.lwjgl.*

org.lwjgl.util.xxhash.XXHash

Modifier and Type
Constant Field
Value

public static final int
XXH_ERROR
1

public static final int
XXH_OK
0

public static final int
XXH_VERSION_MAJOR
0

public static final int
XXH_VERSION_MINOR
6

public static final int
XXH_VERSION_NUMBER
602

public static final int
XXH_VERSION_RELEASE
2

Skip navigation links

Package

Class

Deprecated

Index

Prev

Next

Frames

No Frames

All Classes

JavaScript is disabled on your browser.

Copyright LWJGL. All Rights Reserved. License terms.


text:
package org.apache.hadoop.hdfs.server.namenode.ha;

import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_STATE_CONTEXT_ENABLED_KEY;
import static org.apache.hadoop.hdfs.server.namenode.NameNodeAdapter.getServiceState;
import static org.apache.hadoop.hdfs.server.namenode.ha.ObserverReadProxyProvider.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.doAnswer;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.ha.HAServiceProtocol.HAServiceState;
import org.apache.hadoop.ha.ServiceFailedException;
import org.apache.hadoop.hdfs.DFSTestUtil;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.protocol.Block;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
import org.apache.hadoop.hdfs.protocol.HdfsConstants.SafeModeAction;
import org.apache.hadoop.hdfs.protocol.LocatedBlock;
import org.apache.hadoop.hdfs.protocol.LocatedBlocks;
import org.apache.hadoop.hdfs.qjournal.MiniQJMHACluster;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockManager;
import org.apache.hadoop.hdfs.server.namenode.FSEditLog;
import org.apache.hadoop.hdfs.server.namenode.FSNamesystem;
import org.apache.hadoop.hdfs.server.namenode.NameNodeAdapter;
import org.apache.hadoop.hdfs.server.namenode.TestFsck;
import org.apache.hadoop.hdfs.tools.GetGroups;
import org.apache.hadoop.ipc.ObserverRetryOnActiveException;
import org.apache.hadoop.util.Time;
import org.apache.hadoop.util.concurrent.HadoopExecutors;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mockito;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Test main functionality of ObserverNode.
 */
public class TestObserverNode {
  public static final Logger LOG =
      LoggerFactory.getLogger(TestObserverNode.class.getName());

  private static Configuration conf;
  private static MiniQJMHACluster qjmhaCluster;
  private static MiniDFSCluster dfsCluster;
  private static DistributedFileSystem dfs;

  private final Path testPath= new Path("/TestObserverNode");

  @BeforeClass
  public static void startUpCluster() throws Exception {
    conf = new Configuration();
    conf.setBoolean(DFS_NAMENODE_STATE_CONTEXT_ENABLED_KEY, true);
    // Set observer probe retry period to 0. Required by the tests that restart
    // Observer and immediately try to read from it.
    conf.setTimeDuration(
        OBSERVER_PROBE_RETRY_PERIOD_KEY, 0, TimeUnit.MILLISECONDS);
    qjmhaCluster = HATestUtil.setUpObserverCluster(conf, 1, 1, true);
    dfsCluster = qjmhaCluster.getDfsCluster();
  }

  @Before
  public void setUp() throws Exception {
    setObserverRead(true);
  }

  @After
  public void cleanUp() throws IOException {
    dfs.delete(testPath, true);
    assertEquals("NN[0] should be active", HAServiceState.ACTIVE,
        getServiceState(dfsCluster.getNameNode(0)));
    assertEquals("NN[1] should be standby", HAServiceState.STANDBY,
        getServiceState(dfsCluster.getNameNode(1)));
    assertEquals("NN[2] should be observer", HAServiceState.OBSERVER,
        getServiceState(dfsCluster.getNameNode(2)));
  }

  @AfterClass
  public static void shutDownCluster() throws IOException {
    if (qjmhaCluster != null) {
      qjmhaCluster.shutdown();
    }
  }

  @Test
  public void testNoActiveToObserver() throws Exception {
    try {
      dfsCluster.transitionToObserver(0);
    } catch (ServiceFailedException e) {
      return;
    }
    fail("active cannot be transitioned to observer");
  }

  /**
   * Test that non-ClientProtocol proxies such as
   * {@link org.apache.hadoop.tools.GetUserMappingsProtocol} still work
   * when run in an environment with observers.
   */
  @Test
  public void testGetGroups() throws Exception {
    GetGroups getGroups = new GetGroups(conf);
    assertEquals(0, getGroups.run(new String[0]));
  }

  @Test
  public void testNoObserverToActive() throws Exception {
    try {
      dfsCluster.transitionToActive(2);
    } catch (ServiceFailedException e) {
      return;
    }
    fail("observer cannot be transitioned to active");
  }

  @Test
  public void testSimpleRead() throws Exception {
    Path testPath2 = new Path(testPath, "test2");

    dfs.mkdir(testPath, FsPermission.getDefault());
    assertSentTo(0);

    dfsCluster.rollEditLogAndTail(0);
    dfs.getFileStatus(testPath);
    assertSentTo(2);

    dfs.mkdir(testPath2, FsPermission.getDefault());
    assertSentTo(0);
  }

  @Test
  public void testFailover() throws Exception {
    Path testPath2 = new Path(testPath, "test2");
    setObserverRead(false);

    dfs.mkdir(testPath, FsPermission.getDefault());
    assertSentTo(0);
    dfs.getFileStatus(testPath);
    assertSentTo(0);

    dfsCluster.transitionToStandby(0);
    dfsCluster.transitionToActive(1);
    dfsCluster.waitActive(1);

    dfs.mkdir(testPath2, FsPermission.getDefault());
    assertSentTo(1);
    dfs.getFileStatus(testPath);
    assertSentTo(1);

    dfsCluster.transitionToStandby(1);
    dfsCluster.transitionToActive(0);
    dfsCluster.waitActive(0);
  }

  @Test
  public void testDoubleFailover() throws Exception {
    Path testPath2 = new Path(testPath, "test2");
    Path testPath3 = new Path(testPath, "test3");
    dfs.mkdir(testPath, FsPermission.getDefault());
    assertSentTo(0);

    dfsCluster.rollEditLogAndTail(0);
    dfs.getFileStatus(testPath);
    assertSentTo(2);
    dfs.mkdir(testPath2, FsPermission.getDefault());
    assertSentTo(0);

    dfsCluster.transitionToStandby(0);
    dfsCluster.transitionToActive(1);
    dfsCluster.waitActive(1);

    dfsCluster.rollEditLogAndTail(1);
    dfs.getFileStatus(testPath2);
    assertSentTo(2);
    dfs.mkdir(testPath3, FsPermission.getDefault());
    assertSentTo(1);

    dfsCluster.transitionToStandby(1);
    dfsCluster.transitionToActive(0);
    dfsCluster.waitActive(0);

    dfsCluster.rollEditLogAndTail(0);
    dfs.getFileStatus(testPath3);
    assertSentTo(2);
    dfs.delete(testPath3, false);
    assertSentTo(0);
  }

  @Test
  public void testObserverShutdown() throws Exception {
    dfs.mkdir(testPath, FsPermission.getDefault());
    dfsCluster.rollEditLogAndTail(0);
    dfs.getFileStatus(testPath);
    assertSentTo(2);

    // Shutdown the observer - requests should go to active
    dfsCluster.shutdownNameNode(2);
    dfs.getFileStatus(testPath);
    assertSentTo(0);

    // Start the observer again - requests should go to observer
    dfsCluster.restartNameNode(2);
    dfsCluster.transitionToObserver(2);
    // The first request goes to the active because it has not refreshed yet;
    // the second will properly go to the observer
    dfs.getFileStatus(testPath);
    dfs.getFileStatus(testPath);
    assertSentTo(2);
  }

  @Test
  public void testObserverFailOverAndShutdown() throws Exception {
    dfs.mkdir(testPath, FsPermission.getDefault());
    dfsCluster.rollEditLogAndTail(0);
    dfs.getFileStatus(testPath);
    assertSentTo(2);

    dfsCluster.transitionToStandby(0);
    dfsCluster.transitionToActive(1);
    dfsCluster.waitActive(1);

    // Shutdown the observer - requests should go to active
    dfsCluster.shutdownNameNode(2);
    dfs.getFileStatus(testPath);
    assertSentTo(1);

    // Start the observer again - requests should go to observer
    dfsCluster.restartNameNode(2);
    dfs.getFileStatus(testPath);
    assertSentTo(1);

    dfsCluster.transitionToObserver(2);
    dfs.getFileStatus(testPath);
    // The first request goes to the active because it has not refreshed yet;
    // the second will properly go to the observer
    dfs.getFileStatus(testPath);
    assertSentTo(2);

    dfsCluster.transitionToStandby(1);
    dfsCluster.transitionToActive(0);
    dfsCluster.waitActive(0);
  }

  @Test
  public void testBootstrap() throws Exception {
    for (URI u : dfsCluster.getNameDirs(2)) {
      File dir = new File(u.getPath());
      assertTrue(FileUtil.fullyDelete(dir));
    }
    int rc = BootstrapStandby.run(
        new String[]{"-nonInteractive"},
        dfsCluster.getConfiguration(2)
    );
    assertEquals(0, rc);
  }

  /**
   * Test the case where Observer should throw RetriableException, just like
   * active NN, for certain open() calls where block locations are not
   * available. See HDFS-13898 for details.
   */
  @Test
  public void testObserverNodeSafeModeWithBlockLocations() throws Exception {
    // Create a new file - the request should go to active.
    dfs.create(testPath, (short)1).close();
    assertSentTo(0);

    dfsCluster.rollEditLogAndTail(0);
    dfs.open(testPath).close();
    assertSentTo(2);

    // Set observer to safe mode.
    dfsCluster.getFileSystem(2).setSafeMode(SafeModeAction.SAFEMODE_ENTER);

    // Mock block manager for observer to generate some fake blocks which
    // will trigger the (retriable) safe mode exception.
    BlockManager bmSpy =
        NameNodeAdapter.spyOnBlockManager(dfsCluster.getNameNode(2));
    doAnswer((invocation) -> {
      ExtendedBlock b = new ExtendedBlock("fake-pool", new Block(12345L));
      LocatedBlock fakeBlock = new LocatedBlock(b, DatanodeInfo.EMPTY_ARRAY);
      List<LocatedBlock> fakeBlocks = new ArrayList<>();
      fakeBlocks.add(fakeBlock);
      return new LocatedBlocks(0, false, fakeBlocks, null, true, null, null);
    }).when(bmSpy).createLocatedBlocks(any(), anyLong(), anyBoolean(),
        anyLong(), anyLong(), anyBoolean(), anyBoolean(), any(), any());

    // Open the file again - it should throw retriable exception and then
    // failover to active.
    dfs.open(testPath).close();
    assertSentTo(0);

    Mockito.reset(bmSpy);

    // Remove safe mode on observer, request should still go to it.
    dfsCluster.getFileSystem(2).setSafeMode(SafeModeAction.SAFEMODE_LEAVE);
    dfs.open(testPath).close();
    assertSentTo(2);
  }

  @Test
  public void testObserverNodeBlockMissingRetry() throws Exception {
    setObserverRead(true);

    dfs.create(testPath, (short)1).close();
    assertSentTo(0);

    dfsCluster.rollEditLogAndTail(0);

    // Mock block manager for observer to generate some fake blocks which
    // will trigger the block missing exception.

    BlockManager bmSpy = NameNodeAdapter
        .spyOnBlockManager(dfsCluster.getNameNode(2));
    doAnswer((invocation) -> {
      List<LocatedBlock> fakeBlocks = new ArrayList<>();
      // Remove the datanode info for the only block so it will throw
      // BlockMissingException and retry.
      ExtendedBlock b = new ExtendedBlock("fake-pool", new Block(12345L));
      LocatedBlock fakeBlock = new LocatedBlock(b, DatanodeInfo.EMPTY_ARRAY);
      fakeBlocks.add(fakeBlock);
      return new LocatedBlocks(0, false, fakeBlocks, null, true, null, null);
    }).when(bmSpy).createLocatedBlocks(Mockito.any(), anyLong(),
        anyBoolean(), anyLong(), anyLong(), anyBoolean(), anyBoolean(),
        Mockito.any(), Mockito.any());

    dfs.open(testPath);
    assertSentTo(0);

    Mockito.reset(bmSpy);
  }

  @Test
  public void testFsckWithObserver() throws Exception {
    setObserverRead(true);

    dfs.create(testPath, (short)1).close();
    assertSentTo(0);

    final String result = TestFsck.runFsck(conf, 0, true, "/");
    LOG.info("result=" + result);
    assertTrue(result.contains("Status: HEALTHY"));
  }

  /**
   * Test that, if a write happens happens to go to Observer,
   * Observer would throw {@link ObserverRetryOnActiveException},
   * to inform client to retry on Active
   *
   * @throws Exception
   */
  @Test
  public void testObserverRetryActiveException() throws Exception {
    boolean thrownRetryException = false;
    try {
      // Force a write on Observer, which should throw
      // retry on active exception.
      dfsCluster.getNameNode(2)
          .getRpcServer()
          .mkdirs("/testActiveRetryException",
              FsPermission.createImmutable((short) 0755), true);
    } catch (ObserverRetryOnActiveException orae) {
      thrownRetryException = true;
    }
    assertTrue(thrownRetryException);
  }

  /**
   * Test that for open call, if access time update is required,
   * the open call should go to active, instead of observer.
   *
   * @throws Exception
   */
  @Test
  public void testAccessTimeUpdateRedirectToActive() throws Exception {
    // Create a new pat to not mess up other tests
    Path tmpTestPath = new Path("/TestObserverNodeAccessTime");
    dfs.create(tmpTestPath, (short)1).close();
    assertSentTo(0);
    dfs.open(tmpTestPath).close();
    assertSentTo(2);
    // Set access time to a time in the far past.
    // So that next read call is guaranteed to
    // have passed access time period.
    dfs.setTimes(tmpTestPath, 0, 0);
    // Verify that aTime update redirects on Active
    dfs.open(tmpTestPath).close();
    assertSentTo(0);
  }

  /**
   * Test that if client connects to Active it does not try to find Observer
   * on next calls during some period of time.
   */
  @Test
  public void testStickyActive() throws Exception {
    Path testFile = new Path(testPath, "testStickyActive");
    Configuration newConf = new Configuration(conf);
    // Observer probe retry period set to 5 sec
    newConf.setLong(OBSERVER_PROBE_RETRY_PERIOD_KEY, 5000);
    // Disable cache, so that a new client actually gets created with new conf.
    newConf.setBoolean("fs.hdfs.impl.disable.cache", true);
    DistributedFileSystem newFs = (DistributedFileSystem) FileSystem.get(newConf);
    newFs.create(testFile, (short)1).close();
    assertSentTo(0);
    dfsCluster.rollEditLogAndTail(0);
    // No Observers present, should still go to Active
    dfsCluster.transitionToStandby(2);
    assertEquals("NN[2] should be standby", HAServiceState.STANDBY,
        getServiceState(dfsCluster.getNameNode(2)));
    newFs.open(testFile).close();
    assertSentTo(0);
    // Restore Observer
    int newObserver = 1;
    dfsCluster.transitionToObserver(newObserver);
    assertEquals("NN[" + newObserver + "] should be observer",
        HAServiceState.OBSERVER,
        getServiceState(dfsCluster.getNameNode(newObserver)));
    long startTime = Time.monotonicNow();
    try {
      while(Time.monotonicNow() - startTime <= 5000) {
        newFs.open(testFile).close();
        // Client should still talk to Active
        assertSentTo(0);
        Thread.sleep(200);
      }
    } catch(AssertionError ae) {
      if(Time.monotonicNow() - startTime <= 5000) {
        throw ae;
      }
      assertSentTo(newObserver);
    } finally {
      dfsCluster.transitionToStandby(1);
      dfsCluster.transitionToObserver(2);
    }
  }

  @Test
  public void testFsckDelete() throws Exception {
    setObserverRead(true);
    DFSTestUtil.createFile(dfs, testPath, 512, (short) 1, 0);
    DFSTestUtil.waitForReplication(dfs, testPath, (short) 1, 5000);
    ExtendedBlock block = DFSTestUtil.getFirstBlock(dfs, testPath);
    int dnToCorrupt = DFSTestUtil.firstDnWithBlock(dfsCluster, block);
    FSNamesystem ns = dfsCluster.getNameNode(0).getNamesystem();
    // corrupt Replicas are detected on restarting datanode
    dfsCluster.corruptReplica(dnToCorrupt, block);
    dfsCluster.restartDataNode(dnToCorrupt);
    DFSTestUtil.waitCorruptReplicas(dfs, ns, testPath, block, 1);
    final String result = TestFsck.runFsck(conf, 1, true, "/", "-delete");
    // filesystem should be in corrupt state
    LOG.info("result=" + result);
    assertTrue(result.contains("The filesystem under path '/' is CORRUPT"));
  }

  /**
   * The test models the race of two mkdirs RPC calls on the same path to
   * Active NameNode. The first arrived call will journal a mkdirs transaction.
   * The subsequent call hitting the NameNode before the mkdirs transaction is
   * synced will see that the directory already exists, but will obtain
   * lastSeenStateId smaller than the txId of the mkdirs transaction
   * since the latter hasn't been synced yet.
   * This causes stale read from Observer for the second client.
   * See HDFS-15915.
   */
  @Test
  public void testMkdirsRaceWithObserverRead() throws Exception {
    dfs.mkdir(testPath, FsPermission.getDefault());
    assertSentTo(0);
    dfsCluster.rollEditLogAndTail(0);
    dfs.getFileStatus(testPath);
    assertSentTo(2);

    // Create a spy on FSEditLog, which delays MkdirOp transaction by 100 mec
    FSEditLog spyEditLog = NameNodeAdapter.spyDelayMkDirTransaction(
        dfsCluster.getNameNode(0), 100);

    final int numThreads = 4;
    ClientState[] clientStates = new ClientState[numThreads];
    final ExecutorService threadPool =
        HadoopExecutors.newFixedThreadPool(numThreads);
    final Future<?>[] futures = new Future<?>[numThreads];

    Configuration conf2 = new Configuration(conf);
    // Disable FS cache so that different DFS clients are used
    conf2.setBoolean("fs.hdfs.impl.disable.cache", true);

    for (int i = 0; i < numThreads; i++) {
      clientStates[i] = new ClientState();
      futures[i] = threadPool.submit(new MkDirRunner(conf2, clientStates[i]));
    }

    Thread.sleep(150); // wait until mkdir is logged
    long activStateId =
        dfsCluster.getNameNode(0).getFSImage().getLastAppliedOrWrittenTxId();
    dfsCluster.rollEditLogAndTail(0);
    boolean finished = true;
    // wait for all dispatcher threads to finish
    for (Future<?> future : futures) {
      try {
        future.get();
      } catch (ExecutionException e) {
        finished = false;
        LOG.warn("MkDirRunner thread failed", e.getCause());
      }
    }
    assertTrue("Not all threads finished", finished);
    threadPool.shutdown();

    assertEquals("Active and Observer stateIds don't match",
        dfsCluster.getNameNode(0).getFSImage().getLastAppliedOrWrittenTxId(),
        dfsCluster.getNameNode(2).getFSImage().getLastAppliedOrWrittenTxId());
    for (int i = 0; i < numThreads; i++) {
      assertTrue("Client #" + i
          + " lastSeenStateId=" + clientStates[i].lastSeenStateId
          + " activStateId=" + activStateId
          + "\n" + clientStates[i].fnfe,
          clientStates[i].lastSeenStateId >= activStateId &&
          clientStates[i].fnfe == null);
    }

    // Restore edit log
    Mockito.reset(spyEditLog);
  }

  static class ClientState {
    private long lastSeenStateId = -7;
    private FileNotFoundException fnfe;
  }

  static class MkDirRunner implements Runnable {
    private static final Path DIR_PATH =
        new Path("/TestObserverNode/testMkdirsRaceWithObserverRead");

    private DistributedFileSystem fs;
    private ClientState clientState;

    MkDirRunner(Configuration conf, ClientState cs) throws IOException {
      super();
      fs = (DistributedFileSystem) FileSystem.get(conf);
      clientState = cs;
    }

    @Override
    public void run() {
      try {
        fs.mkdirs(DIR_PATH);
        clientState.lastSeenStateId = HATestUtil.getLastSeenStateId(fs);
        assertSentTo(fs, 0);

        FileStatus stat = fs.getFileStatus(DIR_PATH);
        assertSentTo(fs, 2);
        assertTrue("Should be a directory", stat.isDirectory());
      } catch (FileNotFoundException ioe) {
        clientState.fnfe = ioe;
      } catch (Exception e) {
        fail("Unexpected exception: " + e);
      }
    }
  }

  private static void assertSentTo(DistributedFileSystem fs, int nnIdx)
      throws IOException {
    assertTrue("Request was not sent to the expected namenode " + nnIdx,
        HATestUtil.isSentToAnyOfNameNodes(fs, dfsCluster, nnIdx));
  }

  private void assertSentTo(int nnIdx) throws IOException {
    assertTrue("Request was not sent to the expected namenode " + nnIdx,
        HATestUtil.isSentToAnyOfNameNodes(dfs, dfsCluster, nnIdx));
  }

  private static void setObserverRead(boolean flag) throws Exception {
    dfs = HATestUtil.configureObserverReadFs(
        dfsCluster, conf, ObserverReadProxyProvider.class, flag);
  }
}


text:
import createNewlessClass from '../methods/_internal/createNewlessClass';
import use from '../methods/other/use';
import series from '../methods/other/series';

const dataStore = new WeakMap();

class AsyncAfWrapperProto {
  constructor(data) {
    dataStore.set(this, Promise.resolve(data));
  }
  then(resolve, reject) {
    return this.constructor(dataStore.get(this).then(resolve, reject));
  }
  catch(reject) {
    return this.then(null, reject);
  }
  finally(onFinally) {
    return dataStore.get(this).finally(onFinally);
  }
}

AsyncAfWrapperProto.use = use;

Object.defineProperties(AsyncAfWrapperProto.prototype, {
  ...series,
  [Symbol.toStringTag]: {value: 'AsyncAF'},
});

/**
 * empty AsyncAF class wrapper
 *
 * AsyncAfWrapper is one option for cherry-picking only the methods you'd like to use in your code; {@link AsyncAfWrapper#use use}, {@link AsyncAF#series series}, and {@link AsyncAF#io io} are the only methods initially available on AsyncAfWrapper; see example below
 *
 * **Note:** while AsyncAfWrapper is a class, it can create instances with or without the `new` keyword
 *
 * **Example**
 *
 * say you only want to use {@link AsyncAF#mapAF mapAF}, {@link AsyncAF#filterAF filterAF}, {@link AsyncAF#forEachAF forEachAF}, and {@link AsyncAF#logAF logAF} instead of pulling in the entire AsyncAF library
 *
 * first, install the separate packages (e.g., for npm):
 *
 * `$ npm install --save @async-af/{wrapper,map,filter,foreach,log}`
 *
 * or, if on Windows:
 *
 * `$ npm install --save @async-af/wrapper @async-af/map @async-af/filter @async-af/foreach @async-af/log`
 *
 * then import the packages
 * ```js
 * import AsyncAF from '@async-af/wrapper'; // aliasing 'AsyncAfWrapper' as 'AsyncAF'
 * import mapAF from '@async-af/map';
 * import filterAF from '@async-af/filter';
 * import forEachAF from '@async-af/foreach';
 * import logAF from '@async-af/log';
 * ```
 *
 * _if you'd like to save some vertical screen real estate and cut the imports down to one line, see_ {@tutorial TOO_MANY_IMPORTS}
 *
 * then call {@link AsyncAfWrapper#use use}, including all prototype methods you'd like to add to AsyncAfWrapper's prototype in the first argument, `prototypeMethods` and all static methods you'd like to add to AsyncAfWrapper in the second optional argument, `staticMethods`
 * ```js
 * AsyncAF.use({ // prototype methods go in the first argument
 *   mapAF,
 *   filterAF,
 *   forEachAF
 * }, { // static methods go in the second argument
 *   logAF
 * });
 * ```
 *
 * ready to go!
 * ```js
 * const promises = [1, 2, 3].map(n => Promise.resolve(n));
 *
 * AsyncAF(promises).mapAF(n => n * 2).filterAF(n => n !== 4).forEachAF(n => console.log(n));
 * // logs 2 then 6
 *
 * AsyncAF.logAF(promises);
 * // @filename.js:24:9:
 * //  [ 1, 2, 3 ]
 * // in 0.003 secs
 * ```
 *
 * **protip:** you can use the same technique to add your own custom prototype or static methods to AsyncAfWrapper or even to the main AsyncAF class; see {@link AsyncAfWrapper#use use} for an example
 * @param {any} data the data to be wrapped by the AsyncAF class; can be promises or non-promises
 * @returns {Object} returns an instance of AsyncAfWrapper wrapping the passed in data
 * @since 3.0.0
 * @see AsyncAF
 * @see {@link AsyncAfWrapper#use use}
 * @see {@tutorial TOO_MANY_IMPORTS}
 * @class AsyncAfWrapper
 */
const AsyncAfWrapper = createNewlessClass(
  class AsyncAfWrapper extends AsyncAfWrapperProto {},
);

export {AsyncAfWrapperProto};
export default AsyncAfWrapper;


text:
package algs.model.searchtree;

/**
 * The scoring function returns an int value given a board state.
 *
 * @author George Heineman
 * @version 1.0, 6/15/08
 * @since 1.0
 */
public interface IScore {

	/**
	 * Evaluate the given state and return an integer that is to be used during
	 * search algorithms.
	 * <p>
	 * In general, the lower the score, the closer one is to a desired goal state.
	 *
	 * @param state    The board state to be evaluated. It is unchanged.
	 * @return         integer value for board evaluation (in general, low scores are closer to goal state).
	 */
	int eval (INode state);

	/**
	 * Evaluate the given state and update its score using our scoring function.
	 *
	 * @param state    The board state whose score value is to be updated.
	 */
	void score (INode state);
}


text:
package auth

import (
	tr "github.com/desertbit/bulldozer/translate"

	"github.com/desertbit/bulldozer/template"
)

const (
	templatePackageName = "auth"
)

func init() {
	// Register the authentication template package.
	template.RegisterPackage(templatePackageName, new(templatePackage))
}

//########################//
//### Template Package ###//
//########################//

type templatePackage struct{}

func (p *templatePackage) MustIsAuth(a *template.Action, c *template.Context) {
	if !IsAuth(c) {
		a.Error(tr.S("bud.auth.pkg.mustAuthErrorMessage"))
	}
}

func (p *templatePackage) IsAuth(c *template.Context) bool {
	return IsAuth(c)
}

func (p *templatePackage) GetUser(c *template.Context) *User {
	return GetUser(c)
}

func (p *templatePackage) LoginName(c *template.Context) string {
	u := GetUser(c)
	if u == nil {
		return ""
	}

	return u.LoginName()
}

func (p *templatePackage) UserName(c *template.Context) string {
	u := GetUser(c)
	if u == nil {
		return ""
	}

	return u.Name()
}

func (p *templatePackage) Group(c *template.Context, groups ...string) bool {
	// Get the user.
	u := GetUser(c)
	if u == nil {
		return false
	}

	// Perform the actual action.
	return u.IsInGroup(groups...)
}


text:
module myApp {

    angular.module(appModuleId, [
        shellModuleId,
        homeModuleId,
        dataModuleId,
        commonModuleId,
        'ui.router',
        'ngCookies'
    ])
        .constant(configConstKey, {})
        .config(LoggerConfiguration)
        .config(RouteConfiguration)
        .run(Run);

    function Run(appConfig: IAppConfigService) {
        // because AppConfigService relies on a factory, we have to do this in the Run step
        appConfig.DataApiUrl = '/api'
    }
    Run.$inject = [appConfigServiceId];
}


text:
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;

using Amazon.Runtime;

namespace Amazon.SimpleEmail.Model
{
    /// <summary>
    /// Returns information about the  GetSendStatisticsResult response and response metadata.
    /// </summary>
    public class GetSendStatisticsResponse : AmazonWebServiceResponse
    {
        private GetSendStatisticsResult getSendStatisticsResult;

        /// <summary>
        /// Gets and sets the GetSendStatisticsResult property.
        /// Represents a list of SendDataPoint items returned from a successful GetSendStatistics request. This list contains aggregated data from the
        /// previous two weeks of sending activity.
        /// </summary>
        public GetSendStatisticsResult GetSendStatisticsResult
        {
            get
            {
                if(this.getSendStatisticsResult == null)
                {
                    this.getSendStatisticsResult = new GetSendStatisticsResult();
                }

                return this.getSendStatisticsResult;
            }
            set { this.getSendStatisticsResult = value; }
        }
    }
}


text:
package com.khs.sherpa.exception;

public class SherpaEndpointNotFoundException extends SherpaRuntimeException {

	private static final long serialVersionUID = -4432140915148653751L;

	public SherpaEndpointNotFoundException() {
		super();
	}

	public SherpaEndpointNotFoundException(String arg0, Throwable arg1) {
		super(arg0, arg1);
	}

	public SherpaEndpointNotFoundException(String arg0) {
		super(arg0);
	}

	public SherpaEndpointNotFoundException(Throwable arg0) {
		super(arg0);
	}

}


text:
class Admin::ConfigurationsController < Admin::BaseController

  before_filter :initialize_extension_links, :only => :index
  before_filter :add_shipping_links, :only => :index

  protected

  def add_shipping_links
    @extension_links << {:link => admin_shipping_methods_path, :link_text => t("shipping_methods"), :description => t("shipping_methods_description")}
    @extension_links << {:link => admin_shipping_categories_path, :link_text => t("shipping_categories"), :description => t("shipping_categories_description")}
  end

  def initialize_extension_links
    @extension_links = []
  end
end


text:
"""
Image finder. Usage is run this script with no arguments. :)
"""

import os
import sys
import re
from getopt import getopt
from PIL import Image

class ImageScanner:
    def __init__(self):
        self.maxsize = (1000, 1000)
        self.minsize = (0, 0)
        self.printsize = 1
        self.verbose = 0

    def __parsesize(self, geom):
        matched = re.match('(?P<W>\d+)x(?P<H>\d+)', geom)
        if not matched:
            raise ValueError, 'Geometory format is not "XxY"'
        return (int(matched.group('W')), int(matched.group('H')))

    def setmaxsize(self, geom):
        self.maxsize = self.__parsesize(geom)

    def setminsize(self, geom):
        self.minsize = self.__parsesize(geom)

    def setnoprint(self):
        self.printsize = 0

    def setverbose(self):
        self.verbose = 1

    def scan(self, fn):
        try:
            size = Image.open(fn).size
            if self.maxsize >= size and self.minsize <= size:
                if self.printsize or self.verbose:
                    return fn + ' %dx%d' % size
                return fn
        except: pass
        if self.verbose:
            return fn + ' nil'
        return None

    def __recursivescan(self, arg, path, dirlist):
        for d in dirlist:
            self.__tmpbuf.append(self.scan(os.path.join(path, d)))
    def recursivescan(self, args):
        self.__tmpbuf = []
        for arg in args: os.path.walk(arg, self.__recursivescan, None)
        return self.__tmpbuf

def __list(arg, path, dirlist):
    return

def __usage():
    print >>sys.stderr, 'usage: %s [options] imagefile ...' % sys.argv[0]
    print >>sys.stderr, '''options:
    -h     print this usage
    -M XxY filter maximum image size
    -m XxY filter minimum image size
    -n     do not print size
    -r     recursive
    -v     verbose'''

def __main():
    optdic = {}
    arglist = []
    optlist = []
    tmp = sys.argv[1:]
    while 1:
        opts, tmp = getopt(tmp, 'hm:M:nrv')
        if opts: optlist += opts
        if not tmp: break
        arglist.append(tmp[0])
        tmp = tmp[1:]

    # Examine options and filenames.
    if optlist:
        for key, val in optlist:
            if key == '-h':
                __usage()
                return
            if optdic.has_key(key):
                raise ValueError, '%s option duplicated' % key
            optdic[key] = val
    if not arglist:
        raise ValueError, 'requires filename'

    scanner = ImageScanner()
    if optdic.has_key('-M'): scanner.setmaxsize(optdic['-M'])
    if optdic.has_key('-m'): scanner.setminsize(optdic['-m'])
    if optdic.has_key('-n'): scanner.setnoprint()
    if optdic.has_key('-v'): scanner.setverbose()

    if optdic.has_key('-r'):
        for data in filter(lambda a:a, scanner.recursivescan(arglist)):
            print data
    else:
        for data in filter(lambda a:a, map(scanner.scan, arglist)): print data

if __name__ == '__main__':
    try:
        __main()
    except Exception, e:
        print >>sys.stderr, e
        __usage()
        sys.exit(1)


text:
<component name="libraryTable">
  <library name="beta-1.1.2">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.crashlytics.sdk.android/beta/1.1.2/classes.jar!/" />
      <root url="file://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.crashlytics.sdk.android/beta/1.1.2/res" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text:
package org.apache.doris.load;

import org.apache.doris.common.io.Text;
import org.apache.doris.common.io.Writable;
import org.apache.doris.thrift.TEtlState;
import com.google.common.collect.Maps;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;

public class EtlStatus implements Writable {
    public static final String DEFAULT_TRACKING_URL = "N/A";

    private TEtlState state;
    private String trackingUrl;
    private Map<String, String> stats;
    private Map<String, String> counters;
    // not persist
    private Map<String, Long> fileMap;

    public EtlStatus() {
        this.state = TEtlState.RUNNING;
        this.trackingUrl = DEFAULT_TRACKING_URL;
        this.stats = Maps.newHashMap();
        this.counters = Maps.newHashMap();
        this.fileMap = Maps.newHashMap();
    }

    public TEtlState getState() {
        return state;
    }

    public boolean setState(TEtlState state) {
        // running -> finished or cancelled
        if (this.state != TEtlState.RUNNING) {
            return false;
        }
        this.state = state;
        return true;
    }

    public String getTrackingUrl() {
        return trackingUrl;
    }

    public void setTrackingUrl(String trackingUrl) {
        this.trackingUrl = trackingUrl;
    }

    public Map<String, String> getStats() {
        return stats;
    }

    public void setStats(Map<String, String> stats) {
        this.stats = stats;
    }

    public Map<String, String> getCounters() {
        return counters;
    }

    public void replaceCounter(String key, String value) {
        counters.put(key, value);
    }

    public void setCounters(Map<String, String> counters) {
        this.counters = counters;
    }

    public Map<String, Long> getFileMap() {
        return fileMap;
    }

    public void setFileMap(Map<String, Long> fileMap) {
        this.fileMap = fileMap;
    }

    public void addAllFileMap(Map<String, Long> fileMap) {
        this.fileMap.putAll(fileMap);
    }

    public void reset() {
        this.stats.clear();
        this.counters.clear();
        this.fileMap.clear();
    }

    @Override
    public String toString() {
        return "EtlTaskStatus [state=" + state + ", trackingUrl=" + trackingUrl + ", stats=" + stats + ", counters="
                + counters + "]";
    }

    public void write(DataOutput out) throws IOException {
        Text.writeString(out, state.name());
        Text.writeString(out, trackingUrl);

        int statsCount = (stats == null) ? 0 : stats.size();
        out.writeInt(statsCount);
        for (Map.Entry<String, String> entry : stats.entrySet()) {
            Text.writeString(out, entry.getKey());
            Text.writeString(out, entry.getValue());
        }

        int countersCount = (counters == null) ? 0 : counters.size();
        out.writeInt(countersCount);
        for (Map.Entry<String, String> entry : counters.entrySet()) {
            Text.writeString(out, entry.getKey());
            Text.writeString(out, entry.getValue());
        }
    }

    public void readFields(DataInput in) throws IOException {
        state = TEtlState.valueOf(Text.readString(in));
        trackingUrl = Text.readString(in);

        int statsCount = in.readInt();
        for (int i = 0; i < statsCount; ++i) {
            String key = Text.readString(in);
            String value = Text.readString(in);
            stats.put(key, value);
        }

        int countersCount = in.readInt();
        for (int i = 0; i < countersCount; ++i) {
            String key = Text.readString(in);
            String value = Text.readString(in);
            counters.put(key, value);
        }
    }

    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }

        if (!(obj instanceof EtlStatus)) {
            return false;
        }

        EtlStatus etlTaskStatus = (EtlStatus) obj;

        // Check stats
        if (etlTaskStatus.stats == null) {
            return false;
        }
        if (stats.size() != etlTaskStatus.stats.size()) {
            return false;
        }
        for (Entry<String, String> entry : stats.entrySet()) {
            String key = entry.getKey();
            if (!etlTaskStatus.stats.containsKey(key)) {
                return false;
            }
            if (!entry.getValue().equals(etlTaskStatus.stats.get(key))) {
                return false;
            }
        }

        // Check counters
        if (etlTaskStatus.counters == null) {
            return false;
        }
        if (counters.size() != etlTaskStatus.counters.size()) {
            return false;
        }
        for (Entry<String, String> entry : counters.entrySet()) {
            String key = entry.getKey();
            if (!etlTaskStatus.counters.containsKey(key)) {
                return false;
            }
            if (!entry.getValue().equals(etlTaskStatus.counters.get(key))) {
                return false;
            }
        }

        return state.equals(etlTaskStatus.state) && trackingUrl.equals(etlTaskStatus.trackingUrl);
    }
}