text:
<!DOCTYPE html>

  <meta http-equiv="content-type" content="text/html;charset=utf-8">
  <title>compatibility.rb</title>
  <link rel="stylesheet" href="/recap/rocco.css">

    Jump To …

          recap.rb
          recipes.rb
          rails.rb
          ruby.rb
          static.rb
          capistrano_extensions.rb
          cli.rb
          compatibility.rb
          environment.rb
          namespace.rb
          shell_command.rb
          tasks.rb
          bootstrap.rb
          bundler.rb
          deploy.rb
          env.rb
          foreman.rb
          multistage.rb
          preflight.rb
          rails.rb
          ruby.rb
          version.rb

compatibility.rb

          ¶

recap isn’t intended to be compatible with tasks (such as those within the bundler
or whenever projects) that are built on the original capistrano deployment recipes.  At times
though there are tasks that would work, but for some missing (and redundant) settings.

Including this recipe adds these legacy settings, but provides no guarantee that original tasks
will work.  Many are based on assumptions about the deployment layout that no longer hold true.

module Recap::Support::Compatibility
  extend Recap::Support::Namespace

          ¶

As git to manages releases, all deployments are placed directly in the deploy_to folder.  The
current_path is always this directory (no symlinking required).

  set(:current_path) { deploy_to }
end


text:
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.completion;

import com.intellij.application.options.CodeStyle;
import com.intellij.codeInsight.TailType;
import com.intellij.codeInsight.completion.scope.JavaCompletionProcessor;
import com.intellij.codeInsight.editorActions.wordSelection.DocTagSelectioner;
import com.intellij.codeInsight.javadoc.JavaDocUtil;
import com.intellij.codeInsight.lookup.*;
import com.intellij.codeInsight.template.TemplateManager;
import com.intellij.codeInsight.template.impl.ConstantNode;
import com.intellij.codeInsight.template.impl.TemplateImpl;
import com.intellij.codeInspection.InspectionProfile;
import com.intellij.codeInspection.SuppressionUtilCore;
import com.intellij.codeInspection.javaDoc.JavaDocLocalInspection;
import com.intellij.codeInspection.javaDoc.JavadocHighlightUtil;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Conditions;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.patterns.PsiElementPattern;
import com.intellij.patterns.PsiJavaPatterns;
import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.filters.TrueFilter;
import com.intellij.psi.impl.JavaConstantExpressionEvaluator;
import com.intellij.psi.impl.source.javadoc.PsiDocParamRef;
import com.intellij.psi.javadoc.*;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.ProcessingContext;
import com.intellij.util.SystemProperties;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.text.CharArrayUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

import java.util.*;

import static com.intellij.patterns.PlatformPatterns.psiElement;
import static com.intellij.patterns.StandardPatterns.string;

