text:
package org.elasticsearch.common.io.stream;

import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexFormatTooNewException;
import org.apache.lucene.index.IndexFormatTooOldException;
import org.apache.lucene.store.AlreadyClosedException;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.util.BitUtil;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefBuilder;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.Version;
import org.elasticsearch.common.CharArrays;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.io.stream.Writeable.Writer;
import org.elasticsearch.common.settings.SecureString;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException;
import org.elasticsearch.script.JodaCompatibleZonedDateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.ReadableInstant;

import java.io.EOFException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.AccessDeniedException;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.FileSystemException;
import java.nio.file.FileSystemLoopException;
import java.nio.file.NoSuchFileException;
import java.nio.file.NotDirectoryException;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.IntFunction;

import static java.util.Map.entry;

/**
 * A stream from another node to this node. Technically, it can also be streamed from a byte array but that is mostly for testing.
 *
 * This class's methods are optimized so you can put the methods that read and write a class next to each other and you can scan them
 * visually for differences. That means that most variables should be read and written in a single line so even large objects fit both
 * reading and writing on the screen. It also means that the methods on this class are named very similarly to {@link StreamInput}. Finally
 * it means that the "barrier to entry" for adding new methods to this class is relatively low even though it is a shared class with code
 * everywhere. That being said, this class deals primarily with {@code List}s rather than Arrays. For the most part calls should adapt to
 * lists, either by storing {@code List}s internally or just converting to and from a {@code List} when calling. This comment is repeated
 * on {@link StreamInput}.
 */
public abstract class StreamOutput extends OutputStream {

    private static final Map<TimeUnit, Byte> TIME_UNIT_BYTE_MAP;
    private static final int MAX_NESTED_EXCEPTION_LEVEL = 100;

    static {
        final Map<TimeUnit, Byte> timeUnitByteMap = new EnumMap<>(TimeUnit.class);
        timeUnitByteMap.put(TimeUnit.NANOSECONDS, (byte)0);
        timeUnitByteMap.put(TimeUnit.MICROSECONDS, (byte)1);
        timeUnitByteMap.put(TimeUnit.MILLISECONDS, (byte)2);
        timeUnitByteMap.put(TimeUnit.SECONDS, (byte)3);
        timeUnitByteMap.put(TimeUnit.MINUTES, (byte)4);
        timeUnitByteMap.put(TimeUnit.HOURS, (byte)5);
        timeUnitByteMap.put(TimeUnit.DAYS, (byte)6);

        for (TimeUnit value : TimeUnit.values()) {
            assert timeUnitByteMap.containsKey(value) : value;
        }

        TIME_UNIT_BYTE_MAP = Collections.unmodifiableMap(timeUnitByteMap);
    }

    private Version version = Version.CURRENT;

    /**
     * The version of the node on the other side of this stream.
     */
    public Version getVersion() {
        return this.version;
    }

    /**
     * Set the version of the node on the other side of this stream.
     */
    public void setVersion(Version version) {
        this.version = version;
    }

    public long position() throws IOException {
        throw new UnsupportedOperationException();
    }

    public void seek(long position) throws IOException {
        throw new UnsupportedOperationException();
    }

    /**
     * Writes a single byte.
     */
    public abstract void writeByte(byte b) throws IOException;

    /**
     * Writes an array of bytes.
     *
     * @param b the bytes to write
     */
    public void writeBytes(byte[] b) throws IOException {
        writeBytes(b, 0, b.length);
    }

    /**
     * Writes an array of bytes.
     *
     * @param b      the bytes to write
     * @param length the number of bytes to write
     */
    public void writeBytes(byte[] b, int length) throws IOException {
        writeBytes(b, 0, length);
    }

    /**
     * Writes an array of bytes.
     *
     * @param b      the bytes to write
     * @param offset the offset in the byte array
     * @param length the number of bytes to write
     */
    public abstract void writeBytes(byte[] b, int offset, int length) throws IOException;

    /**
     * Writes an array of bytes.
     *
     * @param b the bytes to write
     */
    public void writeByteArray(byte[] b) throws IOException {
        writeVInt(b.length);
        writeBytes(b, 0, b.length);
    }

    /**
     * Writes the bytes reference, including a length header.
     */
    public void writeBytesReference(@Nullable BytesReference bytes) throws IOException {
        if (bytes == null) {
            writeVInt(0);
            return;
        }
        writeVInt(bytes.length());
        bytes.writeTo(this);
    }

    /**
     * Writes an optional bytes reference including a length header. Use this if you need to differentiate between null and empty bytes
     * references. Use {@link #writeBytesReference(BytesReference)} and {@link StreamInput#readBytesReference()} if you do not.
     */
    public void writeOptionalBytesReference(@Nullable BytesReference bytes) throws IOException {
        if (bytes == null) {
            writeVInt(0);
            return;
        }
        writeVInt(bytes.length() + 1);
        bytes.writeTo(this);
    }

    public void writeBytesRef(BytesRef bytes) throws IOException {
        if (bytes == null) {
            writeVInt(0);
            return;
        }
        writeVInt(bytes.length);
        write(bytes.bytes, bytes.offset, bytes.length);
    }

    private static final ThreadLocal<byte[]> scratch = ThreadLocal.withInitial(() -> new byte[1024]);

    public final void writeShort(short v) throws IOException {
        final byte[] buffer = scratch.get();
        buffer[0] = (byte) (v >> 8);
        buffer[1] = (byte) v;
        writeBytes(buffer, 0, 2);
    }

    /**
     * Writes an int as four bytes.
     */
    public void writeInt(int i) throws IOException {
        final byte[] buffer = scratch.get();
        buffer[0] = (byte) (i >> 24);
        buffer[1] = (byte) (i >> 16);
        buffer[2] = (byte) (i >> 8);
        buffer[3] = (byte) i;
        writeBytes(buffer, 0, 4);
    }

    /**
     * Writes an int in a variable-length format.  Writes between one and
     * five bytes.  Smaller values take fewer bytes.  Negative numbers
     * will always use all 5 bytes and are therefore better serialized
     * using {@link #writeInt}
     */
    public void writeVInt(int i) throws IOException {
        final byte[] buffer = scratch.get();
        int index = 0;
        while ((i & ~0x7F) != 0) {
            buffer[index++] = ((byte) ((i & 0x7f) | 0x80));
            i >>>= 7;
        }
        buffer[index++] = ((byte) i);
        writeBytes(buffer, 0, index);
    }

    /**
     * Writes a long as eight bytes.
     */
    public void writeLong(long i) throws IOException {
        final byte[] buffer = scratch.get();
        buffer[0] = (byte) (i >> 56);
        buffer[1] = (byte) (i >> 48);
        buffer[2] = (byte) (i >> 40);
        buffer[3] = (byte) (i >> 32);
        buffer[4] = (byte) (i >> 24);
        buffer[5] = (byte) (i >> 16);
        buffer[6] = (byte) (i >> 8);
        buffer[7] = (byte) i;
        writeBytes(buffer, 0, 8);
    }

    /**
     * Writes a non-negative long in a variable-length format. Writes between one and ten bytes. Smaller values take fewer bytes. Negative
     * numbers use ten bytes and trip assertions (if running in tests) so prefer {@link #writeLong(long)} or {@link #writeZLong(long)} for
     * negative numbers.
     */
    public void writeVLong(long i) throws IOException {
        if (i < 0) {
            throw new IllegalStateException("Negative longs unsupported, use writeLong or writeZLong for negative numbers [" + i + "]");
        }
        writeVLongNoCheck(i);
    }

    public void writeOptionalVLong(@Nullable  Long l) throws IOException {
        if (l == null) {
            writeBoolean(false);
        } else {
            writeBoolean(true);
            writeVLong(l);
        }
    }

    /**
     * Writes a long in a variable-length format without first checking if it is negative. Package private for testing. Use
     * {@link #writeVLong(long)} instead.
     */
    void writeVLongNoCheck(long i) throws IOException {
        final byte[] buffer = scratch.get();
        int index = 0;
        while ((i & ~0x7F) != 0) {
            buffer[index++] = ((byte) ((i & 0x7f) | 0x80));
            i >>>= 7;
        }
        buffer[index++] = ((byte) i);
        writeBytes(buffer, 0, index);
    }

    /**
     * Writes a long in a variable-length format. Writes between one and ten bytes.
     * Values are remapped by sliding the sign bit into the lsb and then encoded as an unsigned number
     * e.g., 0 -;> 0, -1 -;> 1, 1 -;> 2, ..., Long.MIN_VALUE -;> -1, Long.MAX_VALUE -;> -2
     * Numbers with small absolute value will have a small encoding
     * If the numbers are known to be non-negative, use {@link #writeVLong(long)}
     */
    public void writeZLong(long i) throws IOException {
        final byte[] buffer = scratch.get();
        int index = 0;
        // zig-zag encoding cf. https://developers.google.com/protocol-buffers/docs/encoding?hl=en
        long value = BitUtil.zigZagEncode(i);
        while ((value & 0xFFFFFFFFFFFFFF80L) != 0L) {
            buffer[index++] = (byte) ((value & 0x7F) | 0x80);
            value >>>= 7;
        }
        buffer[index++] = (byte) (value & 0x7F);
        writeBytes(buffer, 0, index);
    }

    public void writeOptionalLong(@Nullable Long l) throws IOException {
        if (l == null) {
            writeBoolean(false);
        } else {
            writeBoolean(true);
            writeLong(l);
        }
    }

    public void writeOptionalString(@Nullable String str) throws IOException {
        if (str == null) {
            writeBoolean(false);
        } else {
            writeBoolean(true);
            writeString(str);
        }
    }

    public void writeOptionalSecureString(@Nullable SecureString secureStr) throws IOException {
        if (secureStr == null) {
            writeOptionalBytesReference(null);
        } else {
            final byte[] secureStrBytes = CharArrays.toUtf8Bytes(secureStr.getChars());
            try {
                writeOptionalBytesReference(new BytesArray(secureStrBytes));
            } finally {
                Arrays.fill(secureStrBytes, (byte) 0);
            }
        }
    }

    /**
     * Writes an optional {@link Integer}.
     */
    public void writeOptionalInt(@Nullable Integer integer) throws IOException {
        if (integer == null) {
            writeBoolean(false);
        } else {
            writeBoolean(true);
            writeInt(integer);
        }
    }

    public void writeOptionalVInt(@Nullable Integer integer) throws IOException {
        if (integer == null) {
            writeBoolean(false);
        } else {
            writeBoolean(true);
            writeVInt(integer);
        }
    }

    public void writeOptionalFloat(@Nullable Float floatValue) throws IOException {
        if (floatValue == null) {
            writeBoolean(false);
        } else {
            writeBoolean(true);
            writeFloat(floatValue);
        }
    }

    public void writeOptionalText(@Nullable Text text) throws IOException {
        if (text == null) {
            writeInt(-1);
        } else {
            writeText(text);
        }
    }

    private final BytesRefBuilder spare = new BytesRefBuilder();

    public void writeText(Text text) throws IOException {
        if (!text.hasBytes()) {
            final String string = text.string();
            spare.copyChars(string);
            writeInt(spare.length());
            write(spare.bytes(), 0, spare.length());
        } else {
            BytesReference bytes = text.bytes();
            writeInt(bytes.length());
            bytes.writeTo(this);
        }
    }

