text:
package mho.wheels.ordering;

import mho.wheels.iterables.IterableUtils;
import mho.wheels.structures.Pair;
import mho.wheels.structures.Triple;
import mho.wheels.testing.Demos;
import mho.wheels.testing.Testing;
import org.jetbrains.annotations.NotNull;

import java.util.Comparator;
import java.util.List;
import java.util.Objects;

import static mho.wheels.iterables.IterableUtils.*;
import static mho.wheels.ordering.Ordering.*;
import static mho.wheels.testing.Testing.*;

@SuppressWarnings("UnusedDeclaration")
public class OrderingDemos extends Demos {
    private static final @NotNull String ORDERING_CHARS = "<=>";

    public OrderingDemos(boolean useRandom) {
        super(useRandom);
    }

    private void demoFromInt() {
        for (int i : take(LIMIT, P.integers())) {
            System.out.println("fromInt(" + i + ") = " + fromInt(i));
        }
    }

    private void demoToInt() {
        for (Ordering o : take(LIMIT, P.orderings())) {
            System.out.println("toInt(" + o + ") = " + o.toInt());
        }
    }

    private void demoInvert() {
        for (Ordering o : take(LIMIT, P.orderings())) {
            System.out.println("invert(" + o + ") = " + o.invert());
        }
    }

    private void demoCompare_T_T() {
        for (Pair<Integer, Integer> p : take(LIMIT, P.pairs(P.integersGeometric()))) {
            System.out.println("compare(" + p.a + ", " + p.b + ") = " + compare(p.a, p.b));
        }
    }

    private void demoCompare_Comparator_T_T() {
        Iterable<Triple<Integer, Integer, Integer>> ts = filter(
                t -> (t.c == 0) == Objects.equals(t.a, t.b),
                P.triples(
                        P.withNull(P.integersGeometric()),
                        P.withNull(P.integersGeometric()),
                        P.withScale(4).integersGeometric()
                )
        );
        for (Triple<Integer, Integer, Integer> t : take(LIMIT, ts)) {
            Comparator<Integer> comparator = (i, j) -> {
                if (!Objects.equals(i, t.a)) {
                    throw new IllegalArgumentException();
                }
                if (!Objects.equals(j, t.b)) {
                    throw new IllegalArgumentException();
                }
                return t.c;
            };
            System.out.println("compare(" + t.a + " " + fromInt(t.c) + " " + t.b + ", " + t.a + ", " + t.b + ") = " +
                    compare(comparator, t.a, t.b));
        }
    }

    private void demoEq_T_T() {
        for (Pair<Integer, Integer> p : take(LIMIT, P.pairs(P.integersGeometric()))) {
            System.out.println(p.a + " is " + (eq(p.a, p.b) ? "" : "not ") + "equal to " + p.b);
        }
    }

    private void demoNe_T_T() {
        for (Pair<Integer, Integer> p : take(LIMIT, P.pairs(P.integersGeometric()))) {
            System.out.println(p.a + " is " + (ne(p.a, p.b) ? "" : "not ") + "unequal to " + p.b);
        }
    }

    private void demoLt_T_T() {
        for (Pair<Integer, Integer> p : take(LIMIT, P.pairs(P.integersGeometric()))) {
            System.out.println(p.a + " is " + (lt(p.a, p.b) ? "" : "not ") + "less than " + p.b);
        }
    }

    private void demoGt_T_T() {
        for (Pair<Integer, Integer> p : take(LIMIT, P.pairs(P.integersGeometric()))) {
            System.out.println(p.a + " is " + (gt(p.a, p.b) ? "" : "not ") + "greater than " + p.b);
        }
    }

    private void demoLe_T_T() {
        for (Pair<Integer, Integer> p : take(LIMIT, P.pairs(P.integersGeometric()))) {
            System.out.println(p.a + " is " + (le(p.a, p.b) ? "" : "not ") + "less than or equal to " + p.b);
        }
    }

    private void demoGe_T_T() {
        for (Pair<Integer, Integer> p : take(LIMIT, P.pairs(P.integersGeometric()))) {
            System.out.println(p.a + " is " + (ge(p.a, p.b) ? "" : "not ") + "greater than or equal to " + p.b);
        }
    }

    private void demoEq_Comparator_T_T() {
        Iterable<Triple<Integer, Integer, Integer>> ts = filter(
                t -> (t.c == 0) == Objects.equals(t.a, t.b),
                P.triples(
                        P.withNull(P.integersGeometric()),
                        P.withNull(P.integersGeometric()),
                        P.withScale(4).integersGeometric()
                )
        );
        for (Triple<Integer, Integer, Integer> t : take(LIMIT, ts)) {
            Comparator<Integer> comparator = (i, j) -> {
                if (!Objects.equals(i, t.a)) {
                    throw new IllegalArgumentException();
                }
                if (!Objects.equals(j, t.b)) {
                    throw new IllegalArgumentException();
                }
                return t.c;
            };
            System.out.println(t.a + " " + fromInt(t.c) + " " + t.b + ": " + t.a + " is " +
                    (eq(comparator, t.a, t.b) ? "" : "not ") + "equal to " + t.b);
        }
    }

    private void demoNe_Comparator_T_T() {
        Iterable<Triple<Integer, Integer, Integer>> ts = filter(
                t -> (t.c == 0) == Objects.equals(t.a, t.b),
                P.triples(
                        P.withNull(P.integersGeometric()),
                        P.withNull(P.integersGeometric()),
                        P.withScale(4).integersGeometric()
                )
        );
        for (Triple<Integer, Integer, Integer> t : take(LIMIT, ts)) {
            Comparator<Integer> comparator = (i, j) -> {
                if (!Objects.equals(i, t.a)) {
                    throw new IllegalArgumentException();
                }
                if (!Objects.equals(j, t.b)) {
                    throw new IllegalArgumentException();
                }
                return t.c;
            };
            System.out.println(t.a + " " + fromInt(t.c) + " " + t.b + ": " + t.a + " is " +
                    (ne(comparator, t.a, t.b) ? "" : "not ") + "unequal to " + t.b);
        }
    }

    private void demoLt_Comparator_T_T() {
        Iterable<Triple<Integer, Integer, Integer>> ts = filter(
                t -> (t.c == 0) == Objects.equals(t.a, t.b),
                P.triples(
                        P.withNull(P.integersGeometric()),
                        P.withNull(P.integersGeometric()),
                        P.withScale(4).integersGeometric()
                )
        );
        for (Triple<Integer, Integer, Integer> t : take(LIMIT, ts)) {
            Comparator<Integer> comparator = (i, j) -> {
                if (!Objects.equals(i, t.a)) {
                    throw new IllegalArgumentException();
                }
                if (!Objects.equals(j, t.b)) {
                    throw new IllegalArgumentException();
                }
                return t.c;
            };
            System.out.println(t.a + " " + fromInt(t.c) + " " + t.b + ": " + t.a + " is " +
                    (lt(comparator, t.a, t.b) ? "" : "not ") + "less than " + t.b);
        }
    }

    private void demoGt_Comparator_T_T() {
        Iterable<Triple<Integer, Integer, Integer>> ts = filter(
                t -> (t.c == 0) == Objects.equals(t.a, t.b),
                P.triples(
                        P.withNull(P.integersGeometric()),
                        P.withNull(P.integersGeometric()),
                        P.withScale(4).integersGeometric()
                )
        );
        for (Triple<Integer, Integer, Integer> t : take(LIMIT, ts)) {
            Comparator<Integer> comparator = (i, j) -> {
                if (!Objects.equals(i, t.a)) {
                    throw new IllegalArgumentException();
                }
                if (!Objects.equals(j, t.b)) {
                    throw new IllegalArgumentException();
                }
                return t.c;
            };
            System.out.println(t.a + " " + fromInt(t.c) + " " + t.b + ": " + t.a + " is " +
                    (gt(comparator, t.a, t.b) ? "" : "not ") + "greater than " + t.b);
        }
    }

    private void demoLe_Comparator_T_T() {
        Iterable<Triple<Integer, Integer, Integer>> ts = filter(
                t -> (t.c == 0) == Objects.equals(t.a, t.b),
                P.triples(
                        P.withNull(P.integersGeometric()),
                        P.withNull(P.integersGeometric()),
                        P.withScale(4).integersGeometric()
                )
        );
        for (Triple<Integer, Integer, Integer> t : take(LIMIT, ts)) {
            Comparator<Integer> comparator = (i, j) -> {
                if (!Objects.equals(i, t.a)) {
                    throw new IllegalArgumentException();
                }
                if (!Objects.equals(j, t.b)) {
                    throw new IllegalArgumentException();
                }
                return t.c;
            };
            System.out.println(t.a + " " + fromInt(t.c) + " " + t.b + ": " + t.a + " is " +
                    (le(comparator, t.a, t.b) ? "" : "not ") + "less than or equal to " + t.b);
        }
    }

    private void demoGe_Comparator_T_T() {
        Iterable<Triple<Integer, Integer, Integer>> ts = filter(
                t -> (t.c == 0) == Objects.equals(t.a, t.b),
                P.triples(
                        P.withNull(P.integersGeometric()),
                        P.withNull(P.integersGeometric()),
                        P.withScale(4).integersGeometric()
                )
        );
        for (Triple<Integer, Integer, Integer> t : take(LIMIT, ts)) {
            Comparator<Integer> comparator = (i, j) -> {
                if (!Objects.equals(i, t.a)) {
                    throw new IllegalArgumentException();
                }
                if (!Objects.equals(j, t.b)) {
                    throw new IllegalArgumentException();
                }
                return t.c;
            };
            System.out.println(t.a + " " + fromInt(t.c) + " " + t.b + ": " + t.a + " is " +
                    (ge(comparator, t.a, t.b) ? "" : "not ") + "greater than or equal to " + t.b);
        }
    }

    private void demoMin_T_T() {
        for (Pair<Integer, Integer> p : take(LIMIT, P.pairs(P.integersGeometric()))) {
            System.out.println("min(" + p.a + ", " + p.b + ") = " + min(p.a, p.b));
        }
    }

    private void demoMax_T_T() {
        for (Pair<Integer, Integer> p : take(LIMIT, P.pairs(P.integersGeometric()))) {
            System.out.println("max(" + p.a + ", " + p.b + ") = " + max(p.a, p.b));
        }
    }

    private void demoMinMax_T_T() {
        for (Pair<Integer, Integer> p : take(LIMIT, P.pairs(P.integersGeometric()))) {
            System.out.println("minMax(" + p.a + ", " + p.b + ") = " + minMax(p.a, p.b));
        }
    }

