text:
package com.intellij.codeInspection;

import com.intellij.codeInsight.daemon.GroupNames;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Conditions;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.codeStyle.JavaCodeStyleSettings;
import com.intellij.psi.impl.source.resolve.graphInference.FunctionalInterfaceParameterizationUtil;
import com.intellij.psi.infos.MethodCandidateInfo;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.*;
import com.intellij.refactoring.util.RefactoringChangeUtil;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.ContainerUtil;
import com.siyeh.ig.psiutils.ExpressionUtils;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Collection;
import java.util.Map;

public class LambdaCanBeMethodReferenceInspection extends AbstractBaseJavaLocalInspectionTool {
  private static final Logger LOG = Logger.getInstance(LambdaCanBeMethodReferenceInspection.class);

  @Nls
  @NotNull
  @Override
  public String getGroupDisplayName() {
    return GroupNames.LANGUAGE_LEVEL_SPECIFIC_GROUP_NAME;
  }

  @Nls
  @NotNull
  @Override
  public String getDisplayName() {
    return "Lambda can be replaced with method reference";
  }

  @Override
  public boolean isEnabledByDefault() {
    return true;
  }

  @NotNull
  @Override
  public String getShortName() {
    return "Convert2MethodRef";
  }

  @NotNull
  @Override
  public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
    return new JavaElementVisitor() {
      @Override
      public void visitLambdaExpression(PsiLambdaExpression expression) {
        super.visitLambdaExpression(expression);
        if (PsiUtil.getLanguageLevel(expression).isAtLeast(LanguageLevel.JDK_1_8)) {
          final PsiElement body = expression.getBody();
          final PsiType functionalInterfaceType = expression.getFunctionalInterfaceType();
          if (functionalInterfaceType == null) return;
          MethodReferenceCandidate methodRefCandidate = extractMethodReferenceCandidateExpression(body);
          if (methodRefCandidate == null) return;
          final PsiExpression candidate =
            canBeMethodReferenceProblem(expression.getParameterList().getParameters(), functionalInterfaceType, null,
                                        methodRefCandidate.myExpression);
          if (candidate == null) return;
          ProblemHighlightType type;
          if (methodRefCandidate.mySafeQualifier && methodRefCandidate.myConformsCodeStyle) {
            type = ProblemHighlightType.GENERIC_ERROR_OR_WARNING;
          }
          else {
            if (!isOnTheFly) return;
            type = ProblemHighlightType.INFORMATION;
          }
          PsiElement element =
            type == ProblemHighlightType.INFORMATION || InspectionProjectProfileManager.isInformationLevel(getShortName(), expression)
            ? expression
            : candidate;
          holder.registerProblem(holder.getManager().createProblemDescriptor(
            element,
            "Can be replaced with method reference",
            type != ProblemHighlightType.INFORMATION,
            type, true, new ReplaceWithMethodRefFix(methodRefCandidate.mySafeQualifier ? "" : " (may change semantics)")));
        }
      }
    };
  }

  @Nullable
  public static PsiExpression canBeMethodReferenceProblem(@Nullable final PsiElement body,
                                                          final PsiVariable[] parameters,
                                                          PsiType functionalInterfaceType,
                                                          @Nullable PsiElement context) {
    MethodReferenceCandidate methodRefCandidate = extractMethodReferenceCandidateExpression(body);
    if (methodRefCandidate == null || !methodRefCandidate.mySafeQualifier || !methodRefCandidate.myConformsCodeStyle) return null;
    return canBeMethodReferenceProblem(parameters, functionalInterfaceType, context, methodRefCandidate.myExpression);
  }

  @Nullable
  public static PsiExpression canBeMethodReferenceProblem(final PsiVariable[] parameters,
                                                          PsiType functionalInterfaceType,
                                                          @Nullable PsiElement context,
                                                          final PsiExpression methodRefCandidate) {
    if (methodRefCandidate instanceof PsiNewExpression) {
      final PsiNewExpression newExpression = (PsiNewExpression)methodRefCandidate;
      if (newExpression.getAnonymousClass() != null || newExpression.getArrayInitializer() != null) {
        return null;
      }
    }

    final String methodReferenceText = createMethodReferenceText(methodRefCandidate, functionalInterfaceType, parameters);
    if (methodReferenceText != null) {
      LOG.assertTrue(methodRefCandidate != null);
      if (!(methodRefCandidate instanceof PsiCallExpression)) return methodRefCandidate;
      PsiCallExpression callExpression = (PsiCallExpression)methodRefCandidate;
      final PsiMethod method = callExpression.resolveMethod();
      if (method != null) {
        if (!isSimpleCall(parameters, callExpression, method)) {
          return null;
        }
      }
      else {
        LOG.assertTrue(callExpression instanceof PsiNewExpression);
        if (((PsiNewExpression)callExpression).getQualifier() != null) {
          return null;
        }

        final PsiExpression[] dims = ((PsiNewExpression)callExpression).getArrayDimensions();
        if (dims.length == 1 && parameters.length == 1){
          if (!resolvesToParameter(dims[0], parameters[0])) {
            return null;
          }
        }
        else if (dims.length > 0) {
          return null;
        }

        if (callExpression.getTypeArguments().length > 0) {
          return null;
        }
      }
      final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(callExpression.getProject());
      PsiMethodReferenceExpression methodReferenceExpression;
      try {
        methodReferenceExpression = (PsiMethodReferenceExpression)elementFactory.createExpressionFromText(methodReferenceText, context != null ? context : callExpression);
      }
      catch (IncorrectOperationException e) {
        LOG.error(callExpression.getText(), e);
        return null;
      }
      final Map<PsiElement, PsiType> map = LambdaUtil.getFunctionalTypeMap();
      try {
        map.put(methodReferenceExpression, functionalInterfaceType);
        final JavaResolveResult result = methodReferenceExpression.advancedResolve(false);
        final PsiElement element = result.getElement();
        if (element != null && result.isAccessible() &&
            !(result instanceof MethodCandidateInfo && !((MethodCandidateInfo)result).isApplicable())) {
          if (!(element instanceof PsiMethod)) {
            return callExpression;
          }

          return method != null && MethodSignatureUtil.areSignaturesEqual((PsiMethod)element, method) ? callExpression : null;
        }
      }
      finally {
        map.remove(methodReferenceExpression);
      }
    }
    return null;
  }

  private static boolean isSimpleCall(final PsiVariable[] parameters, PsiCallExpression callExpression, PsiMethod psiMethod) {
    final PsiExpressionList argumentList = callExpression.getArgumentList();
    if (argumentList == null) {
      return false;
    }

    final int calledParametersCount = psiMethod.getParameterList().getParametersCount();
    final PsiExpression[] expressions = argumentList.getExpressions();

    final PsiExpression qualifier;
    if (callExpression instanceof PsiMethodCallExpression) {
      qualifier = ((PsiMethodCallExpression)callExpression).getMethodExpression().getQualifierExpression();
    }
    else if (callExpression instanceof PsiNewExpression) {
      qualifier = ((PsiNewExpression)callExpression).getQualifier();
    }
    else {
      qualifier = null;
    }

    if (expressions.length == 0 && parameters.length == 0) {
      return !(callExpression instanceof PsiNewExpression && qualifier != null);
    }

    final int offset = parameters.length - calledParametersCount;
    if (expressions.length > calledParametersCount || offset < 0) {
      return false;
    }

    for (int i = 0; i < expressions.length; i++) {
      if (!resolvesToParameter(expressions[i], parameters[i + offset])) {
        return false;
      }
    }

    if (offset == 0) {
      if (qualifier != null) {
        final boolean[] parameterUsed = new boolean[] {false};
        qualifier.accept(new JavaRecursiveElementWalkingVisitor() {
          @Override
          public void visitElement(PsiElement element) {
            if (parameterUsed[0]) return;
            super.visitElement(element);
          }

          @Override
          public void visitReferenceExpression(PsiReferenceExpression expression) {
            super.visitReferenceExpression(expression);
            parameterUsed[0] |= ArrayUtil.find(parameters, expression.resolve()) >= 0;
          }
        });
        return !parameterUsed[0];
      }
      return true;
    }

    return resolvesToParameter(qualifier, parameters[0]);
  }

  @Contract("null, _ -> false")
  private static boolean resolvesToParameter(PsiExpression expression, PsiVariable parameter) {
    return expression instanceof PsiReferenceExpression && ((PsiReferenceExpression)expression).resolve() == parameter;
  }

  @Nullable
  static MethodReferenceCandidate extractMethodReferenceCandidateExpression(PsiElement body) {
    final PsiExpression expression = LambdaUtil.extractSingleExpressionFromBody(body);
    if (expression == null) {
      return null;
    }
    if (expression instanceof PsiNewExpression) {
      PsiExpression qualifier = ((PsiNewExpression)expression).getQualifier();
      if (qualifier != null) return null;
      return new MethodReferenceCandidate(expression, true, true);
    }
    else if (expression instanceof PsiMethodCallExpression) {
      return new MethodReferenceCandidate(expression,
                                          checkQualifier(((PsiMethodCallExpression)expression).getMethodExpression().getQualifier()), true);
    }

    JavaCodeStyleSettings javaSettings =
      CodeStyleSettingsManager.getSettings(expression.getProject()).getCustomSettings(JavaCodeStyleSettings.class);
    if (expression instanceof PsiInstanceOfExpression) {
      return new MethodReferenceCandidate(expression, true,
                                          javaSettings.REPLACE_INSTANCEOF);
    }
    else if (expression instanceof PsiBinaryExpression) {
      if (ExpressionUtils.getValueComparedWithNull((PsiBinaryExpression)expression) != null) {
        return new MethodReferenceCandidate(expression, true,
                                            javaSettings.REPLACE_NULL_CHECK);
      }
    }
    else if (expression instanceof PsiTypeCastExpression) {
      PsiTypeElement typeElement = ((PsiTypeCastExpression)expression).getCastType();
      if (typeElement != null) {
        PsiJavaCodeReferenceElement refs = typeElement.getInnermostComponentReferenceElement();
        if (refs != null && refs.getParameterList() != null && refs.getParameterList().getTypeParameterElements().length != 0) {
          return null;
        }
        PsiType type = typeElement.getType();
        if (type instanceof PsiPrimitiveType || PsiUtil.resolveClassInType(type) instanceof PsiTypeParameter) return null;
        return new MethodReferenceCandidate(expression, true, javaSettings.REPLACE_CAST);
      }
    }
    return null;
  }

  public static void replaceAllLambdasWithMethodReferences(PsiElement root) {
    Collection<PsiLambdaExpression> lambdas = PsiTreeUtil.findChildrenOfType(root, PsiLambdaExpression.class);
    if(!lambdas.isEmpty()) {
      for(PsiLambdaExpression lambda : lambdas) {
        replaceLambdaWithMethodReference(lambda);
      }
    }
  }

  @NotNull
  public static PsiExpression replaceLambdaWithMethodReference(@NotNull PsiLambdaExpression lambda) {
    PsiElement body = LambdaUtil.extractSingleExpressionFromBody(lambda.getBody());
    final PsiExpression candidate = canBeMethodReferenceProblem(body, lambda.getParameterList().getParameters(), lambda.getFunctionalInterfaceType(), lambda);
    return tryConvertToMethodReference(lambda, candidate);
  }

  public static boolean checkQualifier(@Nullable PsiElement qualifier) {
    if (qualifier == null) {
      return true;
    }
    final Condition<PsiElement> callExpressionCondition = Conditions.instanceOf(PsiCallExpression.class, PsiArrayAccessExpression.class);
    final Condition<PsiElement> nonFinalFieldRefCondition = expression -> {
      if (expression instanceof PsiReferenceExpression) {
        PsiElement element = ((PsiReferenceExpression)expression).resolve();
        if (element instanceof PsiField && !((PsiField)element).hasModifierProperty(PsiModifier.FINAL)) {
          return true;
        }
      }
      return false;
    };
    return SyntaxTraverser
      .psiTraverser()
      .withRoot(qualifier)
      .filter(Conditions.or(callExpressionCondition, nonFinalFieldRefCondition)).toList().isEmpty();
  }

  @Nullable
  private static PsiMethod getNonAmbiguousReceiver(PsiVariable[] parameters, @NotNull PsiMethod psiMethod) {
    String methodName = psiMethod.getName();
    PsiClass containingClass = psiMethod.getContainingClass();
    if (containingClass == null) return null;

    final PsiMethod[] psiMethods = containingClass.findMethodsByName(methodName, false);
    if (psiMethods.length == 1) return psiMethod;

    final PsiType receiverType = parameters[0].getType();
    for (PsiMethod method : psiMethods) {
      if (isPairedNoReceiver(parameters, receiverType, method)) {
        final PsiMethod[] deepestSuperMethods = psiMethod.findDeepestSuperMethods();
        if (deepestSuperMethods.length > 0) {
          for (PsiMethod superMethod : deepestSuperMethods) {
            PsiMethod validSuperMethod = getNonAmbiguousReceiver(parameters, superMethod);
            if (validSuperMethod != null) return validSuperMethod;
          }
        }
        return null;
      }
    }
    return psiMethod;
  }

  private static boolean isPairedNoReceiver(PsiVariable[] parameters,
                                            PsiType receiverType,
                                            PsiMethod method) {
    final PsiParameter[] nonReceiverCandidateParams = method.getParameterList().getParameters();
    return nonReceiverCandidateParams.length == parameters.length &&
           method.hasModifierProperty(PsiModifier.STATIC) &&
           TypeConversionUtil.areTypesConvertible(nonReceiverCandidateParams[0].getType(), receiverType);
  }

  private static boolean isSoleParameter(@NotNull PsiVariable[] parameters, @Nullable PsiExpression expression) {
    return parameters.length == 1 &&
           expression instanceof PsiReferenceExpression &&
           parameters[0] == ((PsiReferenceExpression)expression).resolve();
  }

  @Nullable
  static String createMethodReferenceText(final PsiElement element,
                                                 final PsiType functionalInterfaceType,
                                                 final PsiVariable[] parameters) {
    if (element instanceof PsiMethodCallExpression) {
      final PsiMethodCallExpression methodCall = (PsiMethodCallExpression)element;

      JavaResolveResult result = methodCall.resolveMethodGenerics();
      final PsiMethod psiMethod = (PsiMethod)result.getElement();
      if (psiMethod == null) {
        return null;
      }

      final PsiReferenceExpression methodExpression = methodCall.getMethodExpression();
      final String qualifierByMethodCall = getQualifierTextByMethodCall(methodCall, functionalInterfaceType, parameters, psiMethod, result.getSubstitutor());
      if (qualifierByMethodCall != null) {
        return qualifierByMethodCall + "::" + ((PsiMethodCallExpression)element).getTypeArgumentList().getText() + methodExpression.getReferenceName();
      }
    }
    else if (element instanceof PsiNewExpression) {
      final String qualifierByNew = getQualifierTextByNewExpression((PsiNewExpression)element);
      if (qualifierByNew != null) {
        return qualifierByNew + ((PsiNewExpression)element).getTypeArgumentList().getText() + "::new";
      }
    }
    else if (element instanceof PsiInstanceOfExpression) {
      if(isSoleParameter(parameters, ((PsiInstanceOfExpression)element).getOperand())) {
        PsiTypeElement type = ((PsiInstanceOfExpression)element).getCheckType();
        if(type != null) {
          return type.getText() + ".class::isInstance";
        }
      }
    }
    else if (element instanceof PsiBinaryExpression) {
      PsiBinaryExpression nullCheck = (PsiBinaryExpression)element;
      PsiExpression operand = ExpressionUtils.getValueComparedWithNull(nullCheck);
      if(operand != null && isSoleParameter(parameters, operand)) {
        IElementType tokenType = nullCheck.getOperationTokenType();
        if(JavaTokenType.EQEQ.equals(tokenType)) {
          return "java.util.Objects::isNull";
        } else if(JavaTokenType.NE.equals(tokenType)) {
          return "java.util.Objects::nonNull";
        }
      }
    }
    else if (element instanceof PsiTypeCastExpression) {
      PsiTypeCastExpression castExpression = (PsiTypeCastExpression)element;
      if(isSoleParameter(parameters, castExpression.getOperand())) {
        PsiTypeElement type = castExpression.getCastType();
        if (type != null) {
          return type.getText() + ".class::cast";
        }
      }
    }
    return null;
  }

  private static String getQualifierTextByNewExpression(PsiNewExpression element) {
    final PsiType newExprType = element.getType();
    if (newExprType == null) {
      return null;
    }

    PsiClass containingClass = null;
    final PsiJavaCodeReferenceElement classReference = element.getClassOrAnonymousClassReference();
    if (classReference != null) {
      final JavaResolveResult resolve = classReference.advancedResolve(false);
      final PsiElement resolveElement = resolve.getElement();
      if (resolveElement instanceof PsiClass) {
        containingClass = (PsiClass)resolveElement;
      }
    }

    String classOrPrimitiveName = null;
    if (containingClass != null) {
      classOrPrimitiveName = getClassReferenceName(containingClass);
    }
    else if (newExprType instanceof PsiArrayType){
      final PsiType deepComponentType = newExprType.getDeepComponentType();
      if (deepComponentType instanceof PsiPrimitiveType) {
        classOrPrimitiveName = deepComponentType.getCanonicalText();
      }
    }

    if (classOrPrimitiveName == null) {
      return null;
    }

    int dim = newExprType.getArrayDimensions();
    while (dim-- > 0) {
      classOrPrimitiveName += "[]";
    }
    return classOrPrimitiveName;
  }

  @Nullable
  private static String getQualifierTextByMethodCall(final PsiMethodCallExpression methodCall,
                                                     final PsiType functionalInterfaceType,
                                                     final PsiVariable[] parameters,
                                                     final PsiMethod psiMethod,
                                                     final PsiSubstitutor substitutor) {

    final PsiExpression qualifierExpression = methodCall.getMethodExpression().getQualifierExpression();

    final PsiClass containingClass = psiMethod.getContainingClass();
    LOG.assertTrue(containingClass != null);

    if (qualifierExpression != null) {
      boolean isReceiverType = false;
      if (qualifierExpression instanceof PsiReferenceExpression && ArrayUtil.find(parameters, ((PsiReferenceExpression)qualifierExpression).resolve()) > -1) {
        isReceiverType = PsiMethodReferenceUtil.isReceiverType(PsiMethodReferenceUtil.getFirstParameterType(functionalInterfaceType, qualifierExpression), containingClass, substitutor);
      }
      return isReceiverType ? composeReceiverQualifierText(parameters, psiMethod, containingClass, qualifierExpression)
                            : qualifierExpression.getText();
    }
    else {
      if (psiMethod.hasModifierProperty(PsiModifier.STATIC)) {
        return getClassReferenceName(containingClass);
      }
      else {
        PsiClass parentContainingClass = PsiTreeUtil.getParentOfType(methodCall, PsiClass.class);
        if (parentContainingClass instanceof PsiAnonymousClass) {
          parentContainingClass = PsiTreeUtil.getParentOfType(parentContainingClass, PsiClass.class, true);
        }
        PsiClass treeContainingClass = parentContainingClass;
        while (treeContainingClass != null && !InheritanceUtil.isInheritorOrSelf(treeContainingClass, containingClass, true)) {
          treeContainingClass = PsiTreeUtil.getParentOfType(treeContainingClass, PsiClass.class, true);
        }
        if (treeContainingClass != null && containingClass != parentContainingClass && treeContainingClass != parentContainingClass) {
          final String treeContainingClassName = treeContainingClass.getName();
          if (treeContainingClassName == null) {
            return null;
          }
          return treeContainingClassName + ".this";
        }
        else {
          return "this";
        }
      }
    }
  }

  @Nullable
  private static String composeReceiverQualifierText(PsiVariable[] parameters,
                                                     PsiMethod psiMethod,
                                                     PsiClass containingClass,
                                                     @NotNull PsiExpression qualifierExpression) {
    if (psiMethod.hasModifierProperty(PsiModifier.STATIC)) {
      return null;
    }

    final PsiMethod nonAmbiguousMethod = getNonAmbiguousReceiver(parameters, psiMethod);
    if (nonAmbiguousMethod == null) {
      return null;
    }

    final PsiClass nonAmbiguousContainingClass = nonAmbiguousMethod.getContainingClass();
    if (!containingClass.equals(nonAmbiguousContainingClass)) {
      return getClassReferenceName(nonAmbiguousContainingClass);
    }

    if (containingClass.isPhysical() &&
        qualifierExpression instanceof PsiReferenceExpression &&
        !PsiTypesUtil.isGetClass(psiMethod) &&
        ArrayUtil.find(parameters, ((PsiReferenceExpression)qualifierExpression).resolve()) > -1) {
      return getClassReferenceName(containingClass);
    }

    final PsiType qualifierExpressionType = qualifierExpression.getType();
    if (qualifierExpressionType != null && !FunctionalInterfaceParameterizationUtil.isWildcardParameterized(qualifierExpressionType)) {
      try {
        final String canonicalText = qualifierExpressionType.getCanonicalText();
        JavaPsiFacade.getElementFactory(containingClass.getProject()).createExpressionFromText(canonicalText + "::foo", qualifierExpression);
        return canonicalText;
      }
      catch (IncorrectOperationException ignore){}
    }
    return getClassReferenceName(containingClass);
  }

  private static String getClassReferenceName(PsiClass containingClass) {
    final String qualifiedName = containingClass.getQualifiedName();
    if (qualifiedName != null) {
      return qualifiedName;
    }
    else {
      return containingClass.getName();
    }
  }

  private static class ReplaceWithMethodRefFix implements LocalQuickFix {
    private String mySuffix;

    public ReplaceWithMethodRefFix(String suffix) {
      mySuffix = suffix;
    }

    @Nls
    @NotNull
    @Override
    public String getName() {
      return getFamilyName() + mySuffix;
    }

    @NotNull
    @Override
    public String getFamilyName() {
      return "Replace lambda with method reference";
    }

    @Override
    public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
      PsiElement element = descriptor.getPsiElement();
      if (element instanceof PsiLambdaExpression) {
        element = LambdaUtil.extractSingleExpressionFromBody(((PsiLambdaExpression)element).getBody());
      }
      final PsiLambdaExpression lambdaExpression = PsiTreeUtil.getParentOfType(element, PsiLambdaExpression.class);
      if (lambdaExpression == null) return;
      tryConvertToMethodReference(lambdaExpression, element);
    }
  }

  @NotNull
  static PsiExpression tryConvertToMethodReference(@NotNull PsiLambdaExpression lambda, PsiElement body) {
    Project project = lambda.getProject();
    PsiType functionalInterfaceType = lambda.getFunctionalInterfaceType();
    if (functionalInterfaceType == null || !functionalInterfaceType.isValid()) return lambda;
    final PsiType denotableFunctionalInterfaceType = RefactoringChangeUtil.getTypeByExpression(lambda);
    if (denotableFunctionalInterfaceType == null) return lambda;

    Collection<PsiComment> comments = ContainerUtil.map(PsiTreeUtil.findChildrenOfType(lambda, PsiComment.class),
                                                        (comment) -> (PsiComment)comment.copy());

    final String methodRefText = createMethodReferenceText(body, functionalInterfaceType, lambda.getParameterList().getParameters());

    if (methodRefText != null) {
      final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
      final PsiExpression psiExpression = factory.createExpressionFromText(methodRefText, lambda);
      final SmartTypePointer typePointer = SmartTypePointerManager.getInstance(project).createSmartTypePointer(denotableFunctionalInterfaceType);
      PsiExpression replace = (PsiExpression)lambda.replace(psiExpression);
      final PsiType functionalTypeAfterReplacement = GenericsUtil.getVariableTypeByExpressionType(((PsiMethodReferenceExpression)replace).getFunctionalInterfaceType());
      functionalInterfaceType = typePointer.getType();
      if (functionalInterfaceType != null && (functionalTypeAfterReplacement == null ||
          !functionalTypeAfterReplacement.equals(functionalInterfaceType))) { //ambiguity
        final PsiTypeCastExpression cast = (PsiTypeCastExpression)factory.createExpressionFromText("(A)a", replace);
        PsiTypeElement castType = cast.getCastType();
        LOG.assertTrue(castType != null);
        castType.replace(factory.createTypeElement(functionalInterfaceType));
        PsiExpression castOperand = cast.getOperand();
        LOG.assertTrue(castOperand != null);
        castOperand.replace(replace);
        replace = (PsiExpression)replace.replace(cast);
      }

      AnonymousCanBeLambdaInspection.restoreComments(comments, replace);
      JavaCodeStyleManager.getInstance(project).shortenClassReferences(replace);
      return replace;
    }
    return lambda;
  }

  static class MethodReferenceCandidate {
    final PsiExpression myExpression;
    final boolean mySafeQualifier;
    final boolean myConformsCodeStyle;

    MethodReferenceCandidate(PsiExpression expression, boolean safeQualifier, boolean conformsCodeStyle) {
      myExpression = expression;
      mySafeQualifier = safeQualifier;
      myConformsCodeStyle = conformsCodeStyle;
    }
  }
}


