text:
package io.reactivex.netty.protocol.http.internal;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.http.DefaultHttpContent;
import io.netty.handler.codec.http.DefaultHttpRequest;
import io.netty.handler.codec.http.DefaultLastHttpContent;
import io.netty.handler.codec.http.HttpMessage;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.LastHttpContent;
import io.reactivex.netty.channel.Connection;
import io.reactivex.netty.channel.ConnectionInputSubscriberEvent;
import io.reactivex.netty.protocol.http.TrailingHeaders;
import io.reactivex.netty.protocol.http.internal.AbstractHttpConnectionBridge.ConnectionInputSubscriber;
import io.reactivex.netty.protocol.http.internal.AbstractHttpConnectionBridge.TrailerProducer;
import io.reactivex.netty.protocol.http.internal.AbstractHttpConnectionBridgeTest.AbstractHttpConnectionBridgeMock.HttpObject;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExternalResource;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.mockito.Matchers;
import org.mockito.Mockito;
import rx.Producer;
import rx.Subscriber;
import rx.functions.Action0;
import rx.observers.TestSubscriber;
import rx.subscriptions.Subscriptions;

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

import static io.netty.handler.codec.http.HttpHeaderUtil.*;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;

public class AbstractHttpConnectionBridgeTest {

    @Rule
    public final HandlerRule handlerRule = new HandlerRule();

    @Test(timeout = 60000)
    public void testSetTransferEncoding() throws Exception {
        DefaultHttpRequest reqWithNoContentLength = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
        handlerRule.channel.writeAndFlush(reqWithNoContentLength);

        assertThat("Unexpected outbound message count.", handlerRule.channel.outboundMessages(), hasSize(1));

        assertThat("Transfer encoding not set to chunked.", isTransferEncodingChunked(reqWithNoContentLength),
                   is(true));

        DefaultHttpRequest reqWithContentLength = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
        setContentLength(reqWithContentLength, 100);

        handlerRule.channel.writeAndFlush(reqWithContentLength);

        /*One header from previous write*/
        assertThat("Unexpected outbound message count.", handlerRule.channel.outboundMessages(), hasSize(2));

        assertThat("Transfer encoding set to chunked when content length was set.",
                   isTransferEncodingChunked(reqWithContentLength), is(false));
    }

    @Test(timeout = 60000)
    public void testWritePrimitives() throws Exception {
        handlerRule.channel.writeAndFlush("Hello");

        assertThat("Unexpected outbound message count.", handlerRule.channel.outboundMessages(), hasSize(1));
        assertThat("Unexpected message written.", handlerRule.channel.readOutbound(), instanceOf(ByteBuf.class));

        handlerRule.channel.writeAndFlush("Hello".getBytes());

        assertThat("Unexpected outbound message count.", handlerRule.channel.outboundMessages(), hasSize(1));
        assertThat("Unexpected message written.", handlerRule.channel.readOutbound(), instanceOf(ByteBuf.class));
    }

    @Test(timeout = 60000)
    public void testConnInputSubscriberEvent() throws Exception {
        handlerRule.setupAndAssertConnectionInputSub();
    }

    @Test(timeout = 60000)
    public void testHttpContentSubscriberEventWithNoContentInputSub() throws Exception {
        TestSubscriber<String> subscriber = new TestSubscriber<>();
        handlerRule.channel.pipeline().fireUserEventTriggered(new HttpContentSubscriberEvent<>(subscriber));

        subscriber.assertTerminalEvent();

        assertThat("Subscriber did not get an error", subscriber.getOnErrorEvents(), hasSize(1));
        assertThat("Subscriber got an unexpected error", subscriber.getOnErrorEvents().get(0),
                   instanceOf(IllegalStateException.class));
    }

    @Test(timeout = 60000)
    public void testHttpTrailerSubscriberEventWithNoContentInputSub() throws Exception {
        TestSubscriber<TrailingHeaders> subscriber = new TestSubscriber<>();
        handlerRule.channel.pipeline().fireUserEventTriggered(new HttpTrailerSubscriberEvent(subscriber));

        subscriber.assertTerminalEvent();

        assertThat("Subscriber did not get an error", subscriber.getOnErrorEvents(), hasSize(1));
        assertThat("Subscriber got an unexpected error", subscriber.getOnErrorEvents().get(0),
                   instanceOf(IllegalStateException.class));
    }

    @Test(timeout = 60000)
    public void testHttpContentSub() throws Exception {
        handlerRule.setupAndAssertConnectionInputSub();

        ProducerAwareSubscriber<String> subscriber = new ProducerAwareSubscriber<>();
        handlerRule.channel.pipeline().fireUserEventTriggered(new HttpContentSubscriberEvent<>(subscriber));

        subscriber.assertNoErrors();

        @SuppressWarnings("unchecked")
        Subscriber<String> contentSub = (Subscriber<String>) handlerRule.connInSub.getState().getContentSub();

        assertThat("Unexpected HTTP Content subscriber found", contentSub, equalTo((Subscriber<String>)subscriber));
        assertThat("Unexpected content subscriber producer.", subscriber.getProducer(),
                   equalTo(handlerRule.connInputProducerMock));

        subscriber.unsubscribe();

        subscriber.assertUnsubscribed();

        assertThat("Unsubscribing from HTTP content, did not unsubscribe from connection input.",
                   handlerRule.connInSub.isUnsubscribed(), is(true));
    }

    @Test(timeout = 60000)
    public void testHttpTrailerSub() throws Exception {
        handlerRule.setupAndAssertConnectionInputSub();

        ProducerAwareSubscriber<TrailingHeaders> subscriber = new ProducerAwareSubscriber<>();
        handlerRule.channel.pipeline().fireUserEventTriggered(new HttpTrailerSubscriberEvent(subscriber));

        subscriber.assertNoErrors();

        @SuppressWarnings("unchecked")
        Subscriber<TrailingHeaders> trailerSub =
                (Subscriber<TrailingHeaders>) handlerRule.connInSub.getState().getTrailerSub();

        assertThat("Unexpected HTTP trailer subscriber found", trailerSub,
                   equalTo((Subscriber<TrailingHeaders>) subscriber));

        assertThat("Unexpected trailer subscriber producer.", subscriber.getProducer(),
                   instanceOf(TrailerProducer.class));

        final TrailerProducer trailerProducer = (TrailerProducer) subscriber.getProducer();

        assertThat("Unexpected trailer subscriber producer delegate.", trailerProducer.getDelegateProducer(),
                   equalTo(handlerRule.connInputProducerMock));
    }

    @Test(timeout = 60000)
    public void testContentArrivedBeforeSubscription() throws Exception {
        handlerRule.channel.config().setAutoRead(false);

        handlerRule.setupAndAssertConnectionInputSub();

        handlerRule.connInSub.onNext(new DefaultLastHttpContent());/*Simulating content read on channel*/

        TestSubscriber<String> contentSub = new TestSubscriber<>();
        handlerRule.channel.pipeline().fireUserEventTriggered(new HttpContentSubscriberEvent<>(contentSub));

        contentSub.assertTerminalEvent();

        assertThat("Content received on delayed subscription.", contentSub.getOnNextEvents(), is(empty()));
        assertThat("Error not received on delayed subscription.", contentSub.getOnErrorEvents(), hasSize(1));

        TestSubscriber<TrailingHeaders> trailerSub = new TestSubscriber<>();
        handlerRule.channel.pipeline().fireUserEventTriggered(new HttpTrailerSubscriberEvent(trailerSub));

        trailerSub.assertTerminalEvent();

        assertThat("Trailers received on delayed subscription.", trailerSub.getOnNextEvents(), is(empty()));
        assertThat("Error not received on delayed subscription.", trailerSub.getOnErrorEvents(), hasSize(1));
    }