    private void demoMin_Comparator_T_T() {
        Iterable<Triple<Integer, Integer, Integer>> ts = filter(
                t -> (t.c == 0) == Objects.equals(t.a, t.b),
                P.triples(
                        P.withNull(P.integersGeometric()),
                        P.withNull(P.integersGeometric()),
                        P.withScale(4).integersGeometric()
                )
        );
        for (Triple<Integer, Integer, Integer> t : take(LIMIT, ts)) {
            Comparator<Integer> comparator = (i, j) -> {
                if (!Objects.equals(i, t.a)) {
                    throw new IllegalArgumentException();
                }
                if (!Objects.equals(j, t.b)) {
                    throw new IllegalArgumentException();
                }
                return t.c;
            };
            System.out.println("min(" + t.a + " " + fromInt(t.c) + " " + t.b + ", " + t.a + ", " + t.b + ") = " +
                    min(comparator, t.a, t.b));
        }
    }

    private void demoMax_Comparator_T_T() {
        Iterable<Triple<Integer, Integer, Integer>> ts = filter(
                t -> (t.c == 0) == Objects.equals(t.a, t.b),
                P.triples(
                        P.withNull(P.integersGeometric()),
                        P.withNull(P.integersGeometric()),
                        P.withScale(4).integersGeometric()
                )
        );
        for (Triple<Integer, Integer, Integer> t : take(LIMIT, ts)) {
            Comparator<Integer> comparator = (i, j) -> {
                if (!Objects.equals(i, t.a)) {
                    throw new IllegalArgumentException();
                }
                if (!Objects.equals(j, t.b)) {
                    throw new IllegalArgumentException();
                }
                return t.c;
            };
            System.out.println("max(" + t.a + " " + fromInt(t.c) + " " + t.b + ", " + t.a + ", " + t.b + ") = " +
                    max(comparator, t.a, t.b));
        }
    }

    private void demoMinMax_Comparator_T_T() {
        Iterable<Triple<Integer, Integer, Integer>> ts = filter(
                t -> (t.c == 0) == Objects.equals(t.a, t.b),
                P.triples(
                        P.withNull(P.integersGeometric()),
                        P.withNull(P.integersGeometric()),
                        P.withScale(4).integersGeometric()
                )
        );
        for (Triple<Integer, Integer, Integer> t : take(LIMIT, ts)) {
            Comparator<Integer> comparator = (i, j) -> {
                if (!Objects.equals(i, t.a)) {
                    throw new IllegalArgumentException();
                }
                if (!Objects.equals(j, t.b)) {
                    throw new IllegalArgumentException();
                }
                return t.c;
            };
            System.out.println("minMax(" + t.a + " " + fromInt(t.c) + " " + t.b + ", " + t.a + ", " + t.b + ") = " +
                    minMax(comparator, t.a, t.b));
        }
    }

    private void demoMinimum_Iterable_T() {
        for (List<Integer> xs : take(LIMIT, P.listsAtLeast(1, P.integersGeometric()))) {
            System.out.println("minimum(" + middle(xs.toString()) + ") = " + minimum(xs));
        }
    }

    private void demoMaximum_Iterable_T() {
        for (List<Integer> xs : take(LIMIT, P.listsAtLeast(1, P.integersGeometric()))) {
            System.out.println("maximum(" + middle(xs.toString()) + ") = " + maximum(xs));
        }
    }

    private void demoMinimumMaximum_Iterable_T() {
        for (List<Integer> xs : take(LIMIT, P.listsAtLeast(1, P.integersGeometric()))) {
            System.out.println("minimumMaximum(" + middle(xs.toString()) + ") = " + minimumMaximum(xs));
        }
    }

    private void demoMinimum_Comparator_Iterable_T() {
        Iterable<Pair<List<Integer>, List<Integer>>> ps = P.dependentPairs(
                P.withScale(4).listsAtLeast(1, P.withNull(P.integersGeometric())),
                is -> P.permutationsFinite(toList(nub(is)))
        );
        for (Pair<List<Integer>, List<Integer>> p : take(LIMIT, ps)) {
            Comparator<Integer> comparator = (x, y) -> {
                Integer xIndex = p.b.indexOf(x);
                if (xIndex == -1) {
                    throw new IllegalArgumentException();
                }
                Integer yIndex = p.b.indexOf(y);
                if (yIndex == -1) {
                    throw new IllegalArgumentException();
                }
                return Integer.compare(xIndex, yIndex);
            };
            System.out.println(intercalate(" < ", map(Objects::toString, p.b)) + ": minimum(" +
                    middle(p.a.toString()) + ") = " + minimum(comparator, p.a));
        }
    }

    private void demoMaximum_Comparator_Iterable_T() {
        Iterable<Pair<List<Integer>, List<Integer>>> ps = P.dependentPairs(
                P.withScale(4).listsAtLeast(1, P.withNull(P.integersGeometric())),
                is -> P.permutationsFinite(toList(nub(is)))
        );
        for (Pair<List<Integer>, List<Integer>> p : take(LIMIT, ps)) {
            Comparator<Integer> comparator = (x, y) -> {
                Integer xIndex = p.b.indexOf(x);
                if (xIndex == -1) {
                    throw new IllegalArgumentException();
                }
                Integer yIndex = p.b.indexOf(y);
                if (yIndex == -1) {
                    throw new IllegalArgumentException();
                }
                return Integer.compare(xIndex, yIndex);
            };
            System.out.println(intercalate(" < ", map(Objects::toString, p.b)) + ": maximum(" +
                    middle(p.a.toString()) + ") = " + maximum(comparator, p.a));
        }
    }

    private void demoMinimumMaximum_Comparator_Iterable_T() {
        Iterable<Pair<List<Integer>, List<Integer>>> ps = P.dependentPairs(
                P.withScale(4).listsAtLeast(1, P.withNull(P.integersGeometric())),
                is -> P.permutationsFinite(toList(nub(is)))
        );
        for (Pair<List<Integer>, List<Integer>> p : take(LIMIT, ps)) {
            Comparator<Integer> comparator = (x, y) -> {
                Integer xIndex = p.b.indexOf(x);
                if (xIndex == -1) {
                    throw new IllegalArgumentException();
                }
                Integer yIndex = p.b.indexOf(y);
                if (yIndex == -1) {
                    throw new IllegalArgumentException();
                }
                return Integer.compare(xIndex, yIndex);
            };
            System.out.println(intercalate(" < ", map(Objects::toString, p.b)) + ": minimumMaximum(" +
                    middle(p.a.toString()) + ") = " + minimumMaximum(comparator, p.a));
        }
    }

    private void demoMinimum_String() {
        for (String s : take(LIMIT, P.stringsAtLeast(1))) {
            System.out.println("minimum(" + nicePrint(s) + ") = " + nicePrint(minimum(s)));
        }
    }

    private void demoMaximum_String() {
        for (String s : take(LIMIT, P.stringsAtLeast(1))) {
            System.out.println("maximum(" + nicePrint(s) + ") = " + nicePrint(maximum(s)));
        }
    }

    private void demoMinimumMaximum_String() {
        for (String s : take(LIMIT, P.stringsAtLeast(1))) {
            Pair<Character, Character> result = minimumMaximum(s);
            System.out.println("minimumMaximum(" + nicePrint(s) + ") = " +
                    new Pair<>(nicePrint(result.a), nicePrint(result.b)));
        }
    }

    private void demoMinimum_Comparator_String() {
        Iterable<Pair<String, String>> ps = P.dependentPairs(
                P.withScale(4).stringsAtLeast(1),
                s -> map(IterableUtils::charsToString, P.permutationsFinite(toList(nub(s))))
        );
        for (Pair<String, String> p : take(LIMIT, ps)) {
            Comparator<Character> comparator = (x, y) -> {
                Integer xIndex = p.b.indexOf(x);
                if (xIndex == -1) {
                    throw new IllegalArgumentException();
                }
                Integer yIndex = p.b.indexOf(y);
                if (yIndex == -1) {
                    throw new IllegalArgumentException();
                }
                return Integer.compare(xIndex, yIndex);
            };
            System.out.println(intercalate(" < ", map(Testing::nicePrint, fromString(p.b))) + ": minimum(" +
                    nicePrint(p.a) + ") = " + nicePrint(minimum(comparator, p.a)));
        }
    }

    private void demoMaximum_Comparator_String() {
        Iterable<Pair<String, String>> ps = P.dependentPairs(
                P.withScale(4).stringsAtLeast(1),
                s -> map(IterableUtils::charsToString, P.permutationsFinite(toList(nub(s))))
        );
        for (Pair<String, String> p : take(LIMIT, ps)) {
            Comparator<Character> comparator = (x, y) -> {
                Integer xIndex = p.b.indexOf(x);
                if (xIndex == -1) {
                    throw new IllegalArgumentException();
                }
                Integer yIndex = p.b.indexOf(y);
                if (yIndex == -1) {
                    throw new IllegalArgumentException();
                }
                return Integer.compare(xIndex, yIndex);
            };
            System.out.println(intercalate(" < ", map(Testing::nicePrint, fromString(p.b))) + ": minimum(" +
                    nicePrint(p.a) + ") = " + nicePrint(maximum(comparator, p.a)));
        }
    }

    private void demoMinimumMaximum_Comparator_String() {
        Iterable<Pair<String, String>> ps = P.dependentPairs(
                P.withScale(4).stringsAtLeast(1),
                s -> map(IterableUtils::charsToString, P.permutationsFinite(toList(nub(s))))
        );
        for (Pair<String, String> p : take(LIMIT, ps)) {
            Comparator<Character> comparator = (x, y) -> {
                Integer xIndex = p.b.indexOf(x);
                if (xIndex == -1) {
                    throw new IllegalArgumentException();
                }
                Integer yIndex = p.b.indexOf(y);
                if (yIndex == -1) {
                    throw new IllegalArgumentException();
                }
                return Integer.compare(xIndex, yIndex);
            };
            System.out.println(intercalate(" < ", map(Testing::nicePrint, fromString(p.b))) + ": minimum(" +
                    nicePrint(p.a) + ") = " + nicePrint(minimumMaximum(comparator, p.a).toString()));
        }
    }

    private void demoIncreasing_Iterable() {
        for (List<Integer> xs : take(LIMIT, P.withScale(4).lists(P.integersGeometric()))) {
            System.out.println(xs + " is " + (increasing(xs) ? "" : "not ") + "increasing");
        }
    }

    private void demoDecreasing_Iterable() {
        for (List<Integer> xs : take(LIMIT, P.withScale(4).lists(P.integersGeometric()))) {
            System.out.println(xs + " is " + (decreasing(xs) ? "" : "not ") + "decreasing");
        }
    }

    private void demoWeaklyIncreasing_Iterable() {
        for (List<Integer> xs : take(LIMIT, P.withScale(4).lists(P.integersGeometric()))) {
            System.out.println(xs + " is " + (weaklyIncreasing(xs) ? "" : "not ") + "weakly increasing");
        }
    }

    private void demoWeaklyDecreasing_Iterable() {
        for (List<Integer> xs : take(LIMIT, P.withScale(4).lists(P.integersGeometric()))) {
            System.out.println(xs + " is " + (weaklyDecreasing(xs) ? "" : "not ") + "weakly decreasing");
        }
    }