text:
.class final Landroid/app/SystemServiceRegistry$44;
.super Landroid/app/SystemServiceRegistry$CachedServiceFetcher;
.source "SystemServiceRegistry.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/app/SystemServiceRegistry;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = null
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Landroid/app/SystemServiceRegistry$CachedServiceFetcher",
        "<",
        "Landroid/app/usage/StorageStatsManager;",
        ">;"
    }
.end annotation

# direct methods
.method constructor <init>()V
    .locals 0

    invoke-direct {p0}, Landroid/app/SystemServiceRegistry$CachedServiceFetcher;-><init>()V

    return-void
.end method

# virtual methods
.method public createService(Landroid/app/ContextImpl;)Landroid/app/usage/StorageStatsManager;
    .locals 2
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/ServiceManager$ServiceNotFoundException;
        }
    .end annotation

    const-string/jumbo v1, "storagestats"

    invoke-static {v1}, Landroid/os/ServiceManager;->getServiceOrThrow(Ljava/lang/String;)Landroid/os/IBinder;

    move-result-object v1

    invoke-static {v1}, Landroid/app/usage/IStorageStatsManager$Stub;->asInterface(Landroid/os/IBinder;)Landroid/app/usage/IStorageStatsManager;

    move-result-object v0

    new-instance v1, Landroid/app/usage/StorageStatsManager;

    invoke-direct {v1, p1, v0}, Landroid/app/usage/StorageStatsManager;-><init>(Landroid/content/Context;Landroid/app/usage/IStorageStatsManager;)V

    return-object v1
