text:
<?php

declare(strict_types=1);

namespace SlimKit\PlusID;

class Action
{
    protected $actions = [
        'auth/resolve' => \SlimKit\PlusID\Actions\Auth\Resolve::class,
        'auth/login' => \SlimKit\PlusID\Actions\Auth\Login::class,
        'user/check' => \SlimKit\PlusID\Actions\User\Check::class,
        'user/create' => \SlimKit\PlusID\Actions\User\Create::class,
        'user/delete' => \SlimKit\PlusID\Actions\User\Delete::class,
        'user/show' => \SlimKit\PlusID\Actions\User\Show::class,
        'user/update' => \SlimKit\PlusID\Actions\User\Update::class,
    ];

    public function action(string $action)
    {
        if (isset($this->actions[$action])) {
            return new $this->actions[$action];
        }

        abort(404, '不存在的 API.');
    }
}


text:
package scala.tools.tastytest

import scala.util.{Try, Success, Failure}
import scala.util.control.NonFatal

import scala.reflect.internal.util.ScalaClassLoader
import scala.reflect.runtime.ReflectionUtils
import java.lang.reflect.{Modifier, Method}

import ClasspathOps._
import java.io.OutputStream
import java.io.BufferedReader
import java.io.PrintWriter

object Dotc extends Script.Command {

  final case class ClassLoader private (val parent: ScalaClassLoader)

  def initClassloader(): Try[Dotc.ClassLoader] =
    Try(Dotc.ClassLoader(ScalaClassLoader.fromURLs(Classpaths.dottyCompiler.asURLs)))

  def processIn(op: Dotc.ClassLoader => Int): Int = {
    Dotc.initClassloader() match {
      case Success(cl) => op(cl)
      case Failure(err) =>
        println(red(s"could not initialise Scala 3 classpath: $err"))
        1
    }
  }

  def loadClass(name: String)(implicit cl: Dotc.ClassLoader) =
    Class.forName(name, true, cl.parent)

  def invokeStatic(method: Method, args: Seq[Any])(implicit cl: Dotc.ClassLoader) = {
    assert(Modifier.isStatic(method.getModifiers), s"$method is not static!")
    invoke(method, null, args)
  }

  def invokeStatic(
      className: String,
      methodName: String,
      args: Seq[(Class[_], Any)],
  )(implicit cl: Dotc.ClassLoader): Try[Object] = {
    val cls = loadClass(className)
    val (tpes, provided) = args.unzip
    val method = cls.getMethod(methodName, tpes:_*)
    Try {
      invokeStatic(method, provided)
    }
  }

  def invoke(method: Method, obj: AnyRef, args: Seq[Any])(implicit cl: Dotc.ClassLoader) = {
    inClassloader[AnyRef] {
      method.invoke(obj, args.toArray:_*)
    }
  }

  def inClassloader[T](op: => T)(implicit cl: Dotc.ClassLoader): T = {
    try cl.parent.asContext[T] {
      op
    }
    catch {
      case NonFatal(ex) => throw ReflectionUtils.unwrapThrowable(ex)
    }
  }

  def processMethod(className: String)(args: Seq[String])(implicit cl: Dotc.ClassLoader): Try[Boolean] =
    processMethodImpl(className)(args, None)

  private def makeConsoleReporter(stream: OutputStream)(implicit cl: Dotc.ClassLoader): Try[AnyRef] = Try {
    val consoleReporterCls = loadClass("dotty.tools.dotc.reporting.ConsoleReporter")
    val ctor = consoleReporterCls.getConstructor(classOf[BufferedReader], classOf[PrintWriter])
    val pwriter = new PrintWriter(stream, true)
    inClassloader[AnyRef] {
      ctor.newInstance(Console.in, pwriter)
    }
  }

  private def processMethodImpl(className: String)(args: Seq[String], writer: Option[OutputStream])(implicit cl: Dotc.ClassLoader): Try[Boolean] = {
    val reporterCls = loadClass("dotty.tools.dotc.reporting.Reporter")
    val Reporter_hasErrors = reporterCls.getMethod("hasErrors")
    val processArgs: Try[Seq[(Class[_], Any)]] = {
      writer match {
        case Some(stream) =>
          val callbackCls = loadClass("dotty.tools.dotc.interfaces.CompilerCallback")
          for (myReporter <- makeConsoleReporter(stream)) yield
            Seq(classOf[Array[String]] -> args.toArray, reporterCls -> myReporter, callbackCls -> null)
        case _ =>
          Try(Seq(classOf[Array[String]] -> args.toArray))
      }
    }
    for {
      args <- processArgs
      reporter <- invokeStatic(className, "process", args)
    } yield {
      val hasErrors = invoke(Reporter_hasErrors, reporter, Seq.empty).asInstanceOf[Boolean]
      !hasErrors
    }
  }

  def mainMethod(className: String)(args: Seq[String])(implicit cl: Dotc.ClassLoader): Try[Unit] = {
    val mainArgs = Seq(classOf[Array[String]] -> args.toArray)
    for (_ <- invokeStatic(className, "main", mainArgs)) yield ()
  }

  def dotcVersion(implicit cl: Dotc.ClassLoader): String = {
    val compilerPropertiesClass = loadClass("dotty.tools.dotc.config.Properties")
    val Properties_simpleVersionString = compilerPropertiesClass.getMethod("simpleVersionString")
    invokeStatic(Properties_simpleVersionString, Seq.empty).asInstanceOf[String]
  }

  def dotc(out: String, classpath: String, additionalSettings: Seq[String], sources: String*)(implicit cl: Dotc.ClassLoader): Try[Boolean] =
    dotcImpl(None, out, classpath, additionalSettings, sources:_*)