    private void demoZigzagging_Iterable() {
        for (List<Integer> xs : take(LIMIT, P.withScale(4).lists(P.integersGeometric()))) {
            System.out.println(xs + " is " + (zigzagging(xs) ? "" : "not ") + "zigzagging");
        }
    }

    private void demoIncreasing_Comparator_Iterable_T() {
        Iterable<Pair<List<Integer>, List<Integer>>> ps = P.dependentPairs(
                P.withScale(4).lists(P.withNull(P.integersGeometric())),
                is -> P.permutationsFinite(toList(nub(is)))
        );
        for (Pair<List<Integer>, List<Integer>> p : take(LIMIT, ps)) {
            Comparator<Integer> comparator = (x, y) -> {
                Integer xIndex = p.b.indexOf(x);
                if (xIndex == -1) {
                    throw new IllegalArgumentException();
                }
                Integer yIndex = p.b.indexOf(y);
                if (yIndex == -1) {
                    throw new IllegalArgumentException();
                }
                return Integer.compare(xIndex, yIndex);
            };
            System.out.println(intercalate(" < ", map(Objects::toString, p.b)) + ": " + p.a + " is " +
                    (increasing(comparator, p.a) ? "" : "not ") + "increasing");
        }
    }

    private void demoDecreasing_Comparator_Iterable_T() {
        Iterable<Pair<List<Integer>, List<Integer>>> ps = P.dependentPairs(
                P.withScale(4).lists(P.withNull(P.integersGeometric())),
                is -> P.permutationsFinite(toList(nub(is)))
        );
        for (Pair<List<Integer>, List<Integer>> p : take(LIMIT, ps)) {
            Comparator<Integer> comparator = (x, y) -> {
                Integer xIndex = p.b.indexOf(x);
                if (xIndex == -1) {
                    throw new IllegalArgumentException();
                }
                Integer yIndex = p.b.indexOf(y);
                if (yIndex == -1) {
                    throw new IllegalArgumentException();
                }
                return Integer.compare(xIndex, yIndex);
            };
            System.out.println(intercalate(" < ", map(Objects::toString, p.b)) + ": " + p.a + " is " +
                    (decreasing(comparator, p.a) ? "" : "not ") + "decreasing");
        }
    }

    private void demoWeaklyIncreasing_Comparator_Iterable_T() {
        Iterable<Pair<List<Integer>, List<Integer>>> ps = P.dependentPairs(
                P.withScale(4).lists(P.withNull(P.integersGeometric())),
                is -> P.permutationsFinite(toList(nub(is)))
        );
        for (Pair<List<Integer>, List<Integer>> p : take(LIMIT, ps)) {
            Comparator<Integer> comparator = (x, y) -> {
                Integer xIndex = p.b.indexOf(x);
                if (xIndex == -1) {
                    throw new IllegalArgumentException();
                }
                Integer yIndex = p.b.indexOf(y);
                if (yIndex == -1) {
                    throw new IllegalArgumentException();
                }
                return Integer.compare(xIndex, yIndex);
            };
            System.out.println(intercalate(" < ", map(Objects::toString, p.b)) + ": " + p.a + " is " +
                    (weaklyIncreasing(comparator, p.a) ? "" : "not ") + "weakly increasing");
        }
    }

    private void demoWeaklyDecreasing_Comparator_Iterable_T() {
        Iterable<Pair<List<Integer>, List<Integer>>> ps = P.dependentPairs(
                P.withScale(4).lists(P.withNull(P.integersGeometric())),
                is -> P.permutationsFinite(toList(nub(is)))
        );
        for (Pair<List<Integer>, List<Integer>> p : take(LIMIT, ps)) {
            Comparator<Integer> comparator = (x, y) -> {
                Integer xIndex = p.b.indexOf(x);
                if (xIndex == -1) {
                    throw new IllegalArgumentException();
                }
                Integer yIndex = p.b.indexOf(y);
                if (yIndex == -1) {
                    throw new IllegalArgumentException();
                }
                return Integer.compare(xIndex, yIndex);
            };
            System.out.println(intercalate(" < ", map(Objects::toString, p.b)) + ": " + p.a + " is " +
                    (weaklyDecreasing(comparator, p.a) ? "" : "not ") + "weakly decreasing");
        }
    }

    private void demoZigzagging_Comparator_Iterable_T() {
        Iterable<Pair<List<Integer>, List<Integer>>> ps = P.dependentPairs(
                P.withScale(4).lists(P.withNull(P.integersGeometric())),
                is -> P.permutationsFinite(toList(nub(is)))
        );
        for (Pair<List<Integer>, List<Integer>> p : take(LIMIT, ps)) {
            Comparator<Integer> comparator = (x, y) -> {
                Integer xIndex = p.b.indexOf(x);
                if (xIndex == -1) {
                    throw new IllegalArgumentException();
                }
                Integer yIndex = p.b.indexOf(y);
                if (yIndex == -1) {
                    throw new IllegalArgumentException();
                }
                return Integer.compare(xIndex, yIndex);
            };
            System.out.println(intercalate(" < ", map(Objects::toString, p.b)) + ": " + p.a + " is " +
                    (zigzagging(comparator, p.a) ? "" : "not ") + "zigzagging");
        }
    }

    private void demoIncreasing_String() {
        for (String s : take(LIMIT, P.strings())) {
            System.out.println(nicePrint(s) + " is " + (increasing(s) ? "" : "not ") + "increasing");
        }
    }

    private void demoDecreasing_String() {
        for (String s : take(LIMIT, P.strings())) {
            System.out.println(nicePrint(s) + " is " + (decreasing(s) ? "" : "not ") + "decreasing");
        }
    }

    private void demoWeaklyIncreasing_String() {
        for (String s : take(LIMIT, P.strings())) {
            System.out.println(nicePrint(s) + " is " + (weaklyIncreasing(s) ? "" : "not ") + "weakly increasing");
        }
    }

    private void demoWeaklyDecreasing_String() {
        for (String s : take(LIMIT, P.strings())) {
            System.out.println(nicePrint(s) + " is " + (weaklyDecreasing(s) ? "" : "not ") + "weakly decreasing");
        }
    }

    private void demoZigzagging_String() {
        for (String s : take(LIMIT, P.strings())) {
            System.out.println(nicePrint(s) + " is " + (zigzagging(s) ? "" : "not ") + "zigzagging");
        }
    }

    private void demoIncreasing_Comparator_String() {
        Iterable<Pair<String, String>> ps = P.dependentPairs(
                P.withScale(4).strings(),
                s -> map(IterableUtils::charsToString, P.permutationsFinite(toList(nub(s))))
        );
        for (Pair<String, String> p : take(LIMIT, ps)) {
            Comparator<Character> comparator = (x, y) -> {
                Integer xIndex = p.b.indexOf(x);
                if (xIndex == -1) {
                    throw new IllegalArgumentException();
                }
                Integer yIndex = p.b.indexOf(y);
                if (yIndex == -1) {
                    throw new IllegalArgumentException();
                }
                return Integer.compare(xIndex, yIndex);
            };
            System.out.println(intercalate(" < ", map(Testing::nicePrint, fromString(p.b))) + ": " + nicePrint(p.a) +
                    " is " + (increasing(p.b) ? "" : "not ") + "increasing");
        }
    }

    private void demoDecreasing_Comparator_String() {
        Iterable<Pair<String, String>> ps = P.dependentPairs(
                P.withScale(4).strings(),
                s -> map(IterableUtils::charsToString, P.permutationsFinite(toList(nub(s))))
        );
        for (Pair<String, String> p : take(LIMIT, ps)) {
            Comparator<Character> comparator = (x, y) -> {
                Integer xIndex = p.b.indexOf(x);
                if (xIndex == -1) {
                    throw new IllegalArgumentException();
                }
                Integer yIndex = p.b.indexOf(y);
                if (yIndex == -1) {
                    throw new IllegalArgumentException();
                }
                return Integer.compare(xIndex, yIndex);
            };
            System.out.println(intercalate(" < ", map(Testing::nicePrint, fromString(p.b))) + ": " + nicePrint(p.a) +
                    " is " + (decreasing(p.b) ? "" : "not ") + "decreasing");
        }
    }

    private void demoWeaklyIncreasing_Comparator_String() {
        Iterable<Pair<String, String>> ps = P.dependentPairs(
                P.withScale(4).strings(),
                s -> map(IterableUtils::charsToString, P.permutationsFinite(toList(nub(s))))
        );
        for (Pair<String, String> p : take(LIMIT, ps)) {
            Comparator<Character> comparator = (x, y) -> {
                Integer xIndex = p.b.indexOf(x);
                if (xIndex == -1) {
                    throw new IllegalArgumentException();
                }
                Integer yIndex = p.b.indexOf(y);
                if (yIndex == -1) {
                    throw new IllegalArgumentException();
                }
                return Integer.compare(xIndex, yIndex);
            };
            System.out.println(intercalate(" < ", map(Testing::nicePrint, fromString(p.b))) + ": " + nicePrint(p.a) +
                    " is " + (weaklyIncreasing(p.b) ? "" : "not ") + "weakly increasing");
        }
    }

    private void demoWeaklyDecreasing_Comparator_String() {
        Iterable<Pair<String, String>> ps = P.dependentPairs(
                P.withScale(4).strings(),
                s -> map(IterableUtils::charsToString, P.permutationsFinite(toList(nub(s))))
        );
        for (Pair<String, String> p : take(LIMIT, ps)) {
            Comparator<Character> comparator = (x, y) -> {
                Integer xIndex = p.b.indexOf(x);
                if (xIndex == -1) {
                    throw new IllegalArgumentException();
                }
                Integer yIndex = p.b.indexOf(y);
                if (yIndex == -1) {
                    throw new IllegalArgumentException();
                }
                return Integer.compare(xIndex, yIndex);
            };
            System.out.println(intercalate(" < ", map(Testing::nicePrint, fromString(p.b))) + ": " + nicePrint(p.a) +
                    " is " + (weaklyDecreasing(p.b) ? "" : "not ") + "weakly decreasing");
        }
    }

    private void demoZigzagging_Comparator_String() {
        Iterable<Pair<String, String>> ps = P.dependentPairs(
                P.withScale(4).strings(),
                s -> map(IterableUtils::charsToString, P.permutationsFinite(toList(nub(s))))
        );
        for (Pair<String, String> p : take(LIMIT, ps)) {
            Comparator<Character> comparator = (x, y) -> {
                Integer xIndex = p.b.indexOf(x);
                if (xIndex == -1) {
                    throw new IllegalArgumentException();
                }
                Integer yIndex = p.b.indexOf(y);
                if (yIndex == -1) {
                    throw new IllegalArgumentException();
                }
                return Integer.compare(xIndex, yIndex);
            };
            System.out.println(intercalate(" < ", map(Testing::nicePrint, fromString(p.b))) + ": " + nicePrint(p.a) +
                    " is " + (zigzagging(p.b) ? "" : "not ") + "zigzagging");
        }
    }

