text:
using System.Collections;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;

namespace EasyAssertions;

///
/// Collection-related assertions.
///
public static class CollectionAssertions
{
    const string UnorderedCollectionComparisonError = "Do not compare unordered collections with ordered sequences. Use an assertion that does not test ordering instead.";
    const string AssertionReturnsBooleanError = "Assertion callbacks should use assertions rather than returning booleans.";

    /// Disallowed comparison.
    [Obsolete(UnorderedCollectionComparisonError, true)]
    public static void ShouldMatch<TActualKey, TActualValue, TExpectedKey, TExpectedValue>(this IDictionary<TActualKey, TActualValue>? actual, IEnumerable<KeyValuePair<TExpectedKey, TExpectedValue>>? expected, string? message = null) { }
    /// Disallowed comparison.
    [Obsolete(UnorderedCollectionComparisonError, true)]
    public static void ShouldMatch<TActualKey, TActualValue, TExpectedKey, TExpectedValue>(this IEnumerable<KeyValuePair<TActualKey, TActualValue>>? actual, IDictionary<TExpectedKey, TExpectedValue>? expected, string? message = null) { }
    /// Disallowed comparison.
    [Obsolete(UnorderedCollectionComparisonError, true)]
    public static void ShouldMatch<TActual, TExpected>(this ISet<TActual>? actual, IEnumerable<TExpected>? expected, string? message = null) { }
    /// Disallowed comparison.
    [Obsolete(UnorderedCollectionComparisonError, true)]
    public static void ShouldMatch<TActual, TExpected>(this IEnumerable<TActual>? actual, ISet<TExpected>? expected, string? message = null) { }
    /// Disallowed comparison.
    [Obsolete(UnorderedCollectionComparisonError, true)]
    public static void ShouldMatchReferences<TActualKey, TActualValue, TExpectedKey, TExpectedValue>(this IDictionary<TActualKey, TActualValue>? actual, IEnumerable<KeyValuePair<TExpectedKey, TExpectedValue>>? expected, string? message = null) { }
    /// Disallowed comparison.
    [Obsolete(UnorderedCollectionComparisonError, true)]
    public static void ShouldMatchReferences<TActualKey, TActualValue, TExpectedKey, TExpectedValue>(this IEnumerable<KeyValuePair<TActualKey, TActualValue>>? actual, IDictionary<TExpectedKey, TExpectedValue>? expected, string? message = null) { }
    /// Disallowed comparison.
    [Obsolete(UnorderedCollectionComparisonError, true)]
    public static void ShouldMatchReferences<TActual, TExpected>(this ISet<TActual>? actual, IEnumerable<TExpected>? expected, string? message = null) { }
    /// Disallowed comparison.
    [Obsolete(UnorderedCollectionComparisonError, true)]
    public static void ShouldMatchReferences<TActual, TExpected>(this IEnumerable<TActual>? actual, ISet<TExpected>? expected, string? message = null) { }
    /// Disallowed comparison.
    [Obsolete(AssertionReturnsBooleanError, true)]
    public static void ItemsSatisfy<TItem>(this IEnumerable<TItem>? actual, params Func<TItem, bool>[] assertions) { }
    /// Disallowed comparison.
    [Obsolete(AssertionReturnsBooleanError, true)]
    public static void AllItemsSatisfy<TItem>(this IEnumerable<TItem>? actual, Func<TItem, bool> assertion) { }

    ///
    /// Asserts that a sequence has no elements in it.
    ///
    public static Actual<TActual> ShouldBeEmpty<TActual>([NotNull] this TActual? actual, string? message = null)
        where TActual : IEnumerable
    {
        return actual.RegisterNotNullAssertion(c =>
            {
                actual.ShouldBeA<TActual>(message);

                using var bufferedActual = actual.Buffer();

                if (!c.Test.IsEmpty(bufferedActual))
                    throw c.StandardError.NotEmpty(bufferedActual, message);
            });
    }

    ///
    /// Asserts that a sequence contains at least one element.
    ///
    public static Actual<TActual> ShouldNotBeEmpty<TActual>([NotNull] this TActual? actual, string? message = null)
        where TActual : IEnumerable
    {
        return actual.RegisterNotNullAssertion(c =>
            {
                actual.ShouldBeA<TActual>(message);
                if (c.Test.IsEmpty(actual))
                    throw c.StandardError.IsEmpty(message);
            });
    }

    ///
    /// Asserts that a sequence contains exactly one element.
    ///
    public static Actual<TActual> ShouldBeSingular<TActual>([NotNull] this TActual? actual, string? message = null)
        where TActual : IEnumerable
    {
        return actual.RegisterNotNullAssertion(c => AssertLength(actual, 1, message, c));
    }

    ///
    /// Asserts that a sequence contains exactly one element of the specified type.
    ///
    public static Actual<TExpected> ShouldBeASingular<TExpected>([NotNull] this IEnumerable? actual, string? message = null)
        where TExpected : notnull
    {
        return actual.RegisterNotNullAssertion(c =>
            {
                actual.ShouldBeA<IEnumerable>(message);
                using var bufferedActual = actual.Buffer();
                bufferedActual.ShouldBeSingular(message);
                ObjectAssertions.AssertType<TExpected>(bufferedActual.Single(), message, c);
                return new Actual<TExpected>((TExpected)bufferedActual.Single());
            });
    }

    ///
    /// Assert that all items in a sequence are assignable to the specified type.
    ///
    public static Actual<IEnumerable<TExpected>> ShouldAllBeA<TExpected>([NotNull] this IEnumerable? actual, string? message = null)
        where TExpected : notnull
    {
        return actual.RegisterNotNullAssertion(c =>
            {
                actual.ShouldBeA<IEnumerable>(message);

                using var bufferedActual = actual.Buffer();
                var i = 0;
                foreach (var item in bufferedActual)
                    actual.RegisterAssertion(c2 => item.ShouldBeA<TExpected>(message), $"[{i++}]");

                return new Actual<IEnumerable<TExpected>>(actual.Cast<TExpected>());
            });
    }

    ///
    /// Asserts that a sequence contains a specific number of elements.
    ///
    public static Actual<TActual> ShouldBeLength<TActual>([NotNull] this TActual? actual, int expectedLength, string? message = null)
        where TActual : IEnumerable
    {
        return actual.RegisterNotNullAssertion(c => AssertLength(actual, expectedLength, message, c));
    }

    static void AssertLength<TActual>([NotNull] TActual? actual, int expectedLength, string? message, IAssertionContext c) where TActual : IEnumerable
    {
        actual.ShouldBeA<TActual>(message);

        using var bufferedActual = actual.Buffer();

        if (bufferedActual.Count != expectedLength)
            throw c.StandardError.LengthMismatch(expectedLength, bufferedActual, message);
    }

    ///
    /// Asserts that two sequences contain the same items in the same order.
    /// <see cref="IEnumerable"/> items are compared recursively.
    /// Non-<c>IEnumerable</c> items are compared using the default equality comparer.
    ///
    public static Actual<IEnumerable<TActual>> ShouldMatch<TActual, TExpected>([NotNull] this IEnumerable<TActual>? actual, IEnumerable<TExpected> expected, string? message = null)
        where TExpected : TActual
    {
        if (expected == null) throw new ArgumentNullException(nameof(expected));

        return actual.RegisterNotNullAssertion(c => AssertMatch(actual, expected, c.Test.ObjectsMatch, message, c));
    }

    ///
    /// Asserts that two sequences contain the same <see cref="float"/> values (within a specified tolerance), in the same order.
    ///
    public static Actual<IEnumerable<float>> ShouldMatch([NotNull] this IEnumerable<float>? actual, IEnumerable<float> expected, double tolerance, string? message = null)
    {
        if (expected == null) throw new ArgumentNullException(nameof(expected));

        return actual.RegisterNotNullAssertion(c => AssertMatch(actual, expected, (a, e) => c.Test.AreWithinTolerance(a, e, tolerance), message, c));
    }

    ///
    /// Asserts that two sequences contain the same <see cref="double"/> values (within a specified tolerance), in the same order.
    ///
    public static Actual<IEnumerable<double>> ShouldMatch([NotNull] this IEnumerable<double>? actual, IEnumerable<double> expected, double tolerance, string? message = null)
    {
        if (expected == null) throw new ArgumentNullException(nameof(expected));

        return actual.RegisterNotNullAssertion(c => AssertMatch(actual, expected, (a, e) => c.Test.AreWithinTolerance(a, e, tolerance), message, c));
    }

    ///
    /// Asserts that two sequences contain the same items in the same order, using a custom equality function.
    ///
    public static Actual<IEnumerable<TActual>> ShouldMatch<TActual, TExpected>([NotNull] this IEnumerable<TActual>? actual, IEnumerable<TExpected> expected, Func<TActual, TExpected, bool> predicate, string? message = null)
    {
        if (expected == null) throw new ArgumentNullException(nameof(expected));
        if (predicate == null) throw new ArgumentNullException(nameof(predicate));

        return actual.RegisterNotNullAssertion(c => AssertMatch(actual, expected, predicate, message, c));
    }

    static void AssertMatch<TActual, TExpected>([NotNull] IEnumerable<TActual>? actual, IEnumerable<TExpected> expected, Func<TActual, TExpected, bool> predicate, string? message, IAssertionContext c)
    {
        actual.ShouldBeA<IEnumerable<TActual>>(message);

        using var bufferedActual = actual.Buffer();
        using var bufferedExpected = expected.Buffer();

        if (!c.Test.CollectionsMatch(bufferedActual, bufferedExpected, (a, e) => predicate((TActual)a, (TExpected)e)))
            throw c.StandardError.DoNotMatch(bufferedExpected, bufferedActual, predicate, message);
    }

    ///
    /// Asserts that two sequences contain the same items in the same order, using a custom equality function.
    ///
    public static Actual<IEnumerable<TActual>> ShouldMatch<TActual, TExpected>([NotNull] this IEnumerable<TActual>? actual, IEnumerable<TExpected> expected, Action<TActual, TExpected> assertion)
    {
        if (expected == null) throw new ArgumentNullException(nameof(expected));
        if (assertion == null) throw new ArgumentNullException(nameof(assertion));

        return actual.RegisterNotNullAssertion(c =>
            {
                actual.ShouldBeA<IEnumerable<TActual>>();

                using var bufferedActual = actual.Buffer();
                using var bufferedExpected = expected.Buffer();

                if (bufferedActual.Count != bufferedExpected.Count)
                    throw c.StandardError.LengthMismatch(bufferedExpected.Count, bufferedActual);

                for (var i = 0; i < bufferedExpected.Count; i++)
                    c.Call(() => assertion(bufferedActual[i], bufferedExpected[i]), $"[{i}]", $"[{i}]");
            });
    }

    ///
    /// Asserts that two sequences do not contain the same items in the same order.
    /// <see cref="IEnumerable"/> items are compared recursively.
    /// Non-<c>IEnumerable</c> items are compared using the default equality comparer.
    ///
    public static Actual<IEnumerable<TActual>> ShouldNotMatch<TActual, TExpected>([NotNull] this IEnumerable<TActual>? actual, IEnumerable<TExpected> notExpected, string? message = null)
        where TExpected : TActual
    {
        if (notExpected == null) throw new ArgumentNullException(nameof(notExpected));

        return actual.RegisterNotNullAssertion(c => AssertNotMatch(actual, notExpected, c.Test.ObjectsMatch, message, c));
    }

    ///
    /// Asserts that two sequences do not contain the same <see cref="float"/> values (within a specified tolerance), in the same order.
    ///
    public static Actual<IEnumerable<float>> ShouldNotMatch([NotNull] this IEnumerable<float>? actual, IEnumerable<float> notExpected, double tolerance, string? message = null)
    {
        if (notExpected == null) throw new ArgumentNullException(nameof(notExpected));

        return actual.RegisterNotNullAssertion(c => AssertNotMatch(actual, notExpected, (a, e) => c.Test.AreWithinTolerance(a, e, tolerance), message, c));
    }

    ///
    /// Asserts that two sequences do not contain the same <see cref="double"/> values (within a specified tolerance), in the same order.
    ///
    public static Actual<IEnumerable<double>> ShouldNotMatch([NotNull] this IEnumerable<double>? actual, IEnumerable<double> notExpected, double tolerance, string? message = null)
    {
        if (notExpected == null) throw new ArgumentNullException(nameof(notExpected));

        return actual.RegisterNotNullAssertion(c => AssertNotMatch(actual, notExpected, (a, e) => c.Test.AreWithinTolerance(a, e, tolerance), message, c));
    }

