text:
package org.jf.dexlib2.writer.pool;

import com.google.common.base.*;
import com.google.common.collect.*;

import org.jf.dexlib2.*;
import org.jf.dexlib2.builder.*;
import org.jf.dexlib2.iface.*;
import org.jf.dexlib2.iface.debug.*;
import org.jf.dexlib2.iface.instruction.*;
import org.jf.dexlib2.iface.reference.*;
import org.jf.dexlib2.iface.value.*;
import org.jf.dexlib2.immutable.value.*;
import org.jf.dexlib2.util.*;
import org.jf.dexlib2.writer.*;
import org.jf.util.*;

import java.io.*;
import java.util.*;
import java.util.Map.*;

import javax.annotation.*;

public class ClassPool implements ClassSection<CharSequence, CharSequence,
        TypeListPool.Key<? extends Collection<? extends CharSequence>>, PoolClassDef, Field, PoolMethod,
        Set<? extends Annotation>, EncodedValue> {
    private static final Predicate<Field> HAS_INITIALIZER = input -> {
        EncodedValue encodedValue = input.getInitialValue();
        return encodedValue != null && !EncodedValueUtils.isDefaultValue(encodedValue);
    };
    private static final Function<Field, EncodedValue> GET_INITIAL_VALUE = input -> {
        EncodedValue initialValue = input.getInitialValue();
        if (initialValue == null) {
            return ImmutableEncodedValueFactory.defaultValueForType(input.getType());
        }
        return initialValue;
    };
    private static final Predicate<MethodParameter> HAS_PARAMETER_ANNOTATIONS = input -> input.getAnnotations().size() > 0;
    private static final Function<MethodParameter, Set<? extends Annotation>> PARAMETER_ANNOTATIONS =
        input -> input.getAnnotations();
    @Nonnull
    private final StringPool stringPool;
    @Nonnull
    private final TypePool typePool;
    @Nonnull
    private final FieldPool fieldPool;
    @Nonnull
    private final MethodPool methodPool;
    @Nonnull
    private final AnnotationSetPool annotationSetPool;
    @Nonnull
    private final TypeListPool typeListPool;
    @Nonnull
    private HashMap<String, PoolClassDef> internedItems = Maps.newHashMap();
    private ImmutableList<PoolClassDef> sortedClasses = null;

    public ClassPool(@Nonnull StringPool stringPool,
                     @Nonnull TypePool typePool,
                     @Nonnull FieldPool fieldPool,
                     @Nonnull MethodPool methodPool,
                     @Nonnull AnnotationSetPool annotationSetPool,
                     @Nonnull TypeListPool typeListPool) {
        this.stringPool = stringPool;
        this.typePool = typePool;
        this.fieldPool = fieldPool;
        this.methodPool = methodPool;
        this.annotationSetPool = annotationSetPool;
        this.typeListPool = typeListPool;
    }

    public void intern(@Nonnull ClassDef classDef) {
        PoolClassDef poolClassDef = new PoolClassDef(classDef);

        PoolClassDef prev = internedItems.put(poolClassDef.getType(), poolClassDef);
        if (prev != null) {
            throw new ExceptionWithContext("Class %s has already been interned", poolClassDef.getType());
        }

        typePool.intern(poolClassDef.getType());
        typePool.internNullable(poolClassDef.getSuperclass());
        typeListPool.intern(poolClassDef.getInterfaces());
        stringPool.internNullable(poolClassDef.getSourceFile());

        HashSet<String> fields = new HashSet<String>();
        for (Field field : poolClassDef.getFields()) {
            String fieldDescriptor = ReferenceUtil.getShortFieldDescriptor(field);
            if (!fields.add(fieldDescriptor)) {
                throw new ExceptionWithContext("Multiple definitions for field %s->%s",
                        poolClassDef.getType(), fieldDescriptor);
            }
            fieldPool.intern(field);

            EncodedValue initialValue = field.getInitialValue();
            if (initialValue != null) {
                DexPool.internEncodedValue(initialValue, stringPool, typePool, fieldPool, methodPool);
            }

            annotationSetPool.intern(field.getAnnotations());
        }

        HashSet<String> methods = new HashSet<String>();
        for (PoolMethod method : poolClassDef.getMethods()) {
            String methodDescriptor = ReferenceUtil.getShortMethodDescriptor(method);
            if (!methods.add(methodDescriptor)) {
                throw new ExceptionWithContext("Multiple definitions for method %s->%s",
                        poolClassDef.getType(), methodDescriptor);
            }
            methodPool.intern(method);
            internCode(method);
            internDebug(method);
            annotationSetPool.intern(method.getAnnotations());

            for (MethodParameter parameter : method.getParameters()) {
                annotationSetPool.intern(parameter.getAnnotations());
            }
        }

        annotationSetPool.intern(poolClassDef.getAnnotations());
    }

    private void internCode(@Nonnull Method method) {
        // this also handles parameter names, which aren't directly tied to the MethodImplementation, even though the debug items are
        boolean hasInstruction = false;

        MethodImplementation methodImpl = method.getImplementation();
        if (methodImpl != null) {
            for (Instruction instruction : methodImpl.getInstructions()) {
                hasInstruction = true;
                if (instruction instanceof ReferenceInstruction) {
                    Reference reference = ((ReferenceInstruction) instruction).getReference();
                    switch (instruction.getOpcode().referenceType) {
                        case ReferenceType.STRING:
                            stringPool.intern((StringReference) reference);
                            break;
                        case ReferenceType.TYPE:
                            typePool.intern((TypeReference) reference);
                            break;
                        case ReferenceType.FIELD:
                            fieldPool.intern((FieldReference) reference);
                            break;
                        case ReferenceType.METHOD:
                            methodPool.intern((MethodReference) reference);
                            break;
                        default:
                            throw new ExceptionWithContext("Unrecognized reference type: %d",
                                    instruction.getOpcode().referenceType);
                    }
                }
            }

            List<? extends TryBlock> tryBlocks = methodImpl.getTryBlocks();
            if (!hasInstruction && tryBlocks.size() > 0) {
                throw new ExceptionWithContext("Method %s has no instructions, but has try blocks.",
                        ReferenceUtil.getMethodDescriptor(method));
            }

            for (TryBlock<? extends ExceptionHandler> tryBlock : methodImpl.getTryBlocks()) {
                for (ExceptionHandler handler : tryBlock.getExceptionHandlers()) {
                    typePool.internNullable(handler.getExceptionType());
                }
            }
        }
    }

    private void internDebug(@Nonnull Method method) {
        for (MethodParameter param : method.getParameters()) {
            String paramName = param.getName();
            if (paramName != null) {
                stringPool.intern(paramName);
            }
        }

        MethodImplementation methodImpl = method.getImplementation();
        if (methodImpl != null) {
            for (DebugItem debugItem : methodImpl.getDebugItems()) {
                switch (debugItem.getDebugItemType()) {
                    case DebugItemType.START_LOCAL:
                        StartLocal startLocal = (StartLocal) debugItem;
                        stringPool.internNullable(startLocal.getName());
                        typePool.internNullable(startLocal.getType());
                        stringPool.internNullable(startLocal.getSignature());
                        break;
                    case DebugItemType.SET_SOURCE_FILE:
                        stringPool.internNullable(((SetSourceFile) debugItem).getSourceFile());
                        break;
                }
            }
        }
    }

    @Nonnull
    @Override
    public Collection<? extends PoolClassDef> getSortedClasses() {
        if (sortedClasses == null) {
            sortedClasses = Ordering.natural().immutableSortedCopy(internedItems.values());
        }
        return sortedClasses;
    }

    @Nullable
    @Override
    public Map.Entry<? extends PoolClassDef, Integer> getClassEntryByType(@Nullable CharSequence name) {
        if (name == null) {
            return null;
        }

        final PoolClassDef classDef = internedItems.get(name.toString());
        if (classDef == null) {
            return null;
        }

        return new Map.Entry<PoolClassDef, Integer>() {
            @Override
            public PoolClassDef getKey() {
                return classDef;
            }

            @Override
            public Integer getValue() {
                return classDef.classDefIndex;
            }

            @Override
            public Integer setValue(Integer value) {
                return classDef.classDefIndex = value;
            }
        };
    }

    @Nonnull
    @Override
    public CharSequence getType(@Nonnull PoolClassDef classDef) {
        return classDef.getType();
    }

    @Override
    public int getAccessFlags(@Nonnull PoolClassDef classDef) {
        return classDef.getAccessFlags();
    }

    @Nullable
    @Override
    public CharSequence getSuperclass(@Nonnull PoolClassDef classDef) {
        return classDef.getSuperclass();
    }

    @Nullable
    @Override
    public TypeListPool.Key<SortedSet<String>> getSortedInterfaces(@Nonnull PoolClassDef classDef) {
        return classDef.interfaces;
    }

    @Nullable
    @Override
    public CharSequence getSourceFile(@Nonnull PoolClassDef classDef) {
        return classDef.getSourceFile();
    }

    @Nullable
    @Override
    public Collection<? extends EncodedValue> getStaticInitializers(
            @Nonnull PoolClassDef classDef) {
        final SortedSet<Field> sortedStaticFields = classDef.getStaticFields();

        final int lastIndex = CollectionUtils.lastIndexOf(sortedStaticFields, HAS_INITIALIZER);
        if (lastIndex > -1) {
            return new AbstractCollection<EncodedValue>() {
                @Nonnull
                @Override
                public Iterator<EncodedValue> iterator() {
                    return FluentIterable.from(sortedStaticFields)
                            .limit(lastIndex + 1)
                            .transform(GET_INITIAL_VALUE).iterator();
                }

                @Override
                public int size() {
                    return lastIndex + 1;
                }
            };
        }
        return null;
    }

    @Nonnull
    @Override
    public Collection<? extends Field> getSortedStaticFields(@Nonnull PoolClassDef classDef) {
        return classDef.getStaticFields();
    }

    @Nonnull
    @Override
    public Collection<? extends Field> getSortedInstanceFields(@Nonnull PoolClassDef classDef) {
        return classDef.getInstanceFields();
    }

    @Nonnull
    @Override
    public Collection<? extends Field> getSortedFields(@Nonnull PoolClassDef classDef) {
        return classDef.getFields();
    }

    @Nonnull
    @Override
    public Collection<PoolMethod> getSortedDirectMethods(@Nonnull PoolClassDef classDef) {
        return classDef.getDirectMethods();
    }

    @Nonnull
    @Override
    public Collection<PoolMethod> getSortedVirtualMethods(@Nonnull PoolClassDef classDef) {
        return classDef.getVirtualMethods();
    }

    @Nonnull
    @Override
    public Collection<? extends PoolMethod> getSortedMethods(@Nonnull PoolClassDef classDef) {
        return classDef.getMethods();
    }

    @Override
    public int getFieldAccessFlags(@Nonnull Field field) {
        return field.getAccessFlags();
    }

    @Override
    public int getMethodAccessFlags(@Nonnull PoolMethod method) {
        return method.getAccessFlags();
    }

    @Nullable
    @Override
    public Set<? extends Annotation> getClassAnnotations(@Nonnull PoolClassDef classDef) {
        Set<? extends Annotation> annotations = classDef.getAnnotations();
        if (annotations.size() == 0) {
            return null;
        }
        return annotations;
    }

    @Nullable
    @Override
    public Set<? extends Annotation> getFieldAnnotations(@Nonnull Field field) {
        Set<? extends Annotation> annotations = field.getAnnotations();
        if (annotations.size() == 0) {
            return null;
        }
        return annotations;
    }

    @Nullable
    @Override
    public Set<? extends Annotation> getMethodAnnotations(@Nonnull PoolMethod method) {
        Set<? extends Annotation> annotations = method.getAnnotations();
        if (annotations.size() == 0) {
            return null;
        }
        return annotations;
    }

    @Nullable
    @Override
    public List<? extends Set<? extends Annotation>> getParameterAnnotations(
            @Nonnull final PoolMethod method) {
        final List<? extends MethodParameter> parameters = method.getParameters();
        boolean hasParameterAnnotations = Iterables.any(parameters, HAS_PARAMETER_ANNOTATIONS);

        if (hasParameterAnnotations) {
            return new AbstractForwardSequentialList<Set<? extends Annotation>>() {
                @Nonnull
                @Override
                public Iterator<Set<? extends Annotation>> iterator() {
                    return FluentIterable.from(parameters)
                            .transform(PARAMETER_ANNOTATIONS).iterator();
                }

                @Override
                public int size() {
                    return parameters.size();
                }
            };
        }
        return null;
    }

    @Nullable
    @Override
    public Iterable<? extends DebugItem> getDebugItems(@Nonnull PoolMethod method) {
        MethodImplementation impl = method.getImplementation();
        if (impl != null) {
            return impl.getDebugItems();
        }
        return null;
    }

    @Nullable
    @Override
    public Iterable<CharSequence> getParameterNames(@Nonnull PoolMethod method) {
        return Iterables.transform(method.getParameters(), new Function<MethodParameter, CharSequence>() {
            @Nullable
            @Override
            public CharSequence apply(MethodParameter input) {
                return input.getName();
            }
        });
    }

    @Override
    public int getRegisterCount(@Nonnull PoolMethod method) {
        MethodImplementation impl = method.getImplementation();
        if (impl != null) {
            return impl.getRegisterCount();
        }
        return 0;
    }

    @Nullable
    @Override
    public Iterable<? extends Instruction> getInstructions(@Nonnull PoolMethod method) {
        MethodImplementation impl = method.getImplementation();
        if (impl != null) {
            return impl.getInstructions();
        }
        return null;
    }

    @Nonnull
    @Override
    public List<? extends TryBlock<? extends ExceptionHandler>> getTryBlocks(
            @Nonnull PoolMethod method) {
        MethodImplementation impl = method.getImplementation();
        if (impl != null) {
            return impl.getTryBlocks();
        }
        return ImmutableList.of();
    }

    @Nullable
    @Override
    public CharSequence getExceptionType(@Nonnull ExceptionHandler handler) {
        return handler.getExceptionType();
    }

    @Nonnull
    @Override
    public MutableMethodImplementation makeMutableMethodImplementation(@Nonnull PoolMethod poolMethod) {
        return new MutableMethodImplementation(poolMethod.getImplementation());
    }

    @Override
    public void setEncodedArrayOffset(@Nonnull PoolClassDef classDef, int offset) {
        classDef.encodedArrayOffset = offset;
    }

    @Override
    public int getEncodedArrayOffset(@Nonnull PoolClassDef classDef) {
        return classDef.encodedArrayOffset;
    }

    @Override
    public void setAnnotationDirectoryOffset(@Nonnull PoolClassDef classDef, int offset) {
        classDef.annotationDirectoryOffset = offset;
    }

    @Override
    public int getAnnotationDirectoryOffset(@Nonnull PoolClassDef classDef) {
        return classDef.annotationDirectoryOffset;
    }

    @Override
    public void setAnnotationSetRefListOffset(@Nonnull PoolMethod method, int offset) {
        method.annotationSetRefListOffset = offset;

    }

    @Override
    public int getAnnotationSetRefListOffset(@Nonnull PoolMethod method) {
        return method.annotationSetRefListOffset;
    }

    @Override
    public void setCodeItemOffset(@Nonnull PoolMethod method, int offset) {
        method.codeItemOffset = offset;
    }

    @Override
    public int getCodeItemOffset(@Nonnull PoolMethod method) {
        return method.codeItemOffset;
    }

    @Override
    public void writeDebugItem(@Nonnull DebugWriter<CharSequence, CharSequence> writer,
                               DebugItem debugItem) throws IOException {
        switch (debugItem.getDebugItemType()) {
            case DebugItemType.START_LOCAL: {
                StartLocal startLocal = (StartLocal) debugItem;
                writer.writeStartLocal(startLocal.getCodeAddress(),
                        startLocal.getRegister(),
                        startLocal.getName(),
                        startLocal.getType(),
                        startLocal.getSignature());
                break;
            }
            case DebugItemType.END_LOCAL: {
                EndLocal endLocal = (EndLocal) debugItem;
                writer.writeEndLocal(endLocal.getCodeAddress(), endLocal.getRegister());
                break;
            }
            case DebugItemType.RESTART_LOCAL: {
                RestartLocal restartLocal = (RestartLocal) debugItem;
                writer.writeRestartLocal(restartLocal.getCodeAddress(), restartLocal.getRegister());
                break;
            }
            case DebugItemType.PROLOGUE_END: {
                writer.writePrologueEnd(debugItem.getCodeAddress());
                break;
            }
            case DebugItemType.EPILOGUE_BEGIN: {
                writer.writeEpilogueBegin(debugItem.getCodeAddress());
                break;
            }
            case DebugItemType.LINE_NUMBER: {
                LineNumber lineNumber = (LineNumber) debugItem;
                writer.writeLineNumber(lineNumber.getCodeAddress(), lineNumber.getLineNumber());
                break;
            }
            case DebugItemType.SET_SOURCE_FILE: {
                SetSourceFile setSourceFile = (SetSourceFile) debugItem;
                writer.writeSetSourceFile(setSourceFile.getCodeAddress(), setSourceFile.getSourceFile());
            }
            default:
                throw new ExceptionWithContext("Unexpected debug item type: %d", debugItem.getDebugItemType());
        }
    }

    @Override
    public int getItemIndex(@Nonnull PoolClassDef classDef) {
        return classDef.classDefIndex;
    }

    @Nonnull
    @Override
    public Collection<? extends Map.Entry<PoolClassDef, Integer>> getItems() {
        class MapEntry implements Map.Entry<PoolClassDef, Integer> {
            @Nonnull
            private final PoolClassDef classDef;

            public MapEntry(@Nonnull PoolClassDef classDef) {
                this.classDef = classDef;
            }

            @Override
            public PoolClassDef getKey() {
                return classDef;
            }

            @Override
            public Integer getValue() {
                return classDef.classDefIndex;
            }

            @Override
            public Integer setValue(Integer value) {
                int prev = classDef.classDefIndex;
                classDef.classDefIndex = value;
                return prev;
            }
        }

        return new AbstractCollection<Entry<PoolClassDef, Integer>>() {
            @Nonnull
            @Override
            public Iterator<Entry<PoolClassDef, Integer>> iterator() {
                return new Iterator<Entry<PoolClassDef, Integer>>() {
                    Iterator<PoolClassDef> iter = internedItems.values().iterator();

                    @Override
                    public boolean hasNext() {
                        return iter.hasNext();
                    }

                    @Override
                    public Entry<PoolClassDef, Integer> next() {
                        return new MapEntry(iter.next());
                    }

                    @Override
                    public void remove() {
                        throw new UnsupportedOperationException();
                    }
                };
            }

            @Override
            public int size() {
                return internedItems.size();
            }
        };
    }
}


