text:
package com.gs.collections.impl.bag.immutable;

import java.util.Collection;
import java.util.Collections;

import com.gs.collections.api.bag.ImmutableBag;
import com.gs.collections.api.bag.MutableBag;
import com.gs.collections.api.bag.primitive.ImmutableBooleanBag;
import com.gs.collections.api.bag.primitive.ImmutableByteBag;
import com.gs.collections.api.bag.primitive.ImmutableCharBag;
import com.gs.collections.api.bag.primitive.ImmutableDoubleBag;
import com.gs.collections.api.bag.primitive.ImmutableFloatBag;
import com.gs.collections.api.bag.primitive.ImmutableIntBag;
import com.gs.collections.api.bag.primitive.ImmutableLongBag;
import com.gs.collections.api.bag.primitive.ImmutableShortBag;
import com.gs.collections.api.block.function.Function;
import com.gs.collections.api.block.function.Function2;
import com.gs.collections.api.block.function.primitive.BooleanFunction;
import com.gs.collections.api.block.function.primitive.ByteFunction;
import com.gs.collections.api.block.function.primitive.CharFunction;
import com.gs.collections.api.block.function.primitive.DoubleFunction;
import com.gs.collections.api.block.function.primitive.DoubleObjectToDoubleFunction;
import com.gs.collections.api.block.function.primitive.FloatFunction;
import com.gs.collections.api.block.function.primitive.FloatObjectToFloatFunction;
import com.gs.collections.api.block.function.primitive.IntFunction;
import com.gs.collections.api.block.function.primitive.IntObjectToIntFunction;
import com.gs.collections.api.block.function.primitive.LongFunction;
import com.gs.collections.api.block.function.primitive.LongObjectToLongFunction;
import com.gs.collections.api.block.function.primitive.ShortFunction;
import com.gs.collections.api.block.predicate.Predicate;
import com.gs.collections.api.block.predicate.Predicate2;
import com.gs.collections.api.block.procedure.Procedure;
import com.gs.collections.api.block.procedure.primitive.ObjectIntProcedure;
import com.gs.collections.api.collection.MutableCollection;
import com.gs.collections.api.collection.primitive.MutableBooleanCollection;
import com.gs.collections.api.collection.primitive.MutableByteCollection;
import com.gs.collections.api.collection.primitive.MutableCharCollection;
import com.gs.collections.api.collection.primitive.MutableDoubleCollection;
import com.gs.collections.api.collection.primitive.MutableFloatCollection;
import com.gs.collections.api.collection.primitive.MutableIntCollection;
import com.gs.collections.api.collection.primitive.MutableLongCollection;
import com.gs.collections.api.collection.primitive.MutableShortCollection;
import com.gs.collections.api.list.ImmutableList;
import com.gs.collections.api.list.MutableList;
import com.gs.collections.api.multimap.MutableMultimap;
import com.gs.collections.api.partition.bag.PartitionImmutableBag;
import com.gs.collections.api.partition.bag.PartitionMutableBag;
import com.gs.collections.api.tuple.primitive.ObjectIntPair;
import com.gs.collections.impl.Counter;
import com.gs.collections.impl.bag.mutable.primitive.BooleanHashBag;
import com.gs.collections.impl.bag.mutable.primitive.ByteHashBag;
import com.gs.collections.impl.bag.mutable.primitive.CharHashBag;
import com.gs.collections.impl.bag.mutable.primitive.DoubleHashBag;
import com.gs.collections.impl.bag.mutable.primitive.FloatHashBag;
import com.gs.collections.impl.bag.mutable.primitive.IntHashBag;
import com.gs.collections.impl.bag.mutable.primitive.LongHashBag;
import com.gs.collections.impl.bag.mutable.primitive.ShortHashBag;
import com.gs.collections.impl.block.factory.Functions;
import com.gs.collections.impl.block.factory.Predicates;
import com.gs.collections.impl.collection.immutable.AbstractImmutableCollection;
import com.gs.collections.impl.factory.Bags;
import com.gs.collections.impl.factory.Lists;
import com.gs.collections.impl.list.mutable.FastList;
import com.gs.collections.impl.partition.bag.PartitionHashBag;
import com.gs.collections.impl.tuple.primitive.PrimitiveTuples;
import com.gs.collections.impl.utility.Iterate;

/**
 * @since 1.0
 */
