text:
package effectiveJava;

import static org.junit.Assert.assertEquals;

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

import org.junit.Ignore;
import org.junit.Test;

public class SumTest {

	private Sum mathObj = new Sum();

	@Test
	public void testSumFromZeroUpToAutobxed_Ten() {
		long res = mathObj.sumFromZeroUpToAutoboxed(10);

		assertEquals(45, res);
	}

	@Test
	public void testSumFromZeroUpToAutobxed_Negative() {
		long res = mathObj.sumFromZeroUpToAutoboxed(-10);

		assertEquals(0, res);
	}

	@Test
	public void testSumFromZeroUpTo_Ten() {
		long res = mathObj.sumFromZeroUpTo(10);

		assertEquals(45, res);
	}

	@Test
	public void testSumFromZeroUpTo_Negative() {
		long res = mathObj.sumFromZeroUpTo(-10);

		assertEquals(0, res);
	}

	@Ignore("Takes long time")
	@Test
	public void testSumFromZeroUpTo_MaxInt() {
		long res = mathObj.sumFromZeroUpTo(Integer.MAX_VALUE);

		assertEquals(2305843005992468481L, res);
	}

	@Ignore("Takes really long time")
	@Test
	public void testSumFromZeroUpToAutoboxed_MaxInt() {
		long res = mathObj.sumFromZeroUpToAutoboxed(Integer.MAX_VALUE);

		assertEquals(2305843005992468481L, res);
	}

	@Test
	public void testSumList_Positive() {

		List<Integer> vals = new ArrayList<Integer>();

		vals.add(1);
		vals.add(3);
		vals.add(100);

		long sum = (long) mathObj.sumList(vals);
		assertEquals(104, sum);
	}
}


text:
package org.elasticsearch.search;

import org.apache.lucene.index.*;
import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BitSet;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefBuilder;
import org.elasticsearch.index.fielddata.FieldData;
import org.elasticsearch.index.fielddata.NumericDoubleValues;
import org.elasticsearch.index.fielddata.SortedBinaryDocValues;
import org.elasticsearch.index.fielddata.SortedNumericDoubleValues;

import java.io.IOException;
import java.util.Locale;

/**
 * Defines what values to pick in the case a document contains multiple values for a particular field.
 */
public enum MultiValueMode {

    /**
     * Sum of all the values.
     */
    SUM {
        /**
         * Returns the sum of the two values
         */
        @Override
        public double apply(double a, double b) {
            return a + b;
        }

        /**
         * Returns the sum of the two values
         */
        @Override
        public long apply(long a, long b) {
            return a + b;
        }
    },

    /**
     * Average of all the values.
     */
    AVG {

        /**
         * Returns the sum of the two values
         */
        @Override
        public double apply(double a, double b) {
            return a + b;
        }

        /**
         * Returns the sum of the two values
         */
        @Override
        public long apply(long a, long b) {
            return a + b;
        }

        /**
         * Returns a / Math.max(1.0d, numValues)
         */
        @Override
        public double reduce(double a, int numValues) {
            return a / Math.max(1.0d, (double) numValues);
        }

        /**
         * Returns Math.round(a / Math.max(1.0, numValues))
         */
        @Override
        public long reduce(long a, int numValues) {
            if (numValues <= 1) {
                // without this the average might be different from the original
                // values on a single-valued field due to the precision loss of the double
                return a;
            } else {
                return Math.round(a / Math.max(1.0, numValues));
            }
        }
    },

    /**
     * Pick the lowest value.
     */
    MIN {
        /**
         * Equivalent to {@link Math#min(double, double)}
         */
        @Override
        public double apply(double a, double b) {
            return Math.min(a, b);
        }

        /**
         * Equivalent to {@link Math#min(long, long)}
         */
        @Override
        public long apply(long a, long b) {
            return Math.min(a, b);
        }

        @Override
        public int applyOrd(int ord1, int ord2) {
            return Math.min(ord1, ord2);
        }

        @Override
        public BytesRef apply(BytesRef a, BytesRef b) {
            return a.compareTo(b) <= 0 ? a : b;
        }

        /**
         * Returns {@link Double#POSITIVE_INFINITY}
         */
        @Override
        public double startDouble() {
            return Double.POSITIVE_INFINITY;
        }

        /**
         * Returns {@link Long#MAX_VALUE}
         */
        @Override
        public long startLong() {
            return Long.MAX_VALUE;
        }

        @Override
        protected long pick(SortedNumericDocValues values, long missingValue) {
            if (values.count() > 0) {
                return values.valueAt(0);
            } else {
                return missingValue;
            }
        }

        @Override
        protected double pick(SortedNumericDoubleValues values, double missingValue) {
            if (values.count() > 0) {
                return values.valueAt(0);
            } else {
                return missingValue;
            }
        }

        @Override
        protected BytesRef pick(SortedBinaryDocValues values, BytesRef missingValue) {
            if (values.count() > 0) {
                return values.valueAt(0);
            } else {
                return missingValue;
            }
        }

        @Override
        protected int pick(RandomAccessOrds values) {
            if (values.cardinality() > 0) {
                return (int) values.ordAt(0);
            } else {
                return -1;
            }
        }
    },

    /**
     * Pick the highest value.
     */
    MAX {
        /**
         * Equivalent to {@link Math#max(double, double)}
         */
        @Override
        public double apply(double a, double b) {
            return Math.max(a, b);
        }

        /**
         * Equivalent to {@link Math#max(long, long)}
         */
        @Override
        public long apply(long a, long b) {
            return Math.max(a, b);
        }

        @Override
        public int applyOrd(int ord1, int ord2) {
            return Math.max(ord1, ord2);
        }

        @Override
        public BytesRef apply(BytesRef a, BytesRef b) {
            return a.compareTo(b) > 0 ? a : b;
        }

        /**
         * Returns {@link Double#NEGATIVE_INFINITY}
         */
        @Override
        public double startDouble() {
            return Double.NEGATIVE_INFINITY;
        }

        /**
         * Returns {@link Long#MIN_VALUE}
         */
        @Override
        public long startLong() {
            return Long.MIN_VALUE;
        }

        @Override
        protected long pick(SortedNumericDocValues values, long missingValue) {
            final int count = values.count();
            if (count > 0) {
                return values.valueAt(count - 1);
            } else {
                return missingValue;
            }
        }

        @Override
        protected double pick(SortedNumericDoubleValues values, double missingValue) {
            final int count = values.count();
            if (count > 0) {
                return values.valueAt(count - 1);
            } else {
                return missingValue;
            }
        }

        @Override
        protected BytesRef pick(SortedBinaryDocValues values, BytesRef missingValue) {
            final int count = values.count();
            if (count > 0) {
                return values.valueAt(count - 1);
            } else {
                return missingValue;
            }
        }

        @Override
        protected int pick(RandomAccessOrds values) {
            final int count = values.cardinality();
            if (count > 0) {
                return (int) values.ordAt(count - 1);
            } else {
                return -1;
            }
        }
    };

    /**
     * Applies the sort mode and returns the result. This method is meant to be
     * a binary function that is commonly used in a loop to find the relevant
     * value for the sort mode in a list of values. For instance if the sort mode
     * is {@link MultiValueMode#MAX} this method is equivalent to {@link Math#max(double, double)}.
     *
     * Note: all implementations are idempotent.
     *
     * @param a an argument
     * @param b another argument
     * @return the result of the function.
     */
    public abstract double apply(double a, double b);

    /**
     * Applies the sort mode and returns the result. This method is meant to be
     * a binary function that is commonly used in a loop to find the relevant
     * value for the sort mode in a list of values. For instance if the sort mode
     * is {@link MultiValueMode#MAX} this method is equivalent to {@link Math#max(long, long)}.
     *
     * Note: all implementations are idempotent.
     *
     * @param a an argument
     * @param b another argument
     * @return the result of the function.
     */
    public abstract long apply(long a, long b);

    public int applyOrd(int ord1, int ord2) {
        throw new UnsupportedOperationException();
    }

    public BytesRef apply(BytesRef a, BytesRef b) {
        throw new UnsupportedOperationException();
    }

    /**
     * Returns an initial value for the sort mode that is guaranteed to have no impact if passed
     * to {@link #apply(double, double)}. This value should be used as the initial value if the
     * sort mode is applied to a non-empty list of values. For instance:
     *

     *     double relevantValue = sortMode.startDouble();
     *     for (int i = 0; i < array.length; i++) {
     *         relevantValue = sortMode.apply(array[i], relevantValue);
     *     }
     *

     *
     * Note: This method return 0 by default.
     *
     * @return an initial value for the sort mode.
     */
    public double startDouble() {
        return 0;
    }

    /**
     * Returns an initial value for the sort mode that is guaranteed to have no impact if passed
     * to {@link #apply(long, long)}. This value should be used as the initial value if the
     * sort mode is applied to a non-empty list of values. For instance:
     *

     *     long relevantValue = sortMode.startLong();
     *     for (int i = 0; i < array.length; i++) {
     *         relevantValue = sortMode.apply(array[i], relevantValue);
     *     }
     *

     *
     * Note: This method return 0 by default.
     * @return an initial value for the sort mode.
     */
    public long startLong() {
        return 0;
    }

    /**
     * Returns the aggregated value based on the sort mode. For instance if {@link MultiValueMode#AVG} is used
     * this method divides the given value by the number of values. The default implementation returns
     * the first argument.
     *
     * Note: all implementations are idempotent.
     */
    public double reduce(double a, int numValues) {
        return a;
    }

