text:
/*
 * Written by Doug Lea with assistance from members of JCP JSR-166
 * Expert Group and released to the public domain, as explained at
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

package utils.collections.concurrent;

/**
 * A {@link ForkJoinTask} with a completion action performed when
 * triggered and there are no remaining pending actions.
 * CountedCompleters are in general more robust in the
 * presence of subtask stalls and blockage than are other forms of
 * ForkJoinTasks, but are less intuitive to program.  Uses of
 * CountedCompleter are similar to those of other completion based
 * components (such as {@link java.nio.channels.CompletionHandler})
 * except that multiple pending completions may be necessary
 * to trigger the completion action {@link #onCompletion(CountedCompleter)},
 * not just one.
 * Unless initialized otherwise, the {@linkplain #getPendingCount pending
 * count} starts at zero, but may be (atomically) changed using
 * methods {@link #setPendingCount}, {@link #addToPendingCount}, and
 * {@link #compareAndSetPendingCount}. Upon invocation of {@link
 * #tryComplete}, if the pending action count is nonzero, it is
 * decremented; otherwise, the completion action is performed, and if
 * this completer itself has a completer, the process is continued
 * with its completer.  As is the case with related synchronization
 * components such as {@link java.util.concurrent.Phaser Phaser} and
 * {@link java.util.concurrent.Semaphore Semaphore}, these methods
 * affect only internal counts; they do not establish any further
 * internal bookkeeping. In particular, the identities of pending
 * tasks are not maintained. As illustrated below, you can create
 * subclasses that do record some or all pending tasks or their
 * results when needed.  As illustrated below, utility methods
 * supporting customization of completion traversals are also
 * provided. However, because CountedCompleters provide only basic
 * synchronization mechanisms, it may be useful to create further
 * abstract subclasses that maintain linkages, fields, and additional
 * support methods appropriate for a set of related usages.
 *
 *
A concrete CountedCompleter class must define method {@link
 * #compute}, that should in most cases (as illustrated below), invoke
 * {@code tryComplete()} once before returning. The class may also
 * optionally override method {@link #onCompletion(CountedCompleter)}
 * to perform an action upon normal completion, and method
 * {@link #onExceptionalCompletion(Throwable, CountedCompleter)} to
 * perform an action upon any exceptions.
 *
 *
CountedCompleters most often do not bear results, in which case
 * they are normally declared as {@code CountedCompleter<Void>}, and
 * will always return {@code null} as a result value.  In other cases,
 * you should override method {@link #getRawResult} to provide a
 * result from {@code join(), invoke()}, and related methods.  In
 * general, this method should return the value of a field (or a
 * function of one or more fields) of the CountedCompleter object that
 * holds the result upon completion. Method {@link #setRawResult} by
 * default plays no role in CountedCompleters.  It is possible, but
 * rarely applicable, to override this method to maintain other
 * objects or fields holding result data.
 *
 *
A CountedCompleter that does not itself have a completer (i.e.,
 * one for which {@link #getCompleter} returns {@code null}) can be
 * used as a regular ForkJoinTask with this added functionality.
 * However, any completer that in turn has another completer serves
 * only as an internal helper for other computations, so its own task
 * status (as reported in methods such as {@link ForkJoinTask#isDone})
 * is arbitrary; this status changes only upon explicit invocations of
 * {@link #complete}, {@link ForkJoinTask#cancel},
 * {@link ForkJoinTask#completeExceptionally(Throwable)} or upon
 * exceptional completion of method {@code compute}. Upon any
 * exceptional completion, the exceptions may be relayed to a task's
 * completer (and its completer, and so on), if one exists and it has
 * not otherwise already completed. Similarly, cancelling an internal
 * CountedCompleter has only a local effect on that completer, so is
 * not often useful.
 *
 *
Sample Usages.
 *
 *
Parallel recursive decomposition. CountedCompleters may
 * be arranged in trees similar to those often used with {@link
 * RecursiveAction}s, although the constructions involved in setting
 * them up typically vary. Here, the completer of each task is its
 * parent in the computation tree. Even though they entail a bit more
 * bookkeeping, CountedCompleters may be better choices when applying
 * a possibly time-consuming operation (that cannot be further
 * subdivided) to each element of an array or collection; especially
 * when the operation takes a significantly different amount of time
 * to complete for some elements than others, either because of
 * intrinsic variation (for example I/O) or auxiliary effects such as
 * garbage collection.  Because CountedCompleters provide their own
 * continuations, other threads need not block waiting to perform
 * them.
 *
 *
For example, here is an initial version of a class that uses
 * divide-by-two recursive decomposition to divide work into single
 * pieces (leaf tasks). Even when work is split into individual calls,
 * tree-based techniques are usually preferable to directly forking
 * leaf tasks, because they reduce inter-thread communication and
 * improve load balancing. In the recursive case, the second of each
 * pair of subtasks to finish triggers completion of its parent
 * (because no result combination is performed, the default no-op
 * implementation of method {@code onCompletion} is not overridden).
 * A static utility method sets up the base task and invokes it
 * (here, implicitly using the {@link ForkJoinPool#commonPool()}).
 *
 *
 {@code
 * class MyOperation<E> { void apply(E e) { ... }  }
 *
 * class ForEach<E> extends CountedCompleter<Void> {
 *
 *   public static <E> void forEach(E[] array, MyOperation<E> op) {
 *     new ForEach<E>(null, array, op, 0, array.length).invoke();
 *   }
 *
 *   final E[] array; final MyOperation<E> op; final int lo, hi;
 *   ForEach(CountedCompleter<?> p, E[] array, MyOperation<E> op, int lo, int hi) {
 *     super(p);
 *     this.array = array; this.op = op; this.lo = lo; this.hi = hi;
 *   }
 *
 *   public void compute() { // version 1
 *     if (hi - lo >= 2) {
 *       int mid = (lo + hi) >>> 1;
 *       setPendingCount(2); // must set pending count before fork
 *       new ForEach(this, array, op, mid, hi).fork(); // right child
 *       new ForEach(this, array, op, lo, mid).fork(); // left child
 *     }
 *     else if (hi > lo)
 *       op.apply(array[lo]);
 *     tryComplete();
 *   }
 * }}

 *
 * This design can be improved by noticing that in the recursive case,
 * the task has nothing to do after forking its right task, so can
 * directly invoke its left task before returning. (This is an analog
 * of tail recursion removal.)  Also, because the task returns upon
 * executing its left task (rather than falling through to invoke
 * {@code tryComplete}) the pending count is set to one:
 *
 *
 {@code
 * class ForEach<E> ...
 *   public void compute() { // version 2
 *     if (hi - lo >= 2) {
 *       int mid = (lo + hi) >>> 1;
 *       setPendingCount(1); // only one pending
 *       new ForEach(this, array, op, mid, hi).fork(); // right child
 *       new ForEach(this, array, op, lo, mid).compute(); // direct invoke
 *     }
 *     else {
 *       if (hi > lo)
 *         op.apply(array[lo]);
 *       tryComplete();
 *     }
 *   }
 * }

 *
 * As a further improvement, notice that the left task need not even exist.
 * Instead of creating a new one, we can iterate using the original task,
 * and add a pending count for each fork.  Additionally, because no task
 * in this tree implements an {@link #onCompletion(CountedCompleter)} method,
 * {@code tryComplete()} can be replaced with {@link #propagateCompletion}.
 *
 *
 {@code
 * class ForEach<E> ...
 *   public void compute() { // version 3
 *     int l = lo,  h = hi;
 *     while (h - l >= 2) {
 *       int mid = (l + h) >>> 1;
 *       addToPendingCount(1);
 *       new ForEach(this, array, op, mid, h).fork(); // right child
 *       h = mid;
 *     }
 *     if (h > l)
 *       op.apply(array[l]);
 *     propagateCompletion();
 *   }
 * }

 *
 * Additional improvements of such classes might entail precomputing
 * pending counts so that they can be established in constructors,
 * specializing classes for leaf steps, subdividing by say, four,
 * instead of two per iteration, and using an adaptive threshold
 * instead of always subdividing down to single elements.
 *
 *
Searching. A tree of CountedCompleters can search for a
 * value or property in different parts of a data structure, and
 * report a result in an {@link
 * java.util.concurrent.atomic.AtomicReference AtomicReference} as
 * soon as one is found. The others can poll the result to avoid
 * unnecessary work. (You could additionally {@linkplain #cancel
 * cancel} other tasks, but it is usually simpler and more efficient
 * to just let them notice that the result is set and if so skip
 * further processing.)  Illustrating again with an array using full
 * partitioning (again, in practice, leaf tasks will almost always
 * process more than one element):
 *
 *
 {@code
 * class Searcher<E> extends CountedCompleter<E> {
 *   final E[] array; final AtomicReference<E> result; final int lo, hi;
 *   Searcher(CountedCompleter<?> p, E[] array, AtomicReference<E> result, int lo, int hi) {
 *     super(p);
 *     this.array = array; this.result = result; this.lo = lo; this.hi = hi;
 *   }
 *   public E getRawResult() { return result.get(); }
 *   public void compute() { // similar to ForEach version 3
 *     int l = lo,  h = hi;
 *     while (result.get() == null && h >= l) {
 *       if (h - l >= 2) {
 *         int mid = (l + h) >>> 1;
 *         addToPendingCount(1);
 *         new Searcher(this, array, result, mid, h).fork();
 *         h = mid;
 *       }
 *       else {
 *         E x = array[l];
 *         if (matches(x) && result.compareAndSet(null, x))
 *           quietlyCompleteRoot(); // root task is now joinable
 *         break;
 *       }
 *     }
 *     tryComplete(); // normally complete whether or not found
 *   }
 *   boolean matches(E e) { ... } // return true if found
 *
 *   public static <E> E search(E[] array) {
 *       return new Searcher<E>(null, array, new AtomicReference<E>(), 0, array.length).invoke();
 *   }
 * }}

 *
 * In this example, as well as others in which tasks have no other
 * effects except to compareAndSet a common result, the trailing
 * unconditional invocation of {@code tryComplete} could be made
 * conditional ({@code if (result.get() == null) tryComplete();})
 * because no further bookkeeping is required to manage completions
 * once the root task completes.
 *
 *
Recording subtasks. CountedCompleter tasks that combine
 * results of multiple subtasks usually need to access these results
 * in method {@link #onCompletion(CountedCompleter)}. As illustrated in the following
 * class (that performs a simplified form of map-reduce where mappings
 * and reductions are all of type {@code E}), one way to do this in
 * divide and conquer designs is to have each subtask record its
 * sibling, so that it can be accessed in method {@code onCompletion}.
 * This technique applies to reductions in which the order of
 * combining left and right results does not matter; ordered
 * reductions require explicit left/right designations.  Variants of
 * other streamlinings seen in the above examples may also apply.
 *
 *
 {@code
 * class MyMapper<E> { E apply(E v) {  ...  } }
 * class MyReducer<E> { E apply(E x, E y) {  ...  } }
 * class MapReducer<E> extends CountedCompleter<E> {
 *   final E[] array; final MyMapper<E> mapper;
 *   final MyReducer<E> reducer; final int lo, hi;
 *   MapReducer<E> sibling;
 *   E result;
 *   MapReducer(CountedCompleter<?> p, E[] array, MyMapper<E> mapper,
 *              MyReducer<E> reducer, int lo, int hi) {
 *     super(p);
 *     this.array = array; this.mapper = mapper;
 *     this.reducer = reducer; this.lo = lo; this.hi = hi;
 *   }
 *   public void compute() {
 *     if (hi - lo >= 2) {
 *       int mid = (lo + hi) >>> 1;
 *       MapReducer<E> left = new MapReducer(this, array, mapper, reducer, lo, mid);
 *       MapReducer<E> right = new MapReducer(this, array, mapper, reducer, mid, hi);
 *       left.sibling = right;
 *       right.sibling = left;
 *       setPendingCount(1); // only right is pending
 *       right.fork();
 *       left.compute();     // directly execute left
 *     }
 *     else {
 *       if (hi > lo)
 *           result = mapper.apply(array[lo]);
 *       tryComplete();
 *     }
 *   }
 *   public void onCompletion(CountedCompleter<?> caller) {
 *     if (caller != this) {
 *       MapReducer<E> child = (MapReducer<E>)caller;
 *       MapReducer<E> sib = child.sibling;
 *       if (sib == null || sib.result == null)
 *         result = child.result;
 *       else
 *         result = reducer.apply(child.result, sib.result);
 *     }
 *   }
 *   public E getRawResult() { return result; }
 *
 *   public static <E> E mapReduce(E[] array, MyMapper<E> mapper, MyReducer<E> reducer) {
 *     return new MapReducer<E>(null, array, mapper, reducer,
 *                              0, array.length).invoke();
 *   }
 * }}

 *
 * Here, method {@code onCompletion} takes a form common to many
 * completion designs that combine results. This callback-style method
 * is triggered once per task, in either of the two different contexts
 * in which the pending count is, or becomes, zero: (1) by a task
 * itself, if its pending count is zero upon invocation of {@code
 * tryComplete}, or (2) by any of its subtasks when they complete and
 * decrement the pending count to zero. The {@code caller} argument
 * distinguishes cases.  Most often, when the caller is {@code this},
 * no action is necessary. Otherwise the caller argument can be used
 * (usually via a cast) to supply a value (and/or links to other
 * values) to be combined.  Assuming proper use of pending counts, the
 * actions inside {@code onCompletion} occur (once) upon completion of
 * a task and its subtasks. No additional synchronization is required
 * within this method to ensure thread safety of accesses to fields of
 * this task or other completed tasks.
 *
 *
Completion Traversals. If using {@code onCompletion} to
 * process completions is inapplicable or inconvenient, you can use
 * methods {@link #firstComplete} and {@link #nextComplete} to create
 * custom traversals.  For example, to define a MapReducer that only
 * splits out right-hand tasks in the form of the third ForEach
 * example, the completions must cooperatively reduce along
 * unexhausted subtask links, which can be done as follows:
 *
 *
 {@code
 * class MapReducer<E> extends CountedCompleter<E> { // version 2
 *   final E[] array; final MyMapper<E> mapper;
 *   final MyReducer<E> reducer; final int lo, hi;
 *   MapReducer<E> forks, next; // record subtask forks in list
 *   E result;
 *   MapReducer(CountedCompleter<?> p, E[] array, MyMapper<E> mapper,
 *              MyReducer<E> reducer, int lo, int hi, MapReducer<E> next) {
 *     super(p);
 *     this.array = array; this.mapper = mapper;
 *     this.reducer = reducer; this.lo = lo; this.hi = hi;
 *     this.next = next;
 *   }
 *   public void compute() {
 *     int l = lo,  h = hi;
 *     while (h - l >= 2) {
 *       int mid = (l + h) >>> 1;
 *       addToPendingCount(1);
 *       (forks = new MapReducer(this, array, mapper, reducer, mid, h, forks)).fork();
 *       h = mid;
 *     }
 *     if (h > l)
 *       result = mapper.apply(array[l]);
 *     // process completions by reducing along and advancing subtask links
 *     for (CountedCompleter<?> c = firstComplete(); c != null; c = c.nextComplete()) {
 *       for (MapReducer t = (MapReducer)c, s = t.forks;  s != null; s = t.forks = s.next)
 *         t.result = reducer.apply(t.result, s.result);
 *     }
 *   }
 *   public E getRawResult() { return result; }
 *
 *   public static <E> E mapReduce(E[] array, MyMapper<E> mapper, MyReducer<E> reducer) {
 *     return new MapReducer<E>(null, array, mapper, reducer,
 *                              0, array.length, null).invoke();
 *   }
 * }}

 *
 *
Triggers. Some CountedCompleters are themselves never
 * forked, but instead serve as bits of plumbing in other designs;
 * including those in which the completion of one or more async tasks
 * triggers another async task. For example:
 *
 *
 {@code
 * class HeaderBuilder extends CountedCompleter<...> { ... }
 * class BodyBuilder extends CountedCompleter<...> { ... }
 * class PacketSender extends CountedCompleter<...> {
 *   PacketSender(...) { super(null, 1); ... } // trigger on second completion
 *   public void compute() { } // never called
 *   public void onCompletion(CountedCompleter<?> caller) { sendPacket(); }
 * }
 * // sample use:
 * PacketSender p = new PacketSender();
 * new HeaderBuilder(p, ...).fork();
 * new BodyBuilder(p, ...).fork();
 * }

 *
 * @since 1.8
 * @author Doug Lea
 */
