text:
package com.intellij.codeInsight.daemon.impl.quickfix;

import com.intellij.codeInsight.*;
import com.intellij.codeInsight.completion.proc.VariablesProcessor;
import com.intellij.codeInsight.daemon.QuickFixBundle;
import com.intellij.codeInsight.generation.OverrideImplementUtil;
import com.intellij.codeInsight.generation.PsiGenerationInfo;
import com.intellij.codeInsight.intention.impl.CreateClassDialog;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.codeInsight.template.*;
import com.intellij.ide.fileTemplates.FileTemplate;
import com.intellij.ide.fileTemplates.FileTemplateManager;
import com.intellij.ide.fileTemplates.FileTemplateUtil;
import com.intellij.ide.fileTemplates.JavaTemplateUtil;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorModificationUtil;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.codeStyle.SuggestedNameInfo;
import com.intellij.psi.codeStyle.VariableKind;
import com.intellij.psi.scope.util.PsiScopesUtil;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiShortNamesCache;
import com.intellij.psi.search.searches.ClassInheritorsSearch;
import com.intellij.psi.statistics.JavaStatisticsManager;
import com.intellij.psi.util.ProximityLocation;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiTypesUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.util.proximity.PsiProximityComparator;
import com.intellij.refactoring.util.RefactoringUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.Processor;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.*;

/**
 * @author mike
 */
public class CreateFromUsageUtils {
  private static final Logger LOG = Logger.getInstance(
    "#com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageUtils");
  private static final int MAX_GUESSED_MEMBERS_COUNT = 10;
  private static final int MAX_RAW_GUESSED_MEMBERS_COUNT = 2 * MAX_GUESSED_MEMBERS_COUNT;

  static boolean isValidReference(PsiReference reference, boolean unresolvedOnly) {
    if (!(reference instanceof PsiJavaReference)) return false;
    JavaResolveResult[] results = ((PsiJavaReference)reference).multiResolve(true);
    if(results.length == 0) return false;
    if (!unresolvedOnly) {
      for (JavaResolveResult result : results) {
        if (!result.isValidResult()) return false;
        if (result.getElement() instanceof PsiPackage) return false;
      }
    }
    return true;
  }

  static boolean isValidMethodReference(PsiReference reference, PsiMethodCallExpression call) {
    if (!(reference instanceof PsiJavaReference)) return false;
    try {
      JavaResolveResult candidate = ((PsiJavaReference) reference).advancedResolve(true);
      PsiElement result = candidate.getElement();
      return result instanceof PsiMethod && PsiUtil.isApplicable((PsiMethod)result, candidate.getSubstitutor(), call.getArgumentList());
    }
    catch (ClassCastException cce) {
      // rear case
      return false;
    }
  }

  static boolean shouldCreateConstructor(PsiClass targetClass, PsiExpressionList argList, PsiMethod candidate) {
    if (argList == null) return false;
    if (candidate == null) {
      return targetClass != null && !targetClass.isInterface() && !(targetClass instanceof PsiTypeParameter) &&
             !(argList.getExpressions().length == 0 && targetClass.getConstructors().length == 0);
    }
    else {
      return !PsiUtil.isApplicable(candidate, PsiSubstitutor.EMPTY, argList);
    }
  }

  public static void setupMethodBody(PsiMethod method) throws IncorrectOperationException {
    PsiClass aClass = method.getContainingClass();
    setupMethodBody(method, aClass);
  }

  public static void setupMethodBody(final PsiMethod method, final PsiClass aClass) throws IncorrectOperationException {
    FileTemplate template = FileTemplateManager.getInstance(method.getProject()).getCodeTemplate(JavaTemplateUtil.TEMPLATE_FROM_USAGE_METHOD_BODY);
    setupMethodBody(method, aClass, template);
  }

  public static void setupMethodBody(final PsiMethod method, final PsiClass aClass, final FileTemplate template) throws
                                                                                IncorrectOperationException {
    PsiType returnType = method.getReturnType();
    if (returnType == null) {
      returnType = PsiType.VOID;
    }

    JVMElementFactory factory = JVMElementFactories.getFactory(aClass.getLanguage(), aClass.getProject());

    LOG.assertTrue(!aClass.isInterface() ||
                   PsiUtil.isLanguageLevel8OrHigher(method) ||
                   method.getLanguage() != JavaLanguage.INSTANCE, "Interface bodies should be already set up");

    FileType fileType = FileTypeManager.getInstance().getFileTypeByExtension(template.getExtension());
    Properties properties = new Properties();
    properties.setProperty(FileTemplate.ATTRIBUTE_RETURN_TYPE, returnType.getPresentableText());
    properties.setProperty(FileTemplate.ATTRIBUTE_DEFAULT_RETURN_VALUE,
                           PsiTypesUtil.getDefaultValueOfType(returnType));

    JavaTemplateUtil.setClassAndMethodNameProperties(properties, aClass, method);

    @NonNls String methodText;
    CodeStyleManager csManager = CodeStyleManager.getInstance(method.getProject());
    try {
      String bodyText = template.getText(properties);
      if (!bodyText.isEmpty()) bodyText += "\n";
      methodText = returnType.getPresentableText() + " foo () {\n" + bodyText + "}";
      methodText = FileTemplateUtil.indent(methodText, method.getProject(), fileType);
    }
    catch (ProcessCanceledException e) {
      throw e;
    }
    catch (Exception e) {
      throw new IncorrectOperationException("Failed to parse file template", (Throwable)e);
    }

    if (methodText != null) {
      PsiMethod m;
      try {
        m = factory.createMethodFromText(methodText, aClass);
      }
      catch (IncorrectOperationException e) {
        ApplicationManager.getApplication().invokeLater(new Runnable() {
              @Override
              public void run() {
                Messages.showErrorDialog(QuickFixBundle.message("new.method.body.template.error.text"),
                                         QuickFixBundle.message("new.method.body.template.error.title"));
              }
            });
        return;
      }
      PsiCodeBlock oldBody = method.getBody();
      PsiCodeBlock newBody = m.getBody();
      LOG.assertTrue(newBody != null);
      if (oldBody != null) {
        oldBody.replace(newBody);
      } else {
        method.addBefore(newBody, null);
      }
      csManager.reformat(method);
    }
  }

  public static void setupEditor(PsiMethod method, final Editor newEditor) {
    PsiCodeBlock body = method.getBody();
    if (body != null) {
      PsiElement l = PsiTreeUtil.skipSiblingsForward(body.getLBrace(), PsiWhiteSpace.class);
      PsiElement r = PsiTreeUtil.skipSiblingsBackward(body.getRBrace(), PsiWhiteSpace.class);
      if (l != null && r != null) {
        int start = l.getTextRange().getStartOffset();
        int end = r.getTextRange().getEndOffset();
        newEditor.getCaretModel().moveToOffset(Math.max(start, end));
        if (end < start) {
          newEditor.getCaretModel().moveToOffset(end + 1);
          CodeStyleManager styleManager = CodeStyleManager.getInstance(method.getProject());
          PsiFile containingFile = method.getContainingFile();
          final String lineIndent = styleManager.getLineIndent(containingFile, Math.min(start, end));
          PsiDocumentManager manager = PsiDocumentManager.getInstance(method.getProject());
          manager.doPostponedOperationsAndUnblockDocument(manager.getDocument(containingFile));
          EditorModificationUtil.insertStringAtCaret(newEditor, lineIndent);
          EditorModificationUtil.insertStringAtCaret(newEditor, "\n", false, false);
        }
        else {
          //correct position caret for groovy and java methods
          final PsiGenerationInfo<PsiMethod> info = OverrideImplementUtil.createGenerationInfo(method);
          info.positionCaret(newEditor, true);
        }
        newEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
      }
    }
  }

  static void setupMethodParameters(PsiMethod method, TemplateBuilder builder, PsiExpressionList argumentList,
                                    PsiSubstitutor substitutor) throws IncorrectOperationException {
    if (argumentList == null) return;
    PsiExpression[] args = argumentList.getExpressions();

    setupMethodParameters(method, builder, argumentList, substitutor, args);
  }

  public static void setupMethodParameters(final PsiMethod method, final TemplateBuilder builder, final PsiElement contextElement,
                                           final PsiSubstitutor substitutor, final PsiExpression[] arguments) {
    setupMethodParameters(method, builder, contextElement, substitutor, ContainerUtil.map2List(arguments, Pair.<PsiExpression, PsiType>createFunction(null)));
  }

  static void setupMethodParameters(final PsiMethod method, final TemplateBuilder builder, final PsiElement contextElement,
                                    final PsiSubstitutor substitutor, final List<Pair<PsiExpression, PsiType>> arguments)
    throws IncorrectOperationException {
    PsiManager psiManager = method.getManager();
    JVMElementFactory factory = JVMElementFactories.getFactory(method.getLanguage(), method.getProject());

    PsiParameterList parameterList = method.getParameterList();

    GlobalSearchScope resolveScope = method.getResolveScope();

    GuessTypeParameters guesser = new GuessTypeParameters(JavaPsiFacade.getElementFactory(method.getProject()));

    final PsiClass containingClass = method.getContainingClass();
    final boolean isInterface = containingClass != null && containingClass.isInterface();
    for (int i = 0; i < arguments.size(); i++) {
      Pair<PsiExpression, PsiType> arg = arguments.get(i);
      PsiExpression exp = arg.first;

      PsiType argType = exp == null ? arg.second : RefactoringUtil.getTypeByExpression(exp);
      SuggestedNameInfo suggestedInfo = JavaCodeStyleManager.getInstance(psiManager.getProject()).suggestVariableName(
        VariableKind.PARAMETER, null, exp, argType);
      @NonNls String[] names = suggestedInfo.names; //TODO: callback about used name

      if (names.length == 0) {
        names = new String[]{"p" + i};
      }

      if (argType == null || PsiType.NULL.equals(argType) || LambdaUtil.notInferredType(argType)) {
        argType = PsiType.getJavaLangObject(psiManager, resolveScope);
      } else if (argType instanceof PsiDisjunctionType) {
        argType = ((PsiDisjunctionType)argType).getLeastUpperBound();
      } else if (argType instanceof PsiWildcardType) {
        argType = ((PsiWildcardType)argType).isBounded() ? ((PsiWildcardType)argType).getBound() : PsiType.getJavaLangObject(psiManager, resolveScope);
      }
      PsiParameter parameter;
      if (parameterList.getParametersCount() <= i) {
        parameter = factory.createParameter(names[0], argType);
        if (isInterface) {
          PsiUtil.setModifierProperty(parameter, PsiModifier.FINAL, false);
        }
        parameter = (PsiParameter) parameterList.add(parameter);
      } else {
        parameter = parameterList.getParameters()[i];
      }

      ExpectedTypeInfo info = ExpectedTypesProvider.createInfo(argType, ExpectedTypeInfo.TYPE_OR_SUPERTYPE, argType, TailType.NONE);

      PsiElement context = PsiTreeUtil.getParentOfType(contextElement, PsiClass.class, PsiMethod.class);
      guesser.setupTypeElement(parameter.getTypeElement(), new ExpectedTypeInfo[]{info},
                               substitutor, builder, context, containingClass);

      Expression expression = new ParameterNameExpression(names);
      builder.replaceElement(parameter.getNameIdentifier(), expression);
    }
  }