    /**
     * Returns the aggregated value based on the sort mode. For instance if {@link MultiValueMode#AVG} is used
     * this method divides the given value by the number of values. The default implementation returns
     * the first argument.
     *
     * Note: all implementations are idempotent.
     */
    public long reduce(long a, int numValues) {
        return a;
    }

    /**
     * A case insensitive version of {@link #valueOf(String)}
     *
     * @throws IllegalArgumentException if the given string doesn't match a sort mode or is null.
     */
    public static MultiValueMode fromString(String sortMode) {
        try {
            return valueOf(sortMode.toUpperCase(Locale.ROOT));
        } catch (Throwable t) {
            throw new IllegalArgumentException("Illegal sort_mode " + sortMode);
        }
    }

    protected long pick(SortedNumericDocValues values, long missingValue) {
        final int count = values.count();
        if (count == 0) {
            return missingValue;
        } else {
            long aggregate = startLong();
            for (int i = 0; i < count; ++i) {
                aggregate = apply(aggregate, values.valueAt(i));
            }
            return reduce(aggregate, count);
        }
    }

    /**
     * Return a {@link NumericDocValues} instance that can be used to sort documents
     * with this mode and the provided values. When a document has no value,
     * missingValue is returned.
     */
    public NumericDocValues select(final SortedNumericDocValues values, final long missingValue) {
        final NumericDocValues singleton = DocValues.unwrapSingleton(values);
        if (singleton != null) {
            final Bits docsWithField = DocValues.unwrapSingletonBits(values);
            if (docsWithField == null || missingValue == 0) {
                return singleton;
            } else {
                return new NumericDocValues() {
                    @Override
                    public long get(int docID) {
                        final long value = singleton.get(docID);
                        if (value == 0 && docsWithField.get(docID) == false) {
                            return missingValue;
                        }
                        return value;
                    }
                };
            }
        } else {
            return new NumericDocValues() {
                @Override
                public long get(int docID) {
                    values.setDocument(docID);
                    return pick(values, missingValue);
                }
            };
        }
    }