public abstract class AbstractImmutableBag<T>
        extends AbstractImmutableCollection<T>
        implements ImmutableBag<T>
{
    @Override
    protected MutableCollection<T> newMutable(int size)
    {
        return Bags.mutable.empty();
    }

    public ImmutableBag<T> tap(Procedure<? super T> procedure)
    {
        this.forEach(procedure);
        return this;
    }

    @Override
    public <R extends Collection<T>> R select(final Predicate<? super T> predicate, final R target)
    {
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                if (predicate.accept(each))
                {
                    for (int i = 0; i < occurrences; i++)
                    {
                        target.add(each);
                    }
                }
            }
        });
        return target;
    }

    public <P> ImmutableBag<T> selectWith(Predicate2<? super T, ? super P> predicate, P parameter)
    {
        return this.select(Predicates.bind(predicate, parameter));
    }

    @Override
    public <P, R extends Collection<T>> R selectWith(Predicate2<? super T, ? super P> predicate, P parameter, R target)
    {
        return this.select(Predicates.bind(predicate, parameter), target);
    }

    @Override
    public <R extends Collection<T>> R reject(final Predicate<? super T> predicate, final R target)
    {
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                if (!predicate.accept(each))
                {
                    for (int i = 0; i < occurrences; i++)
                    {
                        target.add(each);
                    }
                }
            }
        });
        return target;
    }

    public <P> ImmutableBag<T> rejectWith(Predicate2<? super T, ? super P> predicate, P parameter)
    {
        return this.reject(Predicates.bind(predicate, parameter));
    }

    @Override
    public <P, R extends Collection<T>> R rejectWith(Predicate2<? super T, ? super P> predicate, P parameter, R target)
    {
        return this.reject(Predicates.bind(predicate, parameter), target);
    }

    public PartitionImmutableBag<T> partition(final Predicate<? super T> predicate)
    {
        final PartitionMutableBag<T> partitionMutableBag = new PartitionHashBag<T>();
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                MutableBag<T> bucket = predicate.accept(each)
                        ? partitionMutableBag.getSelected()
                        : partitionMutableBag.getRejected();
                bucket.addOccurrences(each, occurrences);
            }
        });
        return partitionMutableBag.toImmutable();
    }

    public <P> PartitionImmutableBag<T> partitionWith(Predicate2<? super T, ? super P> predicate, P parameter)
    {
        return this.partition(Predicates.bind(predicate, parameter));
    }

    @Override
    public <V, R extends Collection<V>> R collect(final Function<? super T, ? extends V> function, final R target)
    {
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                V value = function.valueOf(each);
                for (int i = 0; i < occurrences; i++)
                {
                    target.add(value);
                }
            }
        });
        return target;
    }

    public <P, V> ImmutableBag<V> collectWith(Function2<? super T, ? super P, ? extends V> function, P parameter)
    {
        return this.collect(Functions.bind(function, parameter));
    }

    @Override
    public <V, R extends Collection<V>> R collectIf(final Predicate<? super T> predicate, final Function<? super T, ? extends V> function, final R target)
    {
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                if (predicate.accept(each))
                {
                    V value = function.valueOf(each);
                    for (int i = 0; i < occurrences; i++)
                    {
                        target.add(value);
                    }
                }
            }
        });
        return target;
    }

    @Override
    public <V, R extends Collection<V>> R flatCollect(final Function<? super T, ? extends Iterable<V>> function, final R target)
    {
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                Iterable<V> iterable = function.valueOf(each);
                for (int i = 0; i < occurrences; i++)
                {
                    Iterate.addAllIterable(iterable, target);
                }
            }
        });
        return target;
    }

    public ImmutableBooleanBag collectBoolean(final BooleanFunction<? super T> booleanFunction)
    {
        final BooleanHashBag result = new BooleanHashBag();
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                result.addOccurrences(booleanFunction.booleanValueOf(each), occurrences);
            }
        });
        return result.toImmutable();
    }

    @Override
    public <R extends MutableBooleanCollection> R collectBoolean(final BooleanFunction<? super T> booleanFunction, final R target)
    {
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                boolean value = booleanFunction.booleanValueOf(each);
                for (int i = 0; i < occurrences; i++)
                {
                    target.add(value);
                }
            }
        });
        return target;
    }

    public ImmutableByteBag collectByte(final ByteFunction<? super T> byteFunction)
    {
        final ByteHashBag result = new ByteHashBag(this.size());
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                result.addOccurrences(byteFunction.byteValueOf(each), occurrences);
            }
        });
        return result.toImmutable();
    }

    @Override
    public <R extends MutableByteCollection> R collectByte(final ByteFunction<? super T> byteFunction, final R target)
    {
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                byte value = byteFunction.byteValueOf(each);
                for (int i = 0; i < occurrences; i++)
                {
                    target.add(value);
                }
            }
        });
        return target;
    }

    public ImmutableCharBag collectChar(final CharFunction<? super T> charFunction)
    {
        final CharHashBag result = new CharHashBag(this.size());
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                result.addOccurrences(charFunction.charValueOf(each), occurrences);
            }
        });
        return result.toImmutable();
    }

    @Override
    public <R extends MutableCharCollection> R collectChar(final CharFunction<? super T> charFunction, final R target)
    {
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                char value = charFunction.charValueOf(each);
                for (int i = 0; i < occurrences; i++)
                {
                    target.add(value);
                }
            }
        });
        return target;
    }

    public ImmutableDoubleBag collectDouble(final DoubleFunction<? super T> doubleFunction)
    {
        final DoubleHashBag result = new DoubleHashBag(this.size());
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                result.addOccurrences(doubleFunction.doubleValueOf(each), occurrences);
            }
        });
        return result.toImmutable();
    }

    @Override
    public <R extends MutableDoubleCollection> R collectDouble(final DoubleFunction<? super T> doubleFunction, final R target)
    {
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                double value = doubleFunction.doubleValueOf(each);
                for (int i = 0; i < occurrences; i++)
                {
                    target.add(value);
                }
            }
        });
        return target;
    }

    public ImmutableFloatBag collectFloat(final FloatFunction<? super T> floatFunction)
    {
        final FloatHashBag result = new FloatHashBag(this.size());
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                result.addOccurrences(floatFunction.floatValueOf(each), occurrences);
            }
        });
        return result.toImmutable();
    }

    @Override
    public <R extends MutableFloatCollection> R collectFloat(final FloatFunction<? super T> floatFunction, final R target)
    {
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                Float value = floatFunction.floatValueOf(each);
                for (int i = 0; i < occurrences; i++)
                {
                    target.add(value);
                }
            }
        });
        return target;
    }

    public ImmutableIntBag collectInt(final IntFunction<? super T> intFunction)
    {
        final IntHashBag result = new IntHashBag(this.size());
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                result.addOccurrences(intFunction.intValueOf(each), occurrences);
            }
        });
        return result.toImmutable();
    }

    @Override
    public <R extends MutableIntCollection> R collectInt(final IntFunction<? super T> intFunction, final R target)
    {
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                int value = intFunction.intValueOf(each);
                for (int i = 0; i < occurrences; i++)
                {
                    target.add(value);
                }
            }
        });
        return target;
    }

    public ImmutableLongBag collectLong(final LongFunction<? super T> longFunction)
    {
        final LongHashBag result = new LongHashBag(this.size());
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                result.addOccurrences(longFunction.longValueOf(each), occurrences);
            }
        });
        return result.toImmutable();
    }

    @Override
    public <R extends MutableLongCollection> R collectLong(final LongFunction<? super T> longFunction, final R target)
    {
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                long value = longFunction.longValueOf(each);
                for (int i = 0; i < occurrences; i++)
                {
                    target.add(value);
                }
            }
        });
        return target;
    }

    public ImmutableShortBag collectShort(final ShortFunction<? super T> shortFunction)
    {
        final ShortHashBag result = new ShortHashBag(this.size());
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                result.addOccurrences(shortFunction.shortValueOf(each), occurrences);
            }
        });
        return result.toImmutable();
    }

    @Override
    public <R extends MutableShortCollection> R collectShort(final ShortFunction<? super T> shortFunction, final R target)
    {
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                short value = shortFunction.shortValueOf(each);
                for (int i = 0; i < occurrences; i++)
                {
                    target.add(value);
                }
            }
        });
        return target;
    }

    @Override
    public int count(final Predicate<? super T> predicate)
    {
        final Counter result = new Counter();
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                if (predicate.accept(each))
                {
                    result.add(occurrences);
                }
            }
        });
        return result.getCount();
    }

    @Override
    public <V, R extends MutableMultimap<V, T>> R groupBy(
            final Function<? super T, ? extends V> function,
            final R target)
    {
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                V value = function.valueOf(each);
                target.putAll(value, Collections.nCopies(occurrences, each));
            }
        });
        return target;
    }

    @Override
    public <V, R extends MutableMultimap<V, T>> R groupByEach(
            final Function<? super T, ? extends Iterable<V>> function,
            final R target)
    {
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(final T each, final int occurrences)
            {
                Iterable<V> values = function.valueOf(each);
                Iterate.forEach(values, new Procedure<V>()
                {
                    public void value(V value)
                    {
                        target.putAll(value, Collections.nCopies(occurrences, each));
                    }
                });
            }
        });
        return target;
    }

    @Override
    public long sumOfInt(final IntFunction<? super T> function)
    {
        final long[] sum = {0L};
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                long value = function.intValueOf(each);
                sum[0] += value * (long) occurrences;
            }
        });
        return sum[0];
    }

    @Override
    public long sumOfLong(final LongFunction<? super T> function)
    {
        final long[] sum = {0L};
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                long value = function.longValueOf(each);
                sum[0] += value * (long) occurrences;
            }
        });
        return sum[0];
    }

    @Override
    public double sumOfFloat(final FloatFunction<? super T> function)
    {
        final double[] sum = {0.0};
        final double[] compensation = {0.0};
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                float f = function.floatValueOf(each);
                for (int i = 0; i < occurrences; i++)
                {
                    double y = (double) f - compensation[0];
                    double t = sum[0] + y;
                    compensation[0] = t - sum[0] - y;
                    sum[0] = t;
                }
            }
        });
        return sum[0];
    }

    @Override
    public double sumOfDouble(final DoubleFunction<? super T> function)
    {
        final double[] sum = {0.0};
        final double[] compensation = {0.0};
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                double d = function.doubleValueOf(each);
                for (int i = 0; i < occurrences; i++)
                {
                    double adjustedValue = d - compensation[0];
                    double nextSum = sum[0] + adjustedValue;
                    compensation[0] = nextSum - sum[0] - adjustedValue;
                    sum[0] = nextSum;
                }
            }
        });
        return sum[0];
    }

    @Override
    public <IV> IV injectInto(IV injectedValue, final Function2<? super IV, ? super T, ? extends IV> function)
    {
        final IV[] result = (IV[]) new Object[]{injectedValue};
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                for (int i = 0; i < occurrences; i++)
                {
                    result[0] = function.value(result[0], each);
                }
            }
        });
        return result[0];
    }

    @Override
    public int injectInto(int injectedValue, final IntObjectToIntFunction<? super T> function)
    {
        final int[] result = {injectedValue};
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                for (int i = 0; i < occurrences; i++)
                {
                    result[0] = function.intValueOf(result[0], each);
                }
            }
        });
        return result[0];
    }

    @Override
    public long injectInto(long injectedValue, final LongObjectToLongFunction<? super T> function)
    {
        final long[] result = {injectedValue};
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                for (int i = 0; i < occurrences; i++)
                {
                    result[0] = function.longValueOf(result[0], each);
                }
            }
        });
        return result[0];
    }

    @Override
    public double injectInto(double injectedValue, final DoubleObjectToDoubleFunction<? super T> function)
    {
        final double[] result = {injectedValue};
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                for (int i = 0; i < occurrences; i++)
                {
                    result[0] = function.doubleValueOf(result[0], each);
                }
            }
        });
        return result[0];
    }

    @Override
    public float injectInto(float injectedValue, final FloatObjectToFloatFunction<? super T> function)
    {
        final float[] result = {injectedValue};
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                for (int i = 0; i < occurrences; i++)
                {
                    result[0] = function.floatValueOf(result[0], each);
                }
            }
        });
        return result[0];
    }

    public String toStringOfItemToCount()
    {
        if (this.isEmpty())
        {
            return "{}";
        }
        final StringBuilder builder = new StringBuilder().append('{');
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int occurrences)
            {
                builder.append(each);
                builder.append('=');
                builder.append(occurrences);
                builder.append(", ");
            }
        });
        builder.deleteCharAt(builder.length() - 1);
        builder.deleteCharAt(builder.length() - 1);
        return builder.append('}').toString();
    }

    protected MutableList<ObjectIntPair<T>> toListWithOccurrences()
    {
        final MutableList<ObjectIntPair<T>> result = FastList.newList(this.sizeDistinct());
        this.forEachWithOccurrences(new ObjectIntProcedure<T>()
        {
            public void value(T each, int count)
            {
                result.add(PrimitiveTuples.pair(each, count));
            }
        });
        return result;
    }

    public ImmutableList<ObjectIntPair<T>> topOccurrences(int n)
    {
        return this.occurrencesSortingBy(n, new IntFunction<ObjectIntPair<T>>()
        {
            public int intValueOf(ObjectIntPair<T> item)
            {
                return -item.getTwo();
            }
        }).toImmutable();
    }

    public ImmutableList<ObjectIntPair<T>> bottomOccurrences(int n)
    {
        return this.occurrencesSortingBy(n, new IntFunction<ObjectIntPair<T>>()
        {
            public int intValueOf(ObjectIntPair<T> item)
            {
                return item.getTwo();
            }
        }).toImmutable();
    }

    private MutableList<ObjectIntPair<T>> occurrencesSortingBy(int n, IntFunction<ObjectIntPair<T>> function)
    {
        if (n < 0)
        {
            throw new IllegalArgumentException("Cannot use a value of n < 0");
        }
        if (n == 0)
        {
            return Lists.fixedSize.empty();
        }
        int keySize = Math.min(n, this.sizeDistinct());
        MutableList<ObjectIntPair<T>> sorted = this.toListWithOccurrences().sortThisByInt(function);
        MutableList<ObjectIntPair<T>> results = sorted.subList(0, keySize).toList();
        while (keySize < sorted.size() && results.getLast().getTwo() == sorted.get(keySize).getTwo())
        {
            results.add(sorted.get(keySize));
            keySize++;
        }
        return results;
    }
}


text:
package org.apache.activemq.artemis.core.journal.impl;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.Executor;

import org.apache.activemq.artemis.api.core.ActiveMQException;
import org.apache.activemq.artemis.core.asyncio.AsynchronousFile;
import org.apache.activemq.artemis.core.asyncio.BufferCallback;
import org.apache.activemq.artemis.core.asyncio.IOExceptionListener;
import org.apache.activemq.artemis.core.asyncio.impl.AsynchronousFileImpl;
import org.apache.activemq.artemis.core.journal.IOAsyncTask;
import org.apache.activemq.artemis.core.journal.SequentialFile;
import org.apache.activemq.artemis.core.journal.SequentialFileFactory;

