text:
package dagger.internal.codegen;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Verify.verify;
import static com.google.common.collect.Iterables.isEmpty;
import static dagger.internal.codegen.ComponentDescriptor.Kind.PRODUCTION_COMPONENT;
import static dagger.internal.codegen.ComponentDescriptor.isComponentContributionMethod;
import static dagger.internal.codegen.ComponentDescriptor.isComponentProductionMethod;
import static dagger.internal.codegen.ContributionBinding.Kind.SYNTHETIC_MULTIBOUND_KINDS;
import static dagger.internal.codegen.ContributionBinding.Kind.SYNTHETIC_OPTIONAL_BINDING;
import static dagger.internal.codegen.Key.indexByKey;
import static dagger.internal.codegen.Scope.reusableScope;
import static dagger.internal.codegen.Util.reentrantComputeIfAbsent;
import static dagger.internal.codegen.Util.toImmutableSet;
import static java.util.function.Predicate.isEqual;
import static javax.lang.model.element.Modifier.ABSTRACT;

import com.google.auto.common.MoreTypes;
import com.google.auto.value.AutoValue;
import com.google.auto.value.extension.memoized.Memoized;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.collect.TreeTraverser;
import dagger.Reusable;
import dagger.Subcomponent;
import dagger.internal.codegen.ComponentDescriptor.BuilderRequirementMethod;
import dagger.internal.codegen.ComponentDescriptor.ComponentMethodDescriptor;
import dagger.internal.codegen.ContributionBinding.Kind;
import dagger.internal.codegen.Key.HasKey;
import dagger.producers.Produced;
import dagger.producers.Producer;
import dagger.releasablereferences.CanReleaseReferences;
import dagger.releasablereferences.ReleasableReferenceManager;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Queue;
import java.util.Set;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.Elements;

/**
 * The canonical representation of a full-resolved graph.
 *
 * @author Gregory Kick
 */
@AutoValue
abstract class BindingGraph {
  abstract ComponentDescriptor componentDescriptor();
  abstract ImmutableMap<BindingKey, ResolvedBindings> resolvedBindings();
  abstract ImmutableSet<BindingGraph> subgraphs();

  /**
   * The scopes in the graph that {@linkplain CanReleaseReferences can release their references} for
   * which there is a dependency request for any of the following:
   *
   *

   *
{@code @ForReleasableReferences(scope)} {@link ReleasableReferenceManager}
   *
{@code @ForReleasableReferences(scope)} {@code TypedReleasableReferenceManager<M>}, where
   *       {@code M} is the releasable-references metatadata type for {@code scope}
   *
{@code Set<ReleasableReferenceManager>}
   *
{@code Set<TypedReleasableReferenceManager<M>>}, where {@code M} is the metadata type for
   *       the scope
   *

   *
   *
This set is always empty for subcomponent graphs.
   */
  abstract ImmutableSet<Scope> scopesRequiringReleasableReferenceManagers();

  /** Returns the resolved bindings for the dependencies of {@code binding}. */
  ImmutableSet<ResolvedBindings> resolvedDependencies(ContributionBinding binding) {
    return binding
        .dependencies()
        .stream()
        .map(
            dependencyRequest ->
                resolvedBindings()
                    .getOrDefault(
                        dependencyRequest.bindingKey(),
                        ResolvedBindings.noBindings(
                            dependencyRequest.bindingKey(), componentDescriptor())))
        .collect(toImmutableSet());
  }
  /**
   * The type that defines the component for this graph.
   *
   * @see ComponentDescriptor#componentDefinitionType()
   */
  TypeElement componentType() {
    return componentDescriptor().componentDefinitionType();
  }

  /**
   * Returns the set of modules that are owned by this graph regardless of whether or not any of
   * their bindings are used in this graph. For graphs representing top-level {@link
   * dagger.Component components}, this set will be the same as
   * {@linkplain ComponentDescriptor#transitiveModules the component's transitive modules}. For
   * {@linkplain Subcomponent subcomponents}, this set will be the transitive modules that are not
   * owned by any of their ancestors.
   */
  abstract ImmutableSet<ModuleDescriptor> ownedModules();

  ImmutableSet<TypeElement> ownedModuleTypes() {
    return FluentIterable.from(ownedModules()).transform(ModuleDescriptor::moduleElement).toSet();
  }

  private static final TreeTraverser<BindingGraph> SUBGRAPH_TRAVERSER =
      new TreeTraverser<BindingGraph>() {
        @Override
        public Iterable<BindingGraph> children(BindingGraph node) {
          return node.subgraphs();
        }
      };

  /**
   * The types for which the component needs instances.
   *
   *

   *
component dependencies
   *
{@linkplain #ownedModules() owned modules} with concrete instance bindings that are used
   *       in the graph
   *
bound instances
   *

   */
  @Memoized
  ImmutableSet<ComponentRequirement> componentRequirements() {
    ImmutableSet.Builder<ComponentRequirement> requirements = ImmutableSet.builder();
    StreamSupport.stream(SUBGRAPH_TRAVERSER.preOrderTraversal(this).spliterator(), false)
        .flatMap(graph -> graph.resolvedBindings().values().stream())
        .flatMap(bindings -> bindings.contributionBindings().stream())
        .filter(ContributionBinding::requiresModuleInstance)
        .map(bindingDeclaration -> bindingDeclaration.contributingModule())
        .filter(Optional::isPresent)
        .map(Optional::get)
        .filter(module -> ownedModuleTypes().contains(module))
        .map(module -> ComponentRequirement.forModule(module.asType()))
        .forEach(requirements::add);
    componentDescriptor()
        .dependencies()
        .stream()
        .map(dep -> ComponentRequirement.forDependency(dep.asType()))
        .forEach(requirements::add);
    if (componentDescriptor().builderSpec().isPresent()) {
      componentDescriptor()
          .builderSpec()
          .get()
          .requirementMethods()
          .stream()
          .map(BuilderRequirementMethod::requirement)
          .filter(req -> req.kind().equals(ComponentRequirement.Kind.BINDING))
          .forEach(requirements::add);
    }
    return requirements.build();
  }
  /** Returns the {@link ComponentDescriptor}s for this component and its subcomponents. */
  ImmutableSet<ComponentDescriptor> componentDescriptors() {
    return SUBGRAPH_TRAVERSER
        .preOrderTraversal(this)
        .transform(BindingGraph::componentDescriptor)
        .toSet();
  }

  ImmutableSet<ComponentRequirement> availableDependencies() {
    return Stream.concat(
            componentDescriptor()
                .transitiveModuleTypes()
                .stream()
                .filter(dep -> !dep.getModifiers().contains(ABSTRACT))
                .map(module -> ComponentRequirement.forModule(module.asType())),
            componentDescriptor()
                .dependencies()
                .stream()
                .map(dep -> ComponentRequirement.forDependency(dep.asType())))
        .collect(toImmutableSet());
  }

  static final class Factory {
    private final Elements elements;
    private final InjectBindingRegistry injectBindingRegistry;
    private final Key.Factory keyFactory;
    private final ProvisionBinding.Factory provisionBindingFactory;
    private final ProductionBinding.Factory productionBindingFactory;

    Factory(
        Elements elements,
        InjectBindingRegistry injectBindingRegistry,
        Key.Factory keyFactory,
        ProvisionBinding.Factory provisionBindingFactory,
        ProductionBinding.Factory productionBindingFactory) {
      this.elements = elements;
      this.injectBindingRegistry = injectBindingRegistry;
      this.keyFactory = keyFactory;
      this.provisionBindingFactory = provisionBindingFactory;
      this.productionBindingFactory = productionBindingFactory;
    }

    BindingGraph create(ComponentDescriptor componentDescriptor) {
      return create(Optional.empty(), componentDescriptor);
    }

    private BindingGraph create(
        Optional<Resolver> parentResolver, ComponentDescriptor componentDescriptor) {
      ImmutableSet.Builder<ContributionBinding> explicitBindingsBuilder = ImmutableSet.builder();
      ImmutableSet.Builder<DelegateDeclaration> delegatesBuilder = ImmutableSet.builder();
      ImmutableSet.Builder<OptionalBindingDeclaration> optionalsBuilder = ImmutableSet.builder();

      // binding for the component itself
      explicitBindingsBuilder.add(
          provisionBindingFactory.forComponent(componentDescriptor.componentDefinitionType()));

      // Collect Component dependencies.
      for (TypeElement componentDependency : componentDescriptor.dependencies()) {
        explicitBindingsBuilder.add(
            provisionBindingFactory.forComponentDependency(componentDependency));
        List<ExecutableElement> dependencyMethods =
            ElementFilter.methodsIn(elements.getAllMembers(componentDependency));
        for (ExecutableElement method : dependencyMethods) {
          // MembersInjection methods aren't "provided" explicitly, so ignore them.
          if (isComponentContributionMethod(elements, method)) {
            explicitBindingsBuilder.add(
                componentDescriptor.kind().equals(PRODUCTION_COMPONENT)
                        && isComponentProductionMethod(elements, method)
                    ? productionBindingFactory.forComponentMethod(method)
                    : provisionBindingFactory.forComponentMethod(method));
          }
        }
      }

      // Collect bindings on the builder.
      if (componentDescriptor.builderSpec().isPresent()) {
        for (BuilderRequirementMethod method :
            componentDescriptor.builderSpec().get().requirementMethods()) {
          if (method.requirement().kind().equals(ComponentRequirement.Kind.BINDING)) {
            explicitBindingsBuilder.add(provisionBindingFactory.forBuilderBinding(method));
          }
        }
      }

      for (Map.Entry<ComponentMethodDescriptor, ComponentDescriptor>
          componentMethodAndSubcomponent :
              componentDescriptor.subcomponentsByBuilderMethod().entrySet()) {
        ComponentMethodDescriptor componentMethod = componentMethodAndSubcomponent.getKey();
        ComponentDescriptor subcomponentDescriptor = componentMethodAndSubcomponent.getValue();
        if (!componentDescriptor.subcomponentsFromModules().contains(subcomponentDescriptor)) {
          explicitBindingsBuilder.add(
              provisionBindingFactory.forSubcomponentBuilderMethod(
                  componentMethod.methodElement(),
                  componentDescriptor.componentDefinitionType()));
        }
      }

      ImmutableSet.Builder<MultibindingDeclaration> multibindingDeclarations =
          ImmutableSet.builder();
      ImmutableSet.Builder<SubcomponentDeclaration> subcomponentDeclarations =
          ImmutableSet.builder();

      // Collect transitive module bindings and multibinding declarations.
      for (ModuleDescriptor moduleDescriptor : componentDescriptor.transitiveModules()) {
        explicitBindingsBuilder.addAll(moduleDescriptor.bindings());
        multibindingDeclarations.addAll(moduleDescriptor.multibindingDeclarations());
        subcomponentDeclarations.addAll(moduleDescriptor.subcomponentDeclarations());
        delegatesBuilder.addAll(moduleDescriptor.delegateDeclarations());
        optionalsBuilder.addAll(moduleDescriptor.optionalDeclarations());
      }

      ImmutableSetMultimap<Scope, ProvisionBinding> releasableReferenceManagerBindings =
          getReleasableReferenceManagerBindings(componentDescriptor);
      explicitBindingsBuilder.addAll(releasableReferenceManagerBindings.values());

      final Resolver requestResolver =
          new Resolver(
              parentResolver,
              componentDescriptor,
              indexByKey(explicitBindingsBuilder.build()),
              indexByKey(multibindingDeclarations.build()),
              indexByKey(subcomponentDeclarations.build()),
              indexByKey(delegatesBuilder.build()),
              indexByKey(optionalsBuilder.build()));
      for (ComponentMethodDescriptor componentMethod : componentDescriptor.componentMethods()) {
        Optional<DependencyRequest> componentMethodRequest = componentMethod.dependencyRequest();
        if (componentMethodRequest.isPresent()) {
          requestResolver.resolve(componentMethodRequest.get().bindingKey());
        }
      }

      // Resolve all bindings for subcomponents, creating subgraphs for all subcomponents that have
      // been detected during binding resolution. If a binding for a subcomponent is never resolved,
      // no BindingGraph will be created for it and no implementation will be generated. This is
      // done in a queue since resolving one subcomponent might resolve a key for a subcomponent
      // from a parent graph. This is done until no more new subcomponents are resolved.
      Set<ComponentDescriptor> resolvedSubcomponents = new HashSet<>();
      ImmutableSet.Builder<BindingGraph> subgraphs = ImmutableSet.builder();
      for (ComponentDescriptor subcomponent :
          Iterables.consumingIterable(requestResolver.subcomponentsToResolve)) {
        if (resolvedSubcomponents.add(subcomponent)) {
          subgraphs.add(create(Optional.of(requestResolver), subcomponent));
        }
      }

      ImmutableMap<BindingKey, ResolvedBindings> resolvedBindingsMap =
          requestResolver.getResolvedBindings();
      for (ResolvedBindings resolvedBindings : resolvedBindingsMap.values()) {
        verify(
            resolvedBindings.owningComponent().equals(componentDescriptor),
            "%s is not owned by %s",
            resolvedBindings,
            componentDescriptor);
      }

      return new AutoValue_BindingGraph(
          componentDescriptor,
          resolvedBindingsMap,
          subgraphs.build(),
          getScopesRequiringReleasableReferenceManagers(
              releasableReferenceManagerBindings, resolvedBindingsMap),
          requestResolver.getOwnedModules());
    }