@SuppressWarnings("all")
public abstract class CountedCompleter<T> extends ForkJoinTask<T> {
    private static final long serialVersionUID = 5232453752276485070L;

    /** This task's completer, or null if none */
    final CountedCompleter<?> completer;
    /** The number of pending tasks until completion */
    volatile int pending;

    /**
     * Creates a new CountedCompleter with the given completer
     * and initial pending count.
     *
     * @param completer this task's completer, or {@code null} if none
     * @param initialPendingCount the initial pending count
     */
    protected CountedCompleter(CountedCompleter<?> completer,
                               int initialPendingCount) {
        this.completer = completer;
        this.pending = initialPendingCount;
    }

    /**
     * Creates a new CountedCompleter with the given completer
     * and an initial pending count of zero.
     *
     * @param completer this task's completer, or {@code null} if none
     */
    protected CountedCompleter(CountedCompleter<?> completer) {
        this.completer = completer;
    }

    /**
     * Creates a new CountedCompleter with no completer
     * and an initial pending count of zero.
     */
    protected CountedCompleter() {
        this.completer = null;
    }

    /**
     * The main computation performed by this task.
     */
    public abstract void compute();

    /**
     * Performs an action when method {@link #tryComplete} is invoked
     * and the pending count is zero, or when the unconditional
     * method {@link #complete} is invoked.  By default, this method
     * does nothing. You can distinguish cases by checking the
     * identity of the given caller argument. If not equal to {@code
     * this}, then it is typically a subtask that may contain results
     * (and/or links to other results) to combine.
     *
     * @param caller the task invoking this method (which may
     * be this task itself)
     */
    public void onCompletion(CountedCompleter<?> caller) {
    }

    /**
     * Performs an action when method {@link
     * #completeExceptionally(Throwable)} is invoked or method {@link
     * #compute} throws an exceptions, and this task has not already
     * otherwise completed normally. On entry to this method, this task
     * {@link ForkJoinTask#isCompletedAbnormally}.  The return value
     * of this method controls further propagation: If {@code true}
     * and this task has a completer that has not completed, then that
     * completer is also completed exceptionally, with the same
     * exceptions as this completer.  The default implementation of
     * this method does nothing except return {@code true}.
     *
     * @param ex the exceptions
     * @param caller the task invoking this method (which may
     * be this task itself)
     * @return {@code true} if this exceptions should be propagated to this
     * task's completer, if one exists
     */
    public boolean onExceptionalCompletion(Throwable ex, CountedCompleter<?> caller) {
        return true;
    }

    /**
     * Returns the completer established in this task's constructor,
     * or {@code null} if none.
     *
     * @return the completer
     */
    public final CountedCompleter<?> getCompleter() {
        return completer;
    }

    /**
     * Returns the current pending count.
     *
     * @return the current pending count
     */
    public final int getPendingCount() {
        return pending;
    }

    /**
     * Sets the pending count to the given value.
     *
     * @param count the count
     */
    public final void setPendingCount(int count) {
        pending = count;
    }

    /**
     * Adds (atomically) the given value to the pending count.
     *
     * @param delta the value to add
     */
    public final void addToPendingCount(int delta) {
        int c;
        do {} while (!U.compareAndSwapInt(this, PENDING, c = pending, c+delta));
    }

    /**
     * Sets (atomically) the pending count to the given count only if
     * it currently holds the given expected value.
     *
     * @param expected the expected value
     * @param count the new value
     * @return {@code true} if successful
     */
    public final boolean compareAndSetPendingCount(int expected, int count) {
        return U.compareAndSwapInt(this, PENDING, expected, count);
    }

    /**
     * If the pending count is nonzero, (atomically) decrements it.
     *
     * @return the initial (undecremented) pending count holding on entry
     * to this method
     */
    public final int decrementPendingCountUnlessZero() {
        int c;
        do {} while ((c = pending) != 0 &&
                !U.compareAndSwapInt(this, PENDING, c, c - 1));
        return c;
    }

    /**
     * Returns the root of the current computation; i.e., this
     * task if it has no completer, else its completer's root.
     *
     * @return the root of the current computation
     */
    public final CountedCompleter<?> getRoot() {
        CountedCompleter<?> a = this, p;
        while ((p = a.completer) != null)
            a = p;
        return a;
    }

    /**
     * If the pending count is nonzero, decrements the count;
     * otherwise invokes {@link #onCompletion(CountedCompleter)}
     * and then similarly tries to complete this task's completer,
     * if one exists, else marks this task as complete.
     */
    public final void tryComplete() {
        CountedCompleter<?> a = this, s = a;
        for (int c;;) {
            if ((c = a.pending) == 0) {
                a.onCompletion(s);
                if ((a = (s = a).completer) == null) {
                    s.quietlyComplete();
                    return;
                }
            }
            else if (U.compareAndSwapInt(a, PENDING, c, c - 1))
                return;
        }
    }