    @Test(timeout = 60000)
    public void testLazyContentAndTrailerSubWithAutoReadOn() throws Exception {
        handlerRule.channel.config().setAutoRead(true);

        handlerRule.setupAndAssertConnectionInputSub();

        /*Request sent, no content/trailer sub registered, will cause error on sub.*/
        handlerRule.connInSub.onNext(new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"));

        TestSubscriber<String> contentSub = new TestSubscriber<>();
        /*Lazy subscription*/
        handlerRule.channel.pipeline().fireUserEventTriggered(new HttpContentSubscriberEvent<>(contentSub));

        contentSub.assertTerminalEvent();

        assertThat("Content received on lazy subscription.", contentSub.getOnNextEvents(), is(empty()));
        assertThat("Error not received on lazy subscription.", contentSub.getOnErrorEvents(), hasSize(1));

        TestSubscriber<TrailingHeaders> trailerSub = new TestSubscriber<>();
        /*Lazy subscription*/
        handlerRule.channel.pipeline().fireUserEventTriggered(new HttpTrailerSubscriberEvent(trailerSub));

        trailerSub.assertTerminalEvent();

        assertThat("Trailers received on lazy subscription.", trailerSub.getOnNextEvents(), is(empty()));
        assertThat("Error not received on lazy subscription.", trailerSub.getOnErrorEvents(), hasSize(1));
    }

    @Test(timeout = 60000)
    public void testLazyContentAndTrailerSubWithAutoReadOff() throws Exception {
        handlerRule.channel.config().setAutoRead(false);

        handlerRule.setupAndAssertConnectionInputSub();

        /*Request sent, after this it will expect the subscriber to be registered before content arrives..*/
        handlerRule.connInSub.onNext(new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"));

        /*Content sent but no subscriber.*/
        handlerRule.connInSub.onNext(new DefaultHttpContent(Unpooled.buffer().writeBytes("Hello".getBytes())));

        TestSubscriber<String> contentSub = new TestSubscriber<>();
        /*Content already sent, lazy sub now.*/
        handlerRule.channel.pipeline().fireUserEventTriggered(new HttpContentSubscriberEvent<>(contentSub));

        contentSub.assertTerminalEvent();

        assertThat("Content received on lazy subscription.", contentSub.getOnNextEvents(), is(empty()));
        assertThat("Error not received on lazy subscription.", contentSub.getOnErrorEvents(), hasSize(1));

        handlerRule.connInSub.onNext(new DefaultLastHttpContent());/*Simulate completion.*/

        TestSubscriber<TrailingHeaders> trailerSub = new TestSubscriber<>();
        /*Content already completed, lazy sub now.*/
        handlerRule.channel.pipeline().fireUserEventTriggered(new HttpTrailerSubscriberEvent(trailerSub));

        trailerSub.assertTerminalEvent();

        assertThat("Trailers received on lazy subscription.", trailerSub.getOnNextEvents(), is(empty()));
        assertThat("Error not received on lazy subscription.", trailerSub.getOnErrorEvents(), hasSize(1));
    }

    @Test(timeout = 60000)
    public void testHttpChunked() throws Exception {
        handlerRule.setupAndAssertConnectionInputSub();

        /*Eager content subscription*/
        TestSubscriber<ByteBuf> contentSub = new TestSubscriber<>();
        handlerRule.channel.pipeline().fireUserEventTriggered(new HttpContentSubscriberEvent<>(contentSub));

        /*Eager trailer subscription*/
        TestSubscriber<TrailingHeaders> trailerSub = new TestSubscriber<>();
        handlerRule.channel.pipeline().fireUserEventTriggered(new HttpTrailerSubscriberEvent(trailerSub));

        /*Headers sent*/
        handlerRule.connInSub.onNext(new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"));

        ByteBuf content1 = Unpooled.buffer().writeBytes("Hello".getBytes());
        ByteBuf content2 = Unpooled.buffer().writeBytes("Hello2".getBytes());
        ByteBuf contentLast = Unpooled.buffer().writeBytes("Hello3".getBytes());

        /*Content 1 sent.*/
        handlerRule.connInSub.onNext(new DefaultHttpContent(content1));
        /*Content 2 sent.*/
        handlerRule.connInSub.onNext(new DefaultHttpContent(content2));

        DefaultLastHttpContent trailers = new DefaultLastHttpContent(contentLast);
        String trailer1Name = "foo";
        String trailer1Value = "bar";
        trailers.trailingHeaders().add(trailer1Name, trailer1Value);

        /*trailers with content*/
        handlerRule.connInSub.onNext(trailers);

        contentSub.assertTerminalEvent();
        contentSub.assertNoErrors();

        assertThat("Unexpected content chunks.", contentSub.getOnNextEvents(), hasSize(3));
        assertThat("Unexpected content chunks.", contentSub.getOnNextEvents(), contains(content1, content2,
                                                                                contentLast));

        trailerSub.assertTerminalEvent();
        trailerSub.assertNoErrors();

        assertThat("Unexpected trailer.", trailerSub.getOnNextEvents(), hasSize(1));

        TrailingHeaders trailingHeaders = trailerSub.getOnNextEvents().get(0);
        assertThat("Unexpected trailing header name.", trailingHeaders.getAllHeaderValues(trailer1Name), hasSize(1));
        assertThat("Unexpected trailing header name.", trailingHeaders.getAllHeaderValues(trailer1Name).get(0),
                   equalTo(trailer1Value));
    }

    @Test(timeout = 60000)
    public void testClose() throws Exception {
        handlerRule.setupAndAssertConnectionInputSub();

        /*Eager content subscription*/
        TestSubscriber<ByteBuf> contentSub = new TestSubscriber<>();
        handlerRule.channel.pipeline().fireUserEventTriggered(new HttpContentSubscriberEvent<>(contentSub));

        /*Eager trailer subscription*/
        TestSubscriber<TrailingHeaders> trailerSub = new TestSubscriber<>();
        handlerRule.channel.pipeline().fireUserEventTriggered(new HttpTrailerSubscriberEvent(trailerSub));

        /*Headers sent*/
        handlerRule.connInSub.onNext(new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"));

        /*Close before response complete*/
        handlerRule.channel.close();

        handlerRule.headerSub.assertTerminalEvent();
        contentSub.assertTerminalEvent();
        trailerSub.assertTerminalEvent();

        assertThat("No error to header subscriber on close.", handlerRule.headerSub.getOnErrorEvents(), hasSize(1));
        assertThat("No error to content subscriber on close.", contentSub.getOnErrorEvents(), hasSize(1));
        assertThat("No error to trailer subscriber on close.", trailerSub.getOnErrorEvents(), hasSize(1));

        assertThat("Close before complete did not get invoked.", handlerRule.handler.closedBeforeReceive, is(true));
    }

    @Test(timeout = 60000)
    public void testHeaderUnsubscribeBeforeHeaderReceive() throws Exception {
        handlerRule.setupAndAssertConnectionInputSub();

        handlerRule.headerSub.unsubscribe();

        assertThat("Connection input not unsubscribed.", handlerRule.connInSub.isUnsubscribed(), is(true));
    }

    @Test(timeout = 60000)
    public void testHeaderUnsubscribeAfterHeaderReceive() throws Exception {
        handlerRule.setupAndAssertConnectionInputSub();
        /*Headers sent*/
        handlerRule.connInSub.onNext(new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"));

        handlerRule.headerSub.unsubscribe();

        assertThat("Connection input unsubscribed post headers.", handlerRule.connInSub.isUnsubscribed(), is(false));
    }

    @Test(timeout = 60000)
    public void testConnectionInputCompleteWithNoHeaders() throws Exception {
        handlerRule.setupAndAssertConnectionInputSub();

        /*Eager content subscription*/
        TestSubscriber<ByteBuf> contentSub = new TestSubscriber<>();
        handlerRule.channel.pipeline().fireUserEventTriggered(new HttpContentSubscriberEvent<>(contentSub));

        /*Eager trailer subscription*/
        TestSubscriber<TrailingHeaders> trailerSub = new TestSubscriber<>();
        handlerRule.channel.pipeline().fireUserEventTriggered(new HttpTrailerSubscriberEvent(trailerSub));

        handlerRule.connInSub.onCompleted();

        handlerRule.headerSub.assertTerminalEvent();
        handlerRule.headerSub.assertNoErrors();

        contentSub.assertTerminalEvent();
        contentSub.assertNoErrors();

        trailerSub.assertTerminalEvent();
        trailerSub.assertNoErrors();
    }

    @Test(timeout = 60000)
    public void testConnectionInputCompletePostHeaders() throws Exception {
        handlerRule.setupAndAssertConnectionInputSub();

        /*Eager content subscription*/
        TestSubscriber<ByteBuf> contentSub = new TestSubscriber<>();
        handlerRule.channel.pipeline().fireUserEventTriggered(new HttpContentSubscriberEvent<>(contentSub));

        /*Eager trailer subscription*/
        TestSubscriber<TrailingHeaders> trailerSub = new TestSubscriber<>();
        handlerRule.channel.pipeline().fireUserEventTriggered(new HttpTrailerSubscriberEvent(trailerSub));

        /*Headers sent*/
        handlerRule.connInSub.onNext(new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"));

        handlerRule.headerSub.assertNoErrors();
        assertThat("Header subscriber did not get the headers.", handlerRule.headerSub.getOnNextEvents(), hasSize(1));
        /*Look only for one HTTP message*/
        handlerRule.headerSub.unsubscribe();
        assertThat("Content subscriber unsubscribed post header unsubscribe.", contentSub.isUnsubscribed(), is(false));
        assertThat("Trailer subscriber unsubscribed post header unsubscribe.", trailerSub.isUnsubscribed(), is(false));

        handlerRule.connInSub.onCompleted();

        contentSub.assertTerminalEvent();
        assertThat("Content subscriber did not get an error.", contentSub.getOnErrorEvents(), hasSize(1));

        trailerSub.assertTerminalEvent();
        assertThat("Trailer subscriber did not get an error.", trailerSub.getOnErrorEvents(), hasSize(1));
    }

    @Test(timeout = 60000)
    public void testMultiSubscribers() throws Exception {
        handlerRule.setupAndAssertConnectionInputSub();

        /*Eager content subscription*/
        TestSubscriber<ByteBuf> contentSub = new TestSubscriber<>();
        handlerRule.channel.pipeline().fireUserEventTriggered(new HttpContentSubscriberEvent<>(contentSub));

        @SuppressWarnings("unchecked")
        Subscriber<ByteBuf> contentSubFound = (Subscriber<ByteBuf>) handlerRule.connInSub.getState().getContentSub();

        assertThat("Unexpected HTTP Content subscriber found", contentSubFound,
                   equalTo((Subscriber<ByteBuf>) contentSub));

        /*Eager trailer subscription*/
        TestSubscriber<TrailingHeaders> trailerSub = new TestSubscriber<>();
        handlerRule.channel.pipeline().fireUserEventTriggered(new HttpTrailerSubscriberEvent(trailerSub));

        @SuppressWarnings("unchecked")
        Subscriber<TrailingHeaders> trailerSubFound =
                (Subscriber<TrailingHeaders>) handlerRule.connInSub.getState().getTrailerSub();

        assertThat("Unexpected HTTP trailer subscriber found", trailerSubFound,
                   equalTo((Subscriber<TrailingHeaders>) trailerSub));

        contentSub.assertNoErrors();
        trailerSub.assertNoErrors();

        /*Second active subscription*/
        TestSubscriber<ByteBuf> contentSub2 = new TestSubscriber<>();
        handlerRule.channel.pipeline().fireUserEventTriggered(new HttpContentSubscriberEvent<>(contentSub2));

        /*Second active subscription*/
        TestSubscriber<TrailingHeaders> trailerSub2 = new TestSubscriber<>();
        handlerRule.channel.pipeline().fireUserEventTriggered(new HttpTrailerSubscriberEvent(trailerSub2));

        contentSub2.assertTerminalEvent();
        assertThat("Second content subscriber did not get an error.", contentSub2.getOnErrorEvents(), hasSize(1));

        trailerSub2.assertTerminalEvent();
        assertThat("Second trailer subscriber did not get an error.", trailerSub2.getOnErrorEvents(), hasSize(1));
    }

    public static class HandlerRule extends ExternalResource {

        private Connection<String, String> connMock;
        private EmbeddedChannel channel;
        private AbstractHttpConnectionBridgeMock handler;
        private EventCatcher eventCatcher;
        private ConnectionInputSubscriber connInSub;
        private Producer connInputProducerMock;
        private ProducerAwareSubscriber<HttpObject> headerSub;

        @Override
        public Statement apply(final Statement base, Description description) {
            return new Statement() {
                @Override
                public void evaluate() throws Throwable {
                    handler = new AbstractHttpConnectionBridgeMock(HttpRequest.class);
                    eventCatcher = new EventCatcher();
                    channel = new EmbeddedChannel(handler, eventCatcher);
                    @SuppressWarnings("unchecked")
                    Connection<String, String> connMock = Mockito.mock(Connection.class);
                    Mockito.when(connMock.unsafeNettyChannel()).thenReturn(channel);

                    HandlerRule.this.connMock = connMock;
                    base.evaluate();
                }
            };
        }

        protected void setupAndAssertConnectionInputSub() {
            headerSub = new ProducerAwareSubscriber<>();

            @SuppressWarnings({"rawtypes", "unchecked"})
            ConnectionInputSubscriberEvent evt = new ConnectionInputSubscriberEvent(headerSub, connMock);

            channel.pipeline().fireUserEventTriggered(evt);

            assertThat("Handler did not pass the event.", eventCatcher.events, hasSize(1));
            assertThat("Handler did not modify the event.", eventCatcher.events, not(contains((Object) evt)));

            Object eventCaught = eventCatcher.events.get(0);

            assertThat("Unexpected propagated event.", eventCaught, instanceOf(ConnectionInputSubscriberEvent.class));

            @SuppressWarnings({"rawtypes", "unchecked"})
            ConnectionInputSubscriberEvent modEvt = (ConnectionInputSubscriberEvent) eventCaught;

            assertThat("Unexpected propagated event subscriber.", modEvt.getSubscriber(),
                       instanceOf(ConnectionInputSubscriber.class));

            @SuppressWarnings("unchecked")
            ConnectionInputSubscriber connInSub = (ConnectionInputSubscriber) modEvt.getSubscriber();
            this.connInSub = connInSub;

            assertThat("Channel not set in the subscriber.", connInSub.getChannel(), is(notNullValue()));
            assertThat("Unexpected channel set in the subscriber.", connInSub.getChannel(), equalTo((Channel)channel));

            @SuppressWarnings("unchecked")
            Subscriber<HttpObject> headerSub = (Subscriber<HttpObject>) connInSub.getState().getHeaderSub();

            assertThat("Unexpected header subscriber.", headerSub, is((Subscriber<HttpObject>) this.headerSub));

            connInputProducerMock = Mockito.mock(Producer.class);
            connInSub.setProducer(connInputProducerMock);

            assertThat("Header subscriber producer not set.", this.headerSub.getProducer(),
                       equalTo(connInputProducerMock));

            Mockito.verify(connInputProducerMock).request(Matchers.anyLong());
        }

    }

    private static class ProducerAwareSubscriber<T> extends TestSubscriber<T> {

        private Producer producer;

        @Override
        public void setProducer(Producer producer) {
            this.producer = producer;
            super.setProducer(producer);
        }

        public Producer getProducer() {
            return producer;
        }
    }

    private static class EventCatcher extends ChannelDuplexHandler {

        private final List<Object> events = new ArrayList<>();

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            events.add(evt);
            super.userEventTriggered(ctx, evt);
        }
    }

    public static class AbstractHttpConnectionBridgeMock extends AbstractHttpConnectionBridge<String> {

        private final Class<?> headerMsgClass;
        private volatile boolean closedBeforeReceive;

        public AbstractHttpConnectionBridgeMock(Class<?> headerMsgClass) {
            this.headerMsgClass = headerMsgClass;
        }

        @Override
        protected boolean isInboundHeader(Object nextItem) {
            return headerMsgClass.isAssignableFrom(nextItem.getClass());
        }

        @Override
        protected boolean isOutboundHeader(Object nextItem) {
            return nextItem instanceof HttpRequest;
        }

        @Override
        protected Object newHttpObject(Object nextItem, Channel channel) {
            return new HttpObject();
        }

        @Override
        protected void onContentReceived() {
            // No Op
        }

        @Override
        protected void onContentReceiveComplete(long receiveStartTimeNanos) {
            // No Op
        }

        @Override
        protected void beforeOutboundHeaderWrite(HttpMessage httpMsg, ChannelPromise promise, long startTimeNanos) {
            // No Op
        }

        @Override
        protected void onOutboundLastContentWrite(LastHttpContent msg, ChannelPromise promise,
                                                  long headerWriteStartTimeNanos) {
            // No Op
        }

        @Override
        protected void onClosedBeforeReceiveComplete(ConnectionInputSubscriber connectionInputSubscriber) {
            closedBeforeReceive = true;
        }

        @Override
        protected void onNewContentSubscriber(final ConnectionInputSubscriber inputSubscriber,
                                              Subscriber<? super String> newSub) {
            newSub.add(Subscriptions.create(new Action0() {
                @Override
                public void call() {
                    inputSubscriber.unsubscribe();
                }
            }));
        }

        public static class HttpObject {
        }
    }
}


text:
using System.Collections.Generic;

namespace designPatterns.Web.Api.Infrastructure.Authentication.Roles
{
    public class UsersRoles
    {
        public string Name { get; set; }
        public IEnumerable<Feature> Features { get; set; }

    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Umbrella\Ya\RetornoBoleto\Cnab\Cnab240\Segmento;

use Stringy\Stringy;
use Umbrella\Ya\RetornoBoleto\Cnab\Cnab240\Detail;
use Umbrella\Ya\RetornoBoleto\Model\Banco;
use Umbrella\Ya\RetornoBoleto\Model\Cedente;
use Umbrella\Ya\RetornoBoleto\Model\Empresa;
use Umbrella\Ya\RetornoBoleto\Model\Inscricao;
use Umbrella\Ya\RetornoBoleto\Model\Sacado;

class SegmentoT extends AbstractSegmento
{

    public function buildDetail(Stringy $linha)
    {
        $detail = new Detail();

        $banco = new Banco();
        $banco->setCod($linha->substr(1, 3));

        $detail
            ->setLote($linha->substr(4, 4))
            ->setRegistro($linha->substr(8, 1))
            ->setNumRegistroLote($linha->substr(9, 5))
            ->setSegmento($linha->substr(14, 1))
            ->setTipoMovimento($linha->substr(15, 1))
            ->setCodMovimento($linha->substr(16, 2));

        $banco->setAgencia($linha->substr(18, 5))
            ->setDvAgencia($linha->substr(23, 1))
            ->setConta($linha->substr(24, 12))
            ->setDvConta($linha->substr(36, 1));

        $detail->setNossoNumero($linha->substr(38, 20))
            ->setCarteira($linha->substr(58, 1))
            ->setNumeroDocumento($linha->substr(59, 15))
            ->setDataVencimento($linha->substr(74, 8))
            ->setValorTitulo($this->convertToFloat($linha->substr(82, 15)));

        $banco->setCod($linha->substr(97, 3))
            ->setAgencia($linha->substr(100, 5))
            ->setDvAgencia($linha->substr(105, 1));

        $empresa = new Empresa();
        $empresa->addUso($linha->substr(106, 25));

        $detail->setCodMoeda($linha->substr(131, 2));

        $sacado = new Sacado();
        $sacado->setInscricao(new Inscricao($linha->substr(134, 15), $linha->substr(133, 1)))
            ->setNome($linha->substr(149, 40));

        $detail->setNumeroContrato($linha->substr(189, 10))
            ->setValorTarifa($this->convertToFloat($linha->substr(199, 15)))
            ->addOcorrencia($linha->substr(214, 10))
            ->addCnab($linha->substr(224, 17));

        $cedente = new Cedente();
        $cedente->setBanco($banco);
        $detail
            ->setCedente($cedente)
            ->setSacado($sacado);

        return $detail;
    }
}


text:
package se.lth.cs.docforia.query;

import se.lth.cs.docforia.Node;

/**
 * Typed node query variable
 */
public class NodeTVar<N extends Node> extends NodeVar {
    public NodeTVar(String type) {
        super(type);
    }

    public NodeTVar(String type, String variant) {
        super(type, variant);
    }

    public NodeTVar(Class<N> type) {
        super(type);
    }

    public NodeTVar(Class<N> type, String variant) {
        super(type, variant);
    }

    public <N extends Node> NodeTVar<N> var(Class<N> clazz) {
        return new NodeTVar<N>(clazz);
    }

    public <N extends Node> NodeTVar<N> var(Class<N> clazz, String variant) {
        return new NodeTVar<N>(clazz, variant);
    }
}


text:
<?php
namespace ScientiaMobile\WurflCloud;

class ConfigTest extends \PHPUnit_Framework_TestCase {

	public function testApiKey() {
		$config = new Config();
		$this->assertNull($config->api_key);
	}

	public function testAddCloudServer() {
		$config = new Config();
		$config->addCloudServer('foo', 'bar', 50);
		$this->assertArrayHasKey('foo', $config->wcloud_servers);
		$this->assertEquals(array('bar', 50), $config->wcloud_servers['foo']);
	}

	public function testClearServers() {
		$config = new Config();
		$this->assertNotEmpty($config->wcloud_servers);
		$config->clearServers();
		$this->assertEmpty($config->wcloud_servers);
	}

	public function testGetCloudHost() {
		$config = new Config();
		$config->clearServers();
		$config->addCloudServer('foo', 'bar', 50);
		$this->assertEquals('bar', $config->getCloudHost());
	}

	public function testGetWeightedServer() {
		$config = new Config();
		$config->clearServers();

		$likely_real = 1000;
		$unlikely_real = 8;
		$runs = 50000;
		$allowed_deviation = 0.01; // 1% ratio deviation

		$config->addCloudServer('foo', 'likely', $likely_real);
		$config->addCloudServer('nota', 'unlikely', $unlikely_real);

		$likely = 0;
		$unlikely = 0;

		// Test the weighting algorithm
		for ($i = 0; $i < $runs; $i++) {
			$server = $config->getWeightedServer();
			if ($server[0] === 'likely') {
				$likely++;
			} else {
				$unlikely++;
			}
		}

		$ratio_real = $unlikely_real / $likely_real;
		$ratio = $unlikely / $likely;
		$deviation = abs($ratio_real - $ratio);

		$deviation_nice = round($deviation * 100, 2);
		$allowed_deviation_nice = round($allowed_deviation * 100, 2);

		$message = "Weighted server algorithm choose $unlikely:$likely which is $deviation_nice% outside of ideal (must be within $allowed_deviation_nice%)";
		$this->assertLessThan($allowed_deviation, $deviation, $message);
	}

}


text:
var game;
// the spinning wheel
var wheel;
// can the wheel spin?
var canSpin;
// slices (prizes) placed in the wheel
var slices = 8;
// prize names, starting from 12 o'clock going clockwise
var slicePrizes = ["A KEY!!!", "50 STARS", "500 STARS", "BAD LUCK!!!", "200 STARS", "100 STARS", "150 STARS", "BAD LUCK!!!"];
// the prize you are about to win
var prize;
// text field where to show the prize
var prizeText;

window.onload = function() {
	// creation of a 458x488 game
	game = new Phaser.Game(458, 488, Phaser.AUTO, "");
	// adding "PlayGame" state
	game.state.add("PlayGame",playGame);
	// launching "PlayGame" state
	game.state.start("PlayGame");
}

// PLAYGAME STATE
var playGame = function(game) {};
playGame.prototype = {
	// function to be executed once the state preloads
	preload: function() {
		// preloading graphic assets
		game.load.image("wheel", "assets/img/wheel.png");
		game.load.image("pin", "assets/img/pin.png");
	},
	// funtion to be executed when the state is created
	create: function() {
		// giving some color to background
		game.stage.backgroundColor = "#880044";
		// adding the wheel in the middle of the canvas
		wheel = game.add.sprite(game.width / 2, game.width / 2, "wheel");
		// setting wheel registration point in its center
		wheel.anchor.set(0.5);
		// adding the pin in the middle of the canvas
		var pin = game.add.sprite(game.width / 2, game.width / 2, "pin");
		// setting pin registration point in its center
		pin.anchor.set(0.5);
		// adding the text field
		prizeText = game.add.text(game.world.centerX, 480, "");
		// setting text field registration point in its center
		prizeText.anchor.set(0.5);
		// aligning the text to center
		prizeText.align = "center";
		// the game has just started = we can spin the wheel
		canSpin = true;
		// waiting for your input, then calling "spin" function
		game.input.onDown.add(this.spin, this);
	},
	// function to spin the wheel
	spin() {
		// can we spin the wheel?
		if (canSpin) {
			// resetting text field
			prizeText.text = "";
			// the wheel will spin round from 2 to 4 times. This is just coreography
			var rounds = game.rnd.between(2, 4);
			// then will rotate by a random number from 0 to 360 degrees. This is the actual spin
			var degrees = game.rnd.between(0, 359);
			// before the wheel ends spinning, we already know the prize according to "degrees" rotation and the number of slices
			prize = slices - 1 - Math.floor(degrees / (360 / slices));
			// now the wheel cannot spin because it's already spinning
			canSpin = false;
			// animation tweeen for the spin: duration 3s, will rotate by (360 * rounds + degrees) degrees
			// the quadratic easing will simulate friction
			var spinTween = game.add.tween(wheel).to({
				angle: 360 * rounds + degrees
			}, 3000, Phaser.Easing.Quadratic.Out, true);
			// once the tween is completed, call winPrize function
			spinTween.onComplete.add(this.winPrize, this);
		}
	},
	// function to assign the prize
	winPrize(){
		// now we can spin the wheel again
		canSpin = true;
		// writing the prize you just won
		prizeText.text = slicePrizes[prize];
	}
}


text:
import collections

import netaddr
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import importutils

from neutron.agent.common import config
from neutron.agent.linux import interface
from neutron.agent.linux import ip_lib
from neutron.common import utils
from neutron.tests.functional.agent.linux import base
from neutron.tests.functional import base as functional_base

LOG = logging.getLogger(__name__)
Device = collections.namedtuple('Device',
                                'name ip_cidrs mac_address namespace')

WRONG_IP = '0.0.0.0'
TEST_IP = '240.0.0.1'

class IpLibTestFramework(functional_base.BaseSudoTestCase):
    def setUp(self):
        super(IpLibTestFramework, self).setUp()
        self._configure()

    def _configure(self):
        config.setup_logging()
        config.register_interface_driver_opts_helper(cfg.CONF)
        cfg.CONF.set_override(
            'interface_driver',
            'neutron.agent.linux.interface.OVSInterfaceDriver')
        cfg.CONF.register_opts(interface.OPTS)
        self.driver = importutils.import_object(cfg.CONF.interface_driver,
                                                cfg.CONF)

    def generate_device_details(self, name=None, ip_cidrs=None,
                                mac_address=None, namespace=None):
        return Device(name or base.get_rand_name(),
                      ip_cidrs or ["%s/24" % TEST_IP],
                      mac_address or
                      utils.get_random_mac('fa:16:3e:00:00:00'.split(':')),
                      namespace or base.get_rand_name())

    def _safe_delete_device(self, device):
        try:
            device.link.delete()
        except RuntimeError:
            LOG.debug('Could not delete %s, was it already deleted?', device)

    def manage_device(self, attr):
        """Create a tuntap with the specified attributes.

        The device is cleaned up at the end of the test.

        :param attr: A Device namedtuple
        :return: A tuntap ip_lib.IPDevice
        """
        ip = ip_lib.IPWrapper(namespace=attr.namespace)
        if attr.namespace:
            ip.netns.add(attr.namespace)
            self.addCleanup(ip.netns.delete, attr.namespace)
        tap_device = ip.add_tuntap(attr.name)
        self.addCleanup(self._safe_delete_device, tap_device)
        tap_device.link.set_address(attr.mac_address)
        self.driver.init_l3(attr.name, attr.ip_cidrs,
                            namespace=attr.namespace)
        tap_device.link.set_up()
        return tap_device

class IpLibTestCase(IpLibTestFramework):
    def test_device_exists(self):
        attr = self.generate_device_details()

        self.assertFalse(
            ip_lib.device_exists(attr.name, namespace=attr.namespace))

        device = self.manage_device(attr)

        self.assertTrue(
            ip_lib.device_exists(device.name, namespace=attr.namespace))

        device.link.delete()

        self.assertFalse(
            ip_lib.device_exists(attr.name, namespace=attr.namespace))

    def test_vxlan_exists(self):
        attr = self.generate_device_details()
        ip = ip_lib.IPWrapper(namespace=attr.namespace)
        ip.netns.add(attr.namespace)
        self.addCleanup(ip.netns.delete, attr.namespace)
        self.assertFalse(ip_lib.vxlan_in_use(9999, namespace=attr.namespace))
        device = ip.add_vxlan(attr.name, 9999)
        self.addCleanup(self._safe_delete_device, device)
        self.assertTrue(ip_lib.vxlan_in_use(9999, namespace=attr.namespace))
        device.link.delete()
        self.assertFalse(ip_lib.vxlan_in_use(9999, namespace=attr.namespace))

    def test_ipwrapper_get_device_by_ip(self):
        attr = self.generate_device_details()
        self.manage_device(attr)
        ip_wrapper = ip_lib.IPWrapper(namespace=attr.namespace)
        self.assertEqual(attr.name, ip_wrapper.get_device_by_ip(TEST_IP).name)
        self.assertIsNone(ip_wrapper.get_device_by_ip(WRONG_IP))

    def test_device_exists_with_ips_and_mac(self):
        attr = self.generate_device_details()
        device = self.manage_device(attr)
        self.assertTrue(
            ip_lib.device_exists_with_ips_and_mac(*attr))

        wrong_ip_cidr = '10.0.0.1/8'
        wrong_mac_address = 'aa:aa:aa:aa:aa:aa'

        attr = self.generate_device_details(name='wrong_name')
        self.assertFalse(
            ip_lib.device_exists_with_ips_and_mac(*attr))

        attr = self.generate_device_details(ip_cidrs=[wrong_ip_cidr])
        self.assertFalse(ip_lib.device_exists_with_ips_and_mac(*attr))

        attr = self.generate_device_details(mac_address=wrong_mac_address)
        self.assertFalse(ip_lib.device_exists_with_ips_and_mac(*attr))

        attr = self.generate_device_details(namespace='wrong_namespace')
        self.assertFalse(ip_lib.device_exists_with_ips_and_mac(*attr))

        device.link.delete()

    def test_get_routing_table(self):
        attr = self.generate_device_details()
        device = self.manage_device(attr)
        device_ip = attr.ip_cidrs[0].split('/')[0]
        destination = '8.8.8.0/24'
        device.route.add_route(destination, device_ip)

        expected_routes = [{'nexthop': device_ip,
                            'device': attr.name,
                            'destination': destination,
                            'scope': None},
                           {'nexthop': None,
                            'device': attr.name,
                            'destination': str(
                                netaddr.IPNetwork(attr.ip_cidrs[0]).cidr),
                            'scope': 'link'}]

        routes = ip_lib.get_routing_table(4, namespace=attr.namespace)
        self.assertEqual(expected_routes, routes)


text:
<?php

use yii\helpers\Html;
use yii\widgets\ListView;

/* @var $this yii\web\View */
/* @var $searchModel common\models\QuestionSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = Yii::t('app', 'Questions');
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

        <?= Html::a(Yii::t('app', 'Create Question'), ['create'], ['class' => 'btn btn-success']) ?>

    <?= ListView::widget([
        'dataProvider' => $dataProvider,
        'itemOptions' => ['class' => 'item'],
        'itemView' => function ($model, $key, $index, $widget) {
            return Html::a(Html::encode($model->id), ['view', 'id' => $model->id]);
        },
    ]) ?>


text:
package ru.stq.pft.addressbook.tests;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.stq.pft.addressbook.model.ContactData;
import ru.stq.pft.addressbook.model.Contacts;
import ru.stq.pft.addressbook.model.GroupData;
import ru.stq.pft.addressbook.model.Groups;

import java.util.List;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

/**
 * Created by A.Kasimova on 28.10.2016.
 */
public class ContactToGroupTests extends TestBase{

  private SessionFactory sessionFactory;

  @BeforeClass
  public void setUpDb() throws Exception {
    // A SessionFactory is set up once for an application!
    final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
            .configure() // configures settings from hibernate.cfg.xml
            .build();
    try {
      sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
    }
    catch (Exception e) {
      e.printStackTrace();
      // The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory
      // so destroy it manually.
      StandardServiceRegistryBuilder.destroy( registry );
    }
  }

  @BeforeMethod
  public void ensurePreconditionsContacts() {
    if (app.db().contacts().size() == 0) {
      app.goTo().gotoContactsPage();
      app.contact().createContact(new ContactData().withContactName("Asya").
              withContactSecondName("Kasimova").withContactAddress("test1").withContactHomePhone("+7 945 111 11 11").withContactEmail("asya.kasimova@a.com"), true);
    }
  }
  @BeforeMethod
  public void ensurePreconditionsGroups() {
    if (app.db().groups().size() == 0) {
      app.goTo().groupPage();
      app.group().create(new GroupData().withName("test1"));
    }
  }

  @Test
  public void testContactToGroup() {
    // подготовка данных для тестов
    Contacts contacts = app.db().contacts();
    ContactData contact = contacts.iterator().next();
    int contactId = contact.getId();
    Groups contactGroupsBefore = contact.getGroups();
    GroupData group = getGroupList().iterator().next();

    // выполнение теста (включение в группу), подготовка данных для проверки постусловий

    app.contact().selectContactById(contact.getId());
    app.contact().addToGroup(group);
    contact = getContactWithId(contactId);
    Groups contactGroupsAfter = contact.getGroups();
    contactGroupsBefore.add(group);

    // проверки

    if (contactGroupsBefore.size() == 0) {
      assertThat(contactGroupsAfter.size(), equalTo(contactGroupsBefore.size() + 1));
    } else {
      if (contactGroupsBefore.stream().filter((g) -> g.equals(group)).findFirst() == null) {
        assertThat(contactGroupsAfter.size(), equalTo(contactGroupsBefore.size() + 1));
      } else {
        assertThat(contactGroupsAfter.size(), equalTo(contactGroupsBefore.size()));
      }
    }

    assertThat(contactGroupsAfter, equalTo(contactGroupsBefore));
  }

  private List<GroupData> getGroupList() {
    Session session = sessionFactory.openSession();
    session.beginTransaction();
    List<GroupData> groups = session.createQuery( "from GroupData" ).list();
    session.getTransaction().commit();
    session.close();
    return groups;
  }
  private List<ContactData> getContacts() {
    Session session = sessionFactory.openSession();
    session.beginTransaction();
    List<ContactData> contacts = session.createQuery( "from ContactData where deprecated = '0000-00-00'" ).list();
    session.getTransaction().commit();
    session.close();
    return contacts;
  }
  private ContactData getContactWithId(int id) {
    Session session = sessionFactory.openSession();
    session.beginTransaction();
    ContactData contact = (ContactData) session.createQuery( "from ContactData where id=" + id).uniqueResult();
    session.getTransaction().commit();
    session.close();
    return contact;
  }
}


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

<!--L
   Copyright SAIC

   Distributed under the OSI-approved BSD 3-Clause License.
   See http://ncip.github.com/i-spy/LICENSE.txt for details.
L-->

<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config>

    <!-- ========== Data Source Configuration ============================== -->
    <data-sources />
    <!-- ========== Form Bean Definitions ================================== -->
    <form-beans>
    	<form-bean name="viewResultsForm" type="gov.nih.nci.ispy.web.struts.form.ViewResultsForm"/>
   		<form-bean name="classComparisonForm" type="gov.nih.nci.ispy.web.struts.form.ClassComparisonForm"/>
		<form-bean name="principalComponentForm" type="gov.nih.nci.ispy.web.struts.form.PrincipalComponentForm"/>
		<form-bean name="correlationScatterForm" type="gov.nih.nci.ispy.web.struts.form.CorrelationScatterForm"/>
		<form-bean name="categoricalCorrelationForm" type="gov.nih.nci.ispy.web.struts.form.CategoricalCorrelationForm"/>
		<form-bean name="clinicalQueryForm" type="gov.nih.nci.ispy.web.struts.form.ClinicalQueryForm"/>
		<form-bean name="fishQueryForm" type="gov.nih.nci.ispy.web.struts.form.FISHQueryForm"/>
		<form-bean name="p53QueryForm" type="gov.nih.nci.ispy.web.struts.form.P53QueryForm"/>
		<form-bean name="ihcLevelQueryForm" type="gov.nih.nci.ispy.web.struts.form.IHCLevelOfExpressionQueryForm"/>
		<form-bean name="ihcLossQueryForm" type="gov.nih.nci.ispy.web.struts.form.IHCLossOfExpressionQueryForm"/>
		<form-bean name="userPreferencesBean" type="gov.nih.nci.ispy.web.struts.bean.UserPreferencesBean"/>
		<form-bean name="hierarchicalClusteringForm" type="gov.nih.nci.ispy.web.struts.form.HierarchicalClusteringForm"/>
		<form-bean name="loginForm" type="gov.nih.nci.ispy.web.struts.form.LoginForm"/>
   		<form-bean name="logoutForm" type="gov.nih.nci.ispy.web.struts.form.LogoutForm"/>
   		<form-bean name="gpIntegrationForm" type="gov.nih.nci.ispy.web.struts.form.GpIntegrationForm"/>
   		<form-bean name="gpProcessForm" type="gov.nih.nci.ispy.web.struts.form.GpProcessForm"/>

  </form-beans>
  <!-- ========== Global Exception Definitions ============================ -->
  <global-exceptions />
  <!-- ========== Global Forward Definitions ============================== -->
  <global-forwards>

  </global-forwards>

    <!-- ========== Action Mapping Definitions ============================ -->

  <action-mappings>

   <action path="/login"
           type="gov.nih.nci.ispy.web.struts.action.LoginAction"
           name="loginForm"
           scope="request"
           input="/index2.jsp">
    <forward name="success" path="/legal.jsp"/>
    <forward name="failure" path="/index2.jsp"/>
    </action>

    <action path="/logout"
           type="gov.nih.nci.ispy.web.struts.action.LogoutAction"
           scope="request"
           input="ispy.analysisHome">
    <forward name="logout" path="/index.jsp"/>
    <forward name="dontLogout" path="ispy.analysisHome"/>
    </action>

    <action path="/analysisHome"
		forward="ispy.analysisHome"/>

	<action path="/advancedHome"
		forward="ispy.advancedHome"/>

	<action path="/clinical"
		forward="ispy.clinical" />

	<action path="/clinicalQueryInit"
		type="gov.nih.nci.ispy.web.struts.action.ClinicalQueryAction"
		name="clinicalQueryForm"
		scope="request"
		validate="false"
		parameter="method">
		<forward name="backToClinicalQuery" path="ispy.clinicalQuery" />
		<forward name="clinicalQuerySetup" path="/clinicalQueryInit.do?method=setup" />
	</action>

	<action path="/clinicalquery"
	    input="/clinicalQueryInit.do?method=setup"
		type="gov.nih.nci.ispy.web.struts.action.ClinicalQueryAction"
		name="clinicalQueryForm"
		scope="request"
		validate="true"
		parameter="method">
		<forward name="backToClinicalQuery" path="ispy.clinicalQuery" />
		<forward name="clinicalQuerySetup" path="/clinicalQueryInit.do?method=setup" />
		<forward name="viewResults" path="/viewResults.do" />
	</action>

	<action path="/correlationScatter"
		forward="ispy.correlationScatter" />

	<action path="/correlationScatterInit"
		type="gov.nih.nci.ispy.web.struts.action.CorrelationScatterAction"
		name="correlationScatterForm"
		scope="request"
		validate="false"
		parameter="method">
		<forward name="backToCorrelationScatter" path="ispy.correlationScatter" />
		<forward name="correlationScatterSetup" path="/correlationScatterInit.do?method=setup" />
	</action>

	<action path="/correlationscatter"
	    input="/correlationScatterInit.do?method=setup"
		type="gov.nih.nci.ispy.web.struts.action.CorrelationScatterAction"
		name="correlationScatterForm"
		scope="request"
		validate="true"
		parameter="method">
		<forward name="backToCorrelationScatter" path="ispy.correlationScatter" />
		<forward name="correlationScatterSetup" path="/correlationScatterInit.do?method=setup" />
		<forward name="viewResults" path="/viewResults.do" />
	</action>

	<action path="/categoricalCorrelation"
		forward="ispy.categoricalCorrelation" />

	<action path="/categoricalCorrelationInit"
		type="gov.nih.nci.ispy.web.struts.action.CategoricalCorrelationAction"
		name="categoricalCorrelationForm"
		scope="request"
		validate="false"
		parameter="method">
		<forward name="backToCategoricalCorrelation" path="ispy.categoricalCorrelation" />
		<forward name="categoricalCorrelationSetup" path="/categoricalCorrelationInit.do?method=setup" />
	</action>

	<action path="/categoricalcorrelation"
	    input="/categoricalCorrelationInit.do?method=setup"
		type="gov.nih.nci.ispy.web.struts.action.CategoricalCorrelationAction"
		name="categoricalCorrelationForm"
		scope="request"
		validate="true"
		parameter="method">
		<forward name="backToCategoricalCorrelation" path="ispy.categoricalCorrelation" />
		<forward name="categoricalCorrelationSetup" path="/categoricalCorrelationInit.do?method=setup" />
		<forward name="viewResults" path="/viewResults.do" />
	</action>

	<action path="/fish"
		forward="ispy.fish" />

	<action path="/fishQueryInit"
		type="gov.nih.nci.ispy.web.struts.action.FISHQueryAction"
		name="fishQueryForm"
		scope="request"
		validate="false"
		parameter="method">
		<forward name="backToFISHQuery" path="ispy.fishQuery" />
		<forward name="fishQuerySetup" path="/fishQueryInit.do?method=setup" />
	</action>

	<action path="/fishquery"
	    input="/fishQueryInit.do?method=setup"
		type="gov.nih.nci.ispy.web.struts.action.FISHQueryAction"
		name="fishQueryForm"
		scope="request"
		validate="true"
		parameter="method">
		<forward name="backToFISHQuery" path="ispy.fishQuery" />
		<forward name="fishQuerySetup" path="/fishQueryInit.do?method=setup" />
		<forward name="viewResults" path="/viewResults.do" />
	</action>

	<action path="/p53QueryInit"
		type="gov.nih.nci.ispy.web.struts.action.P53QueryAction"
		name="p53QueryForm"
		scope="request"
		validate="false"
		parameter="method">
		<forward name="backToP53Query" path="ispy.p53Query" />
		<forward name="p53QuerySetup" path="/p53QueryInit.do?method=setup" />
	</action>

		<action path="/p53query"
	    input="/p53QueryInit.do?method=setup"
		type="gov.nih.nci.ispy.web.struts.action.P53QueryAction"
		name="p53QueryForm"
		scope="request"
		validate="true"
		parameter="method">
		<forward name="backToP53Query" path="ispy.p53Query" />
		<forward name="p53QuerySetup" path="/p53QueryInit.do?method=setup" />
		<forward name="viewResults" path="/viewResults.do" />
	</action>

	<action path="/ihcLevel"
		forward="ispy.ihcLevel" />

	<action path="/ihcLevelQueryInit"
		type="gov.nih.nci.ispy.web.struts.action.IHCLevelOfExpressionQueryAction"
		name="ihcLevelQueryForm"
		scope="request"
		validate="false"
		parameter="method">
		<forward name="backToIHCLevelQuery" path="ispy.ihcLevelQuery" />
		<forward name="ihcLevelQuerySetup" path="/ihcLevelQueryInit.do?method=setup" />
	</action>

	<action path="/ihclevelquery"
	    input="/ihcLevelQueryInit.do?method=setup"
		type="gov.nih.nci.ispy.web.struts.action.IHCLevelOfExpressionQueryAction"
		name="ihcLevelQueryForm"
		scope="request"
		validate="true"
		parameter="method">
		<forward name="backToIHCLevelQuery" path="ispy.ihcLevelQuery" />
		<forward name="ihcLevelQuerySetup" path="/ihcLevelQueryInit.do?method=setup" />
		<forward name="viewResults" path="/viewResults.do" />
	</action>

	<action path="/ihcLoss"
		forward="ispy.ihcLoss" />

	<action path="/ihcLossQueryInit"
		type="gov.nih.nci.ispy.web.struts.action.IHCLossOfExpressionQueryAction"
		name="ihcLossQueryForm"
		scope="request"
		validate="false"
		parameter="method">
		<forward name="backToIHCLossQuery" path="ispy.ihcLossQuery" />
		<forward name="ihcLossQuerySetup" path="/ihcLossQueryInit.do?method=setup" />
	</action>

	<action path="/ihclossquery"
	    input="/ihcLossQueryInit.do?method=setup"
		type="gov.nih.nci.ispy.web.struts.action.IHCLossOfExpressionQueryAction"
		name="ihcLossQueryForm"
		scope="request"
		validate="true"
		parameter="method">
		<forward name="backToIHCLossQuery" path="ispy.ihcLosslQuery" />
		<forward name="ihcLossQuerySetup" path="/ihcLossQueryInit.do?method=setup" />
		<forward name="viewResults" path="/viewResults.do" />
	</action>

	<action path="/classComparison"
         forward="ispy.classComparison" />

    <action path="/classcomparisonInit"
	    type="gov.nih.nci.ispy.web.struts.action.ClassComparisonAction"
		name="classComparisonForm"
		scope="request"
		validate="false"
		parameter="method">
		<forward name="backToClassComparison" path="ispy.classComparison" />
		<forward name="classComparisonSetup" path="/classcomparisonInit.do?method=setup" />
	</action>

	<action path="/classcomparison"
	    input="/classcomparisonInit.do?method=setup"
		type="gov.nih.nci.ispy.web.struts.action.ClassComparisonAction"
		name="classComparisonForm"
		scope="request"
		validate="true"
		parameter="method">
		<forward name="backToClassComparison" path="ispy.classComparison" />
		<forward name="classComparisonSetup" path="/classcomparisonInit.do?method=setup" />
		<forward name="viewResults" path="/viewResults.do" />
	</action>

	<action path="/testReport" forward="/WEB-INF/jsp/ccReport.jsp" />

	<action path="/awWrapper" forward="/WEB-INF/jsp/awFrame.jsp" />

	<action path="/idDownload" forward="/WEB-INF/jsp/idMapperCSV.jsp" />

	<action path="/principalComponent"
         forward="nautilus.principalComponent" />

    <action path="/principalcomponentInit"
		type="gov.nih.nci.ispy.web.struts.action.PrincipalComponentAction"
		name="principalComponentForm"
		scope="request"
		validate="false"
		parameter="method">
		<forward name="backToPrincipalComponent" path="ispy.principalComponent" />
		<forward name="principalComponentSetup" path="/principalcomponentInit.do?method=setup" />
	</action>

	<action path="/principalcomponent"
	    input="/principalcomponentInit.do?method=setup"
		type="gov.nih.nci.ispy.web.struts.action.PrincipalComponentAction"
		name="principalComponentForm"
		scope="request"
		validate="true"
		parameter="method">
		<forward name="backToPrincipalComponent" path="ispy.principalComponent" />
		<forward name="principalComponentSetup" path="/principalcomponentInit.do?method=setup" />
		<forward name="viewResults" path="/viewResults.do" />
	</action>

	<action path="/hierarchicalClustering"
         forward="ispy.hierarchicalClustering" />

	<action path="/hierarchicalclustering"
	    input="/hierarchicalclusteringInit.do?method=setup"
		type="gov.nih.nci.ispy.web.struts.action.HierarchicalClusteringAction"
		name="hierarchicalClusteringForm"
		scope="request"
		validate="true"
		parameter="method">
		<forward name="backToHierarchicalClustering" path="ispy.hierarchicalClustering" />
		<forward name="hierarchicalClusteringSetup" path="/hierarchicalclustering.do?method=setup" />
		<forward name="viewResults" path="/viewResults.do" />
	</action>

	<action path="/hierarchicalclusteringInit"
		type="gov.nih.nci.ispy.web.struts.action.HierarchicalClusteringAction"
		name="hierarchicalClusteringForm"
		scope="request"
		validate="false"
		parameter="method">
		<forward name="backToHierarchicalClustering" path="ispy.hierarchicalClustering" />
		<forward name="hierarchicalClusteringSetup" path="/hierarchicalclustering.do?method=setup" />
	</action>

	<action path="/gpintegrationInit"
		type="gov.nih.nci.ispy.web.struts.action.GPIntegrationAction"
		name="gpIntegrationForm"
		scope="request"
		validate="false"
		parameter="method">
		<forward name="success" path="ispy.gpIntegration" />
	</action>

	<action path="/gpintegration"
		input="ispy.gpIntegration"
		type="gov.nih.nci.ispy.web.struts.action.GPIntegrationAction"
		name="gpIntegrationForm"
		scope="request"
		validate="true"
		parameter="method">
		<forward name="success" path="ispy.gpIntegration" />
		<!-- <forward name="viewJob" path="ispy.gpJobView" /> -->
		<forward name="viewJob" path="/gpProcess.do?method=setup" />
	</action>

		<action path="/gpProcess"
		input="ispy.gpJobView"
		type="gov.nih.nci.ispy.web.struts.action.GPProcessAction"
		name="gpProcessForm"
		scope="request"
		validate="false"
		parameter="method">
		<forward name="success" path="ispy.gpJobView" />
		<forward name="appletViewer" path="ispy.gpJobView" />
		<forward name="viewJob" path="/gpProcess.do?method=setup" />
	</action>

		<action path="/gpApplet"
         forward="/Applets/gp/gpApplet.jsp" />

	<action path="/loeReport" forward="/WEB-INF/jsp/loeReport.jsp" />

	<action path="/p53Report" forward="/WEB-INF/jsp/p53Report.jsp" />

	<action path="/pcaReport" forward="/WEB-INF/jsp/pcaReport.jsp" />

	<action path="/corrReport" forward="/WEB-INF/jsp/corrReport.jsp" />

	<action path="/catCorrReport" forward="/WEB-INF/jsp/catCorrReport.jsp" />

	<action path="/hcReport" forward="/WEB-INF/jsp/hcReport.jsp" />

	<action path="/quickClinical" forward="/WEB-INF/jsp/quickClinical.jsp" />

	<action path="/simpleSearch" forward="ispy.simpleSearch" />

	<action path="/manageLists" forward="ispy.manageLists" />

	<action path="/viewResults"
	    input="ispy.viewResults"
		type="gov.nih.nci.ispy.web.struts.action.ViewResultsAction"
		name="viewResultsForm"
		scope="request">
		<forward name="success" path="ispy.viewResults" />
	</action>

	<action path="/runReport"
           name="reportGeneratorForm"
	       type="gov.nih.nci.ispy.web.struts.action.ReportGeneratorAction"
	       scope="request"
           parameter="method"
           validate="false">
         <forward name="runGeneViewReport" path="/jsp/geneViewReport.jsp" />
         <forward name="runCSVGeneViewReport" path="/jsp/geneViewReportCSV.jsp" />
    </action>
 </action-mappings>

    <!-- ========== Controller Configuration =============================== -->
    <controller />
    <!-- ========== Message Resources Definitions ========================== -->
    <message-resources parameter="ApplicationResources" />
    <!-- ========== Plug Ins Configuration ================================= -->
	 <plug-in className="org.apache.struts.tiles.TilesPlugin" >
	   <set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml" />
	   <set-property property="definitions-parser-validate" value="true" />
	   <set-property property="definitions-debug" value="2" />
	   <set-property property="definitions-parser-details" value="2" />
	   <set-property property="moduleAware" value="true" />
	 </plug-in>
</struts-config>


text:
package io.netty.example.http.helloworld;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.HttpVersion;

import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;
import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpHeaderValues.CLOSE;
import static io.netty.handler.codec.http.HttpHeaderValues.KEEP_ALIVE;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

public class HttpHelloWorldServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    private static final byte[] CONTENT = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd' };

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
        if (msg instanceof HttpRequest) {
            HttpRequest req = (HttpRequest) msg;

            boolean keepAlive = HttpUtil.isKeepAlive(req);
            FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT));
            response.headers().set(CONTENT_TYPE, "text/plain");
            response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());

            if (keepAlive && req.protocolVersion().equals(HttpVersion.HTTP_1_0)) {
                response.headers().set(CONNECTION, KEEP_ALIVE);
            } else {
                // Tell the client we're going to close the connection.
                response.headers().set(CONNECTION, CLOSE);
            }

            ChannelFuture f = ctx.write(response);

            if (!keepAlive) {
                f.addListener(ChannelFutureListener.CLOSE);
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}


text:
import { IForgeCommandResponsePayload } from './forge-command-response-payload';
import { IForgeResponse } from './forge-response';

export interface IForgeCommandResponse extends IForgeResponse<IForgeCommandResponsePayload> {
}


text:
<?php
namespace Bpost;

use Bpost\BpostApiClient\Bpost\Order\Address;
use Bpost\BpostApiClient\Bpost\Order\Box\CustomsInfo\CustomsInfo;
use Bpost\BpostApiClient\Bpost\Order\Box\International;
use Bpost\BpostApiClient\Bpost\Order\Receiver;
use Bpost\BpostApiClient\Bpost\Order\Box\Option\Messaging;
use Bpost\BpostApiClient\Exception\BpostLogicException\BpostInvalidValueException;

class InternationalTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Create a generic DOM Document
     *
     * @return \DOMDocument
     */
    private static function createDomDocument()
    {
        $document = new \DOMDocument('1.0', 'utf-8');
        $document->preserveWhiteSpace = false;
        $document->formatOutput = true;

        return $document;
    }

    /**
     * Tests International->toXML
     */
    public function testToXML()
    {
        $data = array(
            'international' => array(
                'product' => 'bpack World Express Pro',
                'options' => array(
                    array(
                        'common:infoNextDay' => array(
                            '@attributes' => array(
                                'language' => 'NL',
                            ),
                            'common:emailAddress' => 'bpost@verkoyen.eu',
                        )
                    )
                ),
                'receiver' => array(
                    'name' => 'Tijs Verkoyen',
                    'company' => 'Sumo Coders',
                    'address' => array(
                        'streetName' => 'Afrikalaan',
                        'number' => '289',
                        'box' => '3',
                        'postalCode' => '9000',
                        'locality' => 'Gent',
                        'countryCode' => 'BE',
                    ),
                    'emailAddress' => 'bpost@verkoyen.eu',
                    'phoneNumber' => '+32 9 395 02 51',
                ),
                'parcelWeight' => 2000,
                'customsInfo' => array(
                    'parcelValue' => 700,
                    'contentDescription' => 'BOOK',
                    'shipmentType' => 'DOCUMENTS',
                    'parcelReturnInstructions' => 'RTS',
                    'privateAddress' => false,
                )
            ),
        );

        $expectedDocument = self::createDomDocument();
        $nationalBox = $expectedDocument->createElement('internationalBox');
        $expectedDocument->appendChild($nationalBox);
        $international = $expectedDocument->createElement('international:international');
        $nationalBox->appendChild($international);
        $international->appendChild(
            $expectedDocument->createElement('international:product', $data['international']['product'])
        );
        $options = $expectedDocument->createElement('international:options');
        foreach ($data['international']['options'] as $value) {
            foreach ($value as $key2 => $value2) {
                $element = $expectedDocument->createElement($key2);
                foreach ($value2 as $key3 => $value3) {
                    if ($key3 == '@attributes') {
                        foreach ($value3 as $key4 => $value4) {
                            $element->setAttribute($key4, $value4);
                        }
                    } else {
                        $element->appendChild(
                            $expectedDocument->createElement($key3, $value3)
                        );
                    }
                }

                $options->appendChild($element);
            }
        }
        $international->appendChild($options);
        $receiver = $expectedDocument->createElement('international:receiver');
        $international->appendChild($receiver);
        foreach ($data['international']['receiver'] as $key => $value) {
            $key = 'common:' . $key;
            if ($key == 'common:address') {
                $address = $expectedDocument->createElement($key);
                foreach ($value as $key2 => $value2) {
                    $key2 = 'common:' . $key2;
                    $address->appendChild(
                        $expectedDocument->createElement($key2, $value2)
                    );
                }
                $receiver->appendChild($address);
            } else {
                $receiver->appendChild(
                    $expectedDocument->createElement($key, $value)
                );
            }
        }
        $international->appendChild(
            $expectedDocument->createElement('international:parcelWeight', $data['international']['parcelWeight'])
        );
        $customsInfo = $expectedDocument->createElement('international:customsInfo');
        foreach ($data['international']['customsInfo'] as $key => $value) {
            if ($key == 'privateAddress') {
                $value = ($value) ? 'true' : 'false';
            }
            $customsInfo->appendChild(
                $expectedDocument->createElement('international:' . $key, $value)
            );
        }
        $international->appendChild($customsInfo);

        $actualDocument = self::createDomDocument();
        $address = new Address(
            $data['international']['receiver']['address']['streetName'],
            $data['international']['receiver']['address']['number'],
            $data['international']['receiver']['address']['box'],
            $data['international']['receiver']['address']['postalCode'],
            $data['international']['receiver']['address']['locality'],
            $data['international']['receiver']['address']['countryCode']
        );

        $receiver = new Receiver();
        $receiver->setName($data['international']['receiver']['name']);
        $receiver->setCompany($data['international']['receiver']['company']);
        $receiver->setAddress($address);
        $receiver->setEmailAddress($data['international']['receiver']['emailAddress']);
        $receiver->setPhoneNumber($data['international']['receiver']['phoneNumber']);

        $customsInfo = new CustomsInfo();
        $customsInfo->setParcelValue($data['international']['customsInfo']['parcelValue']);
        $customsInfo->setContentDescription($data['international']['customsInfo']['contentDescription']);
        $customsInfo->setShipmentType($data['international']['customsInfo']['shipmentType']);
        $customsInfo->setParcelReturnInstructions($data['international']['customsInfo']['parcelReturnInstructions']);
        $customsInfo->setPrivateAddress($data['international']['customsInfo']['privateAddress']);

        $messaging = new Messaging(
            'infoNextDay',
            $data['international']['options'][0]['common:infoNextDay']['@attributes']['language'],
            $data['international']['options'][0]['common:infoNextDay']['common:emailAddress']
        );

        $international = new International();
        $international->setProduct($data['international']['product']);
        $international->setReceiver($receiver);
        $international->setParcelWeight($data['international']['parcelWeight']);
        $international->setCustomsInfo($customsInfo);

        $international->addOption($messaging);

        // I know, the line below is kinda bogus, but it will make sure all code is tested
        $international->setOptions(array($messaging));

        $actualDocument->appendChild(
            $international->toXML($actualDocument)
        );

        $this->assertSame($expectedDocument->saveXML(), $actualDocument->saveXML());
    }

    /**
     * Test validation in the setters
     */
    public function testFaultyProperties()
    {
        $international = new International();

        try {
            $international->setProduct(str_repeat('a', 10));
            $this->fail('BpostInvalidValueException not launched');
        } catch (BpostInvalidValueException $e) {
            // Nothing, the exception is good
        } catch (\Exception $e) {
            $this->fail('BpostInvalidValueException not caught');
        }

        // Exceptions were caught,
        $this->assertTrue(true);
    }
}


text:
<?php

namespace DesignmovesDeviceContextTest\Factory\Options;

use DesignmovesDeviceContext\Factory\Options\ModuleOptionsFactory;
use PHPUnit_Framework_TestCase;
use Zend\Config\Config;
use Zend\ServiceManager\ServiceManager;

/**
 * @coversDefaultClass DesignmovesDeviceContext\Factory\Options\ModuleOptionsFactory
 */
class ModuleOptionsFactoryTest extends PHPUnit_Framework_TestCase
{
    /**
     * @var ModuleOptionsFactory
     */
    protected $factory;

    /**
     * @var ServiceManager
     */
    protected $serviceManager;

    public function setUp()
    {
        $this->factory        = new ModuleOptionsFactory;
        $this->serviceManager = new ServiceManager;
    }

    /**
     * @covers ::createService
     */
    public function testCanCreateService()
    {
        $config = new Config(array(
            'designmoves_device_context' => array(),
        ));
        $this->serviceManager->setService('Config', $config);

        $options = $this->factory->createService($this->serviceManager);
        $this->assertInstanceOf('DesignmovesDeviceContext\Options\ModuleOptions', $options);
    }
}


text:
<!DOCTYPE html>

        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>
            ProgressBar
        </title>
        <link rel="stylesheet" type="text/css" href="progress-bar.css">
        <link rel="stylesheet" type="text/css" href="../shared/example.css">

            Progress Bar

            The example shows how to use the ProgressBar class. The js is not minified so it is readable. See progress-bar.js.

            Basic Progress Bar: Deferred rendering, dynamic show/hide and built-in progress text: <button id="btn1">Show</button>

            Nothing to see here.

            Additional Options: Rendered on page load, left-aligned text and % width: <button id="btn2">Show</button>

            Waiting Bar: Wait for a long operation to complete (example will stop after 5 secs): <button id="btn3">Show</button>

            Ready

            Custom Styles: Rendered like Windows XP with custom progress text element: <button id="btn4">Show</button>

            Status:


text:
'''
Beacon to emit system load averages
'''

# Import Python libs
from __future__ import absolute_import
import logging
import os

# Import Salt libs
import salt.utils

# Import Py3 compat
from salt.ext.six.moves import zip

log = logging.getLogger(__name__)

__virtualname__ = 'load'

LAST_STATUS = {}

def __virtual__():
    if salt.utils.is_windows():
        return False
    else:
        return __virtualname__

def validate(config):
    '''
    Validate the beacon configuration
    '''

    # Configuration for load beacon should be a list of dicts
    if not isinstance(config, list):
        return False, ('Configuration for load beacon must be a list.')
    else:
        for config_item in config:
            if not isinstance(config_item, dict):
                return False, ('Configuration for load beacon must '
                               'be a list of dictionaries.')
            else:
                if not all(j in ['1m', '5m', '15m'] for j in config_item.keys()):
                    return False, ('Configuration for load beacon must '
                                   'contain 1m, 5m or 15m items.')

            for item in ['1m', '5m', '15m']:
                if item not in config_item:
                    continue

                if not isinstance(config_item[item], list):
                    return False, ('Configuration for load beacon: '
                                   '1m, 5m and 15m items must be '
                                   'a list of two items.')
                else:
                    if len(config_item[item]) != 2:
                        return False, ('Configuration for load beacon: '
                                       '1m, 5m and 15m items must be '
                                       'a list of two items.')
    return True, 'Valid beacon configuration'

def beacon(config):
    '''
    Emit the load averages of this host.

    Specify thresholds for each load average
    and only emit a beacon if any of them are
    exceeded.

    `onchangeonly`: when `onchangeonly` is True the beacon will fire
    events only when the load average pass one threshold.  Otherwise, it will fire an
    event at each beacon interval.  The default is False.

    `emitatstartup`: when `emitatstartup` is False the beacon will not fire
     event when the minion is reload. Applicable only when `onchangeonly` is True.
     The default is True.

    .. code-block:: yaml

        beacons:
          load:
            1m:
              - 0.0
              - 2.0
            5m:
              - 0.0
              - 1.5
            15m:
              - 0.1
              - 1.0
            emitatstartup: True
            onchangeonly: False

    '''
    log.trace('load beacon starting')

    # Default config if not present
    if 'emitatstartup' not in config:
        config['emitatstartup'] = True
    if 'onchangeonly' not in config:
        config['onchangeonly'] = False

    ret = []
    if not os.path.isfile('/proc/loadavg'):
        return ret
    with salt.utils.fopen('/proc/loadavg', 'rb') as fp_:
        avgs = fp_.read().split()[:3]
        avg_keys = ['1m', '5m', '15m']
        avg_dict = dict(zip(avg_keys, avgs))

        if config['onchangeonly']:
            if not LAST_STATUS:
                for k in ['1m', '5m', '15m']:
                    LAST_STATUS[k] = avg_dict[k]
                if not config['emitatstartup']:
                    log.debug('Dont emit because emitatstartup is False')
                    return ret

        send_beacon = False

        # Check each entry for threshold
        for k in ['1m', '5m', '15m']:
            if k in config:
                if config['onchangeonly']:
                    # Emit if current is more that threshold and old value less that threshold
                    if float(avg_dict[k]) > float(config[k][1]) and float(LAST_STATUS[k]) < float(config[k][1]):
                        log.debug('Emit because {0} > {1} and last was {2}'.format(float(avg_dict[k]), float(config[k][1]), float(LAST_STATUS[k])))
                        send_beacon = True
                        break
                    # Emit if current is less that threshold and old value more that threshold
                    if float(avg_dict[k]) < float(config[k][0]) and float(LAST_STATUS[k]) > float(config[k][0]):
                        log.debug('Emit because {0} < {1} and last was {2}'.format(float(avg_dict[k]), float(config[k][0]), float(LAST_STATUS[k])))
                        send_beacon = True
                        break
                else:
                    # Emit no matter LAST_STATUS
                    if float(avg_dict[k]) < float(config[k][0]) or \
                    float(avg_dict[k]) > float(config[k][1]):
                        log.debug('Emit because {0} < {1} or > {2}'.format(float(avg_dict[k]), float(config[k][0]), float(config[k][1])))
                        send_beacon = True
                        break

        if config['onchangeonly']:
            for k in ['1m', '5m', '15m']:
                LAST_STATUS[k] = avg_dict[k]

        if send_beacon:
            ret.append(avg_dict)

    return ret


text:
package server

// WorkQueue server implementation
// Copyright (c) 2017 - Valentin Kuznetsov <vkuznet@gmail.com>

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httputil"
	"strings"
	"time"

	log "github.com/sirupsen/logrus"

	"github.com/segmentio/pointer"
	"github.com/vkuznet/WorkQueue/core"
	"github.com/vkuznet/WorkQueue/services"
	"github.com/vkuznet/WorkQueue/utils"
	"github.com/zemirco/couchdb"
)

// global variable which we initialize once
var _userDNs []string
var authVar bool

func userDNs() []string {
	var out []string
	rurl := "https://cmsweb.cern.ch/sitedb/data/prod/people"
	resp := utils.FetchResponse(rurl, "")
	if resp.Error != nil {
		log.Println("ERROR unable to fetch SiteDB records", resp.Error)
		return out
	}
	var rec map[string]interface{}
	err := json.Unmarshal(resp.Data, &rec)
	if err != nil {
		log.Println("ERROR unable to unmarshal response", err)
		return out
	}
	desc := rec["desc"].(map[string]interface{})
	headers := desc["columns"].([]interface{})
	var idx int
	for i, h := range headers {
		if h.(string) == "dn" {
			idx = i
			break
		}
	}
	values := rec["result"].([]interface{})
	for _, item := range values {
		val := item.([]interface{})
		v := val[idx]
		if v != nil {
			out = append(out, v.(string))
		}
	}
	return out
}

// func init() {
//	_userDNs = userDNs()
//}

// Init is custom initialization function, we don't use init() because we want
// control of authentication from command line
func Init(authArg bool) {
	authVar = authArg
	if authVar {
		_userDNs = userDNs()
	}
}

// custom logic for CMS authentication, users may implement their own logic here
func auth(r *http.Request) bool {

	if !authVar {
		return true
	}

	if utils.VERBOSE > 1 {
		dump, err := httputil.DumpRequest(r, true)
		log.Println("AuthHandler HTTP request", r, string(dump), err)
	}
	userDN := utils.UserDN(r)
	match := utils.InList(userDN, _userDNs)
	if !match {
		log.Println("ERROR Auth userDN", userDN, "not found in SiteDB")
	}
	return match
}

// AuthHandler authenticate incoming requests and route them to appropriate handler
func AuthHandler(w http.ResponseWriter, r *http.Request) {
	// check if server started with hkey file (auth is required)
	status := auth(r)
	if !status {
		msg := "You are not allowed to access this resource"
		http.Error(w, msg, http.StatusForbidden)
		return
	}
	arr := strings.Split(r.URL.Path, "/")
	path := arr[len(arr)-1]
	switch path {
	case "log":
		LogHandler(w, r)
	case "status":
		StatusHandler(w, r)
	case "requests":
		RequestHandler(w, r)
	default:
		DefaultHandler(w, r)
	}
}

// GET methods

// StatusHandler provides information about the agent
func StatusHandler(w http.ResponseWriter, r *http.Request) {

	if r.Method != "GET" {
		w.WriteHeader(http.StatusMethodNotAllowed)
		return
	}

	// find our how many request in workqueue
	params := couchdb.QueryParameters{
		Group: pointer.Bool(true),
	}
	view := core.DB.View("WorkQueue")
	res, err := view.Get("elementsByWorkflow", params)
	if err != nil {
		panic(err)
	}
	addrs := utils.HostIP()
	astats := core.WorkqueueStatus{Addrs: addrs, TimeStamp: time.Now().Unix(), Metrics: core.WorkqueueMetrics.ToDict(), NumberOfRequests: len(res.Rows)}
	data, err := json.Marshal(astats)
	if err != nil {
		log.Println("ERROR StatusHandler", err)
		w.WriteHeader(http.StatusInternalServerError)
	} else {
		w.WriteHeader(http.StatusOK)
	}
	w.Write(data)
}

// RequestHandler provides information about the agent
func RequestHandler(w http.ResponseWriter, r *http.Request) {

	if r.Method != "GET" {
		w.WriteHeader(http.StatusMethodNotAllowed)
		return
	}

	// get requests for given type
	rtype := r.FormValue("type")
	requests := services.GetRequests(rtype)
	data, err := json.Marshal(requests)
	if err != nil {
		log.Println("ERROR StatusHandler", err)
		w.WriteHeader(http.StatusInternalServerError)
	} else {
		w.WriteHeader(http.StatusOK)
	}
	w.Write(data)
}

// DefaultHandler provides information about the agent
func DefaultHandler(w http.ResponseWriter, r *http.Request) {

	if r.Method != "GET" {
		w.WriteHeader(http.StatusMethodNotAllowed)
		return
	}
	w.WriteHeader(http.StatusOK)
	// TODO: implement here default page for data-service
	// should be done via templates
	msg := fmt.Sprintf("Default page: %v\n", time.Now())
	w.Write([]byte(msg))
}

// POST methods

type level struct {
	Level int `json:"level"`
}

// LogHandler sets verbosity level for the server
func LogHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		w.WriteHeader(http.StatusMethodNotAllowed)
		return
	}
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		log.Warn("Unable to parse request body: ", err)
	}
	var v struct {
		Level     int    `json:"level"`
		Metric    string `json:"metric"`
		LogLevel  string `json:"loglevel"`
		LogFormat string `json:"logformat"`
	}
	err = json.Unmarshal(body, &v)
	if err == nil {
		switch v.Metric {
		case "verbose":
			utils.VERBOSE = v.Level
		case "memory":
			if v.Level == 0 {
				utils.MEMORY = false
			} else {
				utils.MEMORY = true
			}
		case "log":
			utils.LogSettings(v.LogLevel, v.LogFormat)
		default:
		}
	}
	w.WriteHeader(http.StatusOK)
}