.end method

.method public bridge synthetic createService(Landroid/app/ContextImpl;)Ljava/lang/Object;
    .locals 1
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/ServiceManager$ServiceNotFoundException;
        }
    .end annotation

    invoke-virtual {p0, p1}, Landroid/app/SystemServiceRegistry$44;->createService(Landroid/app/ContextImpl;)Landroid/app/usage/StorageStatsManager;

    move-result-object v0

    return-object v0
.end method

redpajama_set_name: RedPajamaGithub


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

<!--
  Copyright 2016 Goldman Sachs.
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing,
  software distributed under the License is distributed on an
  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  KIND, either express or implied.  See the License for the
  specific language governing permissions and limitations
  under the License.
  -->

<MithraObject objectType="transactional">
    <PackageName>com.gs.fw.common.mithra.test.domain</PackageName>
    <ClassName>TimezoneTestWithSource</ClassName>
    <DefaultTable>TIMEZONE_TEST_WITH_SOURCE</DefaultTable>
    <SourceAttribute name="deskId" javaType="String" />

    <Attribute name="timezoneTestId" javaType="int" columnName="TIMEZONE_TEST_ID"  primaryKey="true"/>
    <Attribute name="insensitiveDate" javaType="Timestamp" columnName="INSENSISTIVE_DATE" />
    <Attribute name="databaseDate" javaType="Timestamp" columnName="DATABASE_DATE" timezoneConversion="convert-to-database-timezone"/>
    <Attribute name="utcDate" javaType="Timestamp" columnName="UTC_DATE" timezoneConversion="convert-to-utc"/>
</MithraObject>


text:
import $ from 'jquery'
import MiniApp from './mini-app'
import facade from './facade'
import avatarModal from './modules/avatar/modal'
import avatarImage from './modules/avatar/image'
import userForm from './modules/user/form'

$(document).on('turbolinks:load', function () {
    const avatar = new MiniApp(facade)
    avatar.register('.avatar', avatarImage)
    avatar.register('#user-form', userForm)
    avatar.register('#avatar-modal', avatarModal)
    avatar.start()
})


text:
module.exports = function(config) {
  config.set({

    // base path, that will be used to resolve files and exclude
    basePath: '..',

    // frameworks to use
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      'bower_components/angular/angular.js',
      'bower_components/angular-mocks/angular-mocks.js',
      'bower_components/codemirror/lib/codemirror.js',
      'src/ui-codemirror.js',
      'test/*.spec.js'
    ],

    // list of files to exclude
    exclude: [

    ],

    // test results reporter to use
    // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
    reporters: ['dots'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera (has to be installed with `npm install karma-opera-launcher`)
    // - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
    // - PhantomJS
    // - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
    browsers: ['Chrome', 'Firefox', 'PhantomJS'],

    // If browser does not capture in given timeout [ms], kill it
    captureTimeout: 60000,

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false
  });

  if(process.env.TRAVIS){
    config.set({
      browsers: ['TravisCI_Chrome', 'Firefox', 'PhantomJS'],
      customLaunchers: {
        TravisCI_Chrome: {
          base: 'Chrome',
          flags: ['--no-sandbox']
        }
      },
    });
  }
};


text:
(function() {
  var AbstractController, bluebird,
    __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

  bluebird = require("bluebird");

  module.exports = AbstractController = (function() {
    function AbstractController(connection) {
      this.connection = connection;
      this.closeWithSecurityError = __bind(this.closeWithSecurityError, this);
      this.closeWithInternalError = __bind(this.closeWithInternalError, this);
      this.closeWithUnexpectedMessage = __bind(this.closeWithUnexpectedMessage, this);
      this.closeWithProtocolError = __bind(this.closeWithProtocolError, this);
      this.dispatch = __bind(this.dispatch, this);
    }

    AbstractController.prototype.dispatch = function(message) {
      throw new Error("Not implemented.");
    };

    AbstractController.prototype.closeWithProtocolError = function(error, message) {
      if (message == null) {
        message = null;
      }
      this.connection.close(4001, message != null ? message : "Protocol error.");
      return bluebird.reject(error);
    };

    AbstractController.prototype.closeWithUnexpectedMessage = function(message) {
      var _ref;
      return this.closeWithProtocolError("Unexpected message type: " + ((_ref = message.type) != null ? _ref : '<unknown>') + ".");
    };

    AbstractController.prototype.closeWithInternalError = function(error) {
      this.connection.close(4002, "Internal server error.");
      return bluebird.reject(error);
    };

    AbstractController.prototype.closeWithSecurityError = function(error) {
      this.connection.close(4003, "Request forbidden by security policy.");
      return bluebird.reject(error);
    };

    return AbstractController;

  })();

}).call(this);

//# sourceMappingURL=AbstractController.js.map


text:
/*
 * User: wij
 * Date: 25/02/2011 4:52
 */
namespace EATFSConnector
{
	partial class AboutWindow
	{
		/// <summary>
		/// Designer variable used to keep track of non-visual components.
		/// </summary>
		private System.ComponentModel.IContainer components = null;

		/// <summary>
		/// Disposes resources used by the form.
		/// </summary>
		/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
		protected override void Dispose(bool disposing)
		{
			if (disposing) {
				if (components != null) {
					components.Dispose();
				}
			}
			base.Dispose(disposing);
		}