public class AIOSequentialFile extends AbstractSequentialFile implements IOExceptionListener
{
   private boolean opened = false;

   private final int maxIO;

   private AsynchronousFile aioFile;

   private final BufferCallback bufferCallback;

   /** The pool for Thread pollers */
   private final Executor pollerExecutor;

   public AIOSequentialFile(final SequentialFileFactory factory,
                            final int bufferSize,
                            final long bufferTimeoutMilliseconds,
                            final String directory,
                            final String fileName,
                            final int maxIO,
                            final BufferCallback bufferCallback,
                            final Executor writerExecutor,
                            final Executor pollerExecutor)
   {
      super(directory, new File(directory + "/" + fileName), factory, writerExecutor);
      this.maxIO = maxIO;
      this.bufferCallback = bufferCallback;
      this.pollerExecutor = pollerExecutor;
   }

   public boolean isOpen()
   {
      return opened;
   }

   public int getAlignment()
   {
      checkOpened();

      return aioFile.getBlockSize();
   }

   public int calculateBlockStart(final int position)
   {
      int alignment = getAlignment();

      int pos = (position / alignment + (position % alignment != 0 ? 1 : 0)) * alignment;

      return pos;
   }

   public SequentialFile cloneFile()
   {
      return new AIOSequentialFile(factory,
                                   -1,
                                   -1,
                                   getFile().getParent(),
                                   getFileName(),
                                   maxIO,
                                   bufferCallback,
                                   writerExecutor,
                                   pollerExecutor);
   }

   @Override
   public synchronized void close() throws IOException, InterruptedException, ActiveMQException
   {
      if (!opened)
      {
         return;
      }

      super.close();

      opened = false;

      timedBuffer = null;

      aioFile.close();
      aioFile = null;

      notifyAll();
   }

   @Override
   public synchronized void waitForClose() throws Exception
   {
      while (isOpen())
      {
         wait();
      }
   }

   public void fill(final int position, final int size, final byte fillCharacter) throws Exception
   {
      checkOpened();

      int fileblockSize = aioFile.getBlockSize();

      int blockSize = fileblockSize;

      if (size % (100 * 1024 * 1024) == 0)
      {
         blockSize = 100 * 1024 * 1024;
      }
      else if (size % (10 * 1024 * 1024) == 0)
      {
         blockSize = 10 * 1024 * 1024;
      }
      else if (size % (1024 * 1024) == 0)
      {
         blockSize = 1024 * 1024;
      }
      else if (size % (10 * 1024) == 0)
      {
         blockSize = 10 * 1024;
      }
      else
      {
         blockSize = fileblockSize;
      }

      int blocks = size / blockSize;

      if (size % blockSize != 0)
      {
         blocks++;
      }

      int filePosition = position;

      if (position % fileblockSize != 0)
      {
         filePosition = (position / fileblockSize + 1) * fileblockSize;
      }

      aioFile.fill(filePosition, blocks, blockSize, fillCharacter);

      fileSize = aioFile.size();
   }

   public void open() throws Exception
   {
      open(maxIO, true);
   }

   public synchronized void open(final int maxIO, final boolean useExecutor) throws ActiveMQException
   {
      opened = true;

      aioFile = new AsynchronousFileImpl(useExecutor ? writerExecutor : null, pollerExecutor, this);

      try
      {
         aioFile.open(getFile().getAbsolutePath(), maxIO);
      }
      catch (ActiveMQException e)
      {
         factory.onIOError(e, e.getMessage(), this);
         throw e;
      }

      position.set(0);

      aioFile.setBufferCallback(bufferCallback);

      fileSize = aioFile.size();
   }

   public void setBufferCallback(final BufferCallback callback)
   {
      aioFile.setBufferCallback(callback);
   }

   public int read(final ByteBuffer bytes, final IOAsyncTask callback) throws ActiveMQException
   {
      int bytesToRead = bytes.limit();

      long positionToRead = position.getAndAdd(bytesToRead);

      bytes.rewind();

      aioFile.read(positionToRead, bytesToRead, bytes, callback);

      return bytesToRead;
   }

   public int read(final ByteBuffer bytes) throws Exception
   {
      SimpleWaitIOCallback waitCompletion = new SimpleWaitIOCallback();

      int bytesRead = read(bytes, waitCompletion);

      waitCompletion.waitCompletion();

      return bytesRead;
   }

   public void sync()
   {
      throw new UnsupportedOperationException("This method is not supported on AIO");
   }

   public long size() throws Exception
   {
      if (aioFile == null)
      {
         return getFile().length();
      }
      else
      {
         return aioFile.size();
      }
   }

   @Override
   public String toString()
   {
      return "AIOSequentialFile:" + getFile().getAbsolutePath();
   }

   // Public methods
   // -----------------------------------------------------------------------------------------------------

   @Override
   public void onIOException(Exception code, String message)
   {
      factory.onIOError(code, message, this);
   }

   public void writeDirect(final ByteBuffer bytes, final boolean sync) throws Exception
   {
      if (sync)
      {
         SimpleWaitIOCallback completion = new SimpleWaitIOCallback();

         writeDirect(bytes, true, completion);

         completion.waitCompletion();
      }
      else
      {
         writeDirect(bytes, false, DummyCallback.getInstance());
      }
   }

   /**
    *
    * @param sync Not used on AIO
    *  */
   public void writeDirect(final ByteBuffer bytes, final boolean sync, final IOAsyncTask callback)
   {
      final int bytesToWrite = factory.calculateBlockSize(bytes.limit());

      final long positionToWrite = position.getAndAdd(bytesToWrite);

      aioFile.write(positionToWrite, bytesToWrite, bytes, callback);
   }

   public void writeInternal(final ByteBuffer bytes) throws ActiveMQException
   {
      final int bytesToWrite = factory.calculateBlockSize(bytes.limit());

      final long positionToWrite = position.getAndAdd(bytesToWrite);

      aioFile.writeInternal(positionToWrite, bytesToWrite, bytes);
   }

   // Protected methods
   // -----------------------------------------------------------------------------------------------------

   @Override
   protected ByteBuffer newBuffer(int size, int limit)
   {
      size = factory.calculateBlockSize(size);
      limit = factory.calculateBlockSize(limit);

      ByteBuffer buffer = factory.newBuffer(size);
      buffer.limit(limit);
      return buffer;
   }

   // Private methods
   // -----------------------------------------------------------------------------------------------------

   private void checkOpened()
   {
      if (aioFile == null || !opened)
      {
         throw new IllegalStateException("File not opened");
      }
   }

}

redpajama_set_name: RedPajamaGithub


text:
/**
 * Created by alokguha on 06/03/17.
 */
var ll = require('./lib/linkedList');
module.exports = {
  linkedList: function() {
    return new ll.singlyLinkedList();
  }
}


text:
#include "TestTimer.h"
#if !defined (WIN32)
#include <unistd.h>
#endif

//---- TestTimer ----------------------------------------------------------------
TestTimer::TestTimer(tTimeType resolution)
	: fResolution(resolution)
{
	if ( fResolution <= 0 ) {
		fResolution = 0;    // measure in clock ticks
	}

	Start();
}

TestTimer::TestTimer(const TestTimer &dt)
	: fResolution(dt.fResolution)
{
	if ( fResolution <= 0 ) {
		fResolution = 0;    // measure in clock ticks
	}

	Start();
}

TestTimer &TestTimer::operator=(const TestTimer &dt)
{
	fResolution = dt.fResolution;
	return *this;
}

TestTimer::tTimeType TestTimer::Scale(tTimeType rawDiff, tTimeType resolution)
{
	if ( resolution <= 0 ) {
		return rawDiff;
	}
	if ( TicksPerSecond() < resolution ) {
		// beware of wrong scale
		return ( rawDiff * ( resolution / TicksPerSecond() ) );
	}
	// beware of overflow
	return ( (rawDiff * resolution) / TicksPerSecond() );
}

TestTimer::tTimeType TestTimer::Diff(tTimeType simulatedValue)
{
	if (simulatedValue > -1) {
		return simulatedValue;
	} else {
		tTimeType lDiff = Scale(RawDiff(), fResolution);
		return lDiff;
	}
}

void TestTimer::Start()
{
	fStart = GetHRTESTTIME();
}

TestTimer::tTimeType TestTimer::Reset()
{
	tTimeType delta = Diff();
	Start();
	return delta;
}

TestTimer::tTimeType TestTimer::TicksPerSecond()
{
	tTimeType tps( 1 );
#if defined(__sun)
	tps = 1000000000;
#elif defined(WIN32)
	tps = 1000;
#else
	tps = sysconf(_SC_CLK_TCK);
#endif
	return tps;
}


text:
package osmedile.intellij.stringmanip.sort.support;

import java.math.BigInteger;
import java.text.Collator;
import java.text.ParseException;
import java.text.RuleBasedCollator;
import java.util.*;

public enum Sort {