    /**
     * Returns the bindings for {@link ReleasableReferenceManager}s for all {@link
     * CanReleaseReferences @CanReleaseReferences} scopes.
     */
    private ImmutableSetMultimap<Scope, ProvisionBinding> getReleasableReferenceManagerBindings(
        ComponentDescriptor componentDescriptor) {
      ImmutableSetMultimap.Builder<Scope, ProvisionBinding> bindings =
          ImmutableSetMultimap.builder();
      // TODO(dpb,gak): Do we need to bind an empty Set<ReleasableReferenceManager> if there are
      // none?
      for (Scope scope : componentDescriptor.releasableReferencesScopes()) {
        // Add a binding for @ForReleasableReferences(scope) ReleasableReferenceManager.
        bindings.put(scope, provisionBindingFactory.provideReleasableReferenceManager(scope));

        /* Add a binding for Set<ReleasableReferenceManager>. Even if these are added more than
         * once, each instance will be equal to the rest. Since they're being added to a set, there
         * will be only one instance. */
        bindings.put(scope, provisionBindingFactory.provideSetOfReleasableReferenceManagers());

        for (AnnotationMirror metadata : scope.releasableReferencesMetadata()) {
          // Add a binding for @ForReleasableReferences(scope) TypedReleasableReferenceManager<M>.
          bindings.put(
              scope,
              provisionBindingFactory.provideTypedReleasableReferenceManager(
                  scope, metadata.getAnnotationType()));

          /* Add a binding for Set<TypedReleasableReferenceManager<M>>. Even if these are added more
           * than once, each instance will be equal to the rest. Since they're being added to a set,
           * there will be only one instance. */
          bindings.put(
              scope,
              provisionBindingFactory.provideSetOfTypedReleasableReferenceManagers(
                  metadata.getAnnotationType()));
        }
      }
      return bindings.build();
    }

    /**
     * Returns the set of scopes that will be returned by {@link
     * BindingGraph#scopesRequiringReleasableReferenceManagers()}.
     *
     * @param releasableReferenceManagerBindings the {@link ReleasableReferenceManager} bindings for
     *     each scope
     * @param resolvedBindingsMap the resolved bindings for the component
     */
    private ImmutableSet<Scope> getScopesRequiringReleasableReferenceManagers(
        ImmutableSetMultimap<Scope, ProvisionBinding> releasableReferenceManagerBindings,
        ImmutableMap<BindingKey, ResolvedBindings> resolvedBindingsMap) {
      ImmutableSet.Builder<Scope> scopes = ImmutableSet.builder();
      releasableReferenceManagerBindings
          .asMap()
          .forEach(
              (scope, bindings) -> {
                for (Binding binding : bindings) {
                  if (resolvedBindingsMap.containsKey(BindingKey.contribution(binding.key()))) {
                    scopes.add(scope);
                    return;
                  }
                }
              });
      return scopes.build();
    }

    private final class Resolver {
      final Optional<Resolver> parentResolver;
      final ComponentDescriptor componentDescriptor;
      final ImmutableSetMultimap<Key, ContributionBinding> explicitBindings;
      final ImmutableSet<ContributionBinding> explicitBindingsSet;
      final ImmutableSetMultimap<Key, ContributionBinding> explicitMultibindings;
      final ImmutableSetMultimap<Key, MultibindingDeclaration> multibindingDeclarations;
      final ImmutableSetMultimap<Key, SubcomponentDeclaration> subcomponentDeclarations;
      final ImmutableSetMultimap<Key, DelegateDeclaration> delegateDeclarations;
      final ImmutableSetMultimap<Key, OptionalBindingDeclaration> optionalBindingDeclarations;
      final ImmutableSetMultimap<Key, DelegateDeclaration> delegateMultibindingDeclarations;
      final Map<BindingKey, ResolvedBindings> resolvedBindings;
      final Deque<BindingKey> cycleStack = new ArrayDeque<>();
      final Map<BindingKey, Boolean> bindingKeyDependsOnLocalBindingsCache = new HashMap<>();
      final Map<Binding, Boolean> bindingDependsOnLocalBindingsCache = new HashMap<>();
      final Queue<ComponentDescriptor> subcomponentsToResolve = new ArrayDeque<>();

      Resolver(
          Optional<Resolver> parentResolver,
          ComponentDescriptor componentDescriptor,
          ImmutableSetMultimap<Key, ContributionBinding> explicitBindings,
          ImmutableSetMultimap<Key, MultibindingDeclaration> multibindingDeclarations,
          ImmutableSetMultimap<Key, SubcomponentDeclaration> subcomponentDeclarations,
          ImmutableSetMultimap<Key, DelegateDeclaration> delegateDeclarations,
          ImmutableSetMultimap<Key, OptionalBindingDeclaration> optionalBindingDeclarations) {
        this.parentResolver = checkNotNull(parentResolver);
        this.componentDescriptor = checkNotNull(componentDescriptor);
        this.explicitBindings = checkNotNull(explicitBindings);
        this.explicitBindingsSet = ImmutableSet.copyOf(explicitBindings.values());
        this.multibindingDeclarations = checkNotNull(multibindingDeclarations);
        this.subcomponentDeclarations = checkNotNull(subcomponentDeclarations);
        this.delegateDeclarations = checkNotNull(delegateDeclarations);
        this.optionalBindingDeclarations = checkNotNull(optionalBindingDeclarations);
        this.resolvedBindings = Maps.newLinkedHashMap();
        this.explicitMultibindings =
            multibindingContributionsByMultibindingKey(explicitBindingsSet);
        this.delegateMultibindingDeclarations =
            multibindingContributionsByMultibindingKey(delegateDeclarations.values());
        subcomponentsToResolve.addAll(componentDescriptor.subcomponentsFromEntryPoints());
      }

      /**
       * Returns the bindings for the given {@link BindingKey}.
       *
       *
For {@link BindingKey.Kind#CONTRIBUTION} requests, returns all of:
       *
       *

       *
All explicit bindings for:
       *

       *
the requested key
       *
{@code Set<T>} if the requested key's type is {@code Set<Produced<T>>}
       *
{@code Map<K, Provider<V>>} if the requested key's type is {@code Map<K,
       *         Producer<V>>}.
       *

       *
       *
A synthetic binding that depends on {@code Map<K, Producer<V>>} if the requested key's
       *     type is {@code Map<K, V>} and there are some explicit bindings for {@code Map<K,
       *     Producer<V>>}.
       *
A synthetic binding that depends on {@code Map<K, Provider<V>>} if the requested key's
       *     type is {@code Map<K, V>} and there are some explicit bindings for {@code Map<K,
       *     Provider<V>>} but no explicit bindings for {@code Map<K, Producer<V>>}.
       *
An implicit {@link Inject @Inject}-annotated constructor binding if there is one and
       *     there are no explicit bindings or synthetic bindings.
       *

       *
       *
For {@link BindingKey.Kind#MEMBERS_INJECTION} requests, returns the {@link
       * MembersInjectionBinding} for the type.
       */
      ResolvedBindings lookUpBindings(BindingKey bindingKey) {
        Key requestKey = bindingKey.key();
        switch (bindingKey.kind()) {
          case CONTRIBUTION:
            Set<ContributionBinding> contributionBindings = new LinkedHashSet<>();
            ImmutableSet.Builder<ContributionBinding> multibindingContributionsBuilder =
                ImmutableSet.builder();
            ImmutableSet.Builder<MultibindingDeclaration> multibindingDeclarationsBuilder =
                ImmutableSet.builder();
            ImmutableSet.Builder<SubcomponentDeclaration> subcomponentDeclarationsBuilder =
                ImmutableSet.builder();
            ImmutableSet.Builder<OptionalBindingDeclaration> optionalBindingDeclarationsBuilder =
                ImmutableSet.builder();

            for (Key key : keysMatchingRequest(requestKey)) {
              contributionBindings.addAll(getExplicitBindings(key));
              multibindingContributionsBuilder.addAll(getExplicitMultibindings(key));
              multibindingDeclarationsBuilder.addAll(getMultibindingDeclarations(key));
              subcomponentDeclarationsBuilder.addAll(getSubcomponentDeclarations(key));
              optionalBindingDeclarationsBuilder.addAll(getOptionalBindingDeclarations(key));
            }

            ImmutableSet<ContributionBinding> multibindingContributions =
                multibindingContributionsBuilder.build();
            ImmutableSet<MultibindingDeclaration> multibindingDeclarations =
                multibindingDeclarationsBuilder.build();
            ImmutableSet<SubcomponentDeclaration> subcomponentDeclarations =
                subcomponentDeclarationsBuilder.build();
            ImmutableSet<OptionalBindingDeclaration> optionalBindingDeclarations =
                optionalBindingDeclarationsBuilder.build();

            ImmutableSet.Builder<Optional<ContributionBinding>> maybeContributionBindings =
                ImmutableSet.builder();
            maybeContributionBindings.add(
                syntheticMultibinding(
                    requestKey, multibindingContributions, multibindingDeclarations));
            syntheticSubcomponentBuilderBinding(subcomponentDeclarations)
                .ifPresent(
                    binding -> {
                      contributionBindings.add(binding);
                      addSubcomponentToOwningResolver(binding);
                    });
            maybeContributionBindings.add(
                syntheticOptionalBinding(requestKey, optionalBindingDeclarations));

            /* If there are no bindings, add the implicit @Inject-constructed binding if there is
             * one. */
            if (contributionBindings.isEmpty()) {
              maybeContributionBindings.add(
                  injectBindingRegistry
                      .getOrFindProvisionBinding(requestKey)
                      .map((ContributionBinding b) -> b));
            }

            maybeContributionBindings
                .build()
                .stream()
                .filter(Optional::isPresent)
                .map(Optional::get)
                .forEach(contributionBindings::add);

            return ResolvedBindings.forContributionBindings(
                bindingKey,
                componentDescriptor,
                indexBindingsByOwningComponent(
                    bindingKey, ImmutableSet.copyOf(contributionBindings)),
                multibindingDeclarations,
                subcomponentDeclarations,
                optionalBindingDeclarations);

          case MEMBERS_INJECTION:
            // no explicit deps for members injection, so just look it up
            Optional<MembersInjectionBinding> binding =
                injectBindingRegistry.getOrFindMembersInjectionBinding(requestKey);
            return binding.isPresent()
                ? ResolvedBindings.forMembersInjectionBinding(
                    bindingKey, componentDescriptor, binding.get())
                : ResolvedBindings.noBindings(bindingKey, componentDescriptor);

          default:
            throw new AssertionError();
        }
      }

