text:
package com.nhnent.haste.transport.udp;

import com.nhnent.haste.common.*;
import com.nhnent.haste.security.BigInteger;
import com.nhnent.haste.transport.AbstractNetworkPeer;
import com.nhnent.haste.transport.DisconnectReason;
import com.nhnent.haste.transport.QoS;
import com.nhnent.haste.transport.state.ConnectionState;
import com.nhnent.haste.transport.state.Disconnected;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.zip.CRC32;

public final class UDPNetworkPeer extends AbstractNetworkPeer implements TransportPeer {
    private static final Logger logger = LoggerFactory.getLogger(UDPNetworkPeer.class);

    private final byte[] writeBuf = new byte[2048];
    private final ByteBuffer writeByteBuffer = ByteBuffer.wrap(writeBuf);

    private int udpBufferIndex = 0;
    private short udpCommandCount = 0;

    private static final int MAX_COMMANDS_ON_MTU = 100;
    private static final int WARNING_SIZE = 100;
    private static final int SENT_COUNT_ALLOWANCE = 3;

    private SocketAddress socketAddress;

    private final int MTU;
    private final int DISCONNECT_TIMEOUT;
    private final int CHANNEL_COUNT;
    private final byte LAST_CHANNEL;

    private final boolean isCRCEnabled;

    private int packetLossByCRC = 0;
    private CRC32 crc32 = new CRC32();

    private long lastSentData = 0;

    private long SEND_INTERVAL_MILLISECOUNDS = 20;

    private List<Disposable> cleanUpEvents = Collections.synchronizedList(new ArrayList<Disposable>());

    private final List<IncomingCommand> receivedCommands = new Vector<>(MAX_COMMANDS_ON_MTU);

    private final List<OutgoingCommand> outgoingAckList = new Vector<>(MAX_COMMANDS_ON_MTU);

    private final Map<Byte, Channel> channels;

    private UDPNetworkPeer(Builder builder) {
        super(builder, EnvironmentTimer.currentTimeMillis());

        this.MTU = builder.Mtu;
        this.DISCONNECT_TIMEOUT = builder.disconnectionTimeout;
        this.CHANNEL_COUNT = builder.channelCount;

        this.isCRCEnabled = builder.enableCRC;
        this.socketAddress = builder.socketAddress;

        channels = new LinkedHashMap<>(CHANNEL_COUNT);

        for (int i = 0; i < CHANNEL_COUNT; i++) {
            channels.put((byte) i, new Channel(i));
        }

        LAST_CHANNEL = (byte) (CHANNEL_COUNT - 1);
    }

    @Override
    public boolean enqueueOutgoingCommand(byte[] payload, int payloadLength, byte channelIndex, boolean encrypt, QoS qos) {
        if (getConnectionState().isNotEqual(ConnectionState.CONNECTED)) {
            if (logger.isDebugEnabled())
                logger.debug("PeerID[{}] is not connected [{}]", peerID, getConnectionState());
            return false;
        }

        CommandType commandType = (qos == QoS.RELIABLE_SEQUENCED) ? CommandType.RELIABLE : CommandType.UNRELIABLE;

        return createAndEnqueueCommand(commandType, payload, payloadLength, channelIndex, encrypt);
    }

    private boolean createAndEnqueueCommand(CommandType commandType, byte[] payload, int payloadLength, byte channelIndex, boolean encrypt) {
        Channel channel = channels.get(channelIndex);

        if (channel == null) {
            if (logger.isDebugEnabled())
                logger.debug("[{}] channel is not found", channelIndex);
            return false;
        }

        int maximumPayloadSize = MTU - (CommandLength.UDP_MTU_HEADER_LENGTH.getLength() + CommandLength.FRAGMENTED_HEADER_SIZE.getLength());

        if (payloadLength < maximumPayloadSize) {
            OutgoingCommand command = OutgoingCommand.newOutgoingCommand(commandType, payload, payloadLength, encrypt, channelIndex);
            return queueOutgoingCommand(channel, command);
        } else { //FRAGMENT
            short fragmentCount = (short) ((payloadLength + maximumPayloadSize - 1) / maximumPayloadSize);
            long startSequenceNumber = channel.getOutgoingReliableSeqNum() + 1;

            short fragmentSeq = 0;

            for (int offset = 0; offset < payloadLength; offset += maximumPayloadSize) {
                if (payloadLength - offset < maximumPayloadSize) {
                    //Specify last fragment's payload
                    maximumPayloadSize = payloadLength - offset;
                }

                byte[] fragment = new byte[maximumPayloadSize];
                System.arraycopy(payload, offset, fragment, 0, maximumPayloadSize);

                OutgoingCommand command = OutgoingCommand.newOutgoingCommand(CommandType.FRAGMENT, fragment, fragment.length, encrypt, channelIndex);

                command.setFragmentNum(fragmentSeq++);
                command.setStartSeqNum(startSequenceNumber);
                command.setFragmentCount(fragmentCount);
                command.setFragmentOffset(offset);
                command.setFragmentPayloadTotalLength(payloadLength);

                boolean result = queueOutgoingCommand(channel, command);

                if (!result)
                    return false;
            }

            return true;
        }
    }

    private boolean queueOutgoingCommand(Channel channel, OutgoingCommand command) {
        assert command.getSentCount() == 0;

        if (command.isReliable()) {

            int queueSize = channel.outgoingReliableCommandCount();

            if (queueSize > Channel.MAX_COMMAND_SIZE) {
                return false;
            }

            command.setReliableSeqNum(channel.increaseOutgoingReliableSeqNum());

            channel.insertOutgoingReliableCommand(command);

        } else {    //CF_UNRELIABLE

            command.setReliableSeqNum(channel.getOutgoingReliableSeqNum());
            command.setUnreliableSeqNum(channel.increaseOutgoingUnreliableSeqNum());

            channel.insertOutgoingUnreliableCommand(command);
        }

        return true;
    }

    @Override
    public int getPeerID() {
        return super.getPeerID();
    }

    private static class ChannelQueue {
        Queue<OutgoingCommand> unreliableCommandQueue;
        Queue<OutgoingCommand> reliableCommandQueue;
        Channel channel;
    }

    @Override
    public void send(DatagramChannel ch, long currentTime) {
        if (getConnectionState().isEqual(ConnectionState.DISCONNECTED))
            return;

        if (lastSentData + SEND_INTERVAL_MILLISECOUNDS > currentTime) {
            return;
        } else {
            lastSentData = currentTime;
        }

        //Check valid connection state.
        if (currentTime > timestampOfLastReceive + DISCONNECT_TIMEOUT) {
            long interval = currentTime - timestampOfLastReceive;
            if (logger.isDebugEnabled())
                logger.debug("PeerID[{}] Disconnect because valid command is not coming from client during [{}]", peerID, interval);
            disconnect(DisconnectReason.TIMEOUT_DISCONNECT, "Cannot receive any command during " + DISCONNECT_TIMEOUT);
        }

        // the resendCommand method must be called before a channelQueueList was made.
        // then, a channel which contains a resend command is added in a channelQueueList.
        resendCommand(currentTime);

        Queue<ChannelQueue> channelQueueList = new ArrayBlockingQueue<>(channels.size());

        for (Channel channel : channels.values()) {
            ChannelQueue queue = new ChannelQueue();

            queue.unreliableCommandQueue = channel.getOutgoingUnreliableCommandQueue();
            queue.reliableCommandQueue = channel.getOutgoingReliableCommandList();
            queue.channel = channel;

            if (queue.unreliableCommandQueue.size() > 0 || queue.reliableCommandQueue.size() > 0)
                channelQueueList.add(queue);
        }

        int commandLeft;

        do {
            commandLeft = 0;

            writeByteBuffer.clear();

            udpBufferIndex = 0;
            udpCommandCount = 0;

            udpBufferIndex = CommandLength.UDP_MTU_HEADER_LENGTH.getLength();

            sendAck();

            while (!channelQueueList.isEmpty()) {

                ChannelQueue channelQueue = channelQueueList.peek();

                commandLeft = serializeToBuffer(currentTime, channelQueue.unreliableCommandQueue, channelQueue.channel);
                commandLeft += serializeToBuffer(currentTime, channelQueue.reliableCommandQueue, channelQueue.channel);

                if (commandLeft > 0) {
                    break;
                } else if (commandLeft == 0) {
                    channelQueueList.poll();
                }
            }

            if (udpCommandCount > 0) {
                goOut(ch, currentTime);
            }

        } while (commandLeft > 0);

        if (getConnectionState().isEqual(ConnectionState.DISCONNECTING)) {
            getConnectionState().transitDisconnected(this);
            onDisconnected(this.disconnectReason, this.disconnectDetail);
        }
    }

    private void goOut(DatagramChannel ch, long currentTime) {
        int offset = 0;

        offset = ByteWrite.setByte(CommandType.MESSAGES.getByte(), writeBuf, offset);
        offset = ByteWrite.setInt(getPeerID(), writeBuf, offset);
        offset = ByteWrite.setLong(currentTime, writeBuf, offset);
        offset = ByteWrite.setShort(udpCommandCount, writeBuf, offset);

        if (isCRCEnabled) {
            CRC.Write(crc32, writeBuf, udpBufferIndex, offset);
        }

        offset += CRC.CRC_LENGTH;

        assert offset == CommandLength.UDP_MTU_HEADER_LENGTH.getLength();

        writeByteBuffer.position(udpBufferIndex);

        try {
            writeByteBuffer.flip();

            int sentBytes = ch.send(writeByteBuffer, socketAddress);

            if (udpBufferIndex != sentBytes) {
                if (logger.isDebugEnabled())
                    logger.debug("sent bytes: {}", sentBytes);
            }

        } catch (IOException e) {
            logger.error("failed to send!", e);
        }
    }

    private int serializeToBuffer(long currentTime, Queue<OutgoingCommand> commandQueue, Channel channel) {
        while (commandQueue.size() > 0) {

            OutgoingCommand outgoingCommand = commandQueue.peek();

            int length = outgoingCommand.getSerializedArrayLength();

            if ((udpBufferIndex + length) > MTU) {
                break;
            } else {
                commandQueue.poll();
            }

            outgoingCommand.serialize();

            udpBufferIndex = ByteWrite.set(outgoingCommand.serialize(), 0, length, writeBuf, udpBufferIndex);
            udpCommandCount++;

            if (outgoingCommand.isReliable()) {
                queueSentReliableCommand(currentTime, channel, outgoingCommand);
            }
        }

        return commandQueue.size();
    }

    private void queueSentReliableCommand(long currentTime, Channel channel, OutgoingCommand outgoingCommand) {
        outgoingCommand.setSentTime(currentTime);
        outgoingCommand.increaseSentCount();

        outgoingCommand.setRetransmissionTimeout(currentTime, getMeanOfRoundTripTime(), getMeanOfRoundTripTimeDeviation());

        if (outgoingCommand.getSentCount() == 1) {
            outgoingCommand.setTimeout(currentTime + DISCONNECT_TIMEOUT);
            channel.addSentReliableCommand(outgoingCommand);
        }
    }