	SHUFFLE(new ComparatorFactory() {
		@Override
		Comparator<Sortable> sortable(Comparator<String> comparator) {
			return new SortableComparator(string(comparator), "SHUFFLE");

		}

		@Override
		Comparator<String> string(Comparator<String> comparator) {
			return new Comparator<String>() {
				@Override
				public int compare(String o1, String o2) {
					throw new RuntimeException("SHUFFLE not supported");
				}
			};
		}
	}),
	REVERSE(new ComparatorFactory() {
		@Override
		Comparator<Sortable> sortable(Comparator<String> comparator) {
			return new SortableComparator(string(comparator), "REVERSE");
		}

		@Override
		Comparator<String> string(Comparator<String> comparator) {
			return new Comparator<String>() {
				@Override
				public int compare(String o1, String o2) {
					throw new RuntimeException("REVERSE not supported");
				}
			};
		}
	}),
	CASE_SENSITIVE_A_Z(new ComparatorFactory() {
		public Comparator<Sortable> sortable(Comparator<String> comparator) {
			return new SortableComparator(string(comparator), "CASE_SENSITIVE_A_Z");
		}

		@Override
		Comparator<String> string(Comparator<String> comparator) {
			return new Comparator<String>() {
				@Override
				public String toString() {
					return "CASE_SENSITIVE_A_Z";
				}

				@Override
				public int compare(String o1, String o2) {
					if (comparator == null) {
						return o1.compareTo(o2);
					}
					return comparator.compare(o1, o2);
				}
			};
		}
	}),
	CASE_SENSITIVE_Z_A(new ComparatorFactory() {
		public Comparator<Sortable> sortable(Comparator<String> comparator) {
			return new SortableComparator(string(comparator), "CASE_SENSITIVE_Z_A");
		}

		@Override
		Comparator<String> string(Comparator<String> comparator) {
			return new Comparator<String>() {
				@Override
				public String toString() {
					return "CASE_SENSITIVE_Z_A";
				}

				@Override
				public int compare(String o1, String o2) {
					if (comparator == null) {
						return o2.compareTo(o1);
					}

					return comparator.compare(o2, o1);
				}
			};
		}
	}),
	CASE_INSENSITIVE_A_Z(new ComparatorFactory() {
		public Comparator<Sortable> sortable(Comparator<String> comparator) {
			return new SortableComparator(string(comparator), "CASE_INSENSITIVE_A_Z");
		}

		@Override
		Comparator<String> string(Comparator<String> comparator) {
			return new Comparator<String>() {
				@Override
				public String toString() {
					return "CASE_INSENSITIVE_A_Z";
				}

				@Override
				public int compare(String o1, String o2) {
					if (comparator == null) {
						return o1.compareToIgnoreCase(o2);
					}
					return comparator.compare(o1.toLowerCase(), o2.toLowerCase());
				}
			};
		}
	}),
	CASE_INSENSITIVE_Z_A(new ComparatorFactory() {
		public Comparator<Sortable> sortable(Comparator<String> comparator) {
			return new SortableComparator(string(comparator), "CASE_INSENSITIVE_Z_A");
		}

		@Override
		Comparator<String> string(Comparator<String> comparator) {
			return new Comparator<String>() {
				@Override
				public String toString() {
					return "CASE_INSENSITIVE_Z_A";
				}

				@Override
				public int compare(String o1, String o2) {
					if (comparator == null) {
						return o2.compareToIgnoreCase(o1);
					}
					return comparator.compare(o2.toLowerCase(), o1.toLowerCase());
				}
			};
		}
	}),
	LINE_LENGTH_SHORT_LONG(new ComparatorFactory() {
		public Comparator<Sortable> sortable(Comparator<String> comparator) {
			return new SortableComparator(string(comparator), "LINE_LENGTH_SHORT_LONG");
		}

		@Override
		Comparator<String> string(Comparator<String> comparator) {
			return new Comparator<String>() {
				@Override
				public String toString() {
					return "LINE_LENGTH_SHORT_LONG";
				}

				@Override
				public int compare(String o1, String o2) {
					return o1.length() - o2.length();
				}
			};
		}
	}),
	LINE_LENGTH_LONG_SHORT(new ComparatorFactory() {
		public Comparator<Sortable> sortable(Comparator<String> comparator) {
			return new SortableComparator(string(comparator), "LINE_LENGTH_LONG_SHORT");
		}

		@Override
		Comparator<String> string(Comparator<String> comparator) {
			return new Comparator<String>() {
				@Override
				public String toString() {
					return "LINE_LENGTH_LONG_SHORT";
				}

				@Override
				public int compare(String o1, String o2) {
					return o2.length() - o1.length();

				}
			};
		}
	}),

	HEXA(new ComparatorFactory() {
		public Comparator<Sortable> sortable(Comparator<String> comparator) {
			return new SortableComparator(string(comparator), "HEXA");
		}

		@Override
		Comparator<String> string(Comparator<String> comparator) {
			return new Comparator<String>() {
				@Override
				public String toString() {
					return "HEXA";
				}

				@Override
				public int compare(String o1, String o2) {
					try {
						return toHex(o1).compareTo(toHex(o2));
					} catch (Throwable e) {
						throw new SortException("Hexadecimal sort failed, select Hex text only! \n(" + e.toString() + ")", e);
					}
				}

				protected BigInteger toHex(String textForComparison) {
					if (textForComparison == null) {
						return BigInteger.ZERO;
					}
					textForComparison = textForComparison.trim().replaceAll("^0x", "");

					return new BigInteger(textForComparison, 16);
				}
			};
		}
	});

	private ComparatorFactory factory;

	Sort(ComparatorFactory factory) {
		this.factory = factory;
	}

	public <T extends Sortable> List<T> sortLines(List<T> lines, SortSettings.BaseComparator baseComparator, String languageTag) {
		List<T> sortedLines = new ArrayList<T>(lines);
		switch (this) {
			case SHUFFLE:
				Collections.shuffle(sortedLines);
				break;
			case REVERSE:
				Collections.reverse(sortedLines);
				break;
			default:
				sortedLines.sort(getSortLineComparator(baseComparator, languageTag));
		}
		return sortedLines;
	}

	public Comparator<Sortable> getSortLineComparator(SortSettings.BaseComparator baseComparatorEnum, String languageTag) {
		Comparator<String> baseComparator = getBaseStringComparator(baseComparatorEnum, languageTag);
		return factory.sortable(baseComparator);
	}

	public Comparator<String> getStringComparator(SortSettings.BaseComparator baseComparatorEnum, String languageTag) {
		Comparator<String> baseComparator = getBaseStringComparator(baseComparatorEnum, languageTag);
		return factory.string(baseComparator);
	}

	private Comparator<String> getBaseStringComparator(SortSettings.BaseComparator baseComparator, String languageTag) {
		Comparator comparator;
		switch (baseComparator) {
			case NORMAL:
				comparator = null;
				break;
			case NATURAL:
				comparator = new osmedile.intellij.stringmanip.sort.support.Paour.NaturalOrderComparator();
				break;
			case LOCALE_COLLATOR:
				try {
					Collator instance = Collator.getInstance(Locale.forLanguageTag(languageTag));
					String rules = ((RuleBasedCollator) instance).getRules();
					Character[] chars = new Character[]{
							(char) 0x0009,//  9	Horizontal tab	HT
							(char) 0x000B,//  11	Vertical tab	VT
							(char) 0x000C,//  12	Form feed	FF
							(char) 0x000D,//  13	Carriage return	CR
							(char) 0x002D,//  45	Hyphen-minus	0014
							(char) ' ',//
					};
					StringBuilder sb = new StringBuilder();
					for (Character aChar : chars) {
						sb.append("<'").append(aChar).append("'");
					}

					String correctedRules = rules.replaceAll("<'\u005f'", sb.toString() + "<'\u005f'");
					RuleBasedCollator correctedCollator = new RuleBasedCollator(correctedRules);
					comparator = correctedCollator;
				} catch (ParseException e) {
					throw new RuntimeException(e);
				}
				break;
			default:
				throw new RuntimeException("invalid enum");
		}

		return comparator;
	}

	static abstract class ComparatorFactory {
		abstract Comparator<Sortable> sortable(Comparator<String> baseComparator);

		abstract Comparator<String> string(Comparator<String> baseComparator);
	}

	private static class SortableComparator implements Comparator<Sortable> {
		private final Comparator<String> stringComparator;
		private String name;

		public SortableComparator(Comparator<String> stringComparator, String name) {
			this.name = name;
			this.stringComparator = stringComparator;
		}

		@Override
		public String toString() {
			return name;
		}

		@Override
		public int compare(Sortable o1, Sortable o2) {
			return stringComparator.compare(o1.getTextForComparison(), o2.getTextForComparison());
		}
	}
}


text:
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore.Query.Expressions;
using Microsoft.EntityFrameworkCore.Query.ExpressionTranslators;

namespace EFCore.SqlCe.Query.ExpressionTranslators.Internal
{
    public class SqlCeStringLengthTranslator : IMemberTranslator
    {
        public virtual Expression Translate(MemberExpression memberExpression)
        => (memberExpression.Expression != null)
           && (memberExpression.Expression.Type == typeof(string))
           && (memberExpression.Member.Name == nameof(string.Length))
            ? new SqlFunctionExpression("LEN", memberExpression.Type, new[] { memberExpression.Expression })
            : null;
    }
}


text:
{% extends "base.html" %}
{% block body %}

      {% if not emote.verified %}

        {% if can_manage %}
        This emote is pending approval. You won't be able to use it in Discord yet.
        {% else %}
        This emote is pending approval. It won't be able to be used in Discord yet.
        {% endif %}

      {% endif %}

{{ emote.name }}

      {% if g.guilds and emote.shared and emote.verified %}

        <form method="POST" enctype="multipart/form-data">
          <input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />

              <select name="guild_added">
                <option value="" disabled selected hidden>Add to..</option>
                {%- for opt in g.guilds %}
                  {%- if opt.id != guild.id %}
                <option value="{{ opt.id }}">{{ opt.name }}</option>
                  {%- endif %}
                {%- endfor %}
              </select>

            <input class="button is-info" type="submit" value="Add">

        </form>

      {% endif %}

            Emote

            Name
            {{ emote.name }}

            Server
            {% if guild.public %}
            {{ guild.name }}
            {% else %}
            {{ guild.name }}
            {% endif %}

            Shared
            {% if emote.shared %}
              Yes
            {% else %}
              No
            {% endif %}

      {% if can_manage %}

        <form method="POST" enctype="multipart/form-data">

            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
            <input class="button is-info" type="submit" name="toggle" value="{{ 'Make Private' if emote.shared else 'Make Shared' }}">
            <input class="button is-danger" type="submit" name="delete" value="Delete Emote" onclick="return confirm('Are you sure you want to delete this emote?');">

        </form>

      {% endif %}

      {% if shared_guilds %}