    public void writeString(String str) throws IOException {
        final int charCount = str.length();
        byte[] buffer = scratch.get();
        int offset = 0;
        writeVInt(charCount);
        for (int i = 0; i < charCount; i++) {
            final int c = str.charAt(i);
            if (c <= 0x007F) {
                buffer[offset++] = ((byte) c);
            } else if (c > 0x07FF) {
                buffer[offset++] = ((byte) (0xE0 | c >> 12 & 0x0F));
                buffer[offset++] = ((byte) (0x80 | c >> 6 & 0x3F));
                buffer[offset++] = ((byte) (0x80 | c >> 0 & 0x3F));
            } else {
                buffer[offset++] = ((byte) (0xC0 | c >> 6 & 0x1F));
                buffer[offset++] = ((byte) (0x80 | c >> 0 & 0x3F));
            }
            // make sure any possible char can fit into the buffer in any possible iteration
            // we need at most 3 bytes so we flush the buffer once we have less than 3 bytes
            // left before we start another iteration
            if (offset > buffer.length - 3) {
                writeBytes(buffer, offset);
                offset = 0;
            }
        }
        writeBytes(buffer, offset);
    }

    public void writeSecureString(SecureString secureStr) throws IOException {
        final byte[] secureStrBytes = CharArrays.toUtf8Bytes(secureStr.getChars());
        try {
            writeBytesReference(new BytesArray(secureStrBytes));
        } finally {
            Arrays.fill(secureStrBytes, (byte) 0);
        }
    }

    public void writeFloat(float v) throws IOException {
        writeInt(Float.floatToIntBits(v));
    }

    public void writeDouble(double v) throws IOException {
        writeLong(Double.doubleToLongBits(v));
    }

    public void writeOptionalDouble(@Nullable Double v) throws IOException {
        if (v == null) {
            writeBoolean(false);
        } else {
            writeBoolean(true);
            writeDouble(v);
        }
    }

    private static byte ZERO = 0;
    private static byte ONE = 1;
    private static byte TWO = 2;

    /**
     * Writes a boolean.
     */
    public void writeBoolean(boolean b) throws IOException {
        writeByte(b ? ONE : ZERO);
    }

    public void writeOptionalBoolean(@Nullable Boolean b) throws IOException {
        if (b == null) {
            writeByte(TWO);
        } else {
            writeBoolean(b);
        }
    }

    /**
     * Forces any buffered output to be written.
     */
    @Override
    public abstract void flush() throws IOException;

    /**
     * Closes this stream to further operations.
     */
    @Override
    public abstract void close() throws IOException;

    public abstract void reset() throws IOException;

    @Override
    public void write(int b) throws IOException {
        writeByte((byte) b);
    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        writeBytes(b, off, len);
    }

    public void writeStringArray(String[] array) throws IOException {
        writeVInt(array.length);
        for (String s : array) {
            writeString(s);
        }
    }

    /**
     * Writes a string array, for nullable string, writes it as 0 (empty string).
     */
    public void writeStringArrayNullable(@Nullable String[] array) throws IOException {
        if (array == null) {
            writeVInt(0);
        } else {
            writeVInt(array.length);
            for (String s : array) {
                writeString(s);
            }
        }
    }

    /**
     * Writes a string array, for nullable string, writes false.
     */
    public void writeOptionalStringArray(@Nullable String[] array) throws IOException {
        if (array == null) {
            writeBoolean(false);
        } else {
            writeBoolean(true);
            writeStringArray(array);
        }
    }

    public void writeMap(@Nullable Map<String, Object> map) throws IOException {
        writeGenericValue(map);
    }