text:
  Mont-devant-Sassey est
       un village
       localisé dans le département de Meuse en Lorraine. Elle comptait 104 habitants en 2008.

Si vous pensez emmenager à Mont-devant-Sassey, vous pourrez facilement trouver une maison à vendre.

Le parc d'habitations, à Mont-devant-Sassey, se décomposait en 2011 en quatre appartements et 108 maisons soit
 un marché plutôt équilibré.

À coté de Mont-devant-Sassey sont localisées les communes de
Cléry-le-Petit à 4 km, 205 habitants,
Milly-sur-Bradon à 2 km, 167 habitants,
Halles-sous-les-Côtes localisée à 5 km, 151 habitants,
Villers-devant-Dun à 4 km, 70 habitants,
Wiseppe à 5 km, 110 habitants,
Dun-sur-Meuse à 2 km, 747 habitants,
 entre autres. De plus, Mont-devant-Sassey est située à seulement 29 km de Thierville-sur-Meuse.


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Revis. gen. pl. (Leipzig) 3: 446 (1898)

#### Original name
Lachnella hystricula Ellis & Everh.

### Remarks
null


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Annls Sci. Nat. , Bot. , sér. 2 17: 108 (1842)

#### Original name
Septoria polygonorum Desm., 1842

### Remarks
null