    ///
    /// Asserts that two sequences do not contain the same items in the same order, using a custom equality function.
    ///
    public static Actual<IEnumerable<TActual>> ShouldNotMatch<TActual, TExpected>([NotNull] this IEnumerable<TActual>? actual, IEnumerable<TExpected> notExpected, Func<TActual, TExpected, bool> predicate, string? message = null)
    {
        if (notExpected == null) throw new ArgumentNullException(nameof(notExpected));
        if (predicate == null) throw new ArgumentNullException(nameof(predicate));

        return actual.RegisterNotNullAssertion(c => AssertNotMatch(actual, notExpected, predicate, message, c));
    }

    static void AssertNotMatch<TActual, TExpected>([NotNull] IEnumerable<TActual>? actual, IEnumerable<TExpected> notExpected, Func<TActual, TExpected, bool> predicate, string? message, IAssertionContext c)
    {
        actual.ShouldBeA<IEnumerable<TActual>>(message);

        using var bufferedActual = actual.Buffer();
        using var bufferedExpected = notExpected.Buffer();

        if (c.Test.CollectionsMatch(bufferedActual, bufferedExpected, (a, e) => predicate((TActual)a, (TExpected)e)))
            throw c.StandardError.Matches(bufferedExpected, bufferedActual, message);
    }

    ///
    /// Asserts that a sequence starts with another sub-sequence, using the default equality comparer.
    ///
    public static Actual<IEnumerable<TActual>> ShouldStartWith<TActual, TExpected>([NotNull] this IEnumerable<TActual>? actual, IEnumerable<TExpected> expectedStart, string? message = null)
        where TExpected : TActual
    {
        if (expectedStart == null) throw new ArgumentNullException(nameof(expectedStart));

        return actual.RegisterNotNullAssertion(c => AssertStartsWith(actual, expectedStart, c.Test.ObjectsAreEqual, message, c));
    }

    ///
    /// Asserts that a sequence starts with another sub-sequence, using a custom equality function.
    ///
    public static Actual<IEnumerable<TActual>> ShouldStartWith<TActual, TExpected>([NotNull] this IEnumerable<TActual>? actual, IEnumerable<TExpected> expectedStart, Func<TActual, TExpected, bool> predicate, string? message = null)
    {
        if (expectedStart == null) throw new ArgumentNullException(nameof(expectedStart));
        if (predicate == null) throw new ArgumentNullException(nameof(predicate));

        return actual.RegisterNotNullAssertion(c => AssertStartsWith(actual, expectedStart, predicate, message, c));
    }

    static void AssertStartsWith<TActual, TExpected>([NotNull] IEnumerable<TActual>? actual, IEnumerable<TExpected> expectedStart, Func<TActual, TExpected, bool> predicate, string? message, IAssertionContext c)
    {
        actual.ShouldBeA<IEnumerable<TActual>>(message);

        using var bufferedActual = actual.Buffer();
        using var bufferedExpected = expectedStart.Buffer();

        if (!c.Test.CollectionStartsWith(bufferedActual, bufferedExpected, (a, e) => predicate((TActual)a, (TExpected)e)))
            throw c.StandardError.DoesNotStartWith(bufferedExpected, bufferedActual, predicate, message);
    }

    ///
    /// Asserts that a sequence ends with another sub-sequence, using the default equality comparer.
    ///
    public static Actual<IEnumerable<TActual>> ShouldEndWith<TActual, TExpected>([NotNull] this IEnumerable<TActual>? actual, IEnumerable<TExpected> expectedEnd, string? message = null)
        where TExpected : TActual
    {
        if (expectedEnd == null) throw new ArgumentNullException(nameof(expectedEnd));

        return actual.RegisterNotNullAssertion(c => AssertEndsWith(actual, expectedEnd, c.Test.ObjectsAreEqual, message, c));
    }

    ///
    /// Asserts that a sequence ends with another sub-sequence, using a custom equality function.
    ///
    public static Actual<IEnumerable<TActual>> ShouldEndWith<TActual, TExpected>([NotNull] this IEnumerable<TActual>? actual, IEnumerable<TExpected> expectedEnd, Func<TActual, TExpected, bool> predicate, string? message = null)
    {
        if (expectedEnd == null) throw new ArgumentNullException(nameof(expectedEnd));
        if (predicate == null) throw new ArgumentNullException(nameof(predicate));

        return actual.RegisterNotNullAssertion(c => AssertEndsWith(actual, expectedEnd, predicate, message, c));
    }

    static void AssertEndsWith<TActual, TExpected>([NotNull] IEnumerable<TActual>? actual, IEnumerable<TExpected> expectedEnd, Func<TActual, TExpected, bool> predicate, string? message, IAssertionContext c)
    {
        actual.ShouldBeA<IEnumerable<TActual>>(message);

        using var bufferedActual = actual.Buffer();
        using var bufferedExpected = expectedEnd.Buffer();

        if (!c.Test.CollectionEndsWith(bufferedActual, bufferedExpected, (a, e) => predicate((TActual)a, (TExpected)e)))
            throw c.StandardError.DoesNotEndWith(bufferedExpected, bufferedActual, predicate, message);
    }

    ///
    /// Asserts that a sequence contains a specified element, using the default equality comparer.
    ///
    public static Actual<IEnumerable<TActual>> ShouldContain<TActual, TExpected>([NotNull] this IEnumerable<TActual>? actual, TExpected expected, string? message = null)
        where TExpected : TActual
    {
        return actual.RegisterNotNullAssertion(c => AssertContains(actual, expected, c.Test.ObjectsAreEqual, message, c));
    }

    ///
    /// Asserts that a sequence contains a specified element, using a custom equality function.
    ///
    public static Actual<IEnumerable<TActual>> ShouldContain<TActual, TExpected>([NotNull] this IEnumerable<TActual>? actual, TExpected expected, Func<TActual, TExpected, bool> predicate, string? message = null)
    {
        if (predicate == null) throw new ArgumentNullException(nameof(predicate));

        return actual.RegisterNotNullAssertion(c => AssertContains(actual, expected, predicate, message, c));
    }

    static void AssertContains<TActual, TExpected>([NotNull] IEnumerable<TActual>? actual, TExpected expected, Func<TActual, TExpected, bool> predicate, string? message, IAssertionContext c)
    {
        actual.ShouldBeA<IEnumerable<TActual>>(message);

        using var bufferedActual = actual.Buffer();

        if (!c.Test.ContainsAllItems(bufferedActual, new[] { expected }, predicate))
            throw c.StandardError.DoesNotContain(expected, bufferedActual, message: message);
    }

    ///
    /// Asserts that a sequence contains all specified elements, in any order, using the default equality comparer.
    /// If the expected sequence has duplicates, the actual sequence must have at least as many.
    ///
    public static Actual<IEnumerable<TActual>> ShouldContainItems<TActual, TExpected>([NotNull] this IEnumerable<TActual>? actual, IEnumerable<TExpected> expected, string? message = null)
        where TExpected : TActual
    {
        if (expected == null) throw new ArgumentNullException(nameof(expected));

        return actual.RegisterNotNullAssertion(c =>
            {
                actual.ShouldBeA<IEnumerable<TActual>>(message);

                using var bufferedActual = actual.Buffer();
                using var bufferedExpected = expected.Buffer();

                if (!c.Test.ContainsAllItems(bufferedActual, bufferedExpected, c.Test.ObjectsAreEqual))
                    throw c.StandardError.DoesNotContainItems(bufferedExpected, bufferedActual, c.Test.ObjectsAreEqual, message);
            });
    }

    ///
    /// Asserts that a sequence contains all specified elements, in any order, using a custom equality function.
    /// If the expected sequence has duplicates, the actual sequence must have at least as many.
    ///
    public static Actual<IEnumerable<TActual>> ShouldContainItems<TActual, TExpected>([NotNull] this IEnumerable<TActual>? actual, IEnumerable<TExpected> expected, Func<TActual, TExpected, bool> predicate, string? message = null)
    {
        if (expected == null) throw new ArgumentNullException(nameof(expected));
        if (predicate == null) throw new ArgumentNullException(nameof(predicate));

        return actual.RegisterNotNullAssertion(c =>
            {
                actual.ShouldBeA<IEnumerable<TActual>>(message);

                using var bufferedActual = actual.Buffer();
                using var bufferedExpected = expected.Buffer();

                if (!c.Test.ContainsAllItems(bufferedActual, bufferedExpected, predicate))
                    throw c.StandardError.DoesNotContainItems(bufferedExpected, bufferedActual, predicate, message);
            });
    }

    ///
    /// Asserts that all elements in a sequence are contained within another sequence, in any order, using the default equality comparer.
    /// If the actual sequence has duplicates, the expected sequence must have at least as many.
    ///
    public static Actual<IEnumerable<TActual>> ItemsShouldBeIn<TActual, TExpected>([NotNull] this IEnumerable<TActual>? actual, IEnumerable<TExpected> expectedSuperset, string? message = null)
        where TExpected : TActual
    {
        if (expectedSuperset == null) throw new ArgumentNullException(nameof(expectedSuperset));

        return actual.RegisterNotNullAssertion(c =>
            {
                actual.ShouldBeA<IEnumerable<TActual>>(message);

                using var bufferedActual = actual.Buffer();
                using var bufferedExpected = expectedSuperset.Buffer();

                if (!c.Test.ContainsAllItems(bufferedExpected, bufferedActual, (e, a) => c.Test.ObjectsAreEqual(a, e)))
                    throw c.StandardError.ContainsExtraItem(bufferedExpected, bufferedActual, c.Test.ObjectsAreEqual, message);
            });
    }

    ///
    /// Asserts that all elements in a sequence are contained within another sequence, in any order, using a custom equality function.
    /// If the actual sequence has duplicates, the expected sequence must have at least as many.
    ///
    public static Actual<IEnumerable<TActual>> ItemsShouldBeIn<TActual, TExpected>([NotNull] this IEnumerable<TActual>? actual, IEnumerable<TExpected> expectedSuperset, Func<TActual, TExpected, bool> predicate, string? message = null)
    {
        if (expectedSuperset == null) throw new ArgumentNullException(nameof(expectedSuperset));
        if (predicate == null) throw new ArgumentNullException(nameof(predicate));

        return actual.RegisterNotNullAssertion(c =>
            {
                actual.ShouldBeA<IEnumerable<TActual>>(message);

                using var bufferedActual = actual.Buffer();
                using var bufferedExpected = expectedSuperset.Buffer();

                if (!c.Test.ContainsAllItems(bufferedExpected, bufferedActual, (e, a) => predicate(a, e)))
                    throw c.StandardError.ContainsExtraItem(bufferedExpected, bufferedActual, predicate, message);
            });
    }

    ///
    /// Asserts that a sequence does not contain a specified element, using the default equality comparer.
    ///
    public static Actual<IEnumerable<TActual>> ShouldNotContain<TActual, TExpected>([NotNull] this IEnumerable<TActual>? actual, TExpected expectedToNotContain, string? message = null)
        where TExpected : TActual
    {
        return actual.RegisterNotNullAssertion(c => AssertDoesNotContain(actual, expectedToNotContain, c.Test.ObjectsAreEqual, message, c));
    }

    ///
    /// Asserts that a sequence does not contain a specified element, using a custom equality function.
    ///
    public static Actual<IEnumerable<TActual>> ShouldNotContain<TActual, TExpected>([NotNull] this IEnumerable<TActual>? actual, TExpected expectedToNotContain, Func<TActual, TExpected, bool> predicate, string? message = null)
    {
        if (predicate == null) throw new ArgumentNullException(nameof(predicate));

        return actual.RegisterNotNullAssertion(c => AssertDoesNotContain(actual, expectedToNotContain, predicate, message, c));
    }

    static void AssertDoesNotContain<TActual, TExpected>([NotNull] IEnumerable<TActual>? actual, TExpected expectedToNotContain, Func<TActual, TExpected, bool> predicate, string? message, IAssertionContext c)
    {
        actual.ShouldBeA<IEnumerable<TActual>>(message);

        using var bufferedActual = actual.Buffer();

        if (c.Test.ContainsAllItems(bufferedActual, new[] { expectedToNotContain }, predicate))
            throw c.StandardError.Contains(expectedToNotContain, bufferedActual, message: message);
    }