public class JavaDocCompletionContributor extends CompletionContributor implements DumbAware {
  private static final Logger LOG = Logger.getInstance(JavaDocCompletionContributor.class);
  private static final @NonNls String VALUE_TAG = "value";
  private static final @NonNls String LINK_TAG = "link";
  private static final InsertHandler<LookupElement> PARAM_DESCRIPTION_INSERT_HANDLER = (context, item) -> {
    if (context.getCompletionChar() != Lookup.REPLACE_SELECT_CHAR) return;

    context.commitDocument();
    PsiDocTag docTag = PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), context.getStartOffset(), PsiDocTag.class, false);
    if (docTag != null) {
      Document document = context.getDocument();
      int tagEnd = DocTagSelectioner.getDocTagRange(docTag, document.getCharsSequence(), 0).getEndOffset();
      int tail = context.getTailOffset();
      if (tail < tagEnd) {
        document.deleteString(tail, tagEnd);
      }
    }
  };
  static final PsiElementPattern.Capture<PsiElement> THROWS_TAG_EXCEPTION = psiElement().inside(
    psiElement(PsiDocTag.class).withName(
      string().oneOf(PsiKeyword.THROWS, "exception")));

  public JavaDocCompletionContributor() {
    extend(CompletionType.BASIC, PsiJavaPatterns.psiElement(JavaDocTokenType.DOC_TAG_NAME), new TagChooser());

    extend(CompletionType.BASIC, PsiJavaPatterns.psiElement().inside(PsiDocComment.class), new CompletionProvider<>() {
      @Override
      protected void addCompletions(@NotNull final CompletionParameters parameters,
                                    @NotNull final ProcessingContext context,
                                    @NotNull CompletionResultSet result) {
        final PsiElement position = parameters.getPosition();
        boolean isArg = PsiJavaPatterns.psiElement().afterLeaf("(").accepts(position);
        PsiDocTag tag = PsiTreeUtil.getParentOfType(position, PsiDocTag.class);
        boolean onlyConstants = !isArg && tag != null && tag.getName().equals(VALUE_TAG);

        final PsiReference ref = position.getContainingFile().findReferenceAt(parameters.getOffset());
        PsiElement refElement = ref == null ? null : ref.getElement();
        if (refElement instanceof PsiDocParamRef) {
          result = result.withPrefixMatcher(
            refElement.getText().substring(0, parameters.getOffset() - refElement.getTextRange().getStartOffset()));
          for (PsiNamedElement param : getParametersToSuggest(PsiTreeUtil.getParentOfType(position, PsiDocComment.class))) {
            result.addElement(PrioritizedLookupElement.withPriority(LookupElementBuilder.create(param, nameForParamTag(param)),
                                                                    param instanceof PsiTypeParameter ? 0 : 1));
          }
        }
        else if (ref instanceof PsiJavaReference) {
          result = JavaCompletionSorting.addJavaSorting(parameters, result);
          result.stopHere();

          for (LookupElement item : completeJavadocReference(position, (PsiJavaReference)ref)) {
            if (onlyConstants) {
              Object o = item.getObject();
              if (!(o instanceof PsiField)) continue;
              PsiField field = (PsiField)o;
              if (!(field.hasModifierProperty(PsiModifier.STATIC) && field.getInitializer() != null &&
                    JavaConstantExpressionEvaluator.computeConstantExpression(field.getInitializer(), false) != null)) {
                continue;
              }
            }

            if (isArg) {
              item = AutoCompletionPolicy.NEVER_AUTOCOMPLETE.applyPolicy(item);
            }
            result.addElement(item);
          }

          JavaCompletionContributor.addAllClasses(parameters, result, new JavaCompletionSession(result));
        }

        if (tag != null && "author".equals(tag.getName())) {
          result.addElement(LookupElementBuilder.create(SystemProperties.getUserName()));
        }
      }
    });

    extend(CompletionType.SMART, THROWS_TAG_EXCEPTION, new CompletionProvider<>() {
      @Override
      public void addCompletions(@NotNull final CompletionParameters parameters,
                                 @NotNull final ProcessingContext context,
                                 @NotNull final CompletionResultSet result) {
        final PsiElement element = parameters.getPosition();
        final Set<PsiClass> throwsSet = new HashSet<>();
        final PsiMethod method = PsiTreeUtil.getContextOfType(element, PsiMethod.class, true);
        if (method != null) {
          for (PsiClassType ref : method.getThrowsList().getReferencedTypes()) {
            final PsiClass exception = ref.resolve();
            if (exception != null && throwsSet.add(exception)) {
              result.addElement(TailTypeDecorator.withTail(new JavaPsiClassReferenceElement(exception), TailType.HUMBLE_SPACE_BEFORE_WORD));
            }
          }
        }
      }
    });
  }

  @NotNull
  private List<LookupElement> completeJavadocReference(PsiElement position, PsiJavaReference ref) {
    JavaCompletionProcessor processor = new JavaCompletionProcessor(position, TrueFilter.INSTANCE, JavaCompletionProcessor.Options.CHECK_NOTHING, Conditions.alwaysTrue());
    ref.processVariants(processor);
    return ContainerUtil.map(processor.getResults(), (completionResult) -> {
      LookupElement item = createReferenceLookupItem(completionResult.getElement());
      item.putUserData(JavaCompletionUtil.FORCE_SHOW_SIGNATURE_ATTR, Boolean.TRUE);
      return item;
    });
  }

  private LookupElement createReferenceLookupItem(final Object element) {
    if (element instanceof PsiMethod) {
      return new JavaMethodCallElement((PsiMethod)element) {
        @Override
        public void handleInsert(@NotNull InsertionContext context) {
          new MethodSignatureInsertHandler().handleInsert(context, this);
        }
      };
    }
    if (element instanceof PsiClass) {
      JavaPsiClassReferenceElement classElement = new JavaPsiClassReferenceElement((PsiClass)element);
      classElement.setInsertHandler(JavaClassNameInsertHandler.JAVA_CLASS_INSERT_HANDLER);
      return classElement;
    }

    return LookupItemUtil.objectToLookupItem(element);
  }

  private static PsiParameter getDocTagParam(PsiElement tag) {
    if (tag instanceof PsiDocTag && "param".equals(((PsiDocTag)tag).getName())) {
      PsiDocTagValue value = ((PsiDocTag)tag).getValueElement();
      if (value instanceof PsiDocParamRef) {
        final PsiReference psiReference = value.getReference();
        PsiElement target = psiReference != null ? psiReference.resolve() : null;
        if (target instanceof PsiParameter) {
          return (PsiParameter)target;
        }
      }
    }
    return null;
  }

  @Override
  public void fillCompletionVariants(@NotNull final CompletionParameters parameters, @NotNull final CompletionResultSet result) {
    PsiElement position = parameters.getPosition();
    if (PsiJavaPatterns.psiElement(JavaDocTokenType.DOC_COMMENT_DATA).accepts(position)) {
      final PsiParameter param = getDocTagParam(position.getParent());
      if (param != null) {
        suggestSimilarParameterDescriptions(result, position, param);
      }

      if (!(position.getParent() instanceof PsiInlineDocTag)) {
        suggestLinkWrappingVariants(parameters, result.withPrefixMatcher(CompletionUtil.findJavaIdentifierPrefix(parameters)), position);
      }

      suggestCodeLiterals(result, position);

      return;
    }

    super.fillCompletionVariants(parameters, result);
  }

  private static void suggestCodeLiterals(@NotNull CompletionResultSet result, PsiElement position) {
    PsiElement parent = position.getParent();
    if (parent instanceof PsiInlineDocTag && !"code".equals(((PsiInlineDocTag)parent).getName())) {
      return;
    }

    if (!result.getPrefixMatcher().getPrefix().isEmpty()) {
      for (String keyword : ContainerUtil.ar("null", "true", "false")) {
        LookupElementBuilder element = LookupElementBuilder.create(keyword);
        result.addElement(parent instanceof PsiInlineDocTag ? element : wrapIntoCodeTag(element));
      }
    }
  }

  @NotNull
  private static LookupElementBuilder wrapIntoCodeTag(LookupElementBuilder element) {
    String tagText = "{@code " + element.getLookupString() + "}";
    return element.withPresentableText(tagText).withInsertHandler(
      (context, item) -> context.getDocument().replaceString(context.getStartOffset(), context.getTailOffset(), tagText));
  }

  private void suggestLinkWrappingVariants(@NotNull CompletionParameters parameters,
                                           @NotNull CompletionResultSet result,
                                           PsiElement position) {
    PrefixMatcher matcher = result.getPrefixMatcher();
    int prefixStart = parameters.getOffset() - matcher.getPrefix().length() - position.getTextRange().getStartOffset();
    String text = position.getText();
    if (prefixStart > 0 && text.charAt(prefixStart - 1) == '#') {
      int classNameStart = findClassNameStart(text, prefixStart - 1);
      String mockCommentPrefix = "/** {@link ";
      String mockText = mockCommentPrefix + text.substring(classNameStart) + "}*/";
      PsiDocComment mockComment = JavaPsiFacade.getElementFactory(position.getProject()).createDocCommentFromText(mockText, position);
      PsiJavaReference ref = (PsiJavaReference)mockComment.findReferenceAt(mockCommentPrefix.length() + prefixStart - classNameStart);
      assert ref != null : mockText;
      for (LookupElement element : completeJavadocReference(ref.getElement(), ref)) {
        result.addElement(LookupElementDecorator.withInsertHandler(element, wrapIntoLinkTag((context, item) -> element.handleInsert(context))));
      }
    }
    else if (matcher.getPrefix().length() > 0) {
      InsertHandler<JavaPsiClassReferenceElement> handler = wrapIntoLinkTag(JavaClassNameInsertHandler.JAVA_CLASS_INSERT_HANDLER);
      AllClassesGetter.processJavaClasses(parameters, matcher, parameters.getInvocationCount() == 1, psiClass ->
        result.addElement(AllClassesGetter.createLookupItem(psiClass, handler)));
    }
  }

  private static int findClassNameStart(CharSequence text, int sharpOffset) {
    int offset = sharpOffset;
    while (offset > 0 && isQualifiedNamePart(text.charAt(offset - 1))) {
      offset--;
    }
    return offset;
  }

  private static boolean isQualifiedNamePart(char c) {
    return c == '.' || Character.isJavaIdentifierPart(c);
  }

  @NotNull
  private static <T extends LookupElement> InsertHandler<T> wrapIntoLinkTag(InsertHandler<T> delegate) {
    return (context, item) -> {
      Document document = context.getDocument();

      String link = "{@link ";
      int startOffset = context.getStartOffset();
      int qualifierStart = document.getCharsSequence().charAt(startOffset - 1) == '#'
                            ? findClassNameStart(document.getCharsSequence(), startOffset - 1)
                            : startOffset;

      document.insertString(qualifierStart, link);
      document.insertString(context.getTailOffset(), "}");
      context.setTailOffset(context.getTailOffset() - 1);
      context.getOffsetMap().addOffset(CompletionInitializationContext.START_OFFSET, startOffset + link.length());

      context.commitDocument();
      delegate.handleInsert(context, item);
      if (item.getObject() instanceof PsiField) {
        context.getEditor().getCaretModel().moveToOffset(context.getTailOffset() + 1);
      }
    };
  }

  private static void suggestSimilarParameterDescriptions(CompletionResultSet result, PsiElement position, final PsiParameter param) {
    final Set<String> descriptions = new HashSet<>();
    position.getContainingFile().accept(new PsiRecursiveElementWalkingVisitor() {
      @Override
      public void visitElement(@NotNull PsiElement element) {
        PsiParameter param1 = getDocTagParam(element);
        if (param1 != null && param1 != param &&
            Objects.equals(param1.getName(), param.getName()) && Comparing.equal(param1.getType(), param.getType())) {
          String text = "";
          for (PsiElement psiElement : ((PsiDocTag)element).getDataElements()) {
            if (psiElement != ((PsiDocTag)element).getValueElement()) {
              text += psiElement.getText();
            }
          }
          text = text.trim();
          if (text.contains(" ")) {
            descriptions.add(text);
          }
        }

        super.visitElement(element);
      }
    });
    for (String description : descriptions) {
      result.addElement(PrioritizedLookupElement.withPriority(
        LookupElementBuilder.create(description).withInsertHandler(PARAM_DESCRIPTION_INSERT_HANDLER), 1));
    }
  }

  private static class TagChooser extends CompletionProvider<CompletionParameters> {

    @Override
    protected void addCompletions(@NotNull final CompletionParameters parameters, @NotNull final ProcessingContext context, @NotNull final CompletionResultSet result) {
      final List<String> ret = new ArrayList<>();
      final PsiElement position = parameters.getPosition();
      final PsiDocComment comment = PsiTreeUtil.getParentOfType(position, PsiDocComment.class);
      assert comment != null;
      PsiElement parent = comment.getContext();
      if (parent instanceof PsiJavaFile) {
        final PsiJavaFile file = (PsiJavaFile)parent;
        if (PsiPackage.PACKAGE_INFO_FILE.equals(file.getName())) {
          final String packageName = file.getPackageName();
          parent = JavaPsiFacade.getInstance(position.getProject()).findPackage(packageName);
        }
      }

      final boolean isInline = position.getContext() instanceof PsiInlineDocTag;

      for (JavadocTagInfo info : JavadocManager.SERVICE.getInstance(position.getProject()).getTagInfos(parent)) {
        String tagName = info.getName();
        if (tagName.equals(SuppressionUtilCore.SUPPRESS_INSPECTIONS_TAG_NAME)) continue;
        if (isInline != info.isInline() && !(PsiUtil.isLanguageLevel16OrHigher(comment) && tagName.equals("return"))) continue;
        ret.add(tagName);
        addSpecialTags(ret, comment, tagName);
      }

      InspectionProfile inspectionProfile =
        InspectionProjectProfileManager.getInstance(position.getProject()).getCurrentProfile();
      JavaDocLocalInspection inspection =
        (JavaDocLocalInspection)inspectionProfile.getUnwrappedTool(JavaDocLocalInspection.SHORT_NAME, position);
      if (inspection != null) {
        final StringTokenizer tokenizer = new StringTokenizer(inspection.myAdditionalJavadocTags, ", ");
        while (tokenizer.hasMoreTokens()) {
          ret.add(tokenizer.nextToken());
        }
      }
      for (final String s : ret) {
        if (isInline) {
          result.addElement(LookupElementDecorator.withInsertHandler(LookupElementBuilder.create(s), new InlineInsertHandler()));
        } else {
          result.addElement(TailTypeDecorator.withTail(LookupElementBuilder.create(s), TailType.INSERT_SPACE));
        }
      }
      result.stopHere(); // no word completions at this point
    }

    private static void addSpecialTags(final List<? super String> result, PsiDocComment comment, String tagName) {
      if ("author".equals(tagName)) {
        result.add(tagName + " " + SystemProperties.getUserName());
        return;
      }

      if ("param".equals(tagName)) {
        for (PsiNamedElement parameter : getParametersToSuggest(comment)) {
          result.add(tagName + " " + nameForParamTag(parameter));
        }
        return;
      }

      if ("see".equals(tagName)) {
        PsiMember member = PsiTreeUtil.getParentOfType(comment, PsiMember.class);
        if (member instanceof PsiClass) {
          InheritanceUtil.processSupers((PsiClass)member, false, psiClass -> {
            String name = psiClass.getQualifiedName();
            if (StringUtil.isNotEmpty(name) && !CommonClassNames.JAVA_LANG_OBJECT.equals(name)) {
              result.add("see " + name);
            }
            return true;
          });
        }
      }
    }
  }

  private static List<PsiNamedElement> getParametersToSuggest(PsiDocComment comment) {
    List<PsiNamedElement> allParams = PsiDocParamRef.getAllParameters(comment);
    PsiDocTag[] tags = comment.getTags();
    return ContainerUtil.filter(allParams, param -> !JavadocHighlightUtil.hasTagForParameter(tags, param));
  }

  private static String nameForParamTag(PsiNamedElement param) {
    String name = param.getName();
    return param instanceof PsiTypeParameter ? "<" + name + ">" : name;
  }

  private static class InlineInsertHandler implements InsertHandler<LookupElement> {
    @Override
    public void handleInsert(@NotNull InsertionContext context, @NotNull LookupElement item) {
      if (context.getCompletionChar() == Lookup.REPLACE_SELECT_CHAR) {
        final Project project = context.getProject();
        PsiDocumentManager.getInstance(project).commitAllDocuments();
        final Editor editor = context.getEditor();
        final CaretModel caretModel = editor.getCaretModel();
        final int offset = caretModel.getOffset();
        final PsiElement element = context.getFile().findElementAt(offset - 1);
        PsiDocTag tag = PsiTreeUtil.getParentOfType(element, PsiDocTag.class);
        assert tag != null;

        for (PsiElement child = tag.getFirstChild(); child != null; child = child.getNextSibling()) {
          if (child instanceof PsiDocToken) {
            PsiDocToken token = (PsiDocToken)child;
            if (token.getTokenType() == JavaDocTokenType.DOC_INLINE_TAG_END) return;
          }
        }

        final String name = tag.getName();

        final CharSequence chars = editor.getDocument().getCharsSequence();
        final int currentOffset = caretModel.getOffset();
        if (chars.charAt(currentOffset) == '}') {
          caretModel.moveToOffset(offset + 1);
        }
        else if (chars.charAt(currentOffset + 1) == '}' && chars.charAt(currentOffset) == ' ') {
          caretModel.moveToOffset(offset + 2);
        }
        else if (name.equals(LINK_TAG)) {
          EditorModificationUtil.insertStringAtCaret(editor, " }");
          caretModel.moveToOffset(offset + 1);
          editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
          editor.getSelectionModel().removeSelection();
        }
        else {
          EditorModificationUtil.insertStringAtCaret(editor, "}");
          caretModel.moveToOffset(offset + 1);
        }
      }
    }
  }

  private static class MethodSignatureInsertHandler implements InsertHandler<JavaMethodCallElement> {
    @Override
    public void handleInsert(@NotNull InsertionContext context, @NotNull JavaMethodCallElement item) {
      PsiDocumentManager.getInstance(context.getProject()).commitDocument(context.getEditor().getDocument());
      final Editor editor = context.getEditor();
      final PsiMethod method = item.getObject();

      Document document = editor.getDocument();
      final CharSequence chars = document.getCharsSequence();
      int endOffset = editor.getCaretModel().getOffset();
      final Project project = context.getProject();
      int afterSharp = CharArrayUtil.shiftBackwardUntil(chars, endOffset - 1, "#") + 1;
      int signatureOffset = afterSharp;

      PsiElement element = context.getFile().findElementAt(signatureOffset - 1);
      final CodeStyleSettings styleSettings = CodeStyle.getSettings(context.getFile());
      PsiDocTag tag = PsiTreeUtil.getParentOfType(element, PsiDocTag.class);
      if (context.getCompletionChar() == Lookup.REPLACE_SELECT_CHAR && tag != null) {
        PsiDocTagValue valueElement = tag.getValueElement();
        int valueEnd = valueElement != null ? valueElement.getTextRange().getEndOffset() : -1;
        if (valueEnd >= afterSharp) {
          endOffset = valueEnd;
          context.setTailOffset(endOffset);
        }
      }
      document.deleteString(afterSharp, endOffset);
      editor.getCaretModel().moveToOffset(signatureOffset);
      editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
      editor.getSelectionModel().removeSelection();

      String methodName = method.getName();
      int beforeParenth = signatureOffset + methodName.length();
      PsiParameter[] parameters = method.getParameterList().getParameters();
      String signature = "(" +
                         StringUtil.join(parameters,
                                         p -> TypeConversionUtil.erasure(p.getType()).getCanonicalText(),
                                         "," + (styleSettings.getCommonSettings(JavaLanguage.INSTANCE).SPACE_AFTER_COMMA ? " " : "")) +
                         ")";
      String insertString = methodName + signature;
      if (!(tag instanceof PsiInlineDocTag)) {
        insertString += " ";
      }
      else {
        if (chars.charAt(signatureOffset) == '}') {
          afterSharp++;
        }
        else {
          insertString += "} ";
        }
      }

      document.insertString(signatureOffset, insertString);
      RangeMarker paramListMarker = document.createRangeMarker(TextRange.from(beforeParenth, signature.length()));
      editor.getCaretModel().moveToOffset(afterSharp + insertString.length());
      editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
      PsiDocumentManager.getInstance(project).commitDocument(document);

      shortenReferences(project, editor, context, beforeParenth + 1);

      if (parameters.length > 0) {
        startParameterListTemplate(context, editor, document, project, paramListMarker);
      }
    }

    private static void startParameterListTemplate(@NotNull InsertionContext context,
                                                   Editor editor,
                                                   Document document,
                                                   Project project, RangeMarker paramListMarker) {
      PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(document);
      int tail = editor.getCaretModel().getOffset();
      if (paramListMarker.isValid() && tail >= paramListMarker.getEndOffset()) {
        PsiDocComment docComment =
          PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), paramListMarker.getStartOffset(), PsiDocComment.class, false);
        if (docComment != null) {
          TemplateImpl template = new TemplateImpl("", "");
          ConstantNode node = new ConstantNode(document.getText(TextRange.create(paramListMarker)));
          template.addVariable("PARAMETERS", node, node, true);
          template.addTextSegment(document.getText(TextRange.create(paramListMarker.getEndOffset(), tail)));
          template.addEndVariable();
          template.setToShortenLongNames(false);

          editor.getCaretModel().moveToOffset(paramListMarker.getStartOffset());
          document.deleteString(paramListMarker.getStartOffset(), tail);

          TemplateManager.getInstance(project).startTemplate(editor, template);
        }
      }
    }

    private static void shortenReferences(final Project project, final Editor editor, InsertionContext context, int offset) {
      PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
      final PsiElement element = context.getFile().findElementAt(offset);
      final PsiDocComment docComment = PsiTreeUtil.getParentOfType(element, PsiDocComment.class);
      if (!JavaDocUtil.isInsidePackageInfo(docComment)) {
        final PsiDocTagValue tagValue = PsiTreeUtil.getParentOfType(element, PsiDocTagValue.class);
        if (tagValue != null) {
          try {
            JavaCodeStyleManager.getInstance(project).shortenClassReferences(tagValue);
          }
          catch (IncorrectOperationException e) {
            LOG.error(e);
          }
        }
        PsiDocumentManager.getInstance(context.getProject()).commitAllDocuments();
      }
    }
  }
}