    /**
     * Return a {@link NumericDocValues} instance that can be used to sort root documents
     * with this mode, the provided values and filters for root/inner documents.
     *
     * For every root document, the values of its inner documents will be aggregated.
     * If none of the inner documents has a value, then missingValue is returned.
     *
     * NOTE: Calling the returned instance on docs that are not root docs is illegal
     */
    public NumericDocValues select(final SortedNumericDocValues values, final long missingValue, final BitSet rootDocs, final DocIdSet innerDocSet, int maxDoc) throws IOException {
        if (rootDocs == null || innerDocSet == null) {
            return select(DocValues.emptySortedNumeric(maxDoc), missingValue);
        }
        final DocIdSetIterator innerDocs = innerDocSet.iterator();
        if (innerDocs == null) {
            return select(DocValues.emptySortedNumeric(maxDoc), missingValue);
        }

        return new NumericDocValues() {

            int lastSeenRootDoc = 0;
            long lastEmittedValue = missingValue;

            @Override
            public long get(int rootDoc) {
                assert rootDocs.get(rootDoc) : "can only sort root documents";
                assert rootDoc >= lastSeenRootDoc : "can only evaluate current and upcoming root docs";
                // If via compareBottom this method has previously invoked for the same rootDoc then we need to use the
                // last seen value, because innerDocs can't re-iterate over nested child docs it has already emitted,
                // because DocIdSetIterator can only advance forwards.
                if (rootDoc == lastSeenRootDoc) {
                    return lastEmittedValue;
                }
                try {
                    final int prevRootDoc = rootDocs.prevSetBit(rootDoc - 1);
                    final int firstNestedDoc;
                    if (innerDocs.docID() > prevRootDoc) {
                        firstNestedDoc = innerDocs.docID();
                    } else {
                        firstNestedDoc = innerDocs.advance(prevRootDoc + 1);
                    }

                    long accumulated = startLong();
                    int numValues = 0;

                    for (int doc = firstNestedDoc; doc < rootDoc; doc = innerDocs.nextDoc()) {
                        values.setDocument(doc);
                        final int count = values.count();
                        for (int i = 0; i < count; ++i) {
                            final long value = values.valueAt(i);
                            accumulated = apply(accumulated, value);
                        }
                        numValues += count;
                    }
                    lastSeenRootDoc = rootDoc;
                    if (numValues == 0) {
                        lastEmittedValue = missingValue;
                    } else {
                        lastEmittedValue = reduce(accumulated, numValues);
                    }
                    return lastEmittedValue;
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        };
    }

    protected double pick(SortedNumericDoubleValues values, double missingValue) {
        final int count = values.count();
        if (count == 0) {
            return missingValue;
        } else {
            double aggregate = startDouble();
            for (int i = 0; i < count; ++i) {
                aggregate = apply(aggregate, values.valueAt(i));
            }
            return reduce(aggregate, count);
        }
    }

    /**
     * Return a {@link NumericDoubleValues} instance that can be used to sort documents
     * with this mode and the provided values. When a document has no value,
     * missingValue is returned.
     */
    public NumericDoubleValues select(final SortedNumericDoubleValues values, final double missingValue) {
        final NumericDoubleValues singleton = FieldData.unwrapSingleton(values);
        if (singleton != null) {
            final Bits docsWithField = FieldData.unwrapSingletonBits(values);
            if (docsWithField == null || missingValue == 0) {
                return singleton;
            } else {
                return new NumericDoubleValues() {
                    @Override
                    public double get(int docID) {
                        final double value = singleton.get(docID);
                        if (value == 0 && docsWithField.get(docID) == false) {
                            return missingValue;
                        }
                        return value;
                    }
                };
            }
        } else {
            return new NumericDoubleValues() {
                @Override
                public double get(int docID) {
                    values.setDocument(docID);
                    return pick(values, missingValue);
                }
            };
        }
    }

    /**
     * Return a {@link NumericDoubleValues} instance that can be used to sort root documents
     * with this mode, the provided values and filters for root/inner documents.
     *
     * For every root document, the values of its inner documents will be aggregated.
     * If none of the inner documents has a value, then missingValue is returned.
     *
     * NOTE: Calling the returned instance on docs that are not root docs is illegal
     */
    public NumericDoubleValues select(final SortedNumericDoubleValues values, final double missingValue, final BitSet rootDocs, final DocIdSet innerDocSet, int maxDoc) throws IOException {
        if (rootDocs == null || innerDocSet == null) {
            return select(FieldData.emptySortedNumericDoubles(maxDoc), missingValue);
        }

        final DocIdSetIterator innerDocs = innerDocSet.iterator();
        if (innerDocs == null) {
            return select(FieldData.emptySortedNumericDoubles(maxDoc), missingValue);
        }

        return new NumericDoubleValues() {

            int lastSeenRootDoc = 0;
            double lastEmittedValue = missingValue;

            @Override
            public double get(int rootDoc) {
                assert rootDocs.get(rootDoc) : "can only sort root documents";
                assert rootDoc >= lastSeenRootDoc : "can only evaluate current and upcoming root docs";
                if (rootDoc == lastSeenRootDoc) {
                    return lastEmittedValue;
                }
                try {
                    final int prevRootDoc = rootDocs.prevSetBit(rootDoc - 1);
                    final int firstNestedDoc;
                    if (innerDocs.docID() > prevRootDoc) {
                        firstNestedDoc = innerDocs.docID();
                    } else {
                        firstNestedDoc = innerDocs.advance(prevRootDoc + 1);
                    }

                    double accumulated = startDouble();
                    int numValues = 0;

                    for (int doc = firstNestedDoc; doc > prevRootDoc && doc < rootDoc; doc = innerDocs.nextDoc()) {
                        values.setDocument(doc);
                        final int count = values.count();
                        for (int i = 0; i < count; ++i) {
                            final double value = values.valueAt(i);
                            accumulated = apply(accumulated, value);
                        }
                        numValues += count;
                    }

                    lastSeenRootDoc = rootDoc;
                    if (numValues == 0) {
                        lastEmittedValue = missingValue;
                    } else {
                        lastEmittedValue = reduce(accumulated, numValues);
                    }
                    return lastEmittedValue;
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        };
    }

    protected BytesRef pick(SortedBinaryDocValues values, BytesRef missingValue) {
        throw new IllegalArgumentException("Unsupported sort mode: " + this);
    }

    /**
     * Return a {@link BinaryDocValues} instance that can be used to sort documents
     * with this mode and the provided values. When a document has no value,
     * missingValue is returned.
     */
    public BinaryDocValues select(final SortedBinaryDocValues values, final BytesRef missingValue) {
        final BinaryDocValues singleton = FieldData.unwrapSingleton(values);
        if (singleton != null) {
            final Bits docsWithField = FieldData.unwrapSingletonBits(values);
            if (docsWithField == null) {
                return singleton;
            } else {
                return new BinaryDocValues() {
                    @Override
                    public BytesRef get(int docID) {
                        final BytesRef value = singleton.get(docID);
                        if (value.length == 0 && docsWithField.get(docID) == false) {
                            return missingValue;
                        }
                        return value;
                    }
                };
            }
        } else {
            return new BinaryDocValues() {
                @Override
                public BytesRef get(int docID) {
                    values.setDocument(docID);
                    return pick(values, missingValue);
                }
            };
        }
    }

    /**
     * Return a {@link BinaryDocValues} instance that can be used to sort root documents
     * with this mode, the provided values and filters for root/inner documents.
     *
     * For every root document, the values of its inner documents will be aggregated.
     * If none of the inner documents has a value, then missingValue is returned.
     *
     * NOTE: Calling the returned instance on docs that are not root docs is illegal
     */
    public BinaryDocValues select(final SortedBinaryDocValues values, final BytesRef missingValue, final BitSet rootDocs, final DocIdSet innerDocSet, int maxDoc) throws IOException {
        if (rootDocs == null || innerDocSet == null) {
            return select(FieldData.emptySortedBinary(maxDoc), missingValue);
        }

        final DocIdSetIterator innerDocs = innerDocSet.iterator();
        if (innerDocs == null) {
            return select(FieldData.emptySortedBinary(maxDoc), missingValue);
        }

        final BinaryDocValues selectedValues = select(values, new BytesRef());
        final Bits docsWithValue;
        if (FieldData.unwrapSingleton(values) != null) {
            docsWithValue = FieldData.unwrapSingletonBits(values);
        } else {
            docsWithValue = FieldData.docsWithValue(values, maxDoc);
        }
        return new BinaryDocValues() {

            final BytesRefBuilder spare = new BytesRefBuilder();

            int lastSeenRootDoc = 0;
            BytesRef lastEmittedValue = missingValue;

            @Override
            public BytesRef get(int rootDoc) {
                assert rootDocs.get(rootDoc) : "can only sort root documents";
                assert rootDoc >= lastSeenRootDoc : "can only evaluate current and upcoming root docs";
                if (rootDoc == lastSeenRootDoc) {
                    return lastEmittedValue;
                }

                try {
                    final int prevRootDoc = rootDocs.prevSetBit(rootDoc - 1);
                    final int firstNestedDoc;
                    if (innerDocs.docID() > prevRootDoc) {
                        firstNestedDoc = innerDocs.docID();
                    } else {
                        firstNestedDoc = innerDocs.advance(prevRootDoc + 1);
                    }

                    BytesRefBuilder accumulated = null;

                    for (int doc = firstNestedDoc; doc > prevRootDoc && doc < rootDoc; doc = innerDocs.nextDoc()) {
                        values.setDocument(doc);
                        final BytesRef innerValue = selectedValues.get(doc);
                        if (innerValue.length > 0 || docsWithValue == null || docsWithValue.get(doc)) {
                            if (accumulated == null) {
                                spare.copyBytes(innerValue);
                                accumulated = spare;
                            } else {
                                final BytesRef applied = apply(accumulated.get(), innerValue);
                                if (applied == innerValue) {
                                    accumulated.copyBytes(innerValue);
                                }
                            }
                        }
                    }

                    lastSeenRootDoc = rootDoc;
                    if (accumulated == null) {
                        lastEmittedValue = missingValue;
                    } else {
                        lastEmittedValue = accumulated.get();
                    }
                    return lastEmittedValue;
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        };
    }

    protected int pick(RandomAccessOrds values) {
        throw new IllegalArgumentException("Unsupported sort mode: " + this);
    }

    /**
     * Return a {@link SortedDocValues} instance that can be used to sort documents
     * with this mode and the provided values.
     */
    public SortedDocValues select(final RandomAccessOrds values) {
        if (values.getValueCount() >= Integer.MAX_VALUE) {
            throw new UnsupportedOperationException("fields containing more than " + (Integer.MAX_VALUE-1) + " unique terms are unsupported");
        }

        final SortedDocValues singleton = DocValues.unwrapSingleton(values);
        if (singleton != null) {
            return singleton;
        } else {
            return new SortedDocValues() {
                @Override
                public int getOrd(int docID) {
                    values.setDocument(docID);
                    return pick(values);
                }

                @Override
                public BytesRef lookupOrd(int ord) {
                    return values.lookupOrd(ord);
                }

                @Override
                public int getValueCount() {
                    return (int) values.getValueCount();
                }
            };
        }
    }

    /**
     * Return a {@link SortedDocValues} instance that can be used to sort root documents
     * with this mode, the provided values and filters for root/inner documents.
     *
     * For every root document, the values of its inner documents will be aggregated.
     *
     * NOTE: Calling the returned instance on docs that are not root docs is illegal
     */
    public SortedDocValues select(final RandomAccessOrds values, final BitSet rootDocs, final DocIdSet innerDocSet) throws IOException {
        if (rootDocs == null || innerDocSet == null) {
            return select(DocValues.emptySortedSet());
        }

        final DocIdSetIterator innerDocs = innerDocSet.iterator();
        if (innerDocs == null) {
            return select(DocValues.emptySortedSet());
        }

        final SortedDocValues selectedValues = select(values);
        return new SortedDocValues() {

            int lastSeenRootDoc = 0;
            int lastEmittedOrd = -1;

            @Override
            public BytesRef lookupOrd(int ord) {
                return selectedValues.lookupOrd(ord);
            }

            @Override
            public int getValueCount() {
                return selectedValues.getValueCount();
            }

            @Override
            public int getOrd(int rootDoc) {
                assert rootDocs.get(rootDoc) : "can only sort root documents";
                assert rootDoc >= lastSeenRootDoc : "can only evaluate current and upcoming root docs";
                if (rootDoc == lastSeenRootDoc) {
                    return lastEmittedOrd;
                }

                try {
                    final int prevRootDoc = rootDocs.prevSetBit(rootDoc - 1);
                    final int firstNestedDoc;
                    if (innerDocs.docID() > prevRootDoc) {
                        firstNestedDoc = innerDocs.docID();
                    } else {
                        firstNestedDoc = innerDocs.advance(prevRootDoc + 1);
                    }
                    int ord = -1;

                    for (int doc = firstNestedDoc; doc > prevRootDoc && doc < rootDoc; doc = innerDocs.nextDoc()) {
                        final int innerOrd = selectedValues.getOrd(doc);
                        if (innerOrd != -1) {
                            if (ord == -1) {
                                ord = innerOrd;
                            } else {
                                ord = applyOrd(ord, innerOrd);
                            }
                        }
                    }

                    lastSeenRootDoc = rootDoc;
                    return lastEmittedOrd = ord;
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        };
    }
}

redpajama_set_name: RedPajamaGithub


text:
package griffon.swing.converters;

import griffon.converter.ConversionException;
import org.codehaus.griffon.converter.AbstractConverter;

import java.awt.*;
import java.util.List;
import java.util.Map;

/**
 * @author Andres Almiray
 * @since 3.0.0
 */
public class FontConverter extends AbstractConverter<Font> {
    @Override
    public Font fromObject(Object value) throws ConversionException {
        if (null == value) {
            return null;
        } else if (value instanceof CharSequence) {
            return handleAsString(String.valueOf(value));
        } else if (value instanceof List) {
            return handleAsList((List) value);
        } else if (value instanceof Map) {
            return handleAsMap((Map) value);
        } else if (value instanceof Font) {
            return (Font) value;
        } else {
            throw illegalValue(value, Font.class);
        }
    }

    @Override
    public String toString(Font value) throws ConversionException {
        if (null == value) { return null; }
        return value.getFamily() + "-" + formatStyle(value) + "-" + value.getSize();
    }

    protected String formatStyle(Font font) {
        if (font.isBold() && font.isItalic()) {
            return "BOLDITALIC";
        } else if (font.isBold()) {
            return "BOLD";
        } else if (font.isItalic()) {
            return "ITALIC";
        }
        return "PLAIN";
    }

    protected Font handleAsString(String str) {
        if (isBlank(str)) {
            return null;
        }
        String[] parts = str.split("-");
        if (parts.length != 3) {
            throw illegalValue(str, Font.class);
        }

        String family = parts[0];
        int style = resolveStyle(str, parts[1]);
        int size = parseSize(str, parts[2]);

        return new Font(family, style, size);
    }

    protected Font handleAsList(List<?> list) {
        if (list.isEmpty()) {
            return null;
        }

        if (list.size() != 3) {
            throw illegalValue(list, Font.class);
        }

        String family = String.valueOf(list.get(0));
        int style = resolveStyle(list, String.valueOf(list.get(1)));
        int size = parseSize(list, String.valueOf(list.get(2)));

        return new Font(family, style, size);
    }

    protected Font handleAsMap(Map<?, ?> map) {
        if (map.isEmpty()) {
            return null;
        }

        String family = getMapValue(map, "family", "");
        String style = getMapValue(map, "style", "");
        String size = getMapValue(map, "size", "");
        return new Font(family, resolveStyle(map, style), parseSize(map, size));
    }

    protected String getMapValue(Map<?, ?> map, String key, String defaultValue) {
        Object val = map.get(key);
        if (null == val) { val = map.get(String.valueOf(key.charAt(0))); }
        if (null == val) {
            return defaultValue;
        } else if (val instanceof CharSequence) {
            return String.valueOf(val).trim();
        }
        throw illegalValue(map, Font.class);
    }

    protected int parseSize(Object source, String str) {
        int size;
        try {
            size = Integer.parseInt(str);
        } catch (NumberFormatException nfe) {
            throw illegalValue(source, Font.class);
        }
        return size;
    }

    protected int resolveStyle(Object source, String str) {
        if ("PLAIN".equalsIgnoreCase(str)) {
            return Font.PLAIN;
        } else if ("BOLD".equalsIgnoreCase(str)) {
            return Font.BOLD;
        } else if ("ITALIC".equalsIgnoreCase(str)) {
            return Font.ITALIC;
        } else if ("BOLDITALIC".equalsIgnoreCase(str)) {
            return Font.BOLD | Font.ITALIC;
        }
        throw illegalValue(source, Font.class);
    }
}


text:
package org.buzheng.demo.web;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

public class DefaultWebApplicationInitializer implements
		WebApplicationInitializer {

	private final static String DISPATCHER_SERVLET_NAME = "dispatcher";
	private final static String DISPATCHER_SERVLET_MAPPING = "/";

	private final static String ENCODING = "utf-8";
	private final static String ENCODEING_FILTER_NAME = "encodefilter";
	private final static String ENCODEING_FILTER_MAPPING = "/*";

	public void onStartup(ServletContext servletContext)
			throws ServletException {

		AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
		rootContext.register(ApplicationConfig.class);

		servletContext.addListener(new ContextLoaderListener(rootContext));

		// Spring web 控制器
		ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
				DISPATCHER_SERVLET_NAME, new DispatcherServlet(rootContext));
		dispatcher.setLoadOnStartup(1);
		dispatcher.addMapping(DISPATCHER_SERVLET_MAPPING);

		// 编码过滤器
		CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
		encodingFilter.setEncoding(ENCODING);
		encodingFilter.setForceEncoding(true);

		FilterRegistration.Dynamic encodingFilterRegistration = servletContext
				.addFilter(ENCODEING_FILTER_NAME, encodingFilter);
		encodingFilterRegistration.addMappingForUrlPatterns(null, true,
				ENCODEING_FILTER_MAPPING);

	}
}


text:
package io.reactivesw.order.cartdiscount.application.model;

import com.fasterxml.jackson.annotation.JsonCreator;

import io.reactivesw.common.model.Base;
import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * Created by umasuo on 16/11/17. TODO
 */
@Data
@EqualsAndHashCode(callSuper = false)
public final class CartDiscountPredicate extends Base {

  private final String predicate;

  @JsonCreator
  public CartDiscountPredicate(final String predicate) {
    this.predicate = predicate;
  }

}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<parent>
		<artifactId>pdb2rdf</artifactId>
		<groupId>com.dumontierlab</groupId>
		<version>2.0.0</version>
	</parent>
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.dumontierlab</groupId>
	<artifactId>pdb2rdf-parser</artifactId>
	<version>2.0.0</version>
	<name>PDB Parser</name>
	<dependencies>
		<dependency>
			<groupId>org.apache.jena</groupId>
			<artifactId>jena-core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.jena</groupId>
			<artifactId>jena-arq</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.jena</groupId>
			<artifactId>jena-tdb</artifactId>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.jena</groupId>
			<artifactId>jena-tdb</artifactId>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

</project>


text:
/*NEW SLIDER STYLES FOR SCALE, ETC*/
/* slider widget */
.ui-slider  {
	text-decoration: none !important;
}
.ui-slider-tooltip {
	display: none;
}
.ui-slider-handle-active .ui-slider-tooltip {
	display: block;
	position: relative;
	top: -25px;
	text-align: center;
	padding: .1em;
	font-size: .6em;
	width: 8em;
	margin-left: -4em;
	text-decoration: none !important;
}
.ui-slider ol, .ui-slider li, .ui-slider dl, .ui-slider dd, .ui-slider dt {
	list-style: none;
	margin: 0;
	padding: 0;
}
.ui-slider ol, .ui-slider dl {
	position: relative;
	top: 1.3em;
	width: 100%;
}
.ui-slider dt {
	top: 1.5em;
	position: absolute;
	padding-top: .2em;
	text-align: center;
	border-bottom: 1px dotted #ddd;
	height: .7em;
	color: #999;
}
.ui-slider dt span {
	background: #fff;
	padding: 0 .5em;
}
.ui-slider li, .ui-slider dd {
	position: absolute;
	overflow: visible;
	color: #666;
}
.ui-slider li span.ui-slider-label, .ui-slider dd span.ui-slider-label {
	display: none;
}
.ui-slider li span.ui-slider-label-show, .ui-slider dd span.ui-slider-label-show {
	display: block;
	font-size: 0.75em;
}
.ui-slider span.ui-slider-tic {
	position: absolute;
	left: 0;
	height: .8em;
	top: -1.3em;
}
.ui-slider li span.ui-component-content, .ui-slider dd span.ui-component-content {
	border-right: 0;
	border-left-width: 1px;
	border-left-style: dotted;
	border-top: 0;
	border-bottom: 0;
}
.ui-slider .first .ui-slider-tic, .ui-slider .last .ui-slider-tic {
	display: none;
}
.ui-slider {clear: both; top:1.2em; margin-bottom:2em;}


text:
package org.eclipse.webdav;

/**
 * Factory for constructing resource locators.
 *

 * Note: This class/interface is part of an interim API that is still under
 * development and expected to change significantly before reaching stability.
 * It is being made available at this early stage to solicit feedback from pioneering
 * adopters on the understanding that any code that uses this API will almost
 * certainly be broken (repeatedly) as the API evolves.
 *

 *
 * @see ILocator
 */
public interface ILocatorFactory {

    /**
     * Returns a locator with the given resource URL that
     * (implicitly) uses the standard way of resolving resource
     * URLs.
     *

     * Version-unaware clients use this kind of locator exclusively.
     *
     * @param resourceURL the URL identifier of the resource as a
     * String.
     */
    public ILocator newLocator(String resourceURL);

    /**
     * Returns a locator with the given resource URL and
     * label.
     *

     * This kind of locator is used only by version-aware clients.
     * It allows a versioning client to specify a version-controlled
     * resource URL and the label of a version in the corresponding
     * history.  The resulting locator identifies the
     * version.

     *

     * The resource URL MUST NOT be a stable URL.

     *
     * @param requestURL the String representation of
     * the version-controlled resource URL.
     * @param label the label of the version to select from the
     * corresponding history.
     */
    public ILocator newLocator(String requestURL, String label);

    /**
     * Returns a locator given a stable resource URL.
     *

     * This kind of locator is used only by version-aware clients.
     * The stable URL is generated by the server.  Clients may
     * reliably store the URL and use it to identify the same
     * resource in subsequent operations.  Resources identified by
     * a stable URL cannot be moved but they may be deleted.
     * The stable URL cannot be bound to a different resource
     * by the client or server).

     *

     * Note that locators with stable URLs cannot have also have a
     * label.

     *
     * @param resourceURL the stable URL to a versioning resource
     * as a String.
     */
    public ILocator newStableLocator(String resourceURL);
}


text:
<?php

require_once dirname(__FILE__) . '/../../TestHelper.php';

/** Zend_Log */
require_once 'Zend/Log.php';

/** Zend_Log_Writer_Mock */
require_once 'Zend/Log/Writer/Mock.php';

/** Zend_Log_Writer_Stream */
require_once 'Zend/Log/Writer/Stream.php';

/**
 * @category   Zend
 * @package    Zend_Log
 * @subpackage UnitTests
 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @group      Zend_Log
 */
class Zend_Log_LogTest extends PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        $this->log = fopen('php://memory', 'w+');
        $this->writer = new Zend_Log_Writer_Stream($this->log);
    }

    // Writers

    public function testWriterCanBeAddedWithConstructor()
    {
        $logger = new Zend_Log($this->writer);
        $logger->log($message = 'message-to-log', Zend_Log::INFO);

        rewind($this->log);
        $this->assertContains($message, stream_get_contents($this->log));
    }

    public function testAddWriter()
    {
        $logger = new Zend_Log();
        $logger->addWriter($this->writer);
        $logger->log($message = 'message-to-log', Zend_Log::INFO);

        rewind($this->log);
        $this->assertContains($message, stream_get_contents($this->log));
    }

    public function testAddWriterAddsMultipleWriters()
    {
        $logger = new Zend_Log();

        // create writers for two separate streams of temporary memory
        $log1    = fopen('php://memory', 'w+');
        $writer1 = new Zend_Log_Writer_Stream($log1);
        $log2    = fopen('php://memory', 'w+');
        $writer2 = new Zend_Log_Writer_Stream($log2);

        // add the writers
        $logger->addWriter($writer1);
        $logger->addWriter($writer2);

        // log to both writers
        $logger->log($message = 'message-sent-to-both-logs', Zend_Log::INFO);

        // verify both writers were called by the logger
        rewind($log1);
        $this->assertContains($message, stream_get_contents($log1));
        rewind($log2);
        $this->assertContains($message, stream_get_contents($log2));

        // prove the two memory streams are different
        // and both writers were indeed called
        fwrite($log1, 'foo');
        $this->assertNotEquals(ftell($log1), ftell($log2));
    }

    public function testLoggerThrowsWhenNoWriters()
    {
        $logger = new Zend_Log();
        try {
            $logger->log('message', Zend_Log::INFO);
            $this->fail();
        } catch (Zend_Log_Exception $e) {
            $this->assertRegexp('/no writer/i', $e->getMessage());
        }
    }

    public function testDestructorCallsShutdownOnEachWriter()
    {
        $writer1 = new Zend_Log_Writer_Mock();
        $writer2 = new Zend_Log_Writer_Mock();

        $logger = new Zend_Log();
        $logger->addWriter($writer1);
        $logger->addWriter($writer2);

        $this->assertFalse($writer1->shutdown);
        $this->assertFalse($writer2->shutdown);

        $logger = null;

        $this->assertTrue($writer1->shutdown);
        $this->assertTrue($writer2->shutdown);
    }

    // Priorities

    public function testLogThrowsOnBadLogPriority()
    {
        $logger = new Zend_Log($this->writer);
        try {
            $logger->log('foo', 42);
            $this->fail();
        } catch (Exception $e) {
            $this->assertType('Zend_Log_Exception', $e);
            $this->assertRegExp('/bad log priority/i', $e->getMessage());
        }
    }

    public function testLogThrough__callThrowsOnBadLogPriority()
    {
        $logger = new Zend_Log($this->writer);
        try {
            $logger->nonexistantPriority('');
            $this->fail();
        } catch (Exception $e) {
            $this->assertType('Zend_Log_Exception', $e);
            $this->assertRegExp('/bad log priority/i', $e->getMessage());
        }
    }

    public function testAddingPriorityThrowsWhenOverridingBuiltinLogPriority()
    {
        try {
            $logger = new Zend_Log($this->writer);
            $logger->addPriority('BOB', 0);
            $this->fail();
        } catch (Exception $e) {
            $this->assertType('Zend_Log_Exception', $e);
            $this->assertRegExp('/existing priorities/i', $e->getMessage());
        }

    }

    public function testAddLogPriority()
    {
        $logger = new Zend_Log($this->writer);
        $logger->addPriority('EIGHT', $priority = 8);

        $logger->eight($message = 'eight message');

        rewind($this->log);
        $logdata = stream_get_contents($this->log);
        $this->assertContains((string)$priority, $logdata);
        $this->assertContains($message, $logdata);
    }

    // Fields

    public function testLogWritesStandardFields() {
        $logger = new Zend_Log($mock = new Zend_Log_Writer_Mock);
        $logger->info('foo');

        $this->assertEquals(1, count($mock->events));
        $event = array_shift($mock->events);

        $standardFields = array_flip(array('timestamp', 'priority', 'priorityName', 'message'));
        $this->assertEquals(array(), array_diff_key($event, $standardFields));
    }

    public function testLogWritesAndOverwritesExtraFields() {
        $logger = new Zend_Log($mock = new Zend_Log_Writer_Mock);
        $logger->setEventItem('foo', 42);
        $logger->setEventItem($field = 'bar', $value = 43);
        $logger->info('foo');

        $this->assertEquals(1, count($mock->events));
        $event = array_shift($mock->events);

        $this->assertTrue(array_key_exists($field, $event));
        $this->assertEquals($value, $event[$field]);
    }

    /**
     * @group ZF-8491
     */
    public function testLogAcceptsExtrasParameterAsArrayAndPushesIntoEvent()
    {
        $logger = new Zend_Log($mock = new Zend_Log_Writer_Mock);
        $logger->info('foo', array('content' => 'nonesuch'));
        $event = array_shift($mock->events);
        $this->assertContains('content', array_keys($event));
        $this->assertEquals('nonesuch', $event['content']);
    }

    /**
     * @group ZF-8491
     */
    public function testLogNumericKeysInExtrasArrayArePassedToInfoKeyOfEvent()
    {
        $logger = new Zend_Log($mock = new Zend_Log_Writer_Mock);
        $logger->info('foo', array('content' => 'nonesuch', 'bar'));
        $event = array_shift($mock->events);
        $this->assertContains('content', array_keys($event));
        $this->assertContains('info', array_keys($event));
        $this->assertContains('bar', $event['info']);
    }

    /**
     * @group ZF-8491
     */
    public function testLogAcceptsExtrasParameterAsScalarAndAddsAsInfoKeyToEvent()
    {
        $logger = new Zend_Log($mock = new Zend_Log_Writer_Mock);
        $logger->info('foo', 'nonesuch');
        $event = array_shift($mock->events);
        $this->assertContains('info', array_keys($event));
        $info = $event['info'];
        $this->assertContains('nonesuch', $info);
    }

    // Factory

    public function testLogConstructFromConfigStream()
    {
        $cfg = array('log' => array('memory' => array(
            'writerName'      => "Stream",
            'writerNamespace' => "Zend_Log_Writer",
            'writerParams'    => array(
                'stream'      => "php://memory"
            )
        )));

        $logger = Zend_Log::factory($cfg['log']);
        $this->assertTrue($logger instanceof Zend_Log);
    }

    public function testLogConstructFromConfigStreamAndFilter()
    {
        $cfg = array('log' => array('memory' => array(
            'writerName'      => "Stream",
            'writerNamespace' => "Zend_Log_Writer",
            'writerParams'    => array(
                'stream'      => "php://memory"
            ),
            'filterName'   => "Priority",
            'filterParams' => array(
                'priority' => "Zend_Log::CRIT",
                'operator' => "<="
             ),
        )));

        $logger = Zend_Log::factory($cfg['log']);
        $this->assertTrue($logger instanceof Zend_Log);
    }

    public function testFactoryUsesNameAndNamespaceWithoutModifications()
    {
        $cfg = array('log' => array('memory' => array(
            'writerName'      => "ZendMonitor",
            'writerNamespace' => "Zend_Log_Writer",
        )));

        $logger = Zend_Log::factory($cfg['log']);
        $this->assertTrue($logger instanceof Zend_Log);
    }

    /**
     * @group ZF-9192
     */
    public function testUsingWithErrorHandler()
    {
        $writer = new Zend_Log_Writer_Mock();

        $logger = new Zend_Log();
        $logger->addWriter($writer);
        $this->errWriter = $writer;

        $oldErrorLevel = error_reporting();

        $this->expectingLogging = true;
        error_reporting(E_ALL | E_STRICT);

        $oldHandler = set_error_handler(array($this, 'verifyHandlerData'));
        $logger->registerErrorHandler();

        trigger_error("Testing notice shows up in logs", E_USER_NOTICE);
        trigger_error("Testing warning shows up in logs", E_USER_WARNING);
        trigger_error("Testing error shows up in logs", E_USER_ERROR);

        $this->expectingLogging = false;
        error_reporting(0);

        trigger_error("Testing notice misses logs", E_USER_NOTICE);
        trigger_error("Testing warning misses logs", E_USER_WARNING);
        trigger_error("Testing error misses logs", E_USER_ERROR);

        restore_error_handler(); // Pop off the Logger
        restore_error_handler(); // Pop off the verifyHandlerData
        error_reporting($oldErrorLevel); // Restore original reporting level
        unset($this->errWriter);
    }

    /**
     * @group ZF-9192
     * Used by testUsingWithErrorHandler -
     * verifies that the data written to the original logger is the same as the data written in Zend_Log
     */
    public function verifyHandlerData($errno, $errstr, $errfile, $errline, $errcontext)
    {
        if ($this->expectingLogging) {
            $this->assertFalse(empty($this->errWriter->events));
            $event = array_shift($this->errWriter->events);
            $this->assertEquals($errstr, $event['message']);
            $this->assertEquals($errno, $event['errno']);
            $this->assertEquals($errfile, $event['file']);
            $this->assertEquals($errline, $event['line']);
        } else {
            $this->assertTrue(empty($this->errWriter->events));
        }
    }

    /**
     * @group ZF-9870
     */
    public function testSetAndGetTimestampFormat()
    {
        $logger = new Zend_Log($this->writer);
        $this->assertEquals('c', $logger->getTimestampFormat());
        $this->assertSame($logger, $logger->setTimestampFormat('Y-m-d H:i:s'));
        $this->assertEquals('Y-m-d H:i:s', $logger->getTimestampFormat());
    }

    /**
     * @group ZF-9870
     */
    public function testLogWritesWithModifiedTimestampFormat()
    {
        $logger = new Zend_Log($this->writer);
        $logger->setTimestampFormat('Y-m-d');
        $logger->debug('ZF-9870');
        rewind($this->log);
        $message = stream_get_contents($this->log);
        $this->assertEquals(date('Y-m-d'), substr($message, 0, 10));
    }
}


text:
package com.alibaba.json.test.performance.case1;

import java.io.InputStream;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import junit.framework.TestCase;

import org.apache.commons.io.IOUtils;

import com.alibaba.json.test.codec.Codec;
import com.alibaba.json.test.codec.SimpleJsonCodec;

public class IntObjectEncodePerformanceTest extends TestCase {

    private String    text;
    private final int COUNT = 1000 * 100;
    private Object    object;

    protected void setUp() throws Exception {
        String resource = "json/int_array_1000.json";
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource);
        text = IOUtils.toString(is);
        is.close();

        // text = "{\"age\":9223372036854775807}";
        // object = JSON.parseObject(text, Long_100_Entity.class);
        // object = JSON.parseArray(text);
        {
            ArrayList<Long> array = new ArrayList<Long>();
            for (long i = 0; i < 1000; ++i) {
                array.add(i);
            }
            object = array;
        }
    }

    public void test_encodeObject() throws Exception {
        List<Codec> decoders = new ArrayList<Codec>();
        // decoders.add(new FastjsonDecoderImpl());
        // decoders.add(new JacksonDecoderImpl());
        decoders.add(new SimpleJsonCodec());
        // decoders.add(new JsonLibDecoderImpl());

        for (int i = 0; i < 10; ++i) {
            for (Codec decoder : decoders) {
                encode(object, decoder);
            }
            // System.out.println();
        }
        // System.out.println();
        // System.out.println(text);
    }

    public void encode(Object object, Codec decoder) throws Exception {
        long startNano = System.nanoTime();
        for (int i = 0; i < COUNT; ++i) {
            decoder.encode(object);
        }
        long nano = System.nanoTime() - startNano;
        System.out.println(decoder.getName() + " : \t" + NumberFormat.getInstance().format(nano));
    }
}


text:
enum {
    OBTOKENIZER_PARSE_STRINGS = 1 << 0
};

typedef struct {
    obscanner_scanner_t scanner;
    obscanner_char_t    last_ch;

    size_t spec_char_n;
    char   *spec_chars;

    int flags;
} obtokenizer_tokenizer_t;

OBSCANNER_DECL
(
 int obtokenizer_init(obtokenizer_tokenizer_t *tokenizer, const char *str);
 int obtokenizer_initn(obtokenizer_tokenizer_t *tokenizer, const char *str, size_t n);
 int obtokenizer_add_spec_char(obtokenizer_tokenizer_t *tokenizer, char sch);
 int obtokenizer_get(obtokenizer_tokenizer_t *tokenizer, obtokenizer_token_t *token);
)

#endif


text:
'use strict';

var nullthrows = function<T>(
  x: ?T,
  message?: string = 'Got unexpected null or undefined',
): T {
  if (x != null) {
    return x;
  }
  var error = new Error(message);
  (error: any).framesToPop = 1; // Skip nullthrows own stack frame.
  throw error;
};

module.exports = nullthrows;


text:
#include <aws/devops-guru/model/AnomalyReportedTimeRange.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace DevOpsGuru
{
namespace Model
{

AnomalyReportedTimeRange::AnomalyReportedTimeRange() :
    m_openTimeHasBeenSet(false),
    m_closeTimeHasBeenSet(false)
{
}

AnomalyReportedTimeRange::AnomalyReportedTimeRange(JsonView jsonValue) :
    m_openTimeHasBeenSet(false),
    m_closeTimeHasBeenSet(false)
{
  *this = jsonValue;
}

AnomalyReportedTimeRange& AnomalyReportedTimeRange::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("OpenTime"))
  {
    m_openTime = jsonValue.GetDouble("OpenTime");

    m_openTimeHasBeenSet = true;
  }

  if(jsonValue.ValueExists("CloseTime"))
  {
    m_closeTime = jsonValue.GetDouble("CloseTime");

    m_closeTimeHasBeenSet = true;
  }

  return *this;
}

JsonValue AnomalyReportedTimeRange::Jsonize() const
{
  JsonValue payload;

  if(m_openTimeHasBeenSet)
  {
   payload.WithDouble("OpenTime", m_openTime.SecondsWithMSPrecision());
  }

  if(m_closeTimeHasBeenSet)
  {
   payload.WithDouble("CloseTime", m_closeTime.SecondsWithMSPrecision());
  }

  return payload;
}

} // namespace Model
} // namespace DevOpsGuru
} // namespace Aws


text:
package io.jitstatic.injection.executors;

import static org.junit.jupiter.api.Assertions.*;

import java.util.concurrent.ExecutorService;

import org.junit.jupiter.api.Test;

import com.codahale.metrics.MetricRegistry;

class WorkStealerFactoryTest {