    private void resendCommand(long currentTime) {
        for (Channel channel : channels.values()) {
            if (!channel.resend(currentTime)) {
                disconnect(DisconnectReason.TIMEOUT_DISCONNECT, "timeout");
            }
        }
    }

    public void sendAck() {
        if (0 == outgoingAckList.size())
            return;

        short ackCommandCount = 0;

        List<OutgoingCommand> removeList = new LinkedList<>();
        for (OutgoingCommand command : outgoingAckList) {
            byte[] array = command.serialize();
            int length = command.getSerializedArrayLength();

            if (udpBufferIndex + length >= MTU) {
                break;
            }

            removeList.add(command);
            ackCommandCount++;

            System.arraycopy(array, 0, writeBuf, udpBufferIndex, length);
            udpBufferIndex += length;
        }

        for (int i = 0; i < removeList.size(); i++) {
            if (outgoingAckList.contains(removeList.get(i))) {
                outgoingAckList.remove(removeList.get(i));
            }
        }
        removeList.clear();

        int queueSize = outgoingAckList.size();
        if (queueSize > 0 && (queueSize % WARNING_SIZE) == 0) {
            if (logger.isDebugEnabled())
                logger.debug("[{}] outgoingAckList Count [{}]", peerID, queueSize);
        }

        udpCommandCount += ackCommandCount;
    }

    public static final class Builder extends AbstractNetworkPeer.AbstractBuilder<Builder> {
        private final int CHANNEL_COUNT_MAX = 100;
        private final int CHANNEL_COUNT_MIN = 5;
        private final int MIN_MTU_SIZE = 400;

        private SocketAddress socketAddress = null;
        private int Mtu = MIN_MTU_SIZE;
        private int disconnectionTimeout = -1;
        private boolean enableCRC = false;
        private int channelCount = CHANNEL_COUNT_MIN;

        public Builder() {
        }

        public Builder socketAddress(SocketAddress socketAddress) {
            this.socketAddress = socketAddress;
            return this;
        }

        public Builder mtu(int Mtu) {
            this.Mtu = Mtu;
            return this;
        }

        public Builder disconnectTimeout(int disconnectionTimeout) {
            this.disconnectionTimeout = disconnectionTimeout;
            return this;
        }

        public Builder enableCRC(boolean enableCRC) {
            this.enableCRC = enableCRC;
            return this;
        }

        public Builder channelCount(int channelCount) {
            this.channelCount = channelCount < CHANNEL_COUNT_MIN ? CHANNEL_COUNT_MIN :
                    channelCount > CHANNEL_COUNT_MAX ? CHANNEL_COUNT_MAX : channelCount;
            return this;
        }

        public UDPNetworkPeer build() {
            return new UDPNetworkPeer(this);
        }
    }

    public BigInteger getServerKey() {
        return super.serverKeyNumber;
    }

    @Override
    public void addDisposeEvent(Disposable disposeEvent) {
        cleanUpEvents.add(disposeEvent);
    }

    private final Map<Integer, Channel> temporalChannelList = new HashMap<>();

    @Override
    public void onReceive(long currentTime, SocketAddress socketAddress, ByteBuffer byteBuffer, int transferredBytes) {
        if (Disconnected.instance == getConnectionState()) {
            return;
        }

        if (this.socketAddress != socketAddress) {
            this.socketAddress = socketAddress;
        }

        long serverSentTime = byteBuffer.getLong();     //8
        long commandCount = byteBuffer.getShort();      //2

        if (isCRCEnabled) {
            if (!CRC.Check(crc32, byteBuffer.array(), transferredBytes, byteBuffer.position())) {
                logger.debug("Invalid CRC value");
                packetLossByCRC++;

                if ((packetLossByCRC > 0) && (packetLossByCRC % 100) == 0) {
                    if (logger.isDebugEnabled())
                        logger.debug("[{}] CRC error count[{}] address[{}]", peerID, packetLossByCRC, socketAddress.toString());
                }

                return;
            }
        }

        byteBuffer.position(byteBuffer.position() + CRC.CRC_LENGTH);

        if (commandCount > MAX_COMMANDS_ON_MTU || commandCount <= 0) {
            disconnect(DisconnectReason.INVALID_DATA_FORMAT, "Invalid Command Count : " + commandCount);
        }

        timestampOfLastReceive = currentTime;

        try {
            for (int i = 0; i < commandCount; i++) {
                IncomingCommand command = IncomingCommand.newIncomingCommand(timestampOfLastReceive, byteBuffer);

                if (!command.valid()) {
                    disconnect(DisconnectReason.INVALID_DATA_FORMAT, "Invalid commandType");
                    return;
                }

                if (command.isReliable()) {
                    OutgoingCommand ack = command.createAck(serverSentTime);
                    outgoingAckList.add(ack);
                }

                receivedCommands.add(command);
            }

            for (IncomingCommand command : receivedCommands) {
                Channel channel = chooseChannelToProcess(command);

                if (channel != null)
                    temporalChannelList.put(channel.getChannelNumber(), channel);
            }

            for (Channel channel : temporalChannelList.values()) {
                processChannel(channel);
            }

        } finally {
            receivedCommands.clear();
            temporalChannelList.clear();
        }
    }

    private void processChannel(Channel channel) {
        IncomingCommand targetCommand;

        do {
            targetCommand = null;

            if (channel.incomingUnreliableCommandCount() > 0) {
                long minimumUnreliableSeq = Long.MAX_VALUE;

                Set<Long> seqs = channel.getIncomingUnreliableCommandSeqs();

                for (Long seq : seqs) {
                    IncomingCommand command = channel.getIncomingUnreliableCommand(seq);

                    if (command == null)
                        continue;

                    long reliableSeq = command.getReliableSeqNum();
                    long unreliableSeq = command.getUnreliableSeqNum();

                    if (unreliableSeq < minimumUnreliableSeq && reliableSeq == channel.getIncomingReliableSeqNum()) {
                        minimumUnreliableSeq = unreliableSeq;
                    }
                }

                if (minimumUnreliableSeq < Long.MAX_VALUE) {
                    targetCommand = channel.getIncomingUnreliableCommand(minimumUnreliableSeq);

                    if (targetCommand != null) {
                        channel.removeIncomingUnreliableCommand(targetCommand.getUnreliableSeqNum());
                        channel.setIncomingUnreliableSeqNum(targetCommand.getUnreliableSeqNum());
                    }
                }
            }

            if (targetCommand == null && channel.incomingReliableCommandCount() > 0) {

                long expectedReliableSeq = channel.getIncomingReliableSeqNum() + 1;

                if (!channel.containIncomingReliableSeqNum(expectedReliableSeq)) {
                    //it's not necessary to check because unreliable commands are retrieved already.
                    break;
                }

                targetCommand = channel.getIncomingReliableCommand(expectedReliableSeq);
                if (targetCommand == null) {
                    break;
                }

                switch (targetCommand.getCommandType()) {
                    case PING:
                    case EG_SERVER_TIME:
                    case RELIABLE: {
                        long reliableSeq = targetCommand.getReliableSeqNum();

                        channel.setIncomingReliableSeqNum(reliableSeq);
                        channel.removeIncomingReliableCommand(reliableSeq);
                        break;
                    }
                    case FRAGMENT: {

                        long startSeq = targetCommand.getFragmentStartSeqNum();
                        long endSeq = targetCommand.getFragmentStartSeqNum() + targetCommand.getFragmentCount();

                        for (long seq = startSeq; seq < endSeq; seq++) {
                            if (!channel.containIncomingReliableSeqNum(seq)) {
                                targetCommand = null;
                                break;
                            }
                        }

                        if (targetCommand == null)
                            break;

                        byte[] payload = new byte[targetCommand.getFragmentPayloadTotalLength()];

                        for (long seq = startSeq; seq < endSeq; seq++) {
                            IncomingCommand command = channel.getIncomingReliableCommand(seq);
                            if (command == null)
                                continue;
                            if (command.getPayload() != null)
                                command.getPayload().copyBytes(payload, command.getFragmentOffset(), command.getPayload().getLength());
                            channel.removeIncomingReliableCommand(seq);
                        }

                        targetCommand.setPayloadBuf(payload, targetCommand.getFragmentPayloadTotalLength());
                        channel.setIncomingReliableSeqNum(channel.getIncomingReliableSeqNum() + targetCommand.getFragmentCount());
                        break;
                    }
                }
            }

            if (targetCommand != null) {
                switch (targetCommand.getCommandType()) {
                    case RELIABLE:
                    case UNRELIABLE:
                    case FRAGMENT:
                        forwardToClientPeer(targetCommand);
                        break;
                    case DISCONNECT:
                        processDisconnectCommand(targetCommand);
                        break;
                    default:
                        break;
                }
                targetCommand.release();
            }
        } while (targetCommand != null);
    }

    private void forwardToClientPeer(IncomingCommand targetCommand) {
        if (getConnectionState().isEqual(ConnectionState.CONNECTING)) {
            getClientPeer(targetCommand.getPayload(), targetCommand.getChannelIndex());

            if (isClientPeerNull())
                disconnect(DisconnectReason.SERVER_DISCONNECT, "server logic error");
        }
        sendDataToClientPeer(
                targetCommand.getPayload(),
                targetCommand.getChannelIndex(),
                targetCommand.isEncrypted(),
                targetCommand.isReliable() ? QoS.RELIABLE_SEQUENCED : QoS.UNRELIABLE_SEQUENCED);
    }

    private Channel chooseChannelToProcess(IncomingCommand command) {
        Check.NotNull(command, "command");

        Channel channel = null;

        if (getConnectionState().isEqual(ConnectionState.DISCONNECTED))
            return null;

        switch (command.getCommandType()) {
            case ACK: {
                handleReceivedAck(command);
                command.release();
                break;
            }
            case PING: {
                channel = queueIncomingCommand(command);
                break;
            }
            case EG_SERVER_TIME: {
                channel = queueIncomingCommand(command);
                break;
            }
            case DISCONNECT: {
                getConnectionState().transitDisconnected(this);
                if (logger.isDebugEnabled()) {
                    logger.debug("[{}] Recv Disconnect command from Client", peerID);
                }
                processDisconnectCommand(command);
                command.release();
                break;
            }
            case UNRELIABLE:
            case RELIABLE: {
                if (getConnectionState().isEqual(ConnectionState.DISCONNECTED) ||
                        getConnectionState().isEqual(ConnectionState.DISCONNECTING))
                    return null;

                channel = queueIncomingCommand(command);

                break;
            }
            case FRAGMENT: {
                channel = handleFragmentedCommand(command);
                break;
            }
            default: {
                disconnect(DisconnectReason.INVALID_DATA_FORMAT, "Invalid Command Type");
                break;
            }
        }

        return channel;
    }

    private Channel handleFragmentedCommand(final IncomingCommand command) {
        Channel channel = queueIncomingCommand(command);

        if (channel == null)
            return null;

        int totalCommands = command.getFragmentCount();

        long startSeq = command.getFragmentStartSeqNum();
        long endSeq = startSeq + totalCommands;

        for (long seq = startSeq; seq < endSeq; seq++) {
            if (!channel.containIncomingReliableSeqNum(seq)) {
                return null;
            }
        }

        return channel;
    }