    ///
    /// Asserts that a sequence does not contain any of the specified elements, using the default equality comparer.
    ///
    public static Actual<IEnumerable<TActual>> ShouldNotContainItems<TActual, TExpected>([NotNull] this IEnumerable<TActual>? actual, IEnumerable<TExpected> expectedToNotContain, string? message = null)
        where TExpected : TActual
    {
        if (expectedToNotContain == null) throw new ArgumentNullException(nameof(expectedToNotContain));

        return actual.RegisterNotNullAssertion(c =>
            {
                actual.ShouldBeA<IEnumerable<TActual>>(message);

                using var bufferedActual = actual.Buffer();
                using var bufferedExpected = expectedToNotContain.Buffer();

                if (c.Test.ContainsAny(bufferedActual, bufferedExpected))
                    throw c.StandardError.Contains(bufferedExpected, bufferedActual, message);
            });
    }

    ///
    /// Asserts that a sequence does not contain any of the specified elements, using a custom equality function.
    ///
    public static Actual<IEnumerable<TActual>> ShouldNotContainItems<TActual, TExpected>([NotNull] this IEnumerable<TActual>? actual, IEnumerable<TExpected> expectedToNotContain, Func<TActual, TExpected, bool> predicate, string? message = null)
    {
        if (expectedToNotContain == null) throw new ArgumentNullException(nameof(expectedToNotContain));
        if (predicate == null) throw new ArgumentNullException(nameof(predicate));

        return actual.RegisterNotNullAssertion(c =>
            {
                actual.ShouldBeA<IEnumerable<TActual>>(message);

                using var bufferedActual = actual.Buffer();
                using var bufferedExpected = expectedToNotContain.Buffer();

                if (c.Test.ContainsAny(bufferedActual, bufferedExpected, predicate))
                    throw c.StandardError.Contains(bufferedExpected, bufferedActual, message);
            });
    }

    ///
    /// Asserts thats a sequence only contains the specified elements, and nothing else, in any order, using the default equality comparer.
    /// If the expected sequence has duplicates, the actual sequence must have the same amount.
    ///
    public static Actual<IEnumerable<TActual>> ShouldOnlyContain<TActual, TExpected>([NotNull] this IEnumerable<TActual>? actual, IEnumerable<TExpected> expected, string? message = null)
        where TExpected : TActual
    {
        if (expected == null) throw new ArgumentNullException(nameof(expected));

        return actual.RegisterNotNullAssertion(c => AssertOnlyContains(actual, expected, c.Test.ObjectsAreEqual, message, c));
    }

    ///
    /// Asserts that a sequence only contains the specified elements, and nothing else, in any order, using a custom equality function.
    /// If the expected sequence has duplicates, the actual sequence must have the same amount.
    ///
    public static Actual<IEnumerable<TActual>> ShouldOnlyContain<TActual, TExpected>([NotNull] this IEnumerable<TActual>? actual, IEnumerable<TExpected> expected, Func<TActual, TExpected, bool> predicate, string? message = null)
    {
        if (expected == null) throw new ArgumentNullException(nameof(expected));
        if (predicate == null) throw new ArgumentNullException(nameof(predicate));

        return actual.RegisterNotNullAssertion(c => AssertOnlyContains(actual, expected, predicate, message, c));
    }

    static void AssertOnlyContains<TActual, TExpected>([NotNull] IEnumerable<TActual>? actual, IEnumerable<TExpected> expected, Func<TActual, TExpected, bool> predicate, string? message, IAssertionContext c)
    {
        actual.ShouldBeA<IEnumerable<TActual>>(message);

        using var bufferedActual = actual.Buffer();
        using var bufferedExpected = expected.Buffer();

        if (!c.Test.ContainsOnlyExpectedItems(bufferedActual, bufferedExpected, predicate))
            throw c.StandardError.DoesNotOnlyContain(bufferedExpected, bufferedActual, predicate, message);
    }

    ///
    /// Asserts that a sequence contains no duplicated elements, using the default equality comparer.
    ///
    public static Actual<IEnumerable<TActual>> ShouldBeDistinct<TActual>([NotNull] this IEnumerable<TActual>? actual, string? message = null)
    {
        return actual.RegisterNotNullAssertion(c => AssertDistinct(actual, c.Test.ObjectsAreEqual, message, c));
    }

    ///
    /// Asserts that a sequence contains no duplicated elements, using a custom equality function.
    ///
    public static Actual<IEnumerable<TActual>> ShouldBeDistinct<TActual>([NotNull] this IEnumerable<TActual>? actual, Func<TActual, TActual, bool> predicate, string? message = null)
    {
        return actual.RegisterNotNullAssertion(c => AssertDistinct(actual, predicate, message, c));
    }

    static void AssertDistinct<TActual>([NotNull] IEnumerable<TActual>? actual, Func<TActual, TActual, bool> predicate, string? message, IAssertionContext c)
    {
        actual.ShouldBeA<IEnumerable<TActual>>(message);

        using var bufferedActual = actual.Buffer();

        if (c.Test.ContainsDuplicate(bufferedActual, predicate))
            throw c.StandardError.ContainsDuplicate(bufferedActual, message);
    }

    ///
    /// Asserts that two sequences contain the same object instances in the same order.
    ///
    public static Actual<IEnumerable<TActual>> ShouldMatchReferences<TActual, TExpected>([NotNull] this IEnumerable<TActual>? actual, IEnumerable<TExpected> expected, string? message = null)
        where TExpected : TActual
    {
        if (expected == null) throw new ArgumentNullException(nameof(expected));

        return actual.RegisterNotNullAssertion(c =>
            {
                actual.ShouldBeA<IEnumerable<TActual>>(message);

                using var bufferedActual = actual.Buffer();
                using var bufferedExpected = expected.Buffer();

                if (bufferedActual.Count != bufferedExpected.Count)
                    throw c.StandardError.LengthMismatch(bufferedExpected.Count, bufferedActual, message);

                if (!c.Test.CollectionsMatch(bufferedActual, bufferedExpected, ReferenceEquals))
                    throw c.StandardError.ItemsNotSame(bufferedExpected, bufferedActual, message);
            });
    }

    ///
    /// Asserts that a <see cref="KeyedCollection{TKey,TItem}"/> contains an item for the specified key.
    ///
    public static Actual<KeyedCollection<TKey, TItem>> ShouldContainKey<TKey, TItem>([NotNull] this KeyedCollection<TKey, TItem>? actual, TKey expectedKey, string? message = null)
    {
        return actual.RegisterNotNullAssertion(c =>
            {
                actual.ShouldBeA<KeyedCollection<TKey, TItem>>(message);
                if (!actual.Contains(expectedKey))
                    throw c.StandardError.DoesNotContain(expectedKey, actual, "key", message);
            });
    }

    ///
    /// Asserts that a <see cref="KeyedCollection{TKey,TItem}"/> does not contain an item for the specified key.
    ///
    public static Actual<KeyedCollection<TKey, TItem>> ShouldNotContainKey<TKey, TItem>([NotNull] this KeyedCollection<TKey, TItem>? actual, TKey notExpectedKey, string? message = null)
    {
        return actual.RegisterNotNullAssertion(c =>
            {
                actual.ShouldBeA<KeyedCollection<TKey, TItem>>(message);
                if (actual.Contains(notExpectedKey))
                    throw c.StandardError.Contains(notExpectedKey, actual, "key", message);
            });
    }

    ///
    /// Asserts that a sequence of items satisfies a matched sequence of assertions.
    ///
    public static Actual<IEnumerable<TItem>> ItemsSatisfy<TItem>([NotNull] this IEnumerable<TItem>? actual, params Action<TItem>[] assertions)
    {
        if (assertions == null) throw new ArgumentNullException(nameof(assertions));
        if (assertions.Any(a => a == null)) throw new ArgumentException("Assertions can not be null", nameof(assertions));

        return actual.RegisterNotNullAssertion(c =>
            {
                actual.ShouldBeA<IEnumerable<TItem>>();

                using var bufferedActual = actual.Buffer();

                if (bufferedActual.Count != assertions.Length)
                    throw c.StandardError.LengthMismatch(assertions.Length, bufferedActual);

                for (var i = 0; i < assertions.Length; i++)
                    c.Call(() => assertions[i](bufferedActual[i]), $"[{i}]");
            });
    }

    ///
    /// Asserts that all items in a sequence satisfy a specified assertion.
    ///
    public static Actual<IEnumerable<TItem>> AllItemsSatisfy<TItem>([NotNull] this IEnumerable<TItem>? actual, Action<TItem> assertion)
    {
        if (assertion == null) throw new ArgumentNullException(nameof(assertion));

        return actual.RegisterNotNullAssertion(c =>
            {
                actual.ShouldBeA<IEnumerable<TItem>>();

                var i = 0;
                foreach (var item in actual)
                    c.Call(() => assertion(item), $"[{i++}]");
            });
    }
}