      /**
       * When a binding is resolved for a {@link SubcomponentDeclaration}, adds corresponding
       * {@link ComponentDescriptor subcomponent} to a queue in the owning component's resolver.
       * The queue will be used to detect which subcomponents need to be resolved.
       */
      private void addSubcomponentToOwningResolver(ProvisionBinding subcomponentBuilderBinding) {
        checkArgument(subcomponentBuilderBinding.bindingKind().equals(Kind.SUBCOMPONENT_BUILDER));
        Resolver owningResolver = getOwningResolver(subcomponentBuilderBinding).get();

        TypeElement builderType = MoreTypes.asTypeElement(subcomponentBuilderBinding.key().type());
        owningResolver.subcomponentsToResolve.add(
            owningResolver.componentDescriptor.subcomponentsByBuilderType().get(builderType));
      }

      private ImmutableSet<Key> keysMatchingRequest(Key requestKey) {
        ImmutableSet.Builder<Key> keys = ImmutableSet.builder();
        keys.add(requestKey);
        keyFactory.unwrapSetKey(requestKey, Produced.class).ifPresent(keys::add);
        keyFactory.rewrapMapKey(requestKey, Producer.class, Provider.class).ifPresent(keys::add);
        keyFactory.rewrapMapKey(requestKey, Provider.class, Producer.class).ifPresent(keys::add);
        keys.addAll(keyFactory.implicitFrameworkMapKeys(requestKey));
        return keys.build();
      }

      /**
       * Returns a synthetic binding that depends on individual multibinding contributions.
       *
       *
If there are no {@code multibindingContributions} or {@code multibindingDeclarations},
       * returns {@link Optional#empty()}.
       *
       *
If there are production {@code multibindingContributions} or the request is for any of
       * the following types, returns a {@link ProductionBinding}.
       *
       *

       *
{@code Set<Produced<T>>}
       *
{@code Map<K, Producer<V>>}
       *
{@code Map<K, Produced<V>>}
       *

       *
       * Otherwise, returns a {@link ProvisionBinding}.
       */
      private Optional<ContributionBinding> syntheticMultibinding(
          Key key,
          Iterable<ContributionBinding> multibindingContributions,
          Iterable<MultibindingDeclaration> multibindingDeclarations) {
        if (isEmpty(multibindingContributions) && isEmpty(multibindingDeclarations)) {
          return Optional.empty();
        } else if (multibindingsRequireProduction(multibindingContributions, key)) {
          return Optional.of(
              productionBindingFactory.syntheticMultibinding(key, multibindingContributions));
        } else {
          return Optional.of(
              provisionBindingFactory.syntheticMultibinding(key, multibindingContributions));
        }
      }

      private boolean multibindingsRequireProduction(
          Iterable<ContributionBinding> multibindingContributions, Key key) {
        if (MapType.isMap(key)) {
          MapType mapType = MapType.from(key);
          if (mapType.valuesAreTypeOf(Producer.class) || mapType.valuesAreTypeOf(Produced.class)) {
            return true;
          }
        } else if (SetType.isSet(key) && SetType.from(key).elementsAreTypeOf(Produced.class)) {
          return true;
        }
        return Iterables.any(multibindingContributions,
            hasBindingType -> hasBindingType.bindingType().equals(BindingType.PRODUCTION));
      }

      private Optional<ProvisionBinding> syntheticSubcomponentBuilderBinding(
          ImmutableSet<SubcomponentDeclaration> subcomponentDeclarations) {
        return subcomponentDeclarations.isEmpty()
            ? Optional.empty()
            : Optional.of(
                provisionBindingFactory.syntheticSubcomponentBuilder(subcomponentDeclarations));
      }

      /**
       * Returns a synthetic binding for {@code @Qualifier Optional<Type>} if there are any {@code
       * optionalBindingDeclarations}.
       *
       *
If there are no bindings for the underlying key (the key for dependency requests for
       * {@code Type}), returns a provision binding that always returns {@link Optional#empty()}.
       *
       *
If there are any production bindings for the underlying key, returns a production
       * binding. Otherwise returns a provision binding.
       */
      private Optional<ContributionBinding> syntheticOptionalBinding(
          Key key, ImmutableSet<OptionalBindingDeclaration> optionalBindingDeclarations) {
        if (optionalBindingDeclarations.isEmpty()) {
          return Optional.empty();
        }
        DependencyRequest.Kind kind =
            DependencyRequest.extractKindAndType(OptionalType.from(key).valueType()).kind();
        ResolvedBindings underlyingKeyBindings =
            lookUpBindings(BindingKey.contribution(keyFactory.unwrapOptional(key).get()));
        if (underlyingKeyBindings.isEmpty()) {
          return Optional.of(provisionBindingFactory.syntheticAbsentBinding(key));
        } else if (underlyingKeyBindings.bindingTypes().contains(BindingType.PRODUCTION)
            // handles producerFromProvider cases
            || kind.equals(DependencyRequest.Kind.PRODUCER)
            || kind.equals(DependencyRequest.Kind.PRODUCED)) {
          return Optional.of(productionBindingFactory.syntheticPresentBinding(key, kind));
        } else {
          return Optional.of(provisionBindingFactory.syntheticPresentBinding(key, kind));
        }
      }

      private ImmutableSet<ContributionBinding> createDelegateBindings(
          ImmutableSet<DelegateDeclaration> delegateDeclarations) {
        ImmutableSet.Builder<ContributionBinding> builder = ImmutableSet.builder();
        for (DelegateDeclaration delegateDeclaration : delegateDeclarations) {
          builder.add(createDelegateBinding(delegateDeclaration));
        }
        return builder.build();
      }

      /**
       * Creates one (and only one) delegate binding for a delegate declaration, based on the
       * resolved bindings of the right-hand-side of a {@link dagger.Binds} method. If there are
       * duplicate bindings for the dependency key, there should still be only one binding for the
       * delegate key.
       */
      private ContributionBinding createDelegateBinding(DelegateDeclaration delegateDeclaration) {
        BindingKey delegateBindingKey = delegateDeclaration.delegateRequest().bindingKey();

        if (cycleStack.contains(delegateBindingKey)) {
          return provisionBindingFactory.missingDelegate(delegateDeclaration);
        }

        ResolvedBindings resolvedDelegate;
        try {
          cycleStack.push(delegateBindingKey);
          resolvedDelegate = lookUpBindings(delegateBindingKey);
        } finally {
          cycleStack.pop();
        }
        if (resolvedDelegate.contributionBindings().isEmpty()) {
          // This is guaranteed to result in a missing binding error, so it doesn't matter if the
          // binding is a Provision or Production, except if it is a @IntoMap method, in which
          // case the key will be of type Map<K, Provider<V>>, which will be "upgraded" into a
          // Map<K, Producer<V>> if it's requested in a ProductionComponent. This may result in a
          // strange error, that the RHS needs to be provided with an @Inject or @Provides
          // annotated method, but a user should be able to figure out if a @Produces annotation
          // is needed.
          // TODO(gak): revisit how we model missing delegates if/when we clean up how we model
          // binding declarations
          return provisionBindingFactory.missingDelegate(delegateDeclaration);
        }
        // It doesn't matter which of these is selected, since they will later on produce a
        // duplicate binding error.
        // TODO(ronshapiro): Once compile-testing has a CompilationResult, add a test which asserts
        // that a duplicate binding for the RHS does not result in a duplicate binding for the LHS.
        ContributionBinding explicitDelegate =
            resolvedDelegate.contributionBindings().iterator().next();
        switch (explicitDelegate.bindingType()) {
          case PRODUCTION:
            return productionBindingFactory.delegate(
                delegateDeclaration, (ProductionBinding) explicitDelegate);
          case PROVISION:
            return provisionBindingFactory.delegate(
                delegateDeclaration, (ProvisionBinding) explicitDelegate);
          default:
            throw new AssertionError("bindingType: " + explicitDelegate);
        }
      }

      private ImmutableSetMultimap<ComponentDescriptor, ContributionBinding>
          indexBindingsByOwningComponent(
              BindingKey bindingKey, Iterable<? extends ContributionBinding> bindings) {
        ImmutableSetMultimap.Builder<ComponentDescriptor, ContributionBinding> index =
            ImmutableSetMultimap.builder();
        for (ContributionBinding binding : bindings) {
          index.put(getOwningComponent(bindingKey, binding), binding);
        }
        return index.build();
      }

      /**
       * Returns the component that should contain the framework field for {@code binding}.
       *
       *
If {@code binding} is either not bound in an ancestor component or depends transitively
       * on bindings in this component, returns this component.
       *
       *
Otherwise, resolves {@code request} in this component's parent in order to resolve any
       * multibinding contributions in the parent, and returns the parent-resolved {@link
       * ResolvedBindings#owningComponent(ContributionBinding)}.
       */
      private ComponentDescriptor getOwningComponent(
          BindingKey bindingKey, ContributionBinding binding) {
        if (isResolvedInParent(bindingKey, binding)
            && !new LocalDependencyChecker().dependsOnLocalBindings(binding)) {
          ResolvedBindings parentResolvedBindings =
              parentResolver.get().resolvedBindings.get(bindingKey);
          return parentResolvedBindings.owningComponent(binding);
        } else {
          return componentDescriptor;
        }
      }

      /**
       * Returns {@code true} if {@code binding} is owned by an ancestor. If so, {@linkplain
       * #resolve resolves} the {@link BindingKey} in this component's parent. Don't resolve
       * directly in the owning component in case it depends on multibindings in any of its
       * descendants.
       */
      private boolean isResolvedInParent(BindingKey bindingKey, ContributionBinding binding) {
        Optional<Resolver> owningResolver = getOwningResolver(binding);
        if (owningResolver.isPresent() && !owningResolver.get().equals(this)) {
          parentResolver.get().resolve(bindingKey);
          return true;
        } else {
          return false;
        }
      }