    private Channel queueIncomingCommand(final IncomingCommand command) {
        Check.NotNull(command, "command");

        Channel channel = channels.get(command.getChannelIndex());
        if (channel == null)
            return null;

        long reliableSeq = command.getReliableSeqNum();

        if (command.isReliable()) {
            if (reliableSeq <= channel.getIncomingReliableSeqNum() ||
                    channel.containIncomingReliableSeqNum(reliableSeq)) {
                command.release();
                return null;
            }

            channel.insertIncomingReliableCommand(command);

            int queueSize = channel.incomingReliableCommandCount();

            if (queueSize > 0 && (queueSize % WARNING_SIZE) == 0) {
                if (logger.isDebugEnabled())
                    logger.debug("[{}] ch[{}] incomingReliableCommand Count [{}]",
                            peerID, channel.getChannelNumber(), queueSize);
            }
        } else { //CF_UNRELIABLE
            if (command.getReliableSeqNum() < channel.getIncomingReliableSeqNum() ||
                    command.getUnreliableSeqNum() <= channel.getIncomingUnreliableSeqNum()) {
                command.release();
                return null;
            }

            channel.insertIncomingUnreliableCommand(command);

            int queueSize = channel.incomingUnreliableCommandCount();

            if (queueSize > 0 && (queueSize % WARNING_SIZE) == 0) {
                if (logger.isDebugEnabled())
                    logger.debug("[{}] ch[{}] incomingUnreliableCommand Count [{}]",
                            peerID, channel.getChannelNumber(), queueSize);
            }
        }

        return channel;
    }

    private void handleReceivedAck(IncomingCommand command) {
        byte channelIndex = command.getChannelIndex();

        Channel channel = channels.get(channelIndex);
        if (channel == null)
            return;

        if (channel.removeSentReliableCommand(command.getAckReceivedReliableSeq())) {
            long rtt = command.getRoundTripTime();

            if (logger.isTraceEnabled()) {
                logger.trace("[{}] Received Ack ch[{}] seq[{}] rtt[{}] rev[{}] sent[{}]",
                        peerID,
                        command.getChannelIndex(),
                        command.getAckReceivedReliableSeq(),
                        command.getRoundTripTime(),
                        command.getReceiveTime(),
                        command.getAckReceivedSentTime());
            }

            UpdateRoundTripTimeAndVariance(rtt);
        }
    }

    public void processDisconnectCommand(IncomingCommand command) {
        if (command.getCommandType() != CommandType.DISCONNECT) {
            return;
        }

        byte[] payload = command.getPayload().getBytes();
        int reasonCode = ByteRead.getInt(payload, 0);

        DisconnectReason reason = DisconnectReason.getReason(reasonCode);
        onDisconnected(reason, reason.toString());

        doCleanUp();
    }

    @Override
    public void disconnect(DisconnectReason disconnectReason, String detail) {
        if (getConnectionState().isEqual(ConnectionState.DISCONNECTED) ||
                getConnectionState().isEqual(ConnectionState.DISCONNECTING)) {
            return;
        }

        if (detail.isEmpty()) {
            detail = "unknown";
        }

        int reason = disconnectReason.getInt();
        byte[] message = detail.getBytes();
        int length = message.length;

        byte[] payload = new byte[length + 4 + 4];

        int offset = 0;
        offset = ByteWrite.setInt(reason, payload, offset);
        offset = ByteWrite.setInt(length, payload, offset);
        offset = ByteWrite.setBytes(message, 0, length, payload, offset);

        // TODO Must call onDisconnect when disconnecting by timeout.
        createAndEnqueueCommand(CommandType.DISCONNECT, payload, offset, LAST_CHANNEL, false);

        this.disconnectReason = disconnectReason;
        this.disconnectDetail = detail;
        getConnectionState().transitDisconnecting(this);
    }

    private void doCleanUp() {
        synchronized (cleanUpEvents) {
            for (Disposable disposable : cleanUpEvents) {
                disposable.dispose();
            }
            cleanUpEvents.clear();
        }
    }