    /**
     * write map to stream with consistent order
     * to make sure every map generated bytes order are same.
     * This method is compatible with {@code StreamInput.readMap} and {@code StreamInput.readGenericValue}
     * This method only will handle the map keys order, not maps contained within the map
     */
    public void writeMapWithConsistentOrder(@Nullable Map<String, ? extends Object> map)
        throws IOException {
        if (map == null) {
            writeByte((byte) -1);
            return;
        }
        assert false == (map instanceof LinkedHashMap);
        this.writeByte((byte) 10);
        this.writeVInt(map.size());
        Iterator<? extends Map.Entry<String, ?>> iterator =
            map.entrySet().stream().sorted((a, b) -> a.getKey().compareTo(b.getKey())).iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, ?> next = iterator.next();
            this.writeString(next.getKey());
            this.writeGenericValue(next.getValue());
        }
    }

    /**
     * Write a {@link Map} of {@code K}-type keys to {@code V}-type {@link List}s.
     *

     * Map<String, List<String>> map = ...;
     * out.writeMapOfLists(map, StreamOutput::writeString, StreamOutput::writeString);
     *

     *
     * @param keyWriter The key writer
     * @param valueWriter The value writer
     */
    public final <K, V> void writeMapOfLists(final Map<K, List<V>> map, final Writer<K> keyWriter, final Writer<V> valueWriter)
            throws IOException {
        writeMap(map, keyWriter, (stream, list) -> {
            writeVInt(list.size());
            for (final V value : list) {
                valueWriter.write(this, value);
            }
        });
    }

    /**
     * Write a {@link Map} of {@code K}-type keys to {@code V}-type.
     *

     * Map<String, String> map = ...;
     * out.writeMap(map, StreamOutput::writeString, StreamOutput::writeString);
     *

     *
     * @param keyWriter The key writer
     * @param valueWriter The value writer
     */
    public final <K, V> void writeMap(final Map<K, V> map, final Writer<K> keyWriter, final Writer<V> valueWriter)
        throws IOException {
        writeVInt(map.size());
        for (final Map.Entry<K, V> entry : map.entrySet()) {
            keyWriter.write(this, entry.getKey());
            valueWriter.write(this, entry.getValue());
        }
    }

    /**
     * Writes an {@link Instant} to the stream with nanosecond resolution
     */
    public final void writeInstant(Instant instant) throws IOException {
        writeLong(instant.getEpochSecond());
        writeInt(instant.getNano());
    }

    /**
     * Writes an {@link Instant} to the stream, which could possibly be null
     */
    public final void writeOptionalInstant(@Nullable Instant instant) throws IOException {
        if (instant == null) {
            writeBoolean(false);
        } else {
            writeBoolean(true);
            writeInstant(instant);
        }
    }

    private static final Map<Class<?>, Writer> WRITERS = Map.ofEntries(
            entry(
                    String.class,
                    (o, v) -> {
                        o.writeByte((byte) 0);
                        o.writeString((String) v);
                    }),
            entry(
                    Integer.class,
                    (o, v) -> {
                        o.writeByte((byte) 1);
                        o.writeInt((Integer) v);
                    }),
            entry(
                    Long.class,
                    (o, v) -> {
                        o.writeByte((byte) 2);
                        o.writeLong((Long) v);
                    }),
            entry(
                    Float.class,
                    (o, v) -> {
                        o.writeByte((byte) 3);
                        o.writeFloat((float) v);
                    }),
            entry(
                    Double.class,
                    (o, v) -> {
                        o.writeByte((byte) 4);
                        o.writeDouble((double) v);
                    }),
            entry(
                    Boolean.class,
                    (o, v) -> {
                        o.writeByte((byte) 5);
                        o.writeBoolean((boolean) v);
                    }),
            entry(
                    byte[].class,
                    (o, v) -> {
                        o.writeByte((byte) 6);
                        final byte[] bytes = (byte[]) v;
                        o.writeVInt(bytes.length);
                        o.writeBytes(bytes);
                    }),
            entry(
                    List.class,
                    (o, v) -> {
                        o.writeByte((byte) 7);
                        final List list = (List) v;
                        o.writeVInt(list.size());
                        for (Object item : list) {
                            o.writeGenericValue(item);
                        }
                    }),
            entry(
                    Object[].class,
                    (o, v) -> {
                        o.writeByte((byte) 8);
                        final Object[] list = (Object[]) v;
                        o.writeVInt(list.length);
                        for (Object item : list) {
                            o.writeGenericValue(item);
                        }
                    }),
            entry(
                    Map.class,
                    (o, v) -> {
                        if (v instanceof LinkedHashMap) {
                            o.writeByte((byte) 9);
                        } else {
                            o.writeByte((byte) 10);
                        }
                        @SuppressWarnings("unchecked") final Map<String, Object> map = (Map<String, Object>) v;
                        o.writeVInt(map.size());
                        for (Map.Entry<String, Object> entry : map.entrySet()) {
                            o.writeString(entry.getKey());
                            o.writeGenericValue(entry.getValue());
                        }
                    }),
            entry(
                    Byte.class,
                    (o, v) -> {
                        o.writeByte((byte) 11);
                        o.writeByte((Byte) v);
                    }),
            entry(
                    Date.class,
                    (o, v) -> {
                        o.writeByte((byte) 12);
                        o.writeLong(((Date) v).getTime());
                    }),
            entry(
                    ReadableInstant.class,
                    (o, v) -> {
                        o.writeByte((byte) 13);
                        final ReadableInstant instant = (ReadableInstant) v;
                        o.writeString(instant.getZone().getID());
                        o.writeLong(instant.getMillis());
                    }),
            entry(
                    BytesReference.class,
                    (o, v) -> {
                        o.writeByte((byte) 14);
                        o.writeBytesReference((BytesReference) v);
                    }),
            entry(
                    Text.class,
                    (o, v) -> {
                        o.writeByte((byte) 15);
                        o.writeText((Text) v);
                    }),
            entry(
                    Short.class,
                    (o, v) -> {
                        o.writeByte((byte) 16);
                        o.writeShort((Short) v);
                    }),
            entry(
                    int[].class,
                    (o, v) -> {
                        o.writeByte((byte) 17);
                        o.writeIntArray((int[]) v);
                    }),
            entry(
                    long[].class,
                    (o, v) -> {
                        o.writeByte((byte) 18);
                        o.writeLongArray((long[]) v);
                    }),
            entry(
                    float[].class,
                    (o, v) -> {
                        o.writeByte((byte) 19);
                        o.writeFloatArray((float[]) v);
                    }),
            entry(
                    double[].class,
                    (o, v) -> {
                        o.writeByte((byte) 20);
                        o.writeDoubleArray((double[]) v);
                    }),
            entry(
                    BytesRef.class,
                    (o, v) -> {
                        o.writeByte((byte) 21);
                        o.writeBytesRef((BytesRef) v);
                    }),
            entry(
                    GeoPoint.class,
                    (o, v) -> {
                        o.writeByte((byte) 22);
                        o.writeGeoPoint((GeoPoint) v);
                    }),
            entry(
                    ZonedDateTime.class,
                    (o, v) -> {
                        o.writeByte((byte) 23);
                        final ZonedDateTime zonedDateTime = (ZonedDateTime) v;
                        o.writeString(zonedDateTime.getZone().getId());
                        o.writeLong(zonedDateTime.toInstant().toEpochMilli());
                    }),
            entry(
                    JodaCompatibleZonedDateTime.class,
                    (o, v) -> {
                        // write the joda compatibility datetime as joda datetime
                        o.writeByte((byte) 13);
                        final JodaCompatibleZonedDateTime zonedDateTime = (JodaCompatibleZonedDateTime) v;
                        String zoneId = zonedDateTime.getZonedDateTime().getZone().getId();
                        // joda does not understand "Z" for utc, so we must special case
                        o.writeString(zoneId.equals("Z") ? DateTimeZone.UTC.getID() : zoneId);
                        o.writeLong(zonedDateTime.toInstant().toEpochMilli());
                    }),
            entry(
                    Set.class,
                    (o, v) -> {
                        if (v instanceof LinkedHashSet) {
                            o.writeByte((byte) 24);
                        } else {
                            o.writeByte((byte) 25);
                        }
                        o.writeCollection((Set<?>) v, StreamOutput::writeGenericValue);
                    }
            ));

    /**
     * Notice: when serialization a map, the stream out map with the stream in map maybe have the
     * different key-value orders, they will maybe have different stream order.
     * If want to keep stream out map and stream in map have the same stream order when stream,
     * can use {@code writeMapWithConsistentOrder}
     */
    public void writeGenericValue(@Nullable Object value) throws IOException {
        if (value == null) {
            writeByte((byte) -1);
            return;
        }
        final Class type;
        if (value instanceof List) {
            type = List.class;
        } else if (value instanceof Object[]) {
            type = Object[].class;
        } else if (value instanceof Map) {
            type = Map.class;
        } else if (value instanceof Set) {
            type = Set.class;
        } else if (value instanceof ReadableInstant) {
            type = ReadableInstant.class;
        } else if (value instanceof BytesReference) {
            type = BytesReference.class;
        } else {
            type = value.getClass();
        }
        final Writer writer = WRITERS.get(type);
        if (writer != null) {
            writer.write(this, value);
        } else {
            throw new IllegalArgumentException("can not write type [" + type + "]");
        }
    }

    public void writeIntArray(int[] values) throws IOException {
        writeVInt(values.length);
        for (int value : values) {
            writeInt(value);
        }
    }

    public void writeVIntArray(int[] values) throws IOException {
        writeVInt(values.length);
        for (int value : values) {
            writeVInt(value);
        }
    }

    public void writeLongArray(long[] values) throws IOException {
        writeVInt(values.length);
        for (long value : values) {
            writeLong(value);
        }
    }

    public void writeVLongArray(long[] values) throws IOException {
        writeVInt(values.length);
        for (long value : values) {
            writeVLong(value);
        }
    }

    public void writeFloatArray(float[] values) throws IOException {
        writeVInt(values.length);
        for (float value : values) {
            writeFloat(value);
        }
    }

    public void writeDoubleArray(double[] values) throws IOException {
        writeVInt(values.length);
        for (double value : values) {
            writeDouble(value);
        }
    }

    /**
     * Writes the specified array to the stream using the specified {@link Writer} for each element in the array. This method can be seen as
     * writer version of {@link StreamInput#readArray(Writeable.Reader, IntFunction)}. The length of array encoded as a variable-length
     * integer is first written to the stream, and then the elements of the array are written to the stream.
     *
     * @param writer the writer used to write individual elements
     * @param array  the array
     * @param <T>    the type of the elements of the array
     * @throws IOException if an I/O exception occurs while writing the array
     */
    public <T> void writeArray(final Writer<T> writer, final T[] array) throws IOException {
        writeVInt(array.length);
        for (T value : array) {
            writer.write(this, value);
        }
    }

    /**
     * Same as {@link #writeArray(Writer, Object[])} but the provided array may be null. An additional boolean value is
     * serialized to indicate whether the array was null or not.
     */
    public <T> void writeOptionalArray(final Writer<T> writer, final @Nullable T[] array) throws IOException {
        if (array == null) {
            writeBoolean(false);
        } else {
            writeBoolean(true);
            writeArray(writer, array);
        }
    }

    /**
     * Writes the specified array of {@link Writeable}s. This method can be seen as
     * writer version of {@link StreamInput#readArray(Writeable.Reader, IntFunction)}. The length of array encoded as a variable-length
     * integer is first written to the stream, and then the elements of the array are written to the stream.
     */
    public <T extends Writeable> void writeArray(T[] array) throws IOException {
        writeArray((out, value) -> value.writeTo(out), array);
    }

    /**
     * Same as {@link #writeArray(Writeable[])} but the provided array may be null. An additional boolean value is
     * serialized to indicate whether the array was null or not.
     */
    public <T extends Writeable> void writeOptionalArray(@Nullable T[] array) throws IOException {
        writeOptionalArray((out, value) -> value.writeTo(out), array);
    }

    public void writeOptionalWriteable(@Nullable Writeable writeable) throws IOException {
        if (writeable != null) {
            writeBoolean(true);
            writeable.writeTo(this);
        } else {
            writeBoolean(false);
        }
    }

    public void writeException(Throwable throwable) throws IOException {
        writeException(throwable, throwable, 0);
    }

    private void writeException(Throwable rootException, Throwable throwable, int nestedLevel) throws IOException {
        if (throwable == null) {
            writeBoolean(false);
        } else if (nestedLevel > MAX_NESTED_EXCEPTION_LEVEL) {
            assert failOnTooManyNestedExceptions(rootException);
            writeException(new IllegalStateException("too many nested exceptions"));
        } else {
            writeBoolean(true);
            boolean writeCause = true;
            boolean writeMessage = true;
            if (throwable instanceof CorruptIndexException) {
                writeVInt(1);
                writeOptionalString(((CorruptIndexException)throwable).getOriginalMessage());
                writeOptionalString(((CorruptIndexException)throwable).getResourceDescription());
                writeMessage = false;
            } else if (throwable instanceof IndexFormatTooNewException) {
                writeVInt(2);
                writeOptionalString(((IndexFormatTooNewException)throwable).getResourceDescription());
                writeInt(((IndexFormatTooNewException)throwable).getVersion());
                writeInt(((IndexFormatTooNewException)throwable).getMinVersion());
                writeInt(((IndexFormatTooNewException)throwable).getMaxVersion());
                writeMessage = false;
                writeCause = false;
            } else if (throwable instanceof IndexFormatTooOldException) {
                writeVInt(3);
                IndexFormatTooOldException t = (IndexFormatTooOldException) throwable;
                writeOptionalString(t.getResourceDescription());
                if (t.getVersion() == null) {
                    writeBoolean(false);
                    writeOptionalString(t.getReason());
                } else {
                    writeBoolean(true);
                    writeInt(t.getVersion());
                    writeInt(t.getMinVersion());
                    writeInt(t.getMaxVersion());
                }
                writeMessage = false;
                writeCause = false;
            } else if (throwable instanceof NullPointerException) {
                writeVInt(4);
                writeCause = false;
            } else if (throwable instanceof NumberFormatException) {
                writeVInt(5);
                writeCause = false;
            } else if (throwable instanceof IllegalArgumentException) {
                writeVInt(6);
            } else if (throwable instanceof AlreadyClosedException) {
                writeVInt(7);
            } else if (throwable instanceof EOFException) {
                writeVInt(8);
                writeCause = false;
            } else if (throwable instanceof SecurityException) {
                writeVInt(9);
            } else if (throwable instanceof StringIndexOutOfBoundsException) {
                writeVInt(10);
                writeCause = false;
            } else if (throwable instanceof ArrayIndexOutOfBoundsException) {
                writeVInt(11);
                writeCause = false;
            } else if (throwable instanceof FileNotFoundException) {
                writeVInt(12);
                writeCause = false;
            } else if (throwable instanceof FileSystemException) {
                writeVInt(13);
                if (throwable instanceof NoSuchFileException) {
                    writeVInt(0);
                } else if (throwable instanceof NotDirectoryException) {
                    writeVInt(1);
                } else if (throwable instanceof DirectoryNotEmptyException) {
                    writeVInt(2);
                } else if (throwable instanceof AtomicMoveNotSupportedException) {
                    writeVInt(3);
                } else if (throwable instanceof FileAlreadyExistsException) {
                    writeVInt(4);
                } else if (throwable instanceof AccessDeniedException) {
                    writeVInt(5);
                } else if (throwable instanceof FileSystemLoopException) {
                    writeVInt(6);
                } else {
                    writeVInt(7);
                }
                writeOptionalString(((FileSystemException) throwable).getFile());
                writeOptionalString(((FileSystemException) throwable).getOtherFile());
                writeOptionalString(((FileSystemException) throwable).getReason());
                writeCause = false;
            } else if (throwable instanceof IllegalStateException) {
                writeVInt(14);
            } else if (throwable instanceof LockObtainFailedException) {
                writeVInt(15);
            } else if (throwable instanceof InterruptedException) {
                writeVInt(16);
                writeCause = false;
            } else if (throwable instanceof IOException) {
                writeVInt(17);
            } else if (throwable instanceof EsRejectedExecutionException) {
                writeVInt(18);
                writeBoolean(((EsRejectedExecutionException) throwable).isExecutorShutdown());
                writeCause = false;
            } else {
                final ElasticsearchException ex;
                if (throwable instanceof ElasticsearchException && ElasticsearchException.isRegistered(throwable.getClass(), version)) {
                    ex = (ElasticsearchException) throwable;
                } else {
                    ex = new NotSerializableExceptionWrapper(throwable);
                }
                writeVInt(0);
                writeVInt(ElasticsearchException.getId(ex.getClass()));
                ex.writeTo(this);
                return;
            }
            if (writeMessage) {
                writeOptionalString(throwable.getMessage());
            }
            if (writeCause) {
                writeException(rootException, throwable.getCause(), nestedLevel + 1);
            }
            ElasticsearchException.writeStackTraces(throwable, this, (o, t) -> o.writeException(rootException, t, nestedLevel + 1));
        }
    }

    boolean failOnTooManyNestedExceptions(Throwable throwable) {
        throw new AssertionError("too many nested exceptions", throwable);
    }

    /**
     * Writes a {@link NamedWriteable} to the current stream, by first writing its name and then the object itself
     */
    public void writeNamedWriteable(NamedWriteable namedWriteable) throws IOException {
        writeString(namedWriteable.getWriteableName());
        namedWriteable.writeTo(this);
    }

    /**
     * Write an optional {@link NamedWriteable} to the stream.
     */
    public void writeOptionalNamedWriteable(@Nullable NamedWriteable namedWriteable) throws IOException {
        if (namedWriteable == null) {
            writeBoolean(false);
        } else {
            writeBoolean(true);
            writeNamedWriteable(namedWriteable);
        }
    }

    /**
     * Writes the given {@link GeoPoint} to the stream
     */
    public void writeGeoPoint(GeoPoint geoPoint) throws IOException {
        writeDouble(geoPoint.lat());
        writeDouble(geoPoint.lon());
    }

    /**
     * Write a {@linkplain DateTimeZone} to the stream.
     */
    public void writeTimeZone(DateTimeZone timeZone) throws IOException {
        writeString(timeZone.getID());
    }

    /**
     * Write a {@linkplain ZoneId} to the stream.
     */
    public void writeZoneId(ZoneId timeZone) throws IOException {
        writeString(timeZone.getId());
    }

    /**
     * Write an optional {@linkplain DateTimeZone} to the stream.
     */
    public void writeOptionalTimeZone(@Nullable DateTimeZone timeZone) throws IOException {
        if (timeZone == null) {
            writeBoolean(false);
        } else {
            writeBoolean(true);
            writeTimeZone(timeZone);
        }
    }

    /**
     * Write an optional {@linkplain ZoneId} to the stream.
     */
    public void writeOptionalZoneId(@Nullable ZoneId timeZone) throws IOException {
        if (timeZone == null) {
            writeBoolean(false);
        } else {
            writeBoolean(true);
            writeZoneId(timeZone);
        }
    }

    /**
     * Writes a collection to this stream. The corresponding collection can be read from a stream input using
     * {@link StreamInput#readList(Writeable.Reader)}.
     *
     * @param collection the collection to write to this stream
     * @throws IOException if an I/O exception occurs writing the collection
     */
    public void writeCollection(final Collection<? extends Writeable> collection) throws IOException {
        writeCollection(collection, (o, v) -> v.writeTo(o));
    }

    /**
     * Writes a list of {@link Writeable} objects
     */
    public void writeList(List<? extends Writeable> list) throws IOException {
        writeCollection(list);
    }

    /**
     * Writes a collection of objects via a {@link Writer}.
     *
     * @param collection the collection of objects
     * @throws IOException if an I/O exception occurs writing the collection
     */
    public <T> void writeCollection(final Collection<T> collection, final Writer<T> writer) throws IOException {
        writeVInt(collection.size());
        for (final T val: collection) {
            writer.write(this, val);
        }
    }

    /**
     * Writes a collection of a strings. The corresponding collection can be read from a stream input using
     * {@link StreamInput#readList(Writeable.Reader)}.
     *
     * @param collection the collection of strings
     * @throws IOException if an I/O exception occurs writing the collection
     */
    public void writeStringCollection(final Collection<String> collection) throws IOException {
        writeCollection(collection, StreamOutput::writeString);
    }

    /**
     * Writes an optional collection of a strings. The corresponding collection can be read from a stream input using
     * {@link StreamInput#readList(Writeable.Reader)}.
     *
     * @param collection the collection of strings
     * @throws IOException if an I/O exception occurs writing the collection
     */
    public void writeOptionalStringCollection(final Collection<String> collection) throws IOException {
        if (collection != null) {
            writeBoolean(true);
            writeCollection(collection, StreamOutput::writeString);
        } else {
            writeBoolean(false);
        }
    }

    /**
     * Writes a list of {@link NamedWriteable} objects.
     */
    public void writeNamedWriteableList(List<? extends NamedWriteable> list) throws IOException {
        writeVInt(list.size());
        for (NamedWriteable obj: list) {
            writeNamedWriteable(obj);
        }
    }

    /**
     * Writes an enum with type E based on its ordinal value
     */
    public <E extends Enum<E>> void writeEnum(E enumValue) throws IOException {
        writeVInt(enumValue.ordinal());
    }

    /**
     * Writes an EnumSet with type E that by serialized it based on it's ordinal value
     */
    public <E extends Enum<E>> void writeEnumSet(EnumSet<E> enumSet) throws IOException {
        writeVInt(enumSet.size());
        for (E e : enumSet) {
            writeEnum(e);
        }
    }

    /**
     * Write a {@link TimeValue} to the stream
     */
    public void writeTimeValue(TimeValue timeValue) throws IOException {
        writeZLong(timeValue.duration());
        writeByte(TIME_UNIT_BYTE_MAP.get(timeValue.timeUnit()));
    }

    /**
     * Write an optional {@link TimeValue} to the stream.
     */
    public void writeOptionalTimeValue(@Nullable TimeValue timeValue) throws IOException {
        if (timeValue == null) {
            writeBoolean(false);
        } else {
            writeBoolean(true);
            writeTimeValue(timeValue);
        }
    }

}