Other servers using {{ emote.name }}

        {%- for server in shared_guilds %}

                {{ server.name }}

        {% endfor %}

      {% endif %}

{% endblock %}


text:
require 'spec_helper'

describe 'MmoStarterKit Basic List' do

  subject { page }

  describe 'GET /admin' do
    it 'responds successfully' do
      visit dashboard_path
    end
  end

  describe 'GET /admin/typo' do
    it "redirects to dashboard and inform the user the model wasn't found" do
      visit '/admin/whatever'
      expect(page.driver.status_code).to eq(404)
      expect(find('.alert-error')).to have_content("Model 'Whatever' could not be found")
    end
  end

  describe 'GET /admin/balls/545-typo' do
    it "redirects to balls index and inform the user the id wasn't found" do
      visit '/admin/ball/545-typo'
      expect(page.driver.status_code).to eq(404)
      expect(find('.alert-error')).to have_content("Ball with id '545-typo' could not be found")
    end
  end

  describe 'GET /admin/player as list' do
    it "shows \"List of Models\", should show filters and should show column headers" do
      MmoStarterKit.config.default_items_per_page = 1
      2.times { FactoryGirl.create :player } # two pages of players
      visit index_path(model_name: 'player')
      should have_content('List of Players')
      should have_content('Created at')
      should have_content('Updated at')

      # it "shows the show, edit and delete links" do
      should have_selector("li[title='Show'] a")
      should have_selector("li[title='Edit'] a")
      should have_selector("li[title='Delete'] a")

      # it "has the search box with some prompt text" do
      should have_selector("input[placeholder='Filter']")

      # https://github.com/sferik/mmo_starter_kit/issues/362
      # test that no link uses the "wildcard route" with the main
      # controller and list method
      # it "does not use the 'wildcard route'" do
      should have_selector("a[href*='all=true']") # make sure we're fully testing pagination
      should have_no_selector("a[href^='/mmo_starter_kit/main/list']")
    end
  end

  describe 'GET /admin/player' do
    before do
      @teams = 2.times.collect do
        FactoryGirl.create(:team)
      end
      @players = [
        FactoryGirl.create(:player, retired: true, injured: true, team: @teams[0]),
        FactoryGirl.create(:player, retired: true, injured: false, team: @teams[0]),
        FactoryGirl.create(:player, retired: false, injured: true, team: @teams[1]),
        FactoryGirl.create(:player, retired: false, injured: false, team: @teams[1]),
      ]
    end

    it 'allows to query on any attribute' do
      MmoStarterKit.config Player do
        list do
          field :name
          field :team
          field :injured
          field :retired
        end
      end

      visit index_path(model_name: 'player', query: @players[0].name)
      should have_content(@players[0].name)
      (1..3).each do |i|
        should have_no_content(@players[i].name)
      end
    end

    it 'allows to filter on one attribute' do
      MmoStarterKit.config Player do
        list do
          field :name
          field :team
          field :injured
          field :retired
        end
      end

      visit index_path(model_name: 'player', f: {injured: {'1' => {v: 'true'}}})
      should have_content(@players[0].name)
      should have_no_content(@players[1].name)
      should have_content(@players[2].name)
      should have_no_content(@players[3].name)
    end

    it 'allows to combine filters on two different attributes' do
      MmoStarterKit.config Player do
        list do
          field :name
          field :team
          field :injured
          field :retired
        end
      end

      visit index_path(model_name: 'player', f: {retired: {'1' => {v: 'true'}}, injured: {'1' => {v: 'true'}}})
      should have_content(@players[0].name)
      (1..3).each do |i|
        should have_no_content(@players[i].name)
      end
    end

    it 'allows to filter on belongs_to relationships' do
      MmoStarterKit.config Player do
        list do
          field :name
          field :team
          field :injured
          field :retired
        end
      end

      visit index_path(model_name: 'player', f: {team: {'1' => {v: @teams[0].name}}})
      should have_content(@players[0].name)
      should have_content(@players[1].name)
      should have_no_content(@players[2].name)
      should have_no_content(@players[3].name)
    end

    it 'allows to disable search on attributes' do
      MmoStarterKit.config Player do
        list do
          field :position
          field :name do
            searchable false
          end
        end
      end
      visit index_path(model_name: 'player', query: @players[0].name)
      should have_no_content(@players[0].name)
    end

    it 'allows to search a belongs_to attribute over the base table' do
      MmoStarterKit.config Player do
        list do
          field PK_COLUMN
          field :name
          field :team do
            searchable Player => :team_id
          end
        end
      end
      visit index_path(model_name: 'player', f: {team: {'1' => {v: @teams.first.id}}})
      should have_content(@players[0].name)
      should have_content(@players[1].name)
      should have_no_content(@players[2].name)
      should have_no_content(@players[3].name)
    end

    it 'allows to search a belongs_to attribute over the target table' do
      MmoStarterKit.config Player do
        list do
          field PK_COLUMN
          field :name
          field :team do
            searchable Team => :name
          end
        end
      end
      visit index_path(model_name: 'player', f: {team: {'1' => {v: @teams.first.name}}})
      should have_content(@players[0].name)
      should have_content(@players[1].name)
      should have_no_content(@players[2].name)
      should have_no_content(@players[3].name)
    end

    it 'allows to search a belongs_to attribute over the target table with a table name specified as a hash' do
      MmoStarterKit.config Player do
        list do
          field PK_COLUMN
          field :name
          field :team do
            searchable teams: :name
          end
        end
      end
      visit index_path(model_name: 'player', f: {team: {'1' => {v: @teams.first.name}}})
      should have_content(@players[0].name)
      should have_content(@players[1].name)
      should have_no_content(@players[2].name)
      should have_no_content(@players[3].name)
    end

    it 'allows to search a belongs_to attribute over the target table with a table name specified as a string' do
      MmoStarterKit.config Player do
        list do
          field PK_COLUMN
          field :name
          field :team do
            searchable 'teams.name'
          end
        end
      end
      visit index_path(model_name: 'player', f: {team: {'1' => {v: @teams.first.name}}})
      should have_content(@players[0].name)
      should have_content(@players[1].name)
      should have_no_content(@players[2].name)
      should have_no_content(@players[3].name)
    end

    it 'allows to search a belongs_to attribute over the label method by default' do
      MmoStarterKit.config Player do
        list do
          field PK_COLUMN
          field :name
          field :team
        end
      end
      visit index_path(model_name: 'player', f: {team: {'1' => {v: @teams.first.name}}})
      should have_content(@players[0].name)
      should have_content(@players[1].name)
      should have_no_content(@players[2].name)
      should have_no_content(@players[3].name)
    end

    it 'allows to search a belongs_to attribute over the target table when an attribute is specified' do
      MmoStarterKit.config Player do
        list do
          field PK_COLUMN
          field :name
          field :team do
            searchable :name
          end
        end
      end
      visit index_path(model_name: 'player', f: {team: {'1' => {v: @teams.first.name}}})
      should have_content(@players[0].name)
      should have_content(@players[1].name)
      should have_no_content(@players[2].name)
      should have_no_content(@players[3].name)
    end

    it 'allows to search over more than one attribute' do
      MmoStarterKit.config Player do
        list do
          field PK_COLUMN
          field :name
          field :team do
            searchable [:name, {Player => :team_id}]
          end
        end
      end
      visit index_path(model_name: 'player', f: {team: {'1' => {v: @teams.first.name}, '2' => {v: @teams.first.id, o: 'is'}}})
      should have_content(@players[0].name)
      should have_content(@players[1].name)
      should have_no_content(@players[2].name)
      should have_no_content(@players[3].name)
      # same with a different id
      visit index_path(model_name: 'player', f: {team: {'1' => {v: @teams.first.name}, '2' => {v: @teams.last.id, o: 'is'}}})
      should have_no_content(@players[0].name)
      should have_no_content(@players[1].name)
      should have_no_content(@players[2].name)
      should have_no_content(@players[3].name)
    end

    it 'displays base filters when no filters are present in the params' do
      MmoStarterKit.config Player do
        list do
          filters [:name, :team]
        end
      end

      get index_path(model_name: 'player')
      expect(response.body).to include(%{$.filters.append("Name", "name", "string", "", null, "", 1);}) # rubocop:disable StringLiterals
      expect(response.body).to include(%{$.filters.append("Team", "team", "belongs_to_association", "", null, "", 2);}) # rubocop:diasble StringLiterals
    end
  end

  describe 'GET /admin/player with 2 objects' do
    before do
      @players = 2.times.collect { FactoryGirl.create :player }
      visit index_path(model_name: 'player')
    end

    it "shows \"2 results\"" do
      should have_content('2 players')
    end
  end

  describe 'GET /admin/player with 2 objects' do
    before do
      @players = 2.times.collect { FactoryGirl.create :player }
      visit index_path(model_name: 'player')
    end

    it "shows \"2 results\"" do
      should have_content('2 players')
    end
  end

  describe 'GET /admin/player with 3 pages, page 2' do
    before do
      MmoStarterKit.config.default_items_per_page = 1
      items_per_page = MmoStarterKit.config.default_items_per_page
      (items_per_page * 3).times { FactoryGirl.create(:player) }
      visit index_path(model_name: 'player', page: 2)
    end

    it 'paginates correctly' do
      expect(find('.pagination ul li:first')).to have_content('« Prev')
      expect(find('.pagination ul li:last')).to have_content('Next »')
      expect(find('.pagination ul li.active')).to have_content('2')
    end
  end

  describe 'list with 3 pages, page 3' do
    before do
      items_per_page = MmoStarterKit.config.default_items_per_page
      @players = (items_per_page * 3).times.collect { FactoryGirl.create(:player) }
      visit index_path(model_name: 'player', page: 3)
    end

    it 'paginates correctly and contain the right item' do
      expect(find('.pagination ul li:first')).to have_content('« Prev')
      expect(find('.pagination ul li:last')).to have_content('Next »')
      expect(find('.pagination ul li.active')).to have_content('3')
    end
  end

  describe 'GET /admin/player show all' do
    it 'responds successfully with a single model' do
      FactoryGirl.create :player
      visit index_path(model_name: 'player', all: true)
      expect(find('div.total-count')).to have_content('1 player')
      expect(find('div.total-count')).not_to have_content('1 players')
    end

    it 'responds successfully with multiple models' do
      2.times.collect { FactoryGirl.create :player }
      visit index_path(model_name: 'player', all: true)
      expect(find('div.total-count')).to have_content('2 players')
    end
  end

  describe 'GET /admin/player show with pagination disabled by :associated_collection' do
    it 'responds successfully' do
      @team = FactoryGirl.create :team
      2.times.collect { FactoryGirl.create :player, team: @team }
      visit index_path(model_name: 'player', associated_collection: 'players', compact: true, current_action: 'update', source_abstract_model: 'team', source_object_id: @team.id)
      expect(find('div.total-count')).to have_content('2 players')
    end
  end

  describe 'list as compact json' do
    it 'has_content an array with 2 elements and contain an array of elements with keys id and label' do
      2.times.collect { FactoryGirl.create :player }
      get index_path(model_name: 'player', compact: true, format: :json)
      expect(ActiveSupport::JSON.decode(response.body).length).to eq(2)
      ActiveSupport::JSON.decode(response.body).each do |object|
        expect(object).to have_key('id')
        expect(object).to have_key('label')
      end
    end
  end

  describe 'search operator' do
    let(:player) { FactoryGirl.create :player }

    before do
      expect(Player.count).to eq(0)
    end

    it 'finds the player if the query matches the default search opeartor' do
      MmoStarterKit.config do |config|
        config.default_search_operator = 'ends_with'
        config.model Player do
          list { field :name }
        end
      end
      visit index_path(model_name: 'player', query: player.name[2, -1])
      should have_content(player.name)
    end

    it 'does not find the player if the query does not match the default search opeartor' do
      MmoStarterKit.config do |config|
        config.default_search_operator = 'ends_with'
        config.model Player do
          list { field :name }
        end
      end
      visit index_path(model_name: 'player', query: player.name[0, 2])
      should have_no_content(player.name)
    end

    it 'finds the player if the query matches the specified search operator' do
      MmoStarterKit.config Player do
        list do
          field :name do
            search_operator 'starts_with'
          end
        end
      end
      visit index_path(model_name: 'player', query: player.name[0, 2])
      should have_content(player.name)
    end

    it 'does not find the player if the query does not match the specified search operator' do
      MmoStarterKit.config Player do
        list do
          field :name do
            search_operator 'starts_with'
          end
        end
      end
      visit index_path(model_name: 'player', query: player.name[1..-1])
      should have_no_content(player.name)
    end
  end

  describe 'list for objects with overridden to_param' do
    before do
      @ball = FactoryGirl.create :ball

      visit index_path(model_name: 'ball')
    end

    it 'shows the show, edit and delete links with valid url' do
      should have_selector("td a[href='/admin/ball/#{@ball.id}']")
      should have_selector("td a[href='/admin/ball/#{@ball.id}/edit']")
      should have_selector("td a[href='/admin/ball/#{@ball.id}/delete']")
    end

  end

  describe 'Scopes' do
    before do
      MmoStarterKit.config do |config|
        config.model Team do
          list do
            scopes [nil, :red, :white]
          end
        end
      end
      @teams = [
        FactoryGirl.create(:team, color: 'red'),
        FactoryGirl.create(:team, color: 'red'),
        FactoryGirl.create(:team, color: 'white'),
        FactoryGirl.create(:team, color: 'black')
      ]
    end

    it 'displays configured scopes' do
      visit index_path(model_name: 'team')
      expect(find('#scope_selector li:first')).to have_content('All')
      expect(find('#scope_selector li:nth-child(2)')).to have_content('Red')
      expect(find('#scope_selector li:nth-child(3)')).to have_content('White')
      expect(find('#scope_selector li:last')).to have_content('White')
      expect(find('#scope_selector li.active')).to have_content('All')
    end

    it 'shows only scoped records' do
      visit index_path(model_name: 'team')
      should have_content(@teams[0].name)
      should have_content(@teams[1].name)
      should have_content(@teams[2].name)
      should have_content(@teams[3].name)

      visit index_path(model_name: 'team', scope: 'red')
      expect(find('#scope_selector li.active')).to have_content('Red')
      should have_content(@teams[0].name)
      should have_content(@teams[1].name)
      should have_no_content(@teams[2].name)
      should have_no_content(@teams[3].name)

      visit index_path(model_name: 'team', scope: 'white')
      expect(find('#scope_selector li.active')).to have_content('White')
      should have_no_content(@teams[0].name)
      should have_no_content(@teams[1].name)
      should have_content(@teams[2].name)
      should have_no_content(@teams[3].name)
    end
    it 'shows all records instead when scope not in list' do
      visit index_path(model_name: 'team', scope: 'green')
      should have_content(@teams[0].name)
      should have_content(@teams[1].name)
      should have_content(@teams[2].name)
      should have_content(@teams[3].name)
    end
    describe 'i18n' do
      before :each do
        en = {admin: {scopes: {
          _all: 'every',
          red: 'krasnyj'
        }}}
        I18n.backend.store_translations(:en, en)
      end
      after { I18n.reload! }
      context 'global' do
        it 'displays configured scopes' do
          visit index_path(model_name: 'team')
          expect(find('#scope_selector li:first')).to have_content('every')
          expect(find('#scope_selector li:nth-child(2)')).to have_content('krasnyj')
          expect(find('#scope_selector li:nth-child(3)')).to have_content('White')
          expect(find('#scope_selector li:last')).to have_content('White')
          expect(find('#scope_selector li.active')).to have_content('every')
        end
      end
      context 'per model' do
        before :each do
          en = {admin: {scopes: {team: {
            _all: 'any',
            red: 'kr'
          }}}}
          I18n.backend.store_translations(:en, en)
        end
        after { I18n.reload! }
        it 'displays configured scopes' do
          visit index_path(model_name: 'team')
          expect(find('#scope_selector li:first')).to have_content('any')
          expect(find('#scope_selector li:nth-child(2)')).to have_content('kr')
          expect(find('#scope_selector li:nth-child(3)')).to have_content('White')
          expect(find('#scope_selector li:last')).to have_content('White')
          expect(find('#scope_selector li.active')).to have_content('any')
        end
      end
    end
  end