  @Nullable
  public static PsiClass createClass(final PsiJavaCodeReferenceElement referenceElement,
                                     final CreateClassKind classKind,
                                     final String superClassName) {
    assert !ApplicationManager.getApplication().isWriteAccessAllowed() : "You must not run createClass() from under write action";
    final String name = referenceElement.getReferenceName();

    String qualifierName;
    final PsiElement qualifierElement;
    PsiElement qualifier = referenceElement.getQualifier();
    if (qualifier instanceof PsiJavaCodeReferenceElement) {
      qualifierName = ((PsiJavaCodeReferenceElement)qualifier).getQualifiedName();
      qualifierElement = ((PsiJavaCodeReferenceElement)qualifier).resolve();
      if (qualifierElement instanceof PsiClass) {
        return ApplicationManager.getApplication().runWriteAction(
          new Computable<PsiClass>() {
            @Override
            public PsiClass compute() {
              return createClassInQualifier((PsiClass)qualifierElement, classKind, name, referenceElement);
            }
          });
      }
    }
    else {
      qualifierName = null;
      qualifierElement = null;
    }

    final PsiManager manager = referenceElement.getManager();
    final PsiFile sourceFile = referenceElement.getContainingFile();
    final Module module = ModuleUtilCore.findModuleForPsiElement(sourceFile);
    if (qualifierName == null) {
      PsiPackage aPackage = findTargetPackage(qualifierElement, manager, sourceFile);
      if (aPackage == null) return null;
      qualifierName = aPackage.getQualifiedName();
    }
    final PsiDirectory targetDirectory;
    if (!ApplicationManager.getApplication().isUnitTestMode()) {
      Project project = manager.getProject();
      String title = QuickFixBundle.message("create.class.title", StringUtil.capitalize(classKind.getDescription()));

      CreateClassDialog dialog = new CreateClassDialog(project, title, name, qualifierName, classKind, false, module){
        @Override
        protected boolean reportBaseInSourceSelectionInTest() {
          return true;
        }
      };
      dialog.show();
      if (dialog.getExitCode() != DialogWrapper.OK_EXIT_CODE) return null;

      targetDirectory = dialog.getTargetDirectory();
      if (targetDirectory == null) return null;
    }
    else {
      targetDirectory = null;
    }
    return createClass(classKind, targetDirectory, name, manager, referenceElement, sourceFile, superClassName);
  }

  @Nullable
  private static PsiPackage findTargetPackage(PsiElement qualifierElement, PsiManager manager, PsiFile sourceFile) {
    PsiPackage aPackage = null;
    if (qualifierElement instanceof PsiPackage) {
      aPackage = (PsiPackage)qualifierElement;
    }
    else {
      final PsiDirectory directory = sourceFile.getContainingDirectory();
      if (directory != null) {
        aPackage = JavaDirectoryService.getInstance().getPackage(directory);
      }

      if (aPackage == null) {
        aPackage = JavaPsiFacade.getInstance(manager.getProject()).findPackage("");
      }
    }
    if (aPackage == null) return null;
    return aPackage;
  }

  private static PsiClass createClassInQualifier(PsiClass psiClass,
                                                 CreateClassKind classKind,
                                                 String name,
                                                 PsiJavaCodeReferenceElement referenceElement) {
    try {
      if (!FileModificationService.getInstance().preparePsiElementForWrite(psiClass)) return null;

      PsiManager manager = psiClass.getManager();
      PsiElementFactory elementFactory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
      PsiClass result = classKind == CreateClassKind.INTERFACE ? elementFactory.createInterface(name) :
                        classKind == CreateClassKind.CLASS ? elementFactory.createClass(name) :
                        classKind == CreateClassKind.ANNOTATION ? elementFactory.createAnnotationType(name) :
                        elementFactory.createEnum(name);
      CreateFromUsageBaseFix.setupGenericParameters(result, referenceElement);
      result = (PsiClass)CodeStyleManager.getInstance(manager.getProject()).reformat(result);
      return (PsiClass) psiClass.add(result);
    }
    catch (IncorrectOperationException e) {
      LOG.error(e);
      return null;
    }
  }

  public static PsiClass createClass(final CreateClassKind classKind,
                                      final PsiDirectory directory,
                                      final String name,
                                      final PsiManager manager,
                                      @NotNull final PsiElement contextElement,
                                      final PsiFile sourceFile,
                                      final String superClassName) {
    final JavaPsiFacade facade = JavaPsiFacade.getInstance(manager.getProject());
    final PsiElementFactory factory = facade.getElementFactory();

    return ApplicationManager.getApplication().runWriteAction(
      new Computable<PsiClass>() {
        @Override
        public PsiClass compute() {
          try {
            PsiClass targetClass;
            if (directory != null) {
              try {
                if (classKind == CreateClassKind.INTERFACE) {
                  targetClass = JavaDirectoryService.getInstance().createInterface(directory, name);
                }
                else if (classKind == CreateClassKind.CLASS) {
                  targetClass = JavaDirectoryService.getInstance().createClass(directory, name);
                }
                else if (classKind == CreateClassKind.ENUM) {
                  targetClass = JavaDirectoryService.getInstance().createEnum(directory, name);
                }
                else if (classKind == CreateClassKind.ANNOTATION) {
                  targetClass = JavaDirectoryService.getInstance().createAnnotationType(directory, name);
                }
                else {
                  LOG.error("Unknown kind of a class to create");
                  return null;
                }
              }
              catch (final IncorrectOperationException e) {
                scheduleFileOrPackageCreationFailedMessageBox(e, name, directory, false);
                return null;
              }
              if (!facade.getResolveHelper().isAccessible(targetClass, contextElement, null)) {
                PsiUtil.setModifierProperty(targetClass, PsiModifier.PUBLIC, true);
              }
            }
            else { //tests
              PsiClass aClass;
              if (classKind == CreateClassKind.INTERFACE) {
                aClass = factory.createInterface(name);
              }
              else if (classKind == CreateClassKind.CLASS) {
                aClass = factory.createClass(name);
              }
              else if (classKind == CreateClassKind.ENUM) {
                aClass = factory.createEnum(name);
              }
              else if (classKind == CreateClassKind.ANNOTATION) {
                aClass = factory.createAnnotationType(name);
              }
              else {
                LOG.error("Unknown kind of a class to create");
                return null;
              }
              targetClass = (PsiClass) sourceFile.add(aClass);
            }

            if (superClassName != null && (classKind != CreateClassKind.ENUM || !superClassName.equals(CommonClassNames.JAVA_LANG_ENUM))) {
              final PsiClass superClass =
                facade.findClass(superClassName, targetClass.getResolveScope());
              final PsiJavaCodeReferenceElement superClassReference = factory.createReferenceElementByFQClassName(superClassName, targetClass.getResolveScope());
              final PsiReferenceList list = classKind == CreateClassKind.INTERFACE || superClass == null || !superClass.isInterface() ?
                targetClass.getExtendsList() : targetClass.getImplementsList();
              list.add(superClassReference);
            }
            if (contextElement instanceof PsiJavaCodeReferenceElement) {
              CreateFromUsageBaseFix.setupGenericParameters(targetClass, (PsiJavaCodeReferenceElement)contextElement);
            }
            return targetClass;
          }
          catch (IncorrectOperationException e) {
            LOG.error(e);
            return null;
          }
        }
      });
  }

  public static void scheduleFileOrPackageCreationFailedMessageBox(final IncorrectOperationException e, final String name, final PsiDirectory directory,
                                                      final boolean isPackage) {
    ApplicationManager.getApplication().invokeLater(new Runnable() {
      @Override
      public void run() {
        Messages.showErrorDialog(QuickFixBundle.message(
          isPackage ? "cannot.create.java.package.error.text" : "cannot.create.java.file.error.text", name, directory.getVirtualFile().getName(), e.getLocalizedMessage()),
                                 QuickFixBundle.message(
                                   isPackage ? "cannot.create.java.package.error.title" : "cannot.create.java.file.error.title"));
      }
    });
  }

  public static PsiReferenceExpression[] collectExpressions(final PsiExpression expression, Class<? extends PsiElement>... scopes) {
    PsiElement parent = PsiTreeUtil.getParentOfType(expression, scopes);

    final List<PsiReferenceExpression> result = new ArrayList<PsiReferenceExpression>();
    JavaRecursiveElementWalkingVisitor visitor = new JavaRecursiveElementWalkingVisitor() {
      @Override public void visitReferenceExpression(PsiReferenceExpression expr) {
        if (expression instanceof PsiReferenceExpression) {
          if (expr.textMatches(expression) && !isValidReference(expr, false)) {
            result.add(expr);
          }
        }
        visitElement(expr);
      }

      @Override public void visitMethodCallExpression(PsiMethodCallExpression expr) {
        if (expression instanceof PsiMethodCallExpression) {
          PsiReferenceExpression methodExpression = expr.getMethodExpression();
          if (methodExpression.textMatches(((PsiMethodCallExpression) expression).getMethodExpression())) {
            result.add(expr.getMethodExpression());
          }
        }
        visitElement(expr);
      }
    };

    if (parent != null) {
      parent.accept(visitor);
    }
    return result.toArray(new PsiReferenceExpression[result.size()]);
  }

  static PsiVariable[] guessMatchingVariables(final PsiExpression expression) {
    List<ExpectedTypeInfo[]> typesList = new ArrayList<ExpectedTypeInfo[]>();
    List<String> expectedMethodNames = new ArrayList<String>();
    List<String> expectedFieldNames  = new ArrayList<String>();

    getExpectedInformation(expression, typesList, expectedMethodNames, expectedFieldNames);

    final List<PsiVariable> list = new ArrayList<PsiVariable>();
    VariablesProcessor varproc = new VariablesProcessor("", true, list){
      @Override
      public boolean execute(@NotNull PsiElement element, @NotNull ResolveState state) {
        if(!(element instanceof PsiField) ||
           JavaPsiFacade.getInstance(element.getProject()).getResolveHelper().isAccessible((PsiField)element, expression, null)) {
          return super.execute(element, state);
        }
        return true;
      }
    };
    PsiScopesUtil.treeWalkUp(varproc, expression, null);
    PsiVariable[] allVars = varproc.getResultsAsArray();

    ExpectedTypeInfo[] infos = ExpectedTypeUtil.intersect(typesList);

    List<PsiVariable> result = new ArrayList<PsiVariable>();
    nextVar:
    for (PsiVariable variable : allVars) {
      PsiType varType = variable.getType();
      boolean matched = infos.length == 0;
      for (ExpectedTypeInfo info : infos) {
        if (ExpectedTypeUtil.matches(varType, info)) {
          matched = true;
          break;
        }
      }

      if (matched) {
        if (!expectedFieldNames.isEmpty() && !expectedMethodNames.isEmpty()) {
          if (!(varType instanceof PsiClassType)) continue;
          PsiClass aClass = ((PsiClassType)varType).resolve();
          if (aClass == null) continue;
          for (String name : expectedFieldNames) {
            if (aClass.findFieldByName(name, true) == null) continue nextVar;
          }

          for (String name : expectedMethodNames) {
            PsiMethod[] methods = aClass.findMethodsByName(name, true);
            if (methods.length == 0) continue nextVar;
          }
        }

        result.add(variable);
      }
    }

    return result.toArray(new PsiVariable[result.size()]);
  }