text:
package com.graphhopper.routing.util.spatialrules;

import java.util.Collections;
import java.util.List;

import org.locationtech.jts.geom.Envelope;

/**
 * SpatialRuleLookup defines a container that stores SpatialRules and can lookup
 * applicable rules depending on the location.
 *
 * @author Robin Boldt
 */
public interface SpatialRuleLookup {

    /**
     * Return applicable rules for this location.
     *

     * If multiple rules with the same priority overlap for a location, the
     * implementation can decide which of them to return and in which order.
     *

     * If the requested location is outside of the supported bounds or no
     * SpatialRule is registered at this location {@link SpatialRuleSet#EMPTY}
     * is returned.
     */
    SpatialRuleSet lookupRules(double lat, double lon);

    /**
     * @return the rules which are active for {@link #getBounds()}
     */
    List<SpatialRule> getRules();

    /**
     * @return the bounds of the SpatialRuleLookup
     */
    Envelope getBounds();

    SpatialRuleLookup EMPTY = new SpatialRuleLookup() {
        @Override
        public SpatialRuleSet lookupRules(double lat, double lon) {
            return SpatialRuleSet.EMPTY;
        }

        @Override
        public List<SpatialRule> getRules() {
            return Collections.emptyList();
        }

        @Override
        public Envelope getBounds() {
            return new Envelope(-180d, 180d, -90d, 90d);
        }
    };
}

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Created by PhpStorm.
 * User: wesley
 * Date: 10/1/14
 * Time: 9:12 PM
 */

namespace CodeDemo\Model;

interface DataInterface
{

    public function getData();

}