		/// <summary>
		/// This method is required for Windows Forms designer support.
		/// Do not change the method contents inside the source code editor. The Forms designer might
		/// not be able to load this method if it was changed manually.
		/// </summary>
		private void InitializeComponent()
		{
			System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AboutWindow));
			this.ApplicationTitle = new System.Windows.Forms.Label();
			this.VersionLabel = new System.Windows.Forms.Label();
			this.Version = new System.Windows.Forms.Label();
			this.DateLabel = new System.Windows.Forms.Label();
			this.AssemblyDate = new System.Windows.Forms.Label();
			this.AuthorName = new System.Windows.Forms.Label();
			this.AuthorEmail = new System.Windows.Forms.LinkLabel();
			this.HomePage = new System.Windows.Forms.LinkLabel();
			this.OKButton = new System.Windows.Forms.Button();
			this.Logo = new System.Windows.Forms.PictureBox();
			((System.ComponentModel.ISupportInitialize)(this.Logo)).BeginInit();
			this.SuspendLayout();
			//
			// ApplicationTitle
			//
			this.ApplicationTitle.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
			this.ApplicationTitle.Location = new System.Drawing.Point(13, 11);
			this.ApplicationTitle.Name = "ApplicationTitle";
			this.ApplicationTitle.Size = new System.Drawing.Size(267, 23);
			this.ApplicationTitle.TabIndex = 0;
			this.ApplicationTitle.Text = "EA TFS Connector";
			//
			// VersionLabel
			//
			this.VersionLabel.Location = new System.Drawing.Point(13, 91);
			this.VersionLabel.Name = "VersionLabel";
			this.VersionLabel.Size = new System.Drawing.Size(100, 23);
			this.VersionLabel.TabIndex = 1;
			this.VersionLabel.Text = "Version:";
			//
			// Version
			//
			this.Version.Location = new System.Drawing.Point(71, 91);
			this.Version.Name = "Version";
			this.Version.Size = new System.Drawing.Size(100, 23);
			this.Version.TabIndex = 2;
			this.Version.Text = "assemblyVersion";
			//
			// DateLabel
			//
			this.DateLabel.Location = new System.Drawing.Point(13, 104);
			this.DateLabel.Name = "DateLabel";
			this.DateLabel.Size = new System.Drawing.Size(100, 23);
			this.DateLabel.TabIndex = 3;
			this.DateLabel.Text = "Date:";
			//
			// AssemblyDate
			//
			this.AssemblyDate.Location = new System.Drawing.Point(71, 104);
			this.AssemblyDate.Name = "AssemblyDate";
			this.AssemblyDate.Size = new System.Drawing.Size(100, 23);
			this.AssemblyDate.TabIndex = 4;
			this.AssemblyDate.Text = "AssemblyDate";
			//
			// AuthorName
			//
			this.AuthorName.Location = new System.Drawing.Point(13, 43);
			this.AuthorName.Name = "AuthorName";
			this.AuthorName.Size = new System.Drawing.Size(132, 23);
			this.AuthorName.TabIndex = 6;
			this.AuthorName.Text = "© 2016 Bellekens";
			//
			// AuthorEmail
			//
			this.AuthorEmail.Location = new System.Drawing.Point(13, 57);
			this.AuthorEmail.Name = "AuthorEmail";
			this.AuthorEmail.Size = new System.Drawing.Size(127, 23);
			this.AuthorEmail.TabIndex = 7;
			this.AuthorEmail.TabStop = true;
			this.AuthorEmail.Text = "geert@bellekens.com";
			this.AuthorEmail.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.AuthorEmailLinkClicked);
			//
			// HomePage
			//
			this.HomePage.Location = new System.Drawing.Point(12, 140);
			this.HomePage.Name = "HomePage";
			this.HomePage.Size = new System.Drawing.Size(233, 23);
			this.HomePage.TabIndex = 8;
			this.HomePage.TabStop = true;
			this.HomePage.Text = "EA TFS Connector homepage";
			this.HomePage.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.HomePageLinkClicked);
			//
			// OKButton
			//
			this.OKButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
			this.OKButton.AutoSize = true;
			this.OKButton.DialogResult = System.Windows.Forms.DialogResult.OK;
			this.OKButton.Location = new System.Drawing.Point(199, 165);
			this.OKButton.Name = "OKButton";
			this.OKButton.Size = new System.Drawing.Size(75, 23);
			this.OKButton.TabIndex = 9;
			this.OKButton.Text = "OK";
			this.OKButton.UseVisualStyleBackColor = true;
			this.OKButton.Click += new System.EventHandler(this.OKButtonClick);
			//
			// Logo
			//
			this.Logo.Image = ((System.Drawing.Image)(resources.GetObject("Logo.Image")));
			this.Logo.Location = new System.Drawing.Point(167, 37);
			this.Logo.Name = "Logo";
			this.Logo.Size = new System.Drawing.Size(100, 88);
			this.Logo.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
			this.Logo.TabIndex = 10;
			this.Logo.TabStop = false;
			//
			// AboutWindow
			//
			this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.ClientSize = new System.Drawing.Size(286, 200);
			this.Controls.Add(this.Logo);
			this.Controls.Add(this.OKButton);
			this.Controls.Add(this.HomePage);
			this.Controls.Add(this.AuthorEmail);
			this.Controls.Add(this.AuthorName);
			this.Controls.Add(this.AssemblyDate);
			this.Controls.Add(this.DateLabel);
			this.Controls.Add(this.Version);
			this.Controls.Add(this.VersionLabel);
			this.Controls.Add(this.ApplicationTitle);
			this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
			this.MaximizeBox = false;
			this.MinimizeBox = false;
			this.Name = "AboutWindow";
			this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
			this.Text = "About EA TFS Connector";
			((System.ComponentModel.ISupportInitialize)(this.Logo)).EndInit();
			this.ResumeLayout(false);
			this.PerformLayout();

		}
		private System.Windows.Forms.PictureBox Logo;
		private System.Windows.Forms.Button OKButton;
		private System.Windows.Forms.LinkLabel HomePage;
		private System.Windows.Forms.LinkLabel AuthorEmail;
		private System.Windows.Forms.Label AuthorName;
		private System.Windows.Forms.Label AssemblyDate;
		private System.Windows.Forms.Label DateLabel;
		private System.Windows.Forms.Label Version;
		private System.Windows.Forms.Label VersionLabel;
		private System.Windows.Forms.Label ApplicationTitle;
	}
}


text:
import Mixin from '@ember/object/mixin';
import $ from 'jquery';
import DS from 'ember-data';
import { attr } from 'ember-flexberry-data/utils/attributes';

export let Model = Mixin.create({
  diagramPrimaryKey: DS.attr('string'),
  diagramType: DS.attr('string'),
  subsystem: DS.belongsTo('fd-subsystem', { inverse: 'diagramLinks', async: false, polymorphic: true }),
  getValidations: function () {
    let parentValidations = this._super();
    let thisValidations = {
      subsystem: { presence: true }
    };
    return $.extend(true, {}, parentValidations, thisValidations);
  },
  init: function () {
    this.set('validations', this.getValidations());
    this._super(...arguments);
  }
});
export let defineBaseModel = function (modelClass) {
  modelClass.reopenClass({
    _parentModelName: 'fd-object-in-system'
  });
};

export let defineProjections = function (modelClass) {
  modelClass.defineProjection('DiagramLink', 'fd-diagram-link', {
    name: attr('Название'),
    description: attr('Описание')
  });
};


text:
package dpla.ingestion3.mappers.utils

import org.json4s.JsonAST._

import scala.util.{Try, Success, Failure}
import scala.xml.{Elem, MetaData, Node, NodeSeq, Text}

/**
  * For ripping data out of original records
  *
  * @tparam T
  */
trait Extractor[T] {
  // Extract zero or one value
  def extractString(fieldname: String)(implicit data: T): Option[String]
  def extractString(data: T): Option[String]

  // Extract zero to many values
  def extractStrings(fieldname: String)(implicit data: T): Seq[String]
  def extractStrings(data: T): Seq[String]
}

/**
  * XML Extractor
  */
trait XmlExtractor extends Extractor[NodeSeq] {

  // list of common xml namespaces
  protected val dc = "http://purl.org/dc/elements/1.1/"
  protected val dcterms = "http://purl.org/dc/terms/"
  protected val edm = "http://www.europeana.eu/schemas/edm/"
  protected val foaf = "http://xmlns.com/foaf/0.1/"
  protected val mods = "http://www.loc.gov/mods/v3"
  protected val oclcdc = "http://worldcat.org/xmlschemas/oclcdc-1.0/"
  protected val oai_dc="http://www.openarchives.org/OAI/2.0/oai_dc/"
  protected val oai_pmh="http://www.openarchives.org/OAI/2.0/"
  protected val owl = "http://www.w3.org/2002/07/owl#"
  protected val qdc="http://worldcat.org/xmlschemas/qdc-1.0/"
  protected val rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
  protected val rdfa = "http://www.w3.org/ns/rdfa#"
  protected val skos = "http://www.w3.org/2004/02/skos/core#"
  protected val xsf = "http://www.w3.org/2001/XMLSchema#"
  protected val xsi = "http://www.w3.org/2001/XMLSchema-instance"

  /**
    *
    * @param fieldName
    * @param xml
    * @return
    */
  override def extractString(fieldName: String)(implicit xml: NodeSeq): Option[String] =
    extractString(xml \ fieldName)

  /**
    *
    */
  def extractStrings(fieldName: String)(implicit xml: NodeSeq): Seq[String] =
    extractStrings(xml \ fieldName)

  /**
    *
    * @param xValue
    * @return
    */
  override def extractString(xValue: NodeSeq): Option[String] = {
    xValue match {
      case v if v.text.nonEmpty => Some(v.text)
      case _ => None
    }
  }

  /**
   *
   * @param xValue
   * @return
   */
  def extractString(xValue: Node): Option[String] = {
    xValue match {
      case v if v.text.nonEmpty => Some(v.text)
      case _ => None
    }
  }

  /**
    * TODO swing back and deeper dive into NodeSeq vs JValue/JObject
    *
    * @param xValue
    * @return Seq[String]
    */
  override def extractStrings(xValue: NodeSeq): Seq[String] = {
    val values = xValue match {
      case v if v.size > 1 => v.flatMap(value => extractString(value))
      case _ => extractString(xValue) match {
        case Some(stringValue) => Seq(stringValue)
        case _ => Seq()
      }
    }
    values.filter(_.nonEmpty)
  }

  /**
    * Exclude nodes that do not have an attribute that matches att and value parameters
    *
    * @param node Node XML node to examine
    * @param att String name of attribute
    * @param value String value of attribute
    * @return Boolean
    */
  def filterAttribute(node: Node, att: String, value: String): Boolean = (node \ ("@" + att)).text.toLowerCase == value.toLowerCase

  /**
    * Get Nodes that match the given attribute name and attribute value
    * @param e Elem to examine
    * @param att String name of attribute
    * @param value String value of attribute
    * @return NodeSeq of matching nodes
    */
  def getByAttribute(e: Elem, att: String, value: String): NodeSeq = {
    e \\ "_" filter { n => filterAttribute(n, att, value) }
  }

  def getByAttribute(e: NodeSeq, att: String, value: String): NodeSeq = {
    getByAttribute(e.asInstanceOf[Elem], att, value)
  }

  /**
    * Exclude nodes that do not have an attribute that matches att and any of the given value parameters
    *
    * @param node Node XML node to examine
    * @param att String name of attribute
    * @param values Seq[String] all values of attributes
    * @return Boolean
    */
  def filterAttributeListOptions(node: Node, att: String, values: Seq[String]): Boolean =
    values.map(_.toLowerCase).contains((node \ ("@" + att)).text.toLowerCase)

  /**
    * Get nodes that match any of the given values for a given attribute.
    *
    * E.g. getByAttributesListOptions(elem, "color", Seq("red", "blue")) will return all nodes where
    *   attribute "color=red" or "color=blue"
    *
    * @param e Elem to examine
    * @param att String name of attribute
    * @param values Seq[String] Values of attribute
    * @return NodeSeq of matching nodes
    */
  def getByAttributeListOptions(e: Elem, att: String, values: Seq[String]): NodeSeq = {
    e \\ "_" filter { n => filterAttributeListOptions(n, att, values) }
  }

  def getByAttributeListOptions(e: NodeSeq, att: String, values: Seq[String]): NodeSeq = {
    getByAttributeListOptions(e.asInstanceOf[Elem], att, values)
  }

  /**
    * For each given node, get any immediate children that are text values.
    * Ignore nested text values.
    *
    * E.g. <foo>bar</foo> => "bar"
    * E.g. <foo><bar>bat</bar></foo> => nothing
    *
    * @param xValue NodeSeq
    * @return Seq[String]
    */
  def extractChildStrings(xValue: NodeSeq): Seq[String] = xValue.flatMap { node =>
    node.child.collect{ case Text(t) => t }.map(_.trim).filterNot(_.isEmpty)
  }

  /**
   *
   * @param node
   * @param attribute
   * @return
   */
  def getAttributeValue(node: Node, attribute: String): Option[String] = {
    node.attributes.headOption match {
      case Some(metadata: MetaData) => Try {
          metadata.asAttrMap(attribute)
        } match {
        case Success(s) => Some(s)
        case Failure(_) => None
      }
      case _ => None
    }
  }
}