  def dotc(writer: OutputStream, out: String, classpath: String, additionalSettings: Seq[String], sources: String*)(implicit cl: Dotc.ClassLoader): Try[Boolean] =
    dotcImpl(Some(writer), out, classpath, additionalSettings, sources:_*)

  def dotcImpl(writer: Option[OutputStream], out: String, classpath: String, additionalSettings: Seq[String], sources: String*)(implicit cl: Dotc.ClassLoader): Try[Boolean] = {
    if (sources.isEmpty) {
      Success(true)
    }
    else {
      val libraryDeps = Classpaths.dottyLibrary ++ Classpaths.scalaReflect
      val args = Seq(
        "-d", out,
        "-classpath", libraryDeps.mkString(classpath + Files.classpathSep, Files.classpathSep, ""),
        "-deprecation",
        "-Xfatal-warnings",
        "-color:never",
      ) ++ additionalSettings ++ sources
      if (TastyTest.verbose) {
        println(yellow(s"Invoking dotc (version $dotcVersion) with args: $args"))
      }
      processMethodImpl("dotty.tools.dotc.Main")(args, writer)
    }
  }

  val commandName: String = "dotc"
  val describe: String = s"$commandName <out: Directory> <src: File>"

  def process(args: String*): Int = {
    if (args.length < 2) {
      println(red(s"please provide at least two arguments in sub-command: $describe"))
      return 1
    }
    val Seq(out, src, additional @ _*) = args: @unchecked
    Dotc.processIn { implicit scala3classloader =>
      val success = dotc(out, out, additional, src).get
      if (success) 0 else 1
    }
  }

}

redpajama_set_name: RedPajamaGithub


text:
describe("Currency management", function () {
  it("should add a new currency", function () {
  });

  it("should add and return a new currency", function () {
  });

  it("should remove an existing currency", function () {
  });

  it("should silently replace when setting a duplicate currency", function () {
  });

  it("should throw an error when setting an invalid currency", function () {
  });

  it("should list all available currencies", function () {
  });
});


text:
package com.intellij.codeInsight.hint;

import com.intellij.codeInsight.daemon.impl.ParameterHintsPresentationManager;
import com.intellij.codeInsight.hints.ParameterHintsPassFactory;
import com.intellij.codeInsight.lookup.Lookup;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.ide.IdeTooltip;
import com.intellij.injected.editor.EditorWindow;
import com.intellij.lang.parameterInfo.ParameterInfoHandler;
import com.intellij.lang.parameterInfo.ParameterInfoHandlerWithTabActionSupport;
import com.intellij.lang.parameterInfo.ParameterInfoUtils;
import com.intellij.lang.parameterInfo.UpdateParameterInfoContext;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.event.CaretEvent;
import com.intellij.openapi.editor.event.CaretListener;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.event.DocumentListener;
import com.intellij.openapi.editor.impl.EditorImpl;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.Balloon.Position;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiUtilBase;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.ui.HintHint;
import com.intellij.ui.LightweightHint;
import com.intellij.util.Alarm;
import com.intellij.util.containers.JBIterable;
import com.intellij.util.messages.MessageBusConnection;
import com.intellij.util.text.CharArrayUtil;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;

import javax.swing.*;
import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.LockSupport;

public class ParameterInfoController implements Disposable {
  private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.hint.ParameterInfoController");
  private final Project myProject;
  @NotNull private final Editor myEditor;

  private final RangeMarker myLbraceMarker;
  private final LightweightHint myHint;
  private final ParameterInfoComponent myComponent;
  private final boolean myKeepOnHintHidden;

  private final CaretListener myEditorCaretListener;
  @NotNull private final ParameterInfoHandler<Object, Object> myHandler;
  private final MyBestLocationPointProvider myProvider;

  private final Alarm myAlarm = new Alarm();
  private static final int DELAY = 200;

  private boolean myDisposed;

  /**
   * Keeps Vector of ParameterInfoController's in Editor
   */
  private static final Key<List<ParameterInfoController>> ALL_CONTROLLERS_KEY = Key.create("ParameterInfoController.ALL_CONTROLLERS_KEY");

  public static ParameterInfoController findControllerAtOffset(Editor editor, int offset) {
    List<ParameterInfoController> allControllers = getAllControllers(editor);
    for (int i = 0; i < allControllers.size(); ++i) {
      ParameterInfoController controller = allControllers.get(i);

      if (controller.myLbraceMarker.getStartOffset() == offset) {
        if (controller.myKeepOnHintHidden || controller.myHint.isVisible()) return controller;
        Disposer.dispose(controller);
        --i;
      }
    }

    return null;
  }

  private static List<ParameterInfoController> getAllControllers(@NotNull Editor editor) {
    List<ParameterInfoController> array = editor.getUserData(ALL_CONTROLLERS_KEY);
    if (array == null){
      array = new ArrayList<>();
      editor.putUserData(ALL_CONTROLLERS_KEY, array);
    }
    return array;
  }

  public static boolean existsForEditor(@NotNull Editor editor) {
    return !getAllControllers(editor).isEmpty();
  }

  public static boolean isAlreadyShown(Editor editor, int lbraceOffset) {
    ParameterInfoController controller = findControllerAtOffset(editor, lbraceOffset);
    return controller != null && controller.myHint.isVisible();
  }