    private void demoReadOrderingStrict() {
        for (String s : take(LIMIT, P.strings())) {
            System.out.println("readOrderingStrict(" + nicePrint(s) + ") = " + readStrict(s));
        }
    }

    private void demoReadOrderingStrict_targeted() {
        for (String s : take(LIMIT, P.strings(ORDERING_CHARS))) {
            System.out.println("readOrderingStrict(" + s + ") = " + readStrict(s));
        }
    }

    private void demoToString() {
        for (Ordering o : take(LIMIT, P.orderings())) {
            System.out.println(o);
        }
    }
}


text:
<?php

	function db_connect($host, $username, $password, $database)
	{
		$connection = mysql_connect($host, $username, $password, true);
		if ($connection)
		{
			if (!mysql_select_db($database, $connection))
			{
				//Unable to select database.
				return false;
			}
		}
		else
		{
			//Can't connect to database server.
			return false;
		}

		return $connection;
	}

	function db_query($query, $params, $resource=NULL)
	{
		$replacement_pairs = array();
		foreach ($params as $key=>$value) $replacement_pairs['{'.$key.'}'] = $value;
		$replacement_pairs = array_map('mysql_real_escape_string', $replacement_pairs);
		$query = strtr($query, $replacement_pairs);
		$result = is_resource($resource) ? mysql_query($query, $resource) : mysql_query($query);
		return (!mysql_errno()) ? $result : false;
	}
/*
	function db_mysql_query_range($query, $from, $count)
	{
		return $query.' LIMIT '.(int)$from.','.(int)$count;
	}
*/

	function db_error()
	{
		return mysql_errno();
	}

	function db_rows($query, $params, $resource=NULL)
	{
		$result = db_query($query, $params, $resource);
		if ($result)
		{
			$rows = array();
			while ($row = mysql_fetch_assoc($result)) $rows[] = $row;
			return $rows;
		}

		return array();
	}

	function db_row($query, $params, $resource=NULL)
	{
		$result = db_query($query, $params, $resource);
		return $result ? mysql_fetch_assoc($result) : array();
	}

	function db_num_rows($result)
	{
		return $result ? mysql_num_rows($result) : array();
	}

	function db_result($result, $row=0)
	{
		return ($result and (mysql_num_rows($result) > $row)) ? mysql_result($result, $row) : false;
	}

	function db_affected_rows()
	{
		return mysql_affected_rows();
	}

	function db_insert_id()
	{
		return mysql_insert_id();
	}

	function db_update($table, $row, $row_id)
	{
	}

	function db_insert($table, $row)
	{

	}

?>

redpajama_set_name: RedPajamaGithub


text:
<?php
declare(strict_types = 1);

namespace mheinzerling\dist\config;

use mheinzerling\commons\FileUtils;
use mheinzerling\commons\JsonUtils;
use mheinzerling\commons\Separator;

class Local
{
    /**
     * @var string
     */
    private $distDir;
    /**
     * @var string
     */
    private $overwriteDir;

    public function __construct(array $json)
    {
        JsonUtils::validProperties($json, ["distDir", "overwriteDir"]);
        //with trailing / and unix separator TODO
        $this->distDir = rtrim(FileUtils::to(JsonUtils::required($json, "distDir"), Separator::UNIX()), Separator::UNIX) . Separator::UNIX;
        $this->overwriteDir = rtrim(FileUtils::to(JsonUtils::required($json, "overwriteDir"), Separator::UNIX()), Separator::UNIX) . Separator::UNIX;

        $root = stristr(__DIR__, "vendor") !== false ? __DIR__ . '/../../../../..' : __DIR__ . '/../..';
        $this->root = FileUtils::to(realpath($root) . "/", Separator::UNIX());
    }

    public function getRoot(): string
    {
        return $this->root;
    }

    public function stripRoot($absolutePath): string
    {
        return str_replace($this->root, '', $absolutePath);
    }

    public function toOverwritePath($realPath): string
    {
        return str_replace($this->root, $this->getOverwriteDirectory(), $realPath);
    }

    public function getOverwriteDirectory(): string
    {
        return FileUtils::append($this->root, $this->overwriteDir);
    }

    public function getAbsoluteArchivesDirectory(): string
    {
        return FileUtils::append($this->root, $this->distDir);
    }

    public function getAbsoluteArchiveFile($version): string
    {
        $distName = 'dist.' . $version . '.zip';
        return FileUtils::append($this->getAbsoluteArchivesDirectory(), $distName);
    }

    /**
     * @return string[]
     */
    public function getArchives(): array
    {
        return array_map("basename", glob($this->getAbsoluteArchivesDirectory() . "dist*.zip"));
    }

    public function getVersionFile(): string
    {
        return FileUtils::append($this->root, "VERSION");
    }

    public function getProjectIterator(): \RecursiveIteratorIterator
    {
        $directories = new \RecursiveDirectoryIterator($this->root, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::UNIX_PATHS);
        return new \RecursiveIteratorIterator($directories, \RecursiveIteratorIterator::SELF_FIRST);
    }

}


text:
var ziti = require('../../index');

var Language = ziti.define('Language', {
    name: ziti.String,
});

module.exports = Language;


text:
<?php

namespace Nice\Tests\Extension;

use Nice\Extension\CacheConfiguration;
use Symfony\Component\Config\Definition\Processor;

class CacheConfigurationTest extends \PHPUnit_Framework_TestCase
{
    public function testDefaultConfig()
    {
        $processor = new Processor();
        $config = $processor->processConfiguration(new CacheConfiguration(), array(array()));

        $this->assertEquals(
            self::getDefaultConfig(),
            $config
        );
    }

    public function testDefaultConnectionConfig()
    {
        $processor = new Processor();
        $config = $processor->processConfiguration(new CacheConfiguration(), array(array('connections' => array('default' => array('driver' => 'redis')))));

        $this->assertEquals(
            array('connections' => array('default' => array_merge(self::getDefaulConnectionConfig(), array('driver' => 'redis')))),
            $config
        );
    }

    public function testInvalidDriver()
    {
        $this->setExpectedException(
            'Symfony\Component\Config\Definition\Exception\InvalidConfigurationException',
            'Invalid cache driver "fake"'
        );

        $processor = new Processor();
        $processor->processConfiguration(new CacheConfiguration(), array(array('connections' => array('default' => array('driver' => 'fake')))));
    }

    protected static function getDefaultConfig()
    {
        return array(
            'connections' => array(

            )
        );
    }

    protected static function getDefaulConnectionConfig()
    {
        return array(
            'namespace' => 'nice:',
            'options' => array(),
        );
    }
}


text:
import os
import platform
from importlib import reload

import schedule

import augentbot

def connect_run() -> None:
    os.system('git pull')
    if platform.system() == 'Windows':
        os.system('chcp 65001')  # fixes encoding errors on windows
    reload(augentbot)
    augentbot.run(create_buffers=1)

if __name__ == '__main__':
    schedule.every().day.at('00:59').do(connect_run)
    schedule.every().day.at('01:59').do(connect_run)
    schedule.every().day.at('02:59').do(connect_run)
    schedule.every().day.at('03:59').do(connect_run)
    schedule.every().day.at('04:59').do(connect_run)
    schedule.every().day.at('05:59').do(connect_run)
    schedule.every().day.at('06:59').do(connect_run)
    schedule.every().day.at('07:59').do(connect_run)
    schedule.every().day.at('08:59').do(connect_run)
    schedule.every().day.at('09:59').do(connect_run)
    schedule.every().day.at('10:59').do(connect_run)
    schedule.every().day.at('11:59').do(connect_run)
    schedule.every().day.at('12:59').do(connect_run)
    schedule.every().day.at('13:59').do(connect_run)
    schedule.every().day.at('14:59').do(connect_run)
    schedule.every().day.at('15:59').do(connect_run)
    schedule.every().day.at('16:59').do(connect_run)
    schedule.every().day.at('17:59').do(connect_run)
    schedule.every().day.at('18:59').do(connect_run)
    schedule.every().day.at('19:59').do(connect_run)
    schedule.every().day.at('20:59').do(connect_run)
    schedule.every().day.at('21:59').do(connect_run)
    schedule.every().day.at('22:59').do(connect_run)
    schedule.every().day.at('23:59').do(connect_run)

    while True:
        schedule.run_pending()


text:
/* ng-infinite-scroll - v1.0.0 - 2013-02-23 */
var mod;

mod = angular.module('infinite-scroll', []);

mod.directive('infiniteScroll', [
  '$rootScope', '$window', '$timeout', function($rootScope, $window, $timeout) {
    return {
      link: function(scope, elem, attrs) {
        var checkWhenEnabled, handler, scrollDistance, scrollEnabled;

        var container = angular.element($window);
        if (attrs.infiniteScrollContainer !== null){
        	 container = angular.element(attrs.infiniteScrollContainer);
        }
        scrollDistance = 0;
        if (attrs.infiniteScrollDistance != null) {
          scope.$watch(attrs.infiniteScrollDistance, function(value) {
            return scrollDistance = parseInt(value, 10);
          });
        }
        scrollEnabled = true;
        checkWhenEnabled = false;
        if (attrs.infiniteScrollDisabled != null) {
          scope.$watch(attrs.infiniteScrollDisabled, function(value) {
            scrollEnabled = !value;
            if (scrollEnabled && checkWhenEnabled) {
              checkWhenEnabled = false;
              return handler();
            }
          });
        }
        handler = function() {
          var elementBottom, remaining, shouldScroll, windowBottom;
          windowBottom = container.height() + container.scrollTop();
          elementBottom = elem.offset().top + elem.height();
          remaining = elementBottom - windowBottom;
          shouldScroll = remaining <= container.height() * scrollDistance;
          if (shouldScroll && scrollEnabled) {
            if ($rootScope.$$phase) {
              return scope.$eval(attrs.infiniteScroll);
            } else {
              return scope.$apply(attrs.infiniteScroll);
            }
          } else if (shouldScroll) {
            return checkWhenEnabled = true;
          }
        };
        container.on('scroll', handler);
        scope.$on('$destroy', function() {
          return container.off('scroll', handler);
        });
        return $timeout((function() {
          if (attrs.infiniteScrollImmediateCheck) {
            if (scope.$eval(attrs.infiniteScrollImmediateCheck)) {
              return handler();
            }
          } else {
            return handler();
          }
        }), 0);
      }
    };
  }
]);


text:
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>

@interface APLGraphView : UIView

@property float fullScale;
-(void)addX:(double)x y:(double)y z:(double)z;

@end


text:
package org.opencb.opencga.test.manager;

import org.opencb.opencga.test.config.Configuration;
import org.opencb.opencga.test.execution.LocalDatasetExecutor;
import org.opencb.opencga.test.execution.models.DatasetExecutionPlan;

import java.io.IOException;
import java.util.List;

public class DatasetPlanExecutionGenerator {

    private Configuration configuration;