  private static void getExpectedInformation(final PsiExpression expression,
                                             List<ExpectedTypeInfo[]> types,
                                             List<String> expectedMethodNames,
                                             List<String> expectedFieldNames) {
    for (PsiExpression expr : collectExpressions(expression, PsiMember.class, PsiFile.class)) {
      PsiElement parent = expr.getParent();

      if (!(parent instanceof PsiReferenceExpression)) {
        ExpectedTypeInfo[] someExpectedTypes = ExpectedTypesProvider.getExpectedTypes(expr, PsiUtil.skipParenthesizedExprUp(parent) instanceof PsiExpressionList);
        if (someExpectedTypes.length > 0) {
          Arrays.sort(someExpectedTypes, new Comparator<ExpectedTypeInfo>() {
            @Override
            public int compare(ExpectedTypeInfo o1, ExpectedTypeInfo o2) {
              return compareExpectedTypes(o1, o2, expression);
            }
          });
          types.add(someExpectedTypes);
        }
        continue;
      }

      String refName = ((PsiReferenceExpression)parent).getReferenceName();
      if (refName == null) {
        continue;
      }

      PsiElement pparent = parent.getParent();
      if (pparent instanceof PsiMethodCallExpression) {
        expectedMethodNames.add(refName);
        if (refName.equals("equals")) {
          ExpectedTypeInfo[] someExpectedTypes = equalsExpectedTypes((PsiMethodCallExpression)pparent);
          if (someExpectedTypes.length > 0) {
            Arrays.sort(someExpectedTypes, new Comparator<ExpectedTypeInfo>() {
              @Override
              public int compare(ExpectedTypeInfo o1, ExpectedTypeInfo o2) {
                return compareExpectedTypes(o1, o2, expression);
              }
            });
            types.add(someExpectedTypes);
          }
        }
        continue;
      }

      if (pparent instanceof PsiReferenceExpression ||
          pparent instanceof PsiVariable ||
          pparent instanceof PsiExpression) {
        expectedFieldNames.add(refName);
      }
    }
  }

  private static int compareExpectedTypes(ExpectedTypeInfo o1, ExpectedTypeInfo o2, PsiExpression expression) {
    PsiClass c1 = PsiUtil.resolveClassInType(o1.getDefaultType());
    PsiClass c2 = PsiUtil.resolveClassInType(o2.getDefaultType());
    if (c1 == null && c2 == null) return 0;
    if (c1 == null || c2 == null) return c1 == null ? -1 : 1;
    return compareMembers(c1, c2, expression);
  }

  private static ExpectedTypeInfo[] equalsExpectedTypes(PsiMethodCallExpression methodCall) {
    final PsiType[] argumentTypes = methodCall.getArgumentList().getExpressionTypes();
    if (argumentTypes.length != 1) {
      return ExpectedTypeInfo.EMPTY_ARRAY;
    }
    PsiType type = argumentTypes[0];
    if (type instanceof PsiPrimitiveType) {
      type = ((PsiPrimitiveType)type).getBoxedType(methodCall);
    }
    if (type == null) return ExpectedTypeInfo.EMPTY_ARRAY;
    return new ExpectedTypeInfo[]{ExpectedTypesProvider.createInfo(type, ExpectedTypeInfo.TYPE_STRICTLY, type, TailType.NONE)};
  }

  static ExpectedTypeInfo[] guessExpectedTypes(PsiExpression expression, boolean allowVoidType) {
        PsiManager manager = expression.getManager();
    GlobalSearchScope resolveScope = expression.getResolveScope();

    List<ExpectedTypeInfo[]> typesList = new ArrayList<ExpectedTypeInfo[]>();
    List<String> expectedMethodNames = new ArrayList<String>();
    List<String> expectedFieldNames  = new ArrayList<String>();

    getExpectedInformation(expression, typesList, expectedMethodNames, expectedFieldNames);

    if (typesList.size() == 1 && (!expectedFieldNames.isEmpty() || !expectedMethodNames.isEmpty())) {
      ExpectedTypeInfo[] infos = typesList.get(0);
      if (infos.length == 1 && infos[0].getKind() == ExpectedTypeInfo.TYPE_OR_SUBTYPE &&
          infos[0].getType().equals(PsiType.getJavaLangObject(manager, resolveScope))) {
        typesList.clear();
      }
    }

    if (typesList.isEmpty()) {
      final JavaPsiFacade facade = JavaPsiFacade.getInstance(expression.getProject());
      final PsiShortNamesCache cache = PsiShortNamesCache.getInstance(expression.getProject());
      PsiElementFactory factory = facade.getElementFactory();
      for (String fieldName : expectedFieldNames) {
        PsiField[] fields = cache.getFieldsByNameIfNotMoreThan(fieldName, resolveScope, MAX_RAW_GUESSED_MEMBERS_COUNT);
        addMemberInfo(fields, expression, typesList, factory);
      }

      for (String methodName : expectedMethodNames) {
        PsiMethod[] methods = cache.getMethodsByNameIfNotMoreThan(methodName, resolveScope, MAX_RAW_GUESSED_MEMBERS_COUNT);
        addMemberInfo(methods, expression, typesList, factory);
      }
    }

    ExpectedTypeInfo[] expectedTypes = ExpectedTypeUtil.intersect(typesList);
    if (expectedTypes.length == 0 && !typesList.isEmpty()) {
      List<ExpectedTypeInfo> union = new ArrayList<ExpectedTypeInfo>();
      for (ExpectedTypeInfo[] aTypesList : typesList) {
        ContainerUtil.addAll(union, (ExpectedTypeInfo[])aTypesList);
      }
      expectedTypes = union.toArray(new ExpectedTypeInfo[union.size()]);
    }

    if (expectedTypes.length == 0) {
      PsiType t = allowVoidType ? PsiType.VOID : PsiType.getJavaLangObject(manager, resolveScope);
      expectedTypes = new ExpectedTypeInfo[] {ExpectedTypesProvider.createInfo(t, ExpectedTypeInfo.TYPE_OR_SUBTYPE, t, TailType.NONE)};
    }

    return expectedTypes;
  }

  @Nullable
  static PsiType[] guessType(PsiExpression expression, final boolean allowVoidType) {
    final PsiManager manager = expression.getManager();
    final GlobalSearchScope resolveScope = expression.getResolveScope();

    List<ExpectedTypeInfo[]> typesList = new ArrayList<ExpectedTypeInfo[]>();
    final List<String> expectedMethodNames = new ArrayList<String>();
    final List<String> expectedFieldNames  = new ArrayList<String>();

    getExpectedInformation(expression, typesList, expectedMethodNames, expectedFieldNames);

    if (typesList.size() == 1 && (!expectedFieldNames.isEmpty() || !expectedMethodNames.isEmpty())) {
      ExpectedTypeInfo[] infos = typesList.get(0);
      if (infos.length == 1 && infos[0].getKind() == ExpectedTypeInfo.TYPE_OR_SUBTYPE &&
          infos[0].getType().equals(PsiType.getJavaLangObject(manager, resolveScope))) {
        typesList.clear();
      }
    }

    if (typesList.isEmpty()) {
      final JavaPsiFacade facade = JavaPsiFacade.getInstance(manager.getProject());
      final PsiShortNamesCache cache = PsiShortNamesCache.getInstance(expression.getProject());
      PsiElementFactory factory = facade.getElementFactory();
      for (String fieldName : expectedFieldNames) {
        PsiField[] fields = cache.getFieldsByNameIfNotMoreThan(fieldName, resolveScope, MAX_RAW_GUESSED_MEMBERS_COUNT);
        addMemberInfo(fields, expression, typesList, factory);
      }

      for (String methodName : expectedMethodNames) {
        PsiMethod[] methods = cache.getMethodsByNameIfNotMoreThan(methodName, resolveScope, MAX_RAW_GUESSED_MEMBERS_COUNT);
        addMemberInfo(methods, expression, typesList, factory);
      }
    }

    ExpectedTypeInfo[] expectedTypes = ExpectedTypeUtil.intersect(typesList);
    if (expectedTypes.length == 0 && !typesList.isEmpty()) {
      List<ExpectedTypeInfo> union = new ArrayList<ExpectedTypeInfo>();
      for (ExpectedTypeInfo[] aTypesList : typesList) {
        ContainerUtil.addAll(union, (ExpectedTypeInfo[])aTypesList);
      }
      expectedTypes = union.toArray(new ExpectedTypeInfo[union.size()]);
    }

    if (expectedTypes.length == 0) {
      return allowVoidType ? new PsiType[]{PsiType.VOID} : new PsiType[]{PsiType.getJavaLangObject(manager, resolveScope)};
    }
    else {
      //Double check to avoid expensive operations on PsiClassTypes
      final Set<PsiType> typesSet = new HashSet<PsiType>();

      PsiTypeVisitor<PsiType> visitor = new PsiTypeVisitor<PsiType>() {
        @Override
        @Nullable
        public PsiType visitType(PsiType type) {
          if (PsiType.NULL.equals(type)) {
            type = PsiType.getJavaLangObject(manager, resolveScope);
          }
          else if (PsiType.VOID.equals(type) && !allowVoidType) {
            type = PsiType.getJavaLangObject(manager, resolveScope);
          }

          if (!typesSet.contains(type)) {
            if (type instanceof PsiClassType && (!expectedFieldNames.isEmpty() || !expectedMethodNames.isEmpty())) {
              PsiClass aClass = ((PsiClassType) type).resolve();
              if (aClass != null) {
                for (String fieldName : expectedFieldNames) {
                  if (aClass.findFieldByName(fieldName, true) == null) return null;
                }

                for (String methodName : expectedMethodNames) {
                  PsiMethod[] methods = aClass.findMethodsByName(methodName, true);
                  if (methods.length == 0) return null;
                }
              }
            }

            typesSet.add(type);
            return type;
          }

          return null;
        }

        @Override
        public PsiType visitCapturedWildcardType(PsiCapturedWildcardType capturedWildcardType) {
          return capturedWildcardType.getUpperBound().accept(this);
        }
      };

      PsiType[] types = ExpectedTypesProvider.processExpectedTypes(expectedTypes, visitor, manager.getProject());
      if (types.length == 0) {
        return allowVoidType
               ? new PsiType[]{PsiType.VOID}
               : new PsiType[]{PsiType.getJavaLangObject(manager, resolveScope)};
      }

      return types;
    }
  }

  private static void addMemberInfo(PsiMember[] members,
                                    final PsiExpression expression,
                                    List<ExpectedTypeInfo[]> types,
                                    PsiElementFactory factory) {
    Arrays.sort(members, new Comparator<PsiMember>() {
      @Override
      public int compare(final PsiMember m1, final PsiMember m2) {
        return compareMembers(m1, m2, expression);
      }
    });

    List<ExpectedTypeInfo> l = new ArrayList<ExpectedTypeInfo>();
    PsiManager manager = expression.getManager();
    JavaPsiFacade facade = JavaPsiFacade.getInstance(manager.getProject());
    for (PsiMember member : members) {
      ProgressManager.checkCanceled();
      PsiClass aClass = member.getContainingClass();
      if (aClass instanceof PsiAnonymousClass || aClass == null) continue;

      if (facade.getResolveHelper().isAccessible(member, expression, null)) {
        PsiClassType type;
        final PsiElement pparent = expression.getParent().getParent();
        if (pparent instanceof PsiMethodCallExpression && member instanceof PsiMethod) {
          PsiSubstitutor substitutor = ExpectedTypeUtil.inferSubstitutor((PsiMethod)member, (PsiMethodCallExpression)pparent, false);
          if (substitutor == null) {
            type = factory.createType(aClass);
          }
          else {
            type = factory.createType(aClass, substitutor);
          }
        }
        else {
          type = factory.createType(aClass);
        }
        l.add(ExpectedTypesProvider.createInfo(type, ExpectedTypeInfo.TYPE_OR_SUBTYPE, type, TailType.NONE));
        if (l.size() == MAX_GUESSED_MEMBERS_COUNT) break;
      }
    }

    if (!l.isEmpty()) {
      types.add(l.toArray(new ExpectedTypeInfo[l.size()]));
    }
  }