  public ParameterInfoController(@NotNull Project project,
                                 @NotNull Editor editor,
                                 int lbraceOffset,
                                 Object[] descriptors,
                                 Object highlighted,
                                 PsiElement parameterOwner,
                                 @NotNull ParameterInfoHandler handler,
                                 boolean showHint,
                                 boolean requestFocus) {
    myProject = project;
    myEditor = editor;
    myHandler = handler;
    myProvider = new MyBestLocationPointProvider(editor);
    myLbraceMarker = editor.getDocument().createRangeMarker(lbraceOffset, lbraceOffset);
    myComponent = new ParameterInfoComponent(descriptors, editor, handler, requestFocus);
    myHint = new LightweightHint(myComponent);
    myKeepOnHintHidden = !showHint;

    myHint.setSelectingHint(true);
    myComponent.setParameterOwner(parameterOwner);
    myComponent.setHighlightedParameter(highlighted);

    List<ParameterInfoController> allControllers = getAllControllers(myEditor);
    allControllers.add(this);

    myEditorCaretListener = new CaretListener(){
      @Override
      public void caretPositionChanged(CaretEvent e) {
        myAlarm.cancelAllRequests();
        addAlarmRequest();
      }
    };
    myEditor.getCaretModel().addCaretListener(myEditorCaretListener);

    myEditor.getDocument().addDocumentListener(new DocumentListener() {
      @Override
      public void documentChanged(DocumentEvent e) {
        myAlarm.cancelAllRequests();
        addAlarmRequest();
      }
    }, this);

    MessageBusConnection connection = project.getMessageBus().connect(this);
    connection.subscribe(ExternalParameterInfoChangesProvider.TOPIC, (e, offset) -> {
      if (e != myEditor || myLbraceMarker.getStartOffset() != offset) return;
      myAlarm.cancelAllRequests();
      addAlarmRequest();
    });

    PropertyChangeListener lookupListener = new PropertyChangeListener() {
      @Override
      public void propertyChange(PropertyChangeEvent evt) {
        if (LookupManager.PROP_ACTIVE_LOOKUP.equals(evt.getPropertyName())) {
          Lookup lookup = (Lookup)evt.getNewValue();
          if (lookup != null) {
            adjustPositionForLookup(lookup);
          }
        }
      }
    };
    LookupManager.getInstance(project).addPropertyChangeListener(lookupListener, this);
    if (myEditor instanceof EditorImpl) {
      Disposer.register(((EditorImpl)myEditor).getDisposable(), this);
    }

    myComponent.update(); // to have correct preferred size
    if (showHint) {
      showHint(requestFocus);
    }
    updateComponent();
  }

  @Override
  public void dispose(){
    if (myDisposed) return;
    myDisposed = true;
    myHint.hide();
    List<ParameterInfoController> allControllers = getAllControllers(myEditor);
    allControllers.remove(this);
    myEditor.getCaretModel().removeCaretListener(myEditorCaretListener);
  }

  public void showHint(boolean requestFocus) {
    Pair<Point, Short> pos = myProvider.getBestPointPosition(myHint, myComponent.getParameterOwner(), myLbraceMarker.getStartOffset(), true, HintManager.UNDER);
    HintHint hintHint = HintManagerImpl.createHintHint(myEditor, pos.getFirst(), myHint, pos.getSecond());
    hintHint.setExplicitClose(true);
    hintHint.setRequestFocus(requestFocus);

    Editor editorToShow = myEditor instanceof EditorWindow ? ((EditorWindow)myEditor).getDelegate() : myEditor;
    // is case of injection we need to calculate position for EditorWindow
    // also we need to show the hint in the main editor because of intention bulb
    HintManagerImpl.getInstanceImpl().showEditorHint(myHint, editorToShow, pos.getFirst(), HintManager.HIDE_BY_ESCAPE | HintManager.UPDATE_BY_SCROLLING, 0, false, hintHint);

    updateComponent();
  }

  private void adjustPositionForLookup(@NotNull Lookup lookup) {
    if (myEditor.isDisposed()) {
      Disposer.dispose(this);
      return;
    }

    if (!myHint.isVisible()) {
      if (!myKeepOnHintHidden) Disposer.dispose(this);
      return;
    }

    IdeTooltip tooltip = myHint.getCurrentIdeTooltip();
    if (tooltip != null) {
      JRootPane root = myEditor.getComponent().getRootPane();
      if (root != null) {
        Point p = tooltip.getShowingPoint().getPoint(root.getLayeredPane());
        if (lookup.isPositionedAboveCaret()) {
          if (Position.above == tooltip.getPreferredPosition()) {
            myHint.pack();
            myHint.updatePosition(Position.below);
            myHint.updateLocation(p.x, p.y + tooltip.getPositionChangeY());
          }
        }
        else {
          if (Position.below == tooltip.getPreferredPosition()) {
            myHint.pack();
            myHint.updatePosition(Position.above);
            myHint.updateLocation(p.x, p.y - tooltip.getPositionChangeY());
          }
        }
      }
    }
  }

  private void addAlarmRequest(){
    Runnable request = () -> {
      if (!myDisposed && !myProject.isDisposed()) {
        PsiDocumentManager.getInstance(myProject).performLaterWhenAllCommitted(() -> {
          try {
            DumbService.getInstance(myProject).withAlternativeResolveEnabled(this::updateComponent);
          }
          catch (IndexNotReadyException e) {
            LOG.info(e);
            Disposer.dispose(this);
          }
        });
      }
    };
    myAlarm.addRequest(request, DELAY, ModalityState.stateForComponent(myEditor.getComponent()));
  }