text:
package com.akasiyanik.interview.ch4.pr1;

/**
 * Brute-force algorithm
 * Complexity - O(n), n - word size
 * We store result mod 2 (using ~ XOR operator)
 *
 * @author akasiyanik
 *         6/21/17
 */
class BruteForceParityCalculator implements BinaryWordParityCalculator {

    /**
     * @param x - 64-bit integer
     * @return 0 if parity else 1
     */
    @Override
    public short parity(long x) {
        long number = x;
        short result = 0;
        while (number != 0) {
            result ^= (number & 1);
            number >>>= 1;
        }
        return result;
    }
}

redpajama_set_name: RedPajamaGithub


text:
1.2.0 / 2018-12-09
==================

  * Version bump
  * 1.2.0
  * Build
  * 1.1.2 changelog commit
  * Updates readme
  * Fixed default options
  * Merge pull request [#18](https://github.com/samturrell/vue-breadcrumbs/issues/18) from HermannBjorgvin/optional-component
    Added option to disable global component
  * Changed option to 'registerComponent'
  * Made the global breadcrumbs component optional
    This commit makes the global breadcrumbs component optional by setting options.skipComponent to true.

1.1.2 / 2017-06-27
==================

  * 1.1.2
  * Builds assets

1.1.1 / 2017-06-16
==================

  * 1.1.1
  * Added options parameter to docs

1.1.0 / 2017-06-16
==================

  * 1.1.0
  * Merge pull request [#10](https://github.com/samturrell/vue-breadcrumbs/issues/10) from CasperLaiTW/support-options
    Support options for overwriting default configure
  * Support options for overwriting default configure
  * Updates README to piint to live example, and update example to v-cloak content
  * analytics on example
  * removed ga
  * Linked up buttons
  * analytics
  * link to demo
  * Docs on main site
  * Fixed Script location
  * Docs folder
  * Version bump and updated changelog

1.0.0 / 2017-04-30
==================

  * 1.0.0
  * Fixed config indentation
  * Updated readme to reflect v2 update
  * Vue 2.0 functionality
  * Merge pull request [#2](https://github.com/samturrell/vue-breadcrumbs/issues/2) from limonte/patch-1
    Improve markdown to highlight code
  * Improve markdown to highlight code

0.3.1 / 2016-05-15
==================

  * 0.3.1
  * Property not method
  * Added changelog generator
  * Updated readme

0.3.0 / 2016-05-14
==================

  * Version bump
  * 0.3.0
  * Added actual readme and example

0.2.2 / 2016-04-17
==================

  * 0.2.2
  * Create README.md

0.2.1 / 2016-04-17
==================

  * 0.2.1
  * Removed name

0.2.0 / 2016-04-17
==================

  * 0.2.0
  * removed vueify
  * Removed debug

0.1.0 / 2016-04-17
==================

  * 0.1.0
  * Added repo
  * Initial commit


text:
class Post < ActiveRecord::Base
  validates :user_id, presence: true
  validates :content, presence: true

  # This will allow order_by_created_at to work, as well as order_by_created_at(:asc)
  scope :order_by_created_at, -> (direction = :desc) { order(created_at: direction) }
  has_many :replies, dependent: :destroy
  belongs_to :user
  belongs_to :group
  belongs_to :event
end


text:
class Micropython < Formula
  desc "Python implementation for microcontrollers and constrained systems"
  homepage "https://www.micropython.org/"
  url "https://github.com/micropython/micropython/archive/v1.7.tar.gz"
  sha256 "ad44d28700d346ceb9a70ae92d36306d42e187fc1af19fa2c7a3ab7dc18742ef"

  bottle do
    cellar :any
    sha256 "811bdee93e7d2c4dfcaed11437b540b3473e6a1e7ccec08b573c2601afb21176" => :el_capitan
    sha256 "b2c3ccfd452ad15f6840dd3efd7706cd7bd19769920467534e23b0ea2107108a" => :yosemite
    sha256 "78c2a5e5280c047e0f8aa1e20cb22f0ee31f41aa7287b718d36c10d80c76ae67" => :mavericks
  end

  depends_on "pkg-config" => :build
  depends_on "libffi"  # Requires libffi v3 closure API; OS X version is too old

  # The install command in the Makefile uses GNU coreutils syntax
  # which is incompatible with BSD's install and needs patching
  # https://github.com/micropython/micropython/issues/1984
  patch :DATA

  def install
    cd "unix" do
      system "make", "install", "PREFIX=#{prefix}", "V=1"
    end
  end

  test do
    # Test the FFI module
    (testpath/"ffi-hello.py").write <<-EOS.undent
      import ffi

      libc = ffi.open("libc.dylib")
      printf = libc.func("v", "printf", "s")
      printf("Hello!\\n")
    EOS

    system "#{bin}/micropython", "ffi-hello.py"
  end
end

__END__
diff --git a/unix/Makefile b/unix/Makefile
index 6d6239f..c556473 100644
--- a/unix/Makefile
+++ b/unix/Makefile
@@ -186,8 +186,9 @@ PIPSRC = ../tools/pip-micropython
 PIPTARGET = pip-micropython

 install: micropython
-	install -D $(TARGET) $(BINDIR)/$(TARGET)
-	install -D $(PIPSRC) $(BINDIR)/$(PIPTARGET)
+	install -d $(BINDIR)
+	install $(TARGET) $(BINDIR)/$(TARGET)
+	install $(PIPSRC) $(BINDIR)/$(PIPTARGET)

 # uninstall micropython
 uninstall:


text:
using System.Collections.Generic;
using Equinox.Domain.Core.Events;

namespace Equinox.Domain.Core.Notifications
{
    public interface IDomainNotificationHandler<T> : IHandler<T> where T : Message
    {
        bool HasNotifications();
        List<T> GetNotifications();
    }
}


text:
using AutoFixture.Xunit2;
using ComposableAsync.Resilient.Test.Helper;
using FluentAssertions;
using NSubstitute;
using System;
using System.Threading.Tasks;
using Xunit;

namespace ComposableAsync.Resilient.Test
{
    public class CircuitBreakerPolicyTests
    {
        private readonly IDispatcher _ForAll;

        private readonly Action _FakeAction;
        private readonly Func<int> _FakeFunction;
        private readonly Func<Task> _FakeTask;
        private readonly Func<Task<int>> _FakeTaskT;

        private const int ShortTimeOut = 100;
        private const int LongTimeOut = 2000;

        public CircuitBreakerPolicyTests()
        {
            _FakeAction = Substitute.For<Action>();
            _FakeTask = Substitute.For<Func<Task>>();
            _FakeFunction = Substitute.For<Func<int>>();
            _FakeTaskT = Substitute.For<Func<Task<int>>>();
            _ForAll = GetForAllShortTimeOut(5);
        }

        [Fact]
        public async Task ForAllException_Enqueue_Action_Call_Action()
        {
            await _ForAll.Enqueue(_FakeAction);

            _FakeAction.Received(1).Invoke();
        }

        [Theory, AutoData]
        public async Task ForAllException_Enqueue_Func_Call_Func(int result)
        {
            _FakeFunction.Invoke().Returns(result);
            var actual = await _ForAll.Enqueue(_FakeFunction);

            actual.Should().Be(result);
            _FakeFunction.Received(1).Invoke();
        }

        [Fact]
        public async Task ForAllException_Enqueue_Task_Call_Func_Task()
        {
            await _ForAll.Enqueue(_FakeTask);

            await _FakeTask.Received(1).Invoke();
        }

        [Theory, AutoData]
        public async Task ForAllException_Enqueue_Task_Call_Func_Task_T(int result)
        {
            _FakeTaskT.Invoke().Returns(Task.FromResult(result));
            var actual = await _ForAll.Enqueue(_FakeTaskT);

            actual.Should().Be(result);
            await _FakeTaskT.Received(1).Invoke();
        }

        [Theory]
        [InlineData(typeof(ArgumentException))]
        [InlineData(typeof(ArgumentNullException))]
        [InlineData(typeof(SystemException))]
        [InlineData(typeof(Exception))]
        public async Task ForAllException_Enqueue_Action_Rethrow_Exception(Type exceptionType)
        {
            _FakeAction.SetUpExceptions(1, exceptionType);
            Func<Task> @do = async () => await _ForAll.Enqueue(_FakeAction);

            await @do.Should().ThrowAsync(exceptionType);
        }

        [Theory]
        [InlineData(typeof(ArgumentException))]
        [InlineData(typeof(ArgumentNullException))]
        [InlineData(typeof(SystemException))]
        [InlineData(typeof(Exception))]
        public async Task ForAllException_Enqueue_Func_Rethrow_Exception(Type exceptionType)
        {
            _FakeFunction.SetUpExceptions(1, 7, exceptionType);
            Func<Task<int>> @do = async () => await _ForAll.Enqueue(_FakeFunction);

            await @do.Should().ThrowAsync(exceptionType);
        }

        [Theory]
        [InlineData(typeof(ArgumentException))]
        [InlineData(typeof(ArgumentNullException))]
        [InlineData(typeof(SystemException))]
        [InlineData(typeof(Exception))]
        public async Task ForAllException_Enqueue_Task_Rethrow_Exception(Type exceptionType)
        {
            _FakeTask.SetUpExceptions(1, exceptionType);
            Func<Task> @do = async () => await _ForAll.Enqueue(_FakeTask);

            await @do.Should().ThrowAsync(exceptionType);
        }

        [Theory]
        [InlineData(typeof(ArgumentException))]
        [InlineData(typeof(ArgumentNullException))]
        [InlineData(typeof(SystemException))]
        [InlineData(typeof(Exception))]
        public async Task ForAllException_Enqueue_Task_T_Rethrow_Exception(Type exceptionType)
        {
            _FakeTaskT.SetUpExceptions(1, 4, exceptionType);
            Func<Task<int>> @do = async () => await _ForAll.Enqueue(_FakeTaskT);

            await @do.Should().ThrowAsync(exceptionType);
        }

        [Theory]
        [InlineData(typeof(ArgumentException), 1)]
        [InlineData(typeof(ArgumentNullException), 3)]
        [InlineData(typeof(SystemException), 2)]
        [InlineData(typeof(Exception), 1)]
        public async Task ForAllException_Enqueue_Action_Reach_Open_State_When_MaxAttempts_Reached(Type exceptionType, int maxAttempts)
        {
            _FakeAction.SetUpExceptions(10, exceptionType);
            var circuitBreaker = GetForAllLongTimeOut(maxAttempts);
            Func<Task> @do = async () => await circuitBreaker.Enqueue(_FakeAction);

            await RetryAndExpectException(@do, maxAttempts, exceptionType);

            _FakeAction.Received(maxAttempts).Invoke();
            _FakeAction.ClearReceivedCalls();

            await @do.Should().ThrowAsync<CircuitBreakerOpenException>();
            _FakeAction.DidNotReceive().Invoke();
        }

        [Theory]
        [InlineData(typeof(ArgumentException), 1)]
        [InlineData(typeof(ArgumentNullException), 3)]
        [InlineData(typeof(SystemException), 2)]
        [InlineData(typeof(Exception), 1)]
        public async Task ForAllException_Enqueue_Func_Reach_Open_State_When_MaxAttempts_Reached(Type exceptionType, int maxAttempts)
        {
            _FakeFunction.SetUpExceptions(10, 7, exceptionType);
            var circuitBreaker = GetForAllLongTimeOut(maxAttempts);
            Func<Task<int>> @do = async () => await circuitBreaker.Enqueue(_FakeFunction);

            await RetryAndExpectException(@do, maxAttempts, exceptionType);

            _FakeFunction.Received(maxAttempts).Invoke();
            _FakeFunction.ClearReceivedCalls();

            await @do.Should().ThrowAsync<CircuitBreakerOpenException>();
            _FakeFunction.DidNotReceive().Invoke();
        }

        [Theory]
        [InlineData(typeof(ArgumentException), 1)]
        [InlineData(typeof(ArgumentNullException), 3)]
        [InlineData(typeof(SystemException), 2)]
        [InlineData(typeof(Exception), 1)]
        public async Task ForAllException_Enqueue_Task_Reach_Open_State_When_MaxAttempts_Reached(Type exceptionType, int maxAttempts)
        {
            _FakeTask.SetUpExceptions(10, exceptionType);
            var circuitBreaker = GetForAllLongTimeOut(maxAttempts);
            Func<Task> @do = async () => await circuitBreaker.Enqueue(_FakeTask);

            await RetryAndExpectException(@do, maxAttempts, exceptionType);
            await _FakeTask.Received(maxAttempts).Invoke();
            _FakeTask.ClearReceivedCalls();

            await @do.Should().ThrowAsync<CircuitBreakerOpenException>();
            await _FakeTask.DidNotReceive().Invoke();
        }

        [Theory]
        [InlineData(typeof(ArgumentException), 1)]
        [InlineData(typeof(ArgumentNullException), 3)]
        [InlineData(typeof(SystemException), 2)]
        [InlineData(typeof(Exception), 1)]
        public async Task ForAllException_Enqueue_Task_T_Reach_Open_State_When_MaxAttempts_Reached(Type exceptionType, int maxAttempts)
        {
            _FakeTaskT.SetUpExceptions(10, 7, exceptionType);
            var circuitBreaker = GetForAllLongTimeOut(maxAttempts);
            Func<Task<int>> @do = async () => await circuitBreaker.Enqueue(_FakeTaskT);

            await RetryAndExpectException(@do, maxAttempts, exceptionType);
            await _FakeTaskT.Received(maxAttempts).Invoke();
            _FakeTaskT.ClearReceivedCalls();

            await @do.Should().ThrowAsync<CircuitBreakerOpenException>();
            await _FakeTaskT.DidNotReceive().Invoke();
        }

        [Theory]
        [InlineData(typeof(ArgumentException), 1)]
        [InlineData(typeof(ArgumentNullException), 3)]
        [InlineData(typeof(SystemException), 2)]
        [InlineData(typeof(Exception), 1)]
        public async Task ForAllException_Enqueue_Action_Stay_Open_During_Time_Out(Type exceptionType, int maxAttempts)
        {
            _FakeAction.SetUpExceptions(10, exceptionType);
            var circuitBreaker = GetForAllLongTimeOut(maxAttempts);
            async Task Do() => await circuitBreaker.Enqueue(_FakeAction);

            await RetryAndExpectException(Do, maxAttempts, exceptionType);
            _FakeAction.ClearReceivedCalls();

            await AssertStayOpen(Do, 5);
            _FakeAction.DidNotReceive().Invoke();
        }

        [Theory]
        [InlineData(typeof(ArgumentException), 1)]
        [InlineData(typeof(ArgumentNullException), 3)]
        [InlineData(typeof(SystemException), 2)]
        [InlineData(typeof(Exception), 1)]
        public async Task ForAllException_Enqueue_Func_Stay_Open_During_Time_Out(Type exceptionType, int maxAttempts)
        {
            _FakeFunction.SetUpExceptions(10, 7, exceptionType);
            var circuitBreaker = GetForAllLongTimeOut(maxAttempts);
            async Task Do() => await circuitBreaker.Enqueue(_FakeFunction);

            await RetryAndExpectException(Do, maxAttempts, exceptionType);
            _FakeFunction.ClearReceivedCalls();

            await AssertStayOpen(Do, 5);
            _FakeFunction.DidNotReceive().Invoke();
        }

        [Theory]
        [InlineData(typeof(ArgumentException), 1)]
        [InlineData(typeof(ArgumentNullException), 3)]
        [InlineData(typeof(SystemException), 2)]
        [InlineData(typeof(Exception), 1)]
        public async Task ForAllException_Enqueue_Task_Stay_Open_During_Time_Out(Type exceptionType, int maxAttempts)
        {
            _FakeTask.SetUpExceptions(10, exceptionType);
            var circuitBreaker = GetForAllLongTimeOut(maxAttempts);
            async Task Do() => await circuitBreaker.Enqueue(_FakeTask);

            await RetryAndExpectException(Do, maxAttempts, exceptionType);
            _FakeTask.ClearReceivedCalls();

            await AssertStayOpen(Do, 5);
            await _FakeTask.DidNotReceive().Invoke();
        }

        [Theory]
        [InlineData(typeof(ArgumentException), 1)]
        [InlineData(typeof(ArgumentNullException), 3)]
        [InlineData(typeof(SystemException), 2)]
        [InlineData(typeof(Exception), 1)]
        public async Task ForAllException_Enqueue_Task_T_Stay_Open_During_Time_Out(Type exceptionType, int maxAttempts)
        {

            _FakeTaskT.SetUpExceptions(10, 55, exceptionType);
            var circuitBreaker = GetForAllLongTimeOut(maxAttempts);
            async Task Do() => await circuitBreaker.Enqueue(_FakeTaskT);

            await RetryAndExpectException(Do, maxAttempts, exceptionType);
            _FakeTaskT.ClearReceivedCalls();

            await AssertStayOpen(Do, 5);
            await _FakeTaskT.DidNotReceive().Invoke();
        }

        [Theory]
        [InlineData(typeof(ArgumentException), 1)]
        [InlineData(typeof(ArgumentNullException), 3)]
        [InlineData(typeof(SystemException), 2)]
        [InlineData(typeof(Exception), 1)]
        public async Task ForAllException_Enqueue_Action_Retry_After_Time_Out(Type exceptionType, int maxAttempts)
        {
            _FakeAction.SetUpExceptions(10, exceptionType);
            var circuitBreaker = GetForAllShortTimeOut(maxAttempts);
            Func<Task> Do = async () => await circuitBreaker.Enqueue(_FakeAction);

            await RetryAndExpectException(Do, maxAttempts, exceptionType);
            _FakeAction.ClearReceivedCalls();
            await Task.Delay(ShortTimeOut);

            await Do.Should().ThrowAsync(exceptionType);
            _FakeAction.Received(1).Invoke();
        }

        [Theory]
        [InlineData(typeof(ArgumentException), 1)]
        [InlineData(typeof(ArgumentNullException), 3)]
        [InlineData(typeof(SystemException), 2)]
        [InlineData(typeof(Exception), 1)]
        public async Task ForAllException_Enqueue_Func_Retry_After_Time_Out(Type exceptionType, int maxAttempts)
        {
            _FakeFunction.SetUpExceptions(10, 7, exceptionType);
            var circuitBreaker = GetForAllShortTimeOut(maxAttempts);
            Func<Task> Do = async () => await circuitBreaker.Enqueue(_FakeFunction);

            await RetryAndExpectException(Do, maxAttempts, exceptionType);
            _FakeFunction.ClearReceivedCalls();
            await Task.Delay(ShortTimeOut);

            await Do.Should().ThrowAsync(exceptionType);
            _FakeFunction.Received(1).Invoke();
        }

        [Theory]
        [InlineData(typeof(ArgumentException), 1)]
        [InlineData(typeof(ArgumentNullException), 3)]
        [InlineData(typeof(SystemException), 2)]
        [InlineData(typeof(Exception), 1)]
        public async Task ForAllException_Enqueue_Task_Retry_After_Time_Out(Type exceptionType, int maxAttempts)
        {
            _FakeTask.SetUpExceptions(10, exceptionType);
            var circuitBreaker = GetForAllShortTimeOut(maxAttempts);
            Func<Task> Do = async () => await circuitBreaker.Enqueue(_FakeTask);

            await RetryAndExpectException(Do, maxAttempts, exceptionType);
            _FakeTask.ClearReceivedCalls();
            await Task.Delay(ShortTimeOut);

            await Do.Should().ThrowAsync(exceptionType);
            await _FakeTask.Received(1).Invoke();
        }

        [Theory]
        [InlineData(typeof(ArgumentException), 1)]
        [InlineData(typeof(ArgumentNullException), 3)]
        [InlineData(typeof(SystemException), 2)]
        [InlineData(typeof(Exception), 1)]
        public async Task ForAllException_Enqueue_Task_T_Retry_After_Time_Out(Type exceptionType, int maxAttempts)
        {
            _FakeTaskT.SetUpExceptions(10, 55, exceptionType);
            var circuitBreaker = GetForAllShortTimeOut(maxAttempts);
            Func<Task> Do = async () => await circuitBreaker.Enqueue(_FakeTaskT);

            await RetryAndExpectException(Do, maxAttempts, exceptionType);
            _FakeTaskT.ClearReceivedCalls();
            await Task.Delay(ShortTimeOut);

            await Do.Should().ThrowAsync(exceptionType);
            await _FakeTaskT.Received(1).Invoke();
        }

        [Theory]
        [InlineData(typeof(ArgumentException), 1)]
        [InlineData(typeof(ArgumentNullException), 3)]
        public async Task ForException_Enqueue_Action_Reach_Open_State_When_MaxAttempts_Reached(Type exceptionType, int maxAttempts)
        {
            _FakeAction.SetUpExceptions(10, exceptionType);
            var circuitBreaker = GetShortTimeOut<ArgumentException>(maxAttempts);
            Func<Task> @do = async () => await circuitBreaker.Enqueue(_FakeAction);

            await RetryAndExpectException(@do, maxAttempts, exceptionType);

            _FakeAction.Received(maxAttempts).Invoke();
            _FakeAction.ClearReceivedCalls();

            await @do.Should().ThrowAsync<CircuitBreakerOpenException>();
            _FakeAction.DidNotReceive().Invoke();
        }

        [Theory]
        [InlineData(typeof(BadImageFormatException), 3)]
        [InlineData(typeof(SystemException), 2)]
        [InlineData(typeof(Exception), 1)]
        public async Task ForException_Enqueue_Action_Do_Not_Reach_Open_State_When_Exception_Is_Not_Matching(Type exceptionType, int maxAttempts)
        {
            _FakeAction.SetUpExceptions(10, exceptionType);
            var circuitBreaker = GetShortTimeOut<ArgumentException>(maxAttempts);
            Func<Task> @do = async () => await circuitBreaker.Enqueue(_FakeAction);

            await RetryAndExpectException(@do, maxAttempts, exceptionType);

            _FakeAction.Received(maxAttempts).Invoke();
            _FakeAction.ClearReceivedCalls();

            await @do.Should().ThrowAsync(exceptionType);
            _FakeAction.Received(1).Invoke();
        }

        [Theory]
        [InlineAutoData(typeof(ArgumentException), 1)]
        [InlineAutoData(typeof(Exception), 3)]
        public async Task ForExceptionFilter_Enqueue_Action_Reach_Open_State_When_MaxAttempts_Reached(Type exceptionType, int maxAttempts, string message)
        {
            var exception = (Exception)Activator.CreateInstance(exceptionType, message);
            _FakeAction.SetUpExceptions(10, exception);
            var circuitBreaker = GetCircuitBreaker(maxAttempts, message, LongTimeOut);
            Func<Task> @do = async () => await circuitBreaker.Enqueue(_FakeAction);

            await RetryAndExpectException(@do, maxAttempts, exceptionType);

            _FakeAction.Received(maxAttempts).Invoke();
            _FakeAction.ClearReceivedCalls();

            await @do.Should().ThrowAsync<CircuitBreakerOpenException>();
            _FakeAction.DidNotReceive().Invoke();
        }

        [Theory]
        [InlineAutoData(typeof(BadImageFormatException), 3)]
        [InlineAutoData(typeof(SystemException), 2)]
        [InlineAutoData(typeof(Exception), 1)]
        public async Task ForExceptionFilter_Enqueue_Action_Do_Not_Reach_Open_State_When_Exception_Is_Not_Matching(Type exceptionType, int maxAttempts, string message)
        {
            var exception = (Exception)Activator.CreateInstance(exceptionType, $"{message}-different");
            _FakeAction.SetUpExceptions(10, exception);
            var circuitBreaker = GetCircuitBreaker(maxAttempts, message, LongTimeOut);
            Func<Task> @do = async () => await circuitBreaker.Enqueue(_FakeAction);

            await RetryAndExpectException(@do, maxAttempts, exceptionType);

            _FakeAction.Received(maxAttempts).Invoke();
            _FakeAction.ClearReceivedCalls();

            await @do.Should().ThrowAsync(exceptionType);
            _FakeAction.Received(1).Invoke();
        }

        [Theory]
        [InlineAutoData(1)]
        [InlineAutoData(3)]
        public async Task ForExceptionFilterGeneric_Enqueue_Action_Reach_Open_State_When_MaxAttempts_Reached(int maxAttempts, string message)
        {
            var exception = new ArgumentException(message);
            _FakeAction.SetUpExceptions(10, exception);
            var circuitBreaker = GetCircuitBreaker<ArgumentException>(maxAttempts, message, LongTimeOut);
            Func<Task> @do = async () => await circuitBreaker.Enqueue(_FakeAction);

            await RetryAndExpectException(@do, maxAttempts, exception.GetType());

            _FakeAction.Received(maxAttempts).Invoke();
            _FakeAction.ClearReceivedCalls();

            await @do.Should().ThrowAsync<CircuitBreakerOpenException>();
            _FakeAction.DidNotReceive().Invoke();
        }

        [Theory]
        [InlineAutoData(3)]
        [InlineAutoData(2)]
        [InlineAutoData(1)]
        public async Task ForExceptionFilterGeneric_Enqueue_Action_Do_Not_Reach_Open_State_When_Exception_Is_Not_Matching_Filter(int maxAttempts, string message)
        {
            var exception = new ArgumentException($"{message}-suffix");
            _FakeAction.SetUpExceptions(10, exception);
            var circuitBreaker = GetCircuitBreaker<ArgumentException>(maxAttempts, message, LongTimeOut);
            Func<Task> @do = async () => await circuitBreaker.Enqueue(_FakeAction);

            await RetryAndExpectException(@do, maxAttempts, exception.GetType());

            _FakeAction.Received(maxAttempts).Invoke();
            _FakeAction.ClearReceivedCalls();

            await @do.Should().ThrowAsync(exception.GetType());
            _FakeAction.Received(1).Invoke();
        }

        [Theory]
        [InlineAutoData(typeof(BadImageFormatException), 3)]
        [InlineAutoData(typeof(SystemException), 2)]
        [InlineAutoData(typeof(Exception), 1)]
        public async Task ForExceptionFilterGeneric_Enqueue_Action_Do_Not_Reach_Open_State_When_Exception_Is_Not_Matching(Type exceptionType, int maxAttempts, string message)
        {
            var exception = (Exception)Activator.CreateInstance(exceptionType, message);
            _FakeAction.SetUpExceptions(10, exception);
            var circuitBreaker = GetCircuitBreaker<ArgumentException>(maxAttempts, message, LongTimeOut);
            Func<Task> @do = async () => await circuitBreaker.Enqueue(_FakeAction);

            await RetryAndExpectException(@do, maxAttempts, exceptionType);

            _FakeAction.Received(maxAttempts).Invoke();
            _FakeAction.ClearReceivedCalls();

            await @do.Should().ThrowAsync(exceptionType);
            _FakeAction.Received(1).Invoke();
        }

        [Theory]
        [InlineData(typeof(BadImageFormatException), 1)]
        [InlineData(typeof(ArgumentNullException), 3)]
        public async Task ForException_And_Enqueue_Action_Reach_Open_State_When_MaxAttempts_Reached(Type exceptionType, int maxAttempts)
        {
            _FakeAction.SetUpExceptions(10, exceptionType);
            var circuitBreaker = CircuitBreakerPolicy.For<BadImageFormatException>().And<ArgumentNullException>().WithRetryAndTimeout(maxAttempts, ShortTimeOut);
            Func<Task> @do = async () => await circuitBreaker.Enqueue(_FakeAction);

            await RetryAndExpectException(@do, maxAttempts, exceptionType);

            _FakeAction.Received(maxAttempts).Invoke();
            _FakeAction.ClearReceivedCalls();

            await @do.Should().ThrowAsync<CircuitBreakerOpenException>();
            _FakeAction.DidNotReceive().Invoke();
        }

        [Theory]
        [InlineData(typeof(ArgumentException), 3)]
        [InlineData(typeof(SystemException), 2)]
        [InlineData(typeof(Exception), 1)]
        public async Task ForException_And_Enqueue_Action_Do_Not_Reach_Open_State_When_Exception_Is_Not_Matching(Type exceptionType, int maxAttempts)
        {
            _FakeAction.SetUpExceptions(10, exceptionType);
            var circuitBreaker = CircuitBreakerPolicy.For<BadImageFormatException>().And<ArgumentNullException>().WithRetryAndTimeout(maxAttempts, TimeSpan.FromMilliseconds(ShortTimeOut));

            Func<Task> @do = async () => await circuitBreaker.Enqueue(_FakeAction);

            await RetryAndExpectException(@do, maxAttempts, exceptionType);

            _FakeAction.Received(maxAttempts).Invoke();
            _FakeAction.ClearReceivedCalls();

            await @do.Should().ThrowAsync(exceptionType);
            _FakeAction.Received(1).Invoke();
        }

        [Theory]
        [InlineData(typeof(ArgumentException), 1)]
        [InlineData(typeof(ArgumentNullException), 3)]
        [InlineData(typeof(SystemException), 2)]
        [InlineData(typeof(Exception), 1)]
        public async Task ForAllException_DoNotThrowForVoid_Enqueue_Action_Do_Not_Throw_When_Reach_Open_State_When_MaxAttempts_Reached(Type exceptionType, int maxAttempts)
        {
            _FakeAction.SetUpExceptions(10, exceptionType);
            var circuitBreaker = CircuitBreakerPolicy.ForAllException().DoNotThrowForVoid().WithRetryAndTimeout(maxAttempts, LongTimeOut);

            Func<Task> @do = async () => await circuitBreaker.Enqueue(_FakeAction);

            await RetryAndExpectException(@do, maxAttempts, exceptionType);

            _FakeAction.Received(maxAttempts).Invoke();
            _FakeAction.ClearReceivedCalls();

            await @do.Should().NotThrowAsync();
            _FakeAction.DidNotReceive().Invoke();
        }

        [Theory]
        [InlineData(typeof(ArgumentException), 1)]
        [InlineData(typeof(ArgumentNullException), 3)]
        [InlineData(typeof(SystemException), 2)]
        [InlineData(typeof(Exception), 1)]
        public async Task ForAllException_DoNotThrowForVoid_Enqueue_Task_Do_Not_Throw_When_Reach_Open_State_When_MaxAttempts_Reached(Type exceptionType, int maxAttempts)
        {
            _FakeTask.SetUpExceptions(10, exceptionType);
            var circuitBreaker = CircuitBreakerPolicy.ForAllException().DoNotThrowForVoid().WithRetryAndTimeout(maxAttempts, TimeSpan.FromMilliseconds(ShortTimeOut));

            Func<Task> @do = async () => await circuitBreaker.Enqueue(_FakeTask);

            await RetryAndExpectException(@do, maxAttempts, exceptionType);

            await _FakeTask.Received(maxAttempts).Invoke();
            _FakeTask.ClearReceivedCalls();

            await @do.Should().NotThrowAsync();
            await _FakeTask.DidNotReceive().Invoke();
        }

        [Theory]
        [InlineData(typeof(ArgumentException), 1)]
        [InlineData(typeof(ArgumentNullException), 3)]
        [InlineData(typeof(SystemException), 2)]
        public async Task ForException_DoNotThrowForVoid_Enqueue_Task_Do_Not_Throw_When_Reach_Open_State_When_MaxAttempts_Reached(Type exceptionType, int maxAttempts)
        {
            _FakeTask.SetUpExceptions(10, exceptionType);
            var circuitBreaker = CircuitBreakerPolicy.For<SystemException>().DoNotThrowForVoid().WithRetryAndTimeout(maxAttempts, TimeSpan.FromMilliseconds(LongTimeOut));

            Func<Task> @do = async () => await circuitBreaker.Enqueue(_FakeTask);

            await RetryAndExpectException(@do, maxAttempts, exceptionType);

            await _FakeTask.Received(maxAttempts).Invoke();
            _FakeTask.ClearReceivedCalls();

            await @do.Should().NotThrowAsync();
            await _FakeTask.DidNotReceive().Invoke();
        }

        [Theory]
        [InlineData(typeof(ArgumentException), 1)]
        [InlineData(typeof(ArgumentNullException), 3)]
        [InlineData(typeof(SystemException), 2)]
        [InlineData(typeof(Exception), 1)]
        public async Task ForAllException_DoNotThrowForVoid_Enqueue_Func_Do_Throw_When_Reach_Open_State_When_MaxAttempts_Reached(Type exceptionType, int maxAttempts)
        {
            _FakeFunction.SetUpExceptions(10, 5, exceptionType);
            var circuitBreaker = CircuitBreakerPolicy.ForAllException().DoNotThrowForVoid().WithRetryAndTimeout(maxAttempts, LongTimeOut);

            Func<Task> @do = async () => await circuitBreaker.Enqueue(_FakeFunction);

            await RetryAndExpectException(@do, maxAttempts, exceptionType);

            _FakeFunction.Received(maxAttempts).Invoke();
            _FakeFunction.ClearReceivedCalls();

            await @do.Should().ThrowAsync<CircuitBreakerOpenException>();
            _FakeFunction.DidNotReceive().Invoke();
        }

        [Theory]
        [InlineData(typeof(ArgumentException), 1)]
        [InlineData(typeof(ArgumentNullException), 3)]
        [InlineData(typeof(SystemException), 2)]
        [InlineData(typeof(Exception), 1)]
        public async Task ForAllException_ReturnsDefaultWhenOpen_Enqueue_Func_Return_Default_When_Reach_Open_State_When_MaxAttempts_Reached(Type exceptionType, int maxAttempts)
        {
            _FakeFunction.SetUpExceptions(10, 50, exceptionType);
            var circuitBreaker = CircuitBreakerPolicy.ForAllException().ReturnsDefaultWhenOpen().WithRetryAndTimeout(maxAttempts, LongTimeOut);

            async Task Do() => await circuitBreaker.Enqueue(_FakeFunction);

            await RetryAndExpectException(Do, maxAttempts, exceptionType);

            _FakeFunction.Received(maxAttempts).Invoke();
            _FakeFunction.ClearReceivedCalls();

            var res = await circuitBreaker.Enqueue(_FakeFunction);
            _FakeFunction.DidNotReceive().Invoke();
            res.Should().Be(0);
        }

        [Theory]
        [InlineData(typeof(ArgumentException), 1)]
        [InlineData(typeof(ArgumentNullException), 3)]
        [InlineData(typeof(SystemException), 2)]
        public async Task ForException_ReturnsDefaultWhenOpen_Enqueue_Func_Return_Default_When_Reach_Open_State_When_MaxAttempts_Reached(Type exceptionType, int maxAttempts)
        {
            _FakeFunction.SetUpExceptions(10, 50, exceptionType);
            var circuitBreaker = CircuitBreakerPolicy.For<SystemException>().ReturnsDefaultWhenOpen().WithRetryAndTimeout(maxAttempts, LongTimeOut);

            async Task Do() => await circuitBreaker.Enqueue(_FakeFunction);

            await RetryAndExpectException(Do, maxAttempts, exceptionType);

            _FakeFunction.Received(maxAttempts).Invoke();
            _FakeFunction.ClearReceivedCalls();

            var res = await circuitBreaker.Enqueue(_FakeFunction);
            _FakeFunction.DidNotReceive().Invoke();
            res.Should().Be(0);
        }

        [Theory]
        [InlineAutoData(typeof(ArgumentException), 1)]
        [InlineAutoData(typeof(ArgumentNullException), 3)]
        [InlineAutoData(typeof(SystemException), 2)]
        public async Task ForException_ReturnsWhenOpen_Enqueue_Func_Return_Value_When_Reach_Open_State_When_MaxAttempts_Reached(Type exceptionType, int maxAttempts, int expected)
        {
            _FakeFunction.SetUpExceptions(10, 50, exceptionType);
            var circuitBreaker = CircuitBreakerPolicy.For<SystemException>().ReturnsWhenOpen(expected).WithRetryAndTimeout(maxAttempts, LongTimeOut);

            async Task Do() => await circuitBreaker.Enqueue(_FakeFunction);

            await RetryAndExpectException(Do, maxAttempts, exceptionType);

            _FakeFunction.Received(maxAttempts).Invoke();
            _FakeFunction.ClearReceivedCalls();

            var res = await circuitBreaker.Enqueue(_FakeFunction);
            _FakeFunction.DidNotReceive().Invoke();
            res.Should().Be(expected);
        }

        [Theory]
        [InlineAutoData(typeof(ArgumentException), 1)]
        [InlineAutoData(typeof(ArgumentNullException), 3)]
        [InlineAutoData(typeof(SystemException), 2)]
        public async Task ForException_ReturnsWhenOpen_2_Enqueue_Func_Return_Value_When_Reach_Open_State_When_MaxAttempts_Reached(Type exceptionType, int maxAttempts, int expectedInt, string expectedString)
        {
            string Explode() => throw new SystemException();
            _FakeFunction.SetUpExceptions(10, 50, exceptionType);
            var circuitBreaker = CircuitBreakerPolicy.For<SystemException>().ReturnsWhenOpen(expectedInt).ReturnsWhenOpen(expectedString).WithRetryAndTimeout(maxAttempts, LongTimeOut);

            async Task Do() => await circuitBreaker.Enqueue(_FakeFunction);

            await RetryAndExpectException(Do, maxAttempts, exceptionType);

            _FakeFunction.Received(maxAttempts).Invoke();
            _FakeFunction.ClearReceivedCalls();

            var res = await circuitBreaker.Enqueue((Func<string>) Explode);
            _FakeFunction.DidNotReceive().Invoke();
            res.Should().Be(expectedString);

            var resInt = await circuitBreaker.Enqueue(_FakeFunction);
            _FakeFunction.DidNotReceive().Invoke();
            resInt.Should().Be(expectedInt);
        }

        [Theory]
        [InlineAutoData(typeof(ArgumentException), 1)]
        [InlineAutoData(typeof(ArgumentNullException), 3)]
        [InlineAutoData(typeof(SystemException), 2)]
        public async Task ForException_ReturnsWhenOpen_ReturnsDefaultWhenOpen_Enqueue_Func_Return_Value_When_Reach_Open_State_When_MaxAttempts_Reached(Type exceptionType, int maxAttempts, string expectedString)
        {
            _FakeFunction.SetUpExceptions(10, 50, exceptionType);
            var circuitBreaker = CircuitBreakerPolicy.For<SystemException>().ReturnsDefaultWhenOpen().ReturnsWhenOpen(expectedString).WithRetryAndTimeout(maxAttempts, LongTimeOut);

            async Task Do() => await circuitBreaker.Enqueue(_FakeFunction);

            await RetryAndExpectException(Do, maxAttempts, exceptionType);

            _FakeFunction.Received(maxAttempts).Invoke();
            _FakeFunction.ClearReceivedCalls();

            var resInt = await circuitBreaker.Enqueue(_FakeFunction);
            _FakeFunction.DidNotReceive().Invoke();
            resInt.Should().Be(0);
        }

        [Theory]
        [InlineData(typeof(ArgumentException), 1)]
        [InlineData(typeof(ArgumentNullException), 3)]
        [InlineData(typeof(SystemException), 2)]
        [InlineData(typeof(Exception), 1)]
        public async Task ForAllException_ReturnsDefaultWhenOpen_Enqueue_Task_T_Return_Default_When_Reach_Open_State_When_MaxAttempts_Reached(Type exceptionType, int maxAttempts)
        {
            _FakeTaskT.SetUpExceptions(10, 50, exceptionType);
            var circuitBreaker = CircuitBreakerPolicy.ForAllException().ReturnsDefaultWhenOpen().WithRetryAndTimeout(maxAttempts, LongTimeOut);

            async Task Do() => await circuitBreaker.Enqueue(_FakeTaskT);

            await RetryAndExpectException(Do, maxAttempts, exceptionType);

            await _FakeTaskT.Received(maxAttempts).Invoke();
            _FakeTaskT.ClearReceivedCalls();

            var res = await circuitBreaker.Enqueue(_FakeTaskT);
            await _FakeTaskT.DidNotReceive().Invoke();
            res.Should().Be(0);
        }

        private static async Task RetryAndExpectException<T>(Func<Task<T>> action, int replay, Type expected)
        {
            for (var count = 0; count < replay; count++)
            {
                await action.Should().ThrowAsync(expected);
            }
        }

        private static async Task RetryAndExpectException(Func<Task> action, int replay, Type expected)
        {
            for (var count = 0; count < replay; count++)
            {
                await action.Should().ThrowAsync(expected);
            }
        }

        private static async Task AssertStayOpen(Func<Task> action, int replay)
        {
            for (var count = 0; count < replay; count++)
            {
                await action.Should().ThrowAsync<CircuitBreakerOpenException>();
            }
        }

        private static IDispatcher GetForAllShortTimeOut(int maxAttempts)
        {
            return GetForAll(maxAttempts, ShortTimeOut);
        }

        private static IDispatcher GetForAllLongTimeOut(int maxAttempts)
        {
            return GetForAll(maxAttempts, LongTimeOut);
        }

        private static IDispatcher GetForAll(int maxAttempts, int timeOut)
        {
            return CircuitBreakerPolicy.ForAllException().WithRetryAndTimeout(maxAttempts, timeOut);
        }

        private static IDispatcher GetShortTimeOut<T>(int maxAttempts) where T : Exception
        {
            return GetCircuitBreaker<T>(maxAttempts, ShortTimeOut);
        }

        private static IDispatcher GetCircuitBreaker<T>(int maxAttempts, int timeOut) where T : Exception
        {
            return CircuitBreakerPolicy.For<T>().WithRetryAndTimeout(maxAttempts, timeOut);
        }

        private static IDispatcher GetCircuitBreaker(int maxAttempts, string message, int timeOut)
        {
            return CircuitBreakerPolicy.ForException(ex => ex.Message == message).WithRetryAndTimeout(maxAttempts, timeOut);
        }

        private static IDispatcher GetCircuitBreaker<T>(int maxAttempts, string message, int timeOut) where T : Exception
        {
            return CircuitBreakerPolicy.For<T>(ex => ex.Message == message).WithRetryAndTimeout(maxAttempts, timeOut);
        }
    }
}


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.test.util;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.content.Context;
import android.os.Bundle;
import android.test.InstrumentationTestCase;
import android.text.TextUtils;

import org.chromium.sync.signin.ChromeSigninController;
import org.chromium.sync.test.util.AccountHolder;
import org.chromium.sync.test.util.MockAccountManager;

import java.io.IOException;

/**
 *  A tool used for running tests as signed in.
 */
public class ChromeSigninUtils {
    /** Bundle tags */
    private static final String USERNAME = "username";
    private static final String PASSWORD = "password";
    private static final String ALLOW_SKIP = "allowSkip";

    /** Information for Google OS account */
    private static final String GOOGLE_ACCOUNT_TYPE = "com.google";

    private AccountManager mAccountManager;
    private MockAccountManager mMockAccountManager;
    private Context mContext;
    private Context mTargetContext;

    /**
     * The constructor for SigninUtils for a given test case.
     *
     * @param testCase the test case to perform signin operations with.
     */
    public ChromeSigninUtils(InstrumentationTestCase testCase) {
        mContext = testCase.getInstrumentation().getContext();
        mTargetContext = testCase.getInstrumentation().getTargetContext();
        mAccountManager = AccountManager.get(mContext);
        mMockAccountManager = new MockAccountManager(mContext, mTargetContext);
    }

    /**
     * Adds an account to the app.
     *
     * @param username the username for the logged in account; must be a Google account.
     */
    public void addAccountToApp(String username) {
        if (TextUtils.isEmpty(username)) {
            throw new IllegalArgumentException("ERROR: must specify account");
        }

        if (ChromeSigninController.get(mContext).isSignedIn()) {
            ChromeSigninController.get(mContext).clearSignedInUser();
        }
        ChromeSigninController.get(mContext).setSignedInAccountName(username);
    }

    /**
     * Adds a fake account to the OS.
     */
    public void addFakeAccountToOs(String username, String password) {
        if (TextUtils.isEmpty(username)) {
            throw new IllegalArgumentException("ERROR: must specify account");
        }

        Account account = new Account(username, GOOGLE_ACCOUNT_TYPE);
        mMockAccountManager = new MockAccountManager(mContext, mTargetContext, account);
        AccountHolder accountHolder = new AccountHolder.Builder()
                .account(account)
                .password(password)
                .build();
        mMockAccountManager.addAccountHolderExplicitly(accountHolder);
    }

    /**
     * Removes all fake accounts from the OS.
     */
    public void removeAllFakeAccountsFromOs() {
        for (Account acct : mMockAccountManager.getAccountsByType(GOOGLE_ACCOUNT_TYPE)) {
            mMockAccountManager.removeAccountHolderExplicitly(
                    new AccountHolder.Builder().account(acct).build(), true);
        }
    }

    /**
     * Checks if an existing fake account is on the OS.
     *
     * @param username the username of the account you want to check if signed in
     * @return {@code true} if fake account is on OS, false otherwise.
     */
    public boolean isExistingFakeAccountOnOs(String username) {
        if (mMockAccountManager.getAccountsByType(GOOGLE_ACCOUNT_TYPE).length == 0) {
            return false;
        }

        for (Account acct : mMockAccountManager.getAccountsByType(GOOGLE_ACCOUNT_TYPE)) {
            if (username.equals(acct.name)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Adds a Google account to the OS.
     *
     * @param username the username for the logged in account; must be a Google account.
     * @param password the password for the username specified
     * @param googleAccountType the account type to log into (e.g. @gmail.com accounts use "mail")
     */
    public void addGoogleAccountToOs(String username, String password, String googleAccountType) {
        final Bundle options = new Bundle();
        options.putString(USERNAME, username);
        options.putString(PASSWORD, password);
        options.putBoolean(ALLOW_SKIP, true);

        AuthenticationCallback authCallback = new AuthenticationCallback();
        mAccountManager.addAccount(GOOGLE_ACCOUNT_TYPE, googleAccountType, null, options, null,
                authCallback, null);

        Bundle authResult = authCallback.waitForAuthCompletion();

        if (authResult.containsKey(AccountManager.KEY_ERROR_CODE)) {
            throw new IllegalStateException(String.format("AddAccount failed. Reason: %s",
                    authResult.get(AccountManager.KEY_ERROR_MESSAGE)));
        }
    }

    /**
     * Checks to see if an existing Google account is on OS.
     *
     * @param username the username of the account you want to check if signed in
     * @return {@code true} if one or more Google accounts exists on OS, {@code false} otherwise
     */
    public boolean isExistingGoogleAccountOnOs(String username) {
        if (mAccountManager.getAccountsByType(GOOGLE_ACCOUNT_TYPE).length == 0) {
            return false;
        }

        for (Account acct : mAccountManager.getAccountsByType(GOOGLE_ACCOUNT_TYPE)) {
            if (username.equals(acct.name)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Removes all Google accounts from the OS.
     */
    public void removeAllGoogleAccountsFromOs() {
        for (Account acct : mAccountManager.getAccountsByType(GOOGLE_ACCOUNT_TYPE)) {
            mAccountManager.removeAccount(acct, null, null);
        }
    }

    /**
     * Helper class for adding Google accounts to OS.
     *
     * Usage: Use this as the callback parameter when using {@link addAccount} in
     * {@link android.accounts.AccountManager}.
     */
    private static class AuthenticationCallback implements AccountManagerCallback<Bundle> {
        private final Object mAuthenticationCompletionLock = new Object();

        /** Stores the result of account authentication. Null means not finished. */
        private Bundle mResultBundle = null;

        /**
         * Block and wait for the authentication callback to complete.
         *
         * @return the {@link Bundle} result from the authentication.
         */
        public Bundle waitForAuthCompletion() {
            synchronized (mAuthenticationCompletionLock) {
                while (mResultBundle == null) {
                    try {
                        mAuthenticationCompletionLock.wait();
                    } catch (InterruptedException e) {
                        // ignore
                    }
                }
                return mResultBundle;
            }
        }

        public void run(AccountManagerFuture<Bundle> future) {
            Bundle resultBundle;
            try {
                resultBundle = future.getResult();
            } catch (OperationCanceledException e) {
                resultBundle = buildExceptionBundle(e);
            } catch (IOException e) {
                resultBundle = buildExceptionBundle(e);
            } catch (AuthenticatorException e) {
                resultBundle = buildExceptionBundle(e);
            }
            synchronized (mAuthenticationCompletionLock) {
                mResultBundle = resultBundle;
                mAuthenticationCompletionLock.notify();
            }
        }

        /**
         * Create a result bundle for a given exception.
         *
         * @param e the exception to be made into a {@link Bundle}
         * @return the {@link Bundle} for the given exception e.
         */
        private Bundle buildExceptionBundle(Exception e) {
            Bundle bundle = new Bundle();
            bundle.putInt(AccountManager.KEY_ERROR_CODE,
                    AccountManager.ERROR_CODE_INVALID_RESPONSE);
            bundle.putString(AccountManager.KEY_ERROR_MESSAGE, e.toString());
            return bundle;
        }
    }
}


text:
SAPI
####

``puppet-php`` currently supports the SAPIs shown below.

Common arguments
----------------

These arguments are available for all SAPIs, though their defaults may be
different across SAPIs.

* ``$ensure`` defaults to ``installed``.

* ``$package`` default depends on SAPI.

* ``$provider``` default to ``undef``.

* ``$inifile`` default depends on SAPI.

* ``$settings`` defaults to ``[ ]`` (empty array).

php::apache
-----------

Installs the ``mod_php`` PHP SAPI for apache.

* ``$package`` defaults to ``libapache2-mod-php5``.

* ``$inifile`` defaults to ``/etc/php5/apache2/php.ini``.

* ``$service_name`` defaults to ``apache2``.

.. note ::

  This class will **not** install Apache for you, please use a relevant module
  for that.

php::fpm
--------

Installs the ``FPM`` PHP SAPI.

* ``$package`` defaults to ``php5-fpm``.

* ``$inifile`` defaults to ``/etc/php5/fpm/php.ini``.

* ``$service_name`` defaults to ``php5-fpm``.

* ``$service_ensure`` defaults to ``running``.

* ``$service_enable`` defaults to ``true``.

* ``$service_has_status`` defaults to ``true``.

php::cli
--------

Installs the ``CLI`` PHP SAPI.

* ``$package`` defaults to ``php5-cli``.

* ``$inifile`` defaults to ``/etc/php5/cli/php.ini``.


text:
<?php
/**
 * Hush Framework
 *
 * @category   Hush
 * @package    Hush_Mail
 * @author     James.Huang <shagoo@gmail.com>
 * @license    http://www.apache.org/licenses/LICENSE-2.0
 * @version    $Id$
 */

/**
 * @see Hush_Exception
 */
require_once 'Hush/Exception.php';

/**
 * @package Hush_Mail
 */
class Hush_Mail_Exception extends Hush_Exception
{

}


text:
*=======================================================================
*
* WCSLIB 4.24 - an implementation of the FITS WCS standard.
* Copyright (C) 1995-2014, Mark Calabretta
*
* This file is part of WCSLIB.
*
* WCSLIB is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* WCSLIB is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with WCSLIB.  If not, see http://www.gnu.org/licenses.
*
* Direct correspondence concerning WCSLIB to mark@calabretta.id.au
*
* Author: Mark Calabretta, Australia Telescope National Facility, CSIRO.
* http://www.atnf.csiro.au/people/Mark.Calabretta
* $Id: spx_data.f,v 4.24 2014/09/18 15:25:01 mcalabre Exp $
*=======================================================================

      BLOCK DATA SPX_BLOCK_DATA

      CHARACTER SPX_ERRMSG(0:4)*80

      COMMON /SPX_DATA/ SPX_ERRMSG

      DATA SPX_ERRMSG /
     :  'Success',
     :  'Null spxprm pointer passed',
     :  'Invalid spectral parameters',
     :  'Invalid spectral variable',
     :  'One or more of the inspec coordinates were invalid'/

      END


text:
import styled from "styled-components";

import { StyledLink } from "./Link";

const Brand = styled(StyledLink)`
  float:left;
  font-size: 16px;
  font-weight: bold;

  padding: 11px 14px;

  margin-right: 20px;

  &:hover {
    color: #f2f2f2;
  }
`;

export default Brand;


text:
package org.elasticsearch.legacygeo;

import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
import org.elasticsearch.plugins.ExtensiblePlugin;
import org.elasticsearch.plugins.Plugin;

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

public class LegacyGeoPlugin extends Plugin implements ExtensiblePlugin {

    @Override
    public List<NamedWriteableRegistry.Entry> getNamedWriteables() {
        if (ShapesAvailability.JTS_AVAILABLE && ShapesAvailability.SPATIAL4J_AVAILABLE) {
            return new ArrayList<>(GeoShapeType.getShapeWriteables());

        }
        return Collections.emptyList();
    }

}


text:
import os
import posixpath
import stat
from urllib.parse import unquote

from django import template
from django.conf import settings
from django.contrib.staticfiles import finders, storage

register = template.Library()

STATIC_URL_CACHE = {}

@register.simple_tag
def freshstatic(path):
    """
    A template tag that returns the URL to a file using staticfiles storage
    backend.

    Example::

        <link rel="stylesheet" type="text/css" href="{% freshstatic "css/reset.css" %}" />

    Note: The staticfiles finder is expected to find the file on which
    os.stat can be run.

    The last modification time is then appended to the resulting URL.
    This has the advantage that the HTTP Expires header can be set to infinite
    and the browsers get different URL each time the file changes.

    Note 2: As the URLs here are cached on the per-process level, it is
    required the Django application is restarted in production each time
    any static file changes the content.
    """
    url = STATIC_URL_CACHE.get(path)
    if url is None:
        # Call the same method the original staticfiles 'static' tag does.
        url = storage.staticfiles_storage.url(path)

        # Get the real file abs path and its timestamp.
        normalized_path = posixpath.normpath(unquote(path)).lstrip('/')
        absolute_path = finders.find(normalized_path)

        if absolute_path:
            modtime = os.stat(absolute_path)[stat.ST_MTIME]
            url += '?%d' % modtime

        elif not getattr(settings, 'FRESHSTATIC_CAN_BE_MISSING', None):
            raise RuntimeError("Static file %s not found." % path)

        if not settings.DEBUG:
            # Save to cache (only when not developing).
            STATIC_URL_CACHE[path] = url

    return url


text:
//
//  FDSerialUnarchiver.m
//  FDSerialArchiverDemo
//
//  Created by Florian Denis on 23/12/13.
//  Copyright (c) 2013 Florian Denis. All rights reserved.
//

#import "FDSerialUnarchiver.h"
#import "FDSerialCommons.h"

#if !__has_feature(objc_arc)
#error FDSerialArchiver needs ARC
#endif

@interface FDSerialUnarchiver (){
    NSData *_data;                          // Reference to the NSData to read
    const char *_bytes;                     // Pointer to the current position in the NSData buffer

    CFMutableDictionaryRef _references;     // Mapping between references and actual item
}

@end

@implementation FDSerialUnarchiver

#pragma mark - Init

-(id)initForReadingWithData:(NSData*)data
{
    self = [super init];
    if (self) {
        _data = data;
        _bytes = (const char*)[data bytes];

        // Keep track of reference->object mapping
        _references = CFDictionaryCreateMutable(NULL, 0, NULL, &kCFTypeDictionaryValueCallBacks);
    }
    return self;
}

-(void)dealloc
{
    CFRelease(_references);
}

#pragma mark - Core decoding

-(void)_extractBytesTo:(void*)data length:(NSUInteger)length
{
    memcpy(data, _bytes, length);
    _bytes += length;
}

/**
 *  Beware! **YOU** will be responsible for freeing that string
 */
-(char*)_extractCString
{
    NSUInteger length = strlen(_bytes);
    char *string = (char*)malloc((length+1)*sizeof(char));
    [self _extractBytesTo:string length:length+1];

    FDLog(@"Extracted C-String: %s",string);

    return string;

}

-(NSData*)_extractData
{
    uint32_t length;
    [self _extractBytesTo:&length length:sizeof(uint32_t)];

    NSData *data = [NSData dataWithBytes:_bytes length:length];
    _bytes += length;

    FDLog(@"Extracted NSData: %@",data);

    return data;

}

-(reference_t)_extractReference
{
    reference_t reference;
    [self _extractBytesTo:&reference length:sizeof(reference_t)];

    FDLog(@"Extracted reference: %d",reference);

    return reference;
}

-(Class)_extractClass
{
    FDLog(@"Extracting class");
    FDLogIndent(@"{");

    // Lookup class reference
    reference_t reference = [self _extractReference];

    // NSObject is always nil
    if (!reference)
        return [NSObject class];

    Class objectClass;

    // Do we already know that one ?
    if (!(objectClass = (Class)CFDictionaryGetValue(_references, (const void*)reference)))
    {
        // If not, then the name should follow
        char *classCName = [self _extractCString];
        NSString *className = [NSString stringWithCString:classCName encoding:NSASCIIStringEncoding];
        free(classCName);

        objectClass = NSClassFromString(className);

        CFDictionarySetValue(_references, (const void*)reference, (__bridge const void*)objectClass);
    }

    FDLogOutdent(@"}");
    FDLog(@"Extracted class %@", objectClass);

    return objectClass;

}

-(id)_extractObject
{

    FDLog(@"Extracting object");
    FDLogIndent(@"{");

    reference_t objectReference = [self _extractReference];

    if (!objectReference)
    {
        return nil;
    }

    id object;

    // Do we already know that one ?
    if (!(object = CFDictionaryGetValue(_references, (const void*)objectReference)))
    {
        // If not, then the class & enconding should follow
        Class objectClass = [self _extractClass];
        object = [[objectClass alloc] initWithCoder:self];

        CFDictionarySetValue(_references, (const void*)objectReference, (__bridge const void*)object);
    }

    FDLogOutdent(@"}");
    FDLog(@"Extracted object %@", object);

    return object;

}

-(void)_extractArrayOfType:(const char*)type to:(void *)addr
{
    FDLog(@"Extracting array of type: %s",type);
    FDLogIndent(@"[");

    const char *tmp = type+1; // skip [

    // Get number of elements
    NSUInteger length = parseInt(&tmp);

    // Get size of each element
    NSUInteger size = sizeOfType(tmp);

    // We don't know the size of that particular element
    if (length == kFDUnknownSize)
    {
        [self _cannotDecodeType:tmp];
        return;
    }

    // Decode array
    char *dst = (char*)addr;
    for (NSUInteger i = 0; i < length; ++i)
    {
        [self decodeValueOfObjCType:tmp at:dst];
        dst += size;
    }

    FDLogOutdent(@"]");

}

#pragma mark - Branching by type

-(void)_cannotDecodeType:(const char *)type
{

    @throw [NSException exceptionWithName:@"ISUSerialUnarchiverCannotDecodeException"
                                   reason:[NSString stringWithFormat:@"ISUSerialUnarchiver cannot decode type %s",type]
                                 userInfo:nil];
}

-(void)decodeValueOfObjCType:(const char *)type at:(void *)data
{
    switch(*type){
            // char
        case 'c':
        case 'C':
            // short
        case 's':
        case 'S':
            // int
        case 'i':
        case 'I':
            // long
        case 'l':
        case 'L':
            // long long
        case 'q':
        case 'Q':
            // float
        case 'f':
            // double
        case 'd':
            FDLog(@"Extracting value of type %c",*type);
            [self _extractBytesTo:data length:sizeOfType(type)];
            break;

            // Fixed length array
        case '[':
            [self _extractArrayOfType:type to:data];
            break;

            // c-string (zero terminated)
        case '*':
            *(char **)data = [self _extractCString];
            break;

            // Obj-C object
        case '@':
            *(__strong id *) data = [self _extractObject];
            break;

        case '#':
        case ':':
        case '{':
        case '(':
        case 'b':
        case '^':
        case '?':
        default:
            [self _cannotDecodeType:type];
            break;
    }

}

-(id)decodeObject
{
    return [self _extractObject];
}

-(NSData*)decodeDataObject
{
    return [self _extractData];
}

-(id)decodeRootObject
{

    // Header
    char *header = [self _extractCString];
    if (strcmp(header, "fdsarchive"))
    {
        free(header);
        @throw [NSException exceptionWithName:@"ISUSerialUnarchiverInvalidData"
                                       reason:@"Data does not appear to be a valid archive"
                                     userInfo:nil];
    }
    free(header);

    // Version number
    version_t version;
    [self _extractBytesTo:&version length:sizeof(version_t)];
    if (version > kFDArchiverVersion)
    {
        @throw [NSException exceptionWithName:@"ISUSerialUnarchiverUnknownVersion"
                                       reason:@"The version of the archive appears to be too recent for us to decode"
                                     userInfo:nil];
    }

    // Root object
    return [self decodeObject];

}

#pragma mark - Versionning

-(NSInteger)versionForClassName:(NSString *)className
{
    Class objectClass = NSClassFromString(className);
    return objectClass ? [objectClass version] : NSNotFound;
}

#pragma mark - Misc

+(id)unarchiveObjectWithData:(NSData *)data
{
    @autoreleasepool {

        FDSerialUnarchiver *unarchiver = [[FDSerialUnarchiver alloc] initForReadingWithData:data];
        return [unarchiver decodeRootObject];

    }

}

@end


text:
package org.motechproject.csd.it;

import org.joda.time.DateTime;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.motechproject.csd.domain.CSD;
import org.motechproject.csd.domain.Organization;
import org.motechproject.csd.service.CSDService;
import org.motechproject.csd.service.OrganizationService;
import org.motechproject.csd.db.InitialData;
import org.motechproject.testing.osgi.BasePaxIT;
import org.motechproject.testing.osgi.container.MotechNativeTestContainerFactory;
import org.ops4j.pax.exam.ExamFactory;
import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerSuite;

import javax.inject.Inject;

import java.util.HashSet;
import java.util.Set;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

/**
 * Verify OrganizationService is present & functional.
 */
@RunWith(PaxExam.class)
@ExamReactorStrategy(PerSuite.class)
@ExamFactory(MotechNativeTestContainerFactory.class)
public class OrganizationServiceBundleIT extends BasePaxIT {

    @Inject
    private CSDService csdService;

    @Inject
    private OrganizationService organizationService;

    @Before
    public void cleanBefore() {
        getLogger().info("Clean database before test");
        csdService.delete();
    }

    @After
    public void cleanAfter() {
        getLogger().info("Clean database after test");
        csdService.delete();
    }

    @Test
    public void shouldGetAllOrganizations() {
        CSD csd = InitialData.getInitialData();
        csd.getProviderDirectory().getProviders().clear();
        csd.getServiceDirectory().getServices().clear();
        csd.getFacilityDirectory().getFacilities().clear();
        csdService.update(csd);
        assertTrue(csdService.getCSD().equals(csd));

        assertTrue(organizationService.allOrganizations().containsAll(csd.getOrganizationDirectory().getOrganizations()));
    }

    @Test
    public void shouldGetOrganizationByEntityID() {
        CSD csd = InitialData.getInitialData();
        csd.getProviderDirectory().getProviders().clear();
        csd.getServiceDirectory().getServices().clear();
        csd.getFacilityDirectory().getFacilities().clear();
        Organization organization = InitialData.createOrganization(new DateTime(), "EntityIDToFind");
        csd.getOrganizationDirectory().getOrganizations().add(organization);
        csdService.update(csd);
        assertTrue(csdService.getCSD().equals(csd));

        assertEquals(organizationService.getOrganizationByEntityID("EntityIDToFind"), organization);
    }

    @Test
    public void shouldUpdateOrganizationDirectoryEntity() {
        CSD csd = InitialData.getInitialData();
        csd.getProviderDirectory().getProviders().clear();
        csd.getServiceDirectory().getServices().clear();
        csd.getFacilityDirectory().getFacilities().clear();
        csdService.update(csd);
        assertTrue(csdService.getCSD().equals(csd));

        csd = InitialData.getInitialData();
        csd.getOrganizationDirectory().getOrganizations().iterator().next().setPrimaryName("updated name");
        csd.getOrganizationDirectory().getOrganizations().add(InitialData.createOrganization(new DateTime(), "newOrganization"));
        organizationService.update(csd.getOrganizationDirectory().getOrganizations());
        Set<Organization> organizations = new HashSet<>(organizationService.allOrganizations());
        assertTrue(organizations.equals(csd.getOrganizationDirectory().getOrganizations()));
    }

    @Test
    public void shouldGetEntitiesUpdatedAfterGivenDate() {
        DateTime dateUpdated = new DateTime(2020, 1, 1, 1, 1);

        Organization organization = InitialData.createOrganization(dateUpdated.plusSeconds(1), "lastUpdated");

        CSD csd = InitialData.getInitialData();
        csd.getProviderDirectory().getProviders().clear();
        csd.getServiceDirectory().getServices().clear();
        csd.getFacilityDirectory().getFacilities().clear();
        csd.getOrganizationDirectory().getOrganizations().add(organization);
        csdService.update(csd);
        assertTrue(csdService.getCSD().equals(csd));

        Set<Organization> lastUpdated = organizationService.getModifiedAfter(dateUpdated);

        assertEquals(1, lastUpdated.size());

        assertEquals(lastUpdated.iterator().next(), organization);
    }
}


text:
package rusk.application.facade.task;

import java.util.Date;
import java.util.function.BiConsumer;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import rusk.application.exception.ConcurrentUpdateException;
import rusk.application.interceptor.Transactional;
import rusk.domain.task.InWorkingTask;
import rusk.domain.task.Task;
import rusk.domain.task.TaskFactory;
import rusk.domain.task.TaskList;
import rusk.domain.task.TaskRepository;
import rusk.domain.task.WorkTime;
import rusk.domain.task.exception.TaskNotFoundException;
import rusk.domain.task.form.ModifyTaskForm;
import rusk.domain.task.form.ModifyWorkTimeForm;
import rusk.domain.task.form.RegisterTaskForm;
import rusk.domain.task.form.SwitchStatusForm;
import rusk.domain.task.service.InquireTaskListService;
import rusk.domain.task.service.ModifyTaskService;
import rusk.domain.task.service.SwitchTaskStatusService;

@Transactional
public class TaskFacade {
    private static final Logger logger = LoggerFactory.getLogger(TaskFacade.class);

    private final TaskRepository repository;
    private final SwitchTaskStatusService switchTaskStatusService;
    private final InquireTaskListService inquireTaskListService;
    private final ModifyTaskService modifyTaskService;

    @Inject
    public TaskFacade(TaskRepository repository, SwitchTaskStatusService switchTaskStatusService, InquireTaskListService inquireTaskListService, ModifyTaskService modifyTaskService) {
        this.repository = repository;
        this.switchTaskStatusService = switchTaskStatusService;
        this.inquireTaskListService = inquireTaskListService;
        this.modifyTaskService = modifyTaskService;
    }

    /**
     * 指定した ID のタスクを取得する。
     * @param id タスク ID
     * @return 取得したタスク
     */
    public Task inquire(long id) {
        return this.repository.inquireById(id);
    }

    /**
     * タスク一覧を取得する。
     *
     * @return タスク一覧
     */
    public TaskList inquireTaskList() {
        return this.inquireTaskListService.inquireTaskList();
    }

    /**
     * 指定した ID のタスクを削除する。
     *
     * @param deleteTargetTaskId 削除するタスクの ID
     * @throws TaskNotFoundException 指定した ID のタスクが存在しない場合
     */
    public void remove(long deleteTargetTaskId) throws TaskNotFoundException {
        this.repository.remove(deleteTargetTaskId);
    }

    /**
     * 指定したフォームでタスクを登録する。
     *
     * @param form 登録するフォーム情報
     * @return 登録されたタスク
     */
    public Task register(RegisterTaskForm form) {
        Task task = TaskFactory.create(form);
        this.repository.register(task);

        logger.info("created new task. id = " + task.getId());

        return task;
    }

    /**
     * タスクの状態を変更します。
     *
     * @param form タスク状態切り替えフォーム
     */
    public void switchTaskStatus(SwitchStatusForm form) {
        this.modifyTaskWithLock(form.id, form.lastUpdateDate, (storedTask, inWorkingTask) -> {
            this.switchTaskStatusService.switchTaskStatus(storedTask, inWorkingTask, form.status);
        });
    }

    /**
     * タスクを更新します。
     *
     * @param form 更新情報
     */
    public void modify(ModifyTaskForm form) {
        this.modifyTaskWithLock(form.id, form.lastUpdateDate, (storedTask, inWorkingTask) -> {
            this.modifyTaskService.modify(storedTask, form, inWorkingTask);
        });
    }

    private void modifyTaskWithLock(long id, Date lastUpdateDate, BiConsumer<Task, InWorkingTask> consumer) {
        InWorkingTask inWorkingTask = this.repository.inquireTaskInWorkingWithLock();
        Task storedTask = this.repository.inquireWithLock(id);

        this.verifyConcurrentUpdate(storedTask, lastUpdateDate);
        consumer.accept(storedTask, inWorkingTask);
    }

    private void verifyConcurrentUpdate(Task storedTask, Date lastUpdateDate) {
        if (lastUpdateDate.getTime() < storedTask.getUpdateDate().getTime()) {
            throw new ConcurrentUpdateException();
        }
    }

    /**
     * 作業時間を新規に追加する。
     *
     * @param form 登録情報
     */
    public void registerWorkTime(ModifyWorkTimeForm form) {
        // 全作業時間との整合性チェックを行うので、 WorkTime.class で同期を取る。
        synchronized (WorkTime.class) {
            Task task = this.repository.inquireWithLock(form.taskId);
            this.modifyTaskService.registerWorkTime(task, form);
        }
    }

    /**
     * 作業時間を更新する。
     *
     * @param form 更新情報
     */
    public void modifyWorkTime(ModifyWorkTimeForm form) {
        synchronized (WorkTime.class) {
            Task task = this.repository.inquireWithLock(form.taskId);

            WorkTime workTime = task.getWorkTime(form.workTimeId);
            if (form.updateDate.getTime() < workTime.getUpdateDate().getTime()) {
                throw new ConcurrentUpdateException();
            }

            this.modifyTaskService.modifyWorkTime(task, form);
        }
    }

    /**
     * 作業時間を削除する。
     *
     * @param form 削除情報
     */
    public void removeWorkTime(ModifyWorkTimeForm form) {
        Task task = this.repository.inquireWithLock(form.taskId);
        task.removeWorkTime(form.workTimeId);
        this.repository.saveModification(task);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TasksExample.Api.Models
{
    public class TaskItem
    {
        public int Id { get; set; }

        public string Description { get; set; }

        public bool Completed { get; set; }
    }
}


text:
package org.apache.wink.itest.largeentity;

import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.jar.JarInputStream;

import javax.ws.rs.Consumes;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;

@Provider
@Consumes("application/jar")
public class JARInputStreamProvider implements MessageBodyReader<JarInputStream> {

    public boolean isReadable(Class<?> arg0, Type arg1, Annotation[] arg2, MediaType arg3) {
        return JarInputStream.class.isAssignableFrom(arg0);
    }

    public JarInputStream readFrom(Class<JarInputStream> arg0,
                                   Type arg1,
                                   Annotation[] arg2,
                                   MediaType arg3,
                                   MultivaluedMap<String, String> arg4,
                                   InputStream arg5) throws IOException, WebApplicationException {
        return new JarInputStream(arg5);
    }

}