redpajama_set_name: RedPajamaGithub


text: Hosts maven artifacts needed by some of my projects as well as artifacts of the projects themselves


text:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AcquireBearerTokenByUserCredentialSample")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("VMWARE INC")]
[assembly: AssemblyProduct("AcquireBearerTokenByUserCredentialSample")]
[assembly: AssemblyCopyright("Copyright © VMWARE 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("16a76b11-00ca-410b-9f1e-e1508c3e8fa8")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]


text:
<?php

declare(strict_types=1);

namespace Doctrine\ORM\Tools\Console\Command;

use Doctrine\DBAL\Connection;
use Doctrine\ORM\Mapping\Driver\DatabaseDriver;
use Doctrine\ORM\Tools\Console\MetadataFilter;
use Doctrine\ORM\Tools\DisconnectedClassMetadataFactory;
use Doctrine\ORM\Tools\EntityGenerator;
use Doctrine\ORM\Tools\Export\ClassMetadataExporter;
use Doctrine\ORM\Tools\Export\Driver\AbstractExporter;
use Doctrine\ORM\Tools\Export\Driver\AnnotationExporter;
use InvalidArgumentException;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

use function file_exists;
use function is_dir;
use function is_writable;
use function method_exists;
use function mkdir;
use function realpath;
use function sprintf;
use function strtolower;

/**
 * Command to convert your mapping information between the various formats.
 *
 * @link    www.doctrine-project.org
 */
class ConvertMappingCommand extends AbstractEntityManagerCommand
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this->setName('orm:convert-mapping')
             ->setAliases(['orm:convert:mapping'])
             ->setDescription('Convert mapping information between supported formats')
             ->addArgument('to-type', InputArgument::REQUIRED, 'The mapping type to be converted.')
             ->addArgument('dest-path', InputArgument::REQUIRED, 'The path to generate your entities classes.')
             ->addOption('em', null, InputOption::VALUE_REQUIRED, 'Name of the entity manager to operate on')
             ->addOption('filter', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'A string pattern used to match entities that should be processed.')
             ->addOption('force', 'f', InputOption::VALUE_NONE, 'Force to overwrite existing mapping files.')
             ->addOption('from-database', null, null, 'Whether or not to convert mapping information from existing database.')
             ->addOption('extend', null, InputOption::VALUE_OPTIONAL, 'Defines a base class to be extended by generated entity classes.')
             ->addOption('num-spaces', null, InputOption::VALUE_OPTIONAL, 'Defines the number of indentation spaces', 4)
             ->addOption('namespace', null, InputOption::VALUE_OPTIONAL, 'Defines a namespace for the generated entity classes, if converted from database.')
             ->setHelp(<<<EOT
Convert mapping information between supported formats.

This is an execute <info>one-time</info> command. It should not be necessary for
you to call this method multiple times, especially when using the <comment>--from-database</comment>
flag.

Converting an existing database schema into mapping files only solves about 70-80%
of the necessary mapping information. Additionally the detection from an existing
database cannot detect inverse associations, inheritance types,
entities with foreign keys as primary keys and many of the
semantical operations on associations such as cascade.

<comment>Hint:</comment> There is no need to convert YAML or XML mapping files to annotations
every time you make changes. All mapping drivers are first class citizens
in Doctrine 2 and can be used as runtime mapping for the ORM.

<comment>Hint:</comment> If you have a database with tables that should not be managed
by the ORM, you can use a DBAL functionality to filter the tables and sequences down
on a global level:

    \$config->setFilterSchemaAssetsExpression(\$regexp);
EOT
             );
    }

    /**
     * {@inheritdoc}
     *
     * @return int
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $ui = new SymfonyStyle($input, $output);

        $em = $this->getEntityManager($input);

        if ($input->getOption('from-database') === true) {
            $databaseDriver = new DatabaseDriver(
                method_exists(Connection::class, 'createSchemaManager')
                    ? $em->getConnection()->createSchemaManager()
                    : $em->getConnection()->getSchemaManager()
            );

            $em->getConfiguration()->setMetadataDriverImpl(
                $databaseDriver
            );

            $namespace = $input->getOption('namespace');
            if ($namespace !== null) {
                $databaseDriver->setNamespace($namespace);
            }
        }

        $cmf = new DisconnectedClassMetadataFactory();
        $cmf->setEntityManager($em);
        $metadata = $cmf->getAllMetadata();
        $metadata = MetadataFilter::filter($metadata, $input->getOption('filter'));

        // Process destination directory
        $destPath = $input->getArgument('dest-path');
        if (! is_dir($destPath)) {
            mkdir($destPath, 0775, true);
        }

        $destPath = realpath($destPath);

        if (! file_exists($destPath)) {
            throw new InvalidArgumentException(
                sprintf("Mapping destination directory '<info>%s</info>' does not exist.", $input->getArgument('dest-path'))
            );
        }

        if (! is_writable($destPath)) {
            throw new InvalidArgumentException(
                sprintf("Mapping destination directory '<info>%s</info>' does not have write permissions.", $destPath)
            );
        }

        $toType = strtolower($input->getArgument('to-type'));

        $exporter = $this->getExporter($toType, $destPath);
        $exporter->setOverwriteExistingFiles($input->getOption('force'));

        if ($exporter instanceof AnnotationExporter) {
            $entityGenerator = new EntityGenerator();
            $exporter->setEntityGenerator($entityGenerator);

            $entityGenerator->setNumSpaces((int) $input->getOption('num-spaces'));

            $extend = $input->getOption('extend');
            if ($extend !== null) {
                $entityGenerator->setClassToExtend($extend);
            }
        }

        if (empty($metadata)) {
            $ui->success('No Metadata Classes to process.');

            return 0;
        }

        foreach ($metadata as $class) {
            $ui->text(sprintf('Processing entity "<info>%s</info>"', $class->name));
        }

        $exporter->setMetadata($metadata);
        $exporter->export();

        $ui->newLine();
        $ui->text(
            sprintf(
                'Exporting "<info>%s</info>" mapping information to "<info>%s</info>"',
                $toType,
                $destPath
            )
        );

        return 0;
    }

    /**
     * @param string $toType
     * @param string $destPath
     *
     * @return AbstractExporter
     */
    protected function getExporter($toType, $destPath)
    {
        $cme = new ClassMetadataExporter();

        return $cme->getExporter($toType, $destPath);
    }
}


text:
'use strict';

var colors = require('colors');
var format = require('stringformat');

var strings = require('../../resources/index');