    @Override
    public void dispose() {
        if (getConnectionState().isEqual(ConnectionState.DISCONNECTING)) {
            logger.error("Invalid state, when it is expected disconnected status but it is disconnecting status");

            getConnectionState().transitDisconnected(this);
            onDisconnected(DisconnectReason.UNKNOWN_ERROR, "this peer has invalid status");
        }
        doCleanUp();
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.trafficmanager.fluent.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.management.ProxyResource;
import com.azure.resourcemanager.trafficmanager.models.EndpointMonitorStatus;
import com.azure.resourcemanager.trafficmanager.models.EndpointPropertiesCustomHeadersItem;
import com.azure.resourcemanager.trafficmanager.models.EndpointPropertiesSubnetsItem;
import com.azure.resourcemanager.trafficmanager.models.EndpointStatus;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;

/** Class representing a Traffic Manager endpoint. */
@Fluent
public final class EndpointInner extends ProxyResource {
    /*
     * The properties of the Traffic Manager endpoint.
     */
    @JsonProperty(value = "properties")
    private EndpointProperties innerProperties;

    /*
     * Fully qualified resource Id for the resource. Ex -
     * /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficManagerProfiles/{resourceName}
     */
    @JsonProperty(value = "id")
    private String id;

    /*
     * The name of the resource
     */
    @JsonProperty(value = "name")
    private String name;

    /*
     * The type of the resource. Ex- Microsoft.Network/trafficManagerProfiles.
     */
    @JsonProperty(value = "type")
    private String type;

    /** Creates an instance of EndpointInner class. */
    public EndpointInner() {
    }

    /**
     * Get the innerProperties property: The properties of the Traffic Manager endpoint.
     *
     * @return the innerProperties value.
     */
    private EndpointProperties innerProperties() {
        return this.innerProperties;
    }

    /**
     * Get the id property: Fully qualified resource Id for the resource. Ex -
     * /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficManagerProfiles/{resourceName}.
     *
     * @return the id value.
     */
    public String id() {
        return this.id;
    }

    /**
     * Set the id property: Fully qualified resource Id for the resource. Ex -
     * /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficManagerProfiles/{resourceName}.
     *
     * @param id the id value to set.
     * @return the EndpointInner object itself.
     */
    public EndpointInner withId(String id) {
        this.id = id;
        return this;
    }

    /**
     * Get the name property: The name of the resource.
     *
     * @return the name value.
     */
    public String name() {
        return this.name;
    }

    /**
     * Set the name property: The name of the resource.
     *
     * @param name the name value to set.
     * @return the EndpointInner object itself.
     */
    public EndpointInner withName(String name) {
        this.name = name;
        return this;
    }

    /**
     * Get the type property: The type of the resource. Ex- Microsoft.Network/trafficManagerProfiles.
     *
     * @return the type value.
     */
    public String type() {
        return this.type;
    }

    /**
     * Set the type property: The type of the resource. Ex- Microsoft.Network/trafficManagerProfiles.
     *
     * @param type the type value to set.
     * @return the EndpointInner object itself.
     */
    public EndpointInner withType(String type) {
        this.type = type;
        return this;
    }

    /**
     * Get the targetResourceId property: The Azure Resource URI of the of the endpoint. Not applicable to endpoints of
     * type 'ExternalEndpoints'.
     *
     * @return the targetResourceId value.
     */
    public String targetResourceId() {
        return this.innerProperties() == null ? null : this.innerProperties().targetResourceId();
    }

    /**
     * Set the targetResourceId property: The Azure Resource URI of the of the endpoint. Not applicable to endpoints of
     * type 'ExternalEndpoints'.
     *
     * @param targetResourceId the targetResourceId value to set.
     * @return the EndpointInner object itself.
     */
    public EndpointInner withTargetResourceId(String targetResourceId) {
        if (this.innerProperties() == null) {
            this.innerProperties = new EndpointProperties();
        }
        this.innerProperties().withTargetResourceId(targetResourceId);
        return this;
    }

    /**
     * Get the target property: The fully-qualified DNS name or IP address of the endpoint. Traffic Manager returns this
     * value in DNS responses to direct traffic to this endpoint.
     *
     * @return the target value.
     */
    public String target() {
        return this.innerProperties() == null ? null : this.innerProperties().target();
    }

    /**
     * Set the target property: The fully-qualified DNS name or IP address of the endpoint. Traffic Manager returns this
     * value in DNS responses to direct traffic to this endpoint.
     *
     * @param target the target value to set.
     * @return the EndpointInner object itself.
     */
    public EndpointInner withTarget(String target) {
        if (this.innerProperties() == null) {
            this.innerProperties = new EndpointProperties();
        }
        this.innerProperties().withTarget(target);
        return this;
    }

    /**
     * Get the endpointStatus property: The status of the endpoint. If the endpoint is Enabled, it is probed for
     * endpoint health and is included in the traffic routing method.
     *
     * @return the endpointStatus value.
     */
    public EndpointStatus endpointStatus() {
        return this.innerProperties() == null ? null : this.innerProperties().endpointStatus();
    }

    /**
     * Set the endpointStatus property: The status of the endpoint. If the endpoint is Enabled, it is probed for
     * endpoint health and is included in the traffic routing method.
     *
     * @param endpointStatus the endpointStatus value to set.
     * @return the EndpointInner object itself.
     */
    public EndpointInner withEndpointStatus(EndpointStatus endpointStatus) {
        if (this.innerProperties() == null) {
            this.innerProperties = new EndpointProperties();
        }
        this.innerProperties().withEndpointStatus(endpointStatus);
        return this;
    }

    /**
     * Get the weight property: The weight of this endpoint when using the 'Weighted' traffic routing method. Possible
     * values are from 1 to 1000.
     *
     * @return the weight value.
     */
    public Long weight() {
        return this.innerProperties() == null ? null : this.innerProperties().weight();
    }

    /**
     * Set the weight property: The weight of this endpoint when using the 'Weighted' traffic routing method. Possible
     * values are from 1 to 1000.
     *
     * @param weight the weight value to set.
     * @return the EndpointInner object itself.
     */
    public EndpointInner withWeight(Long weight) {
        if (this.innerProperties() == null) {
            this.innerProperties = new EndpointProperties();
        }
        this.innerProperties().withWeight(weight);
        return this;
    }

    /**
     * Get the priority property: The priority of this endpoint when using the 'Priority' traffic routing method.
     * Possible values are from 1 to 1000, lower values represent higher priority. This is an optional parameter. If
     * specified, it must be specified on all endpoints, and no two endpoints can share the same priority value.
     *
     * @return the priority value.
     */
    public Long priority() {
        return this.innerProperties() == null ? null : this.innerProperties().priority();
    }

    /**
     * Set the priority property: The priority of this endpoint when using the 'Priority' traffic routing method.
     * Possible values are from 1 to 1000, lower values represent higher priority. This is an optional parameter. If
     * specified, it must be specified on all endpoints, and no two endpoints can share the same priority value.
     *
     * @param priority the priority value to set.
     * @return the EndpointInner object itself.
     */
    public EndpointInner withPriority(Long priority) {
        if (this.innerProperties() == null) {
            this.innerProperties = new EndpointProperties();
        }
        this.innerProperties().withPriority(priority);
        return this;
    }

    /**
     * Get the endpointLocation property: Specifies the location of the external or nested endpoints when using the
     * 'Performance' traffic routing method.
     *
     * @return the endpointLocation value.
     */
    public String endpointLocation() {
        return this.innerProperties() == null ? null : this.innerProperties().endpointLocation();
    }

    /**
     * Set the endpointLocation property: Specifies the location of the external or nested endpoints when using the
     * 'Performance' traffic routing method.
     *
     * @param endpointLocation the endpointLocation value to set.
     * @return the EndpointInner object itself.
     */
    public EndpointInner withEndpointLocation(String endpointLocation) {
        if (this.innerProperties() == null) {
            this.innerProperties = new EndpointProperties();
        }
        this.innerProperties().withEndpointLocation(endpointLocation);
        return this;
    }

    /**
     * Get the endpointMonitorStatus property: The monitoring status of the endpoint.
     *
     * @return the endpointMonitorStatus value.
     */
    public EndpointMonitorStatus endpointMonitorStatus() {
        return this.innerProperties() == null ? null : this.innerProperties().endpointMonitorStatus();
    }

    /**
     * Set the endpointMonitorStatus property: The monitoring status of the endpoint.
     *
     * @param endpointMonitorStatus the endpointMonitorStatus value to set.
     * @return the EndpointInner object itself.
     */
    public EndpointInner withEndpointMonitorStatus(EndpointMonitorStatus endpointMonitorStatus) {
        if (this.innerProperties() == null) {
            this.innerProperties = new EndpointProperties();
        }
        this.innerProperties().withEndpointMonitorStatus(endpointMonitorStatus);
        return this;
    }

    /**
     * Get the minChildEndpoints property: The minimum number of endpoints that must be available in the child profile
     * in order for the parent profile to be considered available. Only applicable to endpoint of type
     * 'NestedEndpoints'.
     *
     * @return the minChildEndpoints value.
     */
    public Long minChildEndpoints() {
        return this.innerProperties() == null ? null : this.innerProperties().minChildEndpoints();
    }

    /**
     * Set the minChildEndpoints property: The minimum number of endpoints that must be available in the child profile
     * in order for the parent profile to be considered available. Only applicable to endpoint of type
     * 'NestedEndpoints'.
     *
     * @param minChildEndpoints the minChildEndpoints value to set.
     * @return the EndpointInner object itself.
     */
    public EndpointInner withMinChildEndpoints(Long minChildEndpoints) {
        if (this.innerProperties() == null) {
            this.innerProperties = new EndpointProperties();
        }
        this.innerProperties().withMinChildEndpoints(minChildEndpoints);
        return this;
    }

    /**
     * Get the geoMapping property: The list of countries/regions mapped to this endpoint when using the 'Geographic'
     * traffic routing method. Please consult Traffic Manager Geographic documentation for a full list of accepted
     * values.
     *
     * @return the geoMapping value.
     */
    public List<String> geoMapping() {
        return this.innerProperties() == null ? null : this.innerProperties().geoMapping();
    }

    /**
     * Set the geoMapping property: The list of countries/regions mapped to this endpoint when using the 'Geographic'
     * traffic routing method. Please consult Traffic Manager Geographic documentation for a full list of accepted
     * values.
     *
     * @param geoMapping the geoMapping value to set.
     * @return the EndpointInner object itself.
     */
    public EndpointInner withGeoMapping(List<String> geoMapping) {
        if (this.innerProperties() == null) {
            this.innerProperties = new EndpointProperties();
        }
        this.innerProperties().withGeoMapping(geoMapping);
        return this;
    }

    /**
     * Get the subnets property: The list of subnets, IP addresses, and/or address ranges mapped to this endpoint when
     * using the 'Subnet' traffic routing method. An empty list will match all ranges not covered by other endpoints.
     *
     * @return the subnets value.
     */
    public List<EndpointPropertiesSubnetsItem> subnets() {
        return this.innerProperties() == null ? null : this.innerProperties().subnets();
    }

    /**
     * Set the subnets property: The list of subnets, IP addresses, and/or address ranges mapped to this endpoint when
     * using the 'Subnet' traffic routing method. An empty list will match all ranges not covered by other endpoints.
     *
     * @param subnets the subnets value to set.
     * @return the EndpointInner object itself.
     */
    public EndpointInner withSubnets(List<EndpointPropertiesSubnetsItem> subnets) {
        if (this.innerProperties() == null) {
            this.innerProperties = new EndpointProperties();
        }
        this.innerProperties().withSubnets(subnets);
        return this;
    }

    /**
     * Get the customHeaders property: List of custom headers.
     *
     * @return the customHeaders value.
     */
    public List<EndpointPropertiesCustomHeadersItem> customHeaders() {
        return this.innerProperties() == null ? null : this.innerProperties().customHeaders();
    }

    /**
     * Set the customHeaders property: List of custom headers.
     *
     * @param customHeaders the customHeaders value to set.
     * @return the EndpointInner object itself.
     */
    public EndpointInner withCustomHeaders(List<EndpointPropertiesCustomHeadersItem> customHeaders) {
        if (this.innerProperties() == null) {
            this.innerProperties = new EndpointProperties();
        }
        this.innerProperties().withCustomHeaders(customHeaders);
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (innerProperties() != null) {
            innerProperties().validate();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package s_mach.codetools.codegen

import s_mach.codetools.impl

object CaseClassCodegen {

  /**
    * Field definition in a case class
    * @param name name of field
    * @param _type type of field
    * @param optDefault default value of field
    * @param optComment comment for field
    */
  case class Field(
    name: String,
    _type: String,
    optDefault: Option[String] = None,
    optComment: Option[String] = None
  )

  /**
   * Generates Scala code for a case class. If the case class has less than 22
   * fields then a normal case class is generated. If the case class has more
   * than 22 fields a big case class is generated. Generated case  class chunks
   * fields into groups of 22 and creates a child case class for  each chunk.
   * Each generated child case class is named using base class name  with an
   * incremented sequence number appended. Generated code includes  everything
   * that would normally be implemented by compiler for a case class, including:
   * 1. copy method
   * 2. Product methods (productElement, productArity & productIterator)
   * 3. Companion object with apply method (and child case classes)
   *
   * @param name the name of the case class
   * @param fields one or more case class fields
   * @return
   */
  def genCaseClass(name: String, fields: Vector[Field]) : String =
    impl.CaseClassPrinter.printCaseClass(name,fields)

  /**
   * Generates Scala code for a big (> 22 field) case class. Generated case
   * class chunks fields into groups of 22 and creates a child case class for
   * each chunk. Each generated child case class is named using base class name
   * with an incremented sequence number appended. Generated code includes
   * everything that would normally be implemented by compiler for a
   * case class, including:
   * 1. copy method
   * 2. Product methods (productElement, productArity & productIterator)
   * 3. Companion object with apply method (and child case classes)
   *
   * @param name the name of the case class
   * @param fields one or more case class fields
   * @return
   */
  def genBigCaseClass(name: String, fields: Vector[Field]) : String =
    impl.BigCaseClassPrinter.printBigCaseClass(name,fields)
}


text:
<?php

namespace App\Http\Controllers\API\MediaInformation;

use App\Http\Controllers\Controller;
use App\Models\Artist;
use App\Services\MediaInformationService;

class ArtistController extends Controller
{
    public function __construct(private MediaInformationService $mediaInformationService)
    {
    }

    public function show(Artist $artist)
    {
        return response()->json($this->mediaInformationService->getArtistInformation($artist)?->toArray() ?: []);
    }
}


text:
<?php

declare(strict_types=1);

namespace League\CommonMark\Extension\HeadingPermalink;

use League\CommonMark\Node\Node;
use League\CommonMark\Renderer\ChildNodeRendererInterface;
use League\CommonMark\Renderer\NodeRendererInterface;
use League\CommonMark\Util\HtmlElement;
use League\CommonMark\Xml\XmlNodeRendererInterface;
use League\Config\ConfigurationAwareInterface;
use League\Config\ConfigurationInterface;

/**
 * Renders the HeadingPermalink elements
 */
final class HeadingPermalinkRenderer implements NodeRendererInterface, XmlNodeRendererInterface, ConfigurationAwareInterface
{
    public const DEFAULT_SYMBOL = '¶';

    /** @psalm-readonly-allow-private-mutation */
    private ConfigurationInterface $config;

    public function setConfiguration(ConfigurationInterface $configuration): void
    {
        $this->config = $configuration;
    }

    /**
     * @param HeadingPermalink $node
     *
     * {@inheritDoc}
     *
     * @psalm-suppress MoreSpecificImplementedParamType
     */
    public function render(Node $node, ChildNodeRendererInterface $childRenderer): \Stringable
    {
        HeadingPermalink::assertInstanceOf($node);

        $slug = $node->getSlug();

        $idPrefix = (string) $this->config->get('heading_permalink/id_prefix');
        if ($idPrefix !== '') {
            $idPrefix .= '-';
        }

        $fragmentPrefix = (string) $this->config->get('heading_permalink/fragment_prefix');
        if ($fragmentPrefix !== '') {
            $fragmentPrefix .= '-';
        }

        $attrs = $node->data->getData('attributes');
        $attrs->set('id', $idPrefix . $slug);
        $attrs->set('href', '#' . $fragmentPrefix . $slug);
        $attrs->append('class', $this->config->get('heading_permalink/html_class'));

        $hidden = $this->config->get('heading_permalink/aria_hidden');
        if ($hidden) {
            $attrs->set('aria-hidden', 'true');
        }

        $attrs->set('title', $this->config->get('heading_permalink/title'));

        $symbol = $this->config->get('heading_permalink/symbol');
        \assert(\is_string($symbol));

        return new HtmlElement('a', $attrs->export(), \htmlspecialchars($symbol), false);
    }

    public function getXmlTagName(Node $node): string
    {
        return 'heading_permalink';
    }

    /**
     * @param HeadingPermalink $node
     *
     * @return array<string, scalar>
     *
     * @psalm-suppress MoreSpecificImplementedParamType
     */
    public function getXmlAttributes(Node $node): array
    {
        HeadingPermalink::assertInstanceOf($node);

        return [
            'slug' => $node->getSlug(),
        ];
    }
}


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "crond_server_perf_log".
 *
 * @property integer $id
 * @property integer $crond_server_id
 * @property integer $cpu
 * @property integer $memory
 * @property datetime $sampling_time
 */
class CrondServerPerfLog extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'crond_server_perf_log';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['crond_server_id','cpu','memory'], 'integer'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'crond_server_id' => 'crond_server_id',
            'cpu' => 'cpu',
            'memory' => 'Memory',
            'sampling_time' => 'sampling_time'

        ];
    }
}


text:
package com.ironhide.movies;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;

import com.squareup.picasso.Picasso;

import java.util.List;

/**
 * Created by animesh on 30/7/16.
 */
public class MovieAdapter extends ArrayAdapter<Movie> {
    private String LogTAG = MovieAdapter.class.getName();
    private final static String BaseURL = "http://image.tmdb.org/t/p/w300/";

    public MovieAdapter(Activity context, List<Movie> movies)
    {
        super(context,0,movies);
    }

    /**
     * {@inheritDoc}
     *
     * @param position
     * @param convertView
     * @param parent
     */
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        Movie movie = getItem(position);
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(
                    R.layout.movie_listing, parent, false);
        }

        SquareImageView poster = (SquareImageView) convertView.findViewById(R.id.moviePoster);

        if(movie.getImgUrl().equals("null"))
        {
            Picasso.with(convertView.getContext()).load("https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQ17gHXp36K44nGCZSmy0ceuCAEQG4zBZqFWrvNuRxmFaQSuCuB").into(poster);

        }
        else {
            Picasso.with(convertView.getContext()).load(BaseURL + movie.getImgUrl()).into(poster);
        }
        return convertView;
    }
}