    /**
     * Equivalent to {@link #tryComplete} but does not invoke {@link
     * #onCompletion(CountedCompleter)} along the completion path:
     * If the pending count is nonzero, decrements the count;
     * otherwise, similarly tries to complete this task's completer, if
     * one exists, else marks this task as complete. This method may be
     * useful in cases where {@code onCompletion} should not, or need
     * not, be invoked for each completer in a computation.
     */
    public final void propagateCompletion() {
        CountedCompleter<?> a = this, s = a;
        for (int c;;) {
            if ((c = a.pending) == 0) {
                if ((a = (s = a).completer) == null) {
                    s.quietlyComplete();
                    return;
                }
            }
            else if (U.compareAndSwapInt(a, PENDING, c, c - 1))
                return;
        }
    }

    /**
     * Regardless of pending count, invokes
     * {@link #onCompletion(CountedCompleter)}, marks this task as
     * complete and further triggers {@link #tryComplete} on this
     * task's completer, if one exists.  The given rawResult is
     * used as an argument to {@link #setRawResult} before invoking
     * {@link #onCompletion(CountedCompleter)} or marking this task
     * as complete; its value is meaningful only for classes
     * overriding {@code setRawResult}.  This method does not modify
     * the pending count.
     *
     *
This method may be useful when forcing completion as soon as
     * any one (versus all) of several subtask results are obtained.
     * However, in the common (and recommended) case in which {@code
     * setRawResult} is not overridden, this effect can be obtained
     * more simply using {@code quietlyCompleteRoot();}.
     *
     * @param rawResult the raw result
     */
    public void complete(T rawResult) {
        CountedCompleter<?> p;
        setRawResult(rawResult);
        onCompletion(this);
        quietlyComplete();
        if ((p = completer) != null)
            p.tryComplete();
    }

    /**
     * If this task's pending count is zero, returns this task;
     * otherwise decrements its pending count and returns {@code
     * null}. This method is designed to be used with {@link
     * #nextComplete} in completion traversal loops.
     *
     * @return this task, if pending count was zero, else {@code null}
     */
    public final CountedCompleter<?> firstComplete() {
        for (int c;;) {
            if ((c = pending) == 0)
                return this;
            else if (U.compareAndSwapInt(this, PENDING, c, c - 1))
                return null;
        }
    }

    /**
     * If this task does not have a completer, invokes {@link
     * ForkJoinTask#quietlyComplete} and returns {@code null}.  Or, if
     * the completer's pending count is non-zero, decrements that
     * pending count and returns {@code null}.  Otherwise, returns the
     * completer.  This method can be used as part of a completion
     * traversal loop for homogeneous task hierarchies:
     *
     *
 {@code
     * for (CountedCompleter<?> c = firstComplete();
     *      c != null;
     *      c = c.nextComplete()) {
     *   // ... process c ...
     * }}

     *
     * @return the completer, or {@code null} if none
     */
    public final CountedCompleter<?> nextComplete() {
        CountedCompleter<?> p;
        if ((p = completer) != null)
            return p.firstComplete();
        else {
            quietlyComplete();
            return null;
        }
    }

    /**
     * Equivalent to {@code getRoot().quietlyComplete()}.
     */
    public final void quietlyCompleteRoot() {
        for (CountedCompleter<?> a = this, p;;) {
            if ((p = a.completer) == null) {
                a.quietlyComplete();
                return;
            }
            a = p;
        }
    }

    /**
     * Supports ForkJoinTask exceptions propagation.
     */
    void internalPropagateException(Throwable ex) {
        CountedCompleter<?> a = this, s = a;
        while (a.onExceptionalCompletion(ex, s) &&
                (a = (s = a).completer) != null && a.status >= 0 &&
                a.recordExceptionalCompletion(ex) == EXCEPTIONAL)
            ;
    }

    /**
     * Implements execution conventions for CountedCompleters.
     */
    protected final boolean exec() {
        compute();
        return false;
    }

    /**
     * Returns the result of the computation. By default
     * returns {@code null}, which is appropriate for {@code Void}
     * actions, but in other cases should be overridden, almost
     * always to return a field or function of a field that
     * holds the result upon completion.
     *
     * @return the result of the computation
     */
    public T getRawResult() { return null; }

    /**
     * A method that result-bearing CountedCompleters may optionally
     * use to help maintain result data.  By default, does nothing.
     * Overrides are not recommended. However, if this method is
     * overridden to update existing objects or fields, then it must
     * in general be defined to be thread-safe.
     */
    protected void setRawResult(T t) { }

    // Unsafe mechanics
    private static final sun.misc.Unsafe U;
    private static final long PENDING;
    static {
        try {
            U = getUnsafe();
            PENDING = U.objectFieldOffset
                    (CountedCompleter.class.getDeclaredField("pending"));
        } catch (Exception e) {
            throw new Error(e);
        }
    }

    /**
     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
     * Replace with a simple call to Unsafe.getUnsafe when integrating
     * into a jdk.
     *
     * @return a sun.misc.Unsafe
     */
    private static sun.misc.Unsafe getUnsafe() {
        try {
            return sun.misc.Unsafe.getUnsafe();
        } catch (SecurityException tryReflectionInstead) {}
        try {
            return java.security.AccessController.doPrivileged
                    (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
                        public sun.misc.Unsafe run() throws Exception {
                            Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
                            for (java.lang.reflect.Field f : k.getDeclaredFields()) {
                                f.setAccessible(true);
                                Object x = f.get(null);
                                if (k.isInstance(x))
                                    return k.cast(x);
                            }
                            throw new NoSuchFieldError("the Unsafe");
                        }});
        } catch (java.security.PrivilegedActionException e) {
            throw new RuntimeException("Could not initialize intrinsics",
                    e.getCause());
        }
    }
}


text:
<?php
/**
 * LayOut插件
 * @package  plugins
 * @author   tianyi <tianyi1@staff.sina.com.cn>
 *
 */
class LayoutPlugin extends Yaf_Plugin_Abstract {

    public function __construct($layoutFile, $layoutDir=null){

    }

    public function  __set($name, $value) {

    }