  public void updateComponent(){
    if (myKeepOnHintHidden) {
      boolean removeHints = true;
      PsiElement owner = myComponent.getParameterOwner();
      if (owner != null && owner.isValid()) {
        int caretOffset = myEditor.getCaretModel().getOffset();
        TextRange ownerTextRange = owner.getTextRange();
        if (ownerTextRange != null) {
          if (caretOffset > ownerTextRange.getStartOffset() && caretOffset < ownerTextRange.getEndOffset()) {
            removeHints = false;
          }
          else {
            for (PsiElement element : owner.getChildren()) {
              if (element instanceof PsiErrorElement) {
                removeHints = false;
                break;
              }
            }
          }
        }
      }
      if (removeHints) {
        ParameterHintsPassFactory.forceHintsUpdateOnNextPass(myEditor);
        Disposer.dispose(this);
        return;
      }
    }

    if (!myHint.isVisible() && !myKeepOnHintHidden && !ApplicationManager.getApplication().isUnitTestMode()) {
      Disposer.dispose(this);
      return;
    }

    final PsiFile file =  PsiUtilBase.getPsiFileInEditor(myEditor, myProject);
    CharSequence chars = myEditor.getDocument().getCharsSequence();
    boolean noDelimiter = myHandler instanceof ParameterInfoHandlerWithTabActionSupport &&
                          ((ParameterInfoHandlerWithTabActionSupport)myHandler).getActualParameterDelimiterType() == TokenType.WHITE_SPACE;
    int caretOffset = myEditor.getCaretModel().getOffset();
    final int offset = noDelimiter ? caretOffset :
                       CharArrayUtil.shiftBackward(chars, caretOffset - 1, " \t") + 1;

    final UpdateParameterInfoContext context = new MyUpdateParameterInfoContext(offset, file);
    final Object elementForUpdating = myHandler.findElementForUpdatingParameterInfo(context);

    if (elementForUpdating != null) {
      myHandler.updateParameterInfo(elementForUpdating, context);
      if (!myDisposed && myHint.isVisible() && !myEditor.isDisposed() &&
          myEditor.getComponent().getRootPane() != null) {
        myComponent.update();
        IdeTooltip tooltip = myHint.getCurrentIdeTooltip();
        short position = tooltip != null
                         ? toShort(tooltip.getPreferredPosition())
                         : HintManager.UNDER;
        Pair<Point, Short> pos = myProvider.getBestPointPosition(
          myHint, elementForUpdating instanceof PsiElement ? (PsiElement)elementForUpdating : null,
          caretOffset, true, position);
        HintManagerImpl.adjustEditorHintPosition(myHint, myEditor, pos.getFirst(), pos.getSecond());
      }
    }
    else {
      context.removeHint();
    }
  }

  @HintManager.PositionFlags
  private static short toShort(Position position) {
    switch (position) {
      case above:
        return HintManager.ABOVE;
      case atLeft:
        return HintManager.LEFT;
      case atRight:
        return HintManager.RIGHT;
      default:
        return HintManager.UNDER;
    }
  }

  public static boolean hasPrevOrNextParameter(Editor editor, int lbraceOffset, boolean isNext) {
    ParameterInfoController controller = findControllerAtOffset(editor, lbraceOffset);
    return controller != null && controller.getPrevOrNextParameterOffset(isNext) != -1;
  }

  public static void prevOrNextParameter(Editor editor, int lbraceOffset, boolean isNext) {
    ParameterInfoController controller = findControllerAtOffset(editor, lbraceOffset);
    int newOffset = controller != null ? controller.getPrevOrNextParameterOffset(isNext) : -1;
    if (newOffset != -1) {
      controller.moveToParameterAtOffset(newOffset);
    }
  }

  private void moveToParameterAtOffset(int offset) {
    PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument());
    PsiElement argsList = findArgumentList(file, offset, -1);
    if (argsList == null && !Registry.is("java.completion.argument.hints")) return;

    offset = adjustOffsetToInlay(offset);