module.exports = function(dependencies){

  var local = dependencies.local,
      logger = dependencies.logger;

  return function(opts){
    var componentName = opts.componentName,
        templateType = opts.templateType,
        errors = strings.errors.cli;

    local.init(componentName, templateType, function(err, res){
      if(err){
        if(err === 'name not valid'){
          err = errors.NAME_NOT_VALID;
        }

        if(err === 'template type not valid'){
          err = errors.TEMPLATE_TYPE_NOT_VALID;
        }

        logger.log(format(errors.INIT_FAIL.red, err));
      } else {
        logger.log(format(strings.messages.cli.COMPONENT_INITED.green, componentName));
      }
    });
  };
};


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Utilities;

import java.awt.Point;

/**
 * This class combines a Point object and a direction integer to determine
 * the position of a player sprite and direction it is facing. It is used to record
 * the steps taken and enable the Undo function
 *
 * @author Yasen
 */
public class Position{

        private Point point;
        private int direction;

       /**
        * @param p Point: determines the point
        * @param dir DirectionL determines the direction
        */

        public Position(Point p, int dir){
            point = p;
            direction = dir;
        }

       /**
        * @param x Point: determines the x Index
        * @param y Point: determines the y Index
        * @param dir DirectionL determines the direction
        */
        public Position(int x, int y, int dir){
            point = new Point(x,y);
            direction = dir;
        }

        /**
         *   Translates the position obkect into a String with the following format:
         *       "XCOORDINATE,YCOORDITANE,DIRECTION-"
         */
        @Override
        public String toString() {
            return ""+ getPoint().x + "," + getPoint().y + "," +getDirection()+"-";
        }

    /**
     * @return the point
     */
    public Point getPoint() {
        return point;
    }

    /**
     * @param point the point to set
     */
    public void setPoint(Point point) {
        this.point = point;
    }

    /**
     * @return the direction
     */
    public int getDirection() {
        return direction;
    }

    /**
     * @param direction the direction to set
     */
    public void setDirection(int direction) {
        this.direction = direction;
    }

}


text:
static ThreadSearch::ResultType Result;
static DialogMain* Dialog;

static void onWar3Found() {
	bool success;
	Dialog->t_status()->SetWindowText(L"¼ì²âµ½ÓÎÏ·£¬×¢ÈëÖÐ...");
	VMProtectBeginVirtualization("Inject");
	success = Inject(Result.win, Result.process_handle, Result.invoker, L"MHModule.dll");
	VMProtectEnd();
	if (success)
		Dialog->t_status()->SetWindowText(L"×¢Èë³É¹¦");
	else {
		MessageBox(Dialog->handle(), L"×¢Èëʧ°Ü£¡Çë³¢ÊԹرÕɱ¶¾Èí¼þ¡£", NULL, MB_ICONERROR);
		Dialog->t_status()->SetWindowText(L"×¢Èëʧ°Ü");
	}
}

static void onWar3Closed() {
	Dialog->t_status()->SetWindowText(L"µÈ´ýÓÎÏ·¿ªÆô");
}

int Main() {

	BOOLEAN enabled;
	VMProtectBeginVirtualization("AdjustPrivilege");
	if (!NT_SUCCESS(NTDLL::RtlAdjustPrivilege(NTDLL::SE_DEBUG_PRIVILEGE, 1, 0, &enabled))) {
		Abort(EXCEPTION_ADJUST_PRIVILEGE);
	}
	VMProtectEnd();

	ThreadSearch ts;
	ts.onWar3WindowFound += onWar3Found;
	ts.onWar3WindowClosed += onWar3Closed;
	ts.Run((DWORD)&Result);

	Dialog = new DialogMain();
	Dialog->Show(true);
	Dialog->WaitClose();
	delete Dialog;

	ts.Term();
	return 0;
}


text:
module Refinery
  class Activity
    attr_accessor :conditions

    # Image asset to use to represent newly created instances of the class this activity
    # represents
    attr_accessor :created_image

    # Total number of activies to show for a given class of activity
    attr_accessor :limit

    attr_accessor :nested_with

    # SQL order by string to specify how to order the activities in the activity feed for
    # the given activities class
    attr_accessor :order

    # The title to be displayed for each item of this activity
    attr_accessor :title

    # Image asset to use to represent updated instance of the class thisa activity represents
    attr_accessor :updated_image

    # Creates a new instance of Activity for a registered Refinery Plugin. An optional
    # hash of options can be specified to customize the values of each attribute
    # accessor defined on this class. Each key specified in the options hash should be a
    # symbol representation of the accessor name you wish to customize the value for.
    #
    # Example:
    #   To override the limit and title of the activity:
    #   Activity.new(:limit => 10, :title => "Newest Activity!")
    #
    # Warning:
    #  for the nested_with option, pass in the reverse order of ancestry e.g. [parent.parent_of_parent, parent]
    def initialize(options = {})
      {
        :class_name => nil,
        :conditions => nil,
        :created_image => "add.png",
        :limit => 7,
        :nested_with => [],
        :order => "updated_at DESC",
        :title => "title",
        :updated_image => "edit.png",
        :url => nil,
        :url_prefix => "edit"
      }.merge(options).each { |key, value| self.send(:"#{key}=", value) }
    end

    # Returns a string representation of the Class name of the object which this instance is recording
    attr_reader :class_name

    # Sets the class_name instance variable. Takes one parameter which must be a Class Constant, String, or Symbol.
    #
    # Example:
    #   activity.class_name = :'refinery/image'
    #   activity.class_name = "Refinery::Image"
    #   activity.class_name = Refinery::Image
    def class_name=(value)
      @class_name = value.to_s.camelize
    end

    # Returns a string containing the base class name (everything to the right of the last :: in the class definition)
    # of the Class this instance is recording
    #
    # Example:
    #   Given: Activity.new(:class_name => "Refinery::Image")
    #
    #   activity.base_class_name => "Image"
    def base_class_name
      self.klass.name.demodulize
    end

    # Returns the Class Constant for the Class which this instance is recording
    #
    # Example:
    #   activity.klass => Refinery::Image
    def klass
      self.class_name.constantize
    end

    # to use in a URL like edit_refinery_admin_group_individuals_path(record.group, record)
    # which will help you if you're using nested routed.
    def nesting(record_string = "record")
      self.nested_with.inject("") { |nest_chain, nesting|
        nest_chain << "#{record_string}.#{nesting},"
      }
    end

    attr_writer :url_prefix

    def url_prefix
      "#{"#{@url_prefix}_".gsub("__", "_") if @url_prefix.present?}"
    end

    attr_writer :url

    def url
      "#{self.url_prefix}#{@url ||= [ 'refinery', klass.model_name.param_key.to_s.pluralize,
                                      'admin', klass.model_name.param_key, 'path' ].join('_')}"
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="Encoding">
    <file url="file://$PROJECT_DIR$/playground" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/playground/web-playground" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/playground/web-playground/web-a" charset="UTF-8" />
  </component>
</project>


text:
/*
  Wrapper for longlong2str.s

  We need this because the assembler code can't access the local variable
  _dig_vector in a portable manner.
*/

#include <my_global.h>
#include "m_string.h"

extern char *longlong2str_with_dig_vector(longlong val,char *dst,int radix,
                                          const char *dig_vector);

char *longlong2str(longlong val,char *dst,int radix)
{
  return longlong2str_with_dig_vector(val, dst, radix, _dig_vec_upper);
}


text:
package org.apache.felix.sigil.common.osgi;

import java.lang.reflect.Constructor;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;

public class SimpleTerm extends AbstractExpr
{
    public static final char WILDCARD = 2 ^ 16 - 1;
    private static final String WILDCARD_STRING = new String(
        new char[] { SimpleTerm.WILDCARD });

    private Ops op;
    private String name;
    private String rval;

    public SimpleTerm(String name, Ops op, String value)
    {
        this.op = op;
        this.name = name.intern();
        this.rval = value.intern();
    }

    public String getName()
    {
        return name;
    }

    public Ops getOp()
    {
        return op;
    }

    public String getRval()
    {
        return rval;
    }

    public boolean eval(Map<String, ?> map)
    {

        Object lval = map.get(name);
        if (lval == null)
        {
            return false;
        }
        else if (Ops.EQ == op && WILDCARD_STRING.equals(lval))
        {
            return true;
        }
        // any match in the vector will do
        else if (lval instanceof Vector<?>)
        {
            Vector<?> vec = (Vector<?>) lval;
            for (Iterator<?> i = vec.iterator(); i.hasNext();)
            {
                if (check(i.next()))
                {
                    return true;
                }
            }
            return false;
        }
        // any match in the array will do
        else if (lval instanceof Object[])
        {
            Object[] arr = (Object[]) lval;
            for (int i = 0; i < arr.length; i++)
            {
                if (check(arr[i]))
                {
                    return true;
                }
            }
            return false;
        }
        return check(lval);
    }

    @SuppressWarnings("unchecked")
    private boolean check(Object lval)
    {
        if (lval == null)
        {
            return false;
        }
        else if (Ops.EQ == op && WILDCARD_STRING.equals(lval))
        {
            return true;
        }

        Object rhs = null;

        if (lval instanceof String)
        {

            if (Ops.APPROX == op)
            {
                rhs = collapseWhiteSpace(rval);
                lval = collapseWhiteSpace((String) lval);
            }

            if (Ops.EQ == op || Ops.APPROX == op)
            {
                return stringCheck((String) lval);
            }
            // rhs already a string

        }
        else if (lval.getClass() == Byte.class)
        {
            rhs = Byte.valueOf(rval);
        }
        else if (lval.getClass() == Short.class)
        {
            rhs = Short.valueOf(rval);
        }
        else if (lval.getClass() == Integer.class)
        {
            rhs = Integer.valueOf(rval);
        }
        else if (lval.getClass() == Long.class)
        {
            rhs = Long.valueOf(rval);
        }
        else if (lval.getClass() == Float.class)
        {
            rhs = Float.valueOf(rval);
        }
        else if (lval.getClass() == Double.class)
        {
            rhs = Double.valueOf(rval);
        }
        else
        {
            try
            {
                Constructor<?> stringCtor = lval.getClass().getConstructor(
                    new Class[] { String.class });
                rhs = stringCtor.newInstance(rval);
            }
            catch (Exception e)
            {
                // log it
                e.printStackTrace();
                return false;
            }
        }

        if (!(lval instanceof Comparable))
        {
            return Ops.EQ == op && lval.equals(rval);
        }
        else
        {

            Comparable<? super Object> lhs = (Comparable<? super Object>) lval;

            int compare = lhs.compareTo(rhs);

            switch (op)
            {
                case EQ:
                    return compare == 0;
                case APPROX:
                    return compare == 0;
                case GE:
                    return compare >= 0;
                case LE:
                    return compare <= 0;
                case GT:
                    return compare > 0;
                case LT:
                    return compare < 0;
            }
        }

        return false;
    }