end


text:
function data = loadWithMedianFilter(filename)
%
%this function reads the "data" structure from the file specified.
%
%it should be a structure with fields:
%data.positions =[nodeID xPos yPos zPos] in centimeters
%data.RSSI = [receiverId transmitterId packetNumber packetIndex rssi-1 rssi-2 ... rssi-10]
%
%this function returns the data in the format:
%data = [receiverId transmitterId estimatedDistance trueDistance]
%where estimated distance is the mean of the medians over all packets from
%transmitterId to receiverId, where the median is
%take over all readings for each packet.  If there is an even number of
%readings per packet, it uses an average of the middle two elements.

load(filename)
if length(data.RSSI)==0 error(['no RSSI data in file:' filename]); return; end

%this is a hack because the first row of data.RSSI is always zeros:
data.RSSI=data.RSSI(2:end,:);

%first, figure out who the transmitters and receivers are
transmitters=sort(data.RSSI(:,2));
uniques=[find(diff(transmitters)>0); length(transmitters)];
transmitters=transmitters(uniques)';
receivers=sort(data.RSSI(:,1));
uniques=[find(diff(receivers)>0); length(receivers)];
receivers=receivers(uniques)';

%now, for each transmitter/receiver pair
row=1;
for r=receivers
    for t=transmitters
        %store the estimated distance (using the mean filter)
        rssi=data.RSSI(find(data.RSSI(:,2)==t), :);
        rssi=rssi(find(rssi(:,1)==r), :);
        if ~isempty(rssi)
            x(row,3)=mean(median(rssi(:,5:14),2));
        else
            continue;
        end

        %store their IDs
        x(row,1:2)=[r t];

        %store the true distance
        rPos=data.positions(find(data.positions(:,1)==r),2:3);
        tPos=data.positions(find(data.positions(:,1)==t),2:3);
        x(row,4)=sqrt( (rPos(1)-tPos(1))^2 + (rPos(2)-tPos(2))^2 );

        %get ready for the next one
        row=row+1;
    end
end
data=x;


text:
@implementation PageCollectionViewController
@synthesize pageSet, header, deleter, book;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    cellArray = [[NSMutableArray alloc]init];
	pageArray = [[NSMutableArray alloc]init];
    for (Page *p in pageSet){
        [pageArray addObject: p];
    }

    [pageArray sortUsingComparator:
        ^NSComparisonResult(id obj1, id obj2){

            Page *p1 = (Page*)obj1;
            Page *p2 = (Page*)obj2;
            if ([p1.pageNumber intValue] > [p2.pageNumber intValue]) {
                return (NSComparisonResult)NSOrderedDescending;
            }

            if ([p1.pageNumber intValue] < [p2.pageNumber intValue]) {
                return (NSComparisonResult)NSOrderedAscending;
            }
            return (NSComparisonResult)NSOrderedSame;
     }];

    imageArray = [[NSMutableArray alloc]init];

    isDeleteActive = FALSE;
    [deleter setTarget: self];
    [deleter setAction: @selector(activateDelete)];

}