    myEditor.getCaretModel().moveToLogicalPosition(myEditor.offsetToLogicalPosition(offset).leanForward(true));
    myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
    myEditor.getSelectionModel().removeSelection();
    if (argsList != null) {
      myHandler.updateParameterInfo(argsList, new MyUpdateParameterInfoContext(offset, file));
    }
  }

  private int adjustOffsetToInlay(int offset) {
    CharSequence text = myEditor.getDocument().getImmutableCharSequence();
    String whitespaceChars = " \t";
    int whitespaceStart = CharArrayUtil.shiftBackward(text, offset, whitespaceChars) + 1;
    int whitespaceEnd = CharArrayUtil.shiftForward(text, offset, whitespaceChars);
    List<Inlay> inlays = myEditor.getInlayModel().getInlineElementsInRange(whitespaceStart, whitespaceEnd);
    for (Inlay inlay : inlays) {
      if (ParameterHintsPresentationManager.getInstance().isParameterHint(inlay)) return inlay.getOffset();
    }
    return offset;
  }

  private int getPrevOrNextParameterOffset(boolean isNext) {
    if (!(myHandler instanceof ParameterInfoHandlerWithTabActionSupport)) return -1;
    ParameterInfoHandlerWithTabActionSupport handler = (ParameterInfoHandlerWithTabActionSupport)myHandler;

    boolean noDelimiter = handler.getActualParameterDelimiterType() == TokenType.WHITE_SPACE;
    int caretOffset = myEditor.getCaretModel().getOffset();
    int offset = noDelimiter ? caretOffset : CharArrayUtil.shiftBackward(myEditor.getDocument().getCharsSequence(), caretOffset - 1, " \t") + 1;
    int lbraceOffset = myLbraceMarker.getStartOffset();
    PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument());
    PsiElement argList = lbraceOffset < offset ? findArgumentList(file, offset, lbraceOffset) : null;
    if (argList == null) return -1;

    @SuppressWarnings("unchecked") PsiElement[] parameters = handler.getActualParameters(argList);
    int currentParameterIndex =
      noDelimiter ? JBIterable.of(parameters).indexOf((o) -> o.getTextRange().containsOffset(offset)) :
      ParameterInfoUtils.getCurrentParameterIndex(argList.getNode(), offset, handler.getActualParameterDelimiterType());
    if (Registry.is("java.completion.argument.hints")) {
      if (currentParameterIndex < 0 || currentParameterIndex >= parameters.length) return -1;
      int prevOrNextParameterIndex = currentParameterIndex + (isNext ? 1 : -1);
      if (prevOrNextParameterIndex < 0 || prevOrNextParameterIndex >= parameters.length) {
        PsiElement parameterOwner = myComponent.getParameterOwner();
        return (parameterOwner != null && parameterOwner.isValid()) ? parameterOwner.getTextRange().getEndOffset() : -1;
      }
      else {
        return parameters[prevOrNextParameterIndex].getTextRange().getStartOffset();
      }
    }
    else {
      int prevOrNextParameterIndex = isNext && currentParameterIndex < parameters.length - 1 ? currentParameterIndex + 1 :
                                     !isNext && currentParameterIndex > 0 ? currentParameterIndex - 1 : -1;
      return prevOrNextParameterIndex != -1 ? parameters[prevOrNextParameterIndex].getTextRange().getStartOffset() : -1;
    }
  }

  @Nullable
  public static <E extends PsiElement> E findArgumentList(PsiFile file, int offset, int lbraceOffset){
    if (file == null) return null;
    ParameterInfoHandler[] handlers = ShowParameterInfoHandler.getHandlers(file.getProject(), PsiUtilCore.getLanguageAtOffset(file, offset), file.getViewProvider().getBaseLanguage());

    if (handlers != null) {
      for(ParameterInfoHandler handler:handlers) {
        if (handler instanceof ParameterInfoHandlerWithTabActionSupport) {
          final ParameterInfoHandlerWithTabActionSupport parameterInfoHandler2 = (ParameterInfoHandlerWithTabActionSupport)handler;

          // please don't remove typecast in the following line; it's required to compile the code under old JDK 6 versions
          final E e = (E) ParameterInfoUtils.findArgumentList(file, offset, lbraceOffset, parameterInfoHandler2);
          if (e != null) return e;
        }
      }
    }

    return null;
  }

  public Object[] getObjects() {
    return myComponent.getObjects();
  }

  public Object getHighlighted() {
    return myComponent.getHighlighted();
  }

  @TestOnly
  public static void waitForDelayedActions(@NotNull Editor editor, long timeout, @NotNull TimeUnit unit) throws TimeoutException {
    long deadline = System.currentTimeMillis() + unit.toMillis(timeout);
    while (System.currentTimeMillis() < deadline) {
      List<ParameterInfoController> controllers = getAllControllers(editor);
      boolean hasPendingRequests = false;
      for (ParameterInfoController controller : controllers) {
        if (!controller.myAlarm.isEmpty()) {
          hasPendingRequests = true;
          break;
        }
      }
      if (hasPendingRequests) {
        LockSupport.parkNanos(10_000_000);
        UIUtil.dispatchAllInvocationEvents();
      }
      else return;

    }
    throw new TimeoutException();
  }

  /**
   * Returned Point is in layered pane coordinate system.
   * Second value is a {@link com.intellij.codeInsight.hint.HintManager.PositionFlags position flag}.
   */
  static Pair<Point, Short> chooseBestHintPosition(Project project,
                                                   Editor editor,
                                                   LogicalPosition pos,
                                                   LightweightHint hint,
                                                   boolean awtTooltip, short preferredPosition) {
    if (ApplicationManager.getApplication().isUnitTestMode()) return Pair.pair(new Point(), HintManager.DEFAULT);

    HintManagerImpl hintManager = HintManagerImpl.getInstanceImpl();
    Dimension hintSize = hint.getComponent().getPreferredSize();
    JComponent editorComponent = editor.getComponent();
    JLayeredPane layeredPane = editorComponent.getRootPane().getLayeredPane();

    Point p1;
    Point p2;
    boolean isLookupShown = LookupManager.getInstance(project).getActiveLookup() != null;
    if (isLookupShown) {
      p1 = hintManager.getHintPosition(hint, editor, HintManager.UNDER);
      p2 = hintManager.getHintPosition(hint, editor, HintManager.ABOVE);
    }
    else {
      p1 = HintManagerImpl.getHintPosition(hint, editor, pos, HintManager.UNDER);
      p2 = HintManagerImpl.getHintPosition(hint, editor, pos, HintManager.ABOVE);
    }

    if (!awtTooltip) {
      p1.x = Math.min(p1.x, layeredPane.getWidth() - hintSize.width);
      p1.x = Math.max(p1.x, 0);
      p2.x = Math.min(p2.x, layeredPane.getWidth() - hintSize.width);
      p2.x = Math.max(p2.x, 0);
    }

    boolean p1Ok = p1.y + hintSize.height < layeredPane.getHeight();
    boolean p2Ok = p2.y >= 0;

    if (isLookupShown) {
      if (p1Ok) return new Pair<>(p1, HintManager.UNDER);
      if (p2Ok) return new Pair<>(p2, HintManager.ABOVE);
    }
    else {
      if (preferredPosition != HintManager.DEFAULT) {
        if (preferredPosition == HintManager.ABOVE) {
          if (p2Ok) return new Pair<>(p2, HintManager.ABOVE);
        } else if (preferredPosition == HintManager.UNDER) {
          if (p1Ok) return new Pair<>(p1, HintManager.UNDER);
        }
      }

      if (p1Ok) return new Pair<>(p1, HintManager.UNDER);
      if (p2Ok) return new Pair<>(p2, HintManager.ABOVE);
    }

    int underSpace = layeredPane.getHeight() - p1.y;
    int aboveSpace = p2.y;
    return aboveSpace > underSpace ? new Pair<>(new Point(p2.x, 0), HintManager.UNDER) : new Pair<>(p1,
                                                                                HintManager.ABOVE);
  }

  public class MyUpdateParameterInfoContext implements UpdateParameterInfoContext {
    private final int myOffset;
    private final PsiFile myFile;

    public MyUpdateParameterInfoContext(final int offset, final PsiFile file) {
      myOffset = offset;
      myFile = file;
    }

    @Override
    public int getParameterListStart() {
      return myLbraceMarker.getStartOffset();
    }

    @Override
    public int getOffset() {
      return myOffset;
    }

    @Override
    public Project getProject() {
      return myProject;
    }

    @Override
    public PsiFile getFile() {
      return myFile;
    }

    @Override
    @NotNull
    public Editor getEditor() {
      return myEditor;
    }

    @Override
    public void removeHint() {
      myHint.hide();
      Disposer.dispose(ParameterInfoController.this);
    }

    @Override
    public void setParameterOwner(final PsiElement o) {
      myComponent.setParameterOwner(o);
    }

    @Override
    public PsiElement getParameterOwner() {
      return myComponent.getParameterOwner();
    }

    @Override
    public void setHighlightedParameter(final Object method) {
      myComponent.setHighlightedParameter(method);
    }

    @Override
    public Object getHighlightedParameter() {
      return myComponent.getHighlighted();
    }

    @Override
    public void setCurrentParameter(final int index) {
      myComponent.setCurrentParameterIndex(index);
    }

    @Override
    public boolean isUIComponentEnabled(int index) {
      return myComponent.isEnabled(index);
    }

    @Override
    public void setUIComponentEnabled(int index, boolean enabled) {
      myComponent.setEnabled(index, enabled);
    }

    @Override
    public Object[] getObjectsToView() {
      return myComponent.getObjects();
    }

  }

  private static class MyBestLocationPointProvider  {
    private final Editor myEditor;
    private int previousOffset = -1;
    private Point previousBestPoint;
    private Short previousBestPosition;

    public MyBestLocationPointProvider(final Editor editor) {
      myEditor = editor;
    }

    @NotNull
    public Pair<Point, Short> getBestPointPosition(LightweightHint hint,
                                                   final PsiElement list,
                                                   int offset,
                                                   final boolean awtTooltip,
                                                   short preferredPosition) {
      if (list != null) {
        TextRange range = list.getTextRange();
        if (!range.contains(offset)) {
          offset = range.getStartOffset() + 1;
        }
      }
      if (previousOffset == offset) return Pair.create(previousBestPoint, previousBestPosition);

      final boolean isMultiline = list != null && StringUtil.containsAnyChar(list.getText(), "\n\r");
      final LogicalPosition pos = myEditor.offsetToLogicalPosition(offset).leanForward(true);
      Pair<Point, Short> position;

      if (!isMultiline) {
        position = chooseBestHintPosition(myEditor.getProject(), myEditor, pos, hint, awtTooltip, preferredPosition);
      }
      else {
        Point p = HintManagerImpl.getHintPosition(hint, myEditor, pos, HintManager.ABOVE);
        position = new Pair<>(p, HintManager.ABOVE);
      }
      previousBestPoint = position.getFirst();
      previousBestPosition = position.getSecond();
      previousOffset = offset;
      return position;
    }
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--

-->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:orientation="vertical">

    <fragment
        android:id="@+id/fragment_search_departure"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:name="com.markupartist.sthlmtraveling.SearchDeparturesFragment"
        />

</LinearLayout>


text:
package com.consol.citrus.selenium.actions;

import com.consol.citrus.exceptions.CitrusRuntimeException;
import com.consol.citrus.selenium.endpoint.SeleniumBrowser;
import com.consol.citrus.testng.AbstractTestNGUnitTest;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.openqa.selenium.*;
import org.testng.Assert;
import org.testng.annotations.*;

import java.util.Collections;

import static org.mockito.Mockito.*;

/**
 * @author Christoph Deppisch
 * @since 2.7
 */
public class FindElementActionTest extends AbstractTestNGUnitTest {

    private SeleniumBrowser seleniumBrowser = new SeleniumBrowser();
    private WebDriver webDriver = Mockito.mock(WebDriver.class);
    private WebElement element = Mockito.mock(WebElement.class);

    private FindElementAction action;

    @BeforeMethod
    public void setup() {
        reset(webDriver, element);

        seleniumBrowser.setWebDriver(webDriver);

        action =  new FindElementAction();
        action.setBrowser(seleniumBrowser);

        when(element.isDisplayed()).thenReturn(true);
        when(element.isEnabled()).thenReturn(true);
        when(element.getTagName()).thenReturn("button");
    }

    @Test(dataProvider = "findByProvider")
    public void testExecuteFindBy(String property, String value, final By by) throws Exception {
        when(webDriver.findElement(any(By.class))).thenAnswer(new Answer<WebElement>() {
            @Override
            public WebElement answer(InvocationOnMock invocation) throws Throwable {
                By select = (By) invocation.getArguments()[0];

                Assert.assertEquals(select.getClass(), by.getClass());
                Assert.assertEquals(select.toString(), by.toString());
                return element;
            }
        });

        action.setProperty(property);
        action.setPropertyValue(value);

        action.execute(context);

        Assert.assertEquals(context.getVariableObject("button"), element);
    }

    @DataProvider
    public Object[][] findByProvider() {
        return new Object[][] {
            new Object[] { "id", "myId", By.id("myId") },
            new Object[] { "name", "myName", By.name("myName") },
            new Object[] { "tag-name", "button", By.tagName("button") },
            new Object[] { "class-name", "myClass", By.className("myClass") },
            new Object[] { "link-text", "myLinkText", By.linkText("myLinkText") },
            new Object[] { "css-selector", "myCss", By.cssSelector("myCss") },
            new Object[] { "xpath", "myXpath", By.xpath("myXpath") }
        };
    }

    @Test
    public void testExecuteFindByVariableSupport() throws Exception {
        when(webDriver.findElement(any(By.class))).thenAnswer(new Answer<WebElement>() {
            @Override
            public WebElement answer(InvocationOnMock invocation) throws Throwable {
                By select = (By) invocation.getArguments()[0];

                Assert.assertEquals(select.getClass(), By.ById.class);
                Assert.assertEquals(select.toString(), By.id("clickMe").toString());
                return element;
            }
        });

        context.setVariable("myId", "clickMe");

        action.setProperty("id");
        action.setPropertyValue("${myId}");

        action.execute(context);

        Assert.assertEquals(context.getVariableObject("button"), element);
    }

    @Test
    public void testExecuteFindByValidation() throws Exception {
        when(element.getText()).thenReturn("Click Me!");
        when(element.getAttribute("type")).thenReturn("submit");
        when(element.getCssValue("color")).thenReturn("red");

        when(webDriver.findElement(any(By.class))).thenAnswer(new Answer<WebElement>() {
            @Override
            public WebElement answer(InvocationOnMock invocation) throws Throwable {
                By select = (By) invocation.getArguments()[0];

                Assert.assertEquals(select.getClass(), By.ByName.class);
                Assert.assertEquals(select.toString(), By.name("clickMe").toString());
                return element;
            }
        });

        action.setTagName("button");
        action.setText("Click Me!");
        action.setAttributes(Collections.singletonMap("type", "submit"));
        action.setStyles(Collections.singletonMap("color", "red"));

        action.setProperty("name");
        action.setPropertyValue("clickMe");

        action.execute(context);

        Assert.assertEquals(context.getVariableObject("button"), element);
    }

    @Test(dataProvider = "validationErrorProvider")
    public void testExecuteFindByValidationFailed(String tagName, String text, String attribute, String cssStyle, boolean displayed, boolean enabled, String errorMsg) throws Exception {
        when(element.getTagName()).thenReturn("button");
        when(element.getText()).thenReturn("Click Me!");
        when(element.getAttribute("type")).thenReturn("submit");
        when(element.getCssValue("color")).thenReturn("red");

        when(webDriver.findElement(any(By.class))).thenAnswer(new Answer<WebElement>() {
            @Override
            public WebElement answer(InvocationOnMock invocation) throws Throwable {
                By select = (By) invocation.getArguments()[0];

                Assert.assertEquals(select.getClass(), By.ByName.class);
                Assert.assertEquals(select.toString(), By.name("clickMe").toString());
                return element;
            }
        });

        action.setTagName(tagName);
        action.setText(text);
        action.setAttributes(Collections.singletonMap("type", attribute));
        action.setStyles(Collections.singletonMap("color", cssStyle));
        action.setDisplayed(displayed);
        action.setEnabled(enabled);

        action.setProperty("name");
        action.setPropertyValue("clickMe");

        try {
            action.execute(context);
            Assert.fail("Missing exception to to validation error");
        } catch (Exception e) {
            Assert.assertTrue(e.getMessage().endsWith(errorMsg), e.getMessage());
        }
    }

    @DataProvider
    public Object[][] validationErrorProvider() {
        return new Object[][] {
                new Object[] { "input", "Click Me!", "submit", "red", true, true, "tag-name expected 'input', but was 'button'" },
                new Object[] { "button", "Click!", "submit", "red", true, true, "text expected 'Click!', but was 'Click Me!'" },
                new Object[] { "button", "Click Me!", "cancel", "red", true, true, "attribute 'type' expected 'cancel', but was 'submit'" },
                new Object[] { "button", "Click Me!", "submit", "red", false, true, "'displayed' expected 'false', but was 'true'" },
                new Object[] { "button", "Click Me!", "submit", "red", true, false, "'enabled' expected 'false', but was 'true'" },
                new Object[] { "button", "Click Me!", "submit", "blue", true, true, "css style 'color' expected 'blue', but was 'red'" }
        };
    }

    @Test(expectedExceptions = CitrusRuntimeException.class, expectedExceptionsMessageRegExp = "Failed to find element 'id=myButton' on page")
    public void testElementNotFound() {
        when(webDriver.findElement(any(By.class))).thenReturn(null);

        action.setProperty("id");
        action.setPropertyValue("myButton");

        action.execute(context);
    }

    @Test(expectedExceptions = CitrusRuntimeException.class, expectedExceptionsMessageRegExp = "Unknown selector type: unsupported")
    public void testElementUnsupportedProperty() {
        action.setProperty("unsupported");
        action.setPropertyValue("wrong");

        action.execute(context);
    }

}


text:
/**
**  @file tcGameStream.cpp
*/
/*
**  Copyright (c) 2014, GCBLUE PROJECT
**  All rights reserved.
**
**  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
**
**  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
**
**  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
**     documentation and/or other materials provided with the distribution.
**
**  3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from
**     this software without specific prior written permission.
**
**  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
**  NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
**  COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
**  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
**  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
**  IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "common/tcGameStream.h"
#include <iostream>
#include <fstream>
#include <sstream>

int tcGameStream::GetVersionId() const
{
    return versionId;
}

void tcGameStream::LoadFromFile(const char* fileName)
{
    tcStream::LoadFromFile(fileName);

    operator>>(versionId);
}

void tcGameStream::SaveToFile(const char* fileName)
{
    std::ofstream file;

    file.open(fileName, std::ios::binary);

    if (!eof())
    {
        file.write((char*)&versionId, sizeof(versionId));
    }

    while (!eof())
    {
        char byte;
        operator>>(byte);

        file.write(&byte, 1);
    }

    file.close();
}

void tcGameStream::SetVersionId(int id)
{
    versionId = id;
}

/**
*
*/
tcGameStream::tcGameStream(const char* data, std::streamsize count)
: tcStream(data, count),
  versionId(0)
{
}

/**
* copy constructor
*/
tcGameStream::tcGameStream(const tcGameStream& stream)
: tcStream(stream),
  versionId(stream.versionId)
{

}

/**
*
*/
tcGameStream::tcGameStream()
: versionId(0)
{
}


text:
namespace Microsoft.Azure.Management.Network.Models
{
    using Microsoft.Rest;
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// Parameters to get network configuration diagnostic.
    /// </summary>
    public partial class NetworkConfigurationDiagnosticParameters
    {
        /// <summary>
        /// Initializes a new instance of the
        /// NetworkConfigurationDiagnosticParameters class.
        /// </summary>
        public NetworkConfigurationDiagnosticParameters()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the
        /// NetworkConfigurationDiagnosticParameters class.
        /// </summary>
        /// <param name="targetResourceId">The ID of the target resource to
        /// perform network configuration diagnostic. Valid options are VM,
        /// NetworkInterface, VMSS/NetworkInterface and Application
        /// Gateway.</param>
        /// <param name="profiles">List of network configuration diagnostic
        /// profiles.</param>
        /// <param name="verbosityLevel">Verbosity level. Possible values
        /// include: 'Normal', 'Minimum', 'Full'</param>
        public NetworkConfigurationDiagnosticParameters(string targetResourceId, IList<NetworkConfigurationDiagnosticProfile> profiles, string verbosityLevel = default(string))
        {
            TargetResourceId = targetResourceId;
            VerbosityLevel = verbosityLevel;
            Profiles = profiles;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets the ID of the target resource to perform network
        /// configuration diagnostic. Valid options are VM, NetworkInterface,
        /// VMSS/NetworkInterface and Application Gateway.
        /// </summary>
        [JsonProperty(PropertyName = "targetResourceId")]
        public string TargetResourceId { get; set; }

        /// <summary>
        /// Gets or sets verbosity level. Possible values include: 'Normal',
        /// 'Minimum', 'Full'
        /// </summary>
        [JsonProperty(PropertyName = "verbosityLevel")]
        public string VerbosityLevel { get; set; }

        /// <summary>
        /// Gets or sets list of network configuration diagnostic profiles.
        /// </summary>
        [JsonProperty(PropertyName = "profiles")]
        public IList<NetworkConfigurationDiagnosticProfile> Profiles { get; set; }

        /// <summary>
        /// Validate the object.
        /// </summary>
        /// <exception cref="ValidationException">
        /// Thrown if validation fails
        /// </exception>
        public virtual void Validate()
        {
            if (TargetResourceId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "TargetResourceId");
            }
            if (Profiles == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "Profiles");
            }
            if (Profiles != null)
            {
                foreach (var element in Profiles)
                {
                    if (element != null)
                    {
                        element.Validate();
                    }
                }
            }
        }
    }
}