    public function dispatchLoopShutdown ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response ){
        echo $request->getControllerName();
    }

    public function dispatchLoopStartup ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response ){

    }

    public function postDispatch ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response ){
        /* wrap it in the layout */
        $layout = new Yaf_View_Simple($this->_layoutDir);
        $layout->content = $body;
        $layout->assign('layout', $this->_layoutVars);

        /* set the response to use the wrapped version of the content */
        $response->setBody($layout->render($this->_layoutFile));
    }

    public function preDispatch ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response ){

    }

    public function preResponse ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response ){

    }

    public function routerShutdown ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response ){

    }

    public function routerStartup ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response ){

    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.pankai.tcctransaction.sample.order.factory;

import org.apache.commons.lang3.tuple.Pair;
import org.pankai.tcctransaction.sample.order.domain.entity.Order;
import org.pankai.tcctransaction.sample.order.domain.entity.OrderLine;
import org.pankai.tcctransaction.sample.order.domain.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by pktczwd on 2016/12/19.
 */
@Component
public class OrderFactory {

    @Autowired
    private ProductRepository productRepository;

    public Order buildOrder(long payerUserId, long payeeUserId, List<Pair<Long, Integer>> productQuantities) {

        Order order = new Order(payerUserId, payeeUserId);

        for (Pair<Long, Integer> pair : productQuantities) {
            long productId = pair.getLeft();
            order.addOrderLine(new OrderLine(productId, pair.getRight(), productRepository.findById(productId).getPrice()));
        }

        return order;
    }

}


text:
describe("Ext.ProgressBar", function() {

    var c;

    function makeProgress(config) {
        c = new Ext.ProgressBar(Ext.apply({
            renderTo: Ext.getBody(),
            width: 100
        }, config));
    }

    function expectHtml(want) {
        var have = c.textEl.elements[0].innerHTML;

        expect(have).toBe(want);

        have = (c.textEl.elements[1].innerHTML || '').replace(/<\/?.*?>/g, '');
        expect(have).toBe(want);
    }

    afterEach(function() {
        c = Ext.destroy(c);
    });

    describe("init", function() {
        describe("no configs", function() {
            beforeEach(function() {
                makeProgress();
            });

            it("should have value of 0", function() {
                expect(c.value).toBe(0);
            });

            it("should not set text", function() {
                expect(c.text).toBe('');
            });

            it("should display 0%", function() {
                expectHtml('0%');
            });
        });

        describe("value with no text config", function() {
            beforeEach(function() {
                makeProgress({
                    value: 0.42
                });
            });

            it("should have value of 0.42", function() {
                expect(c.value).toBe(0.42);
            });

            it("should not set text", function() {
                expect(c.text).toBe('');
            });

            it("should display 42%", function() {
                expectHtml('42%');
            });
        });

        describe("with text config", function() {
            beforeEach(function() {
                makeProgress({
                    text: '0/100'
                });
            });

            it("should have value of 0", function() {
                expect(c.value).toBe(0);
            });

            it("should set text", function() {
                expect(c.text).toBe('0/100');
            });

            it("should display 0/100", function() {
                expectHtml('0/100');
            });
        });
    });

    describe("setValue", function() {
        it("should cast undefined to 0", function() {
            makeProgress({
                value: 50
            });
            c.setValue(undefined);
            expect(c.getValue()).toBe(0);
        });

        it("should cast null to 0", function() {
            makeProgress({
                value: 50
            });
            c.setValue(null);
            expect(c.getValue()).toBe(0);
        });
    });

    describe("updateProgress", function() {
        beforeEach(function() {
            makeProgress();
        });

        describe("no text", function() {
            beforeEach(function() {
                c.updateProgress(0.42);
            });

            it("should set value to 0.42", function() {
                expect(c.value).toBe(0.42);
            });

            it("should not set text", function() {
                expect(c.text).toBe('');
            });

            it("should display 42%", function() {
                expectHtml('42%');
            });
        });

        describe("with text", function() {
            beforeEach(function() {
                c.updateProgress(0.99, 'Almost there');
            });

            it("should set value to 0.99", function() {
                expect(c.value).toBe(0.99);
            });

            it("should set text", function() {
                expect(c.text).toBe('Almost there');
            });

            it("should display the text", function() {
                expectHtml('Almost there');
            });
        });
    });

    describe("wait", function() {
        beforeEach(function() {
            makeProgress();
        });
        it("should be able to set a text", function() {
            c.wait({
                interval: 100,
                duration: 1000,
                text: 'Foo...',
                scope: c,
                fn: function() {
                    this.updateText('Bar');
                }
            });

            waitsFor(function() {
                return c.text.length;
            });

            runs(function() {
                expect(c.text).toBe('Foo...');
            });

            waitsFor(function() {
                return c.text !== 'Foo...';
            }, 'callback text');

            runs(function (){
                expect(c.text).toBe('Bar');
            });
        });

        it("should display %age if no text has been specified", function() {
            var innerHtml;
            c.wait({
                interval: 100,
                duration: 1000
            });

            waitsFor(function() {
                innerHtml = c && c.textEl && c.textEl.elements[1].innerHTML;
                return innerHtml.length;
            });

            runs(function() {
                expect(innerHtml).toBe('10%');
            });
        });
    });

    describe("Accessibility", function() {
        describe("general", function() {
            beforeEach(function() {
                makeProgress();
            });

            it("should have progressbar role", function() {
                expect(c).toHaveAttr('role', 'progressbar');
            });

            it("should be tabbable", function() {
                expect(c).toHaveAttr('tabIndex', '0');
            });

            it("should have aria-valuemin attribute", function() {
                expect(c).toHaveAttr('aria-valuemin', '0');
            });

            it("should have aria-valuemax attribute", function() {
                expect(c).toHaveAttr('aria-valuemax', '100');
            });

            it("should have aria-valuenow attribute", function() {
                expect(c).toHaveAttr('aria-valuenow', '0');
            });
        });

        describe("no text", function() {
            beforeEach(function() {
                makeProgress();
            });

            it("should not have aria-valuetext attribute", function() {
                expect(c).not.toHaveAttr('aria-valuetext');
            });

            describe("updating with no text", function() {
                beforeEach(function() {
                    c.updateProgress(0.42);
                });

                it("should update aria-valuenow attribute", function() {
                    expect(c).toHaveAttr('aria-valuenow', '42');
                });

                it("should not set aria-valuetext when updating value", function() {
                    expect(c).not.toHaveAttr('aria-valuetext');
                });
            });

            describe("updating with text", function() {
                beforeEach(function() {
                    c.updateProgress(0.42, '42% complete');
                });

                it("should update aria-valuenow attribute", function() {
                    expect(c).toHaveAttr('aria-valuenow', '42');
                });

                it("should update aria-valuetext attribute", function() {
                    expect(c).toHaveAttr('aria-valuetext', '42% complete');
                });
            });
        });

        describe("with text", function() {
            beforeEach(function() {
                makeProgress({
                    text: 'Complete 10%'
                });
            });

            it("should have aria-valuetext attribute", function() {
                expect(c).toHaveAttr('aria-valuetext', 'Complete 10%');
            });

            describe("updating with no text", function() {
                beforeEach(function() {
                    c.updateProgress(0.58);
                });

                it("should update aria-valuenow attribute", function() {
                    expect(c).toHaveAttr('aria-valuenow', '58');
                });

                it("should remove aria-valuetext attribute", function() {
                    expect(c).not.toHaveAttribute('aria-valuetext');
                });
            });

            describe("updating with text", function() {
                beforeEach(function() {
                    c.updateProgress(0.88, 'Time jump!');
                });

                it("should update aria-valuenow attribute", function() {
                    expect(c).toHaveAttr('aria-valuenow', '88');
                });

                it("should update aria-valuetext attribute", function() {
                    expect(c).toHaveAttr('aria-valuetext', 'Time jump!');
                });
            });
        });
    });
});


text:
layout: page
title:	sql injection
category: blog
description:
---
# Preface

# Blind SQL
不显示错误,盲注

# sql Injection
> https://www.owasp.org/index.php/SQL_Injection
> https://www.owasp.org/index.php/Testing_for_SQL_Injection_(OTG-INPVAL-005)

	select * from name = '$name'
		$name = "ahui' or 'a'='a"
		$name = "ahui' ;delete from t1; --"
		$name = "ahui' ;delete from t1; #"

## union

		$name = "ahui' UNION ALL SELECT ... #"

# Wide Charset Injection
> http://security.stackexchange.com/questions/9908/multibyte-character-exploits-php-mysql

1. Basic attacks on, e.g., UTF-8 and other character encodings by eating up extra backslashes/quotes introduced by the quoting function

2. Sneaky attacks on, e.g., GBK, that work by tricking the quoting function to introduce an extra quote for you

3. Attacks on, e.g., UTF-8, that conceal the presence of a quote by using an invalid non-canonical (over-long) encoding of the single quote:
Basically, the normal way of encoding a single quote has it fit into a single-byte sequence (namely, 0x27).
However, there are also multi-byte sequences that the database might decode as a single quote,
and that do not contain the 0x27 byte or any other suspicious byte value.

As a result, standard quote-escaping functions may fail to escape those quotes.

##  multi-byte characters
> https://vigilance.fr/vulnerability/MySQL-SQL-injection-via-multi-byte-characters-5885

(multi-byte). Here are three examples of character tables/encoding:

 - ISO-8859-1/LATIN1 (French)
 - UTF-8 (international, multi-byte)
 - SJIS, BIG5, GBK, GB18030, UHC (Asian, multi-byte)

A SQL string can contain the tick character. For example:

	SELECT ... WHERE var = 'abc\'def';
	SELECT ... WHERE var = 'abc''def';

1. The first vulnerability affects the `mysql_real_escape_string()` function family which does not reject invalid multi-byte characters:

For example, in UTF-8, the `"0xC8 ' ' attackersql"` or `"0xC8 \ ' attackersql"` string is converted to:
`"one_character ' attackersql"` (ignore spaces), `0xC8` will eat `\`. So, the query:

	  SELECT ... WHERE var = ' mysql_real_escape_string("0xC8 ' attackersql") '
	become :
	  SELECT ... WHERE var = ' 0xC8 ' ' attackersql '
	  SELECT ... WHERE var = 'one_character ' attackersql'

An attacker can therefore inject the attackersql command.

2. The second vulnerability only affects Asian encodings,
when they are used with simple escaping functions such as a regular expression replace of `' by \'`, PHP addslashes(), etc.
For example, in SJIS, the query:

	  SELECT ... WHERE var = ' addslashes("0x95 0x5C ' attackersql") '

becomes, because 0x5C is the backslash character(`0x95 0x5c` combines as `one_character`):

	  SELECT ... WHERE var = ' 0x95 0x5C \ \ ' attackersql '
	  SELECT ... WHERE var = 'one_character \\' attackersql'

An attacker can therefore inject the attackersql command.

## 在GBK宽字节中

	%df'
	%df%27
	%df%5c%27 # %df%5c 是gbk 中是一个汉字

	%5C \
	%27 '

	$sql = "select * from t where name='{$name}' and password='{$password}' limit 1";

构造$name:

	$name="\xbf\x27 or name=name /*"

addslash 后, `\xbf` will eat `\x5c`:

		$name="\xbf\x5c' or name=name /*"
		$name="\xbf\x5c' or name=name ;/*"
		$name="\xbf\x5c' or name=name ;#/*"

This type of attack is possible with any character encoding where there is a valid multi-byte character that ends in 0x5c, because addslashes() can be tricked into creating a valid multi-byte character instead of escaping the single quote that follows.
> UTF-8 does not fit this description.


text:
package com.cpic.carmarket.bean;

import java.util.ArrayList;

public class FormData {
	private int code;
	private String msg;
	private ArrayList<FormDataInfo> data;
	public int getCode() {
		return code;
	}
	public void setCode(int code) {
		this.code = code;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	public ArrayList<FormDataInfo> getData() {
		return data;
	}
	public void setData(ArrayList<FormDataInfo> data) {
		this.data = data;
	}
	public FormData() {
		super();
		// TODO Auto-generated constructor stub
	}
	@Override
	public String toString() {
		return "FormData [code=" + code + ", msg=" + msg + ", data=" + data
				+ "]";
	}

}


text:
   /**
    *  Gets URI that identifies the test.
    *  @return uri identifier of test
    */
function getTargetURI() {
      return "http://www.w3.org/2001/DOM-Test-Suite/level2/html/doc01";
   }

var docsLoaded = -1000000;
var builder = null;

//
//   This function is called by the testing framework before
//      running the test suite.
//
//   If there are no configuration exceptions, asynchronous
//        document loading is started.  Otherwise, the status
//        is set to complete and the exception is immediately
//        raised when entering the body of the test.
//
function setUpPage() {
   setUpPageStatus = 'running';
   try {
     //
     //   creates test document builder, may throw exception
     //
     builder = createConfiguredBuilder();

      docsLoaded = 0;

      var docRef = null;
      if (typeof(this.doc) != 'undefined') {
        docRef = this.doc;
      }
      docsLoaded += preload(docRef, "doc", "anchor");

       if (docsLoaded == 1) {
          setUpPageStatus = 'complete';
       }
    } catch(ex) {
        catchInitializationError(builder, ex);
        setUpPageStatus = 'complete';
    }
}

//
//   This method is called on the completion of
//      each asychronous load started in setUpTests.
//
//   When every synchronous loaded document has completed,
//      the page status is changed which allows the
//      body of the test to be executed.
function loadComplete() {
    if (++docsLoaded == 1) {
        setUpPageStatus = 'complete';
    }
}

/**
*
Retrieve the title attribute of HTMLDocument and examine it's value.

* @author Netscape
* @author Sivakiran Tummala
* @see http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-html#ID-18446827
*/
function doc01() {
   var success;
    if(checkInitialization(builder, "doc01") != null) return;
    var vtitle;
      var doc;

      var docRef = null;
      if (typeof(this.doc) != 'undefined') {
        docRef = this.doc;
      }
      doc = load(docRef, "doc", "anchor");
      vtitle = doc.title;

      assertEquals("titleLink","NIST DOM HTML Test - Anchor",vtitle);

}

function runTest() {
   doc01();
}


text:
<?php

namespace Gestion\GestionBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Commentaires
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="Gestion\GestionBundle\Repository\CommentairesRepository")
 */
class Commentaires
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="Utilisateurs\UtilisateursBundle\Entity\Utilisateurs")
     * @ORM\JoinColumn(nullable=false)
     */
    private $utilisateur;

    /**
     * @var string
     *
     * @ORM\Column(name="contenu", type="text")
     */
    private $contenu;

    /**
     * @ORM\OneToMany(targetEntity="Gestion\GestionBundle\Entity\Fichiers",mappedBy="commentaire",cascade={"persist"})
     * @ORM\JoinColumn(nullable=true)
     */
    private $fichier;

    /**
     * @ORM\ManyToOne(targetEntity="Gestion\GestionBundle\Entity\Demandes")
     * @ORM\JoinColumn(nullable=false)
     */
    private $demande;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="dateCommentaire", type="datetime")
     */
    private $dateCommentaire;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="dateSuppression", type="datetime", nullable=true)
     */
    private $dateSuppression;

    function __construct() {
        $this->fichier = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set utilisateur
     *
     * @param string $utilisateur
     * @return Commentaires
     */
    public function setUtilisateur($utilisateur)
    {
        $this->utilisateur = $utilisateur;

        return $this;
    }

    /**
     * Get utilisateur
     *
     * @return string
     */
    public function getUtilisateur()
    {
        return $this->utilisateur;
    }

    /**
     * Set contenu
     *
     * @param string $contenu
     * @return Commentaires
     */
    public function setContenu($contenu)
    {
        $this->contenu = $contenu;

        return $this;
    }

    /**
     * Get contenu
     *
     * @return string
     */
    public function getContenu()
    {
        return $this->contenu;
    }

    /**
     * Set fichier
     *
     * @param string $fichier
     * @return Commentaires
     */
    public function setFichier($fichier)
    {
        $this->fichier = $fichier;

        return $this;
    }

    /**
     * Get fichier
     *
     * @return string
     */
    public function getFichier()
    {
        return $this->fichier;
    }

    /**
     * Set demande
     *
     * @param string $demande
     * @return Commentaires
     */
    public function setDemande($demande)
    {
        $this->demande = $demande;

        return $this;
    }

    /**
     * Get demande
     *
     * @return string
     */
    public function getDemande()
    {
        return $this->demande;
    }

    /**
     * Set dateCommentaire
     *
     * @param \DateTime $dateCommentaire
     * @return Commentaires
     */
    public function setDateCommentaire($dateCommentaire)
    {
        $this->dateCommentaire = $dateCommentaire;

        return $this;
    }

    /**
     * Get dateCommentaire
     *
     * @return \DateTime
     */
    public function getDateCommentaire()
    {
        return $this->dateCommentaire;
    }

    /**
     * Set dateSuppression
     *
     * @param \DateTime $dateSuppression
     * @return Commentaires
     */
    public function setDateSuppression($dateSuppression)
    {
        $this->dateSuppression = $dateSuppression;

        return $this;
    }

    /**
     * Get dateSuppression
     *
     * @return \DateTime
     */
    public function getDateSuppression()
    {
        return $this->dateSuppression;
    }

    /**
     * Add fichier
     *
     * @param \Gestion\GestionBundle\Entity\Fichiers $fichier
     * @return Commentaires
     */
    public function addFichier(\Gestion\GestionBundle\Entity\Fichiers $fichier)
    {
        $this->fichier[] = $fichier;

        return $this;
    }

    /**
     * Remove fichier
     *
     * @param \Gestion\GestionBundle\Entity\Fichiers $fichier
     */
    public function removeFichier(\Gestion\GestionBundle\Entity\Fichiers $fichier)
    {
        $this->fichier->removeElement($fichier);
    }
}