text:
        <?php echo $this->getNavTabs(array('settings' => 'Settings', 'help' => 'Help'), $page); ?>

    <form method="post" action="" enctype="multipart/form-data">

            <input name="reset" type="submit" value="Reset Options" class="button left" onclick="return confirm('Click OK to reset. Any settings will be lost!');">
            <input type="submit" value="Save All Changes" class="button-primary right" name="save-settings" id="save">

                <?php include('plugin-' . $page . ".php"); ?>

            <?php include("plugin-side.php"); ?>

            <input name="reset" type="submit" value="Reset Options" class="button left" onclick="return confirm('Click OK to reset. Any settings will be lost!');">
            <input type="submit" value="Save All Changes" class="button-primary right" name="save-settings" id="save">

    </form>


text:
tripsModule.directive('tripDirective', [function () {
    return {
        restrict: 'A', // Attribute
        templateUrl: 'app/views/directives/tripDirective.html',
        scope: {
            model: '=',
            isLoged: '='
        },
        link: function (scope, element, attributes, controller) {
            //console.log(scope.model);
            //console.log(element);
        },
        replace: false,
        priority: 0,
    };
}]);


text:
package com.amit.realmmvp.presenters;

import android.text.TextUtils;

import com.amit.realmmvp.booksadd.BooksAddNewContract;
import com.amit.realmmvp.booksadd.BooksAddNewPresenter;
import com.amit.realmmvp.models.RealmService;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.runners.MockitoJUnitRunner;

import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.verify;

/**
 * Created by Amit Barjatya on 10/10/17.
 */

@RunWith(MockitoJUnitRunner.class)
public class TestBooksAddNewPresenter {

    @Mock
    BooksAddNewContract.View mView;

    @Mock
    RealmService realmService;

    @Mock
    TextUtils textUtils;

    BooksAddNewContract.Presenter mPresenter;

    /**
     * Before starting a test
     * Make a new instance of the presenter with mocked dependencies
     * Also set the mocked view
     */
    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        mPresenter = new BooksAddNewPresenter(realmService);
        mPresenter.setView(mView);
    }

    /**
     * When a invalid input for name is given
     * Test that the view's showNameRequired method gets called
     */
    @Test
    public void testAddBookReturnsErrorWhenNameIsInvalid() {
        String name = "";
        String author = "someAuthor";

        mPresenter.addBook(name, author);

        verify(mView).showNameRequiredError();
    }

    /**
     * When a invalid input for author is given
     * Test that the view's showAuthorRequired method gets called
     */
    @Test
    public void testAddBookReturnsErrorWhenAuthorIsInvalid() {
        String name = "someName";
        String author = "";

        mPresenter.addBook(name, author);

        verify(mView).showAuthorRequiredError();
    }

    /**
     * When a valid input for name and author is given
     * Test that the realm service's add book method gets called
     * Test that the view's books added method gets called
     */
    @Test
    public void testAddBookWorksForValidNameAndAuthor() {
        String name = "someName";
        String author = "someAuthor";

        mPresenter.addBook(name, author);

        verify(realmService).addBook(name, author);
        verify(mView, atLeastOnce()).onBookAdded();
    }

}


text:
using System;
using System.Text;
using cAlgo.API;
using cAlgo.API.Internals;
using cAlgo.API.Indicators;

namespace cAlgo.Indicators
{
    [Indicator(IsOverlay = true)]
    public class atr : Indicator
    {
        private AverageTrueRange averageTrueRange;

        public StaticPosition corner_position;

        [Parameter("Show Spread", DefaultValue = 1)]
        public bool ShowSpread { get; set; }

        [Parameter("Show ATR", DefaultValue = 1)]
        public bool ShowATR { get; set; }

        [Parameter("Choose corner", DefaultValue = 1, MinValue = 1, MaxValue = 4)]
        public int corner { get; set; }

        [Parameter("ATR Periods", DefaultValue = 14)]
        public int Periods { get; set; }

        [Parameter("ATR Multiplier", DefaultValue = 1)]
        public double ATRMultiplier { get; set; }

        [Parameter("ATR MA Type", DefaultValue = MovingAverageType.Exponential)]
        public MovingAverageType MAType { get; set; }

        protected override void Initialize()
        {
            averageTrueRange = Indicators.AverageTrueRange(Periods, MAType);
        }

        public override void Calculate(int index)
        {

            switch (corner)
            {
                case 1:
                    corner_position = StaticPosition.TopLeft;
                    break;
                case 2:
                    corner_position = StaticPosition.TopRight;
                    break;
                case 3:
                    corner_position = StaticPosition.BottomLeft;
                    break;
                case 4:
                    corner_position = StaticPosition.BottomRight;
                    break;
            }

            double multiplier;
            if (MarketSeries.SymbolCode == "EURJPY" || MarketSeries.SymbolCode == "USDJPY" || MarketSeries.SymbolCode == "AUDJPY" || MarketSeries.SymbolCode == "CADJPY" || MarketSeries.SymbolCode == "CHFJPY" || MarketSeries.SymbolCode == "GBPJPY" || MarketSeries.SymbolCode == "NOKJPY" || MarketSeries.SymbolCode == "NZDJPY" || MarketSeries.SymbolCode == "SEKJPY" || MarketSeries.SymbolCode == "SGDJPY")
            {
                multiplier = 100;
            }
            else
            {
                multiplier = 10000;
            }

            StringBuilder LineBreak = new StringBuilder();
            LineBreak.AppendLine();

            StringBuilder LineBreak2 = new StringBuilder();
            LineBreak2.AppendLine();
            LineBreak2.AppendLine();

            if (ShowATR == true)
            {
                string ATR = "" + Math.Round(averageTrueRange.Result.LastValue * multiplier * ATRMultiplier, 1);
                ChartObjects.DrawText("show ATR", "ATR: " + ATR + " pips" + LineBreak2, corner_position);
            }

            if (ShowSpread == true)

                if (corner == 1 || corner == 2)
                {
                    string spread = "" + Math.Round(Symbol.Spread * multiplier, 1);
                    ChartObjects.DrawText("show Spread", LineBreak + "Spread: " + spread + " pips", corner_position);
                }

                else
                {
                    string spread = "" + Math.Round(Symbol.Spread * multiplier, 1);
                    ChartObjects.DrawText("show Spread", "Spread: " + spread + " pips", corner_position);
                }

        }

    }
}

//changelog:
//v1.1.2 (2014-12-01):
//deleted some uncalled code
//v1.1.1 (2014-12-01):
//fix choose indicator corner
//v1.1.0 (2014-11-28):
//+ Option to choose indicator corner
//v1.0.0 (2014-11-27):
//initial version


text:
namespace thirdsengine {
	namespace graphics {

#define RENDERER2D_MAX_SPRITES		(10000)
#define RENDERER2D_VERTEX_SIZE		(sizeof(VertexData))
#define RENDERER2D_SPRITE_SIZE		(RENDERER2D_VERTEX_SIZE * 4)
#define RENDERER2D_BUFFER_SIZE		(RENDERER2D_SPRITE_SIZE * RENDERER2D_MAX_SPRITES)
#define RENDERER2D_INDICES_SIZE		(RENDERER2D_MAX_SPRITES * 6)

#define SHADER_VERTEX_INDEX			(0)
#define SHADER_COLOUR_INDEX			(1)

		class Renderable2D;

		class Renderer2D {
		private:
			TransformationStack m_TransformationStack;

		public:
			void push(glm::mat4 matrix, bool override = false) {
				m_TransformationStack.push(matrix, override);
			}

			void pop() {
				m_TransformationStack.pop();
			}

			glm::mat4 getTransformation() { return m_TransformationStack.transformation(); }

			virtual void begin() = 0;
			virtual void submit(Renderable2D* renderable) = 0;
			virtual void end() = 0;
			virtual void flush() = 0;
		};
	}
}


text:
import sys, getopt, os
import io, json
import re
import string
from subprocess import call
from subprocess import Popen, PIPE
import shlex
import glob
from glob import glob
from LOCCount import CountLOC
from includeunique import calcUnique
from keywordcount import getKeywordCount
from functionscount import countFunctions
from operatorsOperands import getOperators

#Handles all the measure gatherer functions and can save values to a list for CSV processing by manager.py
#INPUT: Folder address of the folder to parse for the list of specific measures to calculate. Optional variables: csv determines whether or not the output prints or gathers results for csv formatting, csvList is the list of all data for the current file up until this point
#OUTPUT: Returns a blank list if CSV is set to false, or a populated list of measures in the directory if csv=true

def measureManager(idirectory, csv=False, csvList=[]):
	projectFiles = [os.path.join(dirpath, f)
		for dirpath, dirnames, files in os.walk(idirectory)
		for f in files if (f.endswith('.c')) or (f.endswith('.h'))]

	SLOCTotalCount, csvList = CountLOC(projectFiles, csv, csvList)
	csvList = calcUnique(projectFiles, csv, csvList)
	csvList = getKeywordCount(projectFiles, csv, csvList)
	if len(projectFiles) == 0:
		csvList.append(0)
		csvList.append(0)
		csvList.append(0)
		csvList.append(0)
		csvList.append(0)
		return csvList
	functionsCount, csvList = countFunctions(projectFiles, csv, csvList)
	if (csv == False):
		if (functionsCount != 0):
			print "Average function length = ", (SLOCTotalCount / float(functionsCount))
		else:
			print "Average function length is unknown, functions not found."
	if (csv==True):
		if (functionsCount != 0):
			csvList.append(round(SLOCTotalCount / float(functionsCount),2))
		else:
			csvList.append("Error: No functions found")
	csvList = getOperators(projectFiles, csv, csvList)
	return csvList

def main(argv):

	if (len(argv) <= 1):
		print "Please provide a directory to search for C files."
		sys.exit()
	else:
		#Get command line arguments and put them into list
		options = { 'tool': 'includecheck',
					'dir':''
					}

		# define command line arguments and check if the script call is valid
		opts, args = getopt.getopt(argv,'t:d:h',
			['tool=','directory=', 'help'])

		#Set options and tool being selected
		#Currentl only grabs includecheck.py but can be expanded in the future
		for opt, arg in opts:
			if opt in ('--tool', '-t'):
				options['tool'] = arg
			elif opt in ('directory', '-d'):
				idirectory = arg
				if not (os.path.isdir(idirectory)):
					sys.stderr.write( 'Error. Directory ' + idirectory + ' does not exist.\n' )
					sys.exit()

		if idirectory != '':
			options['dir'] = idirectory
	measureManager(idirectory)