text:
package org.nschmidt.ldparteditor.data;

import java.util.Set;

import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.graphics.Point;
import org.nschmidt.ldparteditor.composite.compositetab.CompositeTab;
import org.nschmidt.ldparteditor.helper.composite3d.RectifierSettings;
import org.nschmidt.ldparteditor.helper.compositetext.Text2SelectionConverter;
import org.nschmidt.ldparteditor.helper.math.HashBiMap;
import org.nschmidt.ldparteditor.project.Project;
import org.nschmidt.ldparteditor.shell.editortext.EditorTextWindow;

/**
 * Splits selected quads into triangles
 */
public enum QuadMerger {
    INSTANCE;

    public static void mergeTrianglesIntoQuad(int lineStart, int lineEnd, DatFile datFile) {

        if (datFile.isReadOnly())
            return;

        final VertexManager vm = datFile.getVertexManager();
        vm.backupHideShowState();
        vm.backupSelection();
        vm.clearSelection();

        Text2SelectionConverter.convert(lineStart, lineEnd, datFile);

        final Set<GData> sd = datFile.getVertexManager().getSelectedData();
        HashBiMap<Integer, GData> dpl = datFile.getDrawPerLineNoClone();

        lineEnd += 1;
        for (int line = lineStart; line < lineEnd; line++) {
            sd.add(dpl.getValue(line));
        }

        RectifierSettings rs = new RectifierSettings();
        rs.setScope(1);
        rs.setNoBorderedQuadToRectConversation(true);
        vm.rectify(rs, false, false);

        vm.restoreSelection();
        vm.restoreHideShowState();
        vm.setModifiedNoSync();
        for (EditorTextWindow w : Project.getOpenTextWindows()) {
            for (CTabItem t : w.getTabFolder().getItems()) {
                if (datFile.equals(((CompositeTab) t).getState().getFileNameObj())) {
                    ((CompositeTab) t).getState().setSync(true);
                    Point s = ((CompositeTab) t).getTextComposite().getSelection();
                    ((CompositeTab) t).getTextComposite().setText(datFile.getText());
                    ((CompositeTab) t).getTextComposite().setSelection(s);
                    ((CompositeTab) t).getState().setSync(false);
                    ((CompositeTab) t).parseForErrorAndHints();
                    ((CompositeTab) t).getTextComposite().redraw();
                    break;
                }
            }
        }
        vm.skipSyncTimer();
        vm.setModified(true, true);
    }
}