text:
package org.xins.client;

import org.xins.common.service.CallException;
import org.xins.common.service.TargetDescriptor;

/**
 * XINS-specific call exception.
 *
 * @version $Revision$ $Date$
 * @author Ernst de Haan
 *
 * @since XINS 1.0.0
 */
public abstract class XINSCallException extends CallException {

   /**
    * Constructs a new XINSCallException based on a short reason,
    * the original request, target called, call duration, detail message and
    * cause exception.
    *
    * @param shortReason
    *    the short reason, cannot be null.
    *
    * @param request
    *    the original request, cannot be null.
    *
    * @param target
    *    descriptor for the target that was attempted to be called, can be null.
    *
    * @param duration
    *    the call duration in milliseconds, must be >= 0.
    *
    * @param detail
    *    a detailed description of the problem, can be null if
    *    there is no more detail.
    *
    * @param cause
    *    the cause exception, can be null.
    *
    * @throws IllegalArgumentException
    *    if shortReason == null
    *          || request == null
    *          || duration < 0.
    */
   XINSCallException(String           shortReason,
                     XINSCallRequest  request,
                     TargetDescriptor target,
                     long             duration,
                     String           detail,
                     Throwable        cause)
   throws IllegalArgumentException {

      // Call superconstructor
      super(shortReason, request, target, duration, detail, cause);
   }