    private boolean stringCheck(String lhs)
    {

        String rhs;
        switch (op)
        {
            case EQ:
            case APPROX:
                rhs = rval;
                break;
            default:
                return false;
        }

        int valLength = lhs.length();
        int patLength = rval.length();

        if (valLength == 0 && patLength == 0)
        {
            return true;
        }

        boolean wc = false;
        int j = 0;
        for (int i = 0; i < patLength; i++)
        {
            // trailing wildcards
            char pc = rhs.charAt(i);
            if (j == valLength)
            {
                if (pc != SimpleTerm.WILDCARD)
                {
                    return false;
                }
                continue;
            }
            if (pc == SimpleTerm.WILDCARD)
            {
                wc = true;
                continue;
            }
            while (wc && j < valLength - 1 && lhs.charAt(j) != pc)
            {
                j++;
            }
            if (lhs.charAt(j) != pc)
            {
                return false;
            }
            else
            {
                wc = false;
                j++;
            }
        }
        return (wc || j == valLength);

    }

    private String collapseWhiteSpace(String in)
    {
        StringBuffer out = new StringBuffer(in.trim().length());
        boolean white = false;
        for (int i = 0; i < in.length(); i++)
        {
            char ch = in.charAt(i);
            if (Character.isWhitespace(ch))
            {
                white = true;
            }
            else
            {
                if (white)
                {
                    out.append(" ");
                    white = false;
                }
                out.append(ch);
            }
        }
        return out.toString();
    }

    public LDAPExpr[] getChildren()
    {
        return CHILDLESS;
    }

    @Override
    public boolean equals(Object other)
    {
        if (other instanceof SimpleTerm)
        {
            SimpleTerm that = (SimpleTerm) other;
            return name.equals(that.name) && op.equals(that.op) && rval.equals(that.rval);
        }
        return false;
    }

    @Override
    public String toString()
    {
        return "(" + name + " " + op.toString() + " " + escape(rval) + ")";
    }

    private String escape(String raw)
    {
        StringBuffer buf = new StringBuffer(raw.length() + 10);
        for (int i = 0; i < raw.length(); i++)
        {
            char ch = raw.charAt(i);
            switch (ch)
            {
                case SimpleTerm.WILDCARD:
                    buf.append("*");
                    break;
                case '(':
                case ')':
                case '*':
                    buf.append("\\").append(ch);
                    break;
                default:
                    buf.append(ch);
            }
        }
        return buf.toString();
    }
}


text:
<?php

namespace AppBundle\Entity\Grade;

use AppBundle\Model\Grade\GradeGatewayInterface;
use AppBundle\Model\Grade\GradeInterface;
use Doctrine\ORM\EntityRepository;

/**
 * Class GradeGateway.
 */
class GradeGateway extends EntityRepository implements GradeGatewayInterface
{
    /**
     * @param string|int|Grade $id
     */
    public function find($id)
    {
        return parent::find($id);
    }
    /**
     * @param array $criteria
     * @param array $sort
     * @param int   $limit
     * @param int   $skip
     */
    public function findBy(array $criteria, array $sort = null, $limit = null, $skip = null)
    {
        return parent::findBy($criteria, $sort, $limit, $skip);
    }
    /**
     * @param array $criteria
     */
    public function findOneBy(array $criteria, array $orderBy = null)
    {
        return parent::findOneBy($criteria);
    }
    /**
     * @return Grade
     */
    public function findNew($subject = null, $description = null)
    {
        return new Grade($subject, $description);
    }

    /**
     * @param GradeInterface $grade
     *
     * @return GradeInterface
     */
    public function insert(GradeInterface $grade)
    {
        $this->_em->persist($grade);
        $this->_em->flush();

        return $grade;
    }
    /**
     * Update Grade.
     */
    public function update()
    {
        $this->_em->flush();
    }
    /**
     * @param $id
     */
    public function remove($id)
    {
        $grade = $this->find($id);
        $this->_em->remove($grade);
        $this->_em->flush();
    }
}


text:
//
//  BCShowView.h
//  wwz
//
//  Created by wwz on 16/8/9.
//  Copyright © 2016年 cn.szwwz. All rights reserved.
//

#import <UIKit/UIKit.h>

typedef NS_ENUM(NSUInteger, WWZShowViewAnimateType) {
    WWZShowViewAnimateTypeAlpha,         // 透明度
    WWZShowViewAnimateTypeFromTop,      // 从上面弹出
    WWZShowViewAnimateTypeFromLeft,     // 从左面弹出
    WWZShowViewAnimateTypeFromBottom,   // 从下面弹出
    WWZShowViewAnimateTypeFromRight     // 从右面弹出

};

@interface WWZShowView : UIView

/**
 *  点击空白区域消失,default is YES
 */
@property (nonatomic, assign, getter=isTapEnabled) BOOL tapEnabled;

/**
 *  空白区域背景颜色, default is [UIColor colorWithWhite:0 alpha:0.3]
 */
@property (nonatomic, strong) UIColor *backColor;

/**
 *  动画时间,default is 0.3s
 */
@property (nonatomic, assign) NSTimeInterval animateDuration;

/**
 *  弹出类型, default is none
 */
@property (nonatomic, assign) WWZShowViewAnimateType animateType;

/**
 *  显示
 */
- (void)wwz_showCompletion:(void (^)(BOOL finished))completion;

/**
 *  隐藏
 */
- (void)wwz_dismissCompletion:(void (^)(BOOL finished))completion;

@end


text:
package org.caleydo.core.data.virtualarray.similarity;

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

import org.caleydo.core.data.virtualarray.VirtualArray;
import org.caleydo.core.data.virtualarray.group.Group;
import org.caleydo.core.id.IDMappingManagerRegistry;
import org.caleydo.core.id.IIDTypeMapper;

/**
 * The similarity of one group in source VA1 to all groups in target VA2. You
 * can get two types of information from this class:
 *

 *
The score (accessible via {@link #getScore(int)}), which tells you
 * how many elements this group shares with the group of the other VA in this
 * GroupSimilarity.

 *
The similarity (accessible via {@link #getSimilarity(int)} and in
 * bulk via {@link #getSimilarities()}) which tells you how similar this group
 * is to the other group or groups. The contract here is that if all elements of
 * this group are contained in the foreign group as well, the similarity will be
 * 1, if none are contained 0.
 *

 *

 * Notice that the score of two groups for each other in two VAs will be
 * identical, the similarities however not, since the similarities also consider
 * the size of the group.
 *

 *
 * @author Alexander Lex
 */
public class GroupSimilarity {

	/** Get the id of the group for which the similarities are contained */

	public int getGroupID() {
		return group.getGroupIndex();
	}

	/**
	 * Get the number of shared elements between this group and the group of va2
	 * specified through the groupID
	 *
	 * @param groupID
	 * @return
	 */
	public int getScore(int groupID) {
		if (groupID >= scores.length)
			throw new IllegalArgumentException();
		return scores[groupID];
	}

	/**
	 * Returns the similarity of this group to the group specified via the
	 * groupID in a rate normalized between 0 and 1
	 *
	 * @param groupID
	 * @return
	 */
	public float getSimilarity(int groupID) {
		return similarities[groupID];
	}

	/**
	 * Returns the similarity of this group to all other groups, normalized
	 * between 0 and 1
	 *
	 * @param groupID
	 * @return
	 */
	public float[] getSimilarities() {
		return similarities;
	}

	public int[] getScores() {
		return scores;
	}

	/**
	 * Returns a new virtual array containing all elements which occur in the
	 * primary group of this group similarity and an external group specified
	 * through the foreign group ID.
	 *
	 * @param foreignGroupID
	 *            Returns null if createSimilarity flag is false.
	 * @return
	 */
	public VirtualArray getSimilarityVAs(int foreignGroupID) {

		if (!createSimilarityVAs)
			return null;

		return similarityVAs.get(foreignGroupID);
	}

	@Override
	public String toString() {
		return "Gr. Sim.: src.: " + group + " to: " + scores.length + " groups";
	}

	// -------------------- END OF PUBLIC INTERFACE
	// ----------------------------------

	private int[] scores;
	private Group group;
	private VirtualArray va1;
	private VirtualArray va2;
	private float[] similarities;
	private ArrayList<VirtualArray> similarityVAs;
	private boolean createSimilarityVAs = true;

	GroupSimilarity(Group group, VirtualArray va1, VirtualArray va2) {
		this.va1 = va1;
		this.va2 = va2;
		this.group = group;
		scores = new int[va2.getGroupList().size()];

		if (createSimilarityVAs) {
			similarityVAs = new ArrayList<VirtualArray>(va2.getGroupList().size());

			for (int vaCount = 0; vaCount < va2.getGroupList().size(); vaCount++) {
				// it does not matter which va we use as we only need the object
				similarityVAs.add(new VirtualArray(va2.getIdType()));
			}
		}
	}

	void calculateSimilarity() {
		IIDTypeMapper<Integer, Integer> mapper = IDMappingManagerRegistry.get().getIDMappingManager(va1.getIdType())
				.getIDTypeMapper(va1.getIdType(), va2.getIdType());
		// map all at once
		for (Integer id : mapper.apply(va1.getIDsOfGroup(group.getGroupIndex()))) {
			List<Group> groups2 = va2.getGroupOf(id);

			if (groups2.size() > 1) {
				System.out.println("Similarity size sum: " + groups2.size());
				// throw new IllegalArgumentException("wa");
			}

			for (Group group2 : groups2) {
				scores[group2.getGroupIndex()] += 1;

				if (createSimilarityVAs) {
					similarityVAs.get(group2.getGroupIndex()).append(id);
				}
			}
		}
		int sum = 0;
		similarities = new float[scores.length];
		for (int count = 0; count < scores.length; count++) {
			sum += scores[count];
			similarities[count] = ((float) scores[count]) / group.getSize();
		}

		if (sum != group.getSize()) {
			System.out.println("Similarity size sum " + sum + "!= group sum "
					+ group.getSize());
		}
	}

	void setScore(int groupID, int score) {
		scores[groupID] = score;
	}
}


text:
@interface IMBackgroundFetcher()

@property (nonatomic, copy) void (^completionHandler)(BOOL success);

@end

@implementation IMBackgroundFetcher

- (void)startBackgroundUpdatesWithCompletionHandler:(void (^)(BOOL success))completionHandler
{
    NSLog(@"Starting background updates... ");
    self.completionHandler = completionHandler;
    [self fetchReferences];
}