      private Optional<Resolver> getOwningResolver(ContributionBinding binding) {
        if (binding.scope().isPresent() && binding.scope().get().equals(reusableScope(elements))) {
          for (Resolver requestResolver : getResolverLineage().reverse()) {
            // If a @Reusable binding was resolved in an ancestor, use that component.
            if (requestResolver.resolvedBindings.containsKey(
                BindingKey.contribution(binding.key()))) {
              return Optional.of(requestResolver);
            }
          }
          // If a @Reusable binding was not resolved in any ancestor, resolve it here.
          return Optional.empty();
        }

        for (Resolver requestResolver : getResolverLineage().reverse()) {
          if (requestResolver.explicitBindingsSet.contains(binding)
              || requestResolver.subcomponentDeclarations.containsKey(binding.key())) {
            return Optional.of(requestResolver);
          }
        }

        // look for scope separately.  we do this for the case where @Singleton can appear twice
        // in the † compatibility mode
        Optional<Scope> bindingScope = binding.scope();
        if (bindingScope.isPresent()) {
          for (Resolver requestResolver : getResolverLineage().reverse()) {
            if (requestResolver.componentDescriptor.scopes().contains(bindingScope.get())) {
              return Optional.of(requestResolver);
            }
          }
        }
        return Optional.empty();
      }

      /** Returns the resolver lineage from parent to child. */
      private ImmutableList<Resolver> getResolverLineage() {
        List<Resolver> resolverList = Lists.newArrayList();
        for (Optional<Resolver> currentResolver = Optional.of(this);
            currentResolver.isPresent();
            currentResolver = currentResolver.get().parentResolver) {
          resolverList.add(currentResolver.get());
        }
        return ImmutableList.copyOf(Lists.reverse(resolverList));
      }

      /**
       * Returns the explicit {@link ContributionBinding}s that match the {@code key} from this and
       * all ancestor resolvers.
       */
      private ImmutableSet<ContributionBinding> getExplicitBindings(Key key) {
        ImmutableSet.Builder<ContributionBinding> bindings = ImmutableSet.builder();
        for (Resolver resolver : getResolverLineage()) {
          bindings.addAll(resolver.getLocalExplicitBindings(key));
        }
        return bindings.build();
      }

      /**
       * Returns the explicit {@link ContributionBinding}s that match the {@code key} from this
       * resolver.
       */
      private ImmutableSet<ContributionBinding> getLocalExplicitBindings(Key key) {
        return new ImmutableSet.Builder<ContributionBinding>()
            .addAll(explicitBindings.get(key))
            .addAll(
                createDelegateBindings(
                    delegateDeclarations.get(keyFactory.convertToDelegateKey(key))))
            .build();
      }

      /**
       * Returns the explicit multibinding contributions that contribute to the map or set requested
       * by {@code key} from this and all ancestor resolvers.
       */
      private ImmutableSet<ContributionBinding> getExplicitMultibindings(Key key) {
        ImmutableSet.Builder<ContributionBinding> multibindings = ImmutableSet.builder();
        for (Resolver resolver : getResolverLineage()) {
          multibindings.addAll(resolver.getLocalExplicitMultibindings(key));
        }
        return multibindings.build();
      }

      /**
       * Returns the explicit multibinding contributions that contribute to the map or set requested
       * by {@code key} from this resolver.
       */
      private ImmutableSet<ContributionBinding> getLocalExplicitMultibindings(Key key) {
        ImmutableSet.Builder<ContributionBinding> multibindings = ImmutableSet.builder();
        multibindings.addAll(explicitMultibindings.get(key));
        if (!MapType.isMap(key) || MapType.from(key).valuesAreFrameworkType()) {
          // There are no @Binds @IntoMap delegate declarations for Map<K, V> requests. All
          // @IntoMap requests must be for Map<K, Framework<V>>.
          multibindings.addAll(
              createDelegateBindings(
                  delegateMultibindingDeclarations.get(keyFactory.convertToDelegateKey(key))));
        }
        return multibindings.build();
      }

      /**
       * Returns the {@link MultibindingDeclaration}s that match the {@code key} from this and all
       * ancestor resolvers.
       */
      private ImmutableSet<MultibindingDeclaration> getMultibindingDeclarations(Key key) {
        ImmutableSet.Builder<MultibindingDeclaration> multibindingDeclarations =
            ImmutableSet.builder();
        for (Resolver resolver : getResolverLineage()) {
          multibindingDeclarations.addAll(resolver.multibindingDeclarations.get(key));
        }
        return multibindingDeclarations.build();
      }

      /**
       * Returns the {@link SubcomponentDeclaration}s that match the {@code key} from this and all
       * ancestor resolvers.
       */
      private ImmutableSet<SubcomponentDeclaration> getSubcomponentDeclarations(Key key) {
        ImmutableSet.Builder<SubcomponentDeclaration> subcomponentDeclarations =
            ImmutableSet.builder();
        for (Resolver resolver : getResolverLineage()) {
          subcomponentDeclarations.addAll(resolver.subcomponentDeclarations.get(key));
        }
        return subcomponentDeclarations.build();
      }
      /**
       * Returns the {@link OptionalBindingDeclaration}s that match the {@code key} from this and
       * all ancestor resolvers.
       */
      private ImmutableSet<OptionalBindingDeclaration> getOptionalBindingDeclarations(Key key) {
        Optional<Key> unwrapped = keyFactory.unwrapOptional(key);
        if (!unwrapped.isPresent()) {
          return ImmutableSet.of();
        }
        ImmutableSet.Builder<OptionalBindingDeclaration> declarations = ImmutableSet.builder();
        for (Resolver resolver : getResolverLineage()) {
          declarations.addAll(resolver.optionalBindingDeclarations.get(unwrapped.get()));
        }
        return declarations.build();
      }

      private Optional<ResolvedBindings> getPreviouslyResolvedBindings(
          final BindingKey bindingKey) {
        Optional<ResolvedBindings> result = Optional.ofNullable(resolvedBindings.get(bindingKey));
        if (result.isPresent()) {
          return result;
        } else if (parentResolver.isPresent()) {
          return parentResolver.get().getPreviouslyResolvedBindings(bindingKey);
        } else {
          return Optional.empty();
        }
      }

      void resolve(BindingKey bindingKey) {
        // If we find a cycle, stop resolving. The original request will add it with all of the
        // other resolved deps.
        if (cycleStack.contains(bindingKey)) {
          return;
        }

        // If the binding was previously resolved in this (sub)component, don't resolve it again.
        if (resolvedBindings.containsKey(bindingKey)) {
          return;
        }

        /* If the binding was previously resolved in a supercomponent, then we may be able to avoid
         * resolving it here and just depend on the supercomponent resolution.
         *
         * 1. If it depends transitively on multibinding contributions or optional bindings with
         *    bindings from this subcomponent, then we have to resolve it in this subcomponent so
         *    that it sees the local bindings.
         *
         * 2. If there are any explicit bindings in this component, they may conflict with those in
         *    the supercomponent, so resolve them here so that conflicts can be caught.
         */
        if (getPreviouslyResolvedBindings(bindingKey).isPresent()) {
          /* Resolve in the parent in case there are multibinding contributions or conflicts in some
           * component between this one and the previously-resolved one. */
          parentResolver.get().resolve(bindingKey);
          if (!new LocalDependencyChecker().dependsOnLocalBindings(bindingKey)
              && getLocalExplicitBindings(bindingKey.key()).isEmpty()) {
            /* Cache the inherited parent component's bindings in case resolving at the parent found
             * bindings in some component between this one and the previously-resolved one. */
            ResolvedBindings inheritedBindings =
                getPreviouslyResolvedBindings(bindingKey).get().asInheritedIn(componentDescriptor);
            resolvedBindings.put(bindingKey, inheritedBindings);
            return;
          }
        }

        cycleStack.push(bindingKey);
        try {
          ResolvedBindings bindings = lookUpBindings(bindingKey);
          for (Binding binding : bindings.ownedBindings()) {
            for (DependencyRequest dependency : binding.dependencies()) {
              resolve(dependency.bindingKey());
            }
          }
          resolvedBindings.put(bindingKey, bindings);
        } finally {
          cycleStack.pop();
        }
      }

      ImmutableMap<BindingKey, ResolvedBindings> getResolvedBindings() {
        ImmutableMap.Builder<BindingKey, ResolvedBindings> resolvedBindingsBuilder =
            ImmutableMap.builder();
        resolvedBindingsBuilder.putAll(resolvedBindings);
        if (parentResolver.isPresent()) {
          Collection<ResolvedBindings> bindingsResolvedInParent =
              Maps.difference(parentResolver.get().getResolvedBindings(), resolvedBindings)
                  .entriesOnlyOnLeft()
                  .values();
          for (ResolvedBindings resolvedInParent : bindingsResolvedInParent) {
            resolvedBindingsBuilder.put(
                resolvedInParent.bindingKey(),
                resolvedInParent.asInheritedIn(componentDescriptor));
          }
        }
        return resolvedBindingsBuilder.build();
      }

      ImmutableSet<ModuleDescriptor> getInheritedModules() {
        return parentResolver.isPresent()
            ? Sets.union(
                    parentResolver.get().getInheritedModules(),
                    parentResolver.get().componentDescriptor.transitiveModules())
                .immutableCopy()
            : ImmutableSet.<ModuleDescriptor>of();
      }

      ImmutableSet<ModuleDescriptor> getOwnedModules() {
        return Sets.difference(componentDescriptor.transitiveModules(), getInheritedModules())
            .immutableCopy();
      }

      private final class LocalDependencyChecker {
        private final Set<Object> cycleChecker = new HashSet<>();

        /**
         * Returns {@code true} if any of the bindings resolved for {@code bindingKey} are
         * multibindings with contributions declared within this component's modules or optional
         * bindings with present values declared within this component's modules, or if any of its
         * unscoped dependencies depend on such bindings.
         *
         *
We don't care about scoped dependencies because they will never depend on bindings
         * from subcomponents.
         *
         * @throws IllegalArgumentException if {@link #getPreviouslyResolvedBindings(BindingKey)} is
         *     empty
         */
        boolean dependsOnLocalBindings(BindingKey bindingKey) {
          // Don't recur infinitely if there are valid cycles in the dependency graph.
          // http://b/23032377
          if (!cycleChecker.add(bindingKey)) {
            return false;
          }
          return reentrantComputeIfAbsent(
              bindingKeyDependsOnLocalBindingsCache,
              bindingKey,
              this::dependsOnLocalBindingsUncached);
        }

        private boolean dependsOnLocalBindingsUncached(BindingKey bindingKey) {
          checkArgument(
              getPreviouslyResolvedBindings(bindingKey).isPresent(),
              "no previously resolved bindings in %s for %s",
              Resolver.this,
              bindingKey);
          ResolvedBindings previouslyResolvedBindings =
              getPreviouslyResolvedBindings(bindingKey).get();
          if (hasLocalMultibindingContributions(previouslyResolvedBindings)
              || hasLocallyPresentOptionalBinding(previouslyResolvedBindings)) {
            return true;
          }

          for (Binding binding : previouslyResolvedBindings.bindings()) {
            if (dependsOnLocalBindings(binding)) {
              return true;
            }
          }
          return false;
        }