text:
[![Build Status](https://travis-ci.org/ngTrumbitta/ngtrumbitta-services-selection-cache.svg?branch=master)](https://travis-ci.org/ngTrumbitta/ngtrumbitta-services-selection-cache)

This service scratches one very specific itch I once had for a project I was working on: select multiple items from a list, then do something with each one of them, or all together as a whole.

In other words:

1. Create a cache to store your selected items
2. On click, add an item to the selection cache
3. Use your cache of selected items however you like
4. Create more caches, and use them side by side with the other ones

## Install

```sh
bower install ngtrumbitta-services-selection-cache
```

## Use

```html
<script src="//code.angularjs.org/1.4.5/angular.min.js"></script>
<script src="bowser_components/ngtrumbitta-services-selection-cache/src/selection-cache.service.js"></script>
```

```javascript
angular.module('app.controllers.mycontroller', [
  'ngtrumbitta.services.selectioncache'
  ])
  .controller('myController', function(selectionCacheService, $scope) {
    'use strict';
    var vm = this;

    // try to destroy `myCache` before creating it, just in case
    selectionCacheService.destroy('myCache');
    // create a new named selection cache
    vm.selectionCacheHandler = selectionCacheService.init('myCache');

    // select an unselected item, or deselect an already selected one
    vm.toggleSelected = function(selectedItem) {
      var updatedSelectionCache = selectionCacheService.add(vm.selectionCacheHandler, selectedItem);

      if (angular.isUndefined(updatedSelectionCache)) {
        // selectionCacheService.add returns 'undefined' if the selectedItem
        // was already cached.
        // Given our sample method is **toggle**Selected, this means that we
        // want to deselect that item.
        selectionCacheService.remove(vm.selectionCacheHandler, selectedItem);
      }

      // delegate the actual use of the selection cache to someone else
      $scope.$emit('heyall.dosomething.withthis', selectionCacheService.getCache(vm.selectionCacheHandler));
    };

  });

```

## License

MIT – See [license file](LICENSE)


text:
package cmd

import (
	"github.com/micro/micro/v3/service/auth"
	authSrv "github.com/micro/micro/v3/service/auth/client"
	"github.com/micro/micro/v3/service/broker"
	brokerSrv "github.com/micro/micro/v3/service/broker/client"
	"github.com/micro/micro/v3/service/client"
	grpcCli "github.com/micro/micro/v3/service/client/grpc"
	"github.com/micro/micro/v3/service/events"
	eventsSrv "github.com/micro/micro/v3/service/events/client"
	"github.com/micro/micro/v3/service/metrics"
	noopMet "github.com/micro/micro/v3/service/metrics/noop"
	"github.com/micro/micro/v3/service/network"
	mucpNet "github.com/micro/micro/v3/service/network/mucp"
	"github.com/micro/micro/v3/service/registry"
	registrySrv "github.com/micro/micro/v3/service/registry/client"
	"github.com/micro/micro/v3/service/router"
	routerSrv "github.com/micro/micro/v3/service/router/client"
	"github.com/micro/micro/v3/service/runtime"
	runtimeSrv "github.com/micro/micro/v3/service/runtime/client"
	"github.com/micro/micro/v3/service/server"
	grpcSvr "github.com/micro/micro/v3/service/server/grpc"
	"github.com/micro/micro/v3/service/store"
	storeSrv "github.com/micro/micro/v3/service/store/client"
)

// setupDefaults sets the default auth, broker etc implementations incase they arent configured by
// a profile. The default implementations are always the RPC implementations.
func setupDefaults() {
	client.DefaultClient = grpcCli.NewClient()
	server.DefaultServer = grpcSvr.NewServer()
	network.DefaultNetwork = mucpNet.NewNetwork()
	metrics.DefaultMetricsReporter = noopMet.New()

	// setup rpc implementations after the client is configured
	auth.DefaultAuth = authSrv.NewAuth()
	broker.DefaultBroker = brokerSrv.NewBroker()
	events.DefaultStream = eventsSrv.NewStream()
	events.DefaultStore = eventsSrv.NewStore()
	registry.DefaultRegistry = registrySrv.NewRegistry()
	router.DefaultRouter = routerSrv.NewRouter()
	store.DefaultStore = storeSrv.NewStore()
	store.DefaultBlobStore = storeSrv.NewBlobStore()
	runtime.DefaultRuntime = runtimeSrv.NewRuntime()
}


text: © {{ site.time | date: '%Y' }} {{ site.owner.name }}. Powered by Jekyll using the Neo-HPSTR Theme.


text:
/**
 *
 *  This Page Directive uses RequireJS to `define` a AngularJS constructor function
 *  with its dependencies.
 *
 *  @author  zulfeekar cheriyampurath
 *  @date    july, 2014
 *
 */
(function (define) {
    "use strict";
    /**
     * Register the component class with RequireJS
     */
    define([], function () {

        return function ($window,$timeout) {

            return {
                restrict: 'EA',
                link: function ($scope) {

                    var _tout;

                    function onTimeOut(){

                        if(_tout)
                        {
                            $window.clearTimeout(_tout);
                            _tout = null;
                        }

                        $scope.build();
                    };

                    if ($scope.$last){

                        _tout = $timeout(onTimeOut,200);
                    }
                }
            }
        }

    });

}(define));


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using Xunit;

namespace Microsoft.VisualBasic.CompilerServices.Tests
{
    public class LateBindingTests
    {
        [Theory]
        [MemberData(nameof(LateCall_TestData))]
        public void LateCall(object obj, Type objType, string name, object[] args, string[] paramNames, bool[] copyBack, Func<object, object> getResult, object expected)
        {
            LateBinding.LateCall(obj, objType, name, args, paramNames, copyBack);
            Assert.Equal(expected, getResult(obj));
        }

        [Theory]
        [MemberData(nameof(LateGet_TestData))]
        public void LateGet(object obj, Type objType, string name, object[] args, string[] paramNames, bool[] copyBack, object expected)
        {
            Assert.Equal(expected, LateBinding.LateGet(obj, objType, name, args, paramNames, copyBack));
        }

        [Theory]
        [MemberData(nameof(LateSet_TestData))]
        public void LateSet(object obj, Type objType, string name, object[] args, string[] paramNames, Func<object, object> getResult, object expected)
        {
            LateBinding.LateSet(obj, objType, name, args, paramNames);
            Assert.Equal(expected, getResult(obj));
        }

        [Theory]
        [MemberData(nameof(LateSetComplex_TestData))]
        public void LateSetComplex(object obj, Type objType, string name, object[] args, string[] paramNames, bool missing, bool valueType)
        {
            if (missing)
            {
                Assert.Throws<MissingMemberException>(() => LateBinding.LateSetComplex(obj, objType, name, args, paramNames, false, false));
                Assert.Throws<MissingMemberException>(() => LateBinding.LateSetComplex(obj, objType, name, args, paramNames, false, true));
                LateBinding.LateSetComplex(obj, objType, name, args, paramNames, true, false);
                LateBinding.LateSetComplex(obj, objType, name, args, paramNames, true, true);
            }
            else if (valueType)
            {
                LateBinding.LateSetComplex(obj, objType, name, args, paramNames, false, false);
                Assert.Throws<Exception>(() => LateBinding.LateSetComplex(obj, objType, name, args, paramNames, false, true));
                LateBinding.LateSetComplex(obj, objType, name, args, paramNames, true, false);
                Assert.Throws<Exception>(() => LateBinding.LateSetComplex(obj, objType, name, args, paramNames, true, true));
            }
            else
            {
                LateBinding.LateSetComplex(obj, objType, name, args, paramNames, false, false);
                LateBinding.LateSetComplex(obj, objType, name, args, paramNames, false, true);
                LateBinding.LateSetComplex(obj, objType, name, args, paramNames, true, false);
                LateBinding.LateSetComplex(obj, objType, name, args, paramNames, true, true);
            }
        }

        [Theory]
        [MemberData(nameof(LateIndexGet_TestData))]
        public void LateIndexGet(object obj, object[] args, string[] paramNames, object expected)
        {
            Assert.Equal(expected, LateBinding.LateIndexGet(obj, args, paramNames));
        }

        [Theory]
        [MemberData(nameof(LateIndexSet_TestData))]
        public void LateIndexSet(object obj, object[] args, string[] paramNames, Func<object, object> getResult, object expected)
        {
            LateBinding.LateIndexSet(obj, args, paramNames);
            Assert.Equal(expected, getResult(obj));
        }

        [Theory]
        [MemberData(nameof(LateIndexSet_MissingMember_TestData))]
        public void LateIndexSet_MissingMember(object obj, object[] args, string[] paramNames)
        {
            Assert.Throws<MissingMemberException>(() => LateBinding.LateIndexSet(obj, args, paramNames));
        }

        [Theory]
        [MemberData(nameof(LateIndexSetComplex_TestData))]
        public void LateIndexSetComplex(object obj, object[] args, string[] paramNames, bool missing, bool valueType)
        {
            if (missing)
            {
                Assert.Throws<MissingMemberException>(() => LateBinding.LateIndexSetComplex(obj, args, paramNames, false, false));
                Assert.Throws<MissingMemberException>(() => LateBinding.LateIndexSetComplex(obj, args, paramNames, false, true));
                LateBinding.LateIndexSetComplex(obj, args, paramNames, true, false);
                LateBinding.LateIndexSetComplex(obj, args, paramNames, true, true);
            }
            else if (valueType)
            {
                LateBinding.LateIndexSetComplex(obj, args, paramNames, false, false);
                Assert.Throws<Exception>(() => LateBinding.LateIndexSetComplex(obj, args, paramNames, false, true));
                LateBinding.LateIndexSetComplex(obj, args, paramNames, true, false);
                Assert.Throws<Exception>(() => LateBinding.LateIndexSetComplex(obj, args, paramNames, true, true));
            }
            else
            {
                LateBinding.LateIndexSetComplex(obj, args, paramNames, false, false);
                LateBinding.LateIndexSetComplex(obj, args, paramNames, false, true);
                LateBinding.LateIndexSetComplex(obj, args, paramNames, true, false);
                LateBinding.LateIndexSetComplex(obj, args, paramNames, true, true);
            }
        }

        private static IEnumerable<object[]> LateCall_TestData()
        {
            yield return new object[] { null, typeof(StaticClass), "M", new object[] { }, new string[] { }, new bool[] { }, new Func<object, object>(_ => StaticClass.Value), 1 };
            yield return new object[] { null, typeof(StaticClass), "M", new object[] { 2, 3 }, new string[] { }, new bool[] { }, new Func<object, object>(_ => StaticClass.Value), 2 };
            yield return new object[] { null, typeof(StaticClass), "M", new object[] { 4, 5 }, new string[] { "a", "b" }, new bool[] { }, new Func<object, object>(_ => StaticClass.Value), 5 };
            yield return new object[] { new InstanceClass(), typeof(InstanceClass), "M", new object[] { }, new string[] { }, new bool[] { }, new Func<object, object>(obj => ((InstanceClass)obj).Value), 1 };
            yield return new object[] { new InstanceClass(), typeof(InstanceClass), "M", new object[] { 2, 3 }, new string[] { }, new bool[] { }, new Func<object, object>(obj => ((InstanceClass)obj).Value), 2 };
            yield return new object[] { new InstanceClass(), typeof(InstanceClass), "M", new object[] { 4, 5 }, new string[] { "a", "b" }, new bool[] { }, new Func<object, object>(obj => ((InstanceClass)obj).Value), 5 };
        }

        private static IEnumerable<object[]> LateGet_TestData()
        {
            yield return new object[] { null, typeof(StaticClass), "M", new object[] { }, new string[] { }, new bool[] { }, 1 };
            yield return new object[] { null, typeof(StaticClass), "M", new object[] { 2, 3 }, new string[] { }, new bool[] { }, 2 };
            yield return new object[] { null, typeof(StaticClass), "M", new object[] { 4, 5 }, new string[] { "a", "b" }, new bool[] { }, 5 };
            yield return new object[] { new InstanceClass(), typeof(InstanceClass), "M", new object[] { }, new string[] { }, new bool[] { }, 1 };
            yield return new object[] { new InstanceClass(), typeof(InstanceClass), "M", new object[] { 2, 3 }, new string[] { }, new bool[] { }, 2 };
            yield return new object[] { new InstanceClass(), typeof(InstanceClass), "M", new object[] { 4, 5 }, new string[] { "a", "b" }, new bool[] { }, 5 };
        }

        private static IEnumerable<object[]> LateSet_TestData()
        {
            yield return new object[] { null, typeof(StaticClass), "M", new object[] { 2, 3 }, new string[] { }, new Func<object, object>(_ => StaticClass.Value), 2 };
            yield return new object[] { null, typeof(StaticClass), "M", new object[] { 4, 5 }, new string[] { "a" }, new Func<object, object>(_ => StaticClass.Value), 5 };
            yield return new object[] { new InstanceClass(), typeof(InstanceClass), "M", new object[] { 2, 3 }, new string[] { }, new Func<object, object>(obj => ((InstanceClass)obj).Value), 2 };
            yield return new object[] { new InstanceClass(), typeof(InstanceClass), "M", new object[] { 4, 5 }, new string[] { "a" }, new Func<object, object>(obj => ((InstanceClass)obj).Value), 5 };
            yield return new object[] { new InstanceClass(), typeof(InstanceClass), "P", new object[] { 6 }, new string[] { }, new Func<object, object>(obj => ((InstanceClass)obj).Value), 6 };
        }

        private static IEnumerable<object[]> LateSetComplex_TestData()
        {
            yield return new object[] { new InstanceClass(), typeof(InstanceClass), "P", new object[] { 1 }, new string[] { }, false, false };
            yield return new object[] { new InstanceClass(), typeof(InstanceClass), "Q", new object[] { 2 }, new string[] { }, true, false };
            yield return new object[] { new InstanceStruct(), typeof(InstanceStruct), "P", new object[] { 3 }, new string[] { }, false, true };
            yield return new object[] { new InstanceStruct(), typeof(InstanceStruct), "Q", new object[] { 4 }, new string[] { }, true, true };
        }

        private static IEnumerable<object[]> LateIndexGet_TestData()
        {
            yield return new object[] { new InstanceClass(), new object[] { 1 }, new string[] { }, 2 };
            yield return new object[] { new InstanceClass(), new object[] { 2, 3 }, new string[] { }, 5 };
            yield return new object[] { new InstanceStruct(), new object[] { 4 }, new string[] { }, 8 };
            yield return new object[] { new InstanceStruct(), new object[] { 5, 6 }, new string[] { }, 11 };
        }

        private static IEnumerable<object[]> LateIndexSet_TestData()
        {
            yield return new object[] { new InstanceClass(), new object[] { 1, 2, 3 }, new string[] { }, new Func<object, object>(obj => ((InstanceClass)obj).Value), 6 };
            yield return new object[] { new InstanceStruct(), new object[] { 4, 5, 6 }, new string[] { }, new Func<object, object>(obj => ((InstanceStruct)obj).Value), 15 };
        }

        private static IEnumerable<object[]> LateIndexSet_MissingMember_TestData()
        {
            yield return new object[] { new StaticClass(), new object[] { 1 }, new string[] { } };
            yield return new object[] { new InstanceClass(), new object[] { 2, 3 }, new string[] { } };
            yield return new object[] { new InstanceStruct(), new object[] { 5, 6 }, new string[] { } };
        }

        private static IEnumerable<object[]> LateIndexSetComplex_TestData()
        {
            yield return new object[] { new InstanceClass(), new object[] { 1, 2, 3 }, new string[] { "x", "y" }, false, false };
            yield return new object[] { new InstanceClass(), new object[] { 4, 5 }, new string[] { "i" }, true, false };
            yield return new object[] { new InstanceStruct(), new object[] { 6, 7, 8 }, new string[] { "x", "y" }, false, true };
            yield return new object[] { new InstanceStruct(), new object[] { 9, 10 }, new string[] { "i" }, true, true };
        }

        private sealed class StaticClass
        {
            public static int Value;
            public static int M() => Value = 1;
            public static object M(int x, int y) => Value = x;
            public static object M(object a, object b) => Value = (int)b;
        }

        private sealed class InstanceClass
        {
            public int Value;
            public int P { get { return Value; } set { Value = value; } }
            public int Q => Value;
            public int M() => Value = 1;
            public object M(int x, int y) => Value = x;
            public object M(object a, object b) => Value = (int)b;
            public int this[int i] => i * 2;
            public int this[object x, object y]
            {
                get { return (int)x + (int)y; }
                set { Value = (int)x + (int)y + value; }
            }
        }

        private struct InstanceStruct
        {
            public int Value;
            public int P { get { return Value; } set { Value = value; } }
            public int Q => Value;
            public int this[int i] => i * 2;
            public int this[object x, object y]
            {
                get { return (int)x + (int)y; }
                set { Value = (int)x + (int)y + value; }
            }
        }
    }
}


text:
package com.sonymobile.jenkins.plugins.gitlab.gitlabauth.acl;

import com.sonymobile.jenkins.plugins.gitlab.gitlabauth.security.GitLabUserDetails;
import hudson.security.ACL;
import hudson.security.Permission;
import hudson.security.PermissionGroup;
import org.acegisecurity.Authentication;

import com.sonymobile.gitlab.exceptions.GitLabApiException;
import com.sonymobile.gitlab.model.GitLabGroupMemberInfo;
import com.sonymobile.jenkins.plugins.gitlab.gitlabauth.GitLab;

import java.util.Collection;
import java.util.List;

/**
 * Abstract ACL class for other GitLab ACLs to extend.
 *
 * @author Andreas Alanko
 */
public abstract class GitLabAbstractACL extends ACL {
    /** Contains all identities and their respective granted permissions. */
    private final GitLabGrantedPermissions grantedPermissions;

    /**
     * Creates an ACL based on the given map of granted permissions.
     *
     * @param grantedPermissions map of granted permissions
     */
    protected GitLabAbstractACL(GitLabGrantedPermissions grantedPermissions) {
        this.grantedPermissions = grantedPermissions;
    }

    /**
     * Creates an ACL with default permissions.
     */
    protected GitLabAbstractACL() {
        this(new GitLabGrantedPermissions());
        setDefaultPermissions();
    }

    /**
     * Returns the granted permissions for the identities.
     *
     * @return the granted permissions
     */
    protected GitLabGrantedPermissions getGrantedPermissions() {
        return grantedPermissions;
    }

    /**
     * Gets the permission groups which are applicable for the ACL.
     *
     * @return an iterable collection of permission groups
     */
    public abstract Collection<PermissionGroup> getApplicablePermissionGroups();

    /**
     * Checks if the given user has admin access on the Jenkins server.
     *
     * @param user the user
     * @return true is the user has admin access else false
     */
    protected abstract boolean isAdmin(GitLabUserDetails user);

    /**
     * Sets the default permission for the ACL.
     */
    protected abstract void setDefaultPermissions();

    public List<GitLabPermissionIdentity> getPermissionIdentities(boolean getGitLabIdentities) {
        return grantedPermissions.getPermissionIdentities(getGitLabIdentities);
    }

    /**
     * Checks if the user is logged in and if the principal is a
     * GitLabUserDetails object.
     *
     * @param auth the authentication object
     * @return true if logged in and the principal object is a GitLabUserDetails object
     */
    protected boolean isLoggedIn(Authentication auth) {
        return auth.isAuthenticated() && auth.getPrincipal() instanceof GitLabUserDetails;
    }

    /**
     * Checks if the given identity has the given permission.
     *
     * @param identity   the identity
     * @param permission the permission
     * @return true if permission is granted
     */
    public boolean isPermissionSet(GitLabPermissionIdentity identity, Permission permission) {
        return grantedPermissions.isPermissionSet(identity, permission);
    }

    /**
     * Checks if the permission is granted for the identity type Jenkins.
     * Excluding access level for anonymous.
     *
     * @param user       the user
     * @param permission the permission
     * @return true if permission is granted
     */
    private boolean isPermissionSetJenkins(GitLabUserDetails user, Permission permission) {
        if (isAdmin(user)) {
            if (isPermissionSet(GitLabPermissionIdentity.JENKINS_ADMIN, permission)) {
                return true;
            }
        }

        if (isPermissionSet(GitLabPermissionIdentity.JENKINS_LOGGED_IN, permission)) {
            return true;
        }
        return false;
    }

    /**
     * Checks if the permission is granted for the user with the given username
     * within the identity type User.
     *
     * @param username   the username
     * @param permission the permission
     * @return true if permission is granted
     */
    private boolean isPermissionSetUser(String username, Permission permission) {
        return isPermissionSet(GitLabPermissionIdentity.user(username), permission);
    }

    /**
     * Checks if the permission is granted for the user with the given username
     * within the identity type Group.
     *
     * @param userId     the user id
     * @param permission the permission
     * @return true if permission is granted
     */
    private boolean isPermissionSetGroup(int userId, Permission permission) {
        List<GitLabPermissionIdentity> groups = grantedPermissions.getGroupPermissionIdentities();

        GitLabGroupMemberInfo groupMember;

        for (GitLabPermissionIdentity group : groups) {
            try {
                groupMember = GitLab.getGroupMember(userId, group.id);

                // Check if user is member of group
                if(groupMember != null && !groupMember.isBlocked()) {
                    // Check if the group has the given permission
                    if (isPermissionSet(group, permission)) {
                        return true;
                    }
                }
            } catch (GitLabApiException e) {}
        }
        return false;
    }

    /**
     * Checks if GitLabIdentity Anonymous has the given permission.
     *
     * @param permission the permission
     * @return true if permission is granted
     */
    protected boolean isPermissionSetAnon(Permission permission) {
        return isPermissionSet(GitLabPermissionIdentity.JENKINS_ANONYMOUS, permission);
    }

    /**
     * Checks if the given permission is set for the given user.
     *
     * @param user       the user
     * @param permission the permission
     * @return true if permission is granted
     */
    protected boolean isPermissionSetStandard(GitLabUserDetails user, Permission permission) {
        if (isPermissionSetJenkins(user, permission)) {
            return true;
        }

        if (isPermissionSetUser(user.getUsername(), permission)) {
            return true;
        }

        if (isPermissionSetGroup(user.getId(), permission)) {
            return true;
        }
        return false;
    }
}


text:
import sys

import numpy as np

import numba.core.typing.cffi_utils as cffi_support
from numba.tests.support import import_dynamic, temp_directory
from numba.core.types import complex128

def load_inline_module():
    """
    Create an inline module, return the corresponding ffi and dll objects.
    """
    from cffi import FFI

    # We can't rely on libc availability on Windows anymore, so we use our
    # own compiled wrappers (see https://bugs.python.org/issue23606).

    defs = """
    double _numba_test_sin(double x);
    double _numba_test_cos(double x);
    double _numba_test_funcptr(double (*func)(double));
    bool _numba_test_boolean(void);
    """

    ffi = FFI()
    ffi.cdef(defs)
    # Load the _helperlib namespace
    from numba import _helperlib
    return ffi, ffi.dlopen(_helperlib.__file__)

def load_ool_module():
    """
    Compile an out-of-line module, return the corresponding ffi and
    module objects.
    """
    from cffi import FFI

    numba_complex = """
    typedef struct _numba_complex {
        double real;
        double imag;
    } numba_complex;
    """

    bool_define = """
    #ifdef _MSC_VER
        #define false 0
        #define true 1
        #define bool int
    #else
        #include <stdbool.h>
    #endif
    """

    defs = numba_complex + """
    bool boolean(void);
    double sin(double x);
    double cos(double x);
    int foo(int a, int b, int c);
    void vsSin(int n, float* x, float* y);
    void vdSin(int n, double* x, double* y);
    void vector_real(numba_complex *c, double *real, int n);
    void vector_imag(numba_complex *c, double *imag, int n);
    """

    source = numba_complex + bool_define + """
    static bool boolean(void)
    {
        return true;
    }

    static int foo(int a, int b, int c)
    {
        return a + b * c;
    }

    void vsSin(int n, float* x, float* y) {
        int i;
        for (i=0; i<n; i++)
            y[i] = sin(x[i]);
    }

    void vdSin(int n, double* x, double* y) {
        int i;
        for (i=0; i<n; i++)
            y[i] = sin(x[i]);
    }

    static void vector_real(numba_complex *c, double *real, int n) {
        int i;
        for (i = 0; i < n; i++)
            real[i] = c[i].real;
    }

    static void vector_imag(numba_complex *c, double *imag, int n) {
        int i;
        for (i = 0; i < n; i++)
            imag[i] = c[i].imag;
    }
    """

    ffi = FFI()
    ffi.set_source('cffi_usecases_ool', source)
    ffi.cdef(defs, override=True)
    tmpdir = temp_directory('test_cffi')
    ffi.compile(tmpdir=tmpdir)
    sys.path.append(tmpdir)
    try:
        mod = import_dynamic('cffi_usecases_ool')
        cffi_support.register_module(mod)
        cffi_support.register_type(mod.ffi.typeof('struct _numba_complex'),
                                   complex128)
        return mod.ffi, mod
    finally:
        sys.path.remove(tmpdir)

def init():
    """
    Initialize module globals.  This can invoke external utilities, hence not
    being executed implicitly at module import.
    """
    global ffi, cffi_sin, cffi_cos, cffi_bool

    if ffi is None:
        ffi, dll = load_inline_module()
        cffi_sin = dll._numba_test_sin
        cffi_cos = dll._numba_test_cos
        cffi_bool = dll._numba_test_boolean
        del dll

def init_ool():
    """
    Same as init() for OOL mode.
    """
    global ffi_ool, cffi_sin_ool, cffi_cos_ool, cffi_foo, cffi_bool_ool
    global vsSin, vdSin, vector_real, vector_imag

    if ffi_ool is None:
        ffi_ool, mod = load_ool_module()
        cffi_sin_ool = mod.lib.sin
        cffi_cos_ool = mod.lib.cos
        cffi_foo = mod.lib.foo
        cffi_bool_ool = mod.lib.boolean
        vsSin = mod.lib.vsSin
        vdSin = mod.lib.vdSin
        vector_real = mod.lib.vector_real
        vector_imag = mod.lib.vector_imag
        del mod

ffi = ffi_ool = None

def use_cffi_sin(x):
    return cffi_sin(x) * 2

def use_two_funcs(x):
    return cffi_sin(x) - cffi_cos(x)

def use_cffi_sin_ool(x):
    return cffi_sin_ool(x) * 2

def use_cffi_boolean_true():
    return cffi_bool_ool()

def use_two_funcs_ool(x):
    return cffi_sin_ool(x) - cffi_cos_ool(x)

def use_func_pointer(fa, fb, x):
    if x > 0:
        return fa(x)
    else:
        return fb(x)

def use_user_defined_symbols():
    return cffi_foo(1, 2, 3)

# The from_buffer method is member of cffi.FFI, and also of CompiledFFI objects
# (cffi_usecases_ool.ffi is a CompiledFFI object) so we use both in these
# functions.

def vector_sin_float32(x, y):
    vsSin(len(x), ffi.from_buffer(x), ffi_ool.from_buffer(y))

def vector_sin_float64(x, y):
    vdSin(len(x), ffi.from_buffer(x), ffi_ool.from_buffer(y))

# For testing pointer to structs from buffers

def vector_extract_real(x, y):
    vector_real(ffi.from_buffer(x), ffi.from_buffer(y), len(x))

def vector_extract_imag(x, y):
    vector_imag(ffi.from_buffer(x), ffi.from_buffer(y), len(x))


text:
package com.rockhoppertech.music.midi.js;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.sound.midi.MidiEvent;
import javax.sound.midi.ShortMessage;
import javax.sound.midi.Track;

/**
 * Class MIDIControllers helps you work with MIDI control messages.
 *
 *
 * @author Gene De Lisa
 * @since 1.0
 */
public final class MIDIControllers {

    public static final String ALL_CONTROLLERS_OFF_CONTROLLER = "All Controllers Off";
    public static final String ALL_NOTES_OFF_CONTROLLER = "All Notes Off";
    public static final String ALL_SOUND_OFF_CONTROLLER = "All Sound Off";

    public static final String BALANCE_COARSE_CONTROLLER = "Balance (coarse)";
    public static final String BALANCE_FINE_CONTROLLER = "Balance (fine)";

    public static final String BANK_SELECT_COARSE_CONTROLLER = "Bank Select (coarse)";
    public static final String BANK_SELECT_FINE_CONTROLLER = "Bank Select (fine)";

    public static final String BREATH_CONTROLLER_COARSE_CONTROLLER = "Breath controller (coarse)";

    public static final String BREATH_CONTROLLER_FINE_CONTROLLER = "Breath controller (fine)";

    // look at CONTROLLER_NAMES
    public static final int CC_BANK_SELECT_COARSE = 0;

    public static final int CC_BANK_SELECT_FINE = 32;

    public static final int CC_MODWHEEL_COARSE = 1;

    public static final int CC_MODWHEEL_FINE = 33;

    public static final int CC_PAN_COARSE = 10;

    public static final int CC_PAN_FINE = 42;

    /**
     * 0 (to 63) is off. 127 (to 64) is on.
     */
    public static final int CC_PORTAMENTO_ON_OFF = 65;

    public static final int CC_PORTAMENTO_TIME_COARSE = 5;

    public static final int CC_PORTAMENTO_TIME_FINE = 37;

    /**
     * sometimes called the hold pedal. 0 (to 63) is off. 127 (to 64) is on.
     */
    public static final int CC_SUSTAIN = 64;

    public static final int CC_VOLUME_COARSE = 7;

    public static final int CC_VOLUME_FINE = 39;

    public static final String CELESTE_LEVEL_CONTROLLER = "Celeste Level";

    public static final String CHORUS_LEVEL_CONTROLLER = "Chorus Level";

    // defined controllers
    public static final Map<String, Integer> CONTROLLER_NAMES = new HashMap<String, Integer>();

    public static final String DATA_BUTTON_DECREMENT_CONTROLLER = "Data Button decrement";

    public static final String DATA_BUTTON_INCREMENT_CONTROLLER = "Data Button increment";

    public static final String DATA_ENTRY_COARSE_CONTROLLER = "Data Entry (coarse)";

    public static final String DATA_ENTRY_FINE_CONTROLLER = "Data Entry (fine)";

    public static final String EFFECT_CONTROL_1_COARSE_CONTROLLER = "Effect Control 1 (coarse)";
    public static final String EFFECT_CONTROL_1_FINE_CONTROLLER = "Effect Control 1 (fine)";
    public static final String EFFECT_CONTROL_2_COARSE_CONTROLLER = "Effect Control 2 (coarse)";
    public static final String EFFECT_CONTROL_2_FINE_CONTROLLER = "Effect Control 2 (fine)";
    public static final String EFFECTS_LEVEL_CONTROLLER = "Effects Level";

    public static final String EXPRESSION_COARSE_CONTROLLER = "Expression (coarse)";
    public static final String EXPRESSION_FINE_CONTROLLER = "Expression (fine)";

    public static final String FOOT_PEDAL_COARSE_CONTROLLER = "Foot Pedal (coarse)";

    public static final String FOOT_PEDAL_FINE_CONTROLLER = "Foot Pedal (fine)";

    public static final String GENERAL_PURPOSE_BUTTON_1_ON_OFF_CONTROLLER = "General Purpose Button 1 (on/off)";

    public static final String GENERAL_PURPOSE_BUTTON_2_ON_OFF_CONTROLLER = "General Purpose Button 2 (on/off)";

    public static final String GENERAL_PURPOSE_BUTTON_3_ON_OFF_CONTROLLER = "General Purpose Button 3 (on/off)";

    public static final String GENERAL_PURPOSE_BUTTON_4_ON_OFF_CONTROLLER = "General Purpose Button 4 (on/off)";

    public static final String GENERAL_PURPOSE_SLIDER_1_CONTROLLER = "General Purpose Slider 1";

    public static final String GENERAL_PURPOSE_SLIDER_2_CONTROLLER = "General Purpose Slider 2";

    public static final String GENERAL_PURPOSE_SLIDER_3_CONTROLLER = "General Purpose Slider 3";

    public static final String GENERAL_PURPOSE_SLIDER_4_CONTROLLER = "General Purpose Slider 4";

    public static final String HOLD_2_PEDAL_ON_OFF_CONTROLLER = "Hold 2 Pedal (on/off)";
    public static final String HOLD_PEDAL_ON_OFF_CONTROLLER = "Hold Pedal (on/off)";

    public static final String LEGATO_PEDAL_ON_OFF_CONTROLLER = "Legato Pedal (on/off)";

    public static final String LOCAL_KEYBOARD_ON_OFF_CONTROLLER = "Local Keyboard (on/off)";

    public static final String MODULATION_WHEEL_COARSE_CONTROLLER = "Modulation Wheel (coarse)";
    public static final String MODULATION_WHEEL_FINE_CONTROLLER = "Modulation Wheel (fine)";
    public static final String MONO_OPERATION_CONTROLLER = "Mono Operation";

    public static final String NON_REGISTERED_PARAMETER_COARSE_CONTROLLER = "Non-registered Parameter (coarse)";
    public static final String NON_REGISTERED_PARAMETER_FINE_CONTROLLER = "Non-registered Parameter (fine)";

    public static final String OMNI_MODE_OFF_CONTROLLER = "Omni Mode Off";
    public static final String OMNI_MODE_ON_CONTROLLER = "Omni Mode On";

    public static final String PAN_POSITION_COARSE_CONTROLLER = "Pan position (coarse)";
    public static final String PAN_POSITION_FINE_CONTROLLER = "Pan position (fine)";

    public static final String PHASER_LEVEL_CONTROLLER = "Phaser Level";

    public static final String POLY_OPERATION_CONTROLLER = "Poly Operation";

    public static final String PORTAMENTO_ON_OFF_CONTROLLER = "Portamento (on/off)";
    public static final String PORTAMENTO_TIME_COARSE_CONTROLLER = "Portamento Time (coarse)";
    public static final String PORTAMENTO_TIME_FINE_CONTROLLER = "Portamento Time (fine)";

    public static final String REGISTERED_PARAMETER_COARSE_CONTROLLER = "Registered Parameter (coarse)";
    public static final String REGISTERED_PARAMETER_FINE_CONTROLLER = "Registered Parameter (fine)";

    public static final String SOFT_PEDAL_ON_OFF_CONTROLLER = "Soft Pedal (on/off)";

    public static final String SOUND_ATTACK_TIME_CONTROLLER = "Sound Attack Time";
    public static final String SOUND_BRIGHTNESS_CONTROLLER = "Sound Brightness";
    public static final String SOUND_CONTROL_10_CONTROLLER = "Sound Control 10";
    public static final String SOUND_CONTROL_6_CONTROLLER = "Sound Control 6";
    public static final String SOUND_CONTROL_7_CONTROLLER = "Sound Control 7";
    public static final String SOUND_CONTROL_8_CONTROLLER = "Sound Control 8";
    public static final String SOUND_CONTROL_9_CONTROLLER = "Sound Control 9";
    public static final String SOUND_RELEASE_TIME_CONTROLLER = "Sound Release Time";
    public static final String SOUND_TIMBRE_CONTROLLER = "Sound Timbre";
    public static final String SOUND_VARIATION_CONTROLLER = "Sound Variation";

    public static final String SUSTENUTO_PEDAL_ON_OFF_CONTROLLER = "Sustenuto Pedal (on/off)";

    public static final String TREMULO_LEVEL_CONTROLLER = "Tremulo Level";

    public static final String VOLUME_COARSE_CONTROLLER = "Volume (coarse)";
    public static final String VOLUME_FINE_CONTROLLER = "Volume (fine)";

    static {

        // public static final String BANK_SELECT_CONTROLLER = "Bank Select
        // (coarse)";
        CONTROLLER_NAMES.put(HOLD_PEDAL_ON_OFF_CONTROLLER,
                Integer.valueOf(64));
        CONTROLLER_NAMES.put(ALL_NOTES_OFF_CONTROLLER,
                Integer.valueOf(123));
        CONTROLLER_NAMES.put(SOUND_TIMBRE_CONTROLLER,
                Integer.valueOf(71));
        CONTROLLER_NAMES.put(GENERAL_PURPOSE_BUTTON_2_ON_OFF_CONTROLLER,
                Integer.valueOf(81));
        CONTROLLER_NAMES.put(FOOT_PEDAL_FINE_CONTROLLER,
                Integer.valueOf(36));
        CONTROLLER_NAMES.put(BREATH_CONTROLLER_FINE_CONTROLLER,
                Integer.valueOf(34));
        CONTROLLER_NAMES.put(BALANCE_FINE_CONTROLLER,
                Integer.valueOf(40));
        CONTROLLER_NAMES.put(FOOT_PEDAL_COARSE_CONTROLLER,
                Integer.valueOf(4));
        CONTROLLER_NAMES.put(SOUND_CONTROL_7_CONTROLLER,
                Integer.valueOf(76));
        CONTROLLER_NAMES.put(GENERAL_PURPOSE_BUTTON_1_ON_OFF_CONTROLLER,
                Integer.valueOf(80));
        CONTROLLER_NAMES.put(PHASER_LEVEL_CONTROLLER,
                Integer.valueOf(95));
        CONTROLLER_NAMES.put(MONO_OPERATION_CONTROLLER,
                Integer.valueOf(126));
        CONTROLLER_NAMES.put(EFFECT_CONTROL_2_COARSE_CONTROLLER,
                Integer.valueOf(13));
        CONTROLLER_NAMES.put(DATA_ENTRY_FINE_CONTROLLER,
                Integer.valueOf(38));
        CONTROLLER_NAMES.put(SOUND_CONTROL_9_CONTROLLER,
                Integer.valueOf(78));
        CONTROLLER_NAMES.put(BANK_SELECT_FINE_CONTROLLER,
                Integer.valueOf(32));
        CONTROLLER_NAMES.put(EFFECT_CONTROL_2_FINE_CONTROLLER,
                Integer.valueOf(45));
        CONTROLLER_NAMES.put(BALANCE_COARSE_CONTROLLER,
                Integer.valueOf(8));
        CONTROLLER_NAMES.put(EXPRESSION_COARSE_CONTROLLER,
                Integer.valueOf(11));
        CONTROLLER_NAMES.put(LOCAL_KEYBOARD_ON_OFF_CONTROLLER,
                Integer.valueOf(122));
        CONTROLLER_NAMES.put(SOUND_ATTACK_TIME_CONTROLLER,
                Integer.valueOf(73));
        CONTROLLER_NAMES.put(SUSTENUTO_PEDAL_ON_OFF_CONTROLLER,
                Integer.valueOf(66));
        CONTROLLER_NAMES.put(REGISTERED_PARAMETER_COARSE_CONTROLLER,
                Integer.valueOf(101));
        CONTROLLER_NAMES.put(DATA_BUTTON_DECREMENT_CONTROLLER,
                Integer.valueOf(97));
        CONTROLLER_NAMES.put(SOUND_CONTROL_8_CONTROLLER,
                Integer.valueOf(77));
        CONTROLLER_NAMES.put(LEGATO_PEDAL_ON_OFF_CONTROLLER,
                Integer.valueOf(68));
        CONTROLLER_NAMES.put(CHORUS_LEVEL_CONTROLLER,
                Integer.valueOf(93));
        CONTROLLER_NAMES.put(PAN_POSITION_COARSE_CONTROLLER,
                Integer.valueOf(10));
        CONTROLLER_NAMES.put(ALL_CONTROLLERS_OFF_CONTROLLER,
                Integer.valueOf(121));
        CONTROLLER_NAMES.put(SOUND_CONTROL_6_CONTROLLER,
                Integer.valueOf(75));
        CONTROLLER_NAMES.put(VOLUME_FINE_CONTROLLER,
                Integer.valueOf(39));
        CONTROLLER_NAMES.put(OMNI_MODE_ON_CONTROLLER,
                Integer.valueOf(125));
        CONTROLLER_NAMES.put(PORTAMENTO_ON_OFF_CONTROLLER,
                Integer.valueOf(65));
        CONTROLLER_NAMES.put(SOUND_RELEASE_TIME_CONTROLLER,
                Integer.valueOf(72));
        CONTROLLER_NAMES.put(GENERAL_PURPOSE_SLIDER_3_CONTROLLER,
                Integer.valueOf(18));
        CONTROLLER_NAMES.put(GENERAL_PURPOSE_BUTTON_3_ON_OFF_CONTROLLER,
                Integer.valueOf(82));
        CONTROLLER_NAMES.put(PORTAMENTO_TIME_FINE_CONTROLLER,
                Integer.valueOf(37));
        CONTROLLER_NAMES.put(VOLUME_COARSE_CONTROLLER,
                Integer.valueOf(7));
        CONTROLLER_NAMES.put(GENERAL_PURPOSE_SLIDER_4_CONTROLLER,
                Integer.valueOf(19));
        CONTROLLER_NAMES.put(DATA_BUTTON_INCREMENT_CONTROLLER,
                Integer.valueOf(96));
        CONTROLLER_NAMES.put(REGISTERED_PARAMETER_FINE_CONTROLLER,
                Integer.valueOf(100));
        CONTROLLER_NAMES.put(PAN_POSITION_FINE_CONTROLLER,
                Integer.valueOf(42));
        CONTROLLER_NAMES.put(EFFECTS_LEVEL_CONTROLLER,
                Integer.valueOf(91));
        CONTROLLER_NAMES.put(NON_REGISTERED_PARAMETER_COARSE_CONTROLLER,
                Integer.valueOf(99));
        CONTROLLER_NAMES.put(TREMULO_LEVEL_CONTROLLER,
                Integer.valueOf(92));
        CONTROLLER_NAMES.put(GENERAL_PURPOSE_SLIDER_2_CONTROLLER,
                Integer.valueOf(17));
        CONTROLLER_NAMES.put(CELESTE_LEVEL_CONTROLLER,
                Integer.valueOf(94));
        CONTROLLER_NAMES.put(EFFECT_CONTROL_1_FINE_CONTROLLER,
                Integer.valueOf(44));
        CONTROLLER_NAMES.put(EXPRESSION_FINE_CONTROLLER,
                Integer.valueOf(43));
        CONTROLLER_NAMES.put(SOUND_BRIGHTNESS_CONTROLLER,
                Integer.valueOf(74));
        CONTROLLER_NAMES.put(NON_REGISTERED_PARAMETER_FINE_CONTROLLER,
                Integer.valueOf(98));
        CONTROLLER_NAMES.put(SOUND_CONTROL_10_CONTROLLER,
                Integer.valueOf(79));
        CONTROLLER_NAMES.put(BREATH_CONTROLLER_COARSE_CONTROLLER,
                Integer.valueOf(2));
        CONTROLLER_NAMES.put(PORTAMENTO_TIME_COARSE_CONTROLLER,
                Integer.valueOf(5));
        CONTROLLER_NAMES.put(MODULATION_WHEEL_COARSE_CONTROLLER,
                Integer.valueOf(1));
        CONTROLLER_NAMES.put(HOLD_2_PEDAL_ON_OFF_CONTROLLER,
                Integer.valueOf(69));
        CONTROLLER_NAMES.put(EFFECT_CONTROL_1_COARSE_CONTROLLER,
                Integer.valueOf(12));
        CONTROLLER_NAMES.put(BANK_SELECT_COARSE_CONTROLLER,
                Integer.valueOf(0));
        CONTROLLER_NAMES.put(POLY_OPERATION_CONTROLLER,
                Integer.valueOf(127));
        CONTROLLER_NAMES.put(GENERAL_PURPOSE_SLIDER_1_CONTROLLER,
                Integer.valueOf(16));
        CONTROLLER_NAMES.put(ALL_SOUND_OFF_CONTROLLER,
                Integer.valueOf(120));
        CONTROLLER_NAMES.put(GENERAL_PURPOSE_BUTTON_4_ON_OFF_CONTROLLER,
                Integer.valueOf(83));
        CONTROLLER_NAMES.put(MODULATION_WHEEL_FINE_CONTROLLER,
                Integer.valueOf(33));
        CONTROLLER_NAMES.put(OMNI_MODE_OFF_CONTROLLER,
                Integer.valueOf(124));
        CONTROLLER_NAMES.put(DATA_ENTRY_COARSE_CONTROLLER,
                Integer.valueOf(6));
        CONTROLLER_NAMES.put(SOFT_PEDAL_ON_OFF_CONTROLLER,
                Integer.valueOf(67));
        CONTROLLER_NAMES.put(SOUND_VARIATION_CONTROLLER,
                Integer.valueOf(70));
        /*
         * CONTROLLER_NAMES.put("Bank Select (coarse)", Integer.valueOf(0));
         * CONTROLLER_NAMES.put("Modulation Wheel (coarse)", Integer.valueOf(1));
         * CONTROLLER_NAMES.put("Breath controller (coarse)", Integer.valueOf(2));
         * CONTROLLER_NAMES.put("Foot Pedal (coarse)", Integer.valueOf(4));
         * CONTROLLER_NAMES.put("Portamento Time (coarse)", Integer.valueOf(5));
         * CONTROLLER_NAMES.put("Data Entry (coarse)", Integer.valueOf(6));
         * CONTROLLER_NAMES.put("Volume (coarse)", Integer.valueOf(7));
         * CONTROLLER_NAMES.put("Balance (coarse)", Integer.valueOf(8));
         * CONTROLLER_NAMES.put("Pan position (coarse)", Integer.valueOf(10));
         * CONTROLLER_NAMES.put("Expression (coarse)", Integer.valueOf(11));
         * CONTROLLER_NAMES.put("Effect Control 1 (coarse)", Integer.valueOf(12));
         * CONTROLLER_NAMES.put("Effect Control 2 (coarse)", Integer.valueOf(13));
         * CONTROLLER_NAMES.put("General Purpose Slider 1", Integer.valueOf(16));
         * CONTROLLER_NAMES.put("General Purpose Slider 2", Integer.valueOf(17));
         * CONTROLLER_NAMES.put("General Purpose Slider 3", Integer.valueOf(18));
         * CONTROLLER_NAMES.put("General Purpose Slider 4", Integer.valueOf(19));
         * CONTROLLER_NAMES.put("Bank Select (fine)", Integer.valueOf(32));
         * CONTROLLER_NAMES.put("Modulation Wheel (fine)", Integer.valueOf(33));
         * CONTROLLER_NAMES.put("Breath controller (fine)", Integer.valueOf(34));
         * CONTROLLER_NAMES.put("Foot Pedal (fine)", Integer.valueOf(36));
         * CONTROLLER_NAMES.put("Portamento Time (fine)", Integer.valueOf(37));
         * CONTROLLER_NAMES.put("Data Entry (fine)", Integer.valueOf(38));
         * CONTROLLER_NAMES.put("Volume (fine)", Integer.valueOf(39));
         * CONTROLLER_NAMES.put("Balance (fine)", Integer.valueOf(40));
         * CONTROLLER_NAMES.put("Pan position (fine)", Integer.valueOf(42));
         * CONTROLLER_NAMES.put("Expression (fine)", Integer.valueOf(43));
         * CONTROLLER_NAMES.put("Effect Control 1 (fine)", Integer.valueOf(44));
         * CONTROLLER_NAMES.put("Effect Control 2 (fine)", Integer.valueOf(45));
         * CONTROLLER_NAMES.put("Hold Pedal (on/off)", Integer.valueOf(64));
         * CONTROLLER_NAMES.put("Portamento (on/off)", Integer.valueOf(65));
         * CONTROLLER_NAMES.put("Sustenuto Pedal (on/off)", Integer.valueOf(66));
         * CONTROLLER_NAMES.put("Soft Pedal (on/off)", Integer.valueOf(67));
         * CONTROLLER_NAMES.put("Legato Pedal (on/off)", Integer.valueOf(68));
         * CONTROLLER_NAMES.put("Hold 2 Pedal (on/off)", Integer.valueOf(69));
         * CONTROLLER_NAMES.put("Sound Variation", Integer.valueOf(70));
         * CONTROLLER_NAMES.put("Sound Timbre", Integer.valueOf(71));
         * CONTROLLER_NAMES.put("Sound Release Time", Integer.valueOf(72));
         * CONTROLLER_NAMES.put("Sound Attack Time", Integer.valueOf(73));
         * CONTROLLER_NAMES.put("Sound Brightness", Integer.valueOf(74));
         * CONTROLLER_NAMES.put("Sound Control 6", Integer.valueOf(75));
         * CONTROLLER_NAMES.put("Sound Control 7", Integer.valueOf(76));
         * CONTROLLER_NAMES.put("Sound Control 8", Integer.valueOf(77));
         * CONTROLLER_NAMES.put("Sound Control 9", Integer.valueOf(78));
         * CONTROLLER_NAMES.put("Sound Control 10", Integer.valueOf(79));
         * CONTROLLER_NAMES.put("General Purpose Button 1 (on/off)", new
         * Integer( 80)); CONTROLLER_NAMES.put("General Purpose Button 2
         * (on/off)", Integer.valueOf( 81)); CONTROLLER_NAMES.put("General Purpose
         * Button 3 (on/off)", Integer.valueOf( 82)); CONTROLLER_NAMES.put("General
         * Purpose Button 4 (on/off)", Integer.valueOf( 83));
         * CONTROLLER_NAMES.put("Effects Level", Integer.valueOf(91));
         * CONTROLLER_NAMES.put("Tremulo Level", Integer.valueOf(92));
         * CONTROLLER_NAMES.put("Chorus Level", Integer.valueOf(93));
         * CONTROLLER_NAMES.put("Celeste Level", Integer.valueOf(94));
         * CONTROLLER_NAMES.put("Phaser Level", Integer.valueOf(95));
         * CONTROLLER_NAMES.put("Data Button increment", Integer.valueOf(96));
         * CONTROLLER_NAMES.put("Data Button decrement", Integer.valueOf(97));
         * CONTROLLER_NAMES .put("Non-registered Parameter (fine)", new
         * Integer(98)); CONTROLLER_NAMES.put("Non-registered Parameter
         * (coarse)", Integer.valueOf( 99)); CONTROLLER_NAMES.put("Registered
         * Parameter (fine)", Integer.valueOf(100));
         * CONTROLLER_NAMES.put("Registered Parameter (coarse)", new
         * Integer(101)); CONTROLLER_NAMES.put("All Sound Off", new
         * Integer(120)); CONTROLLER_NAMES.put("All Controllers Off", new
         * Integer(121)); CONTROLLER_NAMES.put("Local Keyboard (on/off)", new
         * Integer(122)); CONTROLLER_NAMES.put("All Notes Off", new
         * Integer(123)); CONTROLLER_NAMES.put("Omni Mode Off", new
         * Integer(124)); CONTROLLER_NAMES.put("Omni Mode On", new
         * Integer(125)); CONTROLLER_NAMES.put("Mono Operation", new
         * Integer(126)); CONTROLLER_NAMES.put("Poly Operation", new
         * Integer(127));
         */
    }

    /**
     * @param track
     *            append to this JavaSound Track
     * @param chan
     *            on this channel
     * @param d1
     *            data1
     * @param d2
     *            data2
     */
    public static void appendControlChange(final Track track, final int chan,
            final int d1, final int d2) {
        try {
            ShortMessage message = new ShortMessage();
            long tick = track.ticks();
            // message.setMessage(0xB0 + chan, d1, d2);
            message.setMessage(ShortMessage.CONTROL_CHANGE,
                    chan,
                    d1,
                    d2);
            MidiEvent event = new MidiEvent(message, tick);
            track.add(event);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * @param value
     *            the controller number
     * @return the controller name
     */
    public static String getControllerName(final Integer value) {
        String r = "Unknown controller: " + value;
        for (Entry<String, Integer> e : CONTROLLER_NAMES.entrySet()) {
            if (e.getValue().equals(value)) {
                r = e.getKey();
                break;
            }
        }
        return r;
    }

    /**
     * @param name
     *            controller name
     * @return the controller number
     */
    public static int getControllerNumber(final String name) {
        Integer i = CONTROLLER_NAMES.get(name);
        if (i == null) {
            System.err.println("name is null");
            throw new IllegalArgumentException(name);
        }
        return i.intValue();
    }

    /**
     * @param track
     *            - the JavaSound Track to modify.
     * @param tick
     *            when to insert it
     * @param chan
     *            on which channel
     * @param d1
     *            data1
     * @param d2
     *            data2
     */
    public static void insertControlChange(final Track track, final long tick,
            final int chan,
            final int d1, final int d2) {
        try {
            ShortMessage message = new ShortMessage();
            // message.setMessage(0xB0 + chan, d1, d2);
            message.setMessage(ShortMessage.CONTROL_CHANGE,
                    chan,
                    d1,
                    d2);
            MidiEvent event = new MidiEvent(message, tick);
            track.add(event);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * @param track - the JavaSound Track to modify.
     * @param tick the tick
     * @param chan the MIDI channel
     */
    public static void insertSustainOff(final Track track, final long tick,
            final int chan) {
        insertControlChange(track,
                tick,
                chan,
                CC_SUSTAIN,
                0);
    }

    /**
     * @param track - the JavaSound Track to modify.
      * @param tick the tick
     * @param chan the MIDI channel
     */
    public static void insertSustainOn(final Track track, final long tick,
            final int chan) {
        insertControlChange(track,
                tick,
                chan,
                CC_SUSTAIN,
                127);
    }

    /**
     * @param track - the JavaSound Track to modify.
     * @param tick the tick
     * @param chan the MIDI channel
     * @param value the value
     */
    public static void insertVolumeChange(final Track track, final long tick,
            final int chan,
            final int value) {
        insertControlChange(track,
                tick,
                chan,
                CC_VOLUME_COARSE,
                value);
    }

    /**
     * @param track - the JavaSound Track to modify.
     * @param tick the tick
     * @param chan the MIDI channel
     * @param value the value
     */
    public static void insertPan(final Track track, final long tick,
            final int chan, final int value) {
        if (value < 0 || value > 127) {
            throw new IllegalArgumentException(
                    "value must be between 0 and 127");
        }
        insertControlChange(track, tick, chan, CC_PAN_COARSE, value);
    }

    /**
     * @param track - the JavaSound Track to modify.
     * @param tick the tick
     * @param chan the MIDI channel
     */
    public static void insertPortamentoOff(final Track track, final long tick,
            final int chan) {
        insertControlChange(track, tick, chan, CC_PORTAMENTO_ON_OFF, 0);
    }

    /**
     * @param track - the JavaSound Track to modify.
     * @param tick the tick
     * @param chan the MIDI channel
     */
    public static void insertPortamentoOn(final Track track, final long tick,
            final int chan) {
        insertControlChange(track, tick, chan, CC_PORTAMENTO_ON_OFF, 127);
    }

    /**
     * No instantiation.
     */
    private MIDIControllers() {
    }

}


text:
using System;

namespace AldursLab.WurmAssistant3.Areas.Core
{
    public interface IChangelogManager
    {
        string GetNewChanges();

        void UpdateLastChangeDate();

        void ShowChanges(string changesText);

        string GetChanges(DateTimeOffset sinceDate);
    }
}