- (void)execute:(IMDataFetcher *)fetcher
{
    fetcher.onFailure = ^(NSError *error){ [self finishedWithError:error]; };
    [fetcher fetchUpdates];
}

- (void)finished
{
    if (self.completionHandler) self.completionHandler(YES);
    NSLog(@"Background Updates Finished");
}

- (void)finishedWithError:(NSError *)error
{
    if (self.completionHandler) self.completionHandler(NO);
    NSLog(@"Background updates error: %@", [error description]);
}

#pragma mark Fetcher Management
- (void)fetchReferences
{
    NSLog(@"Updating References");
    IMDataFetcher *fetcher = [[IMReferencesFetcher alloc] init];
    fetcher.onFinished = ^{ [self fetchAccommodations]; };
    [self execute:fetcher];
}

- (void)fetchAccommodations
{
    NSLog(@"Updating Accommodations");
    IMDataFetcher *fetcher = [[IMAccommodationFetcher alloc] init];
    fetcher.onFinished = ^{ [self fetchInterceptionLocations]; };
    [self execute:fetcher];
}

- (void)fetchInterceptionLocations
{
    NSLog(@"Updating Interception Locations");
    IMDataFetcher *fetcher = [[IMInterceptionLocationFetcher alloc] init];
    fetcher.onFinished = ^{ [self fetchInterceptionCases]; };
    [self execute:fetcher];
}

- (void)fetchInterceptionCases
{
    NSLog(@"Updating Interception Cases");
    IMDataFetcher *fetcher = [[IMInterceptionFetcher alloc] init];
    fetcher.onFinished = ^{ [self synchronizePhotos]; };
    [self execute:fetcher];
}

- (void)fetchMigrants
{
    NSLog(@"Updating Irregular Migrant Data");

}

- (void)synchronizePhotos
{
    NSLog(@"Downloading Photos...");
    IMDataFetcher *fetcher = [[IMPhotoFetcher alloc] init];
    fetcher.onFinished = ^{ [self finished]; };
    [self execute:fetcher];
}

@end


text:
/**
 * Root package for Stork, containing classes for launching the application and
 * providing access to global configuration. Most command line commands will
 * delegate execution to classes in the {@code stork.client} package. One
 * exception is the {@code server} command, which is implemented in {@code
 * StorkServer} and for the most part delegates to classes in the {@code
 * stork.scheduler} package.
 *
 * Other functionality is organized into other subpackages. More information
 * can be found in their respective documentation.
 */
package stork;


text:
package mil.nga.geopackage.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

import mil.nga.geopackage.GeoPackageException;
import mil.nga.geopackage.user.ContentValues;

/**
 * SQL Utility methods
 *
 * @author osbornb
 */
public class SQLUtils {

	/**
	 * Logger
	 */
	private static final Logger log = Logger
			.getLogger(SQLUtils.class.getName());

	/**
	 * Execute the SQL
	 *
	 * @param connection
	 * @param sql
	 */
	public static void execSQL(Connection connection, String sql) {
		Statement statement = null;
		try {
			statement = connection.createStatement();
			statement.execute(sql);
		} catch (SQLException e) {
			throw new GeoPackageException("Failed to execute SQL statement: "
					+ sql, e);
		} finally {
			closeStatement(statement, sql);
		}

	}

	/**
	 * Query for results
	 *
	 * @param connection
	 * @param sql
	 * @param selectionArgs
	 * @return
	 */
	public static ResultSet query(Connection connection, String sql,
			String[] selectionArgs) {

		PreparedStatement statement = null;
		ResultSet resultSet = null;

		try {
			statement = connection.prepareStatement(sql);
			setArguments(statement, selectionArgs);
			resultSet = statement.executeQuery();
		} catch (SQLException e) {
			throw new GeoPackageException("Failed to execute SQL statement: "
					+ sql, e);
		} finally {
			if (resultSet == null) {
				closeStatement(statement, sql);
			}
		}

		return resultSet;
	}

	/**
	 * Attempt to count the results of the query
	 *
	 * @param connection
	 * @param sql
	 * @param selectionArgs
	 * @return count if known, -1 if not able to determine
	 */
	public static int count(Connection connection, String sql,
			String[] selectionArgs) {

		if (!sql.toLowerCase().contains(" count(*) ")) {
			int index = sql.toLowerCase().indexOf(" from ");
			if (index == -1) {
				return -1;
			}
			sql = "select count(*)" + sql.substring(index);
		}

		ResultSet resultSet = query(connection, sql, selectionArgs);

		int count = 0;
		try {
			if (resultSet.next()) {
				count = resultSet.getInt(1);
			} else {
				throw new GeoPackageException("Failed to get count. SQL: "
						+ sql);
			}
		} catch (SQLException e) {
			throw new GeoPackageException("Failed to get count. SQL: " + sql, e);
		} finally {
			closeResultSetStatement(resultSet, sql);
		}

		return count;
	}

	/**
	 * Get the query count
	 *
	 * @param connection
	 * @param table
	 * @param where
	 * @param args
	 * @return
	 */
	public static int count(Connection connection, String table, String where,
			String[] args) {
		StringBuilder countQuery = new StringBuilder();
		countQuery.append("select count(*) from ").append(table);
		if (where != null) {
			countQuery.append(" where ").append(where);
		}
		String sql = countQuery.toString();

		ResultSet resultSet = query(connection, sql, args);

		int count = 0;
		try {
			if (resultSet.next()) {
				count = resultSet.getInt(1);
			} else {
				throw new GeoPackageException("Failed to get count. SQL: "
						+ sql);
			}
		} catch (SQLException e) {
			throw new GeoPackageException("Failed to get count. SQL: " + sql, e);
		} finally {
			closeResultSetStatement(resultSet, sql);
		}

		return count;
	}

	/**
	 * Execute a deletion
	 *
	 * @param connection
	 * @param table
	 * @param where
	 * @param args
	 * @return
	 */
	public static int delete(Connection connection, String table, String where,
			String[] args) {
		StringBuilder delete = new StringBuilder();
		delete.append("delete from ").append(table);
		if (where != null) {
			delete.append(" where ").append(where);
		}
		String sql = delete.toString();

		PreparedStatement statement = null;

		int count = 0;
		try {
			statement = connection.prepareStatement(sql);
			setArguments(statement, args);
			count = statement.executeUpdate();
		} catch (SQLException e) {
			throw new GeoPackageException(
					"Failed to execute SQL delete statement: " + sql, e);
		} finally {
			closeStatement(statement, sql);
		}

		return count;
	}

	/**
	 * Update table rows
	 *
	 * @param connection
	 * @param table
	 * @param values
	 * @param whereClause
	 * @param whereArgs
	 * @return
	 */
	public static int update(Connection connection, String table,
			ContentValues values, String whereClause, String[] whereArgs) {

		StringBuilder update = new StringBuilder();
		update.append("update ").append(table).append(" set ");

		int setValuesSize = values.size();
		int argsSize = (whereArgs == null) ? setValuesSize
				: (setValuesSize + whereArgs.length);
		Object[] args = new Object[argsSize];
		int i = 0;
		for (String colName : values.keySet()) {
			update.append((i > 0) ? "," : "");
			update.append(colName);
			args[i++] = values.get(colName);
			update.append("=?");
		}
		if (whereArgs != null) {
			for (i = setValuesSize; i < argsSize; i++) {
				args[i] = whereArgs[i - setValuesSize];
			}
		}
		if (whereClause != null) {
			update.append(" WHERE ");
			update.append(whereClause);
		}
		String sql = update.toString();

		PreparedStatement statement = null;

		int count = 0;
		try {
			statement = connection.prepareStatement(sql);
			setArguments(statement, args);
			count = statement.executeUpdate();
		} catch (SQLException e) {
			throw new GeoPackageException(
					"Failed to execute SQL update statement: " + sql, e);
		} finally {
			closeStatement(statement, sql);
		}

		return count;
	}

	/**
	 * Insert a new row
	 *
	 * @param connection
	 * @param table
	 * @param values
	 * @return row id or -1 on an exception
	 */
	public static long insert(Connection connection, String table,
			ContentValues values) {
		try {
			return insertOrThrow(connection, table, values);
		} catch (Exception e) {
			log.log(Level.WARNING, "Error inserting into table: " + table
					+ ", Values: " + values, e);
			return -1;
		}
	}

	/**
	 * Insert a new row
	 *
	 * @param connection
	 * @param table
	 * @param values
	 * @return row id
	 */
	public static long insertOrThrow(Connection connection, String table,
			ContentValues values) {

		StringBuilder insert = new StringBuilder();
		insert.append("insert into ").append(table).append("(");

		Object[] args = null;
		int size = (values != null && values.size() > 0) ? values.size() : 0;

		args = new Object[size];
		int i = 0;
		for (String colName : values.keySet()) {
			insert.append((i > 0) ? "," : "");
			insert.append(colName);
			args[i++] = values.get(colName);
		}
		insert.append(')');
		insert.append(" values (");
		for (i = 0; i < size; i++) {
			insert.append((i > 0) ? ",?" : "?");
		}
		insert.append(')');

		String sql = insert.toString();

		PreparedStatement statement = null;

		long id = 0;
		try {
			statement = connection.prepareStatement(sql);
			setArguments(statement, args);
			int count = statement.executeUpdate();

			if (count == 0) {
				throw new GeoPackageException(
						"Failed to execute SQL insert statement: " + sql
								+ ". No rows added from execution.");
			}

			try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
				if (generatedKeys.next()) {
					id = generatedKeys.getLong(1);
				} else {
					throw new GeoPackageException(
							"Failed to execute SQL insert statement: " + sql
									+ ". No row id was found.");
				}
			}
		} catch (SQLException e) {
			throw new GeoPackageException(
					"Failed to execute SQL insert statement: " + sql, e);
		} finally {
			closeStatement(statement, sql);
		}