        /**
         * Returns {@code true} if {@code binding} is unscoped (or has {@link Reusable @Reusable}
         * scope) and depends on multibindings with contributions declared within this component's
         * modules, or if any of its unscoped or {@link Reusable @Reusable} scoped dependencies
         * depend on such local multibindings.
         *
         *
We don't care about non-reusable scoped dependencies because they will never depend on
         * multibindings with contributions from subcomponents.
         */
        boolean dependsOnLocalBindings(Binding binding) {
          if (!cycleChecker.add(binding)) {
            return false;
          }
          return reentrantComputeIfAbsent(
              bindingDependsOnLocalBindingsCache, binding, this::dependsOnLocalBindingsUncached);
        }

        private boolean dependsOnLocalBindingsUncached(Binding binding) {
          if ((!binding.scope().isPresent()
                  || binding.scope().get().equals(reusableScope(elements)))
              // TODO(beder): Figure out what happens with production subcomponents.
              && !binding.bindingType().equals(BindingType.PRODUCTION)) {
            for (DependencyRequest dependency : binding.dependencies()) {
              if (dependsOnLocalBindings(dependency.bindingKey())) {
                return true;
              }
            }
          }
          return false;
        }

        /**
         * Returns {@code true} if {@code resolvedBindings} contains a synthetic multibinding with
         * at least one contribution declared within this component's modules.
         */
        private boolean hasLocalMultibindingContributions(ResolvedBindings resolvedBindings) {
          return resolvedBindings
                  .contributionBindings()
                  .stream()
                  .map(ContributionBinding::bindingKind)
                  .anyMatch(SYNTHETIC_MULTIBOUND_KINDS::contains)
              && keysMatchingRequest(resolvedBindings.key())
                  .stream()
                  .anyMatch(key -> !getLocalExplicitMultibindings(key).isEmpty());
        }

        /**
         * Returns {@code true} if {@code resolvedBindings} contains a synthetic optional binding
         * for which there is an explicit present binding in this component.
         */
        private boolean hasLocallyPresentOptionalBinding(ResolvedBindings resolvedBindings) {
          return resolvedBindings
                  .contributionBindings()
                  .stream()
                  .map(ContributionBinding::bindingKind)
                  .anyMatch(isEqual(SYNTHETIC_OPTIONAL_BINDING))
              && !getLocalExplicitBindings(keyFactory.unwrapOptional(resolvedBindings.key()).get())
                  .isEmpty();
        }
      }
    }

    /**
     * A multimap of those {@code declarations} that are multibinding contribution declarations,
     * indexed by the key of the set or map to which they contribute.
     */
    static <T extends HasKey>
        ImmutableSetMultimap<Key, T> multibindingContributionsByMultibindingKey(
            Iterable<T> declarations) {
      ImmutableSetMultimap.Builder<Key, T> builder = ImmutableSetMultimap.builder();
      for (T declaration : declarations) {
        if (declaration.key().multibindingContributionIdentifier().isPresent()) {
          builder.put(declaration.key().withoutMultibindingContributionIdentifier(), declaration);
        }
      }
      return builder.build();
    }
  }
}


text:
CasAgent
========

** TODO: Add description **

redpajama_set_name: RedPajamaGithub


text:
def code_holder(num1, num2):
    v = 0
    #### YOUR CODE GOES HERE ####
    #### make sure you save the return value in the variable: v

    #### DO NOT WRITE AFTER THIS LINE

    return v


text:
<?php

namespace Drupal\language;

use Drupal\Component\Plugin\PluginManagerInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Site\Settings;
use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUI;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Class responsible for performing language negotiation.
 */
class LanguageNegotiator implements LanguageNegotiatorInterface {

  /**
   * The language negotiation method plugin manager.
   *
   * @var \Drupal\Component\Plugin\PluginManagerInterface
   */
  protected $negotiatorManager;

  /**
   * The language manager.
   *
   * @var \Drupal\language\ConfigurableLanguageManagerInterface
   */
  protected $languageManager;

  /**
   * The configuration factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * The settings instance.
   *
   * @return \Drupal\Core\Site\Settings
   */
  protected $settings;

  /**
   * The request stack object.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected $requestStack;

  /**
   * The current active user.
   *
   * @return \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * Local cache for language negotiation method instances.
   *
   * @var array
   */
  protected $methods;

  /**
   * An array of language objects keyed by method id.
   *
   * @var \Drupal\Core\Language\LanguageInterface[]
   */
  protected $negotiatedLanguages = [];

  /**
   * Constructs a new LanguageNegotiator object.
   *
   * @param \Drupal\language\ConfigurableLanguageManagerInterface $language_manager
   *   The language manager.
   * @param \Drupal\Component\Plugin\PluginManagerInterface $negotiator_manager
   *   The language negotiation methods plugin manager
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The configuration factory.
   * @param \Drupal\Core\Site\Settings $settings
   *   The settings instance.
   */
  public function __construct(ConfigurableLanguageManagerInterface $language_manager, PluginManagerInterface $negotiator_manager, ConfigFactoryInterface $config_factory, Settings $settings, RequestStack $requestStack) {
    $this->languageManager = $language_manager;
    $this->negotiatorManager = $negotiator_manager;
    $this->configFactory = $config_factory;
    $this->settings = $settings;
    $this->requestStack = $requestStack;
  }

  /**
   * Initializes the injected language manager with the negotiator.
   *
   * This should be called right after instantiating the negotiator to make it
   * available to the language manager without introducing a circular
   * dependency.
   */
  public function initLanguageManager() {
    $this->languageManager->setNegotiator($this);
  }

  /**
   * {@inheritdoc}
   */
  public function reset() {
    $this->negotiatedLanguages = [];
    $this->methods = [];
  }

  /**
   * {@inheritdoc}
   */
  public function setCurrentUser(AccountInterface $current_user) {
    $this->currentUser = $current_user;
    $this->reset();
  }

  /**
   * {@inheritdoc}
   */
  public function initializeType($type) {
    $language = NULL;

    if ($this->currentUser) {
      // Execute the language negotiation methods in the order they were set up
      // and return the first valid language found.
      foreach ($this->getEnabledNegotiators($type) as $method_id => $info) {
        if (!isset($this->negotiatedLanguages[$method_id])) {
          $this->negotiatedLanguages[$method_id] = $this->negotiateLanguage($type, $method_id);
        }

        // Since objects are references, we need to return a clone to prevent
        // the language negotiation method cache from being unintentionally
        // altered. The same methods might be used with different language types
        // based on configuration.
        $language = !empty($this->negotiatedLanguages[$method_id]) ? clone($this->negotiatedLanguages[$method_id]) : NULL;

        if ($language) {
          $this->getNegotiationMethodInstance($method_id)->persist($language);
          break;
        }
      }
    }

    if (!$language) {
      // If no other language was found use the default one.
      $language = $this->languageManager->getDefaultLanguage();
      $method_id = static::METHOD_ID;
    }

    return [$method_id => $language];
  }

  /**
   * Gets enabled detection methods for the provided language type.
   *
   * @param string $type
   *   The language type.
   *
   * @return array
   *   An array of enabled detection methods for the provided language type.
   */
  protected function getEnabledNegotiators($type) {
    return $this->configFactory->get('language.types')->get('negotiation.' . $type . '.enabled') ?: [];
  }