/**
  * Json extractor
  */
trait JsonExtractor extends Extractor[JValue] {
  /**
    * Pulls a single string from the implicit json data.
    *
    * @param fieldName Name of field to extract string from.
    * @param json      JSON document or subdocument
    * @return Some(string) if one could be found. Will fail
    *         on non-primitive values like arrays or objects.
    */
  def extractString(fieldName: String)(implicit json: JValue): Option[String] =
    extractString(json \ fieldName)

  /**
    * Pulls a Seq[String] of values from the implicit json
    *
    * @param fieldName Name of field to extract string from.
    * @param json      JSON document or subdocument
    * @return A Seq[String].
    *
    *         If the field is an array, the Seq will contain the array contents,
    *         if they were themselves primitive values.
    *
    *         If the field is an object, the Seq will contain the object field
    *         values, if those were primitive values.
    *
    *         If the field is a primitive, a Seq with a single member is returned.
    *
    *         Otherwise, an empty Seq is returned.
    */
  def extractStrings(fieldName: String)(implicit json: JValue): Seq[String]
    = extractStrings(json \ fieldName)

  /**
    * Pulls a Seq[String] of values from the implicit json from the specified field name
    * at any depth
    *
    * @param fieldName
    * @param json
    * @return
    */
  def extractStringsDeep(fieldName: String)(implicit json: JValue): Seq[String]
    = extractStrings(json \\ fieldName)

  /**
    * @see definition of extractStrings(fieldName: String), save for this version
    *      can be called with a parameter that generates a JValue, such as json4s'
    *      path-walking syntax: jsonTree \ "someChild" \\ "someDecendant"
    *
    */
  def extractStrings(jValue: JValue): Seq[String] = {
    val values = jValue match {
      case JArray(array) => array.flatMap(entry => extractString(entry))
      case JObject(fields) => fields.flatMap({case (_, value) => extractString(value)})
      case _ => extractString(jValue) match {
        case Some(stringValue) => Seq(stringValue)
        case None => Seq()
      }
    }
    values.filter(_.nonEmpty)
  }

  /**
    * @see definition of extractString(fieldName: String), save for this version
    *      can be called with a parameter that generates a JValue, such as json4s'
    *      path-walking syntax: jsonTree \ "someChild" \\ "someDecendant"
    *
    */
  def extractString(jValue: JValue): Option[String] = jValue match {
    case JBool(bool) => Some(bool.toString)
    case JDecimal(decimal) => Some(decimal.toString)
    case JDouble(double) => Some(double.toString)
    case JInt(int) => Some(int.toString())
    case JString(string) => Some(string)
    case _ => None
  }

  /**
    * Sometimes we need to map the keys
    *
    * @param jValue
    * @return
    */
  def extractKeys(jValue: JValue): Seq[String] = jValue match {
    case JArray(array) => array.flatMap(entry => extractKeys(entry))
    case JObject(fields) => fields.map { case(field, _) => field }
    case _ => Seq()
  }

  /**
    * Wraps the JValue in JArray if it is not already a JArray
    * Addresses the problem of inconsistent data types in value field.
    * e.g. '"prop": ["val1"]' vs '"prop": "val1"'
    *
    * @param jvalue
    * @return
    */
  // TODO Can we make this an implicit?
  def iterify(jvalue: JValue): JArray = jvalue match {
    case JArray(j) => JArray(j)
    case JNothing => JArray(List())
    case _ => JArray(List(jvalue))
  }
}


text:
package com.example.project13_2_1;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;

public class Project13_2_1 extends Activity
{
	ImageView show;
	Bitmap bitmap;
	Handler handler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			if(msg.what ==0x123)
			{
				show.setImageBitmap(bitmap);
			}
		}
	};
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		show = (ImageView)findViewById(R.id.show);
		new Thread()
		{
			public void run()
			{
				try {
					URL url = new URL("http://www.crazyit.org/"+"attachments/month_1008/20100812_7763e970f"+"822325bfb019ELQVym8tW3A.png");
					InputStream is = url.openStream();
					bitmap = BitmapFactory.decodeStream(is);
					handler.sendEmptyMessage(0x123);
					is.close();

					is = url.openStream();
					OutputStream os = openFileOutput("crazyit.png", MODE_WORLD_READABLE);
					byte[] buff = new byte[1024];
					int hasRead = 0;
					while((hasRead  = is.read(buff))>0)
					{
						os.write(buff,0,hasRead);
					}
					is.close();
					os.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}
}


text:
"""Test certbot_nginx._internal.display_ops."""
import unittest

from certbot.display import util as display_util
from certbot.tests import util as certbot_util
from certbot_nginx._internal import parser
from certbot_nginx._internal.display_ops import select_vhost_multiple
import test_util as util

class SelectVhostMultiTest(util.NginxTest):
    """Tests for certbot_nginx._internal.display_ops.select_vhost_multiple."""

    def setUp(self):
        super().setUp()
        nparser = parser.NginxParser(self.config_path)
        self.vhosts = nparser.get_vhosts()

    def test_select_no_input(self):
        self.assertFalse(select_vhost_multiple([]))

    @certbot_util.patch_display_util()
    def test_select_correct(self, mock_util):
        mock_util().checklist.return_value = (
            display_util.OK, [self.vhosts[3].display_repr(),
                              self.vhosts[2].display_repr()])
        vhs = select_vhost_multiple([self.vhosts[3],
                                     self.vhosts[2],
                                     self.vhosts[1]])
        self.assertTrue(self.vhosts[2] in vhs)
        self.assertTrue(self.vhosts[3] in vhs)
        self.assertFalse(self.vhosts[1] in vhs)

    @certbot_util.patch_display_util()
    def test_select_cancel(self, mock_util):
        mock_util().checklist.return_value = (display_util.CANCEL, "whatever")
        vhs = select_vhost_multiple([self.vhosts[2], self.vhosts[3]])
        self.assertFalse(vhs)

if __name__ == "__main__":
    unittest.main()  # pragma: no cover


text:
import { Command, ThemeIcon, TreeItem, TreeItemCollapsibleState, Uri } from 'vscode';
import { GlyphChars } from '../../constants';
import { Container } from '../../container';
import { GitUri } from '../../git/gitUri';
import { View } from '../viewBase';
import { ContextValues, PageableViewNode, ViewNode } from './viewNode';

export class MessageNode extends ViewNode {
	constructor(
		view: View,
		parent: ViewNode,
		private readonly _message: string,
		private readonly _description?: string,
		private readonly _tooltip?: string,
		private readonly _iconPath?:
			| string
			| Uri
			| {
					light: string | Uri;
					dark: string | Uri;
			  }
			| ThemeIcon,
		private readonly _contextValue?: string,
	) {
		super(GitUri.unknown, view, parent);
	}

	getChildren(): ViewNode[] | Promise<ViewNode[]> {
		return [];
	}

	getTreeItem(): TreeItem | Promise<TreeItem> {
		const item = new TreeItem(this._message, TreeItemCollapsibleState.None);
		item.contextValue = this._contextValue ?? ContextValues.Message;
		item.description = this._description;
		item.tooltip = this._tooltip;
		item.iconPath = this._iconPath;
		return item;
	}
}

export class CommandMessageNode extends MessageNode {
	constructor(
		view: View,
		parent: ViewNode,
		private readonly _command: Command,
		message: string,
		description?: string,
		tooltip?: string,
		iconPath?:
			| string
			| Uri
			| {
					light: string | Uri;
					dark: string | Uri;
			  }
			| ThemeIcon,
	) {
		super(view, parent, message, description, tooltip, iconPath);
	}

	override getTreeItem(): TreeItem | Promise<TreeItem> {
		const item = super.getTreeItem();
		if (item instanceof TreeItem) {
			item.command = this._command;
			return item;
		}

		return item.then(i => {
			i.command = this._command;
			return i;
		});
	}
}

export class UpdateableMessageNode extends ViewNode {
	override readonly id: string;

	constructor(
		view: View,
		parent: ViewNode,
		id: string,
		private _message: string,
		private _tooltip?: string,
		private _iconPath?:
			| string
			| Uri
			| {
					light: string | Uri;
					dark: string | Uri;
			  }
			| ThemeIcon,
	) {
		super(GitUri.unknown, view, parent);
		this.id = id;
	}

	getChildren(): ViewNode[] | Promise<ViewNode[]> {
		return [];
	}

	getTreeItem(): TreeItem | Promise<TreeItem> {
		const item = new TreeItem(this._message, TreeItemCollapsibleState.None);
		item.id = this.id;
		item.contextValue = ContextValues.Message;
		item.tooltip = this._tooltip;
		item.iconPath = this._iconPath;
		return item;
	}

	update(
		changes: {
			message?: string;
			tooltip?: string | null;
			iconPath?:
				| string
				| null
				| Uri
				| {
						light: string | Uri;
						dark: string | Uri;
				  }
				| ThemeIcon;
		},
		view: View,
	) {
		if (changes.message !== undefined) {
			this._message = changes.message;
		}

		if (changes.tooltip !== undefined) {
			this._tooltip = changes.tooltip === null ? undefined : changes.tooltip;
		}

		if (changes.iconPath !== undefined) {
			this._iconPath = changes.iconPath === null ? undefined : changes.iconPath;
		}

		view.triggerNodeChange(this);
	}
}

export abstract class PagerNode extends ViewNode {
	constructor(
		view: View,
		parent: ViewNode & PageableViewNode,
		protected readonly message: string,
		protected readonly previousNode?: ViewNode,
		protected readonly options?: {
			context?: Record<string, unknown>;
			pageSize?: number;
			getCount?: () => Promise<number | undefined>;
		}, // protected readonly pageSize: number = Container.instance.config.views.pageItemLimit, // protected readonly countFn?: () => Promise<number | undefined>, // protected readonly context?: Record<string, unknown>, // protected readonly beforeLoadCallback?: (mode: 'all' | 'more') => void,
	) {
		super(GitUri.unknown, view, parent);
	}

	async loadAll() {
		const count = (await this.options?.getCount?.()) ?? 0;
		return this.view.loadMoreNodeChildren(
			this.parent! as ViewNode & PageableViewNode,
			count > 5000 ? 5000 : 0,
			this.previousNode,
			this.options?.context,
		);
	}

	loadMore() {
		return this.view.loadMoreNodeChildren(
			this.parent! as ViewNode & PageableViewNode,
			this.options?.pageSize ?? Container.instance.config.views.pageItemLimit,
			this.previousNode,
			this.options?.context,
		);
	}

	getChildren(): ViewNode[] | Promise<ViewNode[]> {
		return [];
	}

	getTreeItem(): TreeItem | Promise<TreeItem> {
		const item = new TreeItem(this.message, TreeItemCollapsibleState.None);
		item.contextValue = ContextValues.Pager;
		item.command = this.getCommand();
		return item;
	}

	override getCommand(): Command | undefined {
		return {
			title: 'Load more',
			command: 'gitlens.views.loadMoreChildren',
			arguments: [this],
		};
	}
}

export class LoadMoreNode extends PagerNode {
	constructor(
		view: View,
		parent: ViewNode & PageableViewNode,
		previousNode: ViewNode,
		options?: {
			context?: Record<string, unknown>;
			getCount?: () => Promise<number | undefined>;
			message?: string;
			pageSize?: number;
		},
	) {
		super(
			view,
			parent,
			options?.message ??
				(options?.pageSize === 0
					? `Load all ${GlyphChars.Space}${GlyphChars.Dash}${GlyphChars.Space} this may take a while`
					: 'Load more'),
			previousNode,
			options,
		);
	}
}


text:
<?php

namespace Julien\Bundle\ArtistBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Artist
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="Julien\Bundle\ArtistBundle\Entity\ArtistRepository")
 */