text:
BINARY_HOME=$PREFIX/bin
PACKAGE_HOME=$PREFIX/share/$PKG_NAME-$PKG_VERSION-$PKG_BUILDNUM

# Create destination directories
mkdir -p $PACKAGE_HOME
mkdir -p $BINARY_HOME

ln -s $PACKAGE_HOME $PREFIX/share/$PKG_NAME

# Copy files into $PACKAGE_HOME
cp -R ./* $PACKAGE_HOME/

# Create wrapper
SOURCE_FILE=$RECIPE_DIR/pathwaymatcher.py
DEST_FILE=$PACKAGE_HOME/pathwaymatcher

cp $SOURCE_FILE $DEST_FILE
# We also copy pathwaymatcher.py as it is
cp $SOURCE_FILE $PACKAGE_HOME/pathwaymatcher.py

chmod +x $DEST_FILE

ln -s $DEST_FILE $BINARY_HOME
ln -s $PACKAGE_HOME/pathwaymatcher.py $BINARY_HOME


text:
using System.Collections.Generic;
using LambdaCore_Skeleton.Interfaces;
using LambdaCore_Skeleton.Models.Cores;

namespace LambdaCore_Skeleton
{
    using System;
    using Collection;

    public class Startup
    {
        static void Main()
        {
            List<ICore> repository = new List<ICore>();
            CommandInterpreter interpreter = new CommandInterpreter();
            string input = Console.ReadLine();
            while (input != "System Shutdown!")
            {
                var command = interpreter.InterpredCommand(input, repository);
                command.Execute();
                input = Console.ReadLine();
            }

        }
    }
}


text: A set of program examples used in a course for parallel programming.


text:
import regeneratorRuntime from 'regenerator-runtime'; // eslint-disable-line
import fs from 'mz/fs';

import {
  CACHE_FILENAME,
} from './constants';
import cacheExports from './cacheExports';

class ExportList {
  loaded: false;
  map: {};

  setApi(nvim) {
    this.nvim = nvim;
  }

  async update() {
    debug(this.nvim);
    this.map = await cacheExports(this.nvim);
    this.loaded = true;
    return this.map;
  }

  async loadFromFile() {
    const results = await fs.readFile(CACHE_FILENAME, 'utf8');
    this.map = JSON.parse(results);
    this.loaded = true;
    return this.map;
  }

  async getWord(word: string) {
    if (!this.loaded) {
      await this.update();
    }

    return this.map[word];
  }
}

export default new ExportList();


text:
function []=A_generate_quantization(save_path, experiment_name, train_folder, quantization_type, nvalues)
    % save_path = path to save the transformation files, necessary for applying the transformation later
    % experiment_name = name of the experiment
    % train_folder = path to the train folder, the transformation will be calculated based on it
    % quantization_type = single-dictionary (1) or multiple-dictionaries (2)
    % nvalues = number of desired values in the dictionary

    if ~exist('save_path', 'var')
        throw(MException('A_generate_quantization:save_path', 'ERROR: Parameter save_path is empty.'));
    end
    if ~exist('experiment_name', 'var')
        throw(MException('A_generate_quantization:experiment_name', 'ERROR: Parameter experiment_name is empty.'));
    end
    if ~exist('train_folder', 'var')
        throw(MException('A_generate_quantization:train_folder', 'ERROR: Parameter train_folder is empty.'));
    end
    if ~exist('quantization_type', 'var')
        throw(MException('A_generate_quantization:quantization_type', 'ERROR: Parameter quantization_type is empty.'));
    end
    if ~exist('nvalues', 'var')
        throw(MException('A_generate_quantization:nvalues', 'ERROR: Parameter nvalues is empty.'));
    end

    fprintf('Initiating %s.\n', experiment_name);
    if quantization_type == 1
        fprintf('- Single-dictionary quantization enabled;\n\n');
    elseif quantization_type == 2
        fprintf('- Multiple-dictionaries quantization enabled;\n\n');
    else
        throw(MException('quantization:quantization_type', sprintf('ERROR: Invalid quantization_type value (%d).\quantization_type should be 1 (single-dictionary) or 2 (multiple-dictionaries).', reduction_type)));
    end

    fcommon = BaseFunctions.getInstance;
    [feature_matrix, files] = fcommon.load_folder(train_folder);
    expname = 'Q';
    exptype = quantization_type;

    if quantization_type == 1
        fprintf('Calculating dictionary...\n');

        maxval = max(max(feature_matrix));
        minval = min(min(feature_matrix));
        step = (maxval-minval) / nvalues;
        val = minval + step / 2;
        dictionary = [];
        while val < maxval
            dictionary = [dictionary val];
            val = val + step;
        end

        save(sprintf('%s/%s', save_path, experiment_name), 'dictionary', 'expname', 'exptype');
        fprintf('Done.\n\n');
    elseif quantization_type == 2
        fprintf('Calculating dictionaries...\n');
        total_dimensions = size(feature_matrix, 2);

        maxval = max(feature_matrix,[],1);
        minval = min(feature_matrix,[],1);
        step = (maxval-minval) / nvalues;
        val = minval + step / 2;
        dictionary = val;
        for index = 2:nvalues
            val = val + step;
            dictionary = vertcat(dictionary, val);
        end
        if size(dictionary,2) ~= total_dimensions
            throw(MException('quantization:total_dimensions', sprintf('Internal ERROR: Number of dimensions mismatch (%d vs %d).', size(dictionary,2), total_dimensions)));
        end

        save(sprintf('%s/%s', save_path, experiment_name), 'dictionary', 'expname', 'exptype');
        fprintf('Done.\n\n');
    end
end


text:
int f1() {
  return test_framework_func(1) + another_test_framework_func(2);
}


text:
#include "config.h"
#include "ScriptValue.h"

#include "InspectorValues.h"
#include "SerializedScriptValue.h"

#include <JavaScriptCore/APICast.h>
#include <JavaScriptCore/JSValueRef.h>

#include <heap/Strong.h>
#include <runtime/JSLock.h>
#include <runtime/UString.h>

using namespace JSC;

namespace WebCore {

bool ScriptValue::getString(ScriptState* scriptState, String& result) const
{
    if (!m_value)
        return false;
    JSLock lock(SilenceAssertionsOnly);
    UString ustring;
    if (!m_value.get().getString(scriptState, ustring))
        return false;
    result = ustringToString(ustring);
    return true;
}

String ScriptValue::toString(ScriptState* scriptState) const
{
    String result = ustringToString(m_value.get().toString(scriptState));
    // Handle the case where an exception is thrown as part of invoking toString on the object.
    if (scriptState->hadException())
        scriptState->clearException();
    return result;
}

bool ScriptValue::isEqual(ScriptState* scriptState, const ScriptValue& anotherValue) const
{
    if (hasNoValue())
        return anotherValue.hasNoValue();

    return JSValueIsEqual(toRef(scriptState), toRef(scriptState, jsValue()), toRef(scriptState, anotherValue.jsValue()), 0);
}

bool ScriptValue::isNull() const
{
    if (!m_value)
        return false;
    return m_value.get().isNull();
}

bool ScriptValue::isUndefined() const
{
    if (!m_value)
        return false;
    return m_value.get().isUndefined();
}

bool ScriptValue::isObject() const
{
    if (!m_value)
        return false;
    return m_value.get().isObject();
}

bool ScriptValue::isFunction() const
{
    CallData callData;
    return getCallData(m_value.get(), callData) != CallTypeNone;
}

PassRefPtr<SerializedScriptValue> ScriptValue::serialize(ScriptState* scriptState, SerializationErrorMode throwExceptions)
{
    return SerializedScriptValue::create(scriptState, jsValue(), throwExceptions);
}

ScriptValue ScriptValue::deserialize(ScriptState* scriptState, SerializedScriptValue* value, SerializationErrorMode throwExceptions)
{
    return ScriptValue(scriptState->globalData(), value->deserialize(scriptState, scriptState->lexicalGlobalObject(), throwExceptions));
}

#if ENABLE(INSPECTOR)
static PassRefPtr<InspectorValue> jsToInspectorValue(ScriptState* scriptState, JSValue value, int maxDepth)
{
    if (!value) {
        ASSERT_NOT_REACHED();
        return 0;
    }

    if (!maxDepth)
        return 0;
    maxDepth--;

    if (value.isNull() || value.isUndefined())
        return InspectorValue::null();
    if (value.isBoolean())
        return InspectorBasicValue::create(value.getBoolean());
    if (value.isNumber())
        return InspectorBasicValue::create(value.uncheckedGetNumber());
    if (value.isString()) {
        UString s = value.getString(scriptState);
        return InspectorString::create(String(s.characters(), s.length()));
    }
    if (value.isObject()) {
        if (isJSArray(&scriptState->globalData(), value)) {
            RefPtr<InspectorArray> inspectorArray = InspectorArray::create();
            JSArray* array = asArray(value);
            unsigned length = array->length();
            for (unsigned i = 0; i < length; i++) {
                JSValue element = array->getIndex(i);
                RefPtr<InspectorValue> elementValue = jsToInspectorValue(scriptState, element, maxDepth);
                if (!elementValue)
                    return 0;
                inspectorArray->pushValue(elementValue);
            }
            return inspectorArray;
        }
        RefPtr<InspectorObject> inspectorObject = InspectorObject::create();
        JSObject* object = value.getObject();
        PropertyNameArray propertyNames(scriptState);
        object->getOwnPropertyNames(scriptState, propertyNames);
        for (size_t i = 0; i < propertyNames.size(); i++) {
            const Identifier& name =  propertyNames[i];
            JSValue propertyValue = object->get(scriptState, name);
            RefPtr<InspectorValue> inspectorValue = jsToInspectorValue(scriptState, propertyValue, maxDepth);
            if (!inspectorValue)
                return 0;
            inspectorObject->setValue(String(name.characters(), name.length()), inspectorValue);
        }
        return inspectorObject;
    }
    ASSERT_NOT_REACHED();
    return 0;
}

PassRefPtr<InspectorValue> ScriptValue::toInspectorValue(ScriptState* scriptState) const
{
    return jsToInspectorValue(scriptState, m_value.get(), InspectorValue::maxDepth);
}
#endif // ENABLE(INSPECTOR)

} // namespace WebCore


text:
package com.github.jlinq;

import java.util.Map;
import java.util.NoSuchElementException;

public interface Queryable<T> extends Iterable<T> {

	/**
	 * Returns a {@link Queryable} that contains the elements selected by the
	 * given function.
	 *
	 * @param func
	 *            The function to apply.
	 * @return A {@link Queryable} that contains the elements selected by the
	 *         given function.
	 */
	<R> Queryable<R> select(Function<? super T, R> func);

	/**
	 * Returns a {@link Queryable} that contains the elements that fulfill the
	 * given condition.
	 *
	 * @param func
	 *            The function that tests if an element fulfills a condition.
	 * @return A {@link Queryable} that contains the elements that fulfill the
	 *         given condition.
	 */
	Queryable<T> where(Function<? super T, Boolean> func);

	/**
	 * Groups the elements of this {@link Queryable} using the given function.
	 * Note: This function will usually execute the query by copying the
	 * underlying elements into a new collection. A change to the underlying
	 * collection will therefore (if not specified otherwise) not be applied to
	 * the returned object. See {@link #execute()}.
	 *
	 * @param func
	 *            The function that returns a value that is used to group the
	 *            elements of this {@link Queryable}.
	 * @return A {@link Map} containing the grouped elements.
	 */
	<R> Map<R, Queryable<T>> group(Function<? super T, R> func);

	/**
	 * Searches for the first element that fulfills the given condition and
	 * returns it.
	 *
	 * @param func
	 *            The function that tests if an element fulfills a condition.
	 * @return The first matching element.
	 */
	T find(Function<? super T, Boolean> func);

	/**
	 * Removes every element that fulfills the given condition. This is the
	 * inverse of {@link Queryable#where(Function)}.
	 *
	 * @param func
	 *            The function that tests if an element fulfills a condition.
	 * @return A {@link Queryable} that contains only the elements that did not
	 *         fulfill the given condition.
	 */
	Queryable<T> filter(Function<? super T, Boolean> func);

	/**
	 * Performs all previous operations based on the currently present elements
	 * and returns the result as an independent instance of {@link Queryable}.
	 * Future changes to the underlying collection won't be applied to result of
	 * this method.
	 *
	 * @return A independent copy of this {@link Queryable}.
	 */
	Queryable<T> execute();

	/**
	 * Orders the elements by comparing the value returned by the given
	 * function. Note: This function will usually execute the query by
	 * copying the underlying elements into a new collection. A change to the
	 * underlying collection will therefore (if not specified otherwise) not be
	 * applied to the returned object. See {@link #execute()}.
	 *
	 * @param func
	 *            A function that returns the values which should be used for
	 *            the comparison.
	 * @return An ordered {@link Queryable}.
	 */
	<R extends Comparable<? super R>> Queryable<T> orderBy(Function<? super T, R> func);

	/**
	 * Orders the elements by comparing the values returned by the given
	 * function and inverts the order. Note: This function will usually
	 * execute the query by copying the underlying elements into a new
	 * collection. A change to the underlying collection will therefore (if not
	 * specified otherwise) not be applied to the returned object. See
	 * {@link #execute()}.
	 *
	 * @param func
	 *            A function that returns the values which should be used for
	 *            the comparison.
	 * @return An inverse ordered {@link Queryable}.
	 */
	<R extends Comparable<? super R>> Queryable<T> orderInverse(Function<? super T, R> func);

	/**
	 * Returns a {@link QList} containing all elements of this {@link Queryable}
	 * . Note: This function will usually execute the query by copying
	 * the underlying elements into a new collection. A change to the underlying
	 * collection will therefore (if not specified otherwise) not be applied to
	 * the returned object. See {@link #execute()}.
	 *
	 * @return A {@link QList} containing all elements of this {@link Queryable}
	 *         .
	 */
	QList<T> toList();

	/**
	 * Returns the amount of elements within this instance.
	 *
	 * @return The amount of elements within this instance.
	 */
	long count();

	/**
	 * Returns the first element of this query.
	 *
	 * @param defaultValue
	 *            The value that should be returned if the query contains no
	 *            elements.
	 * @return The first element of this query or the given default value if
	 *         this query is empty.
	 */
	T first(T defaultValue);

	/**
	 * Returns the first element of this query.
	 *
	 * @return The first element of this query or {@code null} if the query
	 *         contains no elements.
	 */
	T first();

	/**
	 * Returns the last element of this query.
	 *
	 * @param defaultValue
	 *            The value that should be returned if the query contains no
	 *            elements.
	 * @return The last element of this query or the given default value if this
	 *         query is empty.
	 */
	T last(T defaultValue);

	/**
	 * Returns the last element of this query.
	 *
	 * @return The last element of this query or {@code null} if the query
	 *         contains no elements.
	 */
	T last();

	/**
	 * Returns {@code true} if this {@link Queryable} contains the given value.
	 *
	 * @param value
	 *            The value to check.
	 * @return {@code true} if this {@link Queryable} contains the given value.
	 */
	boolean contains(T value);

	/**
	 * Returns all elements that are present in this and the given
	 * {@link Queryable}.
	 *
	 * @param other
	 *            The other query.
	 * @return All elements that are present in this and the given query.
	 */
	Queryable<T> intersect(Queryable<T> other);

	/**
	 * Returns a query containing the elements of this and the given
	 * {@link Queryable}.
	 *
	 * @param other
	 *            The other query.
	 * @return A query containing the elements of this and the given query.
	 */
	Queryable<T> combine(Queryable<T> other);

	/**
	 * Filters all duplicate elements of this queryable.
	 * @return A queryable that doesn't contain duplicate elements.
	 */
	Queryable<T> filterDuplicates();

	/**
	 * Filters all duplicate elements of this queryable.
	 * @param unifier A function that is used to determine the criteria that should be used to find duplicates.
	 * @return A queryable that doesn't contain duplicate elements.
	 */
	Queryable<T> filterDuplicates(Function<? super T, ?> unifier);

	/**
	 * Unites this and the given queryable.
	 * @param other The other queryable.
	 * @return A queryable that contains all elements of this and the given queryable exactly one time.
	 */
	Queryable<T> union(Queryable<T> other);

	/**
	 * Unites this and the given queryable.
	 * @param other The other queryable.
	 * @param unifier A function that is used to determine the criteria that should be used to find duplicates.
	 * @return A queryable that contains all elements of this and the given queryable exactly one time.
	 */
	Queryable<T> union(Queryable<T> other, Function<? super T, ?> unifier);

	/**
	 * Returns the element at the given index.
	 *
	 * @param index
	 *            The index of the element to return.
	 * @return The element at the given index.
	 * @throws NoSuchElementException
	 *             If there is no element at the given position.
	 */
	T get(int index);

	/**
	 * Passes the element at the given index to the given consumer and returns
	 * this instance.
	 *
	 * @param index
	 *            The index of the element to be passed to the given consumer.
	 * @param consumer
	 *            The consumer to call.
	 * @return This instance.
	 */
	Queryable<T> get(int index, ParameterizedCallback<? super T> consumer);

	/**
	 * Iterates over all elements of this query and calls the given consumer.
	 *
	 * @param cosumer
	 *            The consumer that should be called for all elements of this
	 *            query.
	 */
	void forEach(ParameterizedCallback<? super T> cosumer);

	/**
	 * Removes all instances of {@code null} from this query.
	 *
	 * @return A query without {@code null} elements.
	 */
     Queryable<T> notNull();
	/**
	 * Returns {@code true} if every element satisfies the given condition.
	 * @param condition The condition to apply.
	 * @return {@code true} if every element satisfies the given condition.
	 */
	boolean all(Function<? super T, Boolean> condition);

	/**
	 * Returns {@code true} if at least one element satisfies the given condition.
	 * @param condition The condition to apply.
	 * @return {@code true} if at least one element satisfies the given condition.
	 */
	boolean any(Function<? super T, Boolean> condition);

}