if __name__ == '__main__':
	main(sys.argv[1:])


text:
/**
 * Implementation of a non-empty list (a cons).
 */
public class Cons<E> extends List<E> {
    private E head;
    private List<E> tail;
    /**
     *  Construct a Cons with the give arguments
     *  @param head the head of the constructed list
     *  @param tail the tail of the constructed list
     */
    public Cons (E head, List<E> tail) {
			this.head = head;
			this.tail = tail;
    }
    /**
     * Compute the length of this list.
     * @return The length of this list (always a positive value).
     */
    public int length () { return 1 + tail.length (); }
    /**
     * Tell whether this list contains any object.
     * @return The boolean value true.
     */
    public boolean isEmpty () { return false; }
    /**
     * Compute the head of this list.
     * @return The head of this list.
     */
    public E head () { return head; }
    /**
     * Compute the tail of this list.
     * @return The tail of this list.
     */
    public List<E> tail () { return tail; }
    /**
     * Replace the content of the cons of this list.
     * @param head The new head of the cons.
     * @param tail The new tail of the cons.
     */
    void reset (E head, List<E> tail) {
			this.head = head;
			this.tail = tail;
    }
}


text:
/**
 * @fileoverview Rule to flag references to undeclared variables.
 * @author Mark Macdonald
 */
"use strict";

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

function isImplicitGlobal(variable) {
    return variable.defs.every(function(def) {
        return def.type === "ImplicitGlobalVariable";
    });
}

/**
 * Gets the declared variable, defined in `scope`, that `ref` refers to.
 * @param {Scope} scope
 * @param {Reference} ref
 * @returns {Variable} The variable, or null if ref refers to an undeclared variable.
 */
function getDeclaredGlobalVariable(scope, ref) {
    var declaredGlobal = null;
    scope.variables.some(function(variable) {
        if (variable.name === ref.identifier.name) {
            // If it's an implicit global, it must have a `writeable` field (indicating it was declared)
            if (!isImplicitGlobal(variable) || Object.hasOwnProperty.call(variable, "writeable")) {
                declaredGlobal = variable;
                return true;
            }
        }
        return false;
    });
    return declaredGlobal;
}

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

module.exports = function(context) {

    return {

        "Program": function(/*node*/) {

            var globalScope = context.getScope();

            globalScope.through.forEach(function(ref) {
                var variable = getDeclaredGlobalVariable(globalScope, ref),
                    name = ref.identifier.name;
                if (!variable) {
                    context.report(ref.identifier, "'{{name}}' is not defined.", { name: name });
                } else if (ref.isWrite() && variable.writeable === false) {
                    context.report(ref.identifier, "'{{name}}' is read only.", { name: name });
                }
            });
        }
    };

};


text:
<?php

namespace Laravel\Spark\Services\Auth\TwoFactor;

use Exception;
use GuzzleHttp\Client as HttpClient;
use Laravel\Spark\Contracts\Auth\TwoFactor\Provider;
use Laravel\Spark\Contracts\Auth\TwoFactor\Authenticatable as TwoFactorAuthenticatable;

class Authy implements Provider
{
    /**
     * Determine if the given user has two-factor authentication enabled.
     *
     * @param  \Laravel\Spark\Contracts\Auth\TwoFactor\Authenticatable  $user
     * @return bool
     */
    public function isEnabled(TwoFactorAuthenticatable $user)
    {
        return isset($user->getTwoFactorAuthProviderOptions()['id']);
    }

    /**
     * Register the given user with the provider.
     *
     * @param  \Laravel\Spark\Contracts\Auth\TwoFactor\Authenticatable  $user
     * @return void
     */
    public function register(TwoFactorAuthenticatable $user)
    {
        $key = env('AUTHY_KEY');

        $response = json_decode((new HttpClient)->post('https://api.authy.com/protected/json/users/new?api_key='.$key, [
            'form_params' => [
                'user' => [
                    'email' => $user->getEmailForTwoFactorAuth(),
                    'cellphone' => preg_replace('/[^0-9]/', '', $user->getAuthPhoneNumber()),
                    'country_code' => $user->getAuthCountryCode(),
                ],
            ],
        ])->getBody(), true);

        $user->setTwoFactorAuthProviderOptions([
            'id' => $response['user']['id']
        ]);
    }