class Artist
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

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

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

    /**
    * @ORM\ManyToOne(targetEntity="Work", inversedBy="artists", cascade={"persist"})
    * @ORM\joinColumn(name="work_id", referencedColumnName="id", nullable=false)
    */
    private $work;

    /**
    * @ORM\ManyToMany(targetEntity="Type", inversedBy="artists", cascade={"persist"})
    * @ORM\JoinTable(name="artist_type")
    */
    protected $types;

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

    /**
     * Set career
     *
     * @param string $career
     * @return Artist
     */
    public function setCareer($career)
    {
        $this->career = $career;

        return $this;
    }

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

    /**
     * Set birthdayAt
     *
     * @param \DateTime $birthdayAt
     * @return Artist
     */
    public function setBirthdayAt($birthdayAt)
    {
        $this->birthdayAt = $birthdayAt;

        return $this;
    }

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


text:
<?php

namespace Gtk\Larasearch\Engines;

use Closure;
use Gtk\Larasearch\Builder;
use Psr\Log\LoggerInterface;
use Elasticsearch\ClientBuilder;
use Elasticsearch\Client as Elastic;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Collection as BaseCollection;
use Elasticsearch\Connections\ConnectionFactoryInterface;

class ElasticEngine extends Engine
{
    /**
     * The Elastic client.
     *
     * @var \Elasticsearch\Client
     */
    protected $elastic;

    /**
     * The Elastic index.
     *
     * @var string
     */
    protected $index;

    /**
     * Create a new engine instance.
     *
     * @param  \Elasticsearch\Client $elastic
     * @return void
     */
    public function __construct(Elastic $elastic, $index)
    {
        $this->elastic = $elastic;

        $this->index = $index;
    }

    /**
     * Build a new client from the provided config.
     *
     * @param  array $config
     * @return \Elasticsearch\Client
     */
    public static function buildClient(array $config)
    {
        $clientBuilder = ClientBuilder::create()
            ->setHosts($config['hosts'])
            ->setRetries($config['retries'])
            ->setHandler(call_user_func('\Elasticsearch\ClientBuilder::' . $config['handler'] . 'Handler'))
            ->setConnectionPool($config['connection_pool'])
            ->setSelector($config['selector'])
            ->setSerializer($config['serializer']);

        if ($config['ssl_verification']) {
            $clientBuilder->setSSLVerification($config['ssl_verification']);
        }

        if ($config['log']) {
            $logger = isset($config['logger']) && $config['logger'] instanceof LoggerInterface
                ? $config['logger']
                : ClientBuilder::defaultLogger($config['log_path'], $config['log_level']);

            $clientBuilder->setLogger($logger);
        }

        if (isset($config['connection_factory']) && $config['connection_factory'] instanceof ConnectionFactoryInterface) {
            $clientBuilder->setConnectionFactory($config['connection_factory']);
        }

        if (isset($config['endpoint']) && $config['endpoint'] instanceof Closure) {
            $clientBuilder->setEndpoint($config['endpoint']);
        }

        return $clientBuilder->build();
    }

    /**
     * Update the given model in the index.
     *
     * @param  \Illuminate\Database\Eloquent\Collection  $models
     * @return void
     */
    public function update($models)
    {
        $body = new BaseCollection();

        $models->each(function ($model) use ($body) {
            $searchableArray = $model->toSearchableArray();

            if (empty($searchableArray)) {
                return;
            }

            $body->push([
                'index' => [
                    '_index' => $this->index,
                    '_type' => $model->searchableAs(),
                    '_id' => $model->getKey(),
                ],
            ]);

            $body->push($searchableArray);
        });

        if ($body->count()) {
            $this->elastic->bulk([
                'refresh' => true,
                'body' => $body->all(),
            ]);
        }
    }

    /**
     * Remove the given model from the index.
     *
     * @param  \Illuminate\Database\Eloquent\Collection  $models
     * @return void
     */
    public function delete($models)
    {
        $body = new BaseCollection();

        $models->each(function ($model) use ($body) {
            $body->push([
                'delete' => [
                    '_index' => $this->index,
                    '_type' => $model->searchableAs(),
                    '_id' => $model->getKey(),
                ],
            ]);
        });

        if ($body->count()) {
            $this->elastic->bulk([
                'refresh' => true,
                'body' => $body->all(),
            ]);
        }
    }

    /**
     * Perform the given search on the engine.
     *
     * @param  \Gtk\Larasearch\Builder  $builder
     * @return mixed
     */
    public function search(Builder $builder)
    {
        return $this->performSearch($builder, [
            'query' => $this->buildRawQuery($builder),
            'size' => $builder->limit ?: 10000,
        ]);
    }

    /**
     * Perform the given search on the engine.
     *
     * @param  \Gtk\Larasearch\Builder  $builder
     * @param  int  $perPage
     * @param  int  $page
     * @return mixed
     */
    public function paginate(Builder $builder, $perPage, $page)
    {
        $results = $this->performSearch($builder, [
            'query' => $this->buildRawQuery($builder),
            'size' => $perPage,
            'from' => ($page - 1) * $perPage,
        ]);

        $builder->total = $this->getTotalCount($results);

        return $results;
    }

    /**
     * Perform the given search on the engine.
     *
     * @param  \Gtk\Larasearch\Builder  $builder
     * @param  array  $options
     * @return mixed
     */
    protected function performSearch(Builder $builder, array $options = [])
    {
        $params = [
            'index' => $this->index,
            'type' => $builder->model->searchableAs(),
            'body' => $options['query'],
        ];

        if (isset($options['size'])) {
            $params['size'] = $options['size'];
        }

        if (isset($options['from'])) {
            $params['from'] = $options['from'];
        }

        if ($builder->callback) {
            return call_user_func(
                $builder->callback,
                $this->elastic,
                $query
            );
        }

        return $this->elastic->search($params);
    }

    /**
     * Build raw query.
     *
     * @param  \Gtk\Larasearch\Builder  $builder
     * @return array
     */
    protected function buildRawQuery(Builder $builder)
    {
        if ($this->isRawQuery($builder->query)) {
            return $builder->query;
        }

        $filters = [];

        $matches[] = [
            'match' => [
                '_all' => [
                    'query' => $builder->query,
                    'fuzziness' => 1,
                ]
            ]
        ];

        foreach ($builder->wheres as $field => $value) {
            if (is_numeric($value)) {
                $filters[] = [
                    'term' => [
                        $field => $value,
                    ],
                ];
            } elseif (is_string($value)) {
                $matches[] = [
                    'match' => [
                        $field => [
                            'query' => $value,
                            'operator' => 'and',
                        ],
                    ],
                ];
            }
        }

        return [
            'query' => [
                'filtered' => [
                    'filter' => $filters,
                    'query' => [
                        'bool' => [
                            'must' => $matches,
                        ]
                    ],
                ],
            ],
        ];
    }

    /**
     * Check if the query is raw query.
     *
     * @param  mixed
     * @return true|false
     */
    protected function isRawQuery($query)
    {
        return is_array($query);
    }

    /**
     * Map the given results to instances of the given model.
     *
     * @param  mixed  $results
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function map($results, $model)
    {
        if ($results['hits']['total'] === 0) {
            return Collection::make();
        }

        $keys = $this->getIds($results);

        $models = $model->whereIn(
            $model->getQualifiedKeyName(), $keys
        )->get()->keyBy($model->getKeyName());

        return collect($results['hits']['hits'])->map(function ($hit) use ($model, $models) {
            $key = $hit['_source'][$model->getKeyName()];

            if (isset($models[$key])) {
                return $models[$key];
            }
        })->filter();
    }

    /**
     * Pluck and return the primary keys of the results.
     *
     * @param  mixed  $results
     * @return \Illuminate\Support\Collection
     */
    public function getIds($results)
    {
        return collect($results['hits']['hits'])
            ->pluck('_id')
            ->values()
            ->all();
    }

    /**
     * Get the total count from a raw result returned by the engine.
     *
     * @param  mixed  $results
     * @return int
     */
    public function getTotalCount($results)
    {
        return $results['hits']['total'];
    }
}


text:
package cn.epai.admin.security;

import com.epai.contract.model.sys.SysUser;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;

import org.apache.shiro.codec.Base64;
import org.apache.shiro.codec.Hex;
import org.apache.shiro.crypto.AesCipherService;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Md5Hash;
import java.security.Key;

/**
 * @Author jihua.li
 * @Date 2016/12/5 11:33
 */
public final class ShiroEncryptUtils {

	/**
	 * Base64加密
	 *
	 * @param plainPassword
	 *            明文密码
	 * @return 密文密码
	 */
	public static String encryptBase64(String plainPassword) {
		Preconditions.checkArgument(!Strings.isNullOrEmpty(plainPassword), "原始密码不能为空");
		return Base64.encodeToString(plainPassword.getBytes());
	}

	/**
	 * Base64解密
	 *
	 * @param cipherText
	 *            密文密码
	 * @return 明文密码
	 */
	public static String decryptBase64(String cipherText) {
		Preconditions.checkArgument(!Strings.isNullOrEmpty(cipherText), "解密密文不能为空");
		return Base64.decodeToString(cipherText);
	}

	/**
	 * 16进制加密
	 *
	 * @param plainPassword
	 *            明文密码
	 * @return 密文
	 */
	public static String encriptHex(String plainPassword) {
		Preconditions.checkArgument(!Strings.isNullOrEmpty(plainPassword), "原始密码不能为空");
		return Hex.encodeToString(plainPassword.getBytes());
	}

	/**
	 * 16进制解密
	 *
	 * @param cipherText
	 *            密文
	 * @return 明文
	 */
	public static String decriptHex(String cipherText) {
		Preconditions.checkArgument(!Strings.isNullOrEmpty(cipherText), "解密密文不能为空");
		return new String(Hex.decode(cipherText));
	}

	/**
	 * 生成AES加密Key
	 *
	 * @return
	 */
	public static String generateKey() {
		AesCipherService aesCipherService = new AesCipherService();
		Key key = aesCipherService.generateNewKey();
		return Base64.encodeToString(key.getEncoded());
	}

	public static SysUser md5EncriptPassword(String account_name, String user_password) {
		Preconditions.checkArgument(!Strings.isNullOrEmpty(account_name), "加密用户名不能为空");
		Preconditions.checkArgument(!Strings.isNullOrEmpty(user_password), "加密密码不能为空");
		SecureRandomNumberGenerator generator = new SecureRandomNumberGenerator();
		String salt = generator.nextBytes(24).toString();
		String cipherPassword = new Md5Hash(user_password, account_name + salt, 2).toString();
		SysUser user = new SysUser();
		user.setCredentialsSalt(salt);
		user.setAccountName(account_name);
		user.setPassword(cipherPassword);
		return user;
	}

	public static boolean verifyOldPwd(String salt,String oldEncryptPwd,String oldPwd,String account){
       String newCipherPwd=new Md5Hash(oldPwd, account + salt, 2).toString();
	   return oldEncryptPwd.equals(newCipherPwd);
	}
}