  private static int compareMembers(PsiMember m1, PsiMember m2, PsiExpression context) {
    ProgressManager.checkCanceled();
    int result = JavaStatisticsManager.createInfo(null, m2).getUseCount() - JavaStatisticsManager.createInfo(null, m1).getUseCount();
    if (result != 0) return result;
    final PsiClass aClass = m1.getContainingClass();
    final PsiClass bClass = m2.getContainingClass();
    if (aClass != null && bClass != null) {
      result = JavaStatisticsManager.createInfo(null, bClass).getUseCount() - JavaStatisticsManager.createInfo(null, aClass).getUseCount();
      if (result != 0) return result;
    }

    WeighingComparable<PsiElement,ProximityLocation> proximity1 = PsiProximityComparator.getProximity(m1, context);
    WeighingComparable<PsiElement,ProximityLocation> proximity2 = PsiProximityComparator.getProximity(m2, context);
    if (proximity1 != null && proximity2 != null) {
      result = proximity2.compareTo(proximity1);
      if (result != 0) return result;
    }

    String name1 = PsiUtil.getMemberQualifiedName(m1);
    String name2 = PsiUtil.getMemberQualifiedName(m2);
    return Comparing.compare(name1, name2);
  }

  public static boolean isAccessedForWriting(final PsiExpression[] expressionOccurences) {
    for (PsiExpression expression : expressionOccurences) {
      if(expression.isValid() && PsiUtil.isAccessedForWriting(expression)) return true;
    }

    return false;
  }

  static boolean shouldShowTag(int offset, PsiElement namedElement, PsiElement element) {
    if (namedElement == null) return false;
    TextRange range = namedElement.getTextRange();
    if (range.getLength() == 0) return false;
    boolean isInNamedElement = range.contains(offset);
    return isInNamedElement || element.getTextRange().contains(offset-1);
  }

  public static void addClassesWithMember(final String memberName, final PsiFile file, final Set<String> possibleClassNames, final boolean method,
                                          final boolean staticAccess) {
    addClassesWithMember(memberName, file, possibleClassNames, method, staticAccess, true);
  }

  public static void addClassesWithMember(final String memberName, final PsiFile file, final Set<String> possibleClassNames, final boolean method,
                                          final boolean staticAccess,
                                          final boolean addObjectInheritors) {
    final Project project = file.getProject();
    final Module moduleForFile = ModuleUtilCore.findModuleForPsiElement(file);
    if (moduleForFile == null) return;

    final GlobalSearchScope searchScope = ApplicationManager.getApplication().runReadAction(new Computable<GlobalSearchScope>() {
      @Override
      public GlobalSearchScope compute() {
        return file.getResolveScope();
      }
    });
    GlobalSearchScope descendantsSearchScope = GlobalSearchScope.moduleWithDependenciesScope(moduleForFile);
    final JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
    final PsiShortNamesCache cache = PsiShortNamesCache.getInstance(project);

    if (handleObjectMethod(possibleClassNames, facade, searchScope, method, memberName, staticAccess, addObjectInheritors)) {
      return;
    }

    final PsiMember[] members = ApplicationManager.getApplication().runReadAction(new Computable<PsiMember[]>() {
      @Override
      public PsiMember[] compute() {
        return method ? cache.getMethodsByName(memberName, searchScope) : cache.getFieldsByName(memberName, searchScope);
      }
    });

    for (int i = 0; i < members.length; ++i) {
      final PsiMember member = members[i];
      if (hasCorrectModifiers(member, staticAccess)) {
        final PsiClass containingClass = member.getContainingClass();

        if (containingClass != null) {
          final String qName = getQualifiedName(containingClass);
          if (qName == null) continue;

          ClassInheritorsSearch.search(containingClass, descendantsSearchScope, true, true, false).forEach(new Processor<PsiClass>() {
            @Override
            public boolean process(PsiClass psiClass) {
              ContainerUtil.addIfNotNull(getQualifiedName(psiClass), possibleClassNames);
              return true;
            }
          });

          possibleClassNames.add(qName);
        }
      }
      members[i] = null;
    }
  }

  private static boolean handleObjectMethod(Set<String> possibleClassNames, final JavaPsiFacade facade, final GlobalSearchScope searchScope, final boolean method, final String memberName, final boolean staticAccess, boolean addInheritors) {
    final PsiShortNamesCache cache = PsiShortNamesCache.getInstance(facade.getProject());
    final boolean[] allClasses = {false};
    ApplicationManager.getApplication().runReadAction(new Runnable() {
      @Override
      public void run() {
        final PsiClass objectClass = facade.findClass(CommonClassNames.JAVA_LANG_OBJECT, searchScope);
        if (objectClass != null) {
          if (method && objectClass.findMethodsByName(memberName, false).length > 0) {
            allClasses[0] = true;
          }
          else if (!method) {
            final PsiField field = objectClass.findFieldByName(memberName, false);
            if (hasCorrectModifiers(field, staticAccess)) {
              allClasses[0] = true;
            }
          }
        }
      }
    });
    if (allClasses[0]) {
      possibleClassNames.add(CommonClassNames.JAVA_LANG_OBJECT);

      if (!addInheritors) {
        return true;
      }

      final String[] strings = ApplicationManager.getApplication().runReadAction(new Computable<String[]>() {
        @Override
        public String[] compute() {
          return cache.getAllClassNames();
        }
      });
      for (final String className : strings) {
        final PsiClass[] classes = ApplicationManager.getApplication().runReadAction(new Computable<PsiClass[]>() {
          @Override
          public PsiClass[] compute() {
            return cache.getClassesByName(className, searchScope);
          }
        });
        for (final PsiClass aClass : classes) {
          final String qname = getQualifiedName(aClass);
          ContainerUtil.addIfNotNull(qname, possibleClassNames);
        }
      }
      return true;
    }
    return false;
  }

  @Nullable
  private static String getQualifiedName(final PsiClass aClass) {
    return ApplicationManager.getApplication().runReadAction(new Computable<String>() {
      @Nullable
      @Override
      public String compute() {
        return aClass.getQualifiedName();
      }
    });
  }

  private static boolean hasCorrectModifiers(@Nullable final PsiMember member, final boolean staticAccess) {
    if (member == null) {
      return false;
    }

    return ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {
      @Override
      public Boolean compute() {
        return !member.hasModifierProperty(PsiModifier.PRIVATE) && member.hasModifierProperty(PsiModifier.STATIC) == staticAccess;
      }
    }).booleanValue();
  }

  private static class ParameterNameExpression extends Expression {
    private final String[] myNames;

    private ParameterNameExpression(String[] names) {
      myNames = names;
    }

    @Override
    public Result calculateResult(ExpressionContext context) {
      LookupElement[] lookupItems = calculateLookupItems(context);
      if (lookupItems.length == 0) return new TextResult("");

      return new TextResult(lookupItems[0].getLookupString());
    }

    @Override
    public Result calculateQuickResult(ExpressionContext context) {
      return null;
    }

    @Override
    @NotNull
    public LookupElement[] calculateLookupItems(ExpressionContext context) {
      Project project = context.getProject();
      int offset = context.getStartOffset();
      PsiDocumentManager.getInstance(project).commitAllDocuments();
      PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(context.getEditor().getDocument());
      assert file != null;
      PsiElement elementAt = file.findElementAt(offset);
      PsiParameterList parameterList = PsiTreeUtil.getParentOfType(elementAt, PsiParameterList.class);
      if (parameterList == null) {
        if (elementAt == null) return LookupElement.EMPTY_ARRAY;
        final PsiElement parent = elementAt.getParent();
        if (parent instanceof PsiMethod) {
          parameterList = ((PsiMethod)parent).getParameterList();
        }
        else {
          return LookupElement.EMPTY_ARRAY;
        }
      }

      PsiParameter parameter = PsiTreeUtil.getParentOfType(elementAt, PsiParameter.class);

      Set<String> parameterNames = new HashSet<String>();
      for (PsiParameter psiParameter : parameterList.getParameters()) {
        if (psiParameter == parameter) continue;
        parameterNames.add(psiParameter.getName());
      }

      Set<LookupElement> set = new LinkedHashSet<LookupElement>();

      for (String name : myNames) {
        if (parameterNames.contains(name)) {
          int j = 1;
          while (parameterNames.contains(name + j)) j++;
          name += j;
        }

        set.add(LookupElementBuilder.create(name));
      }

      String[] suggestedNames = ExpressionUtil.getNames(context);
      if (suggestedNames != null) {
        for (String name : suggestedNames) {
          if (parameterNames.contains(name)) {
            int j = 1;
            while (parameterNames.contains(name + j)) j++;
            name += j;
          }

          set.add(LookupElementBuilder.create(name));
        }
      }

      return set.toArray(new LookupElement[set.size()]);
    }
  }
}


text:
'use strict';
process.env.NODE_ENV = 'test';
require('should');

var assert = require('assert');

var DataSource = require('loopback-datasource-juggler').DataSource;
var db;

before(function() {
  var config = getDBConfig();
  config.database = 'strongloop';
  db = new DataSource(require('../'), config);
});

describe('discoverModels', function() {
  describe('Discover models including views', function() {
    it('should return an array of tables and views', function(done) {
      db.discoverModelDefinitions({
        views: true,
        limit: 3,
      }, function(err, models) {
        if (err) {
          console.error(err);
          done(err);
        } else {
          var views = false;
          models.forEach(function(m) {
            // console.dir(m);
            if (m.type === 'view') {
              views = true;
            }
          });
          assert(views, 'Should have views');
          done(null, models);
        }
      });
    });
  });

  describe('Discover models excluding views', function() {
    it('should return an array of only tables', function(done) {
      db.discoverModelDefinitions({
        views: false,
        limit: 3,
      }, function(err, models) {
        if (err) {
          console.error(err);
          done(err);
        } else {
          var views = false;
          models.forEach(function(m) {
            // console.dir(m);
            if (m.type === 'view') {
              views = true;
            }
          });
          models.should.have.length(3);
          assert(!views, 'Should not have views');
          done(null, models);
        }
      });
    });
  });
});

describe('Discover models including other users', function() {
  it('should return an array of all tables and views', function(done) {
    db.discoverModelDefinitions({
      all: true,
      limit: 3,
    }, function(err, models) {
      if (err) {
        console.error(err);
        done(err);
      } else {
        var others = false;
        models.forEach(function(m) {
          // console.dir(m);
          if (m.owner !== 'strongloop') {
            others = true;
          }
        });
        assert(others, 'Should have tables/views owned by others');
        done(err, models);
      }
    });
  });
});