    /**
     * Determine if the given token is valid for the given user.
     *
     * @param  \Laravel\Spark\Contracts\Auth\TwoFactor\Authenticatable  $user
     * @param  string  $token
     * @return bool
     */
    public function tokenIsValid(TwoFactorAuthenticatable $user, $token)
    {
        try {
            $key = env('AUTHY_KEY');

            $options = $user->getTwoFactorAuthProviderOptions();

            $response = json_decode((new HttpClient)->get(
                'https://api.authy.com/protected/json/verify/'.$token.'/'.$options['id'].'?force=true&api_key='.$key
            )->getBody(), true);

            return $response['token'] === 'is valid';
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * Delete the given user from the provider.
     *
     * @param  \Laravel\Spark\Contracts\Auth\TwoFactor\Authenticatable  $user
     * @return bool
     */
    public function delete(TwoFactorAuthenticatable $user)
    {
        $key = env('AUTHY_KEY');

        $options = $user->getTwoFactorAuthProviderOptions();

        (new HttpClient)->post(
            'https://api.authy.com/protected/json/users/delete/'.$options['id'].'?api_key='.$key
        );

        $user->setTwoFactorAuthProviderOptions([]);
    }
}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/logging/v2/log_entry.proto

package com.google.logging.v2;

public interface LogEntryOrBuilder extends
    // @@protoc_insertion_point(interface_extends:google.logging.v2.LogEntry)
    com.google.protobuf.MessageOrBuilder {

  /**
   *

   * Required. The resource name of the log to which this log entry belongs:
   *     "projects/[PROJECT_ID]/logs/[LOG_ID]"
   *     "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]"
   *     "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]"
   *     "folders/[FOLDER_ID]/logs/[LOG_ID]"
   * `[LOG_ID]` must be URL-encoded within `log_name`. Example:
   * `"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"`.
   * `[LOG_ID]` must be less than 512 characters long and can only include the
   * following characters: upper and lower case alphanumeric characters,
   * forward-slash, underscore, hyphen, and period.
   * For backward compatibility, if `log_name` begins with a forward-slash, such
   * as `/projects/...`, then the log entry is ingested as usual but the
   * forward-slash is removed. Listing the log entry will not show the leading
   * slash and filtering for a log name with a leading slash will never return
   * any results.
   *

   *
   * string log_name = 12;
   */
  java.lang.String getLogName();
  /**
   *

   * Required. The resource name of the log to which this log entry belongs:
   *     "projects/[PROJECT_ID]/logs/[LOG_ID]"
   *     "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]"
   *     "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]"
   *     "folders/[FOLDER_ID]/logs/[LOG_ID]"
   * `[LOG_ID]` must be URL-encoded within `log_name`. Example:
   * `"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"`.
   * `[LOG_ID]` must be less than 512 characters long and can only include the
   * following characters: upper and lower case alphanumeric characters,
   * forward-slash, underscore, hyphen, and period.
   * For backward compatibility, if `log_name` begins with a forward-slash, such
   * as `/projects/...`, then the log entry is ingested as usual but the
   * forward-slash is removed. Listing the log entry will not show the leading
   * slash and filtering for a log name with a leading slash will never return
   * any results.
   *

   *
   * string log_name = 12;
   */
  com.google.protobuf.ByteString
      getLogNameBytes();

  /**
   *

   * Required. The monitored resource associated with this log entry.
   * Example: a log entry that reports a database error would be
   * associated with the monitored resource designating the particular
   * database that reported the error.
   *

   *
   * .google.api.MonitoredResource resource = 8;
   */
  boolean hasResource();
  /**
   *

   * Required. The monitored resource associated with this log entry.
   * Example: a log entry that reports a database error would be
   * associated with the monitored resource designating the particular
   * database that reported the error.
   *

   *
   * .google.api.MonitoredResource resource = 8;
   */
  com.google.api.MonitoredResource getResource();
  /**
   *

   * Required. The monitored resource associated with this log entry.
   * Example: a log entry that reports a database error would be
   * associated with the monitored resource designating the particular
   * database that reported the error.
   *

   *
   * .google.api.MonitoredResource resource = 8;
   */
  com.google.api.MonitoredResourceOrBuilder getResourceOrBuilder();

  /**
   *

   * The log entry payload, represented as a protocol buffer.  Some
   * Google Cloud Platform services use this field for their log
   * entry payloads.
   *

   *
   * .google.protobuf.Any proto_payload = 2;
   */
  com.google.protobuf.Any getProtoPayload();
  /**
   *

   * The log entry payload, represented as a protocol buffer.  Some
   * Google Cloud Platform services use this field for their log
   * entry payloads.
   *

   *
   * .google.protobuf.Any proto_payload = 2;
   */
  com.google.protobuf.AnyOrBuilder getProtoPayloadOrBuilder();

  /**
   *

   * The log entry payload, represented as a Unicode string (UTF-8).
   *

   *
   * string text_payload = 3;
   */
  java.lang.String getTextPayload();
  /**
   *

   * The log entry payload, represented as a Unicode string (UTF-8).
   *

   *
   * string text_payload = 3;
   */
  com.google.protobuf.ByteString
      getTextPayloadBytes();

  /**
   *

   * The log entry payload, represented as a structure that is
   * expressed as a JSON object.
   *

   *
   * .google.protobuf.Struct json_payload = 6;
   */
  com.google.protobuf.Struct getJsonPayload();
  /**
   *

   * The log entry payload, represented as a structure that is
   * expressed as a JSON object.
   *

   *
   * .google.protobuf.Struct json_payload = 6;
   */
  com.google.protobuf.StructOrBuilder getJsonPayloadOrBuilder();

  /**
   *

   * Optional. The time the event described by the log entry occurred.  If
   * omitted in a new log entry, Stackdriver Logging will insert the time the
   * log entry is received.  Stackdriver Logging might reject log entries whose
   * time stamps are more than a couple of hours in the future. Log entries
   * with time stamps in the past are accepted.
   *

   *
   * .google.protobuf.Timestamp timestamp = 9;
   */
  boolean hasTimestamp();
  /**
   *

   * Optional. The time the event described by the log entry occurred.  If
   * omitted in a new log entry, Stackdriver Logging will insert the time the
   * log entry is received.  Stackdriver Logging might reject log entries whose
   * time stamps are more than a couple of hours in the future. Log entries
   * with time stamps in the past are accepted.
   *

   *
   * .google.protobuf.Timestamp timestamp = 9;
   */
  com.google.protobuf.Timestamp getTimestamp();
  /**
   *

   * Optional. The time the event described by the log entry occurred.  If
   * omitted in a new log entry, Stackdriver Logging will insert the time the
   * log entry is received.  Stackdriver Logging might reject log entries whose
   * time stamps are more than a couple of hours in the future. Log entries
   * with time stamps in the past are accepted.
   *

   *
   * .google.protobuf.Timestamp timestamp = 9;
   */
  com.google.protobuf.TimestampOrBuilder getTimestampOrBuilder();

  /**
   *

   * Output only. The time the log entry was received by Stackdriver Logging.
   *

   *
   * .google.protobuf.Timestamp receive_timestamp = 24;
   */
  boolean hasReceiveTimestamp();
  /**
   *

   * Output only. The time the log entry was received by Stackdriver Logging.
   *

   *
   * .google.protobuf.Timestamp receive_timestamp = 24;
   */
  com.google.protobuf.Timestamp getReceiveTimestamp();
  /**
   *

   * Output only. The time the log entry was received by Stackdriver Logging.
   *

   *
   * .google.protobuf.Timestamp receive_timestamp = 24;
   */
  com.google.protobuf.TimestampOrBuilder getReceiveTimestampOrBuilder();

  /**
   *

   * Optional. The severity of the log entry. The default value is
   * `LogSeverity.DEFAULT`.
   *

   *
   * .google.logging.type.LogSeverity severity = 10;
   */
  int getSeverityValue();
  /**
   *

   * Optional. The severity of the log entry. The default value is
   * `LogSeverity.DEFAULT`.
   *

   *
   * .google.logging.type.LogSeverity severity = 10;
   */
  com.google.logging.type.LogSeverity getSeverity();

  /**
   *

   * Optional. A unique identifier for the log entry. If you provide a value,
   * then Stackdriver Logging considers other log entries in the same project,
   * with the same `timestamp`, and with the same `insert_id` to be duplicates
   * which can be removed.  If omitted in new log entries, then Stackdriver
   * Logging will insert its own unique identifier. The `insert_id` is used
   * to order log entries that have the same `timestamp` value.
   *

   *
   * string insert_id = 4;
   */
  java.lang.String getInsertId();
  /**
   *

   * Optional. A unique identifier for the log entry. If you provide a value,
   * then Stackdriver Logging considers other log entries in the same project,
   * with the same `timestamp`, and with the same `insert_id` to be duplicates
   * which can be removed.  If omitted in new log entries, then Stackdriver
   * Logging will insert its own unique identifier. The `insert_id` is used
   * to order log entries that have the same `timestamp` value.
   *

   *
   * string insert_id = 4;
   */
  com.google.protobuf.ByteString
      getInsertIdBytes();

  /**
   *

   * Optional. Information about the HTTP request associated with this
   * log entry, if applicable.
   *

   *
   * .google.logging.type.HttpRequest http_request = 7;
   */
  boolean hasHttpRequest();
  /**
   *

   * Optional. Information about the HTTP request associated with this
   * log entry, if applicable.
   *

   *
   * .google.logging.type.HttpRequest http_request = 7;
   */
  com.google.logging.type.HttpRequest getHttpRequest();
  /**
   *

   * Optional. Information about the HTTP request associated with this
   * log entry, if applicable.
   *

   *
   * .google.logging.type.HttpRequest http_request = 7;
   */
  com.google.logging.type.HttpRequestOrBuilder getHttpRequestOrBuilder();

  /**
   *

   * Optional. A set of user-defined (key, value) data that provides additional
   * information about the log entry.
   *

   *
   * map<string, string> labels = 11;
   */
  int getLabelsCount();
  /**
   *

   * Optional. A set of user-defined (key, value) data that provides additional
   * information about the log entry.
   *

   *
   * map<string, string> labels = 11;
   */
  boolean containsLabels(
      java.lang.String key);
  /**
   * Use {@link #getLabelsMap()} instead.
   */
  @java.lang.Deprecated
  java.util.Map<java.lang.String, java.lang.String>
  getLabels();
  /**
   *

   * Optional. A set of user-defined (key, value) data that provides additional
   * information about the log entry.
   *

   *
   * map<string, string> labels = 11;
   */
  java.util.Map<java.lang.String, java.lang.String>
  getLabelsMap();
  /**
   *

   * Optional. A set of user-defined (key, value) data that provides additional
   * information about the log entry.
   *

   *
   * map<string, string> labels = 11;
   */

  java.lang.String getLabelsOrDefault(
      java.lang.String key,
      java.lang.String defaultValue);
  /**
   *

   * Optional. A set of user-defined (key, value) data that provides additional
   * information about the log entry.
   *

   *
   * map<string, string> labels = 11;
   */

  java.lang.String getLabelsOrThrow(
      java.lang.String key);

  /**
   *

   * Optional. Information about an operation associated with the log entry, if
   * applicable.
   *

   *
   * .google.logging.v2.LogEntryOperation operation = 15;
   */
  boolean hasOperation();
  /**
   *

   * Optional. Information about an operation associated with the log entry, if
   * applicable.
   *

   *
   * .google.logging.v2.LogEntryOperation operation = 15;
   */
  com.google.logging.v2.LogEntryOperation getOperation();
  /**
   *

   * Optional. Information about an operation associated with the log entry, if
   * applicable.
   *

   *
   * .google.logging.v2.LogEntryOperation operation = 15;
   */
  com.google.logging.v2.LogEntryOperationOrBuilder getOperationOrBuilder();

  /**
   *

   * Optional. Resource name of the trace associated with the log entry, if any.
   * If it contains a relative resource name, the name is assumed to be relative
   * to `//tracing.googleapis.com`. Example:
   * `projects/my-projectid/traces/06796866738c859f2f19b7cfb3214824`
   *

   *
   * string trace = 22;
   */
  java.lang.String getTrace();
  /**
   *

   * Optional. Resource name of the trace associated with the log entry, if any.
   * If it contains a relative resource name, the name is assumed to be relative
   * to `//tracing.googleapis.com`. Example:
   * `projects/my-projectid/traces/06796866738c859f2f19b7cfb3214824`
   *

   *
   * string trace = 22;
   */
  com.google.protobuf.ByteString
      getTraceBytes();

  /**
   *

   * Optional. Source code location information associated with the log entry,
   * if any.
   *

   *
   * .google.logging.v2.LogEntrySourceLocation source_location = 23;
   */
  boolean hasSourceLocation();
  /**
   *

   * Optional. Source code location information associated with the log entry,
   * if any.
   *

   *
   * .google.logging.v2.LogEntrySourceLocation source_location = 23;
   */
  com.google.logging.v2.LogEntrySourceLocation getSourceLocation();
  /**
   *

   * Optional. Source code location information associated with the log entry,
   * if any.
   *

   *
   * .google.logging.v2.LogEntrySourceLocation source_location = 23;
   */
  com.google.logging.v2.LogEntrySourceLocationOrBuilder getSourceLocationOrBuilder();

  public com.google.logging.v2.LogEntry.PayloadCase getPayloadCase();
}


text:
package org.apache.cassandra.cql.jdbc;

import java.nio.ByteBuffer;
import java.util.UUID;

import org.apache.cassandra.utils.UUIDGen;

public class JdbcUUID extends AbstractJdbcUUID
{
    public static final JdbcUUID instance = new JdbcUUID();

    JdbcUUID() {}

    public UUID compose(ByteBuffer bytes)
    {
        bytes = bytes.slice();
        if (bytes.remaining() < 16)
            return new UUID(0, 0);
        return new UUID(bytes.getLong(), bytes.getLong());
    }

    public String getString(ByteBuffer bytes)
    {
        if (bytes.remaining() == 0)
        {
            return "";
        }
        if (bytes.remaining() != 16)
        {
            throw new MarshalException("UUIDs must be exactly 16 bytes");
        }

        return compose(bytes).toString();
    }

    public ByteBuffer decompose(UUID value)
    {
        return ByteBuffer.wrap(UUIDGen.decompose(value));
    }
}


text:
package be.degreyt.libra.comparable;

import java.util.Arrays;

/**
 *
 */
public class Max {

    @SafeVarargs
    public static <T extends Comparable<? super T>> T of(T... elements) {
        T max = null;
        for (T element : elements) {
            if (max == null || max.compareTo(element) < 0) {
                max = element;
            }
        }
        return max;
    }
}


text:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

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

import time
import os
import socket
import struct
import re
import logging
from shadowsocks import common
from shadowsocks import lru_cache
from shadowsocks import eventloop
import server_pool
import Config

class ServerMgr(object):

    def __init__(self):
        self._loop = None
        self._request_id = 1
        self._hosts = {}
        self._hostname_status = {}
        self._hostname_to_cb = {}
        self._cb_to_hostname = {}
        self._last_time = time.time()
        self._sock = None
        self._servers = None

    def add_to_loop(self, loop):
        if self._loop:
            raise Exception('already add to loop')
        self._loop = loop
        # TODO when dns server is IPv6
        self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
                                   socket.SOL_UDP)
        self._sock.bind((Config.MANAGE_BIND_IP, Config.MANAGE_PORT))
        self._sock.setblocking(False)
        loop.add(self._sock, eventloop.POLL_IN, self)

    def _handle_data(self, sock):
        data, addr = sock.recvfrom(128)
        # manage pwd:port:passwd:action
        args = data.split(':')
        if len(args) < 4:
            return
        if args[0] == Config.MANAGE_PASS:
            if args[3] == '0':
                server_pool.ServerPool.get_instance().cb_del_server(args[1])
            elif args[3] == '1':
                server_pool.ServerPool.get_instance(
                ).new_server(args[1], args[2])

    def handle_event(self, sock, fd, event):
        if sock != self._sock:
            return
        if event & eventloop.POLL_ERR:
            logging.error('mgr socket err')
            self._loop.remove(self._sock)
            self._sock.close()
            # TODO when dns server is IPv6
            self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
                                       socket.SOL_UDP)
            self._sock.setblocking(False)
            self._loop.add(self._sock, eventloop.POLL_IN, self)
        else:
            self._handle_data(sock)

    def close(self):
        if self._sock:
            if self._loop:
                self._loop.remove(self._sock)
            self._sock.close()
            self._sock = None

def test():
    pass

if __name__ == '__main__':
    test()


text:
package net.onedaybeard.gradle;

import static com.artemis.meta.ClassMetadata.WeaverType.PACKED;
import static com.artemis.meta.ClassMetadata.WeaverType.POOLED;

import com.artemis.Weaver;
import com.artemis.meta.ClassMetadata;
import org.gradle.api.DefaultTask;
import org.gradle.api.logging.Logger;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.OutputDirectory;
import org.gradle.api.tasks.TaskAction;

import java.io.File;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;

/**
 * Weaving wrapper for gradle.
 *
 * @author Adrian Papari
 * @author Daan van Yperen
 */
public class ArtemisWeavingTask extends DefaultTask {

	/**
	 * Root folder for class files.
	 */
	@OutputDirectory
	private File classesDir;

	/**
	 * If true, will leave field stubs to keep IDE:s happy after transformations.
	 */
	@Input
	private boolean ideFriendlyPacking;

	/**
	 * Enabled weaving of pooled components (more viable on Android than JVM).
	 */
	@Input
	private boolean enablePooledWeaving;

	/**
	 * If false, no weaving will take place (useful for debugging).
	 */
	@Input
	private boolean enableArtemisPlugin;