-(void)viewWillAppear:(BOOL)animated{

}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

    return [pageArray count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *identifier = @"CollectionCell";

    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

    Page *coverPage = [pageArray objectAtIndex: indexPath.row];

    UILabel *num = (UILabel *)[cell viewWithTag:100];
    if ([coverPage.pageNumber intValue] == 0){
        num.text = @"cover";
    }else{
        num.text = [coverPage.pageNumber stringValue];
    }

    UIImageView *gridImageView = (UIImageView *)[cell viewWithTag:99];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{

        dispatch_async(dispatch_get_main_queue(), ^{

            if(indexPath.row >= [imageArray count]){
                NSNumber *pageN = [NSNumber numberWithInt: [coverPage.pageNumber intValue]];
                UIImage *coverPhoto = [self getImage:pageN];
                [imageArray addObject:coverPhoto];
                [UIView transitionWithView: gridImageView
                              duration:0.3f
                               options:UIViewAnimationOptionTransitionCrossDissolve
                            animations:^{
                                gridImageView.image =  [self imageWithImage:coverPhoto scaledToSize:CGSizeMake(61, 90)];
                            } completion:nil];
            }else{
                gridImageView.image = [self imageWithImage:[imageArray objectAtIndex:indexPath.row] scaledToSize: CGSizeMake(61, 90)];
            }
        });

    });

//    if ([selectedIndexPath isEqual:indexPath]) {
//        cell.backgroundColor = [UIColor colorWithRed:(255/255.0) green:(141/255.0) blue:(106/255.0) alpha:1.0];
//    } else {
//        cell.backgroundColor = [UIColor colorWithRed:(255/255.0) green:(141/255.0) blue:(106/255.0) alpha:0.0];
//
//    }

    [cellArray addObject: cell];

    return cell;
}

-(UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

- (UIImage*)getImage: (NSNumber *) pageNumber{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,     NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:header];
    getImagePath = [getImagePath stringByAppendingString: [pageNumber stringValue]];
    getImagePath = [getImagePath stringByAppendingString:@".jpeg"];
    NSLog(@"%@", getImagePath);
    UIImage *img = [UIImage imageWithContentsOfFile:getImagePath];
    return img;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if(isDeleteActive){
        selectedIndexPath = indexPath.row;
        UIAlertView *alert;

        if(indexPath.row != 0){
            alert = [[UIAlertView alloc] initWithTitle:@"Wait" message:@"Are you sure you want to delete this.  This action cannot be undone" delegate:self cancelButtonTitle:@"Delete" otherButtonTitles:@"Cancel", nil];
        }else{
            alert = [[UIAlertView alloc] initWithTitle:@"Hey"
                                                message:@"Don't delete the cover page!"
                                                delegate:nil
                                                cancelButtonTitle:@"Ok"
                                                otherButtonTitles:nil];
        }

        [alert show];
    }else{
        NSMutableArray *photos = [[NSMutableArray alloc]init];

        for (int i = 0; i < [imageArray count]; i++) {
            IDMPhoto *photo = [IDMPhoto photoWithImage:[imageArray objectAtIndex:i]];
            [photos addObject: photo];
        }

        IDMPhotoBrowser *browser = [[IDMPhotoBrowser alloc] initWithPhotos: photos];
        [browser setInitialPageIndex:indexPath.row];
        [self presentViewController:browser animated:YES completion:nil];
    }

}

- (void) activateDelete {

    if(!isDeleteActive){
        deleter.title = @"View";
        isDeleteActive = TRUE;
    }else{
        deleter.title = @"Edit";
        isDeleteActive = FALSE;
    }

}

- (void) deleteFiles: (Page *)deletedPage {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *err;
    NSString *filePath = deletedPage.imageURL;
    BOOL success = [fileManager removeItemAtPath:filePath error:&err];
    NSLog(@"WEWEFWEF %d", success);

    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *context = [appDelegate managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setEntity:[NSEntityDescription entityForName:@"Page" inManagedObjectContext:context]];
    [fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"imageURL == %@", deletedPage.imageURL]];
    NSError* error = nil;
    NSArray* results = [context executeFetchRequest:fetchRequest error:&error];

    for (NSManagedObject *product in results) {
        NSLog(@"%@", product);
        [context deleteObject:product];
    }
    //x[book removeHasPagesObject: deletedPage];
    [context save:&error];

    if ([context save:&error]) {
        NSLog(@"Successfully saved the context.");
    } else {
        NSLog(@"Failed to save the context. Error = %@", error);
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0){
        Page *p = [pageArray objectAtIndex: selectedIndexPath];
        [self deleteFiles: p];
        [imageArray removeObjectAtIndex: selectedIndexPath];
        [pageArray removeObjectAtIndex: selectedIndexPath];
        [self.collectionView performBatchUpdates:^{
            [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
        } completion:nil];
    }
}

#pragma mark - IDMPhotoBrowser Delegate

- (void)photoBrowser:(IDMPhotoBrowser *)photoBrowser didDismissAtPageIndex:(NSUInteger)pageIndex
{
    id <IDMPhoto> photo = [photoBrowser photoAtIndex:pageIndex];
    NSLog(@"Did dismiss photoBrowser with photo index: %d, photo caption: %@", pageIndex, photo.caption);
}

- (void)photoBrowser:(IDMPhotoBrowser *)photoBrowser didDismissActionSheetWithButtonIndex:(NSUInteger)buttonIndex photoIndex:(NSUInteger)photoIndex
{
    id <IDMPhoto> photo = [photoBrowser photoAtIndex:photoIndex];
    NSLog(@"Did dismiss actionSheet with photo index: %d, photo caption: %@", photoIndex, photo.caption);

    NSString *title = [NSString stringWithFormat:@"Option %d", buttonIndex+1];
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(25, 25, 15, 15);
}

@end


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Class virtual_</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../index.html" title="Chapter 1. Boost.Contract 1.0.0">
<link rel="up" href="../../reference.html#header.boost.contract.core.virtual_hpp" title="Header <boost/contract/core/virtual.hpp>">
<link rel="prev" href="specify_except.html" title="Class specify_except">
<link rel="next" href="destructor.html" title="Function template destructor">

Home
Libraries
People
FAQ
More

Class virtual_

boost::contract::virtual_ — Type of extra function parameter to handle contracts for virtual public functions (for subcontracting).

Synopsis

// In header: <boost/contract/core/virtual.hpp>

class virtual_ {
};

Description

Virtual public functions (and therefore also public function overrides) declaring contracts using this library must specify an extra function parameter at the very end of the parameter list. This parameter must be a pointer to this class and it must have default value 0 (i.e., nullptr). (This extra parameter is often named v in this documentation, but any name can be used.)

In practice this extra parameter does not alter the calling interface of the enclosing function declaring the contract because it is always the very last parameter and it has a default value (so it can always be omitted when users call the function). This extra parameter must be passed to  boost::contract::public_function, BOOST_CONTRACT_OLDOF, and all other operations of this library that accept a pointer to  boost::contract::virtual_. A part from that, this class is not intended to be directly used by programmers (and that is why this class does not have any public member and it is not copyable).

See Also:

  Virtual Public Functions,
        Public Function Overrides