   /**
    * Constructs a new XINSCallException based on a short reason,
    * a XINS call result, detail message and cause exception.
    *
    * @param shortReason
    *    the short reason, cannot be null.
    *
    * @param result
    *    the call result, cannot be null.
    *
    * @param detail
    *    a detailed description of the problem, can be null if
    *    there is no more detail.
    *
    * @param cause
    *    the cause exception, can be null.
    *
    * @throws IllegalArgumentException
    *    if shortReason == null || result == null.
    */
   XINSCallException(String           shortReason,
                     XINSCallResult   result,
                     String           detail,
                     Throwable        cause)
   throws IllegalArgumentException {

      // Call superconstructor
      super(shortReason,
            (result == null) ? null : result.getRequest(),
            (result == null) ? null : result.getSucceededTarget(),
            (result == null) ?   0L : result.getDuration(),
            detail,
            cause);
   }
}


text:
\# Последовательности

### Условие

В основном `CASE` используется для замены длинных конструкций из `IF` с включеным `ELSIF`. Например:

```text
IF Svetofor = 1 THEN
    // Color green
ELSIF Svetofor = 2 THEN
    // Color yellow
ELSIF Svetofor = 3 THEN
    // Color red
ELSE
    // Off
END_IF
```

Подобную конструкцию можно заменить на `CASE`