    public DatasetPlanExecutionGenerator(Configuration configuration) {
        this.configuration = configuration;
    }

    /**
     * Process a list of given environments.
     *
     * @param
     * @return
     * @throws IOException
     */
    public List<DatasetExecutionPlan> generateCommandLines(boolean resume) throws IOException {
        DatasetCommandLineGenerator datasetCommandLineGenerator = new DatasetCommandLineGenerator(configuration);
        return datasetCommandLineGenerator.generateCommandLines(resume);
    }

    /**
     * Executes (creates) the VCF, must check execution configuration...
     *
     * @throws IOException
     */
    public void execute() throws IOException {
        List<DatasetExecutionPlan> commandLinesMap = this.generateCommandLines(false);
        LocalDatasetExecutor executor = new LocalDatasetExecutor(configuration);
        executor.execute(commandLinesMap);
    }

    /**
     * Dry-run of all CLIs.
     *
     * @throws IOException
     */
    public void simulate() throws IOException {
        List<DatasetExecutionPlan> datasetPlanExecutions = this.generateCommandLines(false);
        for (DatasetExecutionPlan datasetExecutionPlan : datasetPlanExecutions) {
            datasetExecutionPlan.simulate();
        }
    }

    public void resume() throws IOException {
        List<DatasetExecutionPlan> commandLinesMap = this.generateCommandLines(true);
        LocalDatasetExecutor executor = new LocalDatasetExecutor(configuration);
        executor.execute(commandLinesMap);
    }

    public void mutate() throws IOException {
        // List<DatasetExecutionPlan> commandLinesMap = this.generateCommandLines(true);
        LocalDatasetExecutor executor = new LocalDatasetExecutor(configuration);
        executor.mutate();
    }
}


text:
package org.apache.hadoop.mapreduce.task.reduce;

import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;

import javax.crypto.SecretKey;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.Counters;
import org.apache.hadoop.mapred.IFileOutputStream;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapreduce.TaskAttemptID;
import org.apache.hadoop.mapreduce.security.SecureShuffleUtils;
import org.apache.hadoop.mapreduce.security.token.JobTokenSecretManager;
import org.apache.hadoop.util.DiskChecker.DiskErrorException;
import org.junit.Test;

/**
 * Test that the Fetcher does what we expect it to.
 */
public class TestFetcher {
  private static final Log LOG = LogFactory.getLog(TestFetcher.class);

  public static class FakeFetcher<K,V> extends Fetcher<K,V> {

    private HttpURLConnection connection;

    public FakeFetcher(JobConf job, TaskAttemptID reduceId,
        ShuffleScheduler<K,V> scheduler, MergeManager<K,V> merger, Reporter reporter,
        ShuffleClientMetrics metrics, ExceptionReporter exceptionReporter,
        SecretKey jobTokenSecret, HttpURLConnection connection) {
      super(job, reduceId, scheduler, merger, reporter, metrics, exceptionReporter,
          jobTokenSecret);
      this.connection = connection;
    }

    @Override
    protected HttpURLConnection openConnection(URL url) throws IOException {
      if(connection != null) {
        return connection;
      }
      return super.openConnection(url);
    }
  }

  @SuppressWarnings("unchecked")
  @Test
  public void testReduceOutOfDiskSpace() throws Throwable {
    LOG.info("testReduceOutOfDiskSpace");
    JobConf job = new JobConf();
    TaskAttemptID id = TaskAttemptID.forName("attempt_0_1_r_1_1");
    ShuffleScheduler<Text, Text> ss = mock(ShuffleScheduler.class);
    MergeManager<Text, Text> mm = mock(MergeManager.class);
    Reporter r = mock(Reporter.class);
    ShuffleClientMetrics metrics = mock(ShuffleClientMetrics.class);
    ExceptionReporter except = mock(ExceptionReporter.class);
    SecretKey key = JobTokenSecretManager.createSecretKey(new byte[] { 0, 0, 0,
        0 });
    HttpURLConnection connection = mock(HttpURLConnection.class);

    Counters.Counter allErrs = mock(Counters.Counter.class);
    when(r.getCounter(anyString(), anyString())).thenReturn(allErrs);

    Fetcher<Text, Text> underTest = new FakeFetcher<Text, Text>(job, id, ss,
        mm, r, metrics, except, key, connection);

    MapHost host = new MapHost("localhost", "http://localhost:8080/");
    ArrayList<TaskAttemptID> maps = new ArrayList<TaskAttemptID>(1);
    TaskAttemptID map1ID = TaskAttemptID.forName("attempt_0_1_m_1_1");
    maps.add(map1ID);
    TaskAttemptID map2ID = TaskAttemptID.forName("attempt_0_1_m_2_1");
    maps.add(map2ID);
    String encHash = "vFE234EIFCiBgYs2tCXY/SjT8Kg=";
    String replyHash = SecureShuffleUtils.generateHash(encHash.getBytes(), key);
    ShuffleHeader header = new ShuffleHeader(map1ID.toString(), 10, 10, 1);
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    header.write(new DataOutputStream(bout));

    ByteArrayInputStream in = new ByteArrayInputStream(bout.toByteArray());

    when(ss.getMapsForHost(host)).thenReturn(maps);
    when(connection.getResponseCode()).thenReturn(200);
    when(
        connection
            .getHeaderField(SecureShuffleUtils.HTTP_HEADER_REPLY_URL_HASH))
        .thenReturn(replyHash);
    when(connection.getInputStream()).thenReturn(in);

    when(mm.reserve(any(TaskAttemptID.class), anyLong(), anyInt())).thenThrow(
        new DiskErrorException("No disk space available"));

    underTest.copyFromHost(host);
    verify(ss).reportLocalError(any(IOException.class));
  }

  @SuppressWarnings("unchecked")
  @Test(timeout=30000)
  public void testCopyFromHostConnectionTimeout() throws Exception {
    LOG.info("testCopyFromHostConnectionTimeout");
    JobConf job = new JobConf();
    TaskAttemptID id = TaskAttemptID.forName("attempt_0_1_r_1_1");
    ShuffleScheduler<Text, Text> ss = mock(ShuffleScheduler.class);
    MergeManager<Text, Text> mm = mock(MergeManager.class);
    Reporter r = mock(Reporter.class);
    ShuffleClientMetrics metrics = mock(ShuffleClientMetrics.class);
    ExceptionReporter except = mock(ExceptionReporter.class);
    SecretKey key = JobTokenSecretManager.createSecretKey(new byte[]{0,0,0,0});
    HttpURLConnection connection = mock(HttpURLConnection.class);
    when(connection.getInputStream()).thenThrow(
        new SocketTimeoutException("This is a fake timeout :)"));

    Counters.Counter allErrs = mock(Counters.Counter.class);
    when(r.getCounter(anyString(), anyString()))
      .thenReturn(allErrs);

    Fetcher<Text,Text> underTest = new FakeFetcher<Text,Text>(job, id, ss, mm,
        r, metrics, except, key, connection);

    MapHost host = new MapHost("localhost", "http://localhost:8080/");

    ArrayList<TaskAttemptID> maps = new ArrayList<TaskAttemptID>(1);
    TaskAttemptID map1ID = TaskAttemptID.forName("attempt_0_1_m_1_1");
    maps.add(map1ID);
    TaskAttemptID map2ID = TaskAttemptID.forName("attempt_0_1_m_2_1");
    maps.add(map2ID);
    when(ss.getMapsForHost(host)).thenReturn(maps);

    String encHash = "vFE234EIFCiBgYs2tCXY/SjT8Kg=";

    underTest.copyFromHost(host);

    verify(connection)
      .addRequestProperty(SecureShuffleUtils.HTTP_HEADER_URL_HASH,
          encHash);

    verify(allErrs).increment(1);
    verify(ss).copyFailed(map1ID, host, false, false);
    verify(ss).copyFailed(map2ID, host, false, false);

    verify(ss).putBackKnownMapOutput(any(MapHost.class), eq(map1ID));
    verify(ss).putBackKnownMapOutput(any(MapHost.class), eq(map2ID));
  }

  @SuppressWarnings("unchecked")
  @Test
  public void testCopyFromHostBogusHeader() throws Exception {
    LOG.info("testCopyFromHostBogusHeader");
    JobConf job = new JobConf();
    TaskAttemptID id = TaskAttemptID.forName("attempt_0_1_r_1_1");
    ShuffleScheduler<Text, Text> ss = mock(ShuffleScheduler.class);
    MergeManager<Text, Text> mm = mock(MergeManager.class);
    Reporter r = mock(Reporter.class);
    ShuffleClientMetrics metrics = mock(ShuffleClientMetrics.class);
    ExceptionReporter except = mock(ExceptionReporter.class);
    SecretKey key = JobTokenSecretManager.createSecretKey(new byte[]{0,0,0,0});
    HttpURLConnection connection = mock(HttpURLConnection.class);

    Counters.Counter allErrs = mock(Counters.Counter.class);
    when(r.getCounter(anyString(), anyString()))
      .thenReturn(allErrs);

    Fetcher<Text,Text> underTest = new FakeFetcher<Text,Text>(job, id, ss, mm,
        r, metrics, except, key, connection);

    MapHost host = new MapHost("localhost", "http://localhost:8080/");

    ArrayList<TaskAttemptID> maps = new ArrayList<TaskAttemptID>(1);
    TaskAttemptID map1ID = TaskAttemptID.forName("attempt_0_1_m_1_1");
    maps.add(map1ID);
    TaskAttemptID map2ID = TaskAttemptID.forName("attempt_0_1_m_2_1");
    maps.add(map2ID);
    when(ss.getMapsForHost(host)).thenReturn(maps);

    String encHash = "vFE234EIFCiBgYs2tCXY/SjT8Kg=";
    String replyHash = SecureShuffleUtils.generateHash(encHash.getBytes(), key);

    when(connection.getResponseCode()).thenReturn(200);
    when(connection.getHeaderField(SecureShuffleUtils.HTTP_HEADER_REPLY_URL_HASH))
      .thenReturn(replyHash);
    ByteArrayInputStream in = new ByteArrayInputStream(
        "\u00010 BOGUS DATA\nBOGUS DATA\nBOGUS DATA\n".getBytes());
    when(connection.getInputStream()).thenReturn(in);

    underTest.copyFromHost(host);

    verify(connection)
      .addRequestProperty(SecureShuffleUtils.HTTP_HEADER_URL_HASH,
          encHash);

    verify(allErrs).increment(1);
    verify(ss).copyFailed(map1ID, host, true, false);
    verify(ss).copyFailed(map2ID, host, true, false);

    verify(ss).putBackKnownMapOutput(any(MapHost.class), eq(map1ID));
    verify(ss).putBackKnownMapOutput(any(MapHost.class), eq(map2ID));
  }