  /**
   * Performs language negotiation using the specified negotiation method.
   *
   * @param string $type
   *   The language type to be initialized.
   * @param string $method_id
   *   The string identifier of the language negotiation method to use to detect
   *   language.
   *
   * @return \Drupal\Core\Language\LanguageInterface|null
   *   Negotiated language object for given type and method, FALSE otherwise.
   */
  protected function negotiateLanguage($type, $method_id) {
    $langcode = NULL;
    $method = $this->negotiatorManager->getDefinition($method_id);

    if (!isset($method['types']) || in_array($type, $method['types'])) {
      $langcode = $this->getNegotiationMethodInstance($method_id)->getLangcode($this->requestStack->getCurrentRequest());
    }

    $languages = $this->languageManager->getLanguages();
    return isset($languages[$langcode]) ? $languages[$langcode] : NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function getNegotiationMethods($type = NULL) {
    $definitions = $this->negotiatorManager->getDefinitions();
    if (isset($type)) {
      $enabled_methods = $this->getEnabledNegotiators($type);
      $definitions = array_intersect_key($definitions, $enabled_methods);
    }
    return $definitions;
  }

  /**
   * {@inheritdoc}
   */
  public function getNegotiationMethodInstance($method_id) {
    if (!isset($this->methods[$method_id])) {
      $instance = $this->negotiatorManager->createInstance($method_id, []);
      $instance->setLanguageManager($this->languageManager);
      $instance->setConfig($this->configFactory);
      $instance->setCurrentUser($this->currentUser);
      $this->methods[$method_id] = $instance;
    }
    return $this->methods[$method_id];
  }

  /**
   * {@inheritdoc}
   */
  public function getPrimaryNegotiationMethod($type) {
    $enabled_methods = $this->getEnabledNegotiators($type);
    return empty($enabled_methods) ? LanguageNegotiatorInterface::METHOD_ID : key($enabled_methods);
  }

  /**
   * {@inheritdoc}
   */
  public function isNegotiationMethodEnabled($method_id, $type = NULL) {
    $enabled = FALSE;
    $language_types = !empty($type) ? [$type] : $this->languageManager->getLanguageTypes();

    foreach ($language_types as $type) {
      $enabled_methods = $this->getEnabledNegotiators($type);
      if (isset($enabled_methods[$method_id])) {
        $enabled = TRUE;
        break;
      }
    }

    return $enabled;
  }

  /**
   * {@inheritdoc}
   */
  public function saveConfiguration($type, $enabled_methods) {
    // As configurable language types might have changed, we reset the cache.
    $this->languageManager->reset();
    $definitions = $this->getNegotiationMethods();
    $default_types = $this->languageManager->getLanguageTypes();

    // Order the language negotiation method list by weight.
    asort($enabled_methods);
    foreach ($enabled_methods as $method_id => $weight) {
      if (isset($definitions[$method_id])) {
        $method = $definitions[$method_id];
        // If the language negotiation method does not express any preference
        // about types, make it available for any configurable type.
        $types = array_flip(!empty($method['types']) ? $method['types'] : $default_types);
        // Check whether the method is defined and has the right type.
        if (!isset($types[$type])) {
          unset($enabled_methods[$method_id]);
        }
      }
      else {
        unset($enabled_methods[$method_id]);
      }
    }
    $this->configFactory->getEditable('language.types')->set('negotiation.' . $type . '.enabled', $enabled_methods)->save();
  }

  /**
   * {@inheritdoc}
   */
  public function purgeConfiguration() {
    // Ensure that we are getting the defined language negotiation information.
    // An invocation of \Drupal\Core\Extension\ModuleInstaller::install() or
    // \Drupal\Core\Extension\ModuleInstaller::uninstall() could invalidate the
    // cached information.
    $this->negotiatorManager->clearCachedDefinitions();
    $this->languageManager->reset();
    foreach ($this->languageManager->getDefinedLanguageTypesInfo() as $type => $info) {
      $this->saveConfiguration($type, $this->getEnabledNegotiators($type));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function updateConfiguration(array $types) {
    // Ensure that we are getting the defined language negotiation information.
    // An invocation of \Drupal\Core\Extension\ModuleInstaller::install() or
    // \Drupal\Core\Extension\ModuleInstaller::uninstall() could invalidate the
    // cached information.
    $this->negotiatorManager->clearCachedDefinitions();
    $this->languageManager->reset();

    $language_types = [];
    $language_types_info = $this->languageManager->getDefinedLanguageTypesInfo();
    $method_definitions = $this->getNegotiationMethods();

    foreach ($language_types_info as $type => $info) {
      $configurable = in_array($type, $types);

      // The default language negotiation settings, if available, are stored in
      // $info['fixed'].
      $has_default_settings = !empty($info['fixed']);
      // Check whether the language type is unlocked. Only the status of
      // unlocked language types can be toggled between configurable and
      // non-configurable.
      if (empty($info['locked'])) {
        if (!$configurable && !$has_default_settings) {
          // If we have an unlocked non-configurable language type without
          // default language negotiation settings, we use the values
          // negotiated for the interface language which, should always be
          // available.
          $method_weights = [LanguageNegotiationUI::METHOD_ID];
          $method_weights = array_flip($method_weights);
          $this->saveConfiguration($type, $method_weights);
        }
      }
      else {
        // The language type is locked. Locked language types with default
        // settings are always considered non-configurable. In turn if default
        // settings are missing, the language type is always considered
        // configurable.

        // If the language type is locked we can just store its default language
        // negotiation settings if it has some, since it is not configurable.
        if ($has_default_settings) {
          $method_weights = [];
          // Default settings are in $info['fixed'].

          foreach ($info['fixed'] as $weight => $method_id) {
            if (isset($method_definitions[$method_id])) {
              $method_weights[$method_id] = $weight;
            }
          }
          $this->saveConfiguration($type, $method_weights);
        }
        else {
          // It was missing default settings, so force it to be configurable.
          $configurable = TRUE;
        }
      }

      // Accumulate information for each language type so it can be saved later.
      $language_types[$type] = $configurable;
    }

    // Store the language type configuration.
    $config = [
      'configurable' => array_keys(array_filter($language_types)),
      'all' => array_keys($language_types),
    ];
    $this->languageManager->saveLanguageTypesConfiguration($config);
  }

}


text:
package org.apache.beam.sdk.util;

import java.lang.reflect.InvocationTargetException;

/** Stores whether we are running within AppEngine or not. */
public class AppEngineEnvironment {
  /**
   * True if running inside of AppEngine, false otherwise.
   */
  @Deprecated
  public static final boolean IS_APP_ENGINE = isAppEngine();

  /**
   * Attempts to detect whether we are inside of AppEngine.
   *
   *
Purposely copied and left private from private code.google.common.util.concurrent.MoreExecutors#isAppEngine.
   *
   * @return true if we are inside of AppEngine, false otherwise.
   */
  static boolean isAppEngine() {
    if (System.getProperty("com.google.appengine.runtime.environment") == null) {
      return false;
    }
    try {
      // If the current environment is null, we're not inside AppEngine.
      return Class.forName("com.google.apphosting.api.ApiProxy")
          .getMethod("getCurrentEnvironment")
          .invoke(null) != null;
    } catch (ClassNotFoundException e) {
      // If ApiProxy doesn't exist, we're not on AppEngine at all.
      return false;
    } catch (InvocationTargetException e) {
      // If ApiProxy throws an exception, we're not in a proper AppEngine environment.
      return false;
    } catch (IllegalAccessException e) {
      // If the method isn't accessible, we're not on a supported version of AppEngine;
      return false;
    } catch (NoSuchMethodException e) {
      // If the method doesn't exist, we're not on a supported version of AppEngine;
      return false;
    }
  }
}


text:
. test_harness.sh

DOWNLOAD_SNAPSHOT_POSITIVE_CASES=0

# helper for asserting test_positive_snapshot_download_asset positive cases
test_positive_snapshot_download_asset() {
  os="$1"
  arch="$2"
  format="$3"

  # for troubleshooting
  # log_set_priority 10

  name=${PROJECT_NAME}
  github_download=$(snapshot_download_url)
  version=$(snapshot_version)

  tmpdir=$(mktemp -d)

  actual_filepath=$(download_asset "${github_download}" "${tmpdir}" "${name}" "${os}" "${arch}" "${version}" "${format}" )

  assertFileExists "${actual_filepath}" "download_asset os=${os} arch=${arch} format=${format}"

  assertFilesEqual \
    "$(snapshot_dir)/${name}_${version}_${os}_${arch}.${format}" \
    "${actual_filepath}" \
    "unable to download os=${os} arch=${arch} format=${format}"

  ((DOWNLOAD_SNAPSHOT_POSITIVE_CASES++))

  rm -rf -- "$tmpdir"
}

test_download_snapshot_asset_exercised_all_assets() {
  expected=$(snapshot_assets_count)

  assertEquals "${expected}" "${DOWNLOAD_SNAPSHOT_POSITIVE_CASES}" "did not download all possible assets (missing an os/arch/format variant?)"
}

# helper for asserting download_asset negative cases
test_negative_snapshot_download_asset() {
  os="$1"
  arch="$2"
  format="$3"

  # for troubleshooting
  # log_set_priority 10

  name=${PROJECT_NAME}
  github_download=$(snapshot_download_url)
  version=$(snapshot_version)

  tmpdir=$(mktemp -d)

  actual_filepath=$(download_asset "${github_download}" "${tmpdir}" "${name}" "${os}" "${arch}" "${version}" "${format}")

  assertEquals ""  "${actual_filepath}" "unable to download os=${os} arch=${arch} format=${format}"

  rm -rf -- "$tmpdir"
}

worker_pid=$(setup_snapshot_server)
trap 'teardown_snapshot_server ${worker_pid}' EXIT

# exercise all possible assets
run_test_case test_positive_snapshot_download_asset "linux" "amd64" "tar.gz"
run_test_case test_positive_snapshot_download_asset "linux" "amd64" "rpm"
run_test_case test_positive_snapshot_download_asset "linux" "amd64" "deb"
run_test_case test_positive_snapshot_download_asset "linux" "arm64" "tar.gz"
run_test_case test_positive_snapshot_download_asset "linux" "arm64" "rpm"
run_test_case test_positive_snapshot_download_asset "linux" "arm64" "deb"
run_test_case test_positive_snapshot_download_asset "linux" "ppc64le" "tar.gz"
run_test_case test_positive_snapshot_download_asset "linux" "ppc64le" "rpm"
run_test_case test_positive_snapshot_download_asset "linux" "ppc64le" "deb"
run_test_case test_positive_snapshot_download_asset "linux" "s390x" "tar.gz"
run_test_case test_positive_snapshot_download_asset "linux" "s390x" "rpm"
run_test_case test_positive_snapshot_download_asset "linux" "s390x" "deb"

run_test_case test_positive_snapshot_download_asset "darwin" "amd64" "tar.gz"
run_test_case test_positive_snapshot_download_asset "darwin" "arm64" "tar.gz"
run_test_case test_positive_snapshot_download_asset "windows" "amd64" "zip"
# note: the mac signing process produces a dmg which is not part of the snapshot process (thus is not exercised here)

# let's make certain we covered all assets that were expected
run_test_case test_download_snapshot_asset_exercised_all_assets

# make certain we handle missing assets alright
run_test_case test_negative_snapshot_download_asset "bogus" "amd64" "zip"

trap - EXIT
teardown_snapshot_server "${worker_pid}"


text:
package androidx.media3.decoder.vp9;

import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;

import android.content.Context;
import android.net.Uri;
import android.os.Looper;
import androidx.annotation.Nullable;
import androidx.media3.common.MediaItem;
import androidx.media3.common.PlaybackException;
import androidx.media3.common.Player;
import androidx.media3.common.util.Log;
import androidx.media3.datasource.DefaultDataSource;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.exoplayer.Renderer;
import androidx.media3.exoplayer.RenderersFactory;
import androidx.media3.exoplayer.source.MediaSource;
import androidx.media3.exoplayer.source.ProgressiveMediaSource;
import androidx.media3.exoplayer.video.VideoDecoderGLSurfaceView;
import androidx.media3.extractor.mkv.MatroskaExtractor;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

/** Playback tests using {@link LibvpxVideoRenderer}. */
@RunWith(AndroidJUnit4.class)
public class VpxPlaybackTest {

  private static final String BEAR_URI = "asset:///media/vp9/bear-vp9.webm";
  private static final String BEAR_ODD_DIMENSIONS_URI =
      "asset:///media/vp9/bear-vp9-odd-dimensions.webm";
  private static final String ROADTRIP_10BIT_URI = "asset:///media/vp9/roadtrip-vp92-10bit.webm";
  private static final String INVALID_BITSTREAM_URI = "asset:///media/vp9/invalid-bitstream.webm";

  private static final String TAG = "VpxPlaybackTest";

  @Before
  public void setUp() {
    if (!VpxLibrary.isAvailable()) {
      fail("Vpx library not available.");
    }
  }

  @Test
  public void basicPlayback() throws Exception {
    playUri(BEAR_URI);
  }

  @Test
  public void oddDimensionsPlayback() throws Exception {
    playUri(BEAR_ODD_DIMENSIONS_URI);
  }

  @Test
  public void test10BitProfile2Playback() throws Exception {
    if (VpxLibrary.isHighBitDepthSupported()) {
      Log.d(TAG, "High Bit Depth supported.");
      playUri(ROADTRIP_10BIT_URI);
      return;
    }
    Log.d(TAG, "High Bit Depth not supported.");
  }

  @Test
  public void invalidBitstream() {
    try {
      playUri(INVALID_BITSTREAM_URI);
      fail();
    } catch (Exception e) {
      assertThat(e.getCause()).isNotNull();
      assertThat(e.getCause()).isInstanceOf(VpxDecoderException.class);
    }
  }

  private void playUri(String uri) throws Exception {
    TestPlaybackRunnable testPlaybackRunnable =
        new TestPlaybackRunnable(Uri.parse(uri), ApplicationProvider.getApplicationContext());
    Thread thread = new Thread(testPlaybackRunnable);
    thread.start();
    thread.join();
    if (testPlaybackRunnable.playbackException != null) {
      throw testPlaybackRunnable.playbackException;
    }
  }

  private static class TestPlaybackRunnable implements Player.Listener, Runnable {

    private final Context context;
    private final Uri uri;

    @Nullable private ExoPlayer player;
    @Nullable private PlaybackException playbackException;

    public TestPlaybackRunnable(Uri uri, Context context) {
      this.uri = uri;
      this.context = context;
    }

    @Override
    public void run() {
      Looper.prepare();
      RenderersFactory renderersFactory =
          (eventHandler,
              videoRendererEventListener,
              audioRendererEventListener,
              textRendererOutput,
              metadataRendererOutput) ->
              new Renderer[] {
                new LibvpxVideoRenderer(
                    /* allowedJoiningTimeMs= */ 0,
                    eventHandler,
                    videoRendererEventListener,
                    /* maxDroppedFramesToNotify= */ -1)
              };
      player = new ExoPlayer.Builder(context, renderersFactory).build();
      player.addListener(this);
      MediaSource mediaSource =
          new ProgressiveMediaSource.Factory(
                  new DefaultDataSource.Factory(context), MatroskaExtractor.FACTORY)
              .createMediaSource(MediaItem.fromUri(uri));
      player.setVideoSurfaceView(new VideoDecoderGLSurfaceView(context));
      player.setMediaSource(mediaSource);
      player.prepare();
      player.play();
      Looper.loop();
    }

    @Override
    public void onPlayerError(PlaybackException error) {
      playbackException = error;
    }

    @Override
    public void onPlaybackStateChanged(@Player.State int playbackState) {
      if (playbackState == Player.STATE_ENDED
          || (playbackState == Player.STATE_IDLE && playbackException != null)) {
        player.release();
        Looper.myLooper().quit();
      }
    }
  }
}


text:
from collections import namedtuple

_Link = namedtuple('Link', 'type href rel name')
class Link(_Link):
    def __new__(cls, type, href, rel, name=None):
        return super(cls, Link).__new__(cls, type, href, rel, name)

_ResourceEntity = namedtuple('ResourceEntity', 'type href name')
class ResourceEntity(_ResourceEntity):
    def __new__(cls, type, href, name=None):
        return super(cls, ResourceEntity).__new__(cls, type, href, name)

_Org = namedtuple('Org', 'type href name id full_name description links')
class Org(_Org):
    def __new__(cls, type, href, name, id=None, full_name=None, description=None, links=None):
        return super(cls, Org).__new__(cls, type, href, name, id, full_name, description, links)

_OrgVdc = namedtuple('OrgVdc', 'type href name id storage compute links entities')
class OrgVdc(_OrgVdc):
    def __new__(cls, type, href, name, id=None, storage=None, compute=None, links=None, entities=None):
        return super(cls, OrgVdc).__new__(cls, type, href, name, id, storage, compute, links, entities)

_OrgList = namedtuple('OrgList', 'orgs')
class OrgList(_OrgList):

    def org_by_name(self, name):
        for o in self.orgs:
            if o.name == name:
                return o
        return None

_ExtNetList = namedtuple('ExtNetList', 'ext_nets')
class ExtNetList(_ExtNetList):

    def ext_net_by_name(self, name):
        for en in self.ext_nets:
            if en.name == name:
                return en
        return None

_ExtNet = namedtuple('ExtNet', 'type href name config id description links')
class ExtNet(_ExtNet):
    def __new__(cls, type, href, name, config=None, id=None, description=None, links=None):
        return super(cls, ExtNet).__new__(cls, type, href, name, config, id, description, links)

_OrgNet = namedtuple('OrgNet', 'name gateway netmask dns ranges')
class OrgNet(_OrgNet):
    def __new__(cls, name, gateway, netmask, dns, ranges):
        return super(cls, OrgNet).__new__(cls, name, gateway, netmask, dns, ranges)

_IpRange = namedtuple('IpRange', 'first last')
class IpRange(_IpRange):
    def __new__(cls, first, last):
        return super(cls, IpRange).__new__(cls, first, last)


text:
<?php use_helper('Javascript') ?>

<?php echo javascript_tag("
function insertGadget(type, id, caption)
{
  var parentIframe = parent.document.getElementsByTagName('iframe')[0];

  var typeId = 'plot' + type.charAt(0).toUpperCase() + type.substr(1, type.length - 1);
  var target = parentIframe.contentWindow.document.getElementById(typeId).getElementsByClassName('emptyGadget')[0];
  var contents = '
'+caption+'(".__('削除').")
';
  new Insertion.Before(target, contents);

  var form = parent.document.getElementById('gadgetForm');
  var hidden = document.createElement('input');
  hidden.setAttribute('class', type + 'New');
  hidden.setAttribute('type', 'hidden');
  hidden.setAttribute('name', 'new[' + type + '][]');
  hidden.setAttribute('value', id);
  new Insertion.Bottom(form, hidden);

  parentIframe.contentWindow.parent.adjustByIframeContens(parentIframe);
}
");
?>

<?php if ($config) : ?>
<?php foreach ($config as $key => $value) : ?>

<?php echo $value['caption']['ja_JP'] ?>

<?php echo link_to_function(__('このガジェットを追加する'), 'insertGadget(\''.$type.'\', \''.escape_javascript($key).'\', \'' . escape_javascript($value['caption']['ja_JP']) . '\')') ?>

<?php echo $value['description']['ja_JP'] ?>

<?php endforeach; ?>
<?php else: ?>

<?php echo __('ガジェットがありません') ?>

<?php echo __('追加できるガジェットが登録されていません') ?>

<?php endif; ?>


text:
module Concerns
  module ListeningStats
    extend ActiveSupport::Concern
    def fetch_top_artists_by_period(args = {})
      from = args.fetch(:from)
      to = args.fetch(:to)
      service.top_artists_by_period(from: from, to: to)
    end

    # Deprecate - use #fetch_api_top_artists
    def api_top_artists(args = {})
      response = service.get_top_artists(args)
      result = response['topartists']['artist']
      # Sort artists by tipped, accepting and invitable
      result
    end

    private

    def service(service_class = LastfmApi)
      @service ||= service_class.new(self)
    end
  end
end


text:
namespace MvcTemplate.Web
{
    using System;

    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.EntityFramework;
    using Microsoft.AspNet.Identity.Owin;
    using Microsoft.Owin;
    using Microsoft.Owin.Security.DataProtection;

    using MvcTemplate.Data;
    using MvcTemplate.Data.Models;

    // Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
    public class ApplicationUserManager : UserManager<ApplicationUser>
    {
        public ApplicationUserManager(
            IUserStore<ApplicationUser> store,
            IdentityFactoryOptions<ApplicationUserManager> options)
            : base(store)
        {
            // Configure validation logic for usernames
            this.UserValidator = new UserValidator<ApplicationUser>(this)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail = true
            };

            // Configure validation logic for passwords
            this.PasswordValidator = new PasswordValidator
            {
                RequiredLength = Common.GlobalConstants.PasswordMinLength,
                RequireNonLetterOrDigit = false,
                RequireDigit = false,
                RequireLowercase = false,
                RequireUppercase = false,
            };

            // Configure user lockout defaults
            this.UserLockoutEnabledByDefault = true;
            this.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
            this.MaxFailedAccessAttemptsBeforeLockout = 5;

            // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
            // You can write your own provider and plug it in here.
            this.RegisterPhoneNumberProvider();
            this.RegisterEmailProvider();
            this.RegisterDataProtectionProvider(options.DataProtectionProvider);

            this.EmailService = new EmailService();
            this.SmsService = new SmsService();
        }

        private void RegisterPhoneNumberProvider()
        {
            var provider = new PhoneNumberTokenProvider<ApplicationUser>
            {
                MessageFormat = "Your security code is {0}"
            };
            this.RegisterTwoFactorProvider("Phone Code", provider);
        }

        private void RegisterEmailProvider()
        {
            var provider = new EmailTokenProvider<ApplicationUser>
            {
                Subject = "Security Code",
                BodyFormat = "Your security code is {0}"
            };
            this.RegisterTwoFactorProvider("Email Code", provider);
        }

        private void RegisterDataProtectionProvider(IDataProtectionProvider provider)
        {
            if (provider != null)
            {
                this.UserTokenProvider =
                    new DataProtectorTokenProvider<ApplicationUser>(provider.Create("ASP.NET Identity"));
            }
        }
    }
}


text:
/**
 * <copyright>
 * </copyright>
 *
 * $Id$
 */
package gov.nasa.arc.spife.core.plan.timeline.provider;

import gov.nasa.arc.spife.core.plan.timeline.PlanTimelineFactory;
import gov.nasa.arc.spife.core.plan.timeline.util.PlanTimelineAdapterFactory;
import gov.nasa.arc.spife.timeline.TimelinePackage;
import gov.nasa.arc.spife.timeline.model.ETimeline;
import gov.nasa.arc.spife.timeline.model.util.TimelineSwitch;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.emf.common.util.ResourceLocator;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.edit.command.CommandParameter;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.emf.edit.provider.ChangeNotifier;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.ComposedAdapterFactory;
import org.eclipse.emf.edit.provider.IChangeNotifier;
import org.eclipse.emf.edit.provider.IChildCreationExtender;
import org.eclipse.emf.edit.provider.IDisposable;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.INotifyChangedListener;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;

/**
 * This is the factory that is used to provide the interfaces needed to support Viewers.
 * The adapters generated by this factory convert EMF adapter notifications into calls to {@link #fireNotifyChanged fireNotifyChanged}.
 * The adapters also support Eclipse property sheets.
 * Note that most of the adapters are shared among multiple instances.
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
public class PlanTimelineItemProviderAdapterFactory extends PlanTimelineAdapterFactory implements ComposeableAdapterFactory, IChangeNotifier, IDisposable {
	/**
	 * This keeps track of the root adapter factory that delegates to this adapter factory.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	protected ComposedAdapterFactory parentAdapterFactory;

	/**
	 * This is used to implement {@link org.eclipse.emf.edit.provider.IChangeNotifier}.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	protected IChangeNotifier changeNotifier = new ChangeNotifier();

	/**
	 * This keeps track of all the supported types checked by {@link #isFactoryForType isFactoryForType}.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	protected Collection<Object> supportedTypes = new ArrayList<Object>();

	/**
	 * This constructs an instance.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public PlanTimelineItemProviderAdapterFactory() {
		supportedTypes.add(IEditingDomainItemProvider.class);
		supportedTypes.add(IStructuredItemContentProvider.class);
		supportedTypes.add(ITreeItemContentProvider.class);
		supportedTypes.add(IItemLabelProvider.class);
		supportedTypes.add(IItemPropertySource.class);
	}

	/**
	 * This keeps track of the one adapter used for all {@link gov.nasa.arc.spife.core.plan.timeline.PlanReferencedObjectSection} instances.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	protected PlanReferencedObjectSectionItemProvider planReferencedObjectSectionItemProvider;

	/**
	 * This creates an adapter for a {@link gov.nasa.arc.spife.core.plan.timeline.PlanReferencedObjectSection}.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public Adapter createPlanReferencedObjectSectionAdapter() {
		if (planReferencedObjectSectionItemProvider == null) {
			planReferencedObjectSectionItemProvider = new PlanReferencedObjectSectionItemProvider(this);
		}

		return planReferencedObjectSectionItemProvider;
	}

	/**
	 * This keeps track of the one adapter used for all {@link gov.nasa.arc.spife.core.plan.timeline.PlanSection} instances.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	protected PlanSectionItemProvider planSectionItemProvider;

	/**
	 * This creates an adapter for a {@link gov.nasa.arc.spife.core.plan.timeline.PlanSection}.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public Adapter createPlanSectionAdapter() {
		if (planSectionItemProvider == null) {
			planSectionItemProvider = new PlanSectionItemProvider(this);
		}

		return planSectionItemProvider;
	}

	/**
	 * This keeps track of the one adapter used for all {@link gov.nasa.arc.spife.core.plan.timeline.PlanSectionRow} instances.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	protected PlanSectionRowItemProvider planSectionRowItemProvider;

	/**
	 * This creates an adapter for a {@link gov.nasa.arc.spife.core.plan.timeline.PlanSectionRow}.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public Adapter createPlanSectionRowAdapter() {
		if (planSectionRowItemProvider == null) {
			planSectionRowItemProvider = new PlanSectionRowItemProvider(this);
		}

		return planSectionRowItemProvider;
	}

	/**
	 * This keeps track of the one adapter used for all {@link gov.nasa.arc.spife.core.plan.timeline.ReferencedObjectRow} instances.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	protected ReferencedObjectRowItemProvider referencedObjectRowItemProvider;

	/**
	 * This creates an adapter for a {@link gov.nasa.arc.spife.core.plan.timeline.ReferencedObjectRow}.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public Adapter createReferencedObjectRowAdapter() {
		if (referencedObjectRowItemProvider == null) {
			referencedObjectRowItemProvider = new ReferencedObjectRowItemProvider(this);
		}

		return referencedObjectRowItemProvider;
	}

	/**
	 * This keeps track of the one adapter used for all {@link gov.nasa.arc.spife.core.plan.timeline.FeatureValueRow} instances.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	protected FeatureValueRowItemProvider featureValueRowItemProvider;

	/**
	 * This creates an adapter for a {@link gov.nasa.arc.spife.core.plan.timeline.FeatureValueRow}.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public Adapter createFeatureValueRowAdapter() {
		if (featureValueRowItemProvider == null) {
			featureValueRowItemProvider = new FeatureValueRowItemProvider(this);
		}

		return featureValueRowItemProvider;
	}

	/**
	 * This returns the root adapter factory that contains this factory.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public ComposeableAdapterFactory getRootAdapterFactory() {
		return parentAdapterFactory == null ? this : parentAdapterFactory.getRootAdapterFactory();
	}

	/**
	 * This sets the composed adapter factory that contains this factory.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public void setParentAdapterFactory(ComposedAdapterFactory parentAdapterFactory) {
		this.parentAdapterFactory = parentAdapterFactory;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public boolean isFactoryForType(Object type) {
		return supportedTypes.contains(type) || super.isFactoryForType(type);
	}

	/**
	 * This implementation substitutes the factory itself as the key for the adapter.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public Adapter adapt(Notifier notifier, Object type) {
		return super.adapt(notifier, this);
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public Object adapt(Object object, Object type) {
		if (isFactoryForType(type)) {
			Object adapter = super.adapt(object, type);
			if (!(type instanceof Class<?>) || (((Class<?>)type).isInstance(adapter))) {
				return adapter;
			}
		}

		return null;
	}

	/**
	 * This adds a listener.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public void addListener(INotifyChangedListener notifyChangedListener) {
		changeNotifier.addListener(notifyChangedListener);
	}

	/**
	 * This removes a listener.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public void removeListener(INotifyChangedListener notifyChangedListener) {
		changeNotifier.removeListener(notifyChangedListener);
	}

	/**
	 * This delegates to {@link #changeNotifier} and to {@link #parentAdapterFactory}.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public void fireNotifyChanged(Notification notification) {
		changeNotifier.fireNotifyChanged(notification);

		if (parentAdapterFactory != null) {
			parentAdapterFactory.fireNotifyChanged(notification);
		}
	}

	/**
	 * This disposes all of the item providers created by this factory.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public void dispose() {
		if (featureValueRowItemProvider != null) featureValueRowItemProvider.dispose();
		if (planReferencedObjectSectionItemProvider != null) planReferencedObjectSectionItemProvider.dispose();
		if (planSectionItemProvider != null) planSectionItemProvider.dispose();
		if (planSectionRowItemProvider != null) planSectionRowItemProvider.dispose();
		if (referencedObjectRowItemProvider != null) referencedObjectRowItemProvider.dispose();
	}

	/**
	 * A child creation extender for the {@link TimelinePackage}.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public static class TimelineChildCreationExtender implements IChildCreationExtender {
		/**
		 * The switch for creating child descriptors specific to each extended class.
		 * <!-- begin-user-doc -->
		 * <!-- end-user-doc -->
		 * @generated
		 */
		protected static class CreationSwitch extends TimelineSwitch<Object> {
			/**
			 * The child descriptors being populated.
			 * <!-- begin-user-doc -->
			 * <!-- end-user-doc -->
			 * @generated
			 */
			protected List<Object> newChildDescriptors;

			/**
			 * The domain in which to create the children.
			 * <!-- begin-user-doc -->
			 * <!-- end-user-doc -->
			 * @generated
			 */
			protected EditingDomain editingDomain;

			/**
			 * Creates the a switch for populating child descriptors in the given domain.
			 * <!-- begin-user-doc -->
			 * <!-- end-user-doc -->
			 * @generated
			 */
			CreationSwitch(List<Object> newChildDescriptors, EditingDomain editingDomain) {
				this.newChildDescriptors = newChildDescriptors;
				this.editingDomain = editingDomain;
			}
			/**
			 * <!-- begin-user-doc -->
			 * <!-- end-user-doc -->
			 * @generated
			 */
			@Override
			public Object caseETimeline(ETimeline object) {
				newChildDescriptors.add
					(createChildParameter
						(TimelinePackage.Literals.ETIMELINE__CONTENTS,
						 PlanTimelineFactory.eINSTANCE.createPlanReferencedObjectSection()));

				newChildDescriptors.add
					(createChildParameter
						(TimelinePackage.Literals.ETIMELINE__CONTENTS,
						 PlanTimelineFactory.eINSTANCE.createPlanSection()));

				return null;
			}

			/**
			 * <!-- begin-user-doc -->
			 * <!-- end-user-doc -->
			 * @generated
			 */
			protected CommandParameter createChildParameter(Object feature, Object child) {
				return new CommandParameter(null, feature, child);
			}

		}

		/**
		 * <!-- begin-user-doc -->
		 * <!-- end-user-doc -->
		 * @generated
		 */
		@Override
		public Collection<Object> getNewChildDescriptors(Object object, EditingDomain editingDomain) {
			ArrayList<Object> result = new ArrayList<Object>();
		   new CreationSwitch(result, editingDomain).doSwitch((EObject)object);
		   return result;
		}

		/**
		 * <!-- begin-user-doc -->
		 * <!-- end-user-doc -->
		 * @generated
		 */
		@Override
		public ResourceLocator getResourceLocator() {
			return PlanTimelineEditPlugin.INSTANCE;
		}
	}

}


text:
package generics.java.variant;

import generics.java.data.Animal;

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

class City implements IEntityInfo{
    @Override
    public List<IEntityInfo> getChildren() {
        return null;
    }
}

class Province implements IEntityInfo {
    List<City> cities;