describe('Discover model properties', function() {
  describe('Discover a named model', function() {
    it('should return an array of columns for product', function(done) {
      db.discoverModelProperties('product', function(err, models) {
        if (err) {
          console.error(err);
          done(err);
        } else {
          models.forEach(function(m) {
            // console.dir(m);
            assert(m.tableName === 'product');
          });
          done(null, models);
        }
      });
    });
  });
});

describe('Discover model primary keys', function() {
  it('should return an array of primary keys for product', function(done) {
    db.discoverPrimaryKeys('product', function(err, models) {
      if (err) {
        console.error(err);
        done(err);
      } else {
        models.forEach(function(m) {
          assert.deepEqual(m, {owner: 'strongloop',
            tableName: 'product',
            columnName: 'id',
            keySeq: 1,
            pkName: 'product_pkey'});
        });
        done(null, models);
      }
    });
  });

  it('should return an array of primary keys for strongloop.product', function(done) {
    db.discoverPrimaryKeys('product', {owner: 'strongloop'}, function(err, models) {
      if (err) {
        console.error(err);
        done(err);
      } else {
        models.forEach(function(m) {
          // console.dir(m);
          assert(m.tableName === 'product');
        });
        done(null, models);
      }
    });
  });
});

describe('Discover model foreign keys', function() {
  it('should return an array of foreign keys for inventory', function(done) {
    db.discoverForeignKeys('inventory', function(err, models) {
      if (err) {
        console.error(err);
        done(err);
      } else {
        models.forEach(function(m) {
          // console.dir(m);
          assert(m.fkTableName === 'inventory');
        });
        done(null, models);
      }
    });
  });
  it('should return an array of foreign keys for strongloop.inventory', function(done) {
    db.discoverForeignKeys('inventory', {owner: 'strongloop'}, function(err, models) {
      if (err) {
        console.error(err);
        done(err);
      } else {
        models.forEach(function(m) {
          // console.dir(m);
          assert(m.fkTableName === 'inventory');
        });
        done(null, models);
      }
    });
  });
});

describe('Discover LDL schema from a table', function() {
  it('should return an LDL schema for inventory', function(done) {
    db.discoverSchema('inventory', {owner: 'strongloop'}, function(err, schema) {
      assert(schema.name === 'Inventory');
      assert(schema.options.postgresql.schema === 'strongloop');
      assert(schema.options.postgresql.table === 'inventory');
      assert(schema.properties.productId);
      assert(schema.properties.productId.type === 'String');
      assert(schema.properties.productId.postgresql.columnName === 'product_id');
      assert(schema.properties.locationId);
      assert(schema.properties.locationId.type === 'String');
      assert(schema.properties.locationId.postgresql.columnName === 'location_id');
      assert(schema.properties.available);
      assert(schema.properties.available.type === 'Number');
      assert(schema.properties.total);
      assert(schema.properties.total.type === 'Number');
      done(null, schema);
    });
  });
});

describe('Discover and build models', function() {
  it('should build a model from discovery', function(done) {
    db.discoverAndBuildModels('GeoPoint', {schema: 'strongloop'}, function(err, schema) {
      schema.Geopoint.find(function(err, data) {
        assert(!err);
        assert(Array.isArray(data));
        assert(data[0].location);
        done();
      });
    });
  });
});

redpajama_set_name: RedPajamaGithub


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

namespace Smalldb\StateMachine\Test;

use DateTimeImmutable;
use Smalldb\StateMachine\Definition\StateMachineDefinition;
use Smalldb\StateMachine\Smalldb;
use Smalldb\StateMachine\SmalldbDefinitionBagInterface;
use Smalldb\StateMachine\Test\Example\Post\Post;
use Smalldb\StateMachine\Test\Example\Post\PostData\PostDataImmutable;
use Smalldb\StateMachine\Test\Example\Post\PostData\PostDataMutable;
use Smalldb\StateMachine\Test\Example\Post\PostRepository;
use Smalldb\StateMachine\Test\Example\Tag\Tag;
use Smalldb\StateMachine\Test\Example\Tag\TagData\TagDataMutable;
use Smalldb\StateMachine\Test\Example\Tag\TagRepository;
use Smalldb\StateMachine\Test\Example\User\UserRepository;
use Smalldb\StateMachine\Test\TestTemplate\TestOutputTemplate;

/**
 * DemoControllerTest -- try to emulate Symfony Demo app controllers
 * and test Smalldb as (almost) drop-in replacement of Doctrine. The point
 * of these tests is to make sure that the Smalldb API is similar enough
 * to well-established libraries and frameworks so that new developers
 * have as little trouble as possible.
 *
 * @see https://github.com/symfony/demo/blob/master/src/Controller/BlogController.php
 */
class DemoControllerTest extends TestCaseWithDemoContainer
{

	public function testContainer()
	{
		foreach ([Smalldb::class, PostRepository::class, TagRepository::class, UserRepository::class] as $service) {
			$this->assertInstanceOf($service, $this->get($service));
		}
	}

	public function testDefinitionBag()
	{
		/** @var SmalldbDefinitionBagInterface $definitionBag */
		$definitionBag = $this->get(SmalldbDefinitionBagInterface::class);

		foreach ($definitionBag->getAllMachineTypes() as $machineType) {
			$definition = $definitionBag->getDefinition($machineType);
			$this->assertInstanceOf(StateMachineDefinition::class, $definition);

			// Render the result
			$output = new TestOutputTemplate();
			$output->setTitle('Demo App: ' . ucfirst($machineType));
			$output->addStateMachineGraph($definition);
			$output->addStateMachineDefinitionDump($definition);
			$output->writeHtmlFile('demo_' . $machineType . '.html');
		}
	}

	/**
	 * Create a post in the repository.
	 */
	private function createPost(PostRepository $postRepository, int $id = 1000): Post
	{
		$post = $postRepository->ref($id);
		$this->assertInstanceOf(Post::class, $post);

		$postData = new PostDataMutable();
		$postData->setId($id);
		$postData->setTitle('Foo');
		$postData->setSlug('foo');
		$postData->setAuthorId(1);
		$postData->setPublishedAt(new DateTimeImmutable());
		$postData->setSummary('Foo, foo.');
		$postData->setContent('Foo. Foo. Foo.');
		$postData = new PostDataImmutable($postData);

		$post->create($postData);
		$this->assertEquals(Post::EXISTS, $post->getState());

		return $post;
	}

	public function testPostShowController()
	{
		$postRepository = $this->get(PostRepository::class);

		// The Post object is loaded by Symfony's argument resolver.
		$post = $this->createPost($postRepository);

		$this->postShowController($post);
	}

	private function postShowController(Post $post)
	{
		$this->render(['post' => $post]);
	}

	/**
	 * @dataProvider tagProvider
	 */
	public function testIndexController(?string $tagName)
	{
		/** @var PostRepository $posts */
		$posts = $this->get(PostRepository::class);
		/** @var TagRepository $tags */
		$tags = $this->get(TagRepository::class);

		$tagData = new TagDataMutable();
		$tagData->setName('Foo');

		$ref = $tags->ref(null);
		$ref->create($tagData);

		$this->indexController(1, $tagName, $posts, $tags);
	}

	private function indexController(?int $page, ?string $tagName, PostRepository $posts, TagRepository $tags)
	{
		/** @var Tag $tag */
		$tag = null;
		if ($tagName !== null) {
			$tag = $tags->findByName($tagName);
		}

		$latestPosts = $posts->findLatest($page, $tag);

		return $this->render(['posts' => $latestPosts]);
	}

	public function tagProvider()
	{
		yield 'no tag' => [null];
		yield 'voluptate' => ['voluptate'];
	}

	public function testEditController()
	{
		/** @var PostRepository $posts */
		$postRepository = $this->get(PostRepository::class);
		$post = $this->createPost($postRepository, 1000);

		$newTitle = 'A post about Bar.';
		$request = ['title' => $newTitle];

		$this->assertNotEquals($newTitle, $post->getTitle());

		$this->editController($request, $post);

		$this->assertEquals($newTitle, $post->getTitle());
	}

	private function editController($request, Post $post)
	{
		// TODO: Use real Symfony forms.

		$postData = new PostDataImmutable($post);

		// Process the form; update $postData from the $request.
		$postData = $postData->withTitle($request['title']);

		// if ($form->isSubmitted() && $form->isValid()) {
			// Do some additional modification specific to this form.
			$updatedPostData = $postData->withSlug($this->slugify($postData->getTitle()));
			$post->update($updatedPostData);
		// }

		return $this->render([
			'post' => $post,
			//'form' => $form->createView(),
		]);
	}

	/**
	 * A dummy render function to make examples a bit more realistic.
	 */
	private function render(array $templateArgs)
	{
		if (array_key_exists('posts', $templateArgs)) {
			$this->assertContainsOnlyInstancesOf(Post::class, $templateArgs['posts']);
			foreach ($templateArgs['posts'] as $post) {
				$this->renderPost($post);
			}
		}

		if (array_key_exists('post', $templateArgs)) {
			$this->assertInstanceOf(Post::class, $templateArgs['post']);
			$this->renderPost($templateArgs['post']);
		}
	}

	private function renderPost(Post $post)
	{
		// Read the 'title' attribute to emulate rendering.
		$this->assertNotEmpty($post->getTitle());
	}

	private function slugify(string $string)
	{
		return trim(preg_replace('/[^a-z0-9-]+/', '-', strtolower($string)), '-');
	}

}


text:
namespace IdentityServerWithEfCoreDemo.Authorization.Accounts.Dto
{
    public enum TenantAvailabilityState
    {
        Available = 1,
        InActive,
        NotFound
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.ancheng.sudoku">

    <!-- 允许联网 -->
    <uses-permission android:name="android.permission.INTERNET"/>
    <!-- 获取GSM(2g)、WCDMA(联通3g)等网络状态的信息 -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <!-- 获取wifi网络状态的信息 -->
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <!-- 保持CPU 运转,屏幕和键盘灯有可能是关闭的,用于文件上传和下载 -->
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    <!-- 获取sd卡写的权限,用于文件上传和下载 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <!-- 允许读取手机状态 用于创建BmobInstallation -->
    <uses-permission android:name="android.permission.READ_CONTACTS"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>
    <uses-permission android:name="android.permission.READ_SMS"/>
    <uses-permission android:name="android.permission.GET_TASKS"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.WRITE_APN_SETTINGS"/>

    <!-- 图片选择 -->
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