	@Input
	private boolean optimizeEntitySystems;

	@TaskAction
	public void weave() {
		getLogger().info("Artemis plugin started.");

		if (!enableArtemisPlugin) {
			getLogger().info("Plugin disabled via 'enableArtemisPlugin' set to false.");
			return;
		}

		long start = System.currentTimeMillis();
		//@todo provide gradle alternative.
		//if (context != null && !context.hasDelta(sourceDirectory)) return;

		Logger log = getLogger();
		log.info("Configuration:");
		log.info("\tideFriendlyPacking .............. " + ideFriendlyPacking);
		log.info("\tenablePooledWeaving ............. " + enablePooledWeaving);
		log.info("\toptimizeEntitySystems ........... " + optimizeEntitySystems);
		log.info("\toutputDirectory ................. " + classesDir);

		Weaver.retainFieldsWhenPacking(ideFriendlyPacking);
		Weaver.enablePooledWeaving(enablePooledWeaving);
		Weaver.optimizeEntitySystems(optimizeEntitySystems);

		Weaver weaver = new Weaver(classesDir);
		List<ClassMetadata> processed = weaver.execute();

		log.info(getSummary(processed, start));

		for (ClassMetadata meta : processed) {
			try {
				meta.weaverTask.get();
			} catch (InterruptedException e) {
				throw new RuntimeException(e.getMessage(), e);
			} catch (ExecutionException e) {
				throw new RuntimeException(e.getCause().getMessage(), e.getCause());
			}
		}
	}

	private static String getSummary(List<ClassMetadata> processed, long start) {
		int pooled = 0, packed = 0;
		for (ClassMetadata meta : processed) {
			if (PACKED == meta.annotation) packed++;
			else if (POOLED == meta.annotation) pooled++;
		}

		return String.format("Processed %d PackedComponents and %d PooledComponents in %dms.",
				packed, pooled, (System.currentTimeMillis() - start));
	}

	public boolean isEnableArtemisPlugin() {
		return enableArtemisPlugin;
	}

	public void setEnableArtemisPlugin(boolean enableArtemisPlugin) {
		this.enableArtemisPlugin = enableArtemisPlugin;
	}

	public boolean isIdeFriendlyPacking() {
		return ideFriendlyPacking;
	}

	public void setIdeFriendlyPacking(boolean ideFriendlyPacking) {
		this.ideFriendlyPacking = ideFriendlyPacking;
	}

	public boolean isEnablePooledWeaving() {
		return enablePooledWeaving;
	}

	public void setEnablePooledWeaving(boolean enablePooledWeaving) {
		this.enablePooledWeaving = enablePooledWeaving;
	}

	public boolean isOptimizeEntitySystems() {
		return optimizeEntitySystems;
	}

	public void setOptimizeEntitySystems(boolean optimizeEntitySystems) {
		this.optimizeEntitySystems = optimizeEntitySystems;
	}

	public File getClassesDir() {
		return classesDir;
	}

	public void setClassesDir(File classesDir) {
		this.classesDir = classesDir;
	}
}


text:
import Responsive from 'react-responsive';
import withProps from 'recompose/withProps';
export var Mobile = withProps({
  maxWidth: 767
})(Responsive);
export var Desktop = withProps({
  minWidth: 768
})(Responsive);
//# sourceMappingURL=index.js.map


text:
import os
import Tkinter, Tkconstants, tkFileDialog
from gittalk import upload_youtube

class VideoRecordControlFrame(Tkinter.Frame):
    def __init__(self, root):
        self._root = root
        Tkinter.Frame.__init__(self, self._root)

        # options for buttons
        button_opt = {
            'fill': Tkconstants.BOTH,
            'padx': 5,
            'pady': 5
        }

        Tkinter.Button(self, text='Select Video',
            command=self.ask_open_filename).pack(**button_opt)

    def ask_open_filename(self):
        file_opt = {
            # 'defaultextension': '.mp4',
            'filetypes': [
                ('All files', '.*'),
                ('MPEG 4', '.mp4'),
                ('Windows Media Video', '.wmv'),
                ('Web Media', '.webm'),
                ('Flash Video', '.flv'),
                ('Matroska Video', '.mkv'),
                ('Quick Time Video', '.mov')
            ],
            'initialdir': os.getcwd(),
            'parent': self._root,
            'title': 'Select a video file to upload'
        }
        filename = tkFileDialog.askopenfilename(**file_opt)
        # print 'TODO: upload file: {}'.format(filename)

        url = upload_youtube.upload_youtube(filePath=str(filename), title='put title here', description='line1 description\nline2 description')
        # upload_youtube.upload_youtube(filename)

        # close the window
        self._root.destroy()

        print url


text:
/**
 * RemoteResolution.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
 */

package com.atlassian.jira.rpc.soap.client;

public class RemoteResolution
		extends
			com.atlassian.jira.rpc.soap.client.AbstractRemoteConstant
		implements
			java.io.Serializable {
	public RemoteResolution() {
	}

	public RemoteResolution(java.lang.String id, java.lang.String name,
			java.lang.String description, java.lang.String icon) {
		super(id, name, description, icon);
	}

	private java.lang.Object __equalsCalc = null;
	public synchronized boolean equals(java.lang.Object obj) {
		if (!(obj instanceof RemoteResolution))
			return false;
		RemoteResolution other = (RemoteResolution) obj;
		if (obj == null)
			return false;
		if (this == obj)
			return true;
		if (__equalsCalc != null) {
			return (__equalsCalc == obj);
		}
		__equalsCalc = obj;
		boolean _equals;
		_equals = super.equals(obj);
		__equalsCalc = null;
		return _equals;
	}

	private boolean __hashCodeCalc = false;
	public synchronized int hashCode() {
		if (__hashCodeCalc) {
			return 0;
		}
		__hashCodeCalc = true;
		int _hashCode = super.hashCode();
		__hashCodeCalc = false;
		return _hashCode;
	}

	// Type metadata
	private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(
			RemoteResolution.class, true);

	static {
		typeDesc.setXmlType(new javax.xml.namespace.QName(
				"http://beans.soap.rpc.jira.atlassian.com", "RemoteResolution"));
	}

	/**
	 * Return type metadata object
	 */
	public static org.apache.axis.description.TypeDesc getTypeDesc() {
		return typeDesc;
	}

	/**
	 * Get Custom Serializer
	 */
	public static org.apache.axis.encoding.Serializer getSerializer(
			java.lang.String mechType, java.lang.Class _javaType,
			javax.xml.namespace.QName _xmlType) {
		return new org.apache.axis.encoding.ser.BeanSerializer(_javaType,
				_xmlType, typeDesc);
	}

	/**
	 * Get Custom Deserializer
	 */
	public static org.apache.axis.encoding.Deserializer getDeserializer(
			java.lang.String mechType, java.lang.Class _javaType,
			javax.xml.namespace.QName _xmlType) {
		return new org.apache.axis.encoding.ser.BeanDeserializer(_javaType,
				_xmlType, typeDesc);
	}

}


text:
import { RoundingModes as Modes } from './roundingModes';
declare class bigDecimal {
    private value;
    static RoundingModes: typeof Modes;
    private static validate;
    constructor(number?: (number | string | bigint));
    getValue(): string;
    static getPrettyValue(number: any, digits: any, separator: any): string;
    getPrettyValue(digits: any, separator: any): string;
    static round(number: any, precision?: number, mode?: Modes): string;
    round(precision?: number, mode?: Modes): bigDecimal;
    static floor(number: any): any;
    floor(): bigDecimal;
    static ceil(number: any): any;
    ceil(): bigDecimal;
    static add(number1: any, number2: any): string;
    add(number: bigDecimal): bigDecimal;
    static subtract(number1: any, number2: any): string;
    subtract(number: bigDecimal): bigDecimal;
    static multiply(number1: any, number2: any): string;
    multiply(number: bigDecimal): bigDecimal;
    static divide(number1: any, number2: any, precision: any): string;
    divide(number: bigDecimal, precision: any): bigDecimal;
    static modulus(number1: any, number2: any): string;
    modulus(number: bigDecimal): bigDecimal;
    static compareTo(number1: any, number2: any): 1 | -1 | 0;
    compareTo(number: bigDecimal): 1 | -1 | 0;
    static negate(number: any): string;
    negate(): bigDecimal;
}
export = bigDecimal;


text:
package elastic

// SumAggregation is a single-value metrics aggregation that sums up
// numeric values that are extracted from the aggregated documents.
// These values can be extracted either from specific numeric fields
// in the documents, or be generated by a provided script.
// See: http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-metrics-sum-aggregation.html
type SumAggregation struct {
	field           string
	script          string
	scriptFile      string
	lang            string
	format          string
	params          map[string]interface{}
	subAggregations map[string]Aggregation
}

func NewSumAggregation() SumAggregation {
	a := SumAggregation{
		params:          make(map[string]interface{}),
		subAggregations: make(map[string]Aggregation),
	}
	return a
}

func (a SumAggregation) Field(field string) SumAggregation {
	a.field = field
	return a
}

func (a SumAggregation) Script(script string) SumAggregation {
	a.script = script
	return a
}

func (a SumAggregation) ScriptFile(scriptFile string) SumAggregation {
	a.scriptFile = scriptFile
	return a
}

func (a SumAggregation) Lang(lang string) SumAggregation {
	a.lang = lang
	return a
}

func (a SumAggregation) Format(format string) SumAggregation {
	a.format = format
	return a
}

func (a SumAggregation) Param(name string, value interface{}) SumAggregation {
	a.params[name] = value
	return a
}

func (a SumAggregation) SubAggregation(name string, subAggregation Aggregation) SumAggregation {
	a.subAggregations[name] = subAggregation
	return a
}

func (a SumAggregation) Source() interface{} {
	// Example:
	//	{
	//    "aggs" : {
	//      "intraday_return" : { "sum" : { "field" : "change" } }
	//    }
	//	}
	// This method returns only the { "sum" : { "field" : "change" } } part.

	source := make(map[string]interface{})
	opts := make(map[string]interface{})
	source["sum"] = opts

	// ValuesSourceAggregationBuilder
	if a.field != "" {
		opts["field"] = a.field
	}
	if a.script != "" {
		opts["script"] = a.script
	}
	if a.scriptFile != "" {
		opts["script_file"] = a.scriptFile
	}
	if a.lang != "" {
		opts["lang"] = a.lang
	}
	if a.format != "" {
		opts["format"] = a.format
	}
	if len(a.params) > 0 {
		opts["params"] = a.params
	}

	// AggregationBuilder (SubAggregations)
	if len(a.subAggregations) > 0 {
		aggsMap := make(map[string]interface{})
		source["aggregations"] = aggsMap
		for name, aggregate := range a.subAggregations {
			aggsMap[name] = aggregate.Source()
		}
	}

	return source
}


text:
import webapp2
import uuid

class MainHandler(webapp2.RequestHandler):
    def get(self):
        self.response.headers.add_header("Access-Control-Allow-Origin", "*")
        self.response.write(str(uuid.uuid4()))

app = webapp2.WSGIApplication([
    ('/', MainHandler)
])