text:
function comma (array, spacing = 0) {
  return array.join(',' + ' '.repeat(spacing))
}

module.exports = comma


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('usuarios', '0002_auto_20170109_0928'),
    ]

    operations = [
        migrations.AlterField(
            model_name='usuario',
            name='numero',
            field=models.CharField(blank=True, max_length=50, verbose_name='Número'),
        ),
    ]


text:
package main.java;

import java.io.Serializable;

public class Entry implements Serializable {

  private int id;
  private String name;
  private String type;
  private int qty;
  private float watt;
  private float hour;

  /**
   * Entry constructor with no argument
   */
  public Entry() {
    //
  }

  /**
   * Entry constructor with complete arguments
   */
  public Entry(int id, String name, String type,
               int qty, float watt, float hour) {

    this.id = id;
    this.name = name;
    this.type = type;
    this.qty = qty;
    this.hour = hour;
    this.watt = watt;

  }

  /**
   * Various entry attribute getter
   */

  public int getID() {
    return this.id;
  }

  public String getName() {
    return this.name;
  }

  public String getType() {
    return this.type;
  }

  public int getQty() {
    return this.qty;
  }

  public float getWatt() {
    return this.watt;
  }

  public float getHour() {
    return this.hour;
  }

  /**
   * Update for all entry's information
   */
  public void update(String name, String type,
                     int qty, float watt, float hour) {

    this.name = name;
    this.type = type;
    this.qty = qty;
    this.watt = watt;
    this.hour = hour;

  }

}