Copyright © 2008-2018 Lorenzo Caminiti

        Distributed under the Boost Software License, Version 1.0 (see accompanying
        file LICENSE_1_0.txt or a copy at http://www.boost.org/LICENSE_1_0.txt)


text:
exports.afterRender = function() {
  const route = this.route;
  this.body =
`<div class="${route.module}-${route.action}">
  ${this.body}
</div>`;
};


text:
import { ACCOUNT_PATH as path } from 'constants/paths'

export default (store) => ({
  path,
  /*  Async getComponent is only invoked when route matches   */
  getComponent (nextState, cb) {
    /*  Webpack - use 'require.ensure' to create a split point
        and embed an async module loader (jsonp) when bundling   */
    require.ensure([], (require) => {
      /*  Webpack - use require callback to define
          dependencies for bundling   */
      const Account = require('containers/Account/AccountContainer').default

      /*  Return getComponent   */
      cb(null, Account)

    /* Webpack named bundle   */
    }, 'Account')
  }
})


text:
#include <stdbool.h>
#include <stdint.h>
#include "datatypes.h"

/**
 * move.h / move.c
 *
 * Functions to create and modify Move instances.
 *
 */
#ifndef _MOVE_H_
#define _MOVE_H_

/**
 * Creates a blank Move; doesn't initialize memory for it,
 * only allocates.
 * Only use then filling in ALL content of the Move yourself,
 * otherwise use Move_create.
 */
Move *Move_alloc();

/**
 * Creates a new Move.
 * Source field is x,y and target is xx,yy. `promotion`, if not
 * EMPTY, is the piece to promote to in case of a pawn promotion.
 */
Move *Move_create(int color, int x, int y, int xx, int yy, int promotion);

/**
 * Copy constructor. Doesn't copy any siblings.
 */
Move *Move_clone(Move *move);

/**
 * Recursively destroys this move and all its following siblings.
 */
void Move_destroy(Move *m);

/**
 * Returns true for moves that are empty dummymoves,
 * that are used as the start of a linked list of moves.
 */
inline bool Move_is_nullmove(Move *m) {
	return (m == NULL)
		|| (m->x == 0 && m->y == 0 && m->xx == 0 && m->yy == 0);
}

inline bool Move_equals(Move *m1, Move *m2) {
	return m1->x == m2->x && m1->y == m2->y && m1->xx == m2->xx && m1->yy == m2->yy;
}

unsigned int Move_get_as_int(Move *m);

/**
 * This is just a simple toString method.
 * For official notation use AN_format(board, move)
 */
void Move_print(Move *m);

/**
 * Like Move_print(Move*), but with color.
 */
void Move_print_color(Move *m, int color);

void Move_print_all(Move *head);

/**
* Compare values to another move.
* When sorting, this'll sort in order of ascending move value.
* For white this puts the worst move first, for black the best move
*/
inline int Move_compare(Move *m1, Move *m2) {
	return m1->fitness - m2->fitness;
}

/**
 * Constructor for UndoableMoves, i.e. structs that contain instructions on
 * how to undo a move.
 */
UndoableMove *Undo_create(int x, int y, int xx, int yy, int hit_y, Piece *piece, bool white_can_castle_queens_side, bool white_can_castle_kings_side, bool black_can_castle_queens_side, bool black_can_castle_kings_side, bool white_can_en_passant, bool black_can_en_passant);

/**
 * Cleans up an UndoableMove
 */
void Undo_destroy(UndoableMove* umove);

/**
 * Checks if the UndoableMove is the first of a chain of moves.
 * Since the UndoableMoves are basically on a stack (FILO), this
 * technically means the UndoableMove is the last and the Move is the first.
 */
inline bool Move_is_first(UndoableMove *umove) {
	return umove->previous == NULL;
}

inline int Move_quiescence(UndoableMove *umove, Board *board) {
	return umove->hit_piece == NULL ? 0 : QUIESCENCE_PENALTY_CAPTURE;
}

#endif


text:
<?php
namespace Exar\Annotation\Matcher;

use Exar\ExarTest;

class NumberMatcherTest extends ExarTest {
    public function testNumbers() {
        $m = new NumberMatcher();

        $str = '34abc';
        $result = $m->match($str);
        $this->assertTrue(is_integer($result));
        $this->assertEquals(34, $result);
        $this->assertEquals('abc', $str);

        $str = '3.14159-';
        $result = $m->match($str);
        $this->assertTrue(is_float($result));
        $this->assertEquals(3.14159, $result);
        $this->assertEquals('-', $str);

        $str = 'str';
        try {
            $m->match($str);
            $this->fail('An exception was expected');
        } catch(StringNotMatchedException $e) {
            $this->assertEquals('str', $str);
        }
    }

    /**
     * @expectedException Exar\Annotation\Matcher\StringNotMatchedException
     */
    public function testWhiteSpaces() {
        $m = new NumberMatcher('(');
        $str = '   654   ';
        $m->match($str);
    }
}


text:
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Baseline;
using Marten.Schema;
using Marten.Testing.Documents;
using Marten.Testing.Harness;
using Shouldly;
using Weasel.Postgresql.Tables;
using Xunit;

namespace Marten.Testing.Acceptance
{
    [Collection("acceptance")]
    public class computed_indexes: OneOffConfigurationsContext
    {
        [Fact]
        public void example()
        {
            #region sample_using-a-simple-calculated-index
            var store = DocumentStore.For(_ =>
            {
                _.Connection(ConnectionSource.ConnectionString);

                _.DatabaseSchemaName = "examples";

                // This creates
                _.Schema.For<User>().Index(x => x.UserName);
            });

            using (var session = store.QuerySession())
            {
                // Postgresql will be able to use the computed
                // index generated from above
                var somebody = session
                    .Query<User>()
                    .FirstOrDefault(x => x.UserName == "somebody");
            }
            #endregion sample_using-a-simple-calculated-index

            store.Dispose();
        }

        [Fact]
        public async Task smoke_test()
        {
            StoreOptions(_ => _.Schema.For<Target>().Index(x => x.Number));

            var data = Target.GenerateRandomData(100).ToArray();
            await theStore.BulkInsertAsync(data.ToArray());

            var table = await theStore.Tenancy.Default.ExistingTableFor(typeof(Target));
            table.HasIndex("mt_doc_target_idx_number").ShouldBeTrue();

            using var session = theStore.QuerySession();
            var cmd = session.Query<Target>().Where(x => x.Number == 3)
                .ToCommand();

            session.Query<Target>().Where(x => x.Number == data.First().Number)
                .Select(x => x.Id).ToList().ShouldContain(data.First().Id);
        }

        [Fact]
        public void specify_a_deep_index()
        {
            #region sample_deep-calculated-index
            var store = DocumentStore.For(_ =>
            {
                _.Connection(ConnectionSource.ConnectionString);

                _.Schema.For<Target>().Index(x => x.Inner.Color);
            });
            #endregion sample_deep-calculated-index
        }

        [Fact]
        public void specify_a_different_mechanism_to_customize_the_index()
        {
            #region sample_customizing-calculated-index
            var store = DocumentStore.For(_ =>
            {
                _.Connection(ConnectionSource.ConnectionString);

                // The second, optional argument to Index()
                // allows you to customize the calculated index
                _.Schema.For<Target>().Index(x => x.Number, x =>
                        {
                            // Change the index method to "brin"
                            x.Method = IndexMethod.brin;

                            // Force the index to be generated with casing rules
                            x.Casing = ComputedIndex.Casings.Lower;

                            // Override the index name if you want
                            x.Name = "mt_my_name";

                            // Toggle whether or not the index is concurrent
                            // Default is false
                            x.IsConcurrent = true;

                            // Toggle whether or not the index is a UNIQUE
                            // index
                            x.IsUnique = true;

                            // Toggle whether index value will be constrained unique in scope of whole document table (Global)
                            // or in a scope of a single tenant (PerTenant)
                            // Default is Global
                            x.TenancyScope = Schema.Indexing.Unique.TenancyScope.PerTenant;

                            // Partial index by supplying a condition
                            x.Predicate = "(data ->> 'Number')::int > 10";
                        });

                // For B-tree indexes, it's also possible to change
                // the sort order from the default of "ascending"
                _.Schema.For<User>().Index(x => x.LastName, x =>
                        {
                            // Change the index method to "brin"
                            x.SortOrder = SortOrder.Desc;
                        });
            });
            #endregion sample_customizing-calculated-index
        }

        [Fact]
        public async Task create_multi_property_index()
        {
            StoreOptions(_ =>
            {
                var columns = new Expression<Func<Target, object>>[]
                {
                    x => x.UserId,
                    x => x.Flag
                };
                _.Schema.For<Target>().Index(columns);
            });

            var data = Target.GenerateRandomData(100).ToArray();
            await theStore.BulkInsertAsync(data.ToArray());

            var table = await theStore.Tenancy.Default.ExistingTableFor(typeof(Target));
            var index = table.IndexFor("mt_doc_target_idx_user_idflag").As<ActualIndex>();

            index.DDL.ShouldBe("CREATE INDEX mt_doc_target_idx_user_idflag ON acceptance.mt_doc_target USING btree ((((data ->> 'UserId'::text))::uuid), (((data ->> 'Flag'::text))::boolean));");

        }

        [Fact]
        public async Task create_multi_property_string_index_with_casing()
        {
            StoreOptions(_ =>
            {
                var columns = new Expression<Func<Target, object>>[]
                {
                    x => x.String,
                    x => x.StringField
                };
                _.Schema.For<Target>().Index(columns, c => c.Casing = ComputedIndex.Casings.Upper);
            });

            var data = Target.GenerateRandomData(100).ToArray();
            await theStore.BulkInsertAsync(data.ToArray());

            var table = await theStore.Tenancy.Default.ExistingTableFor(typeof(Target));
            var index = table.IndexFor("mt_doc_target_idx_stringstring_field").ShouldBeOfType<ActualIndex>();

            index.DDL.ShouldBe("CREATE INDEX mt_doc_target_idx_stringstring_field ON acceptance.mt_doc_target USING btree (upper((data ->> 'String'::text)), upper((data ->> 'StringField'::text)));");

        }

        [Fact]
        public void creating_index_using_date_should_work()
        {
            StoreOptions(_ =>
            {
                _.Schema.For<Target>().Index(x => x.Date);
            });

            var data = Target.GenerateRandomData(100).ToArray();
            theStore.BulkInsert(data.ToArray());

        }

        [Fact]
        public async Task create_index_with_custom_name()
        {
            StoreOptions(_ => _.Schema.For<Target>().Index(x => x.String, x =>
            {
                x.Name = "mt_banana_index_created_by_nigel";
            }));

            var testString = "MiXeD cAsE sTrInG";

            using (var session = theStore.LightweightSession())
            {
                var item = Target.GenerateRandomData(1).First();
                item.String = testString;
                session.Store(item);
                await session.SaveChangesAsync();
            }

            (await theStore.Tenancy.Default.ExistingTableFor(typeof(Target)))
                .HasIndex("mt_banana_index_created_by_nigel");

        }

        [Fact]
        public async Task patch_if_missing()
        {
            using (var store1 = SeparateStore())
            {
                store1.Advanced.Clean.CompletelyRemoveAll();

                store1.Tenancy.Default.EnsureStorageExists(typeof(Target));
            }

            using (var store2 = DocumentStore.For(_ =>
            {
                _.Connection(ConnectionSource.ConnectionString);
                _.Schema.For<Target>().Index(x => x.Number);
            }))
            {
                var patch = await store2.Schema.CreateMigration();

                patch.UpdateSql.ShouldContain( "mt_doc_target_idx_number", Case.Insensitive);
            }
        }

        public computed_indexes() : base("acceptance")
        {
        }
    }
}


text:
void foo();

#include <leathers/push>
#if !defined(SHOW_WARNINGS)
# include <leathers/missing-noreturn>
#endif
void foo() {
  throw -1;
}
#include <leathers/pop>

int main() {
}