    <!-- Required -->
    <uses-permission android:name="android.permission.VIBRATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.RECORD_AUDIO"/>
    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.GET_TASKS"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:name=".application.MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/icon_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_splash"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".activity.MainActivity"
            android:screenOrientation="portrait">
        </activity>
        <activity
            android:name=".activity.SplashActivity"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity
            android:name=".login.activity.LoginActivity"
            android:screenOrientation="portrait">
        </activity>
        <activity
            android:name=".forgotpassword.activity.ForgotPasswordActivity"
            android:screenOrientation="portrait">
        </activity>
        <activity
            android:name=".register.activity.RegisterAccountActivity"
            android:screenOrientation="portrait">
        </activity>
        <activity
            android:name="com.mob.tools.MobUIShell"
            android:configChanges="keyboardHidden|orientation|screenSize"
            android:theme="@android:style/Theme.Translucent.NoTitleBar"
            android:windowSoftInputMode="stateHidden|adjustResize"/>
        <activity android:name=".activity.HelpActivity">
        </activity>
        <activity android:name=".activity.MineInfoActivity">
        </activity>
        <activity android:name=".activity.MineScoreActivity">
        </activity>
        <activity android:name=".activity.SettingActivity">
        </activity>
        <activity android:name=".activity.GameViewActivity">
        </activity>
        <activity
            android:name="com.lzy.imagepicker.ui.ImagePreviewDelActivity"
            android:theme="@style/ImagePickerThemeFullScreen"/>
        <activity
            android:name=".activity.NickNameSetActivity"
            android:screenOrientation="portrait">
        </activity>
        <activity
            android:name=".activity.EmailSetActivity"
            android:screenOrientation="portrait">
        </activity>
        <activity
            android:name=".activity.SignatureSetActivity"
            android:screenOrientation="portrait">
        </activity>
        <activity
            android:name=".activity.GameListActivity"
            android:screenOrientation="portrait"/>

        <service android:name=".service.MusicService"/>

        <activity
            android:name=".activity.MusicListActivity"
            android:screenOrientation="portrait">
        </activity>
        <activity
            android:name="com.tencent.tauth.AuthActivity"
            android:launchMode="singleTask"
            android:noHistory="true">
            <intent-filter>
                <action android:name="android.intent.action.VIEW"/>

                <category android:name="android.intent.category.DEFAULT"/>
                <category android:name="android.intent.category.BROWSABLE"/>

                <data android:scheme="tencent101408140"/>
            </intent-filter>
        </activity>
        <activity
            android:name="com.tencent.connect.common.AssistActivity"
            android:configChanges="orientation|keyboardHidden"
            android:screenOrientation="behind"
            android:theme="@android:style/Theme.Translucent.NoTitleBar">
        </activity>

        <!-- 设置环信应用的AppKey -->
        <meta-data
            android:name="EASEMOB_APPKEY"
            android:value="1173170606178941#sudoku"/>
        <!-- 声明SDK所需的service SDK核心功能 -->
        <service
            android:name="com.hyphenate.chat.EMChatService"
            android:exported="true"/>
        <service
            android:name="com.hyphenate.chat.EMJobService"
            android:exported="true"
            android:permission="android.permission.BIND_JOB_SERVICE"/>
        <!-- 声明SDK所需的receiver -->
        <receiver android:name="com.hyphenate.chat.EMMonitorReceiver">
            <intent-filter>
                <action android:name="android.intent.action.PACKAGE_REMOVED"/>

                <data android:scheme="package"/>
            </intent-filter>
            <!-- 可选filter -->
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
                <action android:name="android.intent.action.USER_PRESENT"/>
            </intent-filter>
        </receiver>