```text
CASE Svetofor OF
    1: // Color green
    2: // Color yellow
    3: // Color red
ELSE
    // Off
END_CASE
```

Может конкретно в этом случае, нет прироста в сокращении кода и оптимизации, но чаще такие конструкции читаются гораздо легче.

Вместо числовых индексов можно использовать перечисления. Например если у вас есть свой тип перечисление.

```text
TYPE
    SV : (red :=1, green := 2, orange := 3);
END_TYPE
```

То `CASE` может выглядеть более интуитивно.

```text
VAR
    Svetofor : SV;
END_VAR

CASE Svetofor OF
    green:
        // Color green
    orange:
        // Color yellow
    red:
        // Color red
ELSE
    // Off
END_CASE
```

Такой блок читается еще проще.

## Последовательности

Однако, одним из самых сильных сторон условия `CASE` - это использования его для создания последовательностей или другими словами пошаговых операций.

Если сразу взять все языки МЭК 61131, то понятно что ST может заменить их все И даже больше, он может то чего графические языки не могут. Сомненеие вызывает только один язык, SFC. Хотя я считаяю что SFC не совсем язык. Или даже **SFC совсем не язык программирования** хотя и назван языком в википедии. SFC это скорей определитель структуры программы для ее пошагового вызова. Это просто способ определить какая программа на каком шаге будет исполнятся, а сама исполняемая прогрмма, реализуется на других языках прогрммирования ST, FBD, LD, CFC. Другими словами самим языком SFC вы ни когда не присвоете ни какой переменной значение и не вызовите ни какой функции или ФБ, а только определите шаг где подобныйвызов должен произойти. SFC это просто набор компонентов как шаг, тарнзакция, действие, ... но внутри каждого компонента нужно использовать ST, FBD, LD или CFC.