    public Province(List<City> in) {
        this.cities = in;
    }

    @Override
    public List<? extends IEntityInfo> getChildren() {// change here
        return this.cities;
    }
}

interface IEntityInfo {
    List<? extends IEntityInfo> getChildren(); // change here
}

class RecyclerViewAdapter {
    List<IEntityInfo> data = new ArrayList<>();

    public void setData(List<? extends IEntityInfo> raw) {
        for (IEntityInfo parent : raw) {
            data.add(parent);
            for (IEntityInfo child : parent.getChildren()) {
                data.add(child);
            }
        }
    }
}

class Demo {
    public static void main(String[] args) {
        City london = new City();
        City toronto = new City();
        List<City> onCities = new ArrayList<>();
        onCities.add(london);
        onCities.add(toronto);
        Province on = new Province(onCities);

        List<Province> provinces = new ArrayList<>();
        provinces.add(on);

        RecyclerViewAdapter adapter = new RecyclerViewAdapter();
        adapter.setData(provinces);
    }
}

// ================================
class AdPet extends Animal{}
class Adapter2 {
    List<Animal> data;

    public void setData(List<? extends Animal> raw){
        data.add(0, new AdPet());
        data.addAll(raw);
    }
}


text:
using System;
using System.Linq;
using Autofac.Core;

namespace Autofac.Builder
{
    /// <summary>
    /// Reference object allowing location and update of a registration callback.
    /// </summary>
    public class DeferredCallback
    {
        private Action<IComponentRegistry> _callback;