text:
namespace SharedWeekends.Data.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.EntityFramework;

    using SharedWeekends.Models;

    public sealed class Configuration : DbMigrationsConfiguration<WeekendsDbContext>
    {
        public Configuration()
        {
            this.AutomaticMigrationsEnabled = true;
            this.AutomaticMigrationDataLossAllowed = true;
        }

        protected override void Seed(WeekendsDbContext context)
        {
            var db = new WeekendsDbContext();
            if (db.Users.Any())
            {
                return;
            }

            var userManager = new UserManager<User>(new UserStore<User>(context));
            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));

            roleManager.Create(new IdentityRole("admin"));

            var userAdmin = new User
            {
                UserName = "admin",
                Email = "a@a.a"
            };

            var resultAdmin = userManager.Create(userAdmin, "ad123456min");
            if (resultAdmin.Succeeded)
            {
                userManager.AddToRole(userAdmin.Id, "admin");
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
 Compares object with CanvasControl class

**Namespace:** [OfficeDevPnP.Core.Framework.Provisioning.Model](OfficeDevPnP.Core.Framework.Provisioning.Model.md)
**Assembly:** OfficeDevPnP.Core.dll
## Syntax
```C#
public override bool Equals(Object obj)
```
### Parameters
#### obj
  Type: System.Object
  Object that represents CanvasControl

### Return Value
Type: bool
Checks whether object is CanvasControl class

## See also
- [CanvasControl](OfficeDevPnP.Core.Framework.Provisioning.Model.CanvasControl.md)
- [OfficeDevPnP.Core.Framework.Provisioning.Model](OfficeDevPnP.Core.Framework.Provisioning.Model.md)


text:
package eu.lunisolar.magma.asserts.func.function.conversion;

import eu.lunisolar.magma.asserts.func.FunctionalAttest.AssertionsCheck;
import eu.lunisolar.magma.asserts.func.FunctionalAttest.SemiEvaluation;
import eu.lunisolar.magma.func.supp.Be;
import eu.lunisolar.magma.asserts.func.FunctionalAttest;
import eu.lunisolar.magma.asserts.func.FunctionalAttest.*;
import javax.annotation.Nonnull; // NOSONAR
import javax.annotation.Nullable; // NOSONAR
import eu.lunisolar.magma.func.supp.check.Checks; // NOSONAR
import eu.lunisolar.magma.basics.meta.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.type.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.domain.*; // NOSONAR
import eu.lunisolar.magma.func.action.*; // NOSONAR

import java.util.function.*;

import eu.lunisolar.magma.func.function.conversion.*;

import eu.lunisolar.magma.func.action.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.bi.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.obj.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.tri.*; // NOSONAR
import eu.lunisolar.magma.func.function.*; // NOSONAR
import eu.lunisolar.magma.func.function.conversion.*; // NOSONAR
import eu.lunisolar.magma.func.function.from.*; // NOSONAR
import eu.lunisolar.magma.func.function.to.*; // NOSONAR
import eu.lunisolar.magma.func.operator.binary.*; // NOSONAR
import eu.lunisolar.magma.func.operator.ternary.*; // NOSONAR
import eu.lunisolar.magma.func.operator.unary.*; // NOSONAR
import eu.lunisolar.magma.func.predicate.*; // NOSONAR
import eu.lunisolar.magma.func.supplier.*; // NOSONAR

/** Assert class for LBoolToDblFunction. */
public final class LBoolToDblFunctionAttest extends FunctionalAttest.Full<LBoolToDblFunctionAttest, LBoolToDblFunction, LBoolConsumer, Checks.CheckDbl> {

	public LBoolToDblFunctionAttest(LBoolToDblFunction actual) {
		super(actual);
	}

	public LBoolToDblFunctionAttest(LBoolToDblFunction actual, String name) {
		super(actual, name);
	}

	@Nonnull
	public static LBoolToDblFunctionAttest attestBoolToDblFunc(LBoolToDblFunction func) {
		return new LBoolToDblFunctionAttest(func);
	}

	@Nonnull
	public static LBoolToDblFunctionAttest attestBoolToDblFunc(LBoolToDblFunction func, String name) {
		return new LBoolToDblFunctionAttest(func, name);
	}

	@Nonnull
	public DblEvaluation<LBoolToDblFunctionAttest, LBoolConsumer> doesApplyAsDbl(boolean a) {

		return new DblEvaluation<LBoolToDblFunctionAttest, LBoolConsumer>(this, () -> String.format("(%s)", a), (desc, pc) -> {

			var func = value();
			Checks.check(func).must(Be::notNull, "Actual function is null.");

			if (pc != null) {
				pc.accept(a);
			}

			var result = func.applyAsDbl(a);
			return Checks.attest(result, desc);

		}, recurringAssert);
	}

}


text:
Repo where I'll put all files of the 2016-2017 ICT's lessons.

### General Infos
I will put the files divided in folders, renamed by the dates of the works.
Inside these folders there will be the files and a small .txt file, where I'll put textually what we've done.

### Repo clonation
If (for some akward reasons) You want to clone the repo on your server, You just only have to do these commands:

    $ sudo apt-get install git
    $ git clone github.com/iDoppioclick/ICT-2016-2017.git
    $ cd ICT-2016-2017

To update the repo with the new files, just run this simple command:

    $ git pull

### License
Licensed under [MIT](https://opensource.org/licenses/MIT), created by iDoppioclick - 2016/2017


text:
var AWS = require('aws-sdk');
var MapboxClient = require('mapbox');
var client = new MapboxClient(process.env.MAPBOX_TOKEN);
var username = process.env.MAPBOX_USER

module.exports = function upload(fc) {
  client.createUploadCredentials(function(err, credentials, callback) {
    if (err) {
      return callback(err, null);
    }
    var s3 = new AWS.S3({
     accessKeyId: credentials.accessKeyId,
     secretAccessKey: credentials.secretAccessKey,
     sessionToken: credentials.sessionToken,
     region: 'us-east-1'
    });
    s3.putObject({
      Bucket: credentials.bucket,
      Key: credentials.key,
      Body: JSON.stringify(fc)
    }, function(err, tmp) {
      if (err) {
        return callback(err, null);
      }
      client.createUpload({
        tileset: username + '.' + 'upload-run',
        url: credentials.url,
        name: 'upload-run'
      }, function(err, upload) {
        if (err) {
          return callback(err, null);
        }
        callback(null, upload);
      });
    });
  });
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>T20684467584634880</title>
  <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Source+Sans+Pro:300,300i,600">
  <link rel="stylesheet" href="/style.css">
  <link rel="stylesheet" href="/custom.css">

  <link rel="alternate" type="application/rss+xml" title="Des Paroz" href="http://desparoz.me/feed.xml" />
  <link rel="alternate" type="application/json" title="Des Paroz" href="http://desparoz.me/feed.json" />
  <link rel="EditURI" type="application/rsd+xml" href="/rsd.xml" />

  <link rel="me" href="https://micro.blog/desparoz" />

  	<link rel="me" href="https://twitter.com/desparoz" />

  	<link rel="me" href="https://github.com/desparoz" />

  <link rel="authorization_endpoint" href="https://indieauth.com/auth" />
  <link rel="token_endpoint" href="https://tokens.indieauth.com/token" />
  <link rel="micropub" href="https://micro.blog/micropub" />
  <link rel="webmention" href="https://micro.blog/webmention" />

    Des Paroz

    <time class="dt-published" datetime="2010-12-31 13:35:00 +1000">31 Dec 2010</time>

Picking up stuff for a Japanese banquet for New Years Evev (@ Tokyo Mart) 4sq.com/frajki


text:
package com.whitepages.cloudmanager.action

import com.whitepages.cloudmanager.ManagerException
import com.whitepages.cloudmanager.client.{SolrCloudVersion, SolrRequestHelpers}
import org.apache.solr.client.solrj.impl.CloudSolrServer
import org.apache.solr.common.params.ModifiableSolrParams
import org.apache.solr.common.params.CollectionParams.CollectionAction
import scala.util.Try
import com.whitepages.cloudmanager.state.{SolrReplica, SolrState, ClusterManager}
import scala.concurrent.duration._

case class AddReplica(collection: String, slice: String, copyTo: String, waitUntilActive: Boolean = true, waitTimeoutSec: Int = -1) extends Action {
  override val preConditions: List[StateCondition] = List(
    StateCondition("collection exists", Conditions.collectionExists(collection)),
    StateCondition("live replica exists", Conditions.liveReplicaCount(collection, slice).andThen(_ > 0)),
    StateCondition("target node exists", Conditions.nodeExists(copyTo)),
    StateCondition("target node doesn't have the slice yet", Conditions.sliceIncludesNode(collection, slice, copyTo).andThen(!_))
  )

  override def execute(clusterManager: ClusterManager): Boolean = {
    if (clusterManager.clusterVersion < SolrCloudVersion(4,8))
      throw new ManagerException("AddReplica is not supported before Solr 4.8, this cluster is " + clusterManager.clusterVersion)

    comment.info(s"Issuing command for ${this.name}: Collection: $collection, Slice: $slice, copying onto: $copyTo")
    val params = new ModifiableSolrParams
    params.set("action", CollectionAction.ADDREPLICA.toString)
    params.set("collection", collection)
    params.set("node", copyTo)
    params.set("shard", slice)
    val success = SolrRequestHelpers.submitRequest(clusterManager.client, params)

    success && (!waitUntilActive || Conditions.waitForState(clusterManager, Conditions.activeSliceOnNode(collection, slice, copyTo), waitTimeoutSec))
  }

  override val postConditions: List[StateCondition] = List(
    StateCondition("target node has the slice", Conditions.sliceIncludesNode(collection, slice, copyTo))
  )

  override def toString = {
    s"AddReplica: collection: $collection, slice: $slice, onto: ${SolrReplica.hostName(copyTo)}, waitUntilActive: $waitUntilActive, waitTimeout: $waitTimeoutSec"
  }
}


text:
package org.openkilda.messaging.swmanager.request;

import org.openkilda.messaging.command.CommandData;
import org.openkilda.model.SwitchId;

import lombok.EqualsAndHashCode;
import lombok.Value;

import java.util.Set;

@Value
@EqualsAndHashCode(callSuper = false)
public class UpdateLagPortRequest extends CommandData {
    SwitchId switchId;
    int logicalPortNumber;
    Set<Integer> targetPorts;
    boolean lacpReply;
}


text:
package Game;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
import java.util.LinkedHashMap;
import java.util.Map;

public class TUIMethod {
    private URL serverURL;
    private String serverIPAddress;
    private String serverPort;

    public TUIMethod(String serverIPAddress, String serverPort) {
        this.serverIPAddress = serverIPAddress;
        this.serverPort = serverPort;
        this.serverURL = null;
    }

    public String StartConnection() {
        try {
            //Create connection
            serverURL = new URL("http://" + serverIPAddress + ":" + serverPort + "/Server/REST");
            HttpURLConnection serverConnection = (HttpURLConnection) serverURL.openConnection();
            serverConnection.setRequestMethod("GET");
            // try to recover the response code from the server to know if is on
            serverConnection.getResponseCode();
            return "ok";
        }
        catch (Exception e) {
            return "Connection with server failed...";
        }
    }

    // Writes on terminal the list of current matches
    public String GetListOfCurrentMatches() {
        try {
            // server request
            URL url = new URL(serverURL + "/getGamesNames");
            HttpURLConnection serverConnection = (HttpURLConnection) url.openConnection();
            serverConnection.setRequestMethod("GET");
            // find matches
            return GetRequest(serverConnection);
        }
        catch (Exception e) {
            return "error";
        }
    }

    // Writes on terminal the details of a match
    public String GetDetailsOfMatch(String matchName) {
        try {
            // server request
            URL url = new URL(serverURL + "/gameDetails/" + matchName);
            HttpURLConnection serverConnection = (HttpURLConnection) url.openConnection();
            serverConnection.setRequestMethod("GET");
            // find matches
            return GetRequest(serverConnection);
        }
        catch (Exception e) {
            return "error";
        }
    }

    // Create a new match
    public String CreateANewGame(String playerName, String matchName, String sideSize, String maxScore, String IPAddress, String portAddress) {
        try {
            Map<String,Object> params = new LinkedHashMap<>();
            params.put("gameName", matchName);
            params.put("sizeSide", sideSize);
            params.put("maxScore", maxScore);
            params.put("IPAddress", IPAddress);
            params.put("portAddress", portAddress);
            params.put("playerName", playerName);
            StringBuilder postData = new StringBuilder();
            for (Map.Entry<String,Object> param : params.entrySet()) {
                if (postData.length() != 0) postData.append('&');
                postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                postData.append('=');
                postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
            }
            byte[] postDataBytes = postData.toString().getBytes("UTF-8");
            // server post
            URL url = new URL(serverURL + "/createGame");
            HttpURLConnection serverConnection = (HttpURLConnection) url.openConnection();
            serverConnection.setRequestMethod("POST");
            serverConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            serverConnection.setRequestProperty("Content-Length", Integer.toString(postData.length()));
            serverConnection.setDoOutput(true);
            serverConnection.getOutputStream().write(postDataBytes);

            // receive game from call
            return GetRequest(serverConnection);
        }
        catch (Exception e) {
            return "error";
        }
    }

    // Add player to a created match
    public String AddPlayerInGame(String playerName, String matchName, String IPAddress, String portAddress) {
        try {
            // server post
            URL url = new URL(serverURL + "/addPlayer/" + matchName + "/" + playerName + "/" + IPAddress + "/" + portAddress);
            HttpURLConnection serverConnection = (HttpURLConnection) url.openConnection();
            serverConnection.setRequestMethod("PUT");

            // receive on ok from the server
            return GetRequest(serverConnection);
        }
        catch (Exception e) {
            return "error";
        }
    }

    // Remove a player from a created match
    public String RemovePlayerFromMatch(String playerName, String matchName, String IPAddress, String portAddress) {
        try {
            // server request
            URL url = new URL(serverURL + "/removePlayer/" + matchName + "/" + playerName + "/" + IPAddress + "/" + portAddress);
            HttpURLConnection serverConnection = (HttpURLConnection) url.openConnection();
            serverConnection.setRequestMethod("DELETE");
            // find matches
            return GetRequest(serverConnection);
        }
        catch (Exception e) {
            return "error";
        }
    }

    private String GetRequest(HttpURLConnection serverConnection) {
        try {
            if (serverConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                // recovery json
                BufferedReader in = new BufferedReader(new InputStreamReader(serverConnection.getInputStream()));
                String inputLine;
                StringBuffer result = new StringBuffer();
                while ((inputLine = in.readLine()) != null) {
                    result.append(inputLine);
                }
                in.close();
                return result.toString();
            }
            // no match found
            else {
                return "empty";
            }
        } catch (Exception e) {
            return "error";
        }
    }
}


text:
var SK8RGameWorld = (function() {
    var debugDraw = false ;
    var self = {} ;
    var bodies ;
    var joints ;
    var world ;
    var actors ;
    var timerID ;
    var lastFrameTime ;
    var renderCallback = SK8RBindApply(self, renderFixtures) ;
    var deck ;
    var cameraFollowsDeck = false ;
    var renderers = new Array() ;

    function initFixtures(progressMeter) {
        createDemoGround() ;
        if (progressMeter) {
            progressMeter.progress(0.4) ;
        }
    }

    function initBodies(progressMeter) {
        deck = new Sk8board({
            scale : 2,
            offset : {
                x:1.2,
                y:9.8
            }
        }) ;
        if (progressMeter) {
            progressMeter.progress(0.5) ;
        }
        var sk8rbody = createSK8RRobot({
            offsetx : 1,
            offsety : 6.5,
            scale: 0.8
        }) ;
        var sk8rActor = new SK8RBotActor(sk8rbody) ;
        self.addActor(sk8rActor) ;
        window.onkeydown = SK8RBindApply(sk8rActor, sk8rActor.onkeydown) ;

        if (progressMeter) {
            progressMeter.progress(0.6) ;
        }
    }

    function step() {
        if (!world.IsLocked()) {
            // Advance physics
            world.Step(1 / 30, 10, 10);

            // Let AI-actors advance
            var now = new Date().getTime() ;
            var timeSinceLastFrame = now - lastFrameTime ;
            lastFrameTime = now ;
            for (var n=0; n<actors.length; n++) {
                actors[n].step(timeSinceLastFrame) ;
            }

            if (cameraFollowsDeck) {
                var wp = deck.GetPosition() ;
                SK8RCanvas.panTo(wp.x, wp.y);
            }

            // Renderers
            if (debugDraw) {
                world.DrawDebugData();
            } else {
                SK8RCanvas.clear();
                var viewportAABB = SK8RCanvas.getViewportAABB() ;
                world.QueryAABB(renderCallback, viewportAABB) ;
                for (var n=0; n<renderers.length; n++) {
                    var renderer = renderers[n].pop() ;
                    while (renderer) {
                        renderer.render() ;
                        renderer = renderers[n].pop() ;
                    }
                }
            }
            world.ClearForces();
        } else {
            if (console) {
                console.log("World is locked when entering step");
            }
        }
    }

    function renderFixtures(b2Fixture) {
        // TODO: bodies with several fixtures will be rendered several times using this. Might be ok
        var userdata = b2Fixture.GetBody().GetUserData() ;
        if (userdata) {
            self.queueRenderer(userdata) ;
        }
        return true ;
    }

    function start() {
        lastFrameTime = new Date().getTime() ;
        var callback = SK8RBindCall(self, step) ;
        timerID = window.setInterval(callback, 1000 / 30);
    }

    self.queueRenderer = function(renderer) {
        renderers[renderer.getZIndex()].push(renderer) ;
    }

    self.onLoad = function() {
        var progressBar = new ProgressBar(SK8RCanvas.getContext()) ;
        var progressMeter =
        new ProgressMeter("Initializing",
            [
            SK8RBindApply(progressBar, progressBar.progress),
            function(taskname, progressFraction) {
                console.log("Progress [" + taskname + "]="+progressFraction*100 + "%") ;
            }
            ]) ;
        // Iniitalize globals
        bodies = new Array();
        joints = new Array();
        actors = new Array();
        world = new Box2D.Dynamics.b2World(
            new Box2D.Common.Math.b2Vec2(0, 10), true);
        // setup debug draw
        if (debugDraw) {
            SK8RCanvas.setupDebugDraw(world);
        }
        progressMeter.progress(0.1) ;

        // Setup game world
        initFixtures(progressMeter) ;
        initBodies(progressMeter) ;

        progressMeter.progress(0.7) ;
        for (var n=0; n<10; n++) {
            renderers[n] = new Array() ;
        }
        progressMeter.progress(1.0) ;
        SK8RCanvas.clear() ;

        start() ;
    }

    self.reset = function() {
        SK8RCanvas.clear() ;
        var n ;
        window.clearInterval(timerID) ;
        // Destroy the existing joints
        for (n = 0; n < joints.length; n++) {
            world.DestroyJoint(joints[n]);
        }
        joints = new Array() ;
        // Destroy the existing bodies
        for (n = 0; n < bodies.length; n++) {
            world.DestroyBody(bodies[n]);
        }
        bodies = new Array();
        actors = new Array() ;
        // Setup game world
        initBodies() ;
        start();
    };

    self.toggleFollow = function() {
        cameraFollowsDeck = !cameraFollowsDeck ;
    }

    self.createBody = function(bodyDef, fixtureDef) {
        var body = self.createUntrackedBody(bodyDef, fixtureDef) ;
        bodies.push(body) ;
        return body ;
    };

    self.createUntrackedBody = function(bodyDef, fixtureDef) {
        var fixtureDefinitions = new Array() ;
        fixtureDefinitions = fixtureDefinitions.concat(fixtureDef) ;
        var body = world.CreateBody(bodyDef) ;
        for (var n=0; n<fixtureDefinitions.length; n++) {
            body.CreateFixture(fixtureDefinitions[n]) ;
        }
        return body ;
    };

    self.createJoint = function(jointDef) {
        var joint = world.CreateJoint(jointDef);
        joints.push(joint);
        return joint ;
    };

    self.addActor = function(actor) {
        if (actor) {
            actors.push(actor) ;
        }
    };

    self.removeActor = function(actor) {
        actors = actors.filter(function(curValue, curIndex, curArray)
        {
            return (element != actor) ;
        }
        );
    };

    return self ;
}()) ;

window.onload = function() {
    SK8RCanvas.onLoad() ;
    SK8RGameWorld.onLoad() ;
};


text:
#import "ORKHolePegTestRemoveStepViewController.h"

#import "ORKActiveStepView.h"
#import "ORKHolePegTestRemoveContentView.h"

#import "ORKActiveStepViewController_Internal.h"
#import "ORKStepViewController_Internal.h"
#import "ORKTaskViewController.h"

#import "ORKHolePegTestRemoveStep.h"

#import "ORKHelpers_Internal.h"
#import "ORKResult.h"

@interface ORKHolePegTestRemoveStepViewController () <ORKHolePegTestRemoveContentViewDelegate>

@property (nonatomic, strong) NSMutableArray *samples;
@property (nonatomic, strong) ORKHolePegTestRemoveContentView *holePegTestRemoveContentView;
@property (nonatomic, assign) NSTimeInterval sampleStart;
@property (nonatomic, assign) NSUInteger successes;
@property (nonatomic, assign) NSUInteger failures;

@end

@implementation ORKHolePegTestRemoveStepViewController

- (instancetype)initWithStep:(ORKStep *)step {
    self = [super initWithStep:step];
    if (self) {
        self.suspendIfInactive = YES;
    }
    return self;
}

- (ORKHolePegTestRemoveStep *)holePegTestRemoveStep {
    return (ORKHolePegTestRemoveStep *)self.step;
}

- (void)initializeInternalButtonItems {
    [super initializeInternalButtonItems];

    // Don't show next button
    self.internalContinueButtonItem = nil;
    self.internalDoneButtonItem = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.holePegTestRemoveContentView = [[ORKHolePegTestRemoveContentView alloc] initWithMovingDirection:[self holePegTestRemoveStep].movingDirection];
    self.holePegTestRemoveContentView.threshold = [self holePegTestRemoveStep].threshold;
    self.holePegTestRemoveContentView.delegate = self;
    self.activeStepView.activeCustomView = self.holePegTestRemoveContentView;
    self.activeStepView.stepViewFillsAvailableSpace = YES;

    NSString *identifier = [[self holePegTestRemoveStep].identifier stringByReplacingOccurrencesOfString:@"remove" withString:@"place"];
    NSTimeInterval placeStepDuration = ((ORKHolePegTestResult *)[[self.taskViewController.result stepResultForStepIdentifier:identifier].results firstObject]).totalTime;
    [self holePegTestRemoveStep].stepDuration -= placeStepDuration;

    [self start];
}

#pragma mark - step life cycle methods

- (void)start {
    self.sampleStart = CACurrentMediaTime();
    self.successes = 0;
    self.failures = 0;
    self.samples = [NSMutableArray array];
    [self.holePegTestRemoveContentView setProgress:0.001f animated:NO];

    [super start];
}

#pragma mark - result methods

- (ORKStepResult *)result {
    ORKStepResult *sResult = [super result];

    NSMutableArray *results = [NSMutableArray arrayWithArray:sResult.results];

    ORKHolePegTestResult *holePegTestResult = [[ORKHolePegTestResult alloc] initWithIdentifier:self.step.identifier];
    holePegTestResult.movingDirection = [self holePegTestRemoveStep].movingDirection;
    holePegTestResult.dominantHandTested = [self holePegTestRemoveStep].isDominantHandTested;
    holePegTestResult.numberOfPegs = [self holePegTestRemoveStep].numberOfPegs;
    holePegTestResult.threshold = [self holePegTestRemoveStep].threshold;
    holePegTestResult.rotated = NO;
    holePegTestResult.totalSuccesses = self.successes;
    holePegTestResult.totalFailures = self.failures;
    holePegTestResult.totalTime = [self holePegTestRemoveStep].stepDuration - self.timeRemaining;
    double totalDistance = 0.0;
    for (ORKHolePegTestSample *sample in self.samples) {
        totalDistance += sample.distance;
    }
    holePegTestResult.totalDistance = totalDistance;
    holePegTestResult.samples = self.samples;

    [results addObject:holePegTestResult];

    sResult.results = [results copy];

    return sResult;
}

- (void)saveSampleWithDistance:(CGFloat)distance {
    ORKHolePegTestSample *sample = [[ORKHolePegTestSample alloc] init];
    sample.time = CACurrentMediaTime() - self.sampleStart;
    sample.distance = distance;
    self.sampleStart = CACurrentMediaTime();

    [self.samples addObject:sample];
}

#pragma mark - hole peg test content view delegate

- (NSString *)stepTitle {
    NSString *title = ([self holePegTestRemoveStep].movingDirection == ORKBodySagittalLeft) ? ORKLocalizedString(@"HOLE_PEG_TEST_REMOVE_INSTRUCTION_RIGHT_HAND", nil) : ORKLocalizedString(@"HOLE_PEG_TEST_REMOVE_INSTRUCTION_LEFT_HAND", nil);
    return title;
}

- (void)holePegTestRemoveDidProgress:(ORKHolePegTestRemoveContentView *)holePegTestRemoveContentView {
    [self.activeStepView updateTitle:[self stepTitle]
                                text:ORKLocalizedString(@"HOLE_PEG_TEST_TEXT_2", nil)];
}

- (void)holePegTestRemoveDidSucceed:(ORKHolePegTestRemoveContentView *)holePegTestRemoveContentView withDistance:(CGFloat)distance {
    self.successes++;

    [self saveSampleWithDistance:distance];

    [holePegTestRemoveContentView setProgress:((CGFloat)self.successes / [self holePegTestRemoveStep].numberOfPegs) animated:YES];
    [self.activeStepView updateTitle:[self stepTitle]
                                text:ORKLocalizedString(@"HOLE_PEG_TEST_TEXT", nil)];

    if (self.successes >= [self holePegTestRemoveStep].numberOfPegs) {
        [self finish];
    }
}

- (void)holePegTestRemoveDidFail:(ORKHolePegTestRemoveContentView *)holePegTestRemoveContentView {
    self.failures++;

    [self.activeStepView updateTitle:[self stepTitle]
                                text:ORKLocalizedString(@"HOLE_PEG_TEST_TEXT", nil)];
}

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Mview/etc/mview.xsd">
    <view id="customer_dummy" class="Magento\Customer\Model\Indexer\Mview\Dummy" group="indexer"/>
</config>


text:
published: true
layout: post
---
## Algorithms

[Design and Analysis of Algorithms](https://www.coursera.org/learn/algorithm-design-analysis/lecture/jSwWo/why-study-algorithms).

[algorithm-design-analysis-2](https://www.coursera.org/learn/algorithm-design-analysis-2/home/welcome)

###

[Design and Analysis of Algorithms](http://openclassroom.stanford.edu/MainFolder/HomePage.php)
Introduction to fundamental techniques for designing and analyzing algorithms, including asymptotic analysis; divide-and-conquer algorithms and recurrences; greedy algorithms; data structures; dynamic programming; graph algorithms; and randomized algorithms.

http://www.xlgps.com/article/293113.html

http://www.xlgps.com/article/293110.html

http://www.cnblogs.com/dagon/p/4783213.html

http://www.cnblogs.com/CCBB/archive/2011/09/13/2175043.html


text:
from pprint import pprint

from django.http import JsonResponse
from django.shortcuts import render
from django.views import View

import lotes.models

import cd.forms

class EnderecoLote(View):

    def __init__(self):
        self.Form_class = cd.forms.AskLoteForm
        self.template_name = 'cd/endereco_lote.html'
        self.title_name = 'Verifica endereço de Lote'

    def mount_context(self, request, form):
        lote = form.cleaned_data['lote']
        context = {'lote': lote}

        response = dict_endereco_lote(lote)
        error_level = response.pop('error_level')

        if error_level == 1:
            context.update({'erro': 'Lote não encontrado'})
        elif error_level == 2:
            context.update({'erro': 'Não endereçado'})
        else:
            context.update(response)

        return context

    def get(self, request, *args, **kwargs):
        if 'lote' in kwargs and kwargs['lote'] is not None:
            return self.post(request, *args, **kwargs)
        else:
            context = {'titulo': self.title_name}
            form = self.Form_class()
            context['form'] = form
            return render(request, self.template_name, context)

    def post(self, request, *args, **kwargs):
        context = {'titulo': self.title_name}
        form = self.Form_class(request.POST)
        if 'lote' in kwargs and kwargs['lote'] is not None:
            form.data['lote'] = kwargs['lote']
        if form.is_valid():
            data = self.mount_context(request, form)
            context.update(data)
        context['form'] = form
        return render(request, self.template_name, context)

def dict_endereco_lote(lote):
    data = {
        'lote': lote,
    }

    try:
        lote_rec = lotes.models.Lote.objects.get(lote=lote)

        data.update({
            'op': lote_rec.op,
            'referencia': lote_rec.referencia,
            'cor': lote_rec.cor,
            'tamanho': lote_rec.tamanho,
            'qtd_produzir': lote_rec.qtd_produzir,
        })

        if lote_rec.local is None or lote_rec.local == '':
            data.update({
                'error_level': 2,
                'msg': 'Lote não endereçado',
            })
        else:
            local = lote_rec.local
            lotes_no_local = len(lotes.models.Lote.objects.filter(
                local=lote_rec.local))

            data.update({
                'error_level': 0,
                'local': local,
                'q_lotes': lotes_no_local,
                'msg': f'OK',
            })

    except lotes.models.Lote.DoesNotExist:
        data.update({
            'error_level': 1,
            'msg': 'Lote não encontrado',
        })

    return data

def ajax_endereco_lote(request, lote):
    data = dict_endereco_lote(lote)

    return JsonResponse(data, safe=False)


text:
DOCS := docs/*.md
PROCESSOR ?= "/opt/v8/tools/linux-tick-processor"
LIB := ./node_modules
BIN := $(LIB)/.bin

all: build

# Main tasks
# ----------

build:
	gulp build

lint:
	gulp lint

.PHONY: build lint all

# Install and internal updates
# ----------------------------

install:
	@npm install
	@bower install

# This is required if mocha, expect or benchmark is updated.
update:
	@cp -v $(LIB)/spec/lib/* test/lib/
	@cp -v $(LIB)/benchmark/benchmark.js test/lib/

# Usage: make VERSION=0.1.0 version-bump
version-bump:
	@sed -i 's|\("version": "\)[^"]*\("\)|\1$(VERSION)\2|' {bower,package,component}.json
	@sed -i "s|\(exports\.version = '\)[^']*\('\)|\1$(VERSION)\2|" luaparse.js
	@git add {package,bower,component}.json luaparse.js
	@git commit -m "Version $(VERSION)"
	@git tag -a "v$(VERSION)" -m "v$(VERSION)"

.PHONY: install update version-bump

# Tests
# -----

test-node:
	@node test/runner.js --console

test:
	@$(BIN)/testem ci

testem-engines:
	@$(BIN)/testem -l PhantomJS,node,narwhal,ringo,rhino,rhino1.7R5

# Scaffold all test files in the scaffolding dir.
scaffold-tests:
	@$(foreach file,\
		$(notdir $(wildcard test/scaffolding/*)),\
		$(MAKE) -s scaffold-test FILE=$(file);\
	)

scaffold-test:
	@./scripts/scaffold-test --name=$(FILE) \
		test/scaffolding/$(FILE) \
		> test/spec/$(FILE).js

.PHONY: test-node test testem-engines scaffold-tests scaffold-test

# Documentation
# -------------

docs: docco coverage docs-test docs-md

docco:
	@$(BIN)/docco luaparse.js

docs-index:
	@$(BIN)/marked README.md --gfm \
		| cat docs/layout/head.html - docs/layout/foot.html \
		> docs/index.html

docs-md: docs-index $(patsubst %.md,%.html, $(wildcard docs/*.md))

%.html: %.md
	@echo $<
	@$(BIN)/marked $< --gfm \
		| cat docs/layout/head.html - docs/layout/foot.html \
		> $@

.PHONY: docs docco docs-test docs-index

# Coverage
# --------

coverage:
	@rm -rf html-report docs/coverage
	@$(BIN)/istanbul cover --report html --dir docs/coverage test/runner.js >/dev/null

.PHONY: coverage

# Benchmark
# ---------

benchmark:
	@./scripts/benchmark -v benchmarks/lib/ParseLua.lua

profile:
	@bash benchmarks/run.sh -v --processor $(PROCESSOR) --profile HEAD

benchmark-previous:
	@bash benchmarks/run.sh --js HEAD HEAD~1

.PHONY: benchmark profile benchmark-previous

# Quality Assurance
# -----------------

complexity-analysis:
	@echo "===================== Complexity analysis ============================"
	@./scripts/complexity 10
	@$(BIN)/cr -lws --maxcc 17 luaparse.js

coverage-analysis: coverage
	@$(BIN)/istanbul check-coverage --statements -6 --branches -16 --functions -0 \
		docs/coverage/coverage.json

qa:
	@$(MAKE) -s test lint complexity-analysis coverage-analysis

clean:
	@rm -f docs/*.html
	@rm -rf lib-cov coverage html-report docs/coverage/

.PHONY: complexity-analysis coverage-analysis qa clean


text:
namespace net {

namespace {
static sockaddr* RISA(void* ptr) { return reinterpret_cast<sockaddr*>(ptr); }

static const sockaddr* RICSA(const void* ptr) {
  return reinterpret_cast<const sockaddr*>(ptr);
}

class FDConnReader : public io::ReaderImpl {
 public:
  explicit FDConnReader(base::FD fd) : r_(io::fdreader(std::move(fd))) {}

  std::size_t ideal_block_size() const noexcept override {
    return r_.ideal_block_size();
  }

  void read(event::Task* task, char* out, std::size_t* n, std::size_t min,
            std::size_t max, const base::Options& opts) override {
    r_.read(task, out, n, min, max, opts);
  }

  void write_to(event::Task* task, std::size_t* n, std::size_t max,
                const io::Writer& w, const base::Options& opts) override {
    r_.write_to(task, n, max, w, opts);
  }

  void close(event::Task* task, const base::Options& opts) override {
    if (!prologue(task)) return;
    auto fd = internal_readerfd();
    task->finish(base::shutdown(fd, SHUT_RD));
  }

  base::FD internal_readerfd() const override {
    return r_.implementation()->internal_readerfd();
  }

 private:
  io::Reader r_;
};

class FDConnWriter : public io::WriterImpl {
 public:
  explicit FDConnWriter(base::FD fd) : w_(io::fdwriter(std::move(fd))) {}

  std::size_t ideal_block_size() const noexcept override {
    return w_.ideal_block_size();
  }

  void write(event::Task* task, std::size_t* n, const char* ptr,
             std::size_t len, const base::Options& opts) override {
    w_.write(task, n, ptr, len, opts);
  }

  void read_from(event::Task* task, std::size_t* n, std::size_t max,
                 const io::Reader& r, const base::Options& opts) override {
    w_.read_from(task, n, max, r, opts);
  }

  void close(event::Task* task, const base::Options& opts) override {
    if (!prologue(task)) return;
    auto fd = internal_writerfd();
    task->finish(base::shutdown(fd, SHUT_WR));
  }

  base::FD internal_writerfd() const override {
    return w_.implementation()->internal_writerfd();
  }

 private:
  io::Writer w_;
};

class FDConn : public ConnImpl {
 public:
  FDConn(Addr la, Addr ra, io::Reader r, io::Writer w) noexcept
      : la_(std::move(la)),
        ra_(std::move(ra)),
        r_(std::move(r)),
        w_(std::move(w)) {
    CHECK(la_);
    CHECK(ra_);
    CHECK(r_);
    CHECK(w_);
    VLOG(6) << "net::FDConn::FDConn";
  }

  ~FDConn() noexcept { VLOG(6) << "net::FDConn::~FDConn"; }

  Addr local_addr() const override { return la_; }
  Addr remote_addr() const override { return ra_; }
  io::Reader reader() override { return r_; }
  io::Writer writer() override { return w_; }

  void close(event::Task* task, const base::Options& opts) override {
    VLOG(6) << "net::FDConn::close";
    base::Result r = fd()->close();
    if (task->start()) task->finish(std::move(r));
  }

  void get_option(event::Task* task, SockOpt opt, void* optval,
                  unsigned int* optlen,
                  const base::Options& opts) const override {
    if (!task->start()) return;
    task->finish(opt.get(fd(), optval, optlen));
  }

  void set_option(event::Task* task, SockOpt opt, const void* optval,
                  unsigned int optlen, const base::Options& opts) override {
    if (!task->start()) return;
    task->finish(opt.set(fd(), optval, optlen));
  }

 private:
  base::FD fd() const noexcept {
    return w_.implementation()->internal_writerfd();
  }

  Addr la_;
  Addr ra_;
  io::Reader r_;
  io::Writer w_;
};

class FDListenConn : public ListenConnImpl {
 public:
  FDListenConn(event::Manager m, std::shared_ptr<Protocol> pr, Addr aa,
               base::FD fd, AcceptFn fn) noexcept : m_(std::move(m)),
                                                    pr_(std::move(pr)),
                                                    aa_(std::move(aa)),
                                                    fd_(std::move(fd)),
                                                    fn_(std::move(fn)),
                                                    accepting_(false) {
    auto pair = fd_->acquire_fd();
    VLOG(6) << "net::FDListenConn::FDListenConn: fd=" << pair.first << ", "
            << "bind=" << aa_;
  }

  ~FDListenConn() noexcept { VLOG(6) << "net::FDListenConn::~FDListenConn"; }

  base::Result initialize() {
    auto closure = [this](event::Data data) { return handle(data); };
    return m_.fd(&evt_, fd_, event::Set::no_bits(), event::handler(closure));
  }

  Addr listen_addr() const override { return aa_; }
  void start(event::Task* task, const base::Options& opts) override;
  void stop(event::Task* task, const base::Options& opts) override;
  void close(event::Task* task, const base::Options& opts) override;
  void get_option(event::Task* task, SockOpt opt, void* optval,
                  unsigned int* optlen,
                  const base::Options& opts) const override;
  void set_option(event::Task* task, SockOpt opt, const void* optval,
                  unsigned int optlen, const base::Options& opts) override;

 private:
  base::Result handle(event::Data) const;

  const event::Manager m_;
  const std::shared_ptr<Protocol> pr_;
  const Addr aa_;
  const base::FD fd_;
  const AcceptFn fn_;
  mutable std::mutex mu_;
  event::Handle evt_;
  bool accepting_;
};

void FDListenConn::start(event::Task* task, const base::Options& opts) {
  VLOG(6) << "net::FDListenConn::start";
  auto lock = base::acquire_lock(mu_);
  accepting_ = true;
  base::Result r = evt_.modify(event::Set::readable_bit());
  lock.unlock();
  handle(event::Data()).ignore_ok();
  if (task->start()) task->finish(std::move(r));
}

void FDListenConn::stop(event::Task* task, const base::Options& opts) {
  VLOG(6) << "net::FDListenConn::stop";
  auto lock = base::acquire_lock(mu_);
  accepting_ = false;
  base::Result r = evt_.modify(event::Set::no_bits());
  lock.unlock();
  if (task->start()) task->finish(std::move(r));
}

void FDListenConn::close(event::Task* task, const base::Options& opts) {
  VLOG(6) << "net::FDListenConn::close";
  auto lock = base::acquire_lock(mu_);
  accepting_ = false;
  base::Result r0 = evt_.disable();
  base::Result r1 = fd_->close();
  lock.unlock();
  if (task->start()) task->finish(r0.and_then(r1));
}

void FDListenConn::get_option(event::Task* task, SockOpt opt, void* optval,
                              unsigned int* optlen,
                              const base::Options& opts) const {
  if (!task->start()) return;
  task->finish(opt.get(fd_, optval, optlen));
}

void FDListenConn::set_option(event::Task* task, SockOpt opt,
                              const void* optval, unsigned int optlen,
                              const base::Options& opts) {
  if (!task->start()) return;
  task->finish(opt.set(fd_, optval, optlen));
}

base::Result FDListenConn::handle(event::Data data) const {
  VLOG(4) << "net::FDListenConn: woke, set=" << data.events;
  struct sockaddr_storage ss;
  socklen_t sslen;
  const int flags = SOCK_NONBLOCK | SOCK_CLOEXEC;

  auto lock = base::acquire_lock(mu_);
  while (accepting_) {
    auto pair = fd_->acquire_fd();
    ::bzero(&ss, sizeof(ss));
    sslen = sizeof(ss);
    int fdnum = ::accept4(pair.first, RISA(&ss), &sslen, flags);
    if (fdnum == -1) {
      int err_no = errno;
      if (err_no == EINTR) continue;
      if (err_no == EAGAIN || err_no == EWOULDBLOCK) break;
      base::Result::from_errno(err_no, "accept4(2)")
          .expect_ok(__FILE__, __LINE__);
      break;
    }
    base::FD fd = base::wrapfd(fdnum);

    ProtocolType p = aa_.protocol_type();

    Addr ra;
    base::Result r = pr_->interpret(&ra, p, RICSA(&ss), sslen);
    r.expect_ok(__FILE__, __LINE__);
    if (!r) continue;

    ::bzero(&ss, sizeof(ss));
    sslen = sizeof(ss);
    int rc = ::getsockname(fdnum, RISA(&ss), &sslen);
    if (rc != 0) {
      int err_no = errno;
      base::Result::from_errno(err_no, "getsockname(2)")
          .expect_ok(__FILE__, __LINE__);
      continue;
    }

    Addr la;
    r = pr_->interpret(&la, p, RICSA(&ss), sslen);
    r.expect_ok(__FILE__, __LINE__);
    if (!r) continue;

    VLOG(6) << "net::FDListenConn: accept, "
            << "fdnum=" << fdnum << ", "
            << "self=" << la << ", "
            << "peer=" << ra;

    Conn conn;
    r = fdconn(&conn, std::move(la), std::move(ra), std::move(fd));
    r.expect_ok(__FILE__, __LINE__);
    if (!r) continue;

    pair.second.unlock();
    lock.unlock();
    auto reacquire = base::cleanup([&lock] { lock.lock(); });

    try {
      fn_(std::move(conn));
    } catch (...) {
      LOG_EXCEPTION(std::current_exception());
    }
  }
  return base::Result();
}

struct DialHelper {
  Protocol* const protocol;
  event::Task* const task;
  Conn* const out;
  const ProtocolType type;
  const base::FD filedesc;
  std::mutex mu;
  event::Handle evt;
  bool seen;

  DialHelper(Protocol* pr, event::Task* t, Conn* o, ProtocolType p,
             base::FD fd) noexcept : protocol(pr),
                                     task(t),
                                     out(o),
                                     type(p),
                                     filedesc(std::move(fd)),
                                     seen(false) {}

  base::Result handle(event::Data data) {
    base::Result r;

    auto lock = base::acquire_lock(mu);
    if (seen) return base::Result();
    seen = true;
    evt.disable().expect_ok(__FILE__, __LINE__);
    evt.disown();
    lock.unlock();

    sockaddr_storage ss;
    socklen_t sslen;
    Addr la, ra;
    int x, rc;
    socklen_t xlen;

    auto fdpair = filedesc->acquire_fd();

    x = 0;
    xlen = sizeof(x);
    rc = ::getsockopt(fdpair.first, SOL_SOCKET, SO_ERROR, &x, &xlen);
    if (rc != 0) {
      int err_no = errno;
      r = base::Result::from_errno(err_no, "getsockopt(2)");
      goto end;
    }
    CHECK_EQ(xlen, sizeof(x));
    if (x != 0) {
      r = base::Result::from_errno(x, "connect(2)");
      goto end;
    }

    ::bzero(&ss, sizeof(ss));
    sslen = sizeof(ss);
    rc = ::getsockname(fdpair.first, RISA(&ss), &sslen);
    if (rc != 0) {
      int err_no = errno;
      r = base::Result::from_errno(err_no, "getsockname(2)");
      goto end;
    }

    r = protocol->interpret(&la, type, RICSA(&ss), sslen);
    if (!r) goto end;

    ::bzero(&ss, sizeof(ss));
    sslen = sizeof(ss);
    rc = ::getpeername(fdpair.first, RISA(&ss), &sslen);
    if (rc != 0) {
      int err_no = errno;
      r = base::Result::from_errno(err_no, "getpeername(2)");
      goto end;
    }

    r = protocol->interpret(&ra, type, RICSA(&ss), sslen);
    if (!r) goto end;

    VLOG(6) << "net::FDProtocol::dial: fd=" << fdpair.first << ", "
            << "self=" << la << ", "
            << "peer=" << ra;

    r = fdconn(out, la, ra, filedesc);

  end:
    fdpair.second.unlock();
    task->finish(std::move(r));
    return base::Result();
  }
};
}  // anonymous namespace

void FDProtocol::listen(event::Task* task, ListenConn* out, const Addr& bind,
                        const base::Options& opts, AcceptFn fn) {
  CHECK(task);
  CHECK(out);
  CHECK(bind);
  CHECK(fn);
  std::string protocol = bind.protocol();
  CHECK(supports(protocol));
  if (!task->start()) return;

  ProtocolType p = bind.protocol_type();
  int domain, type, protonum;
  std::tie(domain, type, protonum) = socket_triple(protocol);
  int fdnum = ::socket(domain, type | SOCK_NONBLOCK | SOCK_CLOEXEC, protonum);
  if (fdnum == -1) {
    int err_no = errno;
    task->finish(base::Result::from_errno(err_no, "socket(2)"));
    return;
  }
  base::FD fd = base::wrapfd(fdnum);

  const auto ra = opts.get<net::Options>().reuseaddr;
  if (ra) {
    int x = 1;
    base::Result r = sockopt_reuseaddr.set(fd, &x, sizeof(x));
    r.expect_ok(__FILE__, __LINE__);
  }

  bool apply = false;
  int value;
  const auto dl = opts.get<net::Options>().duallisten;
  switch (dl) {
    case DualListen::system_default:
      break;

    case DualListen::v6mapped:
      apply = true;
      value = 0;
      break;

    case DualListen::v6only:
      apply = true;
      value = 1;
      break;

    default:
      LOG(DFATAL) << "BUG! Unknown DualListen value: "
                  << static_cast<uint8_t>(dl);
  }
  if (apply) {
    base::Result r = sockopt_ipv6_v6only.set(fd, &value, sizeof(value));
    r.expect_ok(__FILE__, __LINE__);
  }

  auto raw = bind.raw();
  int rc = ::bind(fdnum, RICSA(raw.first), raw.second);
  if (rc != 0) {
    int err_no = errno;
    task->finish(base::Result::from_errno(err_no, "bind(2)"));
    return;
  }

  sockaddr_storage ss;
  socklen_t sslen = sizeof(ss);
  rc = ::getsockname(fdnum, RISA(&ss), &sslen);
  if (rc != 0) {
    int err_no = errno;
    task->finish(base::Result::from_errno(err_no, "getsockname(2)"));
    return;
  }
  CHECK_GE(sslen, 0U);

  Addr bound;
  base::Result r = interpret(&bound, p, RICSA(&ss), sslen);
  if (!r) {
    task->finish(std::move(r));
    return;
  }

  rc = ::listen(fdnum, 1000);
  if (rc != 0) {
    int err_no = errno;
    task->finish(base::Result::from_errno(err_no, "listen(2)"));
    return;
  }

  r = fdlistenconn(out, self(), std::move(bound), std::move(fd), opts,
                   std::move(fn));
  task->finish(std::move(r));
}

void FDProtocol::dial(event::Task* task, Conn* out, const Addr& peer,
                      const Addr& bind, const base::Options& opts) {
  CHECK(task);
  CHECK(out);
  CHECK(peer);
  std::string protocol = peer.protocol();
  CHECK(supports(protocol));
  CHECK(!bind || bind.protocol() == protocol);
  if (!task->start()) return;

  ProtocolType p = peer.protocol_type();
  int domain, type, protonum;
  std::tie(domain, type, protonum) = socket_triple(protocol);
  int fdnum = ::socket(domain, type | SOCK_NONBLOCK | SOCK_CLOEXEC, protonum);
  if (fdnum == -1) {
    int err_no = errno;
    task->finish(base::Result::from_errno(err_no, "socket(2)"));
    return;
  }
  base::FD fd = base::wrapfd(fdnum);

  if (bind) {
    auto raw = bind.raw();
    int rc = ::bind(fdnum, RICSA(raw.first), raw.second);
    if (rc != 0) {
      int err_no = errno;
      task->finish(base::Result::from_errno(err_no, "bind(2)"));
      return;
    }
  }

  auto h = std::make_shared<DialHelper>(this, task, out, p, fd);
  auto closure = [h](event::Data data) { return h->handle(data); };

  auto raw = peer.raw();
redo:
  int rc = ::connect(fdnum, RICSA(raw.first), raw.second);
  if (rc == 0) {
    closure(event::Data()).ignore_ok();
    return;
  }
  int err_no = errno;
  if (err_no == EINTR) goto redo;
  base::Result r;
  if (err_no == EINPROGRESS) {
    event::Manager m = io::get_manager(opts);
    r = m.fd(&h->evt, fd, event::Set::writable_bit(), event::handler(closure));
    if (r) return;
  } else {
    r = base::Result::from_errno(err_no, "connect(2)");
  }
  task->finish(std::move(r));
}

io::Reader fdconnreader(base::FD fd) {
  CHECK(fd);
  return io::Reader(std::make_shared<FDConnReader>(std::move(fd)));
}

io::Writer fdconnwriter(base::FD fd) {
  CHECK(fd);
  return io::Writer(std::make_shared<FDConnWriter>(std::move(fd)));
}

base::Result fdconn(Conn* out, Addr la, Addr ra, base::FD fd) {
  CHECK(out);
  CHECK(la);
  CHECK(ra);
  CHECK_EQ(la.protocol(), ra.protocol());
  CHECK(fd);

  io::Reader r = fdconnreader(fd);
  io::Writer w = fdconnwriter(std::move(fd));
  auto impl = std::make_shared<FDConn>(std::move(la), std::move(ra),
                                       std::move(r), std::move(w));
  *out = Conn(std::move(impl));
  return base::Result();
}

base::Result fdlistenconn(ListenConn* out, std::shared_ptr<Protocol> pr,
                          Addr aa, base::FD fd, const base::Options& opts,
                          AcceptFn fn) {
  CHECK(out);
  CHECK(pr);
  CHECK(aa);
  CHECK(fd);
  CHECK(fn);
  auto ptr = std::make_shared<FDListenConn>(io::get_manager(opts),
                                            std::move(pr), std::move(aa),
                                            std::move(fd), std::move(fn));
  auto r = ptr->initialize();
  if (r) {
    *out = ListenConn(std::move(ptr));
  }
  return r;
}

}  // namespace net


text:
<?php

/**
 * Returns the extension of the provided file
 *
 * @author Björn Fromme <fromme@dreipunktnull.com>, dreipunktnull
 * @package Vhs
 * @subpackage ViewHelpers\Media
 */
class Tx_Vhs_ViewHelpers_Media_ExtensionViewHelper extends \TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper {

	/**
	 * Initialize arguments.
	 *
	 * @return void
	 * @api
	 */
	public function initializeArguments() {
		$this->registerArgument('file', 'string', 'Path to the file to determine extension for.', TRUE);
	}

	/**
	 * @return string
	 */
	public function render() {

		$filePath = $this->arguments['file'];

		if ($filePath === NULL) {
			$filePath = $this->renderChildren();

			if ($filePath === NULL) {
				return '';
			}
		}

		$file = \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName($filePath);

		$parts = explode('.', basename($file));

		// file has no extension
		if (count($parts) == 1) {
			return '';
		}

		$extension = strtolower(array_pop($parts));

		return $extension;
	}

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Package view</title>
<meta name="date" content="2015-12-04">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Package
view

Packages that use view

Package
Description

controller.client

view

Classes in view used by controller.client

Class and Description

AllChat

Allchat is a panel used to show a discussion with several users

PrivateChat

PrivateChat is a panel that handles the private conversation between two
 users of the same discussion

ServerList

ServerList is a panel that shows all the servers available

Window

Window is the main frame of the application

Classes in view used by view

Class and Description

AllChat

Allchat is a panel used to show a discussion with several users

DiscussionsWindow

DiscussionsTabs handles the different conversations private, public with one
 or several users

ServerList

ServerList is a panel that shows all the servers available

Window

Window is the main frame of the application

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
<?php

class VipChangeRaceTest extends \Tests\TestHelper
{
    public function testExecute()
    {
        $buyer = Mockery::mock("Character");
        $vip = new VipChangeRace;
        $race = "dwarf";

        $this->assertFalse($vip->execute());

        $vip->setAttributes(compact("race"));
        $vip->setBuyer($buyer);

        $buyer->shouldReceive("set_race")->once()->with($race);
        $buyer->shouldReceive("save")->once()->andReturn(true);

        $this->assertTrue($vip->execute());
    }
}


text:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import argparse
import tqdm
#from astropy import log
from loguru import logger as log
from nicer.values import *
from astropy.io import fits
from astropy.table import Table, vstack
import astropy.units as u
from pint.eventstats import hm, z2m, h2sig

def cached_hm(mask):
    nph = mask.sum()
    if nph == 0:
        return 0
    s = (cached_hm._cache[..., mask].sum(axis=2) ** 2).sum(axis=1)
    return (
        (2.0 / nph) * np.cumsum(s) - 4 * np.arange(0, cached_hm._cache.shape[0])
    ).max()

def cached_zm(mask):
    nph = mask.sum()
    if nph == 0:
        return 0
    s = (cached_zm._cache[..., mask].sum(axis=2) ** 2).sum()
    return (2.0 / nph) * s

parser = argparse.ArgumentParser(
    description="Read event file with phase and optimize cuts"
)
parser.add_argument("evfiles", help="Name of event files to process", nargs="+")
parser.add_argument(
    "--minlowE", help="minimum E for the low cut.", default=0.25, type=float
)
parser.add_argument(
    "--maxlowE", help="maximum E for the low cut.", default=4.00, type=float
)
parser.add_argument(
    "--minhighE", help="minimum E for the high cut.", default=None, type=float
)
parser.add_argument(
    "--maxhighE", help="maximum E for the high cut.", default=12.0, type=float
)
parser.add_argument(
    "--steplowE", help="step in energy for the low cut.", default=0.05, type=float
)
parser.add_argument(
    "--stephighE", help="step in energy for the high cut.", default=0.1, type=float
)
parser.add_argument(
    "--noplot", help="Suppress plotting.", action="store_true", default=False
)
parser.add_argument(
    "--grid", help="Shows grid of H-test", action="store_true", default=False
)
parser.add_argument(
    "-n", "--nbins", help="Number of bins of outout profiles", default=16, type=int
)
parser.add_argument(
    "-m",
    "--maxharm",
    help="Search up to harmonic m; [default=20, H-test]",
    default=20,
    type=int,
)
parser.add_argument(
    "-z",
    "--ztest",
    help="Use Z-test rather than H-test; this searches with exactly the number of harmonics specified.  m=1 is Rayleigh, m=2 is Z^2_2, etc.",
    action="store_true",
    default=False,
)
parser.add_argument(
    "--min_good_time",
    help="Ignore files with GTI sum below specified value [default None; unit sec].",
    default=None,
    type=float,
)
args = parser.parse_args()

object = None
tlist = []

for fn in args.evfiles:
    log.info("Reading file {0}".format(fn))
    if object is None:
        try:
            object = fits.open(fn)[0].header["OBJECT"].replace("_"," ")
        except:
            object = "unknown object"
        log.info("Opening events for {}".format(object))
    t = Table.read(fn, hdu=1)
    if len(t) == 0:
        continue
    if args.min_good_time is not None:
        tgti = Table.read(fn, hdu="gti")
        good_time = np.sum(tgti["STOP"] - tgti["START"])
        if good_time < args.min_good_time:
            log.info("Ignoring file {0} with good time {1:0.2f}.".format(fn, good_time))
            continue
    tlist.append(t)

log.info("Concatenating files")
if len(tlist) == 1:
    etable = tlist[0]
else:
    etable = vstack(tlist, metadata_conflicts="silent")
del tlist

m = args.maxharm
ts_func = cached_zm if args.ztest else cached_hm
phasesinitial = etable["PULSE_PHASE"].astype(np.float32)
h_ini = z2m(phasesinitial, m=m)[-1] if args.ztest else hm(phasesinitial, m=m)
hbest = h_ini
eminbest = 0.0
emaxbest = 100.0
ts_name = "Ztest" if args.ztest else "Htest"
if args.ztest:
    log.info(
        "Initial {0} = {1} in range {2:.2f}-{3:.2f} keV ".format(
        ts_name, np.round(hbest, 3),
        min(etable["PI"] * PI_TO_KEV), max(etable["PI"] * PI_TO_KEV)
        )
    )
else:
    log.info(
        "Initial {0} = {1} ({2} sigma) in range {3:.2f}-{4:.2f} keV".format(
            ts_name, np.round(hbest, 3), np.round(h2sig(hbest), 3),
            min(etable["PI"] * PI_TO_KEV), max(etable["PI"] * PI_TO_KEV)
        )
    )

# assemble cache
cache = np.empty([m, 2, len(phasesinitial)], dtype=np.float32)
for i in range(m):
    cache[i, 0] = np.cos(phasesinitial * (2 * np.pi * (i + 1)))
    cache[i, 1] = np.sin(phasesinitial * (2 * np.pi * (i + 1)))
cached_hm._cache = cached_zm._cache = cache

eminlist = []
emaxlist = []
hgrid = []

emins = np.arange(args.minlowE, args.maxlowE + args.steplowE, args.steplowE)

for emin in tqdm.tqdm(emins):

    if args.minhighE is not None:
        minhighE = max(emin + args.steplowE, args.minhighE)
    else:
        minhighE = emin + args.steplowE
    emaxs = np.arange(minhighE, args.maxhighE + args.stephighE, args.stephighE)

    for emax in emaxs:
        mask = np.logical_and(
            etable["PI"] * PI_TO_KEV > emin, etable["PI"] * PI_TO_KEV < emax
        )
        h = ts_func(mask)
        eminlist.append(emin)
        emaxlist.append(emax)
        hgrid.append(h)
        if h >= hbest:
            hbest = h
            eminbest = emin
            emaxbest = emax

if args.ztest:
    log.info("Final {0} = {1}".format(ts_name, np.round(hbest, 3)))
else:
    log.info(
        "Final {0} = {1} ({2} sigma)".format(
            ts_name, np.round(hbest, 3), np.round(h2sig(hbest), 3)
        )
    )
log.info(
    "Best range:  emin {0} keV -- emax {1} keV".format(
        np.round(eminbest, 3), np.round(emaxbest, 3)
    )
)

if not args.noplot:
    profbins = np.linspace(0.0, 1.0, args.nbins + 1, endpoint=True)
    bbins = np.concatenate((profbins, profbins[1:]+1.0, profbins[1:]+2.0))

    # Initial pulse profile
    prof_ini, edges_ini = np.histogram(phasesinitial, bins=profbins)
    fullprof_ini = np.concatenate((prof_ini, prof_ini, prof_ini, np.array([prof_ini[0]])))

    # Optimal pulse profile
    idx = np.where(
        np.logical_and(
            etable["PI"] * PI_TO_KEV > eminbest, etable["PI"] * PI_TO_KEV < emaxbest
        )
    )[0]
    phases = etable["PULSE_PHASE"][idx]
    prof_opt, edges_ini = np.histogram(phases, bins=profbins)
    fullprof_opt = np.concatenate((prof_opt, prof_opt, prof_opt, np.array([prof_opt[0]])))

    fig, ax = plt.subplots()

    ax.errorbar(bbins-(0.5/args.nbins),fullprof_ini,
             yerr=fullprof_ini**0.5,
             marker ='',
             linewidth=1.5,
             color='r',
             label= 'Init. E range ({0} = {1:.2f})'.format(ts_name, np.round(h_ini, 3)),
             drawstyle='steps-mid',
            )

    ax.errorbar(bbins-(0.5/args.nbins),fullprof_opt,
             yerr=fullprof_opt**0.5,
             marker ='',
             linewidth=1.5,
             color='b',
             label= '{:0.2f}-{:0.2f} keV ({} = {:.2f})'.format(eminbest,emaxbest, ts_name, np.round(hbest, 3)),
             drawstyle='steps-mid',
            )

    # ax.text(
    #     0.1,
    #     0.1,
    #     "{0} = {1:.2f}".format(ts_name, np.round(hbest, 3)),
    #     transform=ax.transAxes,
    # )

    ax.set_ylabel("Counts")
    ax.set_xlabel("Pulse Phase")
    ax.set_title("Pulse Profile for {}".format(object))
    ax.set_xlim(0.0, 2.0)
    ax.set_ylim(ax.get_ylim()[0], 1.1*ax.get_ylim()[1])
    ax.legend(loc='best')
    plt.savefig("OptimalProfile_{:.2f}keV_{:.2f}keV.png".format(eminbest,emaxbest),bbox_inches="tight")
    plt.clf()

if args.grid:
    plt.scatter(eminlist, emaxlist, c=hgrid, s=5)
    cbar = plt.colorbar()
    cbar.set_label("H-test")
    plt.title("{} vs energy range for {}".format(ts_name, object))
    plt.xlabel("Low Energy Cut (keV)")
    plt.ylabel("High Energy Cut (keV)")
    plt.savefig('GridSearch.png')


text:
layout: page
title: Vaquero Documentation
permalink: /docs/
---

Everything you ever wanted to know about Vaquero, and more! (or maybe less...)

- [Getting Started](getting_started.html)
- [Plugins](plugins.html)


text:
<!DOCTYPE html>

    <title></title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

Red Raphael

        <form class="form-horizontal col col-md-4">
            <fieldset>

                        <select class="form-control" id="test-select">
                        </select>

            </fieldset>
        </form>
        <button id="test-btn" class="btn btn-default">Run Test</button>
        <button id="pause-anim" class="btn btn-default">pause</button>
        <button id="resume-anim" class="btn btn-default">resume</button>

        <button id="get-attr" class="btn btn-default">attr</button>
        <button id="set-start" class="btn btn-default">setStart</button>
        <button id="anim-saved" class="btn btn-default">Animate saved</button>

        	<textarea style="width: 100%; height: 100%" id="jsontext"></textarea>
        	<button class="btn btn-default" id="jsonupdate">Update</button>


text:
package org.apache.johnzon.jaxrs;

import javax.json.JsonStructure;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.ext.Provider;

@Provider
@Produces({
    "*/json",
    "*/*+json", "*/x-json",
    "*/javascript", "*/x-javascript"
})
@Consumes({
    "*/json",
    "*/*+json", "*/x-json",
    "*/javascript", "*/x-javascript"
})
public class WildcardJsrProvider extends DelegateProvider<JsonStructure> {
    public WildcardJsrProvider() {
        super(new JsrMessageBodyReader(), new JsrMessageBodyWriter());
    }
}


text:
import bootstrap from "bootstrap/dist/js/bootstrap";

// initialization of Tooltips
export default function setTooltip() {
  var tooltipTriggerList = [].slice.call(
    document.querySelectorAll('[data-bs-toggle="tooltip"]')
  );
  // eslint-disable-next-line no-unused-vars
  var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
    return new bootstrap.Tooltip(tooltipTriggerEl);
  });
}


text:
package org.nerdboy.chatbot.brain.lang;

/**
 * Created by xsank.mz on 2016/5/18.
 */
public class Machine implements Language {
    public String translate(String input) {
        return "说人话!我不知道你在说啥";
    }
}


text:
package com.epam.reportportal.auth.oauth;

import org.springframework.security.core.AuthenticationException;

/**
 * In case of user synchronization has failed
 *
 * @author Andrei Varabyeu
 */
public class UserSynchronizationException extends AuthenticationException {

	public UserSynchronizationException(String msg) {
		super(msg);
	}

	public UserSynchronizationException(String msg, Throwable e) {
		super(msg, e);
	}
}