		return id;
	}

	/**
	 * Set the prepared statement arguments
	 *
	 * @param statement
	 * @param selectionArgs
	 * @throws SQLException
	 */
	public static void setArguments(PreparedStatement statement,
			Object[] selectionArgs) throws SQLException {
		if (selectionArgs != null) {
			for (int i = 0; i < selectionArgs.length; i++) {
				statement.setObject(i + 1, selectionArgs[i]);
			}
		}
	}

	/**
	 * Close the statement
	 *
	 * @param statement
	 * @param sql
	 */
	public static void closeStatement(Statement statement, String sql) {
		if (statement != null) {
			try {
				statement.close();
			} catch (SQLException e) {
				log.log(Level.WARNING, "Failed to close SQL Statement: " + sql,
						e);
			}
		}
	}

	/**
	 * Close the ResultSet
	 *
	 * @param resultSet
	 * @param sql
	 */
	public static void closeResultSet(ResultSet resultSet, String sql) {
		if (resultSet != null) {
			try {
				resultSet.close();
			} catch (SQLException e) {
				log.log(Level.WARNING, "Failed to close SQL ResultSet: " + sql,
						e);
			}
		}
	}

	/**
	 * Close the ResultSet Statement from which it was created, which closes all
	 * ResultSets as well
	 *
	 * @param resultSet
	 * @param sql
	 */
	public static void closeResultSetStatement(ResultSet resultSet, String sql) {
		if (resultSet != null) {
			try {
				resultSet.getStatement().close();
			} catch (SQLException e) {
				log.log(Level.WARNING, "Failed to close SQL ResultSet: " + sql,
						e);
			}
		}
	}

}


text:
package com.vaadin.fluent.ui;

import com.vaadin.fluent.api.FluentPanel;
import com.vaadin.ui.Component;
import com.vaadin.ui.Panel;

public class FPanel
        extends Panel
        implements FluentPanel<FPanel> {

    private static final long serialVersionUID = 8200973348099977390L;

    public FPanel() {
        super();
    }

    public FPanel(Component content) {
        super(content);
    }

    public FPanel(String caption) {
        super(caption);
    }

    public FPanel(String caption, Component content) {
        super(caption, content);
    }

}


text:
package org.apache.edgent.console.servlets;

import java.lang.management.ManagementFactory;

import javax.management.JMX;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;

import org.apache.edgent.streamscope.mbeans.StreamScopeMXBean;
import org.apache.edgent.streamscope.mbeans.StreamScopeRegistryMXBean;

public class StreamScopeUtil {

  /**
   * Get the StreamScope for the specified stream.
   *

   * N.B. until certain runtime issues are worked out, the stream that a
   * StreamScopeMXBean is registered for is NOT the "origin stream" (opletId/oport)
   * that the StreamScope was created for.  Rather the registration is for
   * the actual StreamScope oplet's opletId and oport 0, so that's what must be
   * supplied as the parameters.
   *

   * See the commentary in StreamScope oplet code.
   *

   * Once that is addressed, opletId/oport of the "origin stream" will
   * need to be supplied as parameters.
   *

   *
   * @param jobId the job id (e.g., "JOB_0")
   * @param opletId the oplet id (e.g., "OP_2")
   * @param oport the oplet output port index (0-based)
   *
   * @return null if no StreamScope registered for that stream.
   */
  public static StreamScopeMXBean getStreamScope(String jobId, String opletId, int oport) {
    return getRgy().lookup(jobId, opletId, oport);
  }

  private static StreamScopeRegistryMXBean getRgy() {
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    ObjectName objName = mkObjectName(StreamScopeRegistryMXBean.class, StreamScopeRegistryMXBean.TYPE);
    return JMX.newMXBeanProxy(mbs, objName, StreamScopeRegistryMXBean.class);
  }

  private static ObjectName mkObjectName(Class<?> klass, String beanType) {
    StringBuffer sbuf = new StringBuffer();
    try {
      sbuf.append("*:interface=");
      sbuf.append(ObjectName.quote(klass.getCanonicalName()));
      sbuf.append(",type=");
      sbuf.append(ObjectName.quote(beanType));
      return new ObjectName(sbuf.toString());
    }
    catch (MalformedObjectNameException e) {

      // TODO logger.error("Unable to create ObjectName for "+sbuf, e);

      throw new RuntimeException("Unable to create ObjectName for "+sbuf, e);
    }
  }

}


text:
FROM node:14.6.0-slim

COPY ./ ./

RUN npm install

ENV NODE_ENV production
ENV DATABASE mongo

CMD ["node", "app.js"]


text:
@media(min-width: 1000px){
    [data-am-heroslideshow~="two-box"] .video {
        height: 390px;
        min-width: 580px;
    }
}

[data-am-searchlist] {
    width: 100%;
}

[data-am-button~="filter-chooser"].open:after {
    content: '\e801' !important;
}

[data-am-contactcard]{
    border-bottom: none !important;
}

.quote {
    margin-bottom: 0 !important;
}
.tight-paragraphs p {
    margin-bottom: 0 !important;
}
.fit-image {
    max-width: 100%;
}

.anchor {
    display: block;
    position: relative;
    top: -80px;
    visibility: hidden;
}
.product-anchor{
    display: block;
    position: relative;
    top: -160px;
    visibility: hidden;
}
[data-am-heroslideshow~="one-box"] .slider-item {
    height: 400px;
    vertical-align: top;
}


text:
package pl.chormon.ultimateclans.commands;

import pl.chormon.ultimateclans.Perm;
import pl.chormon.ultimatelib.commands.req.ReqHasPerm;

/**
 *
 * @author Chormon
 */
public class CmdUC extends UCCommand {

    private final CmdList cmdList = new CmdList();
    private final CmdCreate cmdCreate = new CmdCreate();
    private final CmdInvite cmdInvite = new CmdInvite();
    private final CmdInfo cmdInfo = new CmdInfo();
    private final CmdPlayers cmdPlayers = new CmdPlayers();
    private final CmdBoard cmdBoard = new CmdBoard();
    private final CmdTell cmdTell = new CmdTell();
    private final CmdAlly cmdAlly = new CmdAlly();
    private final CmdEnemy cmdEnemy = new CmdEnemy();
    private final CmdDisband cmdDisband = new CmdDisband();
    private final CmdVisualize cmdVisualize = new CmdVisualize();

    public CmdUC() {
        this.addAlias("wioska");

        this.setDesc("Komendy pluginu UltimateClans");

        this.addReq(new ReqHasPerm(Perm.UC.node));

        this.addSubCommand(cmdList);
        this.addSubCommand(cmdCreate);
        this.addSubCommand(cmdInvite);
        this.addSubCommand(cmdInfo);
        this.addSubCommand(cmdPlayers);
        this.addSubCommand(cmdBoard);
        this.addSubCommand(cmdTell);
        this.addSubCommand(cmdAlly);
        this.addSubCommand(cmdEnemy);
        this.addSubCommand(cmdDisband);
        this.addSubCommand(cmdVisualize);
    }

}


text:
package org.wso2.carbon.apimgt.rest.api.common.util;

import org.apache.commons.io.IOUtils;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.carbon.apimgt.core.api.APIMgtAdminService;
import org.wso2.carbon.apimgt.core.api.APIStore;
import org.wso2.carbon.apimgt.core.configuration.APIMConfigurationService;
import org.wso2.carbon.apimgt.core.configuration.models.APIMConfigurations;
import org.wso2.carbon.apimgt.core.exception.APIManagementException;
import org.wso2.carbon.apimgt.core.exception.ErrorHandler;
import org.wso2.carbon.apimgt.core.exception.ExceptionCodes;
import org.wso2.carbon.apimgt.core.impl.APIManagerFactory;
import org.wso2.carbon.apimgt.core.models.policy.Policy;
import org.wso2.carbon.apimgt.rest.api.common.RestApiConstants;
import org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO;
import org.wso2.carbon.apimgt.rest.api.common.exception.APIMgtSecurityException;
import org.wso2.carbon.apimgt.rest.api.common.exception.BadRequestException;
import org.wso2.carbon.transport.http.netty.config.ListenerConfiguration;
import org.wso2.carbon.transport.http.netty.config.TransportsConfiguration;
import org.wso2.carbon.transport.http.netty.config.YAMLTransportConfigurationBuilder;
import org.yaml.snakeyaml.Yaml;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Utility class for all REST APIS.
 */
public class RestApiUtil {

    private static final Logger log = LoggerFactory.getLogger(RestApiUtil.class);
    private static String publisherRestAPIDefinition;
    private static String storeRestAPIDefinition;
    private static String adminRestAPIDefinition;
    private static final String HTTP = "http";
    private static final String HTTPS = "https";
    private static APIMConfigurations apimConfigurations = APIMConfigurationService.getInstance()
            .getApimConfigurations();

    /**
     * Get the current logged in user's username
     * @return The current logged in user.
     */
    public static String getLoggedInUsername() {
//        CarbonContext carbonContext = CarbonContext.getCurrentContext();
//        Principal principal = carbonContext.getUserPrincipal();
//        return principal.getName();
        return "admin";
    }

    /**
     * Logs the error, builds a BadRequestException with specified details and throws it
     *
     * @param msg error message
     * @param log Log instance
     * @throws BadRequestException  If 400 bad request comes.
     */
    public static void handleBadRequest(String msg, Logger log) throws BadRequestException {
        BadRequestException badRequestException = buildBadRequestException(msg);
        log.error(msg);
        throw badRequestException;
    }

    /**
     * Returns a new BadRequestException
     *
     * @param description description of the exception
     * @return a new BadRequestException with the specified details as a response DTO
     */
    public static BadRequestException buildBadRequestException(String description) {
        ErrorDTO errorDTO = getErrorDTO(RestApiConstants.STATUS_BAD_REQUEST_MESSAGE_DEFAULT, 400L, description);
        return new BadRequestException(errorDTO);
    }

    /**
     * Returns a generic errorDTO
     *
     * @param errorHandler The error handler object.
     * @param paramList map of parameters specific to the error.
     * @return A generic errorDTO with the specified details
     */
    public static ErrorDTO getErrorDTO(ErrorHandler errorHandler, Map<String, String> paramList) {
        ErrorDTO errorDTO = new ErrorDTO();
        errorDTO.setCode(errorHandler.getErrorCode());
        errorDTO.setMoreInfo(paramList);
        errorDTO.setMessage(errorHandler.getErrorMessage());
        errorDTO.setDescription(errorHandler.getErrorDescription());
        return errorDTO;
    }

    /**
     * Returns a generic errorDTO
     *
     * @param errorHandler The error handler object.
     * @return A generic errorDTO with the specified details
     */
    public static ErrorDTO getErrorDTO(ErrorHandler errorHandler) {
        ErrorDTO errorDTO = new ErrorDTO();
        errorDTO.setCode(errorHandler.getErrorCode());
        errorDTO.setMessage(errorHandler.getErrorMessage());
        errorDTO.setDescription(errorHandler.getErrorDescription());
        return errorDTO;
    }