text:
<?php

namespace MVCFundamental;

use \Patterns\Traits\SingletonTrait;
use \Library\ServiceContainer\ServiceContainer;
use \MVCFundamental\Interfaces\FrontControllerInterface;
use \MVCFundamental\Interfaces\AppKernelInterface;
use \MVCFundamental\Exception\ErrorException;
use \MVCFundamental\Commons\ServiceContainerProviderTrait;
use \MVCFundamental\Commons\Helper;
use \Patterns\Commons\Collection;
use \Library\Helper\Directory as DirectoryHelper;
use \Library\Logger;

/**
 * Class AppKernel: the root core of the application
 */
class AppKernel
    extends ServiceContainer
    implements  AppKernelInterface
{

    /**
     * This class inherits from \Patterns\Traits\SingletonTrait
     * This class inherits from \MVCFundamental\Commons\ServiceContainerProviderTrait
     */
    use SingletonTrait, ServiceContainerProviderTrait;

// -------------------------
// System environment
// -------------------------

    /**
     * @var array
     */
    protected static $_api = array(
        'controller'        => 'MVCFundamental\Interfaces\ControllerInterface',
        'error_controller'  => 'MVCFundamental\Interfaces\ErrorControllerInterface',
        'response'          => 'MVCFundamental\Interfaces\ResponseInterface',
        'request'           => 'MVCFundamental\Interfaces\RequestInterface',
        'router'            => 'MVCFundamental\Interfaces\RouterInterface',
        'route'             => 'MVCFundamental\Interfaces\RouteInterface',
        'template_engine'   => 'MVCFundamental\Interfaces\TemplateEngineInterface',
        'template'          => 'MVCFundamental\Interfaces\TemplateInterface',
        'layout'            => 'MVCFundamental\Interfaces\LayoutInterface',
        'locator'           => 'MVCFundamental\Interfaces\LocatorInterface',
        'event'             => 'MVCFundamental\Interfaces\EventInterface',
        'event_manager'     => 'MVCFundamental\Interfaces\EventManagerInterface',
        'logger'            => 'Psr\Log\LoggerInterface',
    );

    /**
     * @var array
     */
    protected static $_constructors = array(
        'route_item'        => 'route',
        'template_item'     => 'template',
        'layout_item'       => 'layout',
        'event_item'        => 'event',
    );

// -------------------------
// SingletonInterface
// -------------------------

    /**
     * Avoid public construction of the object and prefer the `getInstance()` static singleton access
     */
    public function __construct()
    {
        $this->init();
    }

// -------------------------
// Service Container system
// -------------------------

    /**
     * @param   string  $name
     * @param   object  $object
     * @return  bool
     * @throws  \MVCFundamental\Exception\ErrorException
     */
    protected function _validateService($name, $object)
    {
        if (array_key_exists($name, self::$_api) && false===self::isApiValid($name, $object)) {
            throw new ErrorException(
                sprintf('A "%s" service must implement interface "%s" (get "%s")!',
                    $name, self::$_api[$name], get_class($object))
            );
        }
        return true;
    }

// -------------------------
// API Manager
// -------------------------

    /**
     * @param   string  $name
     * @return  null|string
     * @api
     */
    public static function getApi($name)
    {
        return (isset(self::$_api[$name]) ? self::$_api[$name] : null);
    }

    /**
     * @param   string          $name
     * @param   object|callable $object
     * @return  bool
     * @api
     */
    public static function isApiValid($name, $object)
    {
        return (bool) (
            array_key_exists($name, self::$_api) &&
            is_object($object) &&
            Helper::classImplements($object, self::$_api[$name])
        );
    }

    /**
     * @param   string  $name
     * @param   string  $class
     * @param   array   $arguments
     * @return  object
     * @throws  \MVCFundamental\Exception\ErrorException
     * @api
     */
    public static function apiFactory($name, $class, array $arguments = array())
    {
        if (!class_exists($class)) {
            $cls_name = self::getApi($class);
        } else {
            $cls_name = $class;
        }
        if (class_exists($cls_name)) {
            $objectReflection = new \ReflectionClass($cls_name);
            $object = $objectReflection->newInstanceArgs($arguments);
            if (!self::isApiValid($name, $object)) {
                throw new ErrorException(
                    sprintf('A "%s" service must implement interface "%s" (get "%s")!',
                        $name, self::$_api[$name], get_class($object))
                );
            }
            return $object;
        } else {
            throw new ErrorException(
                sprintf('Class "%s" not found!', $cls_name)
            );
        }
    }

// -------------------------
// FrontControllerAwareInterface
// -------------------------

    /**
     * @param \MVCFundamental\Interfaces\FrontControllerInterface $app
     */
    public static function setFrontController(FrontControllerInterface $app)
    {
        self::set('front_controller', $app, true);
    }

    /**
     * @return \MVCFundamental\Interfaces\FrontControllerInterface
     */
    public static function getFrontController()
    {
        return self::get('front_controller');
    }

// -------------------------
// AppKernelInterface
// -------------------------

    /**
     * @param   \MVCFundamental\Interfaces\FrontControllerInterface $app
     * @return  void
     * @throws  \MVCFundamental\Exception\ErrorException
     */
    public static function boot(FrontControllerInterface $app)
    {
        // stores the FrontController
        self::setFrontController($app);

        // define internal handlers
        set_exception_handler(array(__CLASS__, 'handleException'));
        register_shutdown_function(array(__CLASS__, 'handleShutdown'));
        if (self::getFrontController()->getOption('convert_error_to_exception')==true) {
            set_error_handler(array(__CLASS__, 'handleError'));
        }

        // the required temporary directory
        $tmp_dir = self::getFrontController()->getOption('temp_dir');
        if (
            empty($tmp_dir) ||
            (!file_exists($tmp_dir) && !@DirectoryHelper::create($tmp_dir)) ||
            !is_dir($tmp_dir) ||
            !is_writable($tmp_dir)
        ) {
            $tmp_dir = DirectoryHelper::slashDirname(sys_get_temp_dir()).'mvc-fundamental';
            if (!@DirectoryHelper::ensureExists($tmp_dir)) {
                throw new ErrorException(
                    sprintf('The "%s" temporary directory can not be created or is not writable (and a default one could not be taken)!', $tmp_dir)
                );
            }
            self::getFrontController()->setOption('temp_dir', $tmp_dir);
        }

        // the application logger
        if (self::getFrontController()->getOption('minimum_log_level')==null) {
            self::getFrontController()->setOption('log_level',
                self::getFrontController()->isMode('production') ? Logger::WARNING : Logger::DEBUG
            );
        }
        $logger_options = array(
            'duplicate_errors'  => false,
            'directory'         => self::getFrontController()->getOption('temp_dir'),
            'minimum_log_level' => self::getFrontController()->getOption('log_level'),
        );
        $logger_class = self::getFrontController()->getOption('app_logger');
        if (!class_exists($logger_class) || !Helper::classImplements($logger_class, self::getApi('logger'))) {
            throw new ErrorException(
                sprintf('A logger must exist and implement the "%s" interface (for class "%s")!',
                    self::getApi('logger'), $logger_class)
            );
        }
        self::set('logger', new $logger_class($logger_options));

        // load services
        foreach (self::getFrontController()->getOptions() as $var=>$val) {
            if (array_key_exists($var, self::$_api)) {
                self::set($var, self::apiFactory($var, $val));
            }

            if (array_key_exists($var, self::$_constructors)) {
                $cls_index  = self::$_constructors[$var];
                self::getInstance()->setProvider(
                    $var, function ($app, $name, array $arguments = array()) use ($val, $cls_index) {
                        return $app::apiFactory($cls_index, $val, $arguments);
                    }
                );
            }
        }

        self::get('event_manager')->setEventClass(self::getFrontController()->getOption('event_item'));
    }

    /**
     * @var bool Does the system already correctly terminated
     */
    private static $_terminated = false;

    /**
     * This must be called when the system terminates its run
     *
     * @param FrontControllerInterface $app
     * @return mixed
     */
    public static function terminate(FrontControllerInterface $app)
    {
        if (!self::$_terminated) {
        }
    }

    /**
     * This must abort a runtime safely
     *
     * @param   \Exception $e
     * @return  void
     */
    public static function abort(\Exception $e)
    {
    }

    /**
     * @param   \Exception $e
     * @return  void
     * @throws  \MVCFundamental\Exception\ErrorException
     */
    public static function handleException(\Exception $e)
    {
        $error_controller = self::getFrontController()->getOption('error_controller');
        try {
            self::getFrontController()->callControllerAction(
                $error_controller, 'index', array($e)
            );
        } catch (\Exception $f) {
            throw new ErrorException(
                $f->getMessage(), $f->getCode(),
                method_exists($f, 'getSeverity') ? $f->getSeverity() : 0,
                $f->getFile(), $f->getLine(), $e
            );
        }
    }

    /**
     * @param   int     $errno
     * @param   string  $errstr
     * @param   string  $errfile
     * @param   int     $errline
     * @param   array   $errcontext
     * @return  void
     * @throws  \MVCFundamental\Exception\ErrorException
     */
    public static function handleError($errno = 0, $errstr = '', $errfile = '', $errline = 0, array $errcontext = array())
    {
        if (!(error_reporting() & $errno)) {
            return true;
        }
        throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
    }

    /**
     * This must handle runtime shutdown
     *
     * @return void
     */
    public static function handleShutdown()
    {
        self::terminate(self::getFrontController());
    }

    /**
     * @param mixed $level
     * @param string $message
     * @param array $context
     * @return mixed
     */
    public static function log($level, $message, array $context = array())
    {
        if (self::getInstance()->hasService('logger')) {
            self::get('logger')->log($level, $message, $context);
        }
    }
}


text:
from django.db import models, migrations
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        ('cms', '0011_auto_20150419_1006'),
    ]

    operations = [
        migrations.AlterField(
            model_name='globalpagepermission',
            name='sites',
            field=models.ManyToManyField(help_text='If none selected, user haves granted permissions to all sites.', to='sites.Site', verbose_name='sites', blank=True),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='usersettings',
            name='user',
            field=models.OneToOneField(on_delete=models.CASCADE, related_name='djangocms_usersettings', editable=False, to=settings.AUTH_USER_MODEL),
            preserve_default=True,
        ),
    ]


text:
using Core.Aggregates;
using Newtonsoft.Json;

namespace MeetingsSearch.Meetings;

public class Meeting: Aggregate
{
    public string Name { get; private set; } = default!;

    public Meeting() { }

    [JsonConstructor]
    public Meeting(Guid id, string name)
    {
        Id = id;
        Name = name;
    }
}