text:
'''
Keeps your MPD playlist filled with music you like

Dependencies : python-mpd2
'''

import os
import mpd
import random
import sqlite3
import time
import io
import sys
import socket

## Config
playtime = 70 # Percentage of a song that must be played before
              #  play count is incremented
mintime = 25 # Minimum length of a track for it
             #  to be considered a song (in seconds)
flood_delay = 12*60 # Minutes to wait before adding the same song again
tries = 10 # Retry connecting this many times
## /Config

version = "3.0.0"
helpstring = """Syntax : """ + sys.argv[0] + """ [command]
command can be one of :
  radio [on|off|toggle]
  trigger [number]
  info [path]

  start
  stop (synonym: kill)
  loglevel [debug|notice|warning|error]
  help
  version"""

def log(msg, stdout=False):
  """Logs to file, and optionally to stdout. Obvious enough"""
  alllevels = "DINWE" # Debug, Info, Notice, Warning, Error
  loglevels = alllevels[alllevels.find(logLevel):]
  if stdout:
    print(msg[2:])
  if msg[0] in loglevels:
    logio.write(msg+"\n")

def connect(i=1):
  log("N Connecting...")
  if i == tries:
    log("E Could not connect to server D:", stdout=True)
    exit(1)
  try:
    client.connect(host, port)
  except socket.error:
    log("N Try n°"+str(i)+" failed")
    time.sleep(i*3)
    connect(i+1)
    return
  if password:
    try:
      log("D Using password")
      client.password(password)
    except mpd.CommandError:
      log("E Couldn't connect. Wrong password?", stdout=True)
      exit(2)
  log("N Connected")

def addsong():
  """Adds a semi-random song to the playlist"""
  rand = random.uniform(-0.5, 2)
  cursor.execute("SELECT file, listened, added FROM songs "
      "WHERE karma>? AND time < ? "
      "AND NOT duplicate ORDER BY random() LIMIT 1;",
      (rand, int(time.time()-(60*(flood_delay-trigger*3)))))
  songdata = cursor.fetchone()
  if not songdata:
    updateone()
    addsong()
  else:
    newkarma = karma(songdata[1], songdata[2]+1)
    cursor.execute(
        "UPDATE songs SET added=?, karma=?, time=? WHERE file=?",
        (songdata[2]+1, newkarma, int(time.time()), songdata[0],)
        )
    cursor.execute(
        "SELECT inode, dev FROM songs WHERE file=?;",
        (songdata[0],)
        )
    one = cursor.fetchone()
    if one and one[0]:
      cursor.execute(
          """UPDATE SONGS SET added=?, karma=?, time=? WHERE inode=?
          AND dev=?""", (songdata[2]+1, newkarma, int(time.time()),
            one[0], one[1])
          )
    db.commit()
    try:
      client.add(songdata[0])
      log("I Added " + songdata[0])
      log("D A:" + str(songdata[2]+1) + ", K:" +
          str(newkarma))
    except mpd.CommandError:
      log("W Couldn't add " + songdata[0])
      update(songdata[0])
      addsong()

def karma(listened, added):
  if listened == 0: listened = 0.1
  if added == 0: added = 0.1
  return float(listened)/added

def listened(file):
  update(file);
  try:
    cursor.execute("SELECT listened, added FROM songs WHERE file = ?",
        (file,))
    songdata = cursor.fetchone()
    newkarma = karma(songdata[0]+1, songdata[1])
    cursor.execute(
        "UPDATE songs SET listened=?, karma=?, time=? WHERE file=?",
        (songdata[0]+1, newkarma, int(time.time()), file)
        )
    cursor.execute(
        "SELECT inode, dev FROM songs WHERE file=?;",
        (file,)
        )
    one = cursor.fetchone()
    if one and one[0]:
      cursor.execute(
          """UPDATE SONGS SET listened=?, karma=?, time=? WHERE inode=?
          AND dev=?""", (songdata[0]+1, newkarma, int(time.time()),
            one[0], one[1])
          )
    db.commit()
    log("I Listened to " + file)
    log("D L:" + str(songdata[0]+1) + ", K:" +str(newkarma))
  except (KeyError, TypeError): # on songdata[n]
    pass

allsongs = []
def updateone():
  if allsongs == []:
    cursor.execute("VACUUM;")
    for song in client.list("file"):
      allsongs.append(song)
    for song in cursor.execute("SELECT file FROM songs;"):
      allsongs.append(song[0])
    random.shuffle(allsongs)

  song = allsongs.pop()
  update(song)

def update(song):
  # Check if the file is in mpd
  records = client.search("filename", song)
  if not any(r['file'] == song for r in records):
    log("N Update : Removing " + song)
    cursor.execute("delete from songs where file=?", (song,))
    db.commit()
    return

  inode = dev = None
  duplicate = False
  listened, added, karma = 0, 0, 5
  if musicdir:
    # Check for duplicate in FS
    try:
      s = os.stat(musicdir + "/" + song)
      inode = s.st_ino
      dev = s.st_dev
      cursor.execute("SELECT listened, added, karma FROM songs WHERE file!=? AND inode=?" +
          "AND dev=? AND NOT duplicate;", (song, inode, dev))
      one = cursor.fetchone();
      if one:
        duplicate=True
        listened, added, karma = one
        cursor.execute("""UPDATE songs SET listened=?, added=?, karma=?,
          inode=?, dev=?, duplicate=? WHERE file=?""",
            (listened, added, karma, inode, dev, duplicate, song))
      else:
        cursor.execute("""UPDATE songs SET inode=?, dev=?, duplicate=? WHERE file=?""",
            (inode, dev, duplicate, song))
    except OSError:
      log("E Couldn't stat " + musicdir + "/" + song)
      pass

  # Check if the file is in DB
  cursor.execute("SELECT 1 FROM songs WHERE file=?", (song,))
  if cursor.fetchone() == None:
    log("N Update : Adding " + song)
    cursor.execute("INSERT INTO songs"+
        "(file, listened, added, karma, time, inode, dev, duplicate)"+
        "VALUES (?, ?, ?, ?, 0, ?, ?, ?);",
        (song, listened, added, karma, inode, dev, duplicate))
    db.commit()

def getSetting(name, default=None):
  cursor.execute("""SELECT value FROM setting
      WHERE name = ?;""", (name,))
  one = cursor.fetchone()
  if not one and default:
    setSetting(name, default)
    return default
  if not one: return None
  return one[0]

def setSetting(name, val):
  val = str(val)
  if getSetting(name) == None:
    cursor.execute("""INSERT INTO setting (name, value)
      VALUES (?, ?);""", (name, val))
  else:
    cursor.execute("""UPDATE setting SET value = ?
      WHERE name = ?;""", (val, name))
  db.commit()

def initDB():
    cursor.execute("""CREATE TABLE IF NOT EXISTS setting(
        name text not null,
        value text
        );""")
    cursor.execute("""CREATE TABLE IF NOT EXISTS songs(
        file text not null,
        listened int not null default 0,
        added int not null default 0,
        karma real not null default 5,
        time int not null default 0,
        inode int,
        dev int,
        duplicate boolean not null default 0
        );""")
    db.commit()
    dbversion = getSetting("dbversion")
    cursor.execute("""SELECT 1 FROM songs LIMIT 1;""")
    if cursor.fetchone() and not dbversion: # old db
      setSetting("dbversion", "1")
    elif not dbversion:
      setSetting("dbversion", "3")
    else:
      if int(dbversion) < 2:
        cursor.execute("""ALTER TABLE songs ADD COLUMN inode int;""")
        cursor.execute("""ALTER TABLE songs ADD COLUMN dev int;""")
        setSetting("dbversion", "2")
      if int(dbversion) < 3:
        cursor.execute("""ALTER TABLE songs ADD COLUMN duplicate boolean
            not null default 0;""")
        setSetting("dbversion", "3")
    db.commit()

def shutdown():
  s.shutdown(socket.SHUT_RDWR)
  s.close()
  os.unlink(datahome + "/socket")
  client.disconnect()
  os.unlink(datahome + "/pid")
  log("N Shutdown")

def triggerStatus():
  return "Trigger : " + str(trigger) + "\n"

def radioStatus():
  return "Radio mode : " +\
    ("Enabled" if radioMode else "Disabled") + "\n"

def pprintSong(file=None):
  try:
    if not file:
      song = client.currentsong()
    else:
      song = client.find("file", file)[0]
    cursor.execute("""SELECT listened, added, karma FROM songs
      WHERE file = ?""", (song['file'],))
    one = cursor.fetchone()
    if not one:
      return "\n"
    prettysong = song['file']
    try:
      prettysong = song['title']
      prettysong = song['artist'] + " - " + prettysong
    except (KeyError, TypeError): pass
    return prettysong + """
Listened : """ + str(one[0]) + """
Added    : """ + str(one[1]) + """
Karma    : """ + str(one[2]) + "\n"
  except (IndexError, KeyError, mpd.ConnectionError):
    return "\n";

def sockAccept():
  global client, db, cursor, s
  global trigger, radioMode, logLevel
  global allsongs

  try: #Socket error
    c, _ = s.accept()
    c.settimeout(1)
    comm = b""
    try:
      while comm[-1:] != b"\n":
        comm += c.recv(1024)
    except socket.error:
      comm=b""
    c.settimeout(0)
    comm = comm[:-1]
    resp, will_shutdown = command(comm);
    c.send(resp)
    c.shutdown(socket.SHUT_RDWR)
    c.close()
    if(will_shutdown):
      shutdown()
      exit(0)
    return True;
  except socket.error:
    return False;

def command(command):
  global client, db, cursor, s
  global trigger, radioMode, logLevel
  global allsongs

  ret = ""
  will_shutdown = False
  command = command.decode()
  args = command.split('\0')

  if args[0] in ("kill", "stop"):
    ret = "Shutting down server...\n"
    will_shutdown = True

  elif args[0] == "radio":
    if len(args) > 1:
      if args[1] in ("off", "no", "stop"):
        radioMode = False
      elif args[1] in ("on", "yes", "start"):
        radioMode = True
      elif args[1] == "toggle":
        radioMode = not radioMode
      else:
        ret = "Syntax: autoplay radio [on|off|toggle]\n"
      setSetting("radioMode", str(radioMode))
    ret += radioStatus()

  elif args[0] == "trigger":
    if len(args) > 1:
      try:
        trigger = int(args[1])
        setSetting("trigger", str(trigger))
      except ValueError:
        ret = '"' + args[1] + '" is not a valid number \n'
    ret += triggerStatus()

  elif args[0] == "info":
    if len(args) > 1:
      ret = pprintSong(args[1])
    else:
      ret = pprintSong()

  elif args[0] in ("version", "-V"):
    ret = "Autoplay v%s\n" % (version,)

  else:
    if command == '':
      ret = radioStatus()
    else:
      if command not in ("help", "--help", "-h"):
        log("W Unknown command: " + command)
        ret = "Unknown command: " + command + "\n"
      ret += helpstring + "\n"

  return (ret.encode(), will_shutdown)