  @SuppressWarnings("unchecked")
  @Test
  public void testCopyFromHostWait() throws Exception {
    LOG.info("testCopyFromHostWait");
    JobConf job = new JobConf();
    TaskAttemptID id = TaskAttemptID.forName("attempt_0_1_r_1_1");
    ShuffleScheduler<Text, Text> ss = mock(ShuffleScheduler.class);
    MergeManager<Text, Text> mm = mock(MergeManager.class);
    Reporter r = mock(Reporter.class);
    ShuffleClientMetrics metrics = mock(ShuffleClientMetrics.class);
    ExceptionReporter except = mock(ExceptionReporter.class);
    SecretKey key = JobTokenSecretManager.createSecretKey(new byte[]{0,0,0,0});
    HttpURLConnection connection = mock(HttpURLConnection.class);

    Counters.Counter allErrs = mock(Counters.Counter.class);
    when(r.getCounter(anyString(), anyString()))
      .thenReturn(allErrs);

    Fetcher<Text,Text> underTest = new FakeFetcher<Text,Text>(job, id, ss, mm,
        r, metrics, except, key, connection);

    MapHost host = new MapHost("localhost", "http://localhost:8080/");

    ArrayList<TaskAttemptID> maps = new ArrayList<TaskAttemptID>(1);
    TaskAttemptID map1ID = TaskAttemptID.forName("attempt_0_1_m_1_1");
    maps.add(map1ID);
    TaskAttemptID map2ID = TaskAttemptID.forName("attempt_0_1_m_2_1");
    maps.add(map2ID);
    when(ss.getMapsForHost(host)).thenReturn(maps);

    String encHash = "vFE234EIFCiBgYs2tCXY/SjT8Kg=";
    String replyHash = SecureShuffleUtils.generateHash(encHash.getBytes(), key);

    when(connection.getResponseCode()).thenReturn(200);
    when(connection.getHeaderField(SecureShuffleUtils.HTTP_HEADER_REPLY_URL_HASH))
      .thenReturn(replyHash);
    ShuffleHeader header = new ShuffleHeader(map1ID.toString(), 10, 10, 1);
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    header.write(new DataOutputStream(bout));
    ByteArrayInputStream in = new ByteArrayInputStream(bout.toByteArray());
    when(connection.getInputStream()).thenReturn(in);
    //Defaults to WAIT, which is what we want to test
    MapOutput<Text,Text> mapOut = new MapOutput<Text, Text>(map1ID);
    when(mm.reserve(any(TaskAttemptID.class), anyLong(), anyInt()))
      .thenReturn(mapOut);

    underTest.copyFromHost(host);

    verify(connection)
      .addRequestProperty(SecureShuffleUtils.HTTP_HEADER_URL_HASH,
          encHash);
    verify(allErrs, never()).increment(1);
    verify(ss, never()).copyFailed(map1ID, host, true, false);
    verify(ss, never()).copyFailed(map2ID, host, true, false);

    verify(ss).putBackKnownMapOutput(any(MapHost.class), eq(map1ID));
    verify(ss).putBackKnownMapOutput(any(MapHost.class), eq(map2ID));
  }
  @SuppressWarnings("unchecked")
  @Test
  public void testCopyFromHostExtraBytes() throws Exception {
    LOG.info("testCopyFromHostWaitExtraBytes");
    JobConf job = new JobConf();
    TaskAttemptID id = TaskAttemptID.forName("attempt_0_1_r_1_1");
    ShuffleScheduler<Text, Text> ss = mock(ShuffleScheduler.class);
    MergeManager<Text, Text> mm = mock(MergeManager.class);
    Reporter r = mock(Reporter.class);
    ShuffleClientMetrics metrics = mock(ShuffleClientMetrics.class);
    ExceptionReporter except = mock(ExceptionReporter.class);
    SecretKey key = JobTokenSecretManager.createSecretKey(new byte[]{0,0,0,0});
    HttpURLConnection connection = mock(HttpURLConnection.class);

    Counters.Counter allErrs = mock(Counters.Counter.class);
    when(r.getCounter(anyString(), anyString()))
      .thenReturn(allErrs);

    Fetcher<Text,Text> underTest = new FakeFetcher<Text,Text>(job, id, ss, mm,
        r, metrics, except, key, connection);

    MapHost host = new MapHost("localhost", "http://localhost:8080/");

    ArrayList<TaskAttemptID> maps = new ArrayList<TaskAttemptID>(1);
    TaskAttemptID map1ID = TaskAttemptID.forName("attempt_0_1_m_1_1");
    maps.add(map1ID);
    TaskAttemptID map2ID = TaskAttemptID.forName("attempt_0_1_m_2_1");
    maps.add(map2ID);
    when(ss.getMapsForHost(host)).thenReturn(maps);

    String encHash = "vFE234EIFCiBgYs2tCXY/SjT8Kg=";
    String replyHash = SecureShuffleUtils.generateHash(encHash.getBytes(), key);

    when(connection.getResponseCode()).thenReturn(200);
    when(connection.getHeaderField(SecureShuffleUtils.HTTP_HEADER_REPLY_URL_HASH))
      .thenReturn(replyHash);
    ShuffleHeader header = new ShuffleHeader(map1ID.toString(), 14, 10, 1);

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(bout);
    IFileOutputStream ios = new IFileOutputStream(dos);
    header.write(dos);
    ios.write("MAPDATA123".getBytes());
    ios.finish();

    ShuffleHeader header2 = new ShuffleHeader(map2ID.toString(), 14, 10, 1);
    IFileOutputStream ios2 = new IFileOutputStream(dos);
    header2.write(dos);
    ios2.write("MAPDATA456".getBytes());
    ios2.finish();

    ByteArrayInputStream in = new ByteArrayInputStream(bout.toByteArray());
    when(connection.getInputStream()).thenReturn(in);
    // 8 < 10 therefore there appear to be extra bytes in the IFileInputStream
    MapOutput<Text,Text> mapOut = new MapOutput<Text, Text>(map1ID, mm, 8, true );
    MapOutput<Text,Text> mapOut2 = new MapOutput<Text, Text>(map2ID, mm, 10, true );

    when(mm.reserve(eq(map1ID), anyLong(), anyInt())).thenReturn(mapOut);
    when(mm.reserve(eq(map2ID), anyLong(), anyInt())).thenReturn(mapOut2);

    underTest.copyFromHost(host);

    verify(allErrs).increment(1);
    verify(ss).copyFailed(map1ID, host, true, false);
    verify(ss, never()).copyFailed(map2ID, host, true, false);

    verify(ss).putBackKnownMapOutput(any(MapHost.class), eq(map1ID));
    verify(ss).putBackKnownMapOutput(any(MapHost.class), eq(map2ID));
  }

}


text:
/**
 * Mnemonist DefaultWeakMap Unit Tests
 * ===================================
 */
var assert = require('assert'),
    DefaultWeakMap = require('../default-weak-map.js');

var FACTORY = function() {
  return [];
};

describe('DefaultWeakMap', function() {

  it('should throw if passed factory is not a function.', function() {

    assert.throws(function() {
      new DefaultWeakMap(null);
    }, /function/);
  });

  it('should be possible to set & get keys.', function() {
    var map = new DefaultWeakMap(FACTORY);
    const one = {}, two = {}, unknown = {};

    map.get(one).push(1);
    map.set(two, [2]);

    assert.deepStrictEqual(map.get(one), [1]);
    assert.deepStrictEqual(map.get(two), [2]);

    assert.deepStrictEqual(map.get(unknown), []);

    map.clear();

    assert.deepStrictEqual(map.get(one), []);
  });

  it('should be possible to delete keys.', function() {
    var map = new DefaultWeakMap(FACTORY);
    const one = {};

    map.set(one, 1);

    assert.strictEqual(map.has(one), true);
    assert.strictEqual(map.delete(one), true);
    assert.strictEqual(map.has(one), false);
    assert.strictEqual(map.delete(one), false);
  });

  it('should be possible to peek.', function() {
    var map = new DefaultWeakMap(FACTORY);
    const one = {}, two = {};

    map.get(one).push(1);

    assert.deepStrictEqual(map.peek(one), [1]);
    assert.strictEqual(map.peek(two), undefined);
    assert.strictEqual(map.has(two), false);
  });
});


text:
#include "maxAudioGraph.h"

int TTCLASSWRAPPERMAX_EXPORT main(void)
{
	MaxAudioGraphWrappedClassOptionsPtr	options = new MaxAudioGraphWrappedClassOptions;
	TTValue								value(0);

	TTAudioGraphInit();

	options->append(TT("nonadapting"), value); // don't change the number of out-channels in response to changes in the number of in-channels
	wrapAsMaxAudioGraph(TT("spat"), "jcom.spat≈", NULL, options);
	wrapAsMaxAudioGraph(TT("spat"), "spat≈", NULL, options);
	return 0;
}


text:
package org.apache.drill.exec.physical.rowSet;

import org.apache.drill.exec.physical.resultSet.model.ReaderIndex;
import org.apache.drill.exec.record.selection.SelectionVector2;

/**
 * Reader index that points to each row indirectly through the
 * selection vector. The {@link #offset()} method points to the
 * actual data row, while the {@link #logicalIndex()} method gives
 * the position relative to the indirection vector. That is,
 * the position increases monotonically, but the index jumps
 * around as specified by the indirection vector.
 */

public class IndirectRowIndex extends ReaderIndex {

  private final SelectionVector2 sv2;

  public IndirectRowIndex(SelectionVector2 sv2) {
    super(sv2.getCount());
    this.sv2 = sv2;
  }

  @Override
  public int offset() { return sv2.getIndex(position); }

  @Override
  public int hyperVectorIndex() { return 0; }
}


text:
<?php

declare(strict_types=1);

namespace Sylius\Component\Inventory\Model;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
interface StockableInterface
{
    /**
     * @return string
     */
    public function getInventoryName();

    /**
     * @return bool
     */
    public function isInStock();

    /**
     * @return int
     */
    public function getOnHold();

    /**
     * @param int $onHold
     */
    public function setOnHold($onHold);

    /**
     * @return int
     */
    public function getOnHand();

    /**
     * @param int $onHand
     */
    public function setOnHand($onHand);

    /**
     * @return bool
     */
    public function isTracked();

    /**
     * @param bool $tracked
     */
    public function setTracked($tracked);
}


text:
Assembly.registerFeature('Middleware', function (
        framework, frameworkPrivate, featureConfig) {

    this.registerInitializationStep('Add_Middleware_Engine', function (
            app, appPrivate, appConfig, proceed, terminate) {

        if (!('middleware' in appConfig) ||
                !(appConfig.middleware instanceof Array)) {

            appConfig.middleware = [];
        };

        appPrivate.middlewareEngine = new MiddlewareEngine();

        proceed();

    });

    this.registerInitializationStep('Start_Middleware_Engine', function (
            app, appPrivate, appConfig, proceed, terminate) {

        this.dependsOnStep('Add_Middleware_Engine');

        appPrivate.middlewareEngine.start(app, appConfig.middleware);

        proceed();
    });
});


text:
package com.wix.reactnativenotifications.core.notificationdrawer;