        /// <summary>
        /// Initializes a new instance of the <see cref="DeferredCallback"/> class.
        /// </summary>
        /// <param name="callback">
        /// An <see cref="Action{T}"/> that executes a registration action
        /// against an <see cref="IComponentRegistry"/>.
        /// </param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown if <paramref name="callback" /> is <see langword="null" />.
        /// </exception>
        public DeferredCallback(Action<IComponentRegistry> callback)
        {
            if (callback == null)
            {
                throw new ArgumentNullException(nameof(callback));
            }

            this.Id = Guid.NewGuid();
            this.Callback = callback;
        }

        /// <summary>
        /// Gets or sets the callback to execute during registration.
        /// </summary>
        /// <value>
        /// An <see cref="Action{T}"/> that executes a registration action
        /// against an <see cref="IComponentRegistry"/>.
        /// </value>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown if <paramref name="value" /> is <see langword="null" />.
        /// </exception>
        public Action<IComponentRegistry> Callback
        {
            get
            {
                return this._callback;
            }

            set
            {
                if (value == null)
                {
                    throw new ArgumentNullException(nameof(value));
                }

                this._callback = value;
            }
        }

        /// <summary>
        /// Gets the callback identifier.
        /// </summary>
        /// <value>
        /// A <see cref="Guid"/> that uniquely identifies the callback action
        /// in a set of callbacks.
        /// </value>
        public Guid Id { get; }
    }
}


text:
Adds a resolve(path) method to the Module prototype.

Node.js has a pretty powerful and intuitive resource path resolution algorithm, which is useful for other things besides source files.  To use it for looking-up other files, we need to be able to lookup relative to the module from which the file is being sought.  This patches in that functionality using private methods of the Module object, so it's not an ideal solution.

A better solution would be for node.js to integrate this method.  Even better would be if it provided a async implementation as well.

See [bug 3285](https://github.com/joyent/node/issues/3285).


text:
<?php

namespace litle\sdk;
require_once realpath(__DIR__) . '/../../vendor/autoload.php';

#Force Capture
$capture_info = array(
    'id' => '456',
    'merchantId' => '101',
    'version' => '8.8',
    'reportGroup' => 'Planets',
    'litleTxnId' => '123456',
    'orderId' => '12344',
    'amount' => '106',
    'orderSource' => 'ecommerce',
    'card' => array(
        'type' => 'VI',
        'number' => '4100000000000001',
        'expDate' => '1210'
    )
);

$initialize = new LitleOnlineRequest();
$response = $initialize->forceCaptureRequest($capture_info);

#display results
echo("Response: " . (XmlParser::getNode($response, 'response')) . "
");
echo("Message: " . XmlParser::getNode($response, 'message') . "
");
echo("Litle Transaction ID: " . XmlParser::getNode($response, 'litleTxnId'));

if (XmlParser::getNode($response, 'message') != 'Approved')
    throw new \Exception('LitleForceCaptureTransaction does not get the right response');