def serve():
  global client, db, cursor, s
  global trigger, radioMode, logLevel
  global allsongs

  s = socket.socket(socket.AF_UNIX)
  s.bind(datahome + "/socket")
  s.settimeout(.3)
  s.listen(2)

  db = sqlite3.connect(datahome+"/db.sqlite")
  cursor = db.cursor()
  initDB()

  logLevel = getSetting("logLevel", "W")
  radioMode = getSetting("radioMode", "True") == "True"
  trigger = int(getSetting("trigger", 6))

  random.seed()
  client = mpd.MPDClient()
  connect()

  armed = True

  lastUpdate = 0
  lastMpd = time.time()

  log("D Music dir is located at " + str(musicdir))

  log("N Ready")

  while True:

    try: #KeyboardInterrupt
      if sockAccept():
        lastUpdate = lastMpd = time.time()
        next

      try: #MPD or socket error
        clock = time.time()
        if clock - lastUpdate >= 5:
          lastUpdate = clock
          updateone()
        if clock - lastMpd >= .6:
          lastMpd = clock
          if radioMode:
            if client.status()["consume"] == "0":
              cursongid = client.status()["songid"]
              for song in client.playlistid():
                if song["id"] == cursongid:
                  neededlength = int(song["pos"]) + trigger
            else:
              neededlength = trigger
            if len(client.playlist()) < neededlength:
              addsong()
              lastMpd = 0

          if client.status()['state'] == "play":
            times = client.status()['time'].split(":")
            pos = int(times[0])
            end = int(times[1])
            currentsong = client.currentsong()
            if not armed and "id" in currentsong and not songid == currentsong["id"]:
              armed = True
            elif armed and (end > mintime) and (pos > playtime*end/100):
              armed = False # Disarm until the next song
              listened(currentsong["file"])
              songid = (currentsong["id"])

      except (KeyError, TypeError):
        pass

      except (socket.error, mpd.ConnectionError):
        log("W Connection to MPD lost")
        client.disconnect()
        connect()

    except KeyboardInterrupt:
      s.shutdown(socket.SHUT_RDWR)

def getServSock():
  try:
    pidf = open(datahome + "/pid") #IOError
    pid = pidf.read()
    pidf.close()
    os.kill(int(pid), 0) #OSError on kill, ValueError on int
  except (IOError, OSError, ValueError):
    print("Starting server...")
    try:
      os.unlink(datahome + "/socket")
    except OSError:
      pass
    pid = os.fork()
    if pid == 0:
      serve()
    pidf = open(datahome + "/pid", "w")
    pidf.write(str(pid))
    pidf.close()

  s = socket.socket(socket.AF_UNIX)
  try:
    s.connect(datahome + "/socket")
  except socket.error:
    try:
      s = getServSock()
    except RuntimeError: # recursion
      log("E Couldn't connect to socket", True)
      exit(1)
  return s

logLevel = "D"

datahome = (os.getenv("XDG_DATA_HOME") or os.getenv("HOME") +
            "/.local/share") + "/autoplay"
if not os.access(datahome, os.W_OK):
  try:
    os.makedirs(datahome)
  except os.error:
    log("E Couldn't access nor create" + datahome + ", quitting", True)
    exit(2)

password = None

host = os.getenv("MPD_HOST", "127.0.0.1")
atloc = host.find("@")
if(atloc != -1):
  password = host[:atloc]
  host = host[atloc+1:]

port = os.getenv("MPD_PORT", "6600")
musicdir = os.getenv("MPD_MUSIC_DIR") or os.getenv("mpd_music_dir")

logio = io.open(datahome + "/log", "at", buffering=1)

if __name__ == "__main__":
  silent = False
  s = getServSock()
  try:
    if len(sys.argv) <= 1 or sys.argv[1] != "start":
      s.sendall(b"\0".join(map(lambda s: s.encode(), sys.argv[1:])) + b"\n")

      data = s.recv(1024)
      while data != b"":
        print(data.decode(), end="")
        data = s.recv(1024)

  except KeyboardInterrupt:
    pass

  s.shutdown(socket.SHUT_RDWR)
  s.close()

# vim: tw=70 ts=2 sw=2


text:
using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using AutoMapper;
using DocumentDbRepositories;
using DocumentDbRepositories.Implementation;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc;
using ProvisioningLibrary;

namespace ScampApi.Infrastructure
{

    public class SecurityHelper : ISecurityHelper
    {
        private readonly HttpContext Context;
        private readonly IUserRepository _userRepository;
        private readonly IGroupRepository _groupRepository;

        public SecurityHelper(IHttpContextAccessor httpContextAccessor, IUserRepository userRepository, IGroupRepository groupRepository)
        {
            Context = httpContextAccessor.HttpContext;
            _userRepository = userRepository;
            _groupRepository = groupRepository;
        }

        public async Task<ScampUserReference> GetUserReference()
        {
            return  Mapper.Map<ScampUserReference>(await GetCurrentUser());
        }

        // retrieves the current user
        public async Task<ScampUser> GetCurrentUser()
        {

            var userId = Context.User.Claims.FirstOrDefault(c => c.Type.Contains("objectidentifier")).Value;
            //TODO check if user is in cache
            ScampUser tmpUser = await GetUserById(userId);
            // TODO put the user object into cache
            return tmpUser;
        }

        //public string GetIPIDByContext()
        //{
        //    // get Tenant and Object ID claims
        //    string tenantID = Context.User.Claims.FirstOrDefault(c => c.Type.Contains("tenantid")).Value;
        //    string objectID = Context.User.Claims.FirstOrDefault(c => c.Type.Contains("objectidentifier")).Value;
        //    // create SCAMP UserID
        //    string IPID = string.Format("{0}-{1}", tenantID, objectID);
        //    return IPID;
        //}

        public async Task<ScampUser> GetUserById(string userId)
        {
            ScampUser tmpUser = await _userRepository.GetUserbyId(userId);
            if (tmpUser == null) // insert if user doesn't exist
            {
                // build user object
                tmpUser = new ScampUser()
                {
                    Id = userId,
                    Name =
                        string.Format("{0} {1}", Context.User.FindFirst(ClaimTypes.GivenName).Value,
                            Context.User.FindFirst(ClaimTypes.Surname).Value).Trim(),
                    IsSystemAdmin = _userRepository.CheckNoUsers().Result,
                    // get email address
                    Email = Context.User.Claims.FirstOrDefault(c => c.Type.Contains("email") || c.Type.Contains("upn")).Value
                };

                // insert into database
                await _userRepository.CreateUser(tmpUser);
            }

            return tmpUser;
        }
        public async Task<bool> IsGroupAdmin(string groupId)
        {
            var user = await GetCurrentUser();
            var grp = await _groupRepository.GetGroup(groupId);
            var checkAdmin = grp.Admins.ToList().Any(q => q.Id == user.Id);
            return checkAdmin;
        }

        public async Task<bool> IsSysAdmin()
        {
            ScampUser user = await GetCurrentUser();

            return user.IsSystemAdmin;
        }
    }
}


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

#include "gradient_editor_plugin.h"

#include "canvas_item_editor_plugin.h"
#include "editor/editor_scale.h"
#include "node_3d_editor_plugin.h"

Size2 GradientEditor::get_minimum_size() const {
	return Size2(0, 60) * EDSCALE;
}

void GradientEditor::_gradient_changed() {
	if (editing) {
		return;
	}

	editing = true;
	Vector<Gradient::Point> points = gradient->get_points();
	set_points(points);
	editing = false;
}

void GradientEditor::_ramp_changed() {
	editing = true;
	UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo();
	undo_redo->create_action(TTR("Gradient Edited"));
	undo_redo->add_do_method(gradient.ptr(), "set_offsets", get_offsets());
	undo_redo->add_do_method(gradient.ptr(), "set_colors", get_colors());
	undo_redo->add_undo_method(gradient.ptr(), "set_offsets", gradient->get_offsets());
	undo_redo->add_undo_method(gradient.ptr(), "set_colors", gradient->get_colors());
	undo_redo->commit_action();
	editing = false;
}

void GradientEditor::_bind_methods() {
}

void GradientEditor::set_gradient(const Ref<Gradient> &p_gradient) {
	gradient = p_gradient;
	connect("ramp_changed", callable_mp(this, &GradientEditor::_ramp_changed));
	gradient->connect("changed", callable_mp(this, &GradientEditor::_gradient_changed));
	set_points(gradient->get_points());
}

GradientEditor::GradientEditor() {
	editing = false;
}

///////////////////////

bool EditorInspectorPluginGradient::can_handle(Object *p_object) {
	return Object::cast_to<Gradient>(p_object) != nullptr;
}

void EditorInspectorPluginGradient::parse_begin(Object *p_object) {
	Gradient *gradient = Object::cast_to<Gradient>(p_object);
	Ref<Gradient> g(gradient);

	GradientEditor *editor = memnew(GradientEditor);
	editor->set_gradient(g);
	add_custom_control(editor);
}

GradientEditorPlugin::GradientEditorPlugin(EditorNode *p_node) {
	Ref<EditorInspectorPluginGradient> plugin;
	plugin.instance();
	add_inspector_plugin(plugin);
}


text:
<?php

namespace Symfony\Component\Cache\Adapter;

use Symfony\Component\Cache\Marshaller\MarshallerInterface;
use Symfony\Component\Cache\Traits\RedisClusterProxy;
use Symfony\Component\Cache\Traits\RedisProxy;
use Symfony\Component\Cache\Traits\RedisTrait;

class RedisAdapter extends AbstractAdapter
{
    use RedisTrait;

    /**
     * @param \Redis|\RedisArray|\RedisCluster|\Predis\ClientInterface|RedisProxy|RedisClusterProxy $redis           The redis client
     * @param string                                                                                $namespace       The default namespace
     * @param int                                                                                $defaultLifetime The default lifetime
     */
    public function __construct($redis, string $namespace = '', int $defaultLifetime = 0, MarshallerInterface $marshaller = null)
    {
        $this->init($redis, $namespace, $defaultLifetime, $marshaller);
    }
}