    /**
     * Return errorDTO object. This method accept APIMGTException as a parameter so we can set the e.getMessage
     * directly to the errorDTO.
     * @param errorHandler Error Handler object.
     * @param paramList Parameter list
     * @param e APIMGTException object.
     * @return ErrorDTO Object.
     */
    public static ErrorDTO getErrorDTO(ErrorHandler errorHandler, HashMap<String, String> paramList,
            APIManagementException e) {
        ErrorDTO errorDTO = new ErrorDTO();
        errorDTO.setCode(errorHandler.getErrorCode());
        errorDTO.setMoreInfo(paramList);
        if (e.getMessage() == null) {
            errorDTO.setMessage(errorHandler.getErrorMessage());
        } else {
            errorDTO.setMessage(e.getMessage());
        }
        errorDTO.setDescription(errorHandler.getErrorDescription());
        return errorDTO;
    }

    /**
     * Returns a generic errorDTO
     *
     * @param message specifies the error message
     * @param code  error code.
     * @param description   error description.
     * @return A generic errorDTO with the specified details
     */
    public static ErrorDTO getErrorDTO(String message, Long code, String description) {
        ErrorDTO errorDTO = new ErrorDTO();
        errorDTO.setCode(code);
        errorDTO.setMessage(message);
        errorDTO.setDescription(description);
        return errorDTO;
    }

    /**
     * Returns an APIStore.
     *
     * @param subscriberName    Name of the subscriber.
     * @return  {@code APIStore}
     * @throws APIManagementException   if failed to get the consumers.
     */
    public static APIStore getConsumer(String subscriberName) throws APIManagementException {
        return APIManagerFactory.getInstance().getAPIConsumer(subscriberName);
    }

    /**
     * Returns an APIStore for anonymous user.
     *
     * @return  {@code APIStore}
     * @throws APIManagementException if failed to get the consumer object.
     */
    public static APIStore getConsumer() throws APIManagementException {
        return APIManagerFactory.getInstance().getAPIConsumer();
    }

    /**
     * Returns an APIMgtAdminService.
     *
     * @return API Management Admin Service
     * @throws APIManagementException   If failed to retrieve admin service.
     */
    public static APIMgtAdminService getAPIMgtAdminService() throws APIManagementException {
        return APIManagerFactory.getInstance().getAPIMgtAdminService();
    }

    /**
     * Returns the next/previous offset/limit parameters properly when current offset, limit and size parameters are
     * specified
     *
     * @param offset current starting index
     * @param limit  current max records
     * @param size   maximum index possible
     * @return the next/previous offset/limit parameters as a hash-map
     */
    public static Map<String, Integer> getPaginationParams(Integer offset, Integer limit, Integer size) {
        Map<String, Integer> result = new HashMap<>();
        if (offset >= size || offset < 0) {
            return result;
        }
        int start = offset;
        int end = offset + limit - 1;

        int nextStart = end + 1;
        if (nextStart < size) {
            result.put(RestApiConstants.PAGINATION_NEXT_OFFSET, nextStart);
            result.put(RestApiConstants.PAGINATION_NEXT_LIMIT, limit);
        }

        int previousEnd = start - 1;
        int previousStart = previousEnd - limit + 1;

        if (previousEnd >= 0) {
            if (previousStart < 0) {
                result.put(RestApiConstants.PAGINATION_PREVIOUS_OFFSET, 0);
                result.put(RestApiConstants.PAGINATION_PREVIOUS_LIMIT, limit);
            } else {
                result.put(RestApiConstants.PAGINATION_PREVIOUS_OFFSET, previousStart);
                result.put(RestApiConstants.PAGINATION_PREVIOUS_LIMIT, limit);
            }
        }
        return result;
    }

    /**
     * Returns the paginated url for Applications API
     *
     * @param offset  starting index
     * @param limit   max number of objects returned
     * @return constructed paginated url
     */
    public static String getApplicationPaginatedURL(Integer offset, Integer limit) {
        String paginatedURL = RestApiConstants.APPLICATIONS_GET_PAGINATION_URL;
        paginatedURL = paginatedURL.replace(RestApiConstants.LIMIT_PARAM, String.valueOf(limit));
        paginatedURL = paginatedURL.replace(RestApiConstants.OFFSET_PARAM, String.valueOf(offset));
        return paginatedURL;
    }

    /**
     * Returns the gateway config retrieve url
     *
     * @param uuid api id
     * @return constructed gateway config retrieve  url
     */
    public static String getGatewayConfigGetURL(String uuid) {
        String path = RestApiConstants.GATEWAY_CONFIG_GET_URL + "/" + uuid + "/gateway-config";
        return path;
    }

    /**
     * Returns the swagger retrieve url
     *
     * @param uuid api id
     * @return constructed gateway config retrieve  url
     */
    public static String getSwaggerGetURL(String uuid) {
        String path = RestApiConstants.SWAGGER_GET_URL + "/" + uuid + "/swagger";
        return path;
    }

    /**
     * Search the Policy in the given collection of Policies. Returns it if it is included there. Otherwise return null
     *
     * @param policies Policy Collection
     * @param tierName Policy to find
     * @return Matched Policy with its name
     */
    public static Policy findPolicy(Collection<Policy> policies, String tierName) {
        for (Policy policy : policies) {
            if (policy.getPolicyName() != null && tierName != null && policy.getPolicyName().equals(tierName)) {
                return policy;
            }
        }
        return null;
    }

    public static boolean isURL(String sourceUrl) {
        //TODO: to be implemented
        return true;
    }

    /**
     * This is static method to return API definition of API Publisher REST API.
     * This content need to load only one time and keep it in memory as content will not change
     * during runtime.
     *
     * @return String associated with API Manager publisher REST API
     * @throws APIManagementException   if failed to get publisher api resource.
     */
    public static String getPublisherRestAPIResource() throws APIManagementException {

        if (publisherRestAPIDefinition == null) {
            //if(basePath.contains("/api/am/store/")){
            //this is store API and pick resources accordingly
            try {
                publisherRestAPIDefinition = IOUtils
                        .toString(RestApiUtil.class.getResourceAsStream(RestApiConstants.PUBLISHER_API_YAML), "UTF-8");
            } catch (IOException e) {
                String message = "Error while reading the swagger definition of Publisher Rest API";
                log.error(message, e);
                throw new APIMgtSecurityException(message, ExceptionCodes.API_NOT_FOUND);
            }

        }
        return publisherRestAPIDefinition;
    }

    /**
     * This is static method to return API definition of API Publisher REST API.
     * This content need to load only one time and keep it in memory as content will not change
     * during runtime.
     *
     * @return String associated with API Manager store REST API
     * @throws  APIManagementException   if failed to get store api resource
     */
    public static String getStoreRestAPIResource() throws APIManagementException {

        if (storeRestAPIDefinition == null) {
            //if(basePath.contains("/api/am/store/")){
            //this is store API and pick resources accordingly
            try {
                storeRestAPIDefinition = IOUtils
                        .toString(RestApiUtil.class.getResourceAsStream(RestApiConstants.STORE_API_YAML), "UTF-8");
            } catch (IOException e) {
                String message = "Error while reading the swagger definition of Store Rest API";
                log.error(message, e);
                throw new APIMgtSecurityException(message, ExceptionCodes.API_NOT_FOUND);
            }

        }
        return storeRestAPIDefinition;
    }

    /**
     * This method return API swagger definition of Admin REST API
     *
     * @return  String associated with API Manager admin REST API
     * @throws APIManagementException   if failed to get admin api resource
     */
    public static String getAdminRestAPIResource() throws APIManagementException {

        if (adminRestAPIDefinition == null) {
            // this is admin API and pick resources accordingly
            try {
                adminRestAPIDefinition = IOUtils
                        .toString(RestApiUtil.class.getResourceAsStream(RestApiConstants.ADMIN_API_YAML), "UTF-8");
            } catch (IOException e) {
                String message = "Error while reading the swagger definition of Admin Rest API";
                log.error(message, e);
                throw new APIMgtSecurityException(message, ExceptionCodes.API_NOT_FOUND);
            }

        }
        return adminRestAPIDefinition;
    }

    /**
     * used to convert yaml to json
     *
     * @param yamlString yaml String
     * @return  Json string
     */
    public static String convertYmlToJson(String yamlString) {
        Yaml yaml = new Yaml();
        Map map = (Map) yaml.load(yamlString);
        JSONObject jsonObject = new JSONObject();
        jsonObject.putAll(map);
        return jsonObject.toJSONString();
    }

    public static String getContext(String appType) {
        APIMConfigurations apimConfigurations = APIMConfigurationService.getInstance().getApimConfigurations();
        if (RestApiConstants.APPType.PUBLISHER.equals(appType)) {
            return apimConfigurations.getPublisherContext();
        } else if (RestApiConstants.APPType.STORE.equals(appType)) {
            return apimConfigurations.getStoreContext();
        } else if (RestApiConstants.APPType.ADMIN.equals(appType)) {
            return apimConfigurations.getAdminContext();
        } else {
            return null;
        }
    }

    public static String getHost(String protocol) {
        TransportsConfiguration transportsConfiguration = YAMLTransportConfigurationBuilder.build();
        Set<ListenerConfiguration> listenerConfigurationSet = transportsConfiguration.getListenerConfigurations();
        String host = apimConfigurations.getHostname();
        if (!apimConfigurations.isReverseProxyEnabled()) {
            if (HTTP.equals(protocol)) {
                for (ListenerConfiguration listenerConfiguration : listenerConfigurationSet) {
                    if (HTTP.equals(listenerConfiguration.getScheme())) {
                        host = host.concat(":").concat(String.valueOf(listenerConfiguration.getPort()));
                        break;
                    }
                }
            } else {
                for (ListenerConfiguration listenerConfiguration : listenerConfigurationSet) {
                    if (HTTPS.equals(listenerConfiguration.getScheme())) {
                        host = host.concat(":").concat(String.valueOf(listenerConfiguration.getPort()));
                    }
                }
            }
        }
        return host;
    }

    /**
     * Util method for mapping from rest API policy level String to {@link APIMgtAdminService.PolicyLevel} enum
     */
    public static APIMgtAdminService.PolicyLevel mapRestApiPolicyLevelToPolicyLevelEnum (String level)
            throws APIManagementException {
        if (APIMgtAdminService.PolicyLevel.api.name().equals(level)) {
            return APIMgtAdminService.PolicyLevel.api;
        } else if (APIMgtAdminService.PolicyLevel.application.name().equals(level)) {
            return APIMgtAdminService.PolicyLevel.application;
        } else if (APIMgtAdminService.PolicyLevel.subscription.name().equals(level)) {
            return APIMgtAdminService.PolicyLevel.subscription;
        } else {
            throw new APIManagementException("Policy Level " + level + " not supported",
                    ExceptionCodes.POLICY_LEVEL_NOT_SUPPORTED);
        }
    }
}