        <activity android:name=".activity.AddFriendActivity">
        </activity>
    </application>

</manifest>


text:
import { getContext, setContext } from "../Global";
import { Seconds } from "../type/Units";
import { OfflineContext } from "./OfflineContext";
import { ToneAudioBuffer } from "./ToneAudioBuffer";

/**
 * Generate a buffer by rendering all of the Tone.js code within the callback using the OfflineAudioContext.
 * The OfflineAudioContext is capable of rendering much faster than real time in many cases.
 * The callback function also passes in an offline instance of [[Context]] which can be used
 * to schedule events along the Transport.
 * @param  callback  All Tone.js nodes which are created and scheduled within this callback are recorded into the output Buffer.
 * @param  duration     the amount of time to record for.
 * @return  The promise which is invoked with the ToneAudioBuffer of the recorded output.
 * @example
 * // render 2 seconds of the oscillator
 * Tone.Offline(() => {
 * 	// only nodes created in this callback will be recorded
 * 	const oscillator = new Tone.Oscillator().toDestination().start(0);
 * }, 2).then((buffer) => {
 * 	// do something with the output buffer
 * 	console.log(buffer);
 * });
 * @example
 * // can also schedule events along the Transport
 * // using the passed in Offline Transport
 * Tone.Offline(({ transport }) => {
 * 	const osc = new Tone.Oscillator().toDestination();
 * 	transport.schedule(time => {
 * 		osc.start(time).stop(time + 0.1);
 * 	}, 1);
 * 	// make sure to start the transport
 * 	transport.start(0.2);
 * }, 4).then((buffer) => {
 * 	// do something with the output buffer
 * 	console.log(buffer);
 * });
 * @category Core
 */
export async function Offline(
	callback: (context: OfflineContext) => Promise<void> | void,
	duration: Seconds,
	channels = 2,
	sampleRate: number = getContext().sampleRate,
): Promise<ToneAudioBuffer> {
	// set the OfflineAudioContext based on the current context
	const originalContext = getContext();

	const context = new OfflineContext(channels, duration, sampleRate);
	setContext(context);

	// invoke the callback/scheduling
	await callback(context);

	// then render the audio
	const bufferPromise = context.render();

	// return the original AudioContext
	setContext(originalContext);

	// await the rendering
	const buffer = await bufferPromise;

	// return the audio
	return new ToneAudioBuffer(buffer);
}


text:
import startOfDay from 'date-fns/startOfDay';
import omit from 'lodash/omit';
import { useCallback, useEffect, useReducer, useRef, useState } from 'react';

import type { DialogType, ModalFields, Props, State } from './types';

import { CREATE_ID } from '~client/constants/data';
import type { Delta, FieldKey } from '~client/types';
import type {
  IncomeDeductionInput,
  ListItemInput,
  StockSplitInput,
  TransactionInput,
} from '~client/types/gql';

const enum ActionType {
  Hidden,
  Shown,
  ChangedId,
}

type PersistentStatePayload = {
  type: DialogType;
  id?: number;
  canRemove: boolean;
};

type ActionHidden = {
  type: ActionType.Hidden;
};

type ActionShown = {
  type: ActionType.Shown;
  payload: PersistentStatePayload;
};

type ActionChangedId = {
  type: ActionType.ChangedId;
  payload: PersistentStatePayload;
};

export type Action = ActionHidden | ActionShown | ActionChangedId;

export type Reducer = (state: State, action: Action) => State;

function getTitle({ type, id }: Pick<PersistentStatePayload, 'type' | 'id'>): string {
  if (type === 'edit') {
    return `Editing id#${id}`;
  }
  return 'Add item';
}

const updatePersistentState = (
  state: State,
  { payload }: { payload: PersistentStatePayload },
): State => ({
  ...state,
  title: getTitle(payload),
  canRemove: payload.canRemove,
});

export const reducer: Reducer = (state, action): State => {
  if (action.type === ActionType.Hidden) {
    return {
      ...state,
      visible: false,
    };
  }
  if (action.type === ActionType.Shown) {
    return {
      ...updatePersistentState(state, action),
      visible: true,
    };
  }
  if (action.type === ActionType.ChangedId) {
    return updatePersistentState(state, action);
  }

  return state;
};

export const animationTime = 350;

export function useModalState<I extends ListItemInput>({
  type = 'edit',
  id = CREATE_ID,
  onRemove,
  active,
}: Pick<Props<I>, 'id' | 'active' | 'type' | 'onRemove'>): State {
  const canRemove = !!onRemove;
  const [state, dispatch] = useReducer<Reducer>(reducer, {
    title: getTitle({ type, id }),
    canRemove,
    visible: active,
  });

  const timer = useRef<number>();

  useEffect((): (() => void) => (): void => clearTimeout(timer.current), []);

  useEffect(() => {
    if (active && !state.visible) {
      dispatch({ type: ActionType.Shown, payload: { type, id, canRemove } });
    } else if (!active && state.visible) {
      clearTimeout(timer.current);
      timer.current = window.setTimeout(() => {
        dispatch({ type: ActionType.Hidden });
      }, animationTime);
    } else {
      dispatch({ type: ActionType.ChangedId, payload: { type, id, canRemove } });
    }
  }, [type, id, canRemove, active, state.visible]);

  return state;
}

const arrayTypeFields: string[] = ['transactions', 'stockSplits', 'deductions'];

function initField<I extends ListItemInput>(field: 'date', item: Delta<I>): Date;
function initField<I extends ListItemInput>(field: 'cost', item: Delta<I>): number;
function initField<I extends ListItemInput>(
  field: 'transactions',
  item: Delta<I>,
): TransactionInput[];
function initField<I extends ListItemInput>(
  field: 'stockSplits',
  item: Delta<I>,
): StockSplitInput[];
function initField<I extends ListItemInput>(
  field: 'deductions',
  item: Delta<I>,
): IncomeDeductionInput[];
function initField<I extends ListItemInput, K extends keyof I>(
  field: keyof I,
  item: Delta<I>,
): I[K];

function initField<I extends ListItemInput>(field: FieldKey<I>, item: Partial<I>): unknown {
  if (field === 'date' && !Reflect.get(item, field)) {
    return startOfDay(new Date());
  }
  if (field === 'cost' && typeof Reflect.get(item, field) === 'undefined') {
    return 0;
  }
  if (
    arrayTypeFields.includes(field as string) &&
    typeof Reflect.get(item, field) === 'undefined'
  ) {
    return [];
  }
  return item[field] ?? '';
}

const initFields = <I extends ListItemInput>(item: Partial<I>, fields: ModalFields<I>): I =>
  (Object.keys(fields) as FieldKey<I>[]).reduce<Partial<I>>(
    (last, field) => ({
      ...last,
      [field]: initField(field, item),
    }),
    omit(item, '__typename', 'id') as Partial<I>,
  ) as I;

export const emptyFields = {};
export const emptyItem = {};

export function useModalSubmit<I extends ListItemInput>({
  active,
  fields = emptyFields,
  id = CREATE_ID,
  item = emptyItem,
  onSubmit,
}: Pick<Props<I>, 'active' | 'fields' | 'id' | 'item' | 'onSubmit'>): {
  tempFields: I;
  invalid: FieldKey<I>[];
  onSubmitCallback: () => void;
  onChangeField: <F extends FieldKey<I>>(field: string, value: I[F] | undefined) => void;
} {
  const [tempFields, setTempFields] = useState<I>(initFields<I>(item, fields));
  useEffect(() => {
    setTempFields(initFields(item, fields));
  }, [item, fields]);

  const [invalid, setInvalid] = useState<FieldKey<I>[]>([]);
  const isInvalid = invalid.length > 0;

  const onSubmitCallback = useCallback(() => {
    const nextInvalid = (Object.keys(fields) as FieldKey<I>[]).filter(
      (field) =>
        typeof tempFields[field] === 'undefined' ||
        (typeof tempFields[field] === 'string' && !tempFields[field]),
    );
    setInvalid(nextInvalid);

    if (!nextInvalid.length) {
      onSubmit(id, tempFields);
      setTempFields(initFields(item, fields));
    }
  }, [item, fields, onSubmit, tempFields, id]);

  useEffect(() => {
    if (!active && isInvalid) {
      setInvalid([]);
    }
  }, [active, isInvalid]);

  const onChangeField = useCallback(
    <F extends FieldKey<I>>(field: string, value: I[F] | undefined): void =>
      setTempFields((last) => ({
        ...last,
        [field]: value,
      })),
    [],
  );

  return { tempFields, invalid, onSubmitCallback, onChangeField };
}


text:
namespace starboard {
namespace shared {
namespace pthread {

// This is the maximum priority that will be passed to SetRoundRobinScheduler().
const int kMaxRoundRobinPriority = 2;

// Permissions are needed to allow usage non-default thread schedulers and
// thread priorities. Specifically, /etc/security/limits.conf should set
// "rtprio" and "nice" limits. "rtprio" will allow use of the real-time
// schedulers, and "nice" will allow use of nice priorities as well as allow
// SCHED_IDLE threads to increase their priority. If the user is 'pi', then
// limits.conf should have the following lines:
//   @pi hard rtprio 99
//   @pi soft rtprio 99
//   @pi hard nice -20
//   @pi soft nice -20
const char kSchedulerErrorMessage[] =
    "Unable to set scheduler. Please update "
    "limits.conf to set 'rtprio' limit to 99 and 'nice' limit to -20.";

// Note that use of sched_setscheduler() has been found to be more reliably
// supported than pthread_setschedparam(), so we are using that.

void SetIdleScheduler() {
  struct sched_param thread_sched_param;
  thread_sched_param.sched_priority = 0;
  int result = sched_setscheduler(0, SCHED_IDLE, &thread_sched_param);
  SB_CHECK(result == 0) << kSchedulerErrorMessage;
}

void SetOtherScheduler() {
  struct sched_param thread_sched_param;
  thread_sched_param.sched_priority = 0;
  int result = sched_setscheduler(0, SCHED_OTHER, &thread_sched_param);
  SB_CHECK(result == 0) << kSchedulerErrorMessage;
}

// Here |priority| is a number >= 0, where the higher the number, the
// higher the priority.
//
// If real time priorities are not allowed, then fall back to SCHED_OTHER.
// Otherwise, use SCHED_RR with the desired priority (or RLIMIT_RTPRIO --
// whichever is lower).
void SetRoundRobinScheduler(int priority) {
  // Determine the minimum and maximum priorities that will be used.
  int min_priority = sched_get_priority_min(SCHED_RR);
  int max_used_priority = min_priority + kMaxRoundRobinPriority;

  struct rlimit rlimit_rtprio;
  getrlimit(RLIMIT_RTPRIO, &rlimit_rtprio);

  if (rlimit_rtprio.rlim_cur < min_priority) {
    // Can't use the real-time scheduler at all. Use SCHED_OTHER instead.
    // Performance will be noticeably worse than ideal.
    SB_LOG(ERROR) << "Unable to use real-time round-robin scheduler because "
                  << "the maximum real-time scheduling priority is too low ("
                  << rlimit_rtprio.rlim_cur << " < " << max_used_priority
                  << "). Update setting using `ulimit -r` or limits.conf file.";
    SetOtherScheduler();
    return;
  }

  if (rlimit_rtprio.rlim_cur < max_used_priority) {
    // The maximum desired priority will be clamped.
    // Performance will be slightly worse than ideal.
    SB_LOG(WARNING) << "The maximum real-time scheduling priority is too low ("
                    << rlimit_rtprio.rlim_cur << " < " << max_used_priority
                    << "). Update setting using `ulimit -r` or limits.conf "
                    << "file.";
  }

  struct sched_param thread_sched_param;
  thread_sched_param.sched_priority = std::min(
      min_priority + priority, static_cast<int>(rlimit_rtprio.rlim_cur));
  int result = sched_setscheduler(0, SCHED_RR, &thread_sched_param);
  SB_CHECK(result == 0) << kSchedulerErrorMessage;
}

void ThreadSetPriority(SbThreadPriority priority) {
  if (!kSbHasThreadPrioritySupport)
    return;

  // Use different schedulers according to priority. This is preferred over
  // using SCHED_RR for all threads because the scheduler time slice is too
  // high (defaults to 100ms) for the desired threading behavior.
  switch (priority) {
    case kSbThreadPriorityLowest:
    case kSbThreadPriorityLow:
      SetIdleScheduler();
      break;
    case kSbThreadNoPriority:
    case kSbThreadPriorityNormal:
      SetOtherScheduler();
      break;
    case kSbThreadPriorityHigh:
      SetRoundRobinScheduler(0);
      break;
    case kSbThreadPriorityHighest:
      SetRoundRobinScheduler(1);
      break;
    case kSbThreadPriorityRealTime:
      SetRoundRobinScheduler(kMaxRoundRobinPriority);
      break;
    default:
      SB_NOTREACHED();
      break;
  }
}

}  // namespace pthread
}  // namespace shared
}  // namespace starboard


text:
#include "dcmtk/config/osconfig.h"    /* make sure OS specific configuration is included first */

#include "dcmtk/ofstd/ofuuid.h"

#include "dcmtk/dcmdata/dcvrof.h"
#include "dcmtk/dcmdata/dcvrfl.h"
#include "dcmtk/dcmdata/dcswap.h"
#include "dcmtk/dcmdata/dcuid.h"      /* for UID generation */

// ********************************

DcmOtherFloat::DcmOtherFloat(const DcmTag &tag,
                             const Uint32 len)
  : DcmFloatingPointSingle(tag, len)
{
}

DcmOtherFloat::DcmOtherFloat(const DcmOtherFloat &old)
  : DcmFloatingPointSingle(old)
{
}

DcmOtherFloat::~DcmOtherFloat()
{
}

DcmOtherFloat &DcmOtherFloat::operator=(const DcmOtherFloat &obj)
{
    DcmFloatingPointSingle::operator=(obj);
    return *this;
}

OFCondition DcmOtherFloat::copyFrom(const DcmObject& rhs)
{
  if (this != &rhs)
  {
    if (rhs.ident() != ident()) return EC_IllegalCall;
    *this = OFstatic_cast(const DcmOtherFloat &, rhs);
  }
  return EC_Normal;
}

// ********************************

DcmEVR DcmOtherFloat::ident() const
{
    return EVR_OF;
}

OFCondition DcmOtherFloat::checkValue(const OFString & /*vm*/,
                                      const OFBool /*oldFormat*/)
{
    /* currently no checks are performed */
    return EC_Normal;
}

unsigned long DcmOtherFloat::getVM()
{
    /* value multiplicity for OF is defined as 1 */
    return 1;
}

// ********************************

OFCondition DcmOtherFloat::writeXML(STD_NAMESPACE ostream &out,
                                    const size_t flags)
{
    /* always write XML start tag */
    writeXMLStartTag(out, flags);
    /* OF data requires special handling in the Native DICOM Model format */
    if (flags & DCMTypes::XF_useNativeModel)
    {
        /* for an empty value field, we do not need to do anything */
        if (getLengthField() > 0)
        {
            /* encode binary data as Base64 */
            if (flags & DCMTypes::XF_encodeBase64)
            {
                out << "<InlineBinary>";
                Uint8 *byteValues = OFstatic_cast(Uint8 *, getValue());
                /* Base64 encoder requires big endian input data */
                swapIfNecessary(EBO_BigEndian, gLocalByteOrder, byteValues, getLengthField(), sizeof(Float32));
                /* update the byte order indicator variable correspondingly */
                setByteOrder(EBO_BigEndian);
                OFStandard::encodeBase64(out, byteValues, OFstatic_cast(size_t, getLengthField()));
                out << "</InlineBinary>" << OFendl;
            } else {
                /* generate a new UID but the binary data is not (yet) written. */
                OFUUID uuid;
                out << "<BulkData uuid=\"";
                uuid.print(out, OFUUID::ER_RepresentationHex);
                out << "\"/>" << OFendl;
            }
        }
    } else {
        /* write element value (if loaded) */
        if (valueLoaded())
        {
            Float32 *floatValues = NULL;
            /* get and check 32 bit float data */
            if (getFloat32Array(floatValues).good() && (floatValues != NULL))
            {
                /* increase default precision - see DcmFloatingPointSingle::print() */
                const STD_NAMESPACE streamsize oldPrecision = out.precision(8);
                /* we cannot use getVM() since it always returns 1 */
                const size_t count = getLengthField() / sizeof(Float32);
                /* print float values with separators */
                out << (*(floatValues++));
                for (unsigned long i = 1; i < count; i++)
                    out << "\\" << (*(floatValues++));
                /* reset i/o manipulators */
                out.precision(oldPrecision);
            }
        }
    }
    /* always write XML end tag */
    writeXMLEndTag(out, flags);
    /* always report success */
    return EC_Normal;
}


text:
package org.onosproject.yang;

import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.onosproject.core.CoreService;
import org.onosproject.drivers.netconf.MockCoreService;
import org.onosproject.yang.model.ModelConverter;
import org.onosproject.yang.model.ModelObjectData;
import org.onosproject.yang.model.NodeKey;
import org.onosproject.yang.model.ResourceData;
import org.onosproject.yang.model.ResourceId;
import org.onosproject.yang.model.SchemaContext;
import org.onosproject.yang.model.SchemaContextProvider;
import org.onosproject.yang.model.YangModel;
import org.onosproject.yang.runtime.CompositeData;
import org.onosproject.yang.runtime.CompositeStream;
import org.onosproject.yang.runtime.ModelRegistrationParam;
import org.onosproject.yang.runtime.RuntimeContext;
import org.onosproject.yang.runtime.YangModelRegistry;
import org.onosproject.yang.runtime.YangRuntimeService;
import org.onosproject.yang.runtime.YangSerializer;
import org.onosproject.yang.runtime.YangSerializerRegistry;
import org.onosproject.yang.runtime.impl.DefaultModelConverter;
import org.onosproject.yang.runtime.impl.DefaultYangModelRegistry;
import org.onosproject.yang.runtime.impl.DefaultYangRuntimeHandler;
import org.onosproject.yang.runtime.impl.DefaultYangSerializerRegistry;
import org.onosproject.yang.serializers.json.JsonSerializer;
import org.onosproject.yang.serializers.xml.XmlSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Set;

import static com.google.common.base.Preconditions.checkNotNull;

public class MockYangRuntimeManager implements YangModelRegistry,
            YangSerializerRegistry, YangRuntimeService, ModelConverter,
            SchemaContextProvider {

        private static final String APP_ID = "org.onosproject.yang";
        private final Logger log = LoggerFactory.getLogger(getClass());

        @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
        protected CoreService coreService;

        private DefaultYangModelRegistry modelRegistry;
        private DefaultYangSerializerRegistry serializerRegistry;
        private DefaultYangRuntimeHandler runtimeService;
        private DefaultModelConverter modelConverter;

        public void setModelRegistry(DefaultYangModelRegistry yReg) {
            this.modelRegistry = yReg;
        }

        @Activate
        public void activate() {
            coreService = new MockCoreService();
            coreService.registerApplication(APP_ID);
            serializerRegistry = new DefaultYangSerializerRegistry();
            runtimeService =
                    new DefaultYangRuntimeHandler(serializerRegistry, modelRegistry);
            serializerRegistry.registerSerializer(new JsonSerializer());
            serializerRegistry.registerSerializer(new XmlSerializer());
            modelConverter = new DefaultModelConverter(modelRegistry);
            log.info("Started");
        }

        @Deactivate
        public void deactivate() {
            log.info("Stopped");
        }

        @Override
        public void registerModel(ModelRegistrationParam p) {
            modelRegistry.registerModel(p);
        }

        @Override
        public void unregisterModel(ModelRegistrationParam p) {
            modelRegistry.unregisterModel(p);
        }

        @Override
        public Set<YangModel> getModels() {
            return modelRegistry.getModels();
        }

        @Override
        public void registerSerializer(YangSerializer ys) {
            serializerRegistry.registerSerializer(ys);
        }

        @Override
        public void unregisterSerializer(YangSerializer ys) {
            serializerRegistry.unregisterSerializer(ys);
        }

        @Override
        public Set<YangSerializer> getSerializers() {
            return serializerRegistry.getSerializers();
        }

        @Override
        public CompositeData decode(CompositeStream cs, RuntimeContext rc) {
            return runtimeService.decode(cs, rc);
        }

        @Override
        public CompositeStream encode(CompositeData cd, RuntimeContext rc) {
            return runtimeService.encode(cd, rc);
        }

        @Override
        public ModelObjectData createModel(ResourceData resourceData) {
            return modelConverter.createModel(resourceData);
        }

        @Override
        public ResourceData createDataNode(ModelObjectData modelObjectData) {
            return modelConverter.createDataNode(modelObjectData);
        }

        @Override
        public SchemaContext getSchemaContext(ResourceId resourceId) {
            checkNotNull(resourceId, " resource id can't be null.");
            NodeKey key = resourceId.nodeKeys().get(0);
            if (resourceId.nodeKeys().size() == 1 &&
                    "/".equals(key.schemaId().name())) {
                return modelRegistry;
            }
            log.info("To be implemented.");
            return null;
        }
}


text:
"""The hypervisors admin extension."""

import webob.exc

from nova.api.openstack import extensions
from nova import compute
from nova import exception
from nova.i18n import _
from nova import servicegroup

authorize = extensions.extension_authorizer('compute', 'hypervisors')

class HypervisorsController(object):
    """The Hypervisors API controller for the OpenStack API."""