import android.app.Activity;

public interface IPushNotificationsDrawer {
    void onAppInit();
    void onAppVisible();
    void onNewActivity(Activity activity);

    void onNotificationOpened();
    void onNotificationClearRequest(int id);
}


text:
package com.hostxin.android.download;

import android.content.Context;
import android.os.Environment;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;

import com.hostxin.android.util.Dbg;

import org.junit.Test;
import org.junit.runner.RunWith;

import static org.junit.Assert.*;

@RunWith(AndroidJUnit4.class)
public class DownloadManagerTest {

    private static final String TAG = "DownloadManagerTest";

    @Test
    public void testDownloadMaianger() throws Exception {
        // Context of the app under test.
        Context appContext = InstrumentationRegistry.getTargetContext();

        assertEquals("com.hostxin.android.download.test", appContext.getPackageName());

        //this always init in Application
        NativeDownloadManager.getInstence().init(Contants.FILE_PATH);

        //this always set in Activity or Fragment
        NativeDownloadManager.getInstence().addDownloadCallback(mDownloadWatcher);

        String downloadId = "";
        int downloadtype = 1;
        String downloadUrl = "";
        NativeDownloadManager.getInstence().addDownload(downloadId,downloadtype,downloadUrl);

        //you mast remove it when the Activity or Fragment is destory
        //NativeDownloadManager.getInstence().removeDownloadWatcher(mDownloadWatcher);
    }

    //we always change the ui when the downloadinfo is change;
    NativeDownloadManager.DownloadWatcher mDownloadWatcher = new NativeDownloadManager.DownloadWatcher() {
        @Override
        public void onPending(DownloadInfo downloadInfo) {
            Dbg.d(TAG,"onPending "+downloadInfo);
        }

        @Override
        public void onConnecting(DownloadInfo downloadInfo) {
            Dbg.d(TAG,"onConnecting "+downloadInfo);
        }

        @Override
        public void onStart(DownloadInfo downloadInfo) {
            Dbg.d(TAG,"onStart "+downloadInfo);
        }

        @Override
        public void onProcess(DownloadInfo downloadInfo) {
            Dbg.d(TAG,"onProcess "+downloadInfo);
        }

        @Override
        public void onStop(DownloadInfo downloadInfo) {
            Dbg.d(TAG,"onStop "+downloadInfo);
        }

        @Override
        public void onSuccess(DownloadInfo downloadInfo) {
            Dbg.d(TAG,"onSuccess "+downloadInfo);
        }

        @Override
        public void onError(DownloadInfo downloadInfo) {
            Dbg.d(TAG,"onError "+downloadInfo);
        }

        @Override
        public void onRemove(DownloadInfo downloadInfo) {
            Dbg.d(TAG,"onRemove "+downloadInfo);
        }
    };
}


text:
import Immutable from 'immutable'
import {CALL_API, GET, POST} from '../middleware/api'

const LOAD_REQUEST = 'USERS_LOAD_REQUEST'
const LOAD_SUCCESS = 'USERS_LOAD_SUCCESS'
const LOAD_FAILURE = 'USERS_LOAD_FAILURE'

const ADD_REQUEST = 'USERS_ADD_REQUEST'
const ADD_SUCCESS = 'USERS_ADD_SUCCESS'
const ADD_FAILURE = 'USERS_ADD_FAILURE'

const DELETE_REQUEST = 'USERS_DELETE_REQUEST'
const DELETE_SUCCESS = 'USERS_DELETE_SUCCESS'
const DELETE_FAILURE = 'USERS_DELETE_FAILURE'

const initialState = Immutable.Record(
  { fetching: false
  , fetchingError: null
  , data: null
  , adding: false
  , addingError: null
  , deleting: false
  , deletingError: null
  })

export default function reducer(state=new initialState(), action) {
  switch (action.type) {
    case LOAD_REQUEST:
      return state.merge(new initialState())
    case LOAD_SUCCESS:
      let data = Immutable.OrderedMap()
      action.data.forEach((item) => {
        data = data.set(item.id, Immutable.fromJS(item))
      })
      return state.merge(
        { fetching: false
        , data: data
        })
    case LOAD_FAILURE:
      return state.merge(
        { fetching: false
        , fetchingError: action.error
        })
    case ADD_REQUEST:
      return state.merge(
        { adding: true
        , addingError: null
        })
    case ADD_SUCCESS:
      return state.set('adding', false).setIn(['data', action.data.id],
        Immutable.fromJS(action.data))
    case ADD_FAILURE:
      return state.merge(
        { adding: false
        , addingError: action.error
        })
    case DELETE_REQUEST:
      return state.merge(
        { deleting: true
        , deletingError: null
        })
    case DELETE_SUCCESS:
      return state.set('deleting', false).removeIn(['data', action.id])
    case DELETE_FAILURE:
      return state.merge(
        { deleting: false
        , deletingError: action.error
        })
    default:
      return state
  }
}

function fetch() {
  return (
    { [CALL_API]:
      { method: GET
      , started: [LOAD_REQUEST]
      , success: [LOAD_SUCCESS]
      , failure: [LOAD_FAILURE]
      , endpoint: 'users/list'
      }
    })
}

export function loadUsers() {
  return (dispatch, getState) => {
    const fetching = getState().levels.fetching
    if (fetching) {
      return null
    }
    return dispatch(fetch())
  }
}

export function addUser(url, superuser) {
  return (
    { [CALL_API]:
      { method: POST
      , started: [ADD_REQUEST]
      , success: [ADD_SUCCESS]
      , failure: [ADD_FAILURE]
      , endpoint: `users/add?superuser=${superuser}`
      , data: url
      }
    })
}

export function deleteUser(id) {
  return (
    { [CALL_API]:
      { method: POST
      , started: [DELETE_REQUEST]
      , success: [DELETE_SUCCESS]
      , failure: [DELETE_FAILURE]
      , endpoint: `users/${id}/delete`
      }
    , id
    })
}


text:
import unittest

import gevent
from scales.thrift import Thrift

from integration.thrift.gen_py.example_rpc_service import (
  ExampleService,
  ttypes
)

class ThriftTestCase(unittest.TestCase):
  BUILDER = Thrift

  def setUp(self):
    self.client = self.BUILDER.NewClient(ExampleService.Iface, 'tcp://localhost:8080')

  def _send_request(self):
    try:
      ret = self.client.passMessage(ttypes.Message('hi!'))
      return ret.content == 'hi! server!'
    except:
      return False

  def test(self):
    ret = self._send_request()
    self.assertTrue(ret)

  def test_concurrency(self):
    num_threads = 3
    num_iterations = 1000
    def _test():
      for _ in xrange(num_iterations):
        self.assertTrue(self._send_request())

    greenlets = []
    for _ in xrange(num_threads):
      greenlets.append(gevent.spawn(_test))

    [g.join() for g in greenlets]

if __name__ == '__main__':
  unittest.main()


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE195_Signed_to_Unsigned_Conversion_Error__fgets_malloc_21.c
Label Definition File: CWE195_Signed_to_Unsigned_Conversion_Error.label.xml
Template File: sources-sink-21.tmpl.c
*/
/*
 * @description
 * CWE: 195 Signed to Unsigned Conversion Error
 * BadSource: fgets Read data from the console using fgets()
 * GoodSource: Positive integer
 * Sink: malloc
 *    BadSink : Allocate memory using malloc() with the size of data
 * Flow Variant: 21 Control flow: Flow controlled by value of a static global variable. All functions contained in one file.
 *
 * */

#include "std_testcase.h"

#define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2)

#ifndef OMITBAD

/* The static variable below is used to drive control flow in the source function */
static int badStatic = 0;

static int badSource(int data)
{
    if(badStatic)
    {
        {
            char inputBuffer[CHAR_ARRAY_SIZE] = "";
            /* POTENTIAL FLAW: Read data from the console using fgets() */
            if (fgets(inputBuffer, CHAR_ARRAY_SIZE, stdin) != NULL)
            {
                /* Convert to int */
                data = atoi(inputBuffer);
            }
            else
            {
                printLine("fgets() failed.");
            }
        }
    }
    return data;
}