Так вот `CASE` прекрасно заменяет SFC и позволяет легко структурировать код, для его последовательного или пошагового вызова. Если вы схватите основную идею, то вам будет все не почем и вы будет использовать это почти везде где нужна цикличность.

Давайте рассмотрим на примере. Допустим у нас упаковочная машина. Пакуем конфетки. Мы пишем алгоритм для участка измерения, где мы считаем сколько конфеток, попадёт у упаковку. И так у нас следующий алгоритм.

1. Открываем бункер и сыпем конфетки. У нас есть датчик который делает один импульс на каждую пролетающую конфетку.
2. Досчитали нужное количество, закрываем бункер
3. Запечатываем упаковку термо прессом на 1 секунду
4. Продергиваем рукав упаковки, что бы насыпать следующую партию

   VAR Step : USINT := 0; Ctu1 : CTU; Ton1 : TON; END\_VAR

   CASE Step OF

   \(_ Ни чего не происходит. Ждем пока кто то запустит процесс. _\) 0: \(_ Если кто-то нажал кнопку старт, переходим на шаг 10 _\) IF btnStart THEN Step := 10; END\_IF

   \(_ Делаем протяжку и убеждаемся что упаковка в нужном положении. _\) 10: \(_ Включаем протяжку _\) Role := TRUE;

   ```text
    (* Если датчик увидел метку на рукаве, выключаем протяжку и переходим на шаг 20 *)
    IF PackPosition THEN
        Role := FALSE;
        Step := 20;
    END_IF
   ```

   \(_ Начинаем сыпать конфетки _\) 20:

   ```text
    (* Открываем бункер с конфетками *)
    KandyGate := TRUE;

    (* Назначаем датчик пролета конфеток на вход отсчета *)
    Ctu1.CU := KandyFly;

    (* Назначаем что счетчик будет отсчитывать 20 конфеток в упаковку. *)
    Ctu1.PV := 20;

    Ctu1();

    (*
        Если мы достигли уставки в 20 конфеток, сбрасываем счетчик, зарываем бункер
        и переходим на шаг склейки упаковки.
    *)
    IF Ctu1.Q THEN
        Ctu1(RESET := TRUE);
        Ctu1.RESET := FALSE;
        KandyGate := FALSE;
        Step := 30;
    END_IF
   ```

   30:

   ```text
    (* Включаем пневмоцелиндр утюжка на сжатие *)
    Clamp := TRUE;

    (* Назначаем таймеру время на 1ну секунду и запускаем его *)
    Ton1.IN := TRUE;
    Ton1.PT := T#1s;

    Ton1();

    (*
        Как время истекло, раскрываем утюжек, сбрасываем таймер,
        и возвращаемся к шагу 10 для подергивания рукава упаковки
        для новой пачки
    *)
    IF Ton1.Q THEN
        Clamp := FALSE;
        Ton1(IN := FALSE);
        Step := 10;
    END_IF
   ```

   END\_CASE