    def __init__(self, ext_mgr):
        self.host_api = compute.HostAPI()
        self.servicegroup_api = servicegroup.API()
        super(HypervisorsController, self).__init__()
        self.ext_mgr = ext_mgr

    def _view_hypervisor(self, hypervisor, service, detail, servers=None,
                         **kwargs):
        hyp_dict = {
            'id': hypervisor.id,
            'hypervisor_hostname': hypervisor.hypervisor_hostname,
            }

        ext_status_loaded = self.ext_mgr.is_loaded('os-hypervisor-status')
        if ext_status_loaded:
            alive = self.servicegroup_api.service_is_up(service)
            hyp_dict['state'] = 'up' if alive else "down"
            hyp_dict['status'] = (
                'disabled' if service.disabled else 'enabled')

        if detail and not servers:
            fields = ('vcpus', 'memory_mb', 'local_gb', 'vcpus_used',
                      'memory_mb_used', 'local_gb_used',
                      'hypervisor_type', 'hypervisor_version',
                      'free_ram_mb', 'free_disk_gb', 'current_workload',
                      'running_vms', 'cpu_info', 'disk_available_least')
            ext_loaded = self.ext_mgr.is_loaded('os-extended-hypervisors')
            if ext_loaded:
                fields += ('host_ip',)
            for field in fields:
                hyp_dict[field] = hypervisor[field]

            hyp_dict['service'] = {
                'id': service.id,
                'host': hypervisor.host,
                }
            if ext_status_loaded:
                hyp_dict['service'].update(
                    disabled_reason=service.disabled_reason)

        if servers:
            hyp_dict['servers'] = [dict(name=serv['name'], uuid=serv['uuid'])
                                   for serv in servers]

        # Add any additional info
        if kwargs:
            hyp_dict.update(kwargs)

        return hyp_dict

    def index(self, req):
        context = req.environ['nova.context']
        authorize(context)
        compute_nodes = self.host_api.compute_node_get_all(context)
        req.cache_db_compute_nodes(compute_nodes)
        return dict(hypervisors=[self._view_hypervisor(
                                 hyp,
                                 self.host_api.service_get_by_compute_host(
                                     context, hyp.host),
                                 False)
                                 for hyp in compute_nodes])

    def detail(self, req):
        context = req.environ['nova.context']
        authorize(context)
        compute_nodes = self.host_api.compute_node_get_all(context)
        req.cache_db_compute_nodes(compute_nodes)
        return dict(hypervisors=[self._view_hypervisor(
                                 hyp,
                                 self.host_api.service_get_by_compute_host(
                                     context, hyp.host),
                                 True)
                                 for hyp in compute_nodes])

    def show(self, req, id):
        context = req.environ['nova.context']
        authorize(context)
        try:
            hyp = self.host_api.compute_node_get(context, id)
            req.cache_db_compute_node(hyp)
        except (ValueError, exception.ComputeHostNotFound):
            msg = _("Hypervisor with ID '%s' could not be found.") % id
            raise webob.exc.HTTPNotFound(explanation=msg)
        service = self.host_api.service_get_by_compute_host(
            context.elevated(), hyp.host)
        return dict(hypervisor=self._view_hypervisor(hyp, service, True))

    def uptime(self, req, id):
        context = req.environ['nova.context']
        authorize(context)
        try:
            hyp = self.host_api.compute_node_get(context, id)
            req.cache_db_compute_node(hyp)
        except (ValueError, exception.ComputeHostNotFound):
            msg = _("Hypervisor with ID '%s' could not be found.") % id
            raise webob.exc.HTTPNotFound(explanation=msg)

        # Get the uptime
        try:
            host = hyp.host
            uptime = self.host_api.get_host_uptime(context, host)
        except NotImplementedError:
            msg = _("Virt driver does not implement uptime function.")
            raise webob.exc.HTTPNotImplemented(explanation=msg)

        service = self.host_api.service_get_by_compute_host(context, host)
        return dict(hypervisor=self._view_hypervisor(hyp, service, False,
                                                     uptime=uptime))

    def search(self, req, id):
        context = req.environ['nova.context']
        authorize(context)
        hypervisors = self.host_api.compute_node_search_by_hypervisor(
                context, id)
        if hypervisors:
            return dict(hypervisors=[self._view_hypervisor(
                                     hyp,
                                     self.host_api.service_get_by_compute_host(
                                         context, hyp.host),
                                     False)
                                     for hyp in hypervisors])
        else:
            msg = _("No hypervisor matching '%s' could be found.") % id
            raise webob.exc.HTTPNotFound(explanation=msg)

    def servers(self, req, id):
        context = req.environ['nova.context']
        authorize(context)
        compute_nodes = self.host_api.compute_node_search_by_hypervisor(
                context, id)
        if not compute_nodes:
            msg = _("No hypervisor matching '%s' could be found.") % id
            raise webob.exc.HTTPNotFound(explanation=msg)
        hypervisors = []
        for compute_node in compute_nodes:
            instances = self.host_api.instance_get_all_by_host(context,
                    compute_node.host)
            service = self.host_api.service_get_by_compute_host(
                context, compute_node.host)
            hyp = self._view_hypervisor(compute_node, service, False,
                                        instances)
            hypervisors.append(hyp)
        return dict(hypervisors=hypervisors)

    def statistics(self, req):
        context = req.environ['nova.context']
        authorize(context)
        stats = self.host_api.compute_node_statistics(context)
        return dict(hypervisor_statistics=stats)

class Hypervisors(extensions.ExtensionDescriptor):
    """Admin-only hypervisor administration."""

    name = "Hypervisors"
    alias = "os-hypervisors"
    namespace = "http://docs.openstack.org/compute/ext/hypervisors/api/v1.1"
    updated = "2012-06-21T00:00:00Z"

    def get_resources(self):
        resources = [extensions.ResourceExtension('os-hypervisors',
                HypervisorsController(self.ext_mgr),
                collection_actions={'detail': 'GET',
                                    'statistics': 'GET'},
                member_actions={'uptime': 'GET',
                                'search': 'GET',
                                'servers': 'GET'})]

        return resources


text:
import * as canny from 'canny';
import { addPageEnvironmentNode } from '../../pageEnvironment';
import { icons } from '../../misc/icons';

const template = require('./header.html');

let cannyModules;

canny.add('header', {
    add : function (node) {
        node.innerHTML = template;
        cannyModules.icons = icons;
        canny.cannyParse.apply(cannyModules, [node]);
        addPageEnvironmentNode(node);
    }
});

export const header = function (mods) {
    cannyModules = mods;
};


text:
namespace peloton {
namespace planner {

AnalyzePlan::AnalyzePlan(storage::DataTable *table) : target_table_(table) {}

AnalyzePlan::AnalyzePlan(std::string table_name, std::string schema_name,
                         std::string database_name,
                         concurrency::TransactionContext *txn)
    : table_name_(table_name) {
  target_table_ = catalog::Catalog::GetInstance()->GetTableWithName(txn,
                                                                    database_name,
                                                                    schema_name,
                                                                    table_name);
}

AnalyzePlan::AnalyzePlan(std::string table_name, std::string schema_name,
                         std::string database_name,
                         std::vector<char *> column_names,
                         concurrency::TransactionContext *txn)
    : table_name_(table_name), column_names_(column_names) {
  target_table_ = catalog::Catalog::GetInstance()->GetTableWithName(txn,
                                                                    database_name,
                                                                    schema_name,
                                                                    table_name);
}

AnalyzePlan::AnalyzePlan(parser::AnalyzeStatement *analyze_stmt,
                         concurrency::TransactionContext *txn) {
  table_name_ = analyze_stmt->GetTableName();
  column_names_ = std::vector<char *>();
  for (auto &name : analyze_stmt->GetColumnNames())
    column_names_.push_back((char *)name.c_str());
  if (!table_name_.empty()) {
    target_table_ = catalog::Catalog::GetInstance()->GetTableWithName(txn,
                                                                      analyze_stmt->GetDatabaseName(),
                                                                      analyze_stmt->GetSchemaName(),
                                                                      table_name_);
  }
}

}  // namespace planner
}  // namespace peloton


text:
/* app/views/sections/photography.js - Main Photography page */
'use strict';

define([
    'jquery',
    'backbone',
    'underscore',
    'app/collections/photography',
    'app/views/partials/grid',
], function( $, Backbone, _, photoCollection, G ) {

    // Photo landing thumbnail
    var PhotoThumb = G.Thumb.extend({
        url : function() {
            return '/photography/' + this.model.get('url-title')
        }
    })

    // PhotoGrid
    var PhotoGrid = G.Grid.extend({
        Thumb : PhotoThumb
    })

    var Photography = G.Page.extend({
        class : 'photography',
        Grid : PhotoGrid
    })

    return new Photography({
        model : new Backbone.Model(),
        collection : photoCollection
    })
})


text:
order: 8
title:
  zh-CN: React 错误处理
  en-US: ErrorBoundary
---

## zh-CN

友好的 [React 错误处理](https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html) 包裹组件。

## en-US

ErrorBoundary Component for making error handling easier in [React](https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html).

```tsx
import { Alert, Button } from 'antd';
import React, { useState } from 'react';

const { ErrorBoundary } = Alert;
const ThrowError: React.FC = () => {
  const [error, setError] = useState<Error>();
  const onClick = () => {
    setError(new Error('An Uncaught Error'));
  };

  if (error) {
    throw error;
  }
  return (
    <Button danger onClick={onClick}>
      Click me to throw a error
    </Button>
  );
};

const App: React.FC = () => (
  <ErrorBoundary>
    <ThrowError />
  </ErrorBoundary>
);

export default App;
```