text:
if [[ $1 = "--help" ]]; then
cat <<EOF
${0##*/}, version %version%
This script makes all the post update with backup for single pairs incl. backups

Usage: ${0##*/}
EOF
   exit 0
fi

name=$(csg_get_interaction_property name)

#could be done by a overwrite somewhere
is_done "post_update-$name" && exit 0

tasklist=$(csg_get_interaction_property --allow-empty inverse.post_update)
[[ -n $tasklist ]] && msg "Postupd tasks for $name: $tasklist"
i=1
#after all other task shift dpot
for task in $tasklist shift; do
  echo "Doing postupd task '$task' for '${name}'"

  #save the current one
  critical mv "${name}.pot.new" "${name}.pot.${i}"

  #perform postupd task
  do_external postupd "$task" "${name}.pot.${i}" "${name}.pot.new"

  ((i++))
done
mark_done "post_update-$name"


text:
Stackdriver Debugger is a feature of the Google Cloud Platform that lets you
inspect the state of an application at any code location without using logging
statements and without stopping or slowing down your applications. Your users
are not impacted during debugging. Using the production debugger you can capture
the local variables and call stack and link it back to a specific line location
in your source code. You can use this to analyze the production state of your
application and understand the behavior of your code in production.

For general information about Stackdriver Debugger, read [Stackdriver Debugger
Documentation](https://cloud.google.com/debugger/docs/).

The Stackdriver Debugger Ruby library, `google-cloud-debugger`, provides:

* Easy-to-use debugger instrumentation that reports state data, such as value of
  program variables and the call stack, to Stackdriver Debugger when the code at
  a breakpoint location is executed in your Ruby application. See the
  [instrumenting your app](#instrumenting-your-app) section for how to debug
  your application, in both development and production.
* An idiomatic Ruby API for registerying debuggee application, and querying or
  manipulating breakpoints in registered Ruby debuggee application. See
  [Debugger API](#stackdriver-debugger-api) section for an introduction to
  Stackdriver Debugger API.

## Instrumenting Your App

This instrumentation library provides the following features to help you debug
your applications in production:

* Automatic application registration. It facilitates multiple running instances
  of same version of application when hosted in production.
* A background debugger agent that runs side-by-side with your application that
  automatically collects state data when code is executed at breakpoint
  locations.
* A Rack middleware and Railtie that automatically manages the debugger agent
  for Ruby on Rails and other Rack-based Ruby applications.

When this library is configured in your running application, and the source code
and breakpoints are setup through the Google Cloud Console, You'll be able to
[interact](https://cloud.google.com/debugger/docs/debugging) with your
application in real time through the [Stackdriver Debugger
UI](https://console.cloud.google.com/debug?_ga=1.84295834.280814654.1476313407).
This library also integrates with Google App Engine Flexible to make debuggee
application configuration more seemless.

Note that when no breakpoints are created, the debugger agent consumes very
little resource and has no interference with the running application. Once
breakpoints are created and depends on where the breakpoints are located, the
debugger agent may add a little latency onto each request. The application
performance will be back to normal after all breakpoints are finished being
evaluated. Be aware the more breakpoints are created, or the harder to reach the
breakpoints, the more resource the debugger agent would need to consume.

### Using instrumentation with Ruby on Rails

To install application instrumentation in your Ruby on Rails app, add this gem,
`google-cloud-debugger`, to your Gemfile and update your bundle. Then add the
following line to your `config/application.rb` file:

```ruby
require "google/cloud/debugger/rails"
```

This will load a Railtie that automatically integrates with the Rails framework
by injecting a Rack middleware. The Railtie also takes in the following Rails
configuration as parameter of the debugger agent initialization:

```ruby
# Explicitly enable or disable Stackdriver Debugger Agent
config.google_cloud.use_debugger = true
# Shared Google Cloud Platform project identifier
config.google_cloud.project_id = "gcloud-project"
# Google Cloud Platform project identifier for Stackdriver Debugger only
config.google_cloud.debugger.project_id = "debugger-project"
# Shared Google Cloud authentication json file
config.google_cloud.keyfile = "/path/to/keyfile.json"
# Google Cloud authentication json file for Stackdriver Debugger only
config.google_cloud.debugger.keyfile = "/path/to/debugger/keyfile.json"
# Stackdriver Debugger Agent service name identifier
config.google_cloud.debugger.service_name = "my-ruby-app"
# Stackdriver Debugger Agent service version identifier
config.google_cloud.debugger.service_version = "v1"
```

See the {Google::Cloud::Debugger::Railtie} class for more information.

### Using instrumentation with Sinatra

To install application instrumentation in your Sinatra app, add this gem,
`google-cloud-debugger`, to your Gemfile and update your bundle. Then add the
following lines to your main application Ruby file:

```ruby
require "google/cloud/debugger"
use Google::Cloud::Debugger::Middleware
```

This will install the debugger middleware in your application.

Configuration parameters may also be passed in as arguments to Middleware.

```ruby
require "google/cloud/debugger"
use Google::Cloud::Debugger::Middleware project: "debugger-project-id",
                                        keyfile: "/path/to/keyfile.json",
                                        service_name: "my-ruby-app",
                                        service_version: "v1"
```

### Using instrumentation with other Rack-based frameworks

To install application instrumentation in an app using another Rack-based web
framework, add this gem, `google-cloud-debugger`, to your Gemfile and update
your bundle. Then add install the debugger middleware in your middleware stack.
In most cases, this means adding these lines to your `config.ru` Rack
configuration file:

```ruby
require "google/cloud/debugger"
use Google::Cloud::Debugger::Middleware
```

Some web frameworks have an alternate mechanism for modifying the middleware
stack. Consult your web framework's documentation for more information.

### The Stackdriver diagnostics suite

The debugger library is part of the Stackdriver diagnostics suite, which also
includes error reporting, log analysis, and tracing analysis. If you include the
`stackdriver` gem in your Gemfile, this debugger library will be included
automatically. In addition, if you include the `stackdriver` gem in an
application using Ruby On Rails, the Railties will be installed automatically.
See the documentation for the "stackdriver" gem for more details.

## Stackdriver Debugger API

This library also includes an easy to use Ruby client for the Stackdriver
Debugger API. This API provides calls to register debuggee application, as well
as creating or modifying breakpoints.

For further information on the Debugger API, see
{Google::Cloud::Debugger::Project}

### Registering debuggee application

```ruby
require "google/cloud/debugger/v2"

controller_client = Google::Cloud::Debugger::V2::Controller::Client.new
debuggee = Google::Cloud::Debugger::V2::Debuggee.new
response = controller_client.register_debuggee debuggee: debuggee
debuggee_id = response.debuggee.id
```
See [Stackdriver Debugger Debuggee
doc](https://cloud.google.com/debugger/api/reference/rpc/google.devtools.clouddebugger.v2#google.devtools.clouddebugger.v2.Debuggee)
on fields necessary for registerying a debuggee.

Upon successful registration, the response debuggee object will contain a
debuggee_id that's later needed to interact with the other Stackdriver Debugger
API.

### List Active Breakpoints

```ruby
require "google/cloud/debugger/v2"

controller_client = Google::Cloud::Debugger::V2::Controller::Client.new

debuggee_id = ''
response = controller_client.list_active_breakpoints debuggee_id: debuggee_id
breakpoints = response.breakpoints
```

### Update Active Breakpoint

Users can send custom snapshots for active breakpoints using this API.

```ruby
require "google/cloud/debugger/v2"

controller_client = Google::Cloud::Debugger::V2::Controller::Client.new
debuggee_id = ''
breakpoint = Google::Cloud::Debugger::V2::Breakpoint.new
response = controller_client.update_active_breakpoint(
  debuggee_id: debuggee_id, breakpoint: breakpoint)
```

See [Stackdriver Debugger Breakpoint
doc](https://cloud.google.com/debugger/api/reference/rpc/google.devtools.clouddebugger.v2#google.devtools.clouddebugger.v2.Breakpoint)
for all available fields for breakpoint.

### Set Breakpoint

```ruby
require "google/cloud/debugger/v2"

debugger_client = Google::Cloud::Debugger::V2::Debugger::Client.new
debuggee_id = ''
breakpoint = Google::Cloud::Debugger::V2::Breakpoint.new
client_version = ''
response = debugger_client.set_breakpoint(
  debuggee_id: debuggee_id, breakpoint: breakpoint,
  client_version: client_version)
```

See [Stackdriver Debugger Breakpoint
doc](https://cloud.google.com/debugger/api/reference/rpc/google.devtools.clouddebugger.v2#google.devtools.clouddebugger.v2.Breakpoint)
for fields needed to specify breakpoint location.

### Get Breakpoint

```ruby
require "google/cloud/debugger/v2"

debugger_client = Google::Cloud::Debugger::V2::Debugger::Client.new
debuggee_id = ''
breakpoint_id = ''
client_version = ''
response = debugger_client.get_breakpoint(
  debuggee_id: debuggee_id, breakpoint_id: breakpoint_id,
  client_version: client_version)
```

### Delete Breakpoint

```ruby
require "google/cloud/debugger/v2"

debugger_client = Google::Cloud::Debugger::V2::Debugger::Client.new
debuggee_id = ''
breakpoint_id = ''
client_version = ''
debugger_client.delete_breakpoint(
  debuggee_id: debuggee_id, breakpoint_id: breakpoint_id,
  client_version: client_version)
```

### List Breakpoints

```ruby
require "google/cloud/debugger/v2"

debugger_client = Google::Cloud::Debugger::V2::Debugger::Client.new
debuggee_id = ''
client_version = ''
response = debugger_client.list_breakpoints(
  debuggee_id: debuggee_id, client_version: client_version)
```

### List Debuggees

```ruby
require "google/cloud/debugger/v2"

debugger_client = Google::Cloud::Debugger::V2::Debugger::Client.new
project = ''
client_version = ''
response = debugger_client.list_debuggees(
  project: project, client_version: client_version)
```

## Additional information

Stackdriver Debugger can be configured to use gRPC's logging. To learn more, see
the [Logging guide](LOGGING.md).


text:
package router.connectors

import mocks.MockHttp
import mocks.config.MockAppConfig
import mocks.httpParser.MockSelfAssessmentHttpParser
import play.api.http.Status
import play.api.libs.json.{JsValue, Json}
import router.httpParsers.SelfAssessmentHttpParser.SelfAssessmentOutcome
import support.UnitSpec
import uk.gov.hmrc.http.HttpResponse

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

class DividendsConnectorSpec extends UnitSpec with MockHttp with MockAppConfig with MockSelfAssessmentHttpParser {

  class Setup {

    object TestConnector
        extends DividendsConnector(
          mockHttp,
          mockSelfAssessmentHttpParser,
          mockAppConfig
        )

    MockAppConfig.dividendsApiUrl returns dividendsApiUrl
    MockAppConfig.environmentHeaders returns None
  }

  lazy val dividendsApiUrl = "test-di-api-url"
  val path                 = "/2.0/test-path"

  "amend" should {
    "return a HttpResponse" when {
      "a successful HttpResponse is returned" in new Setup {
        val response    = HttpResponse(Status.OK, Json.obj().toString())
        val requestJson = Json.obj("test" -> "request json")

        MockSelfAssessmentHttpParser.read.returns(Right(response))
        MockHttp.PUT[JsValue, SelfAssessmentOutcome](s"$dividendsApiUrl$path", requestJson).returns(Future.successful(Right(response)))
        await(TestConnector.put(path, requestJson)(hc)) shouldBe Right(response)
      }
    }
  }

  "retrieve" should {
    "return a HttpResponse" when {
      "a successful HttpResponse is returned" in new Setup {
        val response = HttpResponse(Status.OK, Json.obj().toString())

        MockSelfAssessmentHttpParser.read.returns(Right(response))
        MockHttp.GET[SelfAssessmentOutcome](s"$dividendsApiUrl$path").returns(Future.successful(Right(response)))
        await(TestConnector.get(path)(hc)) shouldBe Right(response)
      }
    }
  }

}