Ну как? Шикарно! Смотрите как это элегантно, понятно и гибко.

Обратите внимание как шаги я использовал числа 10, 20, 30, ... Я мог бы использовать 1, 2, 3, ... но это сделано для того, что бы в последствии туда можно было вставить другие шаги. Например мне нужно вставить шаг между 10 и 20, я дам ему номер 15. Таким образом нумерация шагов сохранит числовую последовательность.

Еще один хороший способ, это создания перечисления, и использования имен шагов, вместо цифр. Это сделает код более читабельным. И при таком подходе не обязательно будет сохранять числовую последовательность.

#### Таймеры в последовательностях

Очень часто выход из какогото шага происходит по условии времени, по этому использование таймеров является частой практикой. Есть 2 паттерна программирования `CASE` с таймерами.

**Таймер за **`CASE`

Такой метоод рекомендован некотырыми популярными книгами по МЭК 61131-3, хотя я считаю что у него есть ряд недостатков, но и ряд приемуществ. Рассмотрим пример.

Вот примемущества:

1. Как вы видите из за того что таймер вынесен за условие `CASE` нам не надо его брасывать по окончании работы, от сам сброситься. Так же к
2. Код внутри `CASE` выглядит чище, и проще читается.

   Какие недостатки? Преимущества следующего патерна будут как раз недостатками текущего.

**Таймер внутри **`CASE`

Этот метод тоже рекомендуется в книге, но не в других а в этой. Вот посмотрите пример:

Как вы видите что хотя нам нужно сбрасывать таймер, и кода больше у нас есть следующие приемущества.

1. Мы не разделяем код. Запуская таймер внутри `CASE` мы делаем код понятным. Когда код запускается в другом месте прогрммы, может получиться эффект магии, когда не совсем понятно как работает код.
2. Так как мы можем находиться только водном участке `CASE`, то мы можем определить и использовать только один экземпляр таймера.

#### Паралельные процессы

И таких процессов может идти несколько паралельно. Далее участок упаковки в коробки, по 20 пакетов в коробку. Естественно он не будет сделудующим шагом, что бы конфеткам не ждать, а будет другой `CASE`.

## Оптимизация

Этот пример не оптимизирован что бы легче было понять именно принцип использования `CASE`. Для быстродействия можно некоторые объявления поменять позиции. Например, объявления в шаге 20:

```text
Ctu1.CU := KandyFly;
Ctu1.PV := 20;
```

Можно перемесить в шаг 0. Они статичны, и не нужно эту операцию присвоения делать на каждый цикл пока мы в шаге 20.

Или объявление в шаге 20

```text
KandyGate := TRUE;
```

Можно перенести в шаг 10

```text
IF PackPosition THEN
    Role := FALSE;
    KandyGate := TRUE;
    Step := 20;
END_IF
```

В этом случае операция присвоения не будет выполняться только один раз на выходе из шага 10

Есть и другие улучшения. Посмотрите, я использовал для переменой `Step`, тип `USINT`. Это только положительные числа от 0 до 255. Я знаю, что я не выйду за эти пределы, так зачем мне резервировать в памяти больше байтов при помощи `INT` которую, обычно используют для большинства числовых переменных?

Хотя в этом примере задача показать не оптимизацию, а принцип последовательных вызовов, на оптимизацию всегда нужно обращать внимание. Эти поправки - мелочи, но они вырабатывают отношение. ПЛК это не 4х ядерный компьютер. Его ресурсы сильно ограничены, и нужно быть очень осторожным как вы их используете на каждом шаге, и все эти мелочи в последствии могут дать значительный прирост в производительности.

## Другие случаи

`CASE` можно и нужно использовать везде, где требуется последовательный или блокирующий вызов функций.

Причина этого кроется в принципе исполнения программы в ПЛК. Если, например, сравнить с другими языками как РНР, то там исполнение идет от строки к строке и не переходит к следующей строке, пока предыдущая строка не закончила исполнения. Другими словами одна строка блокирует исполнение другой. Поэтому можно в столбец писать открытие файла, чтение, и потом закрытие и быть уверенным, что чтение не начнется, пока файл не откроется. При этом запущенный код, может исполняться не определённое количество времени, и по завершении останавливается до следующего запуска.

Стиль программирования ПЛК на ST другой, потому что программа исполняется по циклу. ПЛК не будет ждать пока ФБ закончит работу, например подключения к удаленному сервису, а пойдет дальше. Именно по этому нам нужно убедиться, что в следующей строке мы взываем следующий ФБ, когда предыдущий завершил свою работу.

Именно

Например, подключение по сокету к удаленному серверу. Нам нужно создать соединение, потом его открыть, сделать запрос, прочитать данные и закрыть. И каждое следующее действие нужно делать только когда предыдущее закончило


text:
BluetoothLowEnergyInAction
==========================


text:
namespace gfx {
class Size;
struct GpuMemoryBufferHandle;
}  // namespace gfx

namespace media {
// Gets the file size of |fd| and writes in |size|. Returns false on failure.
MEDIA_GPU_EXPORT bool GetFileSize(const int fd, size_t* size);

// Verifies if GpuMemoryBufferHandle is valid.
MEDIA_GPU_EXPORT bool VerifyGpuMemoryBufferHandle(
    media::VideoPixelFormat pixel_format,
    const gfx::Size& coded_size,
    const gfx::GpuMemoryBufferHandle& gmb_handle);

}  // namespace media
#endif  // MEDIA_GPU_BUFFER_VALIDATION_H_