    @Test
    void testRegistration() {
        WorkStealerFactory def = new WorkStealerFactory(new MetricRegistry());
        ExecutorService executorService = def.provide();
        assertNotNull(executorService);
        assertFalse(executorService.isTerminated());
        def.dispose(executorService);
        assertTrue(executorService.isShutdown());
        assertTrue(executorService.isTerminated());
    }

    @Test
    public void testAnnotation() {
        assertSame(WorkStealerAnnotation.INSTANCE, WorkStealerAnnotation.INSTANCE);
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="text_size_1">12sp</dimen>
</resources>


text:
import {
  Attribute,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  ContentChild,
  ContentChildren,
  Directive,
  ElementRef,
  EmbeddedViewRef,
  Input,
  IterableChangeRecord,
  IterableDiffer,
  IterableDiffers,
  NgIterable,
  QueryList,
  Renderer2,
  ViewChild,
  ViewContainerRef,
  ViewEncapsulation
} from '@angular/core';
import {CollectionViewer, DataSource} from './data-source';
import {CdkCellOutlet, CdkCellOutletRowContext, CdkHeaderRowDef, CdkRowDef} from './row';
import {Observable} from 'rxjs/Observable';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import 'rxjs/add/operator/let';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/observable/combineLatest';
import {Subscription} from 'rxjs/Subscription';
import {Subject} from 'rxjs/Subject';
import {CdkCellDef, CdkColumnDef, CdkHeaderCellDef} from './cell';

/**
 * Returns an error to be thrown when attempting to find an unexisting column.
 * @param id Id whose lookup failed.
 * @docs-private
 */
export function getDataTableUnknownColumnError(id: string) {
  return new Error(`md-data-table: Could not find column with id "${id}".`);
}

/**
 * Provides a handle for the table to grab the view container's ng-container to insert data rows.
 * @docs-private
 */
@Directive({selector: '[rowPlaceholder]'})
export class RowPlaceholder {
  constructor(public viewContainer: ViewContainerRef) { }
}

/**
 * Provides a handle for the table to grab the view container's ng-container to insert the header.
 * @docs-private
 */
@Directive({selector: '[headerRowPlaceholder]'})
export class HeaderRowPlaceholder {
  constructor(public viewContainer: ViewContainerRef) { }
}

/**
 * A data table that connects with a data source to retrieve data of type T and renders
 * a header row and data rows. Updates the rows when new data is provided by the data source.
 */
@Component({
  selector: 'cdk-table',
  template: `
    <ng-container headerRowPlaceholder></ng-container>
    <ng-container rowPlaceholder></ng-container>
  `,
  host: {
    'class': 'cdk-table',
  },
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CdkTable<T> implements CollectionViewer {
  /** Subject that emits when the component has been destroyed. */
  private _onDestroy = new Subject<void>();

  /** Flag set to true after the component has been initialized. */
  private _isViewInitialized = false;

  /** Latest data provided by the data source through the connect interface. */
  private _data: NgIterable<T> = [];

  /** Subscription that listens for the data provided by the data source. */
  private _renderChangeSubscription: Subscription;

  /**
   * Map of all the user's defined columns identified by name.
   * Contains the header and data-cell templates.
   */
  private _columnDefinitionsByName = new Map<string,  CdkColumnDef>();

  /** Differ used to find the changes in the data provided by the data source. */
  private _dataDiffer: IterableDiffer<T>;

  // TODO(andrewseguin): Remove max value as the end index
  //   and instead calculate the view on init and scroll.
  /**
   * Stream containing the latest information on what rows are being displayed on screen.
   * Can be used by the data source to as a heuristic of what data should be provided.
   */
  viewChange =
      new BehaviorSubject<{start: number, end: number}>({start: 0, end: Number.MAX_VALUE});

  /**
   * Provides a stream containing the latest data array to render. Influenced by the table's
   * stream of view window (what rows are currently on screen).
   */
  @Input()
  get dataSource(): DataSource<T> { return this._dataSource; }
  set dataSource(dataSource: DataSource<T>) {
    if (this._dataSource !== dataSource) {
      this._switchDataSource(dataSource);
    }
  }
  private _dataSource: DataSource<T>;

  // Placeholders within the table's template where the header and data rows will be inserted.
  @ViewChild(RowPlaceholder) _rowPlaceholder: RowPlaceholder;
  @ViewChild(HeaderRowPlaceholder) _headerRowPlaceholder: HeaderRowPlaceholder;

  /**
   * The column definitions provided by the user that contain what the header and cells should
   * render for each column.
   */
  @ContentChildren(CdkColumnDef) _columnDefinitions: QueryList<CdkColumnDef>;

  /** Template used as the header container. */
  @ContentChild(CdkHeaderRowDef) _headerDefinition: CdkHeaderRowDef;

  /** Set of templates that used as the data row containers. */
  @ContentChildren(CdkRowDef) _rowDefinitions: QueryList<CdkRowDef>;

  constructor(private readonly _differs: IterableDiffers,
              private readonly _changeDetectorRef: ChangeDetectorRef,
              elementRef: ElementRef,
              renderer: Renderer2,
              @Attribute('role') role: string) {
    // Show the stability warning of the data-table only if it doesn't run inside of jasmine.
    // This is just temporary and should reduce warnings when running the tests.
    if (!(typeof window !== 'undefined' && window['jasmine'])) {
      console.warn('The data table is still in active development ' +
          'and should be considered unstable.');
    }

    if (!role) {
      renderer.setAttribute(elementRef.nativeElement, 'role', 'grid');
    }

    // TODO(andrewseguin): Add trackby function input.
    // Find and construct an iterable differ that can be used to find the diff in an array.
    this._dataDiffer = this._differs.find(this._data).create();
  }

  ngOnDestroy() {
    this._onDestroy.next();
    this._onDestroy.complete();
  }

  ngOnInit() {
    // TODO(andrewseguin): Setup a listener for scroll events
    //   and emit the calculated view to this.viewChange
  }

  ngAfterContentInit() {
    // TODO(andrewseguin): Throw an error if two columns share the same name
    this._columnDefinitions.forEach(columnDef => {
      this._columnDefinitionsByName.set(columnDef.name, columnDef);
    });

    // Re-render the rows if any of their columns change.
    // TODO(andrewseguin): Determine how to only re-render the rows that have their columns changed.
    Observable.merge(...this._rowDefinitions.map(rowDef => rowDef.columnsChange))
        .takeUntil(this._onDestroy)
        .subscribe(() => {
          // Reset the data to an empty array so that renderRowChanges will re-render all new rows.
          this._rowPlaceholder.viewContainer.clear();
          this._dataDiffer.diff([]);
          this._renderRowChanges();
        });

    // Re-render the header row if the columns change
    this._headerDefinition.columnsChange
        .takeUntil(this._onDestroy)
        .subscribe(() => {
          this._headerRowPlaceholder.viewContainer.clear();
          this._renderHeaderRow();
        });
  }

  ngAfterViewInit() {
    this._isViewInitialized = true;
    this._renderHeaderRow();
  }

  ngDoCheck() {
    if (this._isViewInitialized && this.dataSource && !this._renderChangeSubscription) {
      this._observeRenderChanges();
    }
  }

  /**
   * Switch to the provided data source by resetting the data and unsubscribing from the current
   * render change subscription if one exists. If the data source is null, interpret this by
   * clearing the row placeholder. Otherwise start listening for new data.
   */
  private _switchDataSource(dataSource: DataSource<T>) {
    this._data = [];
    this._dataSource = dataSource;

    if (this._isViewInitialized) {
      if (this._renderChangeSubscription) {
        this._renderChangeSubscription.unsubscribe();
      }

      if (this._dataSource) {
        this._observeRenderChanges();
      } else {
        this._rowPlaceholder.viewContainer.clear();
      }
    }
  }

  /** Set up a subscription for the data provided by the data source. */
  private _observeRenderChanges() {
    this._renderChangeSubscription = this.dataSource.connect(this)
        .takeUntil(this._onDestroy)
        .subscribe(data => {
          this._data = data;
          this._renderRowChanges();
        });
  }

  /**
   * Create the embedded view for the header template and place it in the header row view container.
   */
  private _renderHeaderRow() {
    const cells = this._getHeaderCellTemplatesForRow(this._headerDefinition);
    if (!cells.length) { return; }

    // TODO(andrewseguin): add some code to enforce that exactly
    //   one CdkCellOutlet was instantiated as a result
    //   of `createEmbeddedView`.
    this._headerRowPlaceholder.viewContainer
        .createEmbeddedView(this._headerDefinition.template, {cells});

    cells.forEach(cell => {
      CdkCellOutlet.mostRecentCellOutlet._viewContainer.createEmbeddedView(cell.template, {});
    });

    this._changeDetectorRef.markForCheck();
  }

  /** Check for changes made in the data and render each change (row added/removed/moved). */
  private _renderRowChanges() {
    const changes = this._dataDiffer.diff(this._data);
    if (!changes) { return; }

    const viewContainer = this._rowPlaceholder.viewContainer;
    changes.forEachOperation(
        (item: IterableChangeRecord<any>, adjustedPreviousIndex: number, currentIndex: number) => {
          if (item.previousIndex == null) {
            this._insertRow(this._data[currentIndex], currentIndex);
          } else if (currentIndex == null) {
            viewContainer.remove(adjustedPreviousIndex);
          } else {
            const view = viewContainer.get(adjustedPreviousIndex);
            viewContainer.move(view!, currentIndex);
          }
        });

    this._updateRowContext();
  }

  /**
   * Create the embedded view for the data row template and place it in the correct index location
   * within the data row view container.
   */
  private _insertRow(rowData: T, index: number) {
    // TODO(andrewseguin): Add when predicates to the row definitions
    //   to find the right template to used based on
    //   the data rather than choosing the first row definition.
    const row = this._rowDefinitions.first;

    // Row context that will be provided to both the created embedded row view and its cells.
    const context: CdkCellOutletRowContext<T> = {$implicit: rowData};

    // TODO(andrewseguin): add some code to enforce that exactly one
    //   CdkCellOutlet was instantiated as a result  of `createEmbeddedView`.
    this._rowPlaceholder.viewContainer.createEmbeddedView(row.template, context, index);

    // Insert empty cells if there is no data to improve rendering time.
    const cells = rowData ? this._getCellTemplatesForRow(row) : [];

    cells.forEach(cell => {
      CdkCellOutlet.mostRecentCellOutlet._viewContainer.createEmbeddedView(cell.template, context);
    });

    this._changeDetectorRef.markForCheck();
  }

  /**
   * Updates the context for each row to reflect any data changes that may have caused
   * rows to be added, removed, or moved. The view container contains the same context
   * that was provided to each of its cells.
   */
  private _updateRowContext() {
    const viewContainer = this._rowPlaceholder.viewContainer;
    for (let index = 0, count = viewContainer.length; index < count; index++) {
      const viewRef = viewContainer.get(index) as EmbeddedViewRef<CdkCellOutletRowContext<T>>;
      viewRef.context.index = index;
      viewRef.context.count = count;
      viewRef.context.first = index === 0;
      viewRef.context.last = index === count - 1;
      viewRef.context.even = index % 2 === 0;
      viewRef.context.odd = index % 2 !== 0;
    }
  }

  /**
   * Returns the cell template definitions to insert into the header
   * as defined by its list of columns to display.
   */
  private _getHeaderCellTemplatesForRow(headerDef: CdkHeaderRowDef): CdkHeaderCellDef[] {
    return headerDef.columns.map(columnId => {
      const column = this._columnDefinitionsByName.get(columnId);

      if (!column) {
        throw getDataTableUnknownColumnError(columnId);
      }

      return column.headerCell;
    });
  }

  /**
   * Returns the cell template definitions to insert in the provided row
   * as defined by its list of columns to display.
   */
  private _getCellTemplatesForRow(rowDef: CdkRowDef): CdkCellDef[] {
    return rowDef.columns.map(columnId => {
      const column = this._columnDefinitionsByName.get(columnId);

      if (!column) {
        throw getDataTableUnknownColumnError(columnId);
      }

      return column.cell;
    });
  }
}


text:
package com.gs.fw.common.mithra.attribute;

import com.gs.fw.common.mithra.AggregateAttribute;
import com.gs.fw.common.mithra.MithraDataObject;
import com.gs.fw.common.mithra.attribute.update.AttributeUpdateWrapper;
import com.gs.fw.common.mithra.attribute.update.ByteArrayUpdateWrapper;
import com.gs.fw.common.mithra.databasetype.DatabaseType;
import com.gs.fw.common.mithra.extractor.ByteArrayExtractor;
import com.gs.fw.common.mithra.extractor.Extractor;
import com.gs.fw.common.mithra.finder.Operation;
import com.gs.fw.common.mithra.finder.bytearray.ByteArrayEqOperation;
import com.gs.fw.common.mithra.finder.bytearray.ByteArraySet;
import com.gs.fw.common.mithra.finder.orderby.ByteArrayOrderBy;
import com.gs.fw.common.mithra.finder.orderby.OrderBy;
import com.gs.fw.common.mithra.util.HashUtil;

import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.Format;
import java.text.ParseException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;

public abstract class ByteArrayAttribute<Owner> extends NonPrimitiveAttribute<Owner, byte[]> implements com.gs.fw.finder.attribute.ByteArrayAttribute<Owner>, ByteArrayExtractor<Owner, byte[]>
{
    private int maxLength = Integer.MAX_VALUE;
    private transient OrderBy ascendingOrderBy;
    private transient OrderBy descendingOrderBy;

    private static final long serialVersionUID = -2871034560645486938L;

    public ByteArrayAttribute(int maxLength)
    {
        this.maxLength = maxLength;
    }

    public ByteArrayAttribute()
    {
    }

    @Override
    protected void serializedNonNullValue(Owner o, ObjectOutput out) throws IOException
    {
        byte[] bytes = this.byteArrayValueOf(o);
        out.writeInt(bytes.length);
        out.write(bytes);
    }

    @Override
    protected void deserializedNonNullValue(Owner o, ObjectInput in) throws IOException
    {
        int len = in.readInt();
        byte[] bytes = new byte[len];
        in.readFully(bytes);
        this.setByteArrayValue(o, bytes);
    }

    public int getMaxLength()
    {
        return maxLength;
    }

    protected void setMaxLength(int maxLength)
    {
        this.maxLength = maxLength;
    }

    @Override
    public int valueHashCode(Owner o)
    {
        byte[] bytes = this.byteArrayValueOf(o);
        if (bytes == null)
        {
            return HashUtil.NULL_HASH;
        }
        return HashUtil.hash(bytes);
    }

    @Override
    public boolean valueEquals(Owner first, Owner second)
    {
        if (first == second)
        {
            return true;
        }
        boolean firstNull = this.isAttributeNull(first);
        boolean secondNull = this.isAttributeNull(second);
        if (firstNull)
        {
            return secondNull;
        }
        return ByteArrayEqOperation.byteArrayEquals(this.valueOf(first), this.valueOf(second));
    }

    @Override
    public <O> boolean valueEquals(Owner first, O second, Extractor<O, byte[]> secondExtractor)
    {
        boolean firstNull = this.isAttributeNull(first);
        boolean secondNull = secondExtractor.isAttributeNull(second);
        if (firstNull != secondNull)
        {
            return false;
        }
        if (!firstNull)
        {
            return ByteArrayEqOperation.byteArrayEquals(this.valueOf(first), secondExtractor.valueOf(second));
        }
        return true;
    }

    @Override
    public Operation in(final List objects, final Extractor extractor)
    {
        final ByteArraySet set = new ByteArraySet();
        for (int i = 0, n = objects.size(); i < n; i++)
        {
            final Object o = extractor.valueOf(objects.get(i));
            if (o != null)
            {
                set.add((byte[]) o);
            }
        }
        return this.in(set);
    }

    @Override
    public Operation in(final Iterable objects, final Extractor extractor)
    {
        final ByteArraySet set = new ByteArraySet();
        for (Object object : objects)
        {
            final Object o = extractor.valueOf(object);
            if (o != null)
            {
                set.add((byte[]) o);
            }
        }
        return this.in(set);
    }

    @Override
    public Operation nonPrimitiveEq(Object other)
    {
        return this.eq((byte[]) other);
    }

    @Override
    public OrderBy ascendingOrderBy()
    {
        if (this.ascendingOrderBy == null)
        {
            this.ascendingOrderBy = new ByteArrayOrderBy(this, true);
        }
        return this.ascendingOrderBy;
    }

    @Override
    public OrderBy descendingOrderBy()
    {
        if (this.descendingOrderBy == null)
        {
            this.descendingOrderBy = new ByteArrayOrderBy(this, false);
        }
        return this.descendingOrderBy;
    }

    @Override
    public abstract Operation eq(byte[] other);

    // join operation:
    /**
     * @deprecated  use joinEq or filterEq instead
     * @param other Attribute to join to
     * @return Operation corresponding to the join
     **/
    @Deprecated
    public abstract Operation eq(ByteArrayAttribute other);

    public abstract Operation joinEq(ByteArrayAttribute other);

    public abstract Operation filterEq(ByteArrayAttribute other);

    @Override
    public Operation notEq(byte[] other)
    {
        throw new UnsupportedOperationException("notEq is not supported for byte array attributes");
    }

    @Override
    public Operation in(Set<byte[]> set)
    {
        return this.in((ByteArraySet) set);
    }

    @Override
    public Operation notIn(Set<byte[]> set)
    {
        return this.notIn((ByteArraySet) set);
    }

    public abstract Operation in(ByteArraySet set);

    public abstract Operation notIn(ByteArraySet set);

    @Override
    protected Set newSetForInClause()
    {
        return new ByteArraySet();
    }

    @Override
    public void setSqlParameter(int index, PreparedStatement ps, Object o, TimeZone databaseTimeZone, DatabaseType databaseType) throws SQLException
    {
        ps.setBytes(index, (byte[]) o);
    }

    public byte[] valueOf(Owner o)
    {
        return this.byteArrayValueOf(o);
    }

    public abstract byte[] byteArrayValueOf(Owner o);

    public void setValue(Owner o, byte[] newValue)
    {
        this.setByteArrayValue(o, newValue);
    }

    public abstract void setByteArrayValue(Owner o, byte[] bytes);

    @Override
    public Class valueType()
    {
        return byte[].class;
    }

    @Override
    public void parseStringAndSet(String value, Owner data, int lineNumber, Format format) throws ParseException
    {
        this.parseWordAndSet(value, data, lineNumber);
    }

    @Override
    public void parseWordAndSet(String word, Owner data, int lineNumber) throws ParseException
    {
        if (word.equals("null"))
        {
            this.setValueNull(data);
        }
        else
        {
            if (word.length() % 2 > 0)
            {
                throw new ParseException(
                        "Could not parse " + word + " on line " + lineNumber
                                + " because it has to have an even number of hex digits", 0
                );
            }

            byte[] parsedBytes = new byte[word.length() / 2];
            for (int i = 0; i < word.length(); i += 2)
            {
                parsedBytes[i / 2] = parseByte(word.charAt(i), word.charAt(i + 1), lineNumber);
            }

            this.setByteArrayValue(data, parsedBytes);
        }
    }

    private byte parseByte(char first, char second, int lineNumber) throws ParseException
    {
        int result = getIntFromChar(first, lineNumber) * 16 + getIntFromChar(second, lineNumber);
        if (result > 127)
        {
            result -= -256;
        }
        return (byte) (result & 0xFF);
    }

    private int getIntFromChar(char first, int lineNumber) throws ParseException
    {
        if (first >= '0' && first <= '9')
        {
            return first - '0';
        }
        if (first >= 'A' && first <= 'F')
        {
            return first - 'A' + 10;
        }
        throw new ParseException("Could not parse '" + first + "' character on line " + lineNumber, 0);
    }

    @Override
    public void setValueUntil(Owner o, byte[] newValue, Timestamp exclusiveUntil)
    {
        this.setUntil(o, newValue, exclusiveUntil);
    }

    protected void setUntil(Object o, byte[] bytes, Timestamp exclusiveUntil)
    {
        throw new RuntimeException("not implemented");
    }

    public String valueOfAsString(Owner object, Formatter formatter)
    {
        byte[] bytes = this.byteArrayValueOf(object);

        StringBuilder buffer = new StringBuilder();
        for (int i = 0; i < bytes.length; i++)
        {
            buffer.append(formatter.format(bytes[i]));
        }

        return buffer.toString();
    }

    @Override
    public int zCountUniqueInstances(MithraDataObject[] dataObjects)
    {
        if (this.isAttributeNull((Owner) dataObjects[0]))
        {
            return 1;
        }
        byte[] firstValue = this.valueOf((Owner) dataObjects[0]);
        ByteArraySet set = null;
        for (int i = 1; i < dataObjects.length; i++)
        {
            byte[] nextValue = this.valueOf((Owner) dataObjects[i]);
            if (set != null)
            {
                set.add(nextValue);
            }
            else if (!ByteArrayEqOperation.byteArrayEquals(nextValue, firstValue))
            {
                set = new ByteArraySet();
                set.add(firstValue);
                set.add(nextValue);
            }
        }
        if (set != null)
        {
            return set.size();
        }
        return 1;
    }

    @Override
    public AggregateAttribute min()
    {
        throw new RuntimeException("not implemented");
    }

    @Override
    public AggregateAttribute max()
    {
        throw new RuntimeException("not implemented");
    }

    @Override
    public String zGetSqlForDatabaseType(DatabaseType databaseType)
    {
        throw new RuntimeException("not implemented");
    }

    @Override
    public AttributeUpdateWrapper zConstructNullUpdateWrapper(MithraDataObject data)
    {
        return new ByteArrayUpdateWrapper(this, data, null);
    }

    @Override
    public Operation zGetPrototypeOperation(Map<Attribute, Object> tempOperationPool)
    {
        return this.eq(new byte[0]);
    }
}


text:
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <title>{{ if .Params.seo_title }}{{ .Params.seo_title }}{{ else }}{{ .Title }} — {{ .Site.Title }}{{ end }}</title>

    {{ "<!--[if !IE]> -->" | safeHTML }}
    <link rel="stylesheet"
          href="//cloud.typography.com/6102252/617726/css/fonts.css">
    <link rel="stylesheet"
          href="//maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
    <!-- inject:css -->
    <link rel="stylesheet" href="/css/main-bd79d11cb5.min.css">
    <!-- endinject -->{{ "<!-- <![endif]-->" | safeHTML }}

    <link rel="canonical" href="{{ .Permalink }}">
    <link rel="publisher" href="https://plus.google.com/+Lengstorf">
    <meta property="fb:admins" content="1468448880" />
    <meta name="p:domain_verify" content="96778d384f05c0f6fadda46a947404b8"/>

    {{ partial "head/seo/schema.html" . }}
    {{ partial "head/seo/open-graph.html" . }}
    {{ partial "head/seo/twitter-cards.html" . }}
    {{ partial "head/favicon.html" . }}
    {{ partial "head/rss.html" . }}
    {{ partial "head/google-analytics.html" . }}
  </head>


text:
package cz.metacentrum.perun.core.implApi.modules.attributes;

import cz.metacentrum.perun.audit.events.AuditEvent;
import cz.metacentrum.perun.core.api.Attribute;
import cz.metacentrum.perun.core.api.AttributeDefinition;
import cz.metacentrum.perun.core.api.Member;
import cz.metacentrum.perun.core.api.exceptions.InternalErrorException;
import cz.metacentrum.perun.core.impl.PerunSessionImpl;

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

/**
 * Abstract class for Member Virtual Attributes modules.
 * Implements methods for modules to perform default function.
 * In the function that the method in the module does nothing, it is not necessary to implement it, simply extend this abstract class.
 *
 * @author Michal Stava <stavamichal@gmail.com>
 *
 */
public abstract class MemberVirtualAttributesModuleAbstract extends MemberAttributesModuleAbstract implements MemberVirtualAttributesModuleImplApi{

	public Attribute getAttributeValue(PerunSessionImpl perunSession, Member member, AttributeDefinition attribute) throws InternalErrorException {
		return new Attribute(attribute);
	}

	public boolean setAttributeValue(PerunSessionImpl perunSession, Member member, Attribute attribute) {
		return false;
	}

	public void removeAttributeValue(PerunSessionImpl perunSession, Member member, AttributeDefinition attribute) throws InternalErrorException {

	}

	@Override
	public List<AuditEvent> resolveVirtualAttributeValueChange(PerunSessionImpl perunSession, AuditEvent message) {
		return new ArrayList<>();
	}

	@Override
	public List<String> getStrongDependencies() {
		List<String> dependecies = new ArrayList<>();
		return dependecies;
	}
}


text:
<?php
namespace <%= appName %>;

class Example {

	public function run() {
		echo 'Application is running';
	}
}