void CWE195_Signed_to_Unsigned_Conversion_Error__fgets_malloc_21_bad()
{
    int data;
    /* Initialize data */
    data = -1;
    badStatic = 1; /* true */
    data = badSource(data);
    /* Assume we want to allocate a relatively small buffer */
    if (data < 100)
    {
        /* POTENTIAL FLAW: malloc() takes a size_t (unsigned int) as input and therefore if it is negative,
         * the conversion will cause malloc() to allocate a very large amount of data or fail */
        char * dataBuffer = (char *)malloc(data);
        if (dataBuffer == NULL) {exit(-1);}
        /* Do something with dataBuffer */
        memset(dataBuffer, 'A', data-1);
        dataBuffer[data-1] = '\0';
        printLine(dataBuffer);
        free(dataBuffer);
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* The static variables below are used to drive control flow in the source functions. */
static int goodG2B1Static = 0;
static int goodG2B2Static = 0;

/* goodG2B1() - use goodsource and badsink by setting the static variable to false instead of true */
static int goodG2B1Source(int data)
{
    if(goodG2B1Static)
    {
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
    }
    else
    {
        /* FIX: Use a positive integer less than &InitialDataSize&*/
        data = 100-1;
    }
    return data;
}

static void goodG2B1()
{
    int data;
    /* Initialize data */
    data = -1;
    goodG2B1Static = 0; /* false */
    data = goodG2B1Source(data);
    /* Assume we want to allocate a relatively small buffer */
    if (data < 100)
    {
        /* POTENTIAL FLAW: malloc() takes a size_t (unsigned int) as input and therefore if it is negative,
         * the conversion will cause malloc() to allocate a very large amount of data or fail */
        char * dataBuffer = (char *)malloc(data);
        if (dataBuffer == NULL) {exit(-1);}
        /* Do something with dataBuffer */
        memset(dataBuffer, 'A', data-1);
        dataBuffer[data-1] = '\0';
        printLine(dataBuffer);
        free(dataBuffer);
    }
}

/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if in the source function */
static int goodG2B2Source(int data)
{
    if(goodG2B2Static)
    {
        /* FIX: Use a positive integer less than &InitialDataSize&*/
        data = 100-1;
    }
    return data;
}

static void goodG2B2()
{
    int data;
    /* Initialize data */
    data = -1;
    goodG2B2Static = 1; /* true */
    data = goodG2B2Source(data);
    /* Assume we want to allocate a relatively small buffer */
    if (data < 100)
    {
        /* POTENTIAL FLAW: malloc() takes a size_t (unsigned int) as input and therefore if it is negative,
         * the conversion will cause malloc() to allocate a very large amount of data or fail */
        char * dataBuffer = (char *)malloc(data);
        if (dataBuffer == NULL) {exit(-1);}
        /* Do something with dataBuffer */
        memset(dataBuffer, 'A', data-1);
        dataBuffer[data-1] = '\0';
        printLine(dataBuffer);
        free(dataBuffer);
    }
}

void CWE195_Signed_to_Unsigned_Conversion_Error__fgets_malloc_21_good()
{
    goodG2B1();
    goodG2B2();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
 * its own for testing or for building a binary to use in testing binary
 * analysis tools. It is not used when compiling all the testcases as one
 * application, which is how source code analysis tools are tested.
 */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE195_Signed_to_Unsigned_Conversion_Error__fgets_malloc_21_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE195_Signed_to_Unsigned_Conversion_Error__fgets_malloc_21_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
package org.apache.ignite.internal.processors.cache.distributed;

/**
 *
 */
public class CacheLoadingConcurrentGridStartSelfTestAllowOverwrite extends CacheLoadingConcurrentGridStartSelfTest {
    /**
     * Default constructor.
     */
    public CacheLoadingConcurrentGridStartSelfTestAllowOverwrite() {
        allowOverwrite = true;
    }
}


text:
```yml
  ssc.views.factory:
    class:     SSC\Views\Factory
    parent:    projectstack.views.factory
    calls:
      - [inject, ["@markdown.parser"]]
```

```php

  protected function createView($fqn, $vars = array()) {
    if ($fqn === 'SSC\Views\RegistrationTeaser') {
      return new RegistrationTeaser($this->getCountdownTeaser(), $this->getRegistrationPlacesLeft(), $vars);
    } else {
      return parent::createView($fqn, $vars);
    }
  }

  protected function injectView(\Webforge\ProjectStack\Views\View $view) {
    if ($view instanceof MarkdownTransforming) {
      $view->setMarkdownParser($this->markdownParser);
    }

    if ($view instanceof NeedsPreparing) {
      $view->prepare();
    }

    return $view;
  }
}
```


text:
<?php

namespace Gmo\Common\Exception;

/**
 * Class ConfigException
 *
 * @since   1.5.0
 */
class ConfigException extends \Exception
{
}


text:
/**
 * Utility classes for Watcher.
 */
package org.apache.reef.io.watcher.util;


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.18052
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace CommonWell.Tools.Properties {

    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
    internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {

        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

        public static Settings Default {
            get {
                return defaultInstance;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("No Certificate")]
        public string CertificatePath {
            get {
                return ((string)(this["CertificatePath"]));
            }
            set {
                this["CertificatePath"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("")]
        public string Passphrase {
            get {
                return ((string)(this["Passphrase"]));
            }
            set {
                this["Passphrase"] = value;
            }
        }
    }
}


text:
package org.fusesource.fabric.web;

import static org.fusesource.fabric.zookeeper.utils.ZooKeeperUtils.delete;
import static org.fusesource.fabric.zookeeper.utils.ZooKeeperUtils.setData;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.fusesource.fabric.api.Container;
import org.fusesource.fabric.api.FabricService;
import org.fusesource.fabric.api.jcip.GuardedBy;
import org.fusesource.fabric.api.jcip.ThreadSafe;
import org.fusesource.fabric.api.scr.AbstractComponent;
import org.fusesource.fabric.api.scr.ValidatingReference;
import org.fusesource.fabric.zookeeper.ZkPath;
import org.ops4j.pax.web.service.spi.ServletEvent;
import org.ops4j.pax.web.service.spi.ServletListener;
import org.ops4j.pax.web.service.spi.WebEvent;
import org.ops4j.pax.web.service.spi.WebListener;
import org.osgi.framework.Bundle;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ThreadSafe
@Component(name = "org.fusesource.fabric.web", description = "Fabric Web Registration Handler", immediate = true)
@Service({ WebListener.class, ServletListener.class, ConnectionStateListener.class })
public final class FabricWebRegistrationHandler extends AbstractComponent implements WebListener, ServletListener, ConnectionStateListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(FabricWebRegistrationHandler.class);

    @Reference(referenceInterface = FabricService.class)
    private final ValidatingReference<FabricService> fabricService = new ValidatingReference<FabricService>();
    @Reference(referenceInterface = CuratorFramework.class)
    private final ValidatingReference<CuratorFramework> curator = new ValidatingReference<CuratorFramework>();

    @GuardedBy("ConcurrentMap") private final ConcurrentMap<Bundle, WebEvent> webEvents = new ConcurrentHashMap<Bundle, WebEvent>();
    @GuardedBy("ConcurrentMap") private final ConcurrentMap<Bundle, Map<String, ServletEvent>> servletEvents = new ConcurrentHashMap<Bundle, Map<String, ServletEvent>>();

    @Activate
    void activate() {
        activateComponent();
    }

    @Deactivate
    void deactivate() {
        deactivateComponent();
    }

    @Override
    public void stateChanged(CuratorFramework client, ConnectionState newState) {
        if (isValid()) {
            switch (newState) {
            case CONNECTED:
            case RECONNECTED:
                replay();
            }
        }
    }

    @Override
    public void webEvent(WebEvent webEvent) {
        if (isValid()) {
            webEvents.put(webEvent.getBundle(), webEvent);
            switch (webEvent.getType()) {
            case WebEvent.DEPLOYING:
                break;
            case WebEvent.DEPLOYED:
                registerWebapp(fabricService.get().getCurrentContainer(), webEvent);
                break;
            default:
                unRegisterWebapp(fabricService.get().getCurrentContainer(), webEvent);
            }
        }
    }

    @Override
    public void servletEvent(ServletEvent servletEvent) {
        if (isValid()) {
            WebEvent webEvent = webEvents.get(servletEvent.getBundle());
            if (webEvent != null || servletEvent.getAlias() == null) {
                // this servlet is part of a web application, ignore it
                return;
            }
            Map<String, ServletEvent> events;
            synchronized (servletEvents) {
                events = servletEvents.get(servletEvent.getBundle());
                if (events == null) {
                    events = new HashMap<String, ServletEvent>();
                    servletEvents.put(servletEvent.getBundle(), events);
                }
            }
            events.put(servletEvent.getAlias(), servletEvent);
            if (curator.get().getZookeeperClient().isConnected()) {
                switch (servletEvent.getType()) {
                case ServletEvent.DEPLOYING:
                    break;
                case ServletEvent.DEPLOYED:
                    registerServlet(fabricService.get().getCurrentContainer(), servletEvent);
                    break;
                default:
                    unregisterServlet(fabricService.get().getCurrentContainer(), servletEvent);
                    break;
                }
            }
        }
    }

    /**
     * Replays again all events.
     */
    private void replay() {
        for (Map.Entry<Bundle, WebEvent> entry : webEvents.entrySet()) {
            webEvent(entry.getValue());
        }
        for (Map.Entry<Bundle, Map<String, ServletEvent>> entry : servletEvents.entrySet()) {
            Map<String, ServletEvent> servletEventMap = entry.getValue();
            for (Map.Entry<String, ServletEvent> sentry : servletEventMap.entrySet()) {
                servletEvent(sentry.getValue());
            }
        }
    }

    private void registerServlet(Container container, ServletEvent servletEvent) {
        String id = container.getId();
        String url = "${zk:" + id + "/http}" + servletEvent.getAlias();

        String name = servletEvent.getBundle().getSymbolicName();
        setJolokiaUrl(container, url, name);

        String json = "{\"id\":\"" + id + "\", \"services\":[\"" + url + "\"],\"container\":\"" + id + "\"}";
        try {
            //We don't want to register / it's fabric-redirect for hawtio
            if (!servletEvent.getAlias().equals("/")) {
                String path = createServletPath(servletEvent, id);
                setData(curator.get(), path, json, CreateMode.EPHEMERAL);
            }
        } catch (Exception e) {
            LOGGER.error("Failed to register servlet {}.", servletEvent.getAlias(), e);
        }
    }

    private void unregisterServlet(Container container, ServletEvent servletEvent) {
        try {
            String name = servletEvent.getBundle().getSymbolicName();
            clearJolokiaUrl(container, name);

            String id = container.getId();
            //We don't want to register / it's fabric-redirect for hawtio
            if (!servletEvent.getAlias().equals("/")) {
                String path = createServletPath(servletEvent, id);
                delete(curator.get(), path);
            }
        } catch (KeeperException.NoNodeException e) {
            // If the node does not exists, ignore the exception
        } catch (Exception e) {
            LOGGER.error("Failed to unregister servlet {}.", servletEvent.getAlias(), e);
        }
    }

    /**
     * Registers a webapp to the registry.
     */
    private void registerWebapp(Container container, WebEvent webEvent) {
        String id = container.getId();
        String url = "${zk:" + id + "/http}" + webEvent.getContextPath();

        String name = webEvent.getBundle().getSymbolicName();
        setJolokiaUrl(container, url, name);

        String json = "{\"id\":\"" + id + "\", \"services\":[\"" + url + "\"],\"container\":\"" + id + "\"}";
        try {
            setData(curator.get(), ZkPath.WEBAPPS_CONTAINER.getPath(name, webEvent.getBundle().getVersion().toString(), id), json, CreateMode.EPHEMERAL);
        } catch (Exception e) {
            LOGGER.error("Failed to register webapp {}.", webEvent.getContextPath(), e);
        }
    }

    /**
     * Unregister a webapp from the registry.
     * @param container
     * @param webEvent
     */
    private void unRegisterWebapp(Container container, WebEvent webEvent) {
        try {
            String name = webEvent.getBundle().getSymbolicName();
            clearJolokiaUrl(container, name);

            delete(curator.get(), ZkPath.WEBAPPS_CONTAINER.getPath(name, webEvent.getBundle().getVersion().toString(), container.getId()));
        } catch (KeeperException.NoNodeException e) {
            // If the node does not exists, ignore the exception
        } catch (Exception e) {
            LOGGER.error("Failed to unregister webapp {}.", webEvent.getContextPath(), e);
        }
    }

    private String createServletPath(ServletEvent servletEvent, String id) {
        StringBuilder path = new StringBuilder();
        path.append("/fabric/registry/clusters/servlets/").append(servletEvent.getBundle().getSymbolicName()).append("/")
                .append(servletEvent.getBundle().getVersion().toString()).append(servletEvent.getAlias()).append("/").append(id);
        return path.toString();
    }

    private void setJolokiaUrl(Container container, String url, String symbolicName) {
        if (symbolicName.contains("jolokia")) {
            container.setJolokiaUrl(url);
            System.setProperty("jolokia.agent", url);
        }
    }

    private void clearJolokiaUrl(Container container, String symbolicName) {
        if (symbolicName.contains("jolokia")) {
            container.setJolokiaUrl(null);
            System.clearProperty("jolokia.agent");
        }
    }

    void bindFabricService(FabricService fabricService) {
        this.fabricService.bind(fabricService);
    }

    void unbindFabricService(FabricService fabricService) {
        this.fabricService.unbind(fabricService);
    }

    void bindCurator(CuratorFramework curator) {
        this.curator.bind(curator);
    }

    void unbindCurator(CuratorFramework curator) {
        this.curator.unbind(curator);
    }
}