text:
package com.intellij.ide;

import com.intellij.Patches;
import com.intellij.ide.dnd.DnDManager;
import com.intellij.ide.dnd.DnDManagerImpl;
import com.intellij.ide.ui.UISettings;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.impl.ApplicationImpl;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.keymap.impl.IdeKeyEventDispatcher;
import com.intellij.openapi.keymap.impl.IdeMouseEventDispatcher;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.openapi.wm.ex.WindowManagerEx;
import com.intellij.util.Alarm;
import com.intellij.util.ReflectionUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.HashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @author Vladimir Kondratyev
 * @author Anton Katilin
 */

public class IdeEventQueue extends EventQueue {
  private static final Logger LOG = Logger.getInstance("#com.intellij.ide.IdeEventQueue");

  /**
   * Adding/Removing of "idle" listeners should be thread safe.
   */
  private final Object myLock = new Object();

  private final ArrayList<Runnable> myIdleListeners = new ArrayList<Runnable>(2);

  private final ArrayList<Runnable> myActivityListeners = new ArrayList<Runnable>(2);

  private final Alarm myIdleRequestsAlarm = new Alarm();

  private final Alarm myIdleTimeCounterAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD);

  private long myIdleTime;

  private final Map<Runnable, MyFireIdleRequest> myListener2Request = new HashMap<Runnable, MyFireIdleRequest>();
  // IdleListener -> MyFireIdleRequest

  private final IdeKeyEventDispatcher myKeyEventDispatcher = new IdeKeyEventDispatcher(this);

  private final IdeMouseEventDispatcher myMouseEventDispatcher = new IdeMouseEventDispatcher();

  private final IdePopupManager myPopupManager = new IdePopupManager();

  private final ToolkitBugsProcessor myToolkitBugsProcessor = new ToolkitBugsProcessor();

  private boolean mySuspendMode;

  /**
   * We exit from suspend mode when focus owner changes and no more WindowEvent.WINDOW_OPENED events
   *

   * in the queue. If WINDOW_OPENED event does exists in the queus then we restart the alarm.
   */

  private Component myFocusOwner;

  private final Runnable myExitSuspendModeRunnable = new ExitSuspendModeRunnable();

  /**
   * We exit from suspend mode when this alarm is triggered and no mode WindowEvent.WINDOW_OPENED
   *

   * events in the queue. If WINDOW_OPENED event does exist then we restart the alarm.
   */
  private final Alarm mySuspendModeAlarm = new Alarm();

  /**
   * Counter of processed events. It is used to assert that data context lives only inside single
   *

   * Swing event.
   */

  private int myEventCount;

  private boolean myIsInInputEvent = false;

  private AWTEvent myCurrentEvent = null;

  private long myLastActiveTime;

  private WindowManagerEx myWindowManager;

  private final Set<EventDispatcher> myDispatchers = new LinkedHashSet<EventDispatcher>();
  private final Set<EventDispatcher> myPostprocessors = new LinkedHashSet<EventDispatcher>();

  private final Set<Runnable> myReady = new HashSet<Runnable>();
  private boolean myKeyboardBusy;
  private boolean myDispatchingFocusEvent;

  private static class IdeEventQueueHolder {
    private static final IdeEventQueue INSTANCE = new IdeEventQueue();
  }

  public static IdeEventQueue getInstance() {
    return IdeEventQueueHolder.INSTANCE;
  }

  private IdeEventQueue() {
    addIdleTimeCounterRequest();
    final KeyboardFocusManager keyboardFocusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();

    //noinspection HardCodedStringLiteral
    keyboardFocusManager.addPropertyChangeListener("permanentFocusOwner", new PropertyChangeListener() {

      public void propertyChange(final PropertyChangeEvent e) {
        final Application application = ApplicationManager.getApplication();
        if (application == null) {

          // We can get focus event before application is initialized
          return;
        }
        application.assertIsDispatchThread();
        final Window focusedWindow = keyboardFocusManager.getFocusedWindow();
        final Component focusOwner = keyboardFocusManager.getFocusOwner();
        if (mySuspendMode && focusedWindow != null && focusOwner != null && focusOwner != myFocusOwner && !(focusOwner instanceof Window)) {
          exitSuspendMode();
        }
      }
    });

    addDispatcher(new WindowsAltSupressor(), null);
  }

  public void setWindowManager(final WindowManagerEx windowManager) {
    myWindowManager = windowManager;
  }

  private void addIdleTimeCounterRequest() {
    Application application = ApplicationManager.getApplication();
    if (application != null && application.isUnitTestMode()) return;

    myIdleTimeCounterAlarm.cancelAllRequests();
    myLastActiveTime = System.currentTimeMillis();
    myIdleTimeCounterAlarm.addRequest(new Runnable() {
      public void run() {
        myIdleTime += System.currentTimeMillis() - myLastActiveTime;
        addIdleTimeCounterRequest();
      }
    }, 20000, ModalityState.NON_MODAL);
  }

  public boolean shouldNotTypeInEditor() {
    return myKeyEventDispatcher.isWaitingForSecondKeyStroke() || mySuspendMode;
  }

  private void enterSuspendMode() {
    mySuspendMode = true;
    myFocusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
    mySuspendModeAlarm.cancelAllRequests();
    mySuspendModeAlarm.addRequest(myExitSuspendModeRunnable, 750);
  }

  /**
   * Exits supend mode and pumps all suspended events.
   */

  private void exitSuspendMode() {
    if (shallEnterSuspendMode()) {

      // We have to exit from suspend mode (focus owner changes or alarm is triggered) but

      // WINDOW_OPENED isn't dispatched yet. In this case we have to restart the alarm until

      // all WINDOW_OPENED event will be processed.
      mySuspendModeAlarm.cancelAllRequests();
      mySuspendModeAlarm.addRequest(myExitSuspendModeRunnable, 250);
    }
    else {

      // Now we can pump all suspended events.
      mySuspendMode = false;
      myFocusOwner = null; // to prevent memory leaks
    }
  }

  public void addIdleListener(@NotNull final Runnable runnable, final int timeout) {
    LOG.assertTrue(timeout > 0);
    synchronized (myLock) {
      myIdleListeners.add(runnable);
      final MyFireIdleRequest request = new MyFireIdleRequest(runnable, timeout);
      myListener2Request.put(runnable, request);
      myIdleRequestsAlarm.addRequest(request, timeout);
    }
  }

  public void removeIdleListener(@NotNull final Runnable runnable) {
    synchronized (myLock) {
      final boolean wasRemoved = myIdleListeners.remove(runnable);
      if (!wasRemoved) {
        LOG.error("unknown runnable: " + runnable);
      }
      final MyFireIdleRequest request = myListener2Request.remove(runnable);
      LOG.assertTrue(request != null);
      myIdleRequestsAlarm.cancelRequest(request);
    }
  }

  public void addActivityListener(@NotNull final Runnable runnable) {
    synchronized (myLock) {
      myActivityListeners.add(runnable);
    }
  }

  public void addActivityListener(@NotNull final Runnable runnable, Disposable parentDisposable) {
    synchronized (myLock) {
      ContainerUtil.add(runnable, myActivityListeners, parentDisposable);
    }
  }

  public void removeActivityListener(@NotNull final Runnable runnable) {
    synchronized (myLock) {
      myActivityListeners.remove(runnable);
    }
  }

  public void addDispatcher(final EventDispatcher dispatcher, Disposable parent) {
    _addProcessor(dispatcher, parent, myDispatchers);
  }

  public void removeDispatcher(EventDispatcher dispatcher) {
    myDispatchers.remove(dispatcher);
  }

  public boolean containsDispatcher(EventDispatcher dispatcher) {
    return myDispatchers.contains(dispatcher);
  }

  public void addPostprocessor(EventDispatcher dispatcher, Disposable parent) {
    _addProcessor(dispatcher, parent, myPostprocessors);
  }

  public void removePostprocessor(EventDispatcher dispatcher) {
    myPostprocessors.remove(dispatcher);
  }

  private void _addProcessor(final EventDispatcher dispatcher, Disposable parent, Set<EventDispatcher> set) {
    set.add(dispatcher);
    if (parent != null) {
      Disposer.register(parent, new Disposable() {
        public void dispose() {
          removeDispatcher(dispatcher);
        }
      });
    }
  }

  public int getEventCount() {
    return myEventCount;
  }

  public void setEventCount(int evCount) {
    myEventCount = evCount;
  }

  public AWTEvent getTrueCurrentEvent() {
    return myCurrentEvent;
  }

  //[jeka] commented for performance reasons

  /*

  public void postEvent(final AWTEvent e) {

    // [vova] sometime people call SwingUtilities.invokeLater(null). To

    // find such situations we will specially check InvokationEvents

    try {

      if (e instanceof InvocationEvent) {

        //noinspection HardCodedStringLiteral

        final Field field = InvocationEvent.class.getDeclaredField("runnable");

        field.setAccessible(true);

        final Object runnable = field.get(e);

        if (runnable == null) {

          //noinspection HardCodedStringLiteral

          throw new IllegalStateException("InvocationEvent contains null runnable: " + e);

        }

      }

    }

    catch (final Exception exc) {

      throw new Error(exc);

    }

    super.postEvent(e);

  }

  */

  public void dispatchEvent(final AWTEvent e) {
    boolean wasInputEvent = myIsInInputEvent;
    myIsInInputEvent = e instanceof InputEvent || e instanceof InputMethodEvent || e instanceof WindowEvent || e instanceof ActionEvent;
    AWTEvent oldEvent = myCurrentEvent;
    myCurrentEvent = e;

    try {
      _dispatchEvent(e);
    }
    finally {
      myIsInInputEvent = wasInputEvent;
      myCurrentEvent = oldEvent;

      for (EventDispatcher each : myPostprocessors) {
        each.dispatch(e);
      }

      if (e instanceof KeyEvent) {
        maybeReady();
      }
    }
  }

  @SuppressWarnings({"ALL"})
  private static String toDebugString(final AWTEvent e) {
    if (e instanceof InvocationEvent) {
      try {
        final Field f = InvocationEvent.class.getDeclaredField("runnable");
        f.setAccessible(true);
        Object runnable = f.get(e);

        return "Invoke Later[" + runnable.toString() + "]";
      }
      catch (NoSuchFieldException e1) {
      }
      catch (IllegalAccessException e1) {
      }
    }
    return e.toString();
  }

  private void _dispatchEvent(final AWTEvent e) {
    _dispatchEvent(e, false);
  }

  public void _dispatchEvent(AWTEvent e, boolean typeaheadFlushing) {
    if (e.getID() == MouseEvent.MOUSE_DRAGGED) {
      DnDManagerImpl dndManager = (DnDManagerImpl)DnDManager.getInstance();
      if (dndManager != null) {
        dndManager.setLastDropHandler(null);
      }
    }

    myEventCount++;

    if (processAppActivationEvents(e)) return;

    if (!typeaheadFlushing) {
      fixStickyFocusedComponents(e);
    }

    if (!myPopupManager.isPopupActive()) {
      enterSuspendModeIfNeeded(e);
    }

    if (e instanceof KeyEvent) {
      myKeyboardBusy = e.getID() != KeyEvent.KEY_RELEASED || ((KeyEvent)e).getModifiers() != 0;
    }

    if (!typeaheadFlushing && typeAheadDispatchToFocusManager(e)) return;

    if (e instanceof WindowEvent) {
      ActivityTracker.getInstance().inc();
    }

    // Process "idle" and "activity" listeners
    if (e instanceof KeyEvent || e instanceof MouseEvent) {
      ActivityTracker.getInstance().inc();

      synchronized (myLock) {
        myIdleRequestsAlarm.cancelAllRequests();
        for (Runnable idleListener : myIdleListeners) {
          final MyFireIdleRequest request = myListener2Request.get(idleListener);
          if (request == null) {
            LOG.error("There is no request for " + idleListener);
          }
          int timeout = request.getTimeout();
          myIdleRequestsAlarm.addRequest(request, timeout, ModalityState.NON_MODAL);
        }
        if (KeyEvent.KEY_PRESSED == e.getID() ||
            KeyEvent.KEY_TYPED == e.getID() ||
            MouseEvent.MOUSE_PRESSED == e.getID() ||
            MouseEvent.MOUSE_RELEASED == e.getID() ||
            MouseEvent.MOUSE_CLICKED == e.getID()) {
          addIdleTimeCounterRequest();
          for (Runnable activityListener : myActivityListeners) {
            activityListener.run();
          }
        }
      }
    }
    if (myPopupManager.isPopupActive() && myPopupManager.dispatch(e)) {
      return;
    }

    for (EventDispatcher eachDispatcher : myDispatchers) {
      if (eachDispatcher.dispatch(e)) {
        return;
      }
    }

    if (e instanceof InputMethodEvent) {
      if (SystemInfo.isMac && myKeyEventDispatcher.isWaitingForSecondKeyStroke()) {
        return;
      }
    }
    if (e instanceof InputEvent && Patches.SPECIAL_WINPUT_METHOD_PROCESSING) {
      final InputEvent inputEvent = (InputEvent)e;
      if (!inputEvent.getComponent().isShowing()) {
        return;
      }
    }
    if (e instanceof ComponentEvent && myWindowManager != null) {
      myWindowManager.dispatchComponentEvent((ComponentEvent)e);
    }
    if (e instanceof KeyEvent) {
      if (mySuspendMode || !myKeyEventDispatcher.dispatchKeyEvent((KeyEvent)e)) {
        defaultDispatchEvent(e);
      }
      else {
        ((KeyEvent)e).consume();
        defaultDispatchEvent(e);
      }
    }
    else if (e instanceof MouseEvent) {
      if (!myMouseEventDispatcher.dispatchMouseEvent((MouseEvent)e)) {
        defaultDispatchEvent(e);
      }
    }
    else {
      defaultDispatchEvent(e);
    }
  }

  private static void fixStickyWindow(KeyboardFocusManager mgr, Window wnd, String resetMethod) {
    Window showingWindow = wnd;

    if (wnd != null && !wnd.isShowing()) {
      while (showingWindow != null) {
        if (showingWindow.isShowing()) break;
        showingWindow = (Window)showingWindow.getParent();
      }

      if (showingWindow == null) {
        final Frame[] allFrames = Frame.getFrames();
        for (Frame each : allFrames) {
          if (each.isShowing()) {
            showingWindow = each;
            break;
          }
        }
      }

      if (showingWindow != null && showingWindow != wnd) {
        final Method setActive = ReflectionUtil.findMethod(KeyboardFocusManager.class.getDeclaredMethods(), resetMethod, Window.class);
        if (setActive != null) {
          try {
            setActive.setAccessible(true);
            setActive.invoke(mgr, (Window)showingWindow);
          }
          catch (Exception exc) {
            LOG.info(exc);
          }
        }
      }
    }
  }

  public void fixStickyFocusedComponents(@Nullable AWTEvent e) {
    if (e != null && !(e instanceof InputEvent)) return;

    final KeyboardFocusManager mgr = KeyboardFocusManager.getCurrentKeyboardFocusManager();

    if (Registry.is("actionSystem.fixStickyFocusedWindows")) {
      fixStickyWindow(mgr, mgr.getActiveWindow(), "setGlobalActiveWindow");
      fixStickyWindow(mgr, mgr.getFocusedWindow(), "setGlobalFocusedWindow");
    }

    if (Registry.is("actionSystem.fixNullFocusedComponent")) {
      final Component focusOwner = mgr.getFocusOwner();
      if (focusOwner == null) {

        IdeEventQueue queue = IdeEventQueue.getInstance();
        boolean mouseEventsAhead = e instanceof MouseEvent ||
                                   queue.peekEvent(MouseEvent.MOUSE_PRESSED) != null ||
                                   queue.peekEvent(MouseEvent.MOUSE_RELEASED) != null ||
                                   queue.peekEvent(MouseEvent.MOUSE_CLICKED) != null;

        if (!mouseEventsAhead) {
          Window showingWindow = mgr.getActiveWindow();
          if (showingWindow == null) {
            Method getNativeFocusOwner = ReflectionUtil.getDeclaredMethod(KeyboardFocusManager.class, "getNativeFocusOwner");
            if (getNativeFocusOwner != null) {
              getNativeFocusOwner.setAccessible(true);
              try {
                Object owner = getNativeFocusOwner.invoke(mgr);
                if (owner instanceof Component) {
                  Component nativeFocusOwner = (Component)owner;
                  if (nativeFocusOwner instanceof Window) {
                    showingWindow = (Window)nativeFocusOwner;
                  } else {
                    showingWindow = SwingUtilities.getWindowAncestor(nativeFocusOwner);
                  }
                }
              }
              catch (Exception e1) {
                LOG.debug(e1);
              }
            }
          }
          if (showingWindow != null) {
            final IdeFocusManager fm = IdeFocusManager.findInstanceByComponent(showingWindow);
            Runnable requestDefaultFocus = new Runnable() {
              public void run() {
                if (mgr.getFocusOwner() == null) {
                  if (getPopupManager().requestDefaultFocus(false)) return;

                  final Application app = ApplicationManager.getApplication();
                  if (app != null && app.isActive()) {
                    fm.requestDefaultFocus(false);
                  }
                }
              }
            };
            if (e != null) {
              fm.doWhenFocusSettlesDown(requestDefaultFocus);
            }
            else {
              requestDefaultFocus.run();
            }
          }
        }
      }
    }
  }

  private void enterSuspendModeIfNeeded(AWTEvent e) {
    if (e instanceof KeyEvent) {
      if (!mySuspendMode && shallEnterSuspendMode()) {
        enterSuspendMode();
      }
    }
  }

  private boolean shallEnterSuspendMode() {
    return peekEvent(WindowEvent.WINDOW_OPENED) != null;
  }

  private static boolean processAppActivationEvents(AWTEvent e) {
    final Application app = ApplicationManager.getApplication();
    if (!(app instanceof ApplicationImpl)) return false;

    ApplicationImpl appImpl = (ApplicationImpl)app;

    boolean consumed = false;
    if (e instanceof WindowEvent) {
      WindowEvent we = (WindowEvent)e;
      if (we.getID() == WindowEvent.WINDOW_GAINED_FOCUS && we.getWindow() != null) {
        if (we.getOppositeWindow() == null && !appImpl.isActive()) {
          consumed = appImpl.tryToApplyActivationState(true, we.getWindow());
        }
      }
      else if (we.getID() == WindowEvent.WINDOW_LOST_FOCUS && we.getWindow() != null) {
        if (we.getOppositeWindow() == null && appImpl.isActive()) {
          consumed = appImpl.tryToApplyActivationState(false, we.getWindow());
        }
      }
    }

    return false;
  }

  private void defaultDispatchEvent(final AWTEvent e) {
    try {
      myDispatchingFocusEvent = e instanceof FocusEvent;
      super.dispatchEvent(e);
    }
    catch (ProcessCanceledException pce) {
      throw pce;
    }
    catch (Throwable exc) {
      if (!myToolkitBugsProcessor.process(exc)) {
        LOG.error("Error during dispatching of " + e, exc);
      }
    } finally {
      myDispatchingFocusEvent = false;
    }
  }

  public boolean isDispatchingFocusEvent() {
    return myDispatchingFocusEvent;
  }

  private static boolean typeAheadDispatchToFocusManager(AWTEvent e) {
    if (e instanceof KeyEvent) {
      final KeyEvent event = (KeyEvent)e;
      if (!event.isConsumed()) {
        final IdeFocusManager focusManager = IdeFocusManager.findInstanceByComponent(event.getComponent());
        return focusManager.dispatch(event);
      }
    }

    return false;
  }

  public void flushQueue() {
    while (true) {
      AWTEvent event = peekEvent();
      if (event == null) return;
      try {
        AWTEvent event1 = getNextEvent();
        dispatchEvent(event1);
      }
      catch (Exception e) {
        LOG.error(e); //?
      }
    }
  }

  public void pumpEventsForHierarchy(Component modalComponent, Condition<AWTEvent> exitCondition) {
    AWTEvent event;
    do {
      try {
        event = getNextEvent();
        boolean eventOk = true;
        if (event instanceof InputEvent) {
          final Object s = event.getSource();
          if (s instanceof Component) {
            Component c = (Component)s;
            Window modalWindow = SwingUtilities.windowForComponent(modalComponent);
            while (c != null && c != modalWindow) c = c.getParent();
            if (c == null) {
              eventOk = false;
              ((InputEvent)event).consume();
            }
          }
        }

        if (eventOk) {
          dispatchEvent(event);
        }
      }
      catch (Throwable e) {
        LOG.error(e);
        event = null;
      }
    }
    while (!exitCondition.value(event));
  }

  public interface EventDispatcher {
    boolean dispatch(AWTEvent e);
  }

  private final class MyFireIdleRequest implements Runnable {
    private final Runnable myRunnable;
    private final int myTimeout;

    public MyFireIdleRequest(@NotNull Runnable runnable, final int timeout) {
      myTimeout = timeout;
      myRunnable = runnable;
    }

    public void run() {
      myRunnable.run();
      synchronized (myLock) {
        if (myIdleListeners.contains(myRunnable)) // do not reschedule if not interested anymore
        {
          myIdleRequestsAlarm.addRequest(this, myTimeout, ModalityState.NON_MODAL);
        }
      }
    }

    public int getTimeout() {
      return myTimeout;
    }
  }

  private final class ExitSuspendModeRunnable implements Runnable {

    public void run() {
      if (mySuspendMode) {
        exitSuspendMode();
      }
    }
  }

  public long getIdleTime() {
    return myIdleTime;
  }

  public IdePopupManager getPopupManager() {
    return myPopupManager;
  }

  public IdeKeyEventDispatcher getKeyEventDispatcher() {
    return myKeyEventDispatcher;
  }

  public void blockNextEvents(final MouseEvent e) {
    myMouseEventDispatcher.blockNextEvents(e);
  }

  public boolean isSuspendMode() {
    return mySuspendMode;
  }

  public boolean hasFocusEventsPending() {
    return peekEvent(FocusEvent.FOCUS_GAINED) != null || peekEvent(FocusEvent.FOCUS_LOST) != null;
  }

  public boolean isReady() {
    return !myKeyboardBusy && myKeyEventDispatcher.isReady();
  }

  public void maybeReady() {
    flushReady();
  }

  private void flushReady() {
    if (myReady.isEmpty() || !isReady()) return;

    Runnable[] ready = myReady.toArray(new Runnable[myReady.size()]);
    myReady.clear();

    for (Runnable each : ready) {
      each.run();
    }
  }

  public void doWhenReady(final Runnable runnable) {
    if (EventQueue.isDispatchThread()) {
      myReady.add(runnable);
      maybeReady();
    }
    else {
      SwingUtilities.invokeLater(new Runnable() {
        public void run() {
          myReady.add(runnable);
          maybeReady();
        }
      });
    }
  }

  public boolean isPopupActive() {
    return myPopupManager.isPopupActive();
  }

  private static class WindowsAltSupressor implements EventDispatcher {

    private boolean myPureAltWasPressed;
    private boolean myWaitingForAltRelease;
    private boolean myWaiterScheduled;

    private Robot myRobot;

    public boolean dispatch(AWTEvent e) {
      boolean dispatch = true;
      if (e instanceof KeyEvent) {
        KeyEvent ke = ((KeyEvent)e);
        boolean pureAlt = ke.getKeyCode() == KeyEvent.VK_ALT && (ke.getModifiers() | KeyEvent.ALT_MASK) == KeyEvent.ALT_MASK;
        if (!pureAlt) {
          myPureAltWasPressed = false;
          myWaitingForAltRelease = false;
          myWaiterScheduled = false;
        }
        else {
          Application app = ApplicationManager.getApplication();
          if (app == null ||
              !SystemInfo.isWindows ||
              !Registry.is("actionSystem.win.supressAlt") ||
              !UISettings.getInstance().HIDE_TOOL_STRIPES) {
            return !dispatch;
          }

          if (ke.getID() == KeyEvent.KEY_PRESSED) {
            myPureAltWasPressed = true;
            dispatch = !myWaitingForAltRelease;
          }
          else if (ke.getID() == KeyEvent.KEY_RELEASED) {
            if (myWaitingForAltRelease) {
              myPureAltWasPressed = false;
              myWaitingForAltRelease = false;
              myWaiterScheduled = false;
              dispatch = false;
            }
            else {
              myWaiterScheduled = true;
              SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                  try {
                    myWaitingForAltRelease = true;
                    if (myRobot == null) {
                      myRobot = new Robot();
                    }
                    myRobot.keyPress(KeyEvent.VK_ALT);
                    myRobot.keyRelease(KeyEvent.VK_ALT);
                  }
                  catch (AWTException e1) {
                    LOG.debug(e1);
                  }
                }
              });
            }
          }
        }
      }

      return !dispatch;
    }
  }
}


text:
require 'spec_helper'

module Adhearsion
  class CallController
    module MenuDSL
      describe CalculatedMatch do
        it "should make accessible the context name" do
          expect(CalculatedMatch.new(:match_payload => :foobar).match_payload).to be :foobar
        end

        it "should make accessible the original pattern" do
          expect(CalculatedMatch.new(:pattern => :something).pattern).to be :something
        end

        it "should make accessible the matched query" do
          expect(CalculatedMatch.new(:query => 123).query).to be 123
        end

        it "#type_of_match should return :exact, :potential, or nil" do
          expect(CalculatedMatch.new(:potential_matches => [1]).type_of_match).to be :potential
          expect(CalculatedMatch.new(:exact_matches => [3,3]).type_of_match).to be :exact
          expect(CalculatedMatch.new(:exact_matches => [8,3], :potential_matches => [0,9]).type_of_match).to be :exact
        end

        it "#exact_match? should return true if the match was exact" do
          expect(CalculatedMatch.new(:exact_matches => [0,3,5]).exact_match?).to be true
        end

        it "#potential_match? should return true if the match was exact" do
          expect(CalculatedMatch.new(:potential_matches => [88,99,77]).potential_match?).to be true
        end

        it "#failed_match? should return false if the match was exact" do
          expect(CalculatedMatch.new(:potential_matches => [88,99,77]).failed_match?).to be false
        end

        it "#exact_matches should return an array of exact matches" do
          expect(CalculatedMatch.new(:exact_matches => [0,3,5]).exact_matches).to eq([0,3,5])
        end

        it "#potential_matches should return an array of potential matches" do
          expect(CalculatedMatch.new(:potential_matches => [88,99,77]).potential_matches).to eq([88,99,77])
        end

        it "::failed_match! should return a match that *really* failed" do
          failure = CalculatedMatch.failed_match! 10..20, 30, :match_payload_does_not_matter
          expect(failure.exact_match?).not_to be true
          expect(failure.potential_match?).not_to be true
          expect(failure.failed_match?).to be true
          expect(failure.type_of_match).to be nil

          expect(failure.match_payload).to be :match_payload_does_not_matter
          expect(failure.pattern).to eq(10..20)
          expect(failure.query).to eq(30)
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Application\Sonata\UserBundle\Security;

use FOS\UserBundle\Model\UserInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use DateTime;
use FOS\UserBundle\Model\UserManagerInterface;

/**
 * Interactive login listener class.
 */
class InteractiveLoginListener
{
    /**
     * @var UserManagerInterface
     */
    protected $userManager;

    function __construct(UserManagerInterface $userManager)
    {
        $this->userManager = $userManager;
    }

    /**
     * On security interactive login listener action.
     *
     * @param \Symfony\Component\Security\Http\Event\InteractiveLoginEvent $event Event instance
     */
    public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
    {
        /** @var $user UserInterface */
        $user = $event->getAuthenticationToken()->getUser();
        if ($user instanceof UserInterface && $user->getId()) {
            // Don't save new social user:
            $user->setLastLogin(new DateTime());
            $this->userManager->updateUser($user, false);
        } else {
            $event->stopPropagation();
        }
    }
}


text:
<?php

namespace Oro\Bundle\SearchBundle\Tests\Unit\Engine\Orm;

use Doctrine\Common\Collections\Expr\Comparison;
use Doctrine\Common\Collections\Expr\Value;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\QueryBuilder;
use Oro\Bundle\SearchBundle\Engine\Orm\BaseDriver;
use Oro\Bundle\SearchBundle\Engine\Orm\OrmExpressionVisitor;
use Oro\Bundle\SearchBundle\Query\Criteria\Comparison as SearchComparison;
use Oro\Bundle\SearchBundle\Query\Criteria\Criteria;
use Oro\Bundle\SearchBundle\Query\Query;

class OrmExpressionVisitorTest extends \PHPUnit\Framework\TestCase
{
    /** @var BaseDriver|\PHPUnit\Framework\MockObject\MockObject */
    protected $driver;

    /** @var QueryBuilder|\PHPUnit\Framework\MockObject\MockObject */
    protected $qb;

    /** @var OrmExpressionVisitor */
    protected $visitor;

    protected function setUp()
    {
        $this->driver = $this->createMock(BaseDriver::class);
        $this->qb = $this->createMock(QueryBuilder::class);

        $this->visitor = new OrmExpressionVisitor($this->driver, $this->qb);
    }

    /**
     * @dataProvider filteringOperatorProvider
     *
     * @param string $operator
     * @param string $fieldName
     * @param string $expected
     */
    public function testWalkComparisonFilteringOperator($operator, $fieldName, $expected)
    {
        $index = 42;
        $type = Query::TYPE_INTEGER;

        $joinAliases = [];
        $joinField = 'search.integerFields';

        $field = strpos($fieldName, '|') !== false ? explode('|', $fieldName) : $fieldName;
        $joinAlias = str_replace('|', '_', sprintf('%sField%s_%s', $type, $fieldName, $index));

        $this->qb->expects($this->once())
            ->method('getAllAliases')
            ->willReturn($joinAliases);

        $this->driver->expects($this->once())
            ->method('getJoinAttributes')
            ->with($field, $type, $joinAliases)
            ->willReturn([$joinAlias, $index]);

        $this->driver->expects($this->once())
            ->method('getJoinField')
            ->willReturn($joinField);

        $this->qb->expects($this->once())
            ->method('leftJoin')
            ->with($joinField, $joinAlias, Join::WITH, sprintf($expected, $joinAlias, $index));

        $this->qb->expects($this->once())
            ->method('setParameter')
            ->with(sprintf('field%s', $index), $field);

        $expression = 'RETURN EXPRESSION';

        $this->driver->expects($this->once())
            ->method('addFilteringField')
            ->with(
                $index,
                [
                    'fieldName'  => $field,
                    'condition'  => Criteria::getSearchOperatorByComparisonOperator($operator),
                    'fieldValue' => null,
                    'fieldType'  => $type
                ]
            )
            ->willReturn($expression);

        $fieldName = sprintf('%s.%s', $type, $fieldName);

        $this->assertEquals(
            $expression,
            $this->visitor->walkComparison(new Comparison($fieldName, $operator, new Value(null)))
        );
    }

    /**
     * @return array
     */
    public function filteringOperatorProvider()
    {
        return [
            'EXISTS single parameter' => [
                'operator' => SearchComparison::EXISTS,
                'fieldName' => 'testData',
                'expected' => '%s.field = :field%s'
            ],
            'NOT EXISTS single parameter' => [
                'operator' => SearchComparison::NOT_EXISTS,
                'fieldName' => 'testData',
                'expected' => '%s.field = :field%s'
            ],
            'EXISTS multi parameter' => [
                'operator' => SearchComparison::EXISTS,
                'fieldName' => 'testData1|testData2',
                'expected' => '%s.field IN (:field%s)'
            ],
            'NOT EXISTS multi parameter' => [
                'operator' => SearchComparison::NOT_EXISTS,
                'fieldName' => 'testData1|testData2',
                'expected' => '%s.field IN (:field%s)'
            ],
        ];
    }
}


text:
var _ = require('underscore');

/**
 * Single error message.
 */

exports.error = function (text) {
	return {messages: [{ status: 'error', text: text }]};
}

/**
 * Single success message.
 */

exports.success = function (text) {
	return {messages: [{ status: 'ok', text: text }]};
}

/**
 * Mongoose error messages.
 */

exports.mongooseErrors = function(err, model) {
	var
		errors = err.errors || err,
		messages = [];

	var keys = Object.keys(errors)

	// if there is no validation error, just display a generic error
	if (!keys) {
		return {messages: [{ status: 'error', text: 'Database error.'}]};
	} else {
		keys.forEach(function (key) {
			messages.push({status: 'error', text: model +'.'+errors[key].message })
		});
		return {messages: messages};
	}
}

exports.errorsArray = function(array) {

	var messages = [];

	array.forEach(function (message) {
		messages.push({status: 'error', text: message });
	})

	return messages;
}

exports.errors = function (err) {

	var errors = err.errors || err;
	var json = {};

	json.messages = [];

	if (typeof(errors) == 'Array') {
		errors.forEach(function(error){
			json.messages.push({status: 'error', text: errors })
		})
	} else if (errors.name == 'MongoError') {
		json.messages.push({status: 'error', text: errors.err})
	} else {
		var keys = Object.keys(errors)

		// if there is no validation error, just display a generic error
		if (!keys) {
			return {messages: [{ status: 'error', text: 'Houve um erro.'}]}
		}

		keys.forEach(function (key) {
			json.messages.push({status: 'error', text: errors[key].err })
		})
	}

	return json;
}

/**
 * Helper function to check if a request body has Yby's API compliant messages.
 */

exports.hasValidMessages = function(body) {
	if (!body.messages) return false;
	if (body.messages.lenght == 0) return false;
	else {
		var invalidMessages = _.reject(body.messages, function(message){
			var statusIsValid = _.contains(['error', 'ok'], message.status);
			var textIsValid = (message.text && message.text.length > 0);
			return (statusIsValid && textIsValid);
		});
		return (invalidMessages.length == 0);
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

public partial class PackageInfo : System.Web.UI.Page
{
    string sdkRoot = "C:\\Inetpub\\wwwroot\\sdk\\";

    private string GetHtml(string file)
    {
        if (File.Exists(file))
        {
            StringBuilder retval = new StringBuilder();
            using (System.IO.FileStream s = System.IO.File.OpenRead(file))
            {
                using (System.IO.StreamReader reader = new System.IO.StreamReader(s))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        if (retval.Length > 0)
                            retval.Append("
");
                        retval.Append(line);
                    }
                    return retval.ToString();
                }
            }
        }
        return "No information available";
    }

    private string GetDescription(FileInfo file)
    {
        if (Regex.Match(file.Name, @"gdal-.*-core\.msi", RegexOptions.IgnoreCase).Success)
            return "Generic installer for the GDAL core components";

        if (Regex.Match(file.Name, @"MapManager.*\.msi", RegexOptions.IgnoreCase).Success)
            return "Installer for the MapServer MapManager application. The installer doesn't contain the ECW, Oracle, MrSID and FileGDB plugins, which should be installed by using the GDAL plugin msi installers.";

        if (Regex.Match(file.Name, @"gdal-.*-ecw\.msi", RegexOptions.IgnoreCase).Success)
            return "Installer for the GDAL ECW plugin (must be installed to the same directory as the GDAL core)";

        if (Regex.Match(file.Name, @"gdal-.*-oracle\.msi", RegexOptions.IgnoreCase).Success)
            return "Installer for the GDAL Oracle plugin (must be installed to the same directory as the GDAL core, make sure the proper version of oci.dll is available on your system)";

        if (Regex.Match(file.Name, @"gdal-.*-mrsid\.msi", RegexOptions.IgnoreCase).Success)
            return "Installer for the GDAL MrSID plugin (must be installed to the same directory as the GDAL core)";

        if (Regex.Match(file.Name, @"gdal-.*-filegdb\.msi", RegexOptions.IgnoreCase).Success)
            return "Installer for the OGR FileGDB plugin (must be installed to the same directory as the GDAL core)";

        if (Regex.Match(file.Name, @"GDAL-.*py.*\.(exe|msi)", RegexOptions.IgnoreCase).Success)
            return "Installer for the GDAL python bindings (requires to install the GDAL core)";

        if (Regex.Match(file.Name, @"MapScript-.*py.*\.(exe|msi)", RegexOptions.IgnoreCase).Success)
            return "Installer for the MapScript python bindings (Not yet working)";

        if (Regex.Match(file.Name, @"mapserver.*\.msi", RegexOptions.IgnoreCase).Success)
            return "MapServer installer with IIS registration support, including GDAL. The plugin installers can be used to install further drivers. When registering with IIS, the IIS6 management compatibility option should be installed in the IIS7+ web servers.";

        return "";
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        string fileIn = this.Request.QueryString["file"];
        if (fileIn == null)
            return;

        StringBuilder contents = new StringBuilder();

        string dirName = Path.GetFileNameWithoutExtension(fileIn);

        contents.AppendLine("
Available downloads (" + dirName + "):
");
        contents.AppendLine("
");
        contents.AppendLine("
File name	Date of compilation	Size	Description	");

        if (File.Exists(sdkRoot + "downloads\\" + fileIn))
        {
            FileInfo file = new FileInfo(sdkRoot + "downloads\\" + fileIn);
            contents.AppendLine("
" + file.Name + "	" + file.LastWriteTime.ToShortDateString() + " " + file.LastWriteTime.ToShortTimeString() + "	" + Math.Round((double)file.Length / 1024).ToString() + " kB	Compiled binaries in a single .zip package
");
        }

        if (File.Exists(sdkRoot + "downloads\\" + dirName + "-src.zip"))
        {
            FileInfo file = new FileInfo(sdkRoot + "downloads\\" + dirName + "-src.zip");
            contents.AppendLine("
" + file.Name + "	" + file.LastWriteTime.ToShortDateString() + " " + file.LastWriteTime.ToShortTimeString() + "	" + Math.Round((double)file.Length / 1024).ToString() + " kB	GDAL and MapServer sources
");
        }

        if (File.Exists(sdkRoot + "downloads\\" + dirName + "-libs.zip"))
        {
            FileInfo file = new FileInfo(sdkRoot + "downloads\\" + dirName + "-libs.zip");
            contents.AppendLine("
" + file.Name + "	" + file.LastWriteTime.ToShortDateString() + " " + file.LastWriteTime.ToShortTimeString() + "	" + Math.Round((double)file.Length / 1024).ToString() + " kB	Compiled libraries and headers
");
        }

        DirectoryInfo di = new DirectoryInfo(sdkRoot + "downloads\\" + dirName);
        if (di.Exists)
        {
            FileInfo[] files = di.GetFiles();

            foreach (FileInfo file in files)
            {
                contents.AppendLine("
" + file.Name + "	" + file.LastWriteTime.ToShortDateString() + " " + file.LastWriteTime.ToShortTimeString() + "	" + Math.Round((double)file.Length / 1024).ToString() + " kB	" + GetDescription(file) + "
");
            }
        }

        contents.AppendLine("
");
        if (di.Exists)
        {
            contents.AppendLine("
Note: In order to have the bindings work the location of the core components must be included manually in the PATH environment variable.
");
        }

        filelistDiv.InnerHtml = contents.ToString();

    }
}


text:
package org.axonframework.common;

import java.util.Collection;
import java.util.function.Supplier;

/**
 * Utility methods for operations on collections.
 *
 * @author Allard Buijze
 * @since 0.7
 */
public abstract class CollectionUtils {

    private CollectionUtils() {
        // prevent instantiation
    }

    /**
     * Merge two collections into a new collection instance. The new collection is created using the given {@code
     * factoryMethod}.
     * <p>
     * If any of the two inputs collections is {@code null} or empty the other input collection is returned (even if
     * that one is {@code null} as well).
     *
     * @param collection1 the first collection
     * @param collection2 the second collection
     * @param factoryMethod function to initialize the new collection
     * @param <S> the type of elements in the collections
     * @param <T> the type of collection
     * @return a collection that combines both collections
     */
    public static <S, T extends Collection<S>> T merge(T collection1, T collection2, Supplier<T> factoryMethod) {
        if (collection1 == null || collection1.isEmpty()) {
            return collection2;
        }
        if (collection2 == null || collection2.isEmpty()) {
            return collection1;
        }
        T combined = factoryMethod.get();
        combined.addAll(collection1);
        combined.addAll(collection2);
        return combined;
    }
}


text:
package swing.revival.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import swing.revival.enums.HorizontalKey;

/**
 *
 * @author Alistair A. Israel
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface RadioButton {

    /**
     * A specific name to use
     */
    String name() default "";

    /**
     * The button group this button should belong to
     */
    String buttonGroup() default "";

    /**
     * Used for
     * {@link javax.swing.AbstractButton#setHorizontalTextPosition(int)}
     */
    HorizontalKey horizontalTextPosition() default HorizontalKey.DEFAULT;
}


text:
from libraries.alchemy.alchemyapi import AlchemyAPI
import requests
import datetime
import pymongo
from pymongo import MongoClient
import pipeline

# --------------------------------------------------
# Connect with the remote Mongo and prepare NLP API.
# --------------------------------------------------
client = MongoClient('ds047571.mongolab.com:47571')
db = client.coinage
db.authenticate('bit', 'coin')
collection = db['articles']
api = AlchemyAPI()

# Call the pipeline to get the Feedly articles.
articles = pipeline.get_articles()

# Iterate through and score each article, storing the important metrics in MongoDB.
for article in articles:
	date = datetime.datetime.strptime(str(article[0]), '%a %Y-%m-%d %H:%M:%S')
	url = article[1]
	engagement = float(article[2])

	text = article[3]
	title = article[4]
	text_score = float(api.sentiment("text", text)['docSentiment']['score'])
	title_received = api.sentiment("text", title)
	title_score = 0.0

	if 'score' in title_received['docSentiment']:
		title_score = float(title_received['docSentiment']['score'])

	article_entry = {'date': date, 'url': url, 'engagement': engagement, 'title_score': title_score,'text_score': text_score}
	collection.save(article_entry)


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Text.RegularExpressions;

namespace PgpSharp.IO
{
    public static class IOUtility
    {
        /// <summary>
        /// Writes the <see cref="SecureString"/> char-by-char to the specified input.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <param name="secret">The secret.</param>
        public static void WriteSecret(this TextWriter input, SecureString secret)
        {
            if (input != null && secret != null && secret.Length > 0)
            {
                IntPtr ptr = Marshal.SecureStringToBSTR(secret);
                try
                {
                    int offset = 0;
                    short unichar = Marshal.ReadInt16(ptr, offset);
                    while (unichar != 0)
                    {
                        input.Write((char)unichar);
                        offset += 2;
                        unichar = Marshal.ReadInt16(ptr, offset);
                    }
                }
                finally
                {
                    Marshal.ZeroFreeBSTR(ptr);
                }
            }
        }

        /// <summary>
        /// Deletes the specified files.
        /// </summary>
        /// <param name="files"></param>
        public static void DeleteFiles(params string[] files)
        {
            if (files != null)
            {
                foreach (var f in files)
                {
                    if (File.Exists(f)) { File.Delete(f); }
                }
            }
        }

        /// <summary>
        /// Decodes the strings containing ASCII escapes like \x3a into : (colon).
        /// </summary>
        /// <param name="input">The input.</param>
        /// <returns></returns>
        public static string DecodeAsciiEscapes(this string input)
        {
            // modified from http://stackoverflow.com/questions/11584148/how-to-convert-a-string-containing-escape-characters-to-a-string

            var rx = new Regex(@"\\x([0-9A-Fa-f]{2})");
            MatchCollection matches;
            if (input != null && (matches = rx.Matches(input)).Count > 0) // only do the work if found!
            {
                var res = new StringBuilder();
                var pos = 0;
                foreach (Match m in matches)
                {
                    res.Append(input.Substring(pos, m.Index - pos));
                    pos = m.Index + m.Length;
                    res.Append((char)Convert.ToInt32(m.Groups[1].ToString(), 16));
                }
                res.Append(input.Substring(pos));
                return res.ToString();
            }
            return input;
        }
    }
}


text:
package de.cubeisland.engine.modularity.asm.info.module1;

import javax.inject.Inject;
import de.cubeisland.engine.modularity.asm.marker.ModuleInfo;
import de.cubeisland.engine.modularity.asm.marker.Version;
import de.cubeisland.engine.modularity.core.Maybe;
import de.cubeisland.engine.modularity.core.Module;
import de.cubeisland.engine.modularity.core.graph.meta.ModuleMetadata;

@ModuleInfo(name = "basic", description = "just testing")
public class BasicModule extends Module
{
    @Inject @Version(1) private Maybe<BasicService> anOptionalService;
}


text:
/**
 * 版本修订记录
 * 创建:2013-6-20
 * 版本:
 *
 * 修订1:  说明:
 * 修订2:  说明:
 *
 * 代码参考:
 * http://jbgtwang.iteye.com/blog/1499940
 */
package org.howsun.util.zip;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.howsun.log.Log;
import org.howsun.log.LogFactory;

/**
 * 描述:加密与解密工具
 * @author howsun
 * @version 3.0
 * Building Time 2013-6-20
 *
 */
public class Encrypts {

	private final static String ENCRYPTKEY="0123456789";

	public static final Log log = LogFactory.getLog(Encrypts.class);

	/**
	 *
	 * @Title: getEncryptKey
	 * @Description: 检验加密key
	 * @param encryptKey
	 * @return
	 * String
	 *
	 */
	private static String getEncryptKey(String encryptKey){
		if(null == encryptKey || "".equals(encryptKey)){
			return ENCRYPTKEY;
		}
		return encryptKey;
	}

	/**
	 *
	 * @Title: encrypt
	 * @Description: 加密:普通java字串加密成16进制字串(String -> Byte -> HexStr)
	 * @param content 要加密处理的字串
	 * @param encryptKey 加密密钥
	 * @return
	 * String
	 *
	 */
	public static String encrypt(String content, String encryptKey){
		byte[] encryptResult = encryptStrToByte(content, getEncryptKey(encryptKey));
		return parseByte2HexStr(encryptResult);
	}

	/**
	 *
	 * @Title: decrypt
	 * @Description: 加密:16进制字串解密成普通java字串(HexStr -> Byte ->String)
	 * @param content 要解密处理的16进制字串
	 * @param encryptKey 解密密钥
	 * @return
	 * String
	 *
	 */
	public static String decrypt(String content, String encryptKey){
		byte[] decryptFrom   = parseHexStr2Byte(content);
		byte[] decryptResult = decrypt(decryptFrom,getEncryptKey(encryptKey));
		return new String(decryptResult);
	}

	/**
	 * 加密:字串 --> 二进制
	 * @param content 需要加密的内容
	 * @param password 加密密码
	 * @return
	 */
	private static byte[] encryptStrToByte(String content, String password) {

		try {
			return encrypt(content.getBytes("utf-8"), password);
		}
		catch (UnsupportedEncodingException e) {
			log.info("UnsupportedEncodingException:", e);
		}

		return null;

		/*try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			kgen.init(128, new SecureRandom(password.getBytes()));
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES");// 创建密码器
			byte[] byteContent = content.getBytes("utf-8");
			cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
			byte[] result = cipher.doFinal(byteContent);
			return result; // 加密
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
		return null;*/
	}

	public static byte[] encrypt(byte[] contents, String password) {
		try {
			KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");

			/*
			 * SecureRandom实现完全隨操作系统本身的內部狀態,除非調用方在調用getInstance方法之後又調用了setSeed方法;
			 * 该实现在  windows上每次生成的key都相同,但是在 solaris或部分linux系统上则不同。
			 * kgen.init(128, new SecureRandom(password.getBytes()));
			 * SecretKey secretKey = kgen.generateKey();
			 */
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
	        secureRandom.setSeed(password.getBytes());
	        keyGenerator.init(128, secureRandom);
	        SecretKey secretKey = keyGenerator.generateKey();

			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES");//创建密码器
			cipher.init(Cipher.ENCRYPT_MODE, key);//初始化
			byte[] result = cipher.doFinal(contents);
			return result; // 加密

		} catch (NoSuchAlgorithmException e) {
			log.info("NoSuchAlgorithmException:", e);
		} catch (NoSuchPaddingException e) {
			log.info("NoSuchPaddingException:", e);
		} catch (InvalidKeyException e) {
			log.info("InvalidKeyException:", e);
		} catch (IllegalBlockSizeException e) {
			log.info("IllegalBlockSizeException:", e);
		} catch (BadPaddingException e) {
			log.info("BadPaddingException:", e);
		}
		return null;
	}

	/**解密
	 * @param content 待解密内容
	 * @param password 解密密钥
	 * @return
	 */
	public static byte[] decrypt(byte[] content, String password) {
		try {
			KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");

			/*
			 * SecureRandom实现完全隨操作系统本身的內部狀態,除非調用方在調用getInstance方法之後又調用了setSeed方法;
			 * 该实现在  windows上每次生成的key都相同,但是在 solaris或部分linux系统上则不同。
			 * kgen.init(128, new SecureRandom(password.getBytes()));
			 * SecretKey secretKey = kgen.generateKey();
			 */
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
	        secureRandom.setSeed(password.getBytes());
	        keyGenerator.init(128, secureRandom);
			SecretKey secretKey = keyGenerator.generateKey();

			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES");// 创建密码器
			cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
			byte[] result = cipher.doFinal(content);
			return result; // 加密

		} catch (NoSuchAlgorithmException e) {
			log.info("NoSuchAlgorithmException 错误:", e);
		} catch (NoSuchPaddingException e) {
			log.info("NoSuchPaddingException 错误:", e);
		} catch (InvalidKeyException e) {
			log.info("InvalidKeyException 错误:", e);
		} catch (IllegalBlockSizeException e) {
			log.info("IllegalBlockSizeException 错误:", e);
		} catch (BadPaddingException e) {
			throw new RuntimeException("密码错误");
			//log.info("BadPaddingException 错误:", e);
		}
		return null;
	}

	/**将二进制转换成16进制
	 * @param buf
	 * @return
	 */
	public static String parseByte2HexStr(byte buf[]) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < buf.length; i++) {
			String hex = Integer.toHexString(buf[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			sb.append(hex.toUpperCase());
		}
		return sb.toString();
	}

	/**
	 * 将16进制转换为二进制
	 *
	 * @param hexStr
	 * @return
	 */
	public static byte[] parseHexStr2Byte(String hexStr) {
		if (hexStr.length() < 1)
			return null;
		byte[] result = new byte[hexStr.length() / 2];
		for (int i = 0; i < hexStr.length() / 2; i++) {
			int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
			int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),
					16);
			result[i] = (byte) (high * 16 + low);
		}
		return result;
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ybproject.diarymemo"
    android:versionCode="151"
    android:versionName="1.5.1" >

 	<application
		android:icon="@drawable/ic_launcher"
		android:label="@string/app_name"
		android:description="@string/app_description">

		<provider android:name=".provider.DiaryMemoProvider" android:authorities="com.ybproject.diarymemo"/>
		<meta-data android:name="android.app.default_searchable" android:value=".DiaryMemoSearchResults" />

		<activity android:name=".DiaryMemoAppManager" android:label="@string/app_name" android:screenOrientation="portrait" android:theme="@android:style/Theme.Dialog">
		    <intent-filter>
				<action android:name="android.intent.action.MAIN" />
				<category android:name="android.intent.category.DEFAULT" />
			</intent-filter>
		</activity>

		////////
		<activity android:name=".Splash">
			<intent-filter>
				<action android:name="android.intent.action.MAIN"/>
				<category android:name="android.intent.category.LAUNCHER"/>
			</intent-filter>
		</activity>
		///////

		<activity android:name=".DiaryMemoList" android:configChanges="orientation" android:label="@string/app_name" android:screenOrientation="portrait">
			<intent-filter>
				<action android:name="android.intent.action.VIEW" />
				<action android:name="android.intent.action.EDIT" />
				<action android:name="android.intent.action.PICK" />
				<category android:name="android.intent.category.DEFAULT" />
				<data android:mimeType="vnd.android.cursor.dir/vnd.diarymemo.note" />
			</intent-filter>

			<intent-filter>
				<action android:name="android.intent.action.GET_CONTENT" />
				<category android:name="android.intent.category.DEFAULT" />
				<data android:mimeType="vnd.android.cursor.item/vnd.diarymemo.note" />
			</intent-filter>
		</activity>

		<activity android:name=".DiaryMemoSearchResults" android:launchMode="singleTop">
			<intent-filter>
				<action android:name="android.intent.action.SEARCH" />
			</intent-filter>
			<meta-data android:name="android.app.searchable" android:resource="@xml/searchable" />
		</activity>

		<activity android:name=".TitleEdit" android:configChanges="orientation" android:label="@string/menu_edit_title" android:theme="@android:style/Theme.Dialog"
			android:windowSoftInputMode="stateVisible|adjustResize">
			<intent-filter android:label="@string/menu_edit_title">
				<action android:name="com.android.diarymemo.action.EDIT_TITLE" />
				<category android:name="android.intent.category.DEFAULT" />
				<category android:name="android.intent.category.ALTERNATIVE" />
				<category android:name="android.intent.category.SELECTED_ALTERNATIVE" />
				<data android:mimeType="vnd.android.cursor.item/vnd.diarymemo.note" />
			</intent-filter>
		</activity>

		<activity android:name=".DiaryMemoEdit" android:configChanges="orientation"
			android:windowSoftInputMode="stateHidden|adjustPan">
			<intent-filter android:label="@string/menu_edit">
				<action android:name="android.intent.action.VIEW" />
				<action android:name="android.intent.action.EDIT" />
				<action android:name="android.intent.action.CREATE_SHORTCUT" />
				<action android:name="com.ybproject.diarymemo.action.EDIT_NOTE" />
				<category android:name="android.intent.category.DEFAULT" />
				<data android:mimeType="vnd.android.cursor.item/vnd.diarymemo.note" />
			</intent-filter>
			<intent-filter>
				<action android:name="android.intent.action.INSERT" />
				<category android:name="android.intent.category.DEFAULT" />
				<data android:mimeType="vnd.android.cursor.dir/vnd.diarymemo.note" />
			</intent-filter>
		</activity>

		<activity android:name=".Grid_mainActivity" android:configChanges="orientation" android:screenOrientation="portrait" android:windowSoftInputMode="stateHidden|adjustPan"/>
		<activity android:name=".DiaryMemoViewEdit" android:configChanges="orientation" android:windowSoftInputMode="stateHidden|adjustPan"/>
		<activity android:name=".DiaryMemoExport" android:launchMode="singleTop"></activity>
		<activity android:name=".DiaryMemoImport" android:launchMode="singleTop"></activity>
		<activity android:name=".desk.DiaryMemoInfo" android:configChanges="orientation" android:label="@string/about" />
		<activity android:name=".desk.DiaryMemoHelp" android:label="@string/menu_help" />
		<activity android:name=".desk.DiaryMemoBugreport" android:label="@string/pref_bugreport"/>
		<activity android:name=".desk.DiaryMemoHomepage" android:label="@string/homepage" />
		<activity android:name=".desk.DiaryMemoChanglog" android:label="ChangLog.." android:theme="@android:style/Theme.Dialog"/>
		<activity android:name=".widget.WidgetDetailActivty" android:configChanges="orientation" android:label="메모내용 바로보기" />
		<!-- 파싱 -->
		<activity android:name=".xml.RssReaderActivity"/>
		<activity android:name=".xml.ItemDetailActivity"/>

		<!-- 암호 -->
		<activity android:name=".passwordmanager.InsertPassword" android:configChanges="orientation"/>
		<activity android:name=".passwordmanager.EnablePassword" android:configChanges="orientation"/>
		<activity android:name=".passwordmanager.Password" android:configChanges="orientation" android:label="@string/app_name"/>
		<activity android:name=".passwordmanager.InsertResultPassword"  android:label="@string/app_name"/>
		<!-- 환경설정 -->
		<activity android:name=".Preferences_thema"/>
		<activity android:name=".Preferences_Password"/>
		<activity android:name=".Preferences"/>
		<!-- 낙서메모 -->
		<activity android:name=".DrawNoteInit"
			android:screenOrientation="portrait"
			android:theme="@android:style/Theme.NoTitleBar">
		</activity>
				<activity android:name=".DrawNoteBoard"
			android:screenOrientation="portrait"
			android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
			android:launchMode="singleTask"/>

		<activity android:name=".DrawNoteList"
			android:theme="@android:style/Theme.NoTitleBar"
			android:launchMode="singleTask">
		</activity>
		<activity android:name=".DrawNoteOptionDialog"
			android:theme="@android:style/Theme.Dialog"/>

		<activity
        	android:name=".DrawNotePenPaletteDialog"
        	android:theme="@android:style/Theme.Dialog"/>

        <activity android:name=".DrawNoteColorPickerDialog"
                  android:theme="@android:style/Theme.Dialog">
            <intent-filter>
                <action android:name="com.ybproject.diarymemo.action.PICK_COLOR" />
				<category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

        <activity
        	android:name=".DrawNoteSetting"
        	android:theme="@android:style/Theme.Black"
        	android:launchMode="singleTask"/>

		<!-- Widget 선언 -->
		<receiver
			android:name=".widget.Widget2x2" android:label="@string/widget_2x">
			<intent-filter>
				<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
			</intent-filter>
			<meta-data
			    android:name= "android.appwidget.provider"
			    android:resource="@xml/widget2x"/>
		</receiver>
		 <activity android:name=".widget.WidgetConfigActivty2x" android:label="@string/widget_config" android:theme="@android:style/Theme.Dialog">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
            </intent-filter>
        </activity>
      <receiver android:name=".AppUpdateReciever">
	      <intent-filter>
		      <action android:name="android.intent.action.PACKAGE_INSTALL" />
		      <action android:name="android.intent.action.PACKAGE_ADDED" />
		      <action android:name="android.intent.action.PACKAGE_REMOVED" />
		      <action android:name="android.intent.action.PACKAGE_REPLACED" />
		      <data android:scheme="package" />
	     </intent-filter>
		</receiver>

      <!-- 낙서메모 서비스 등록 -->
		<service android:name=".background.DrawNoteNotification"></service>
	</application>

	<supports-screens
		android:largeScreens="true"
		android:normalScreens="true"
		android:smallScreens="true"
		android:anyDensity="true"/>

	    <uses-sdk android:minSdkVersion="7" android:maxSdkVersion="22" />

	<uses-permission android:name="android.permission.INTERNET"/>
	<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
	<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
	<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
</manifest>


text:
$(document).ready(function () {

    var date = new Date();
    var d = date.getDate();
    var m = date.getMonth();
    var y = date.getFullYear();

    $('#calendar').fullCalendar({

        monthNames: ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'],
        monthNamesShort: ['janv.', 'févr.', 'mars', 'avr.', 'mai', 'juin', 'juil.', 'août', 'sept.', 'oct.', 'nov.', 'déc.'],
        dayNames: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'],
        dayNamesShort: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'],
        titleFormat: {
            month: 'MMMM yyyy',
            week: "d[ MMMM][ yyyy]{ - d MMMM yyyy}",
            day: 'dddd d MMMM yyyy'
        },
        columnFormat: {
            month: 'ddd',
            week: 'ddd d',
            day: ''
        },
        axisFormat: 'H:mm',
        timeFormat: {
            '': 'H:mm',
            agenda: 'H:mm{ - H:mm}'
        },
        firstDay: 1,
        buttonText: {
            today: 'aujourd\'hui',
            day: 'jour',
            week: 'semaine',
            month: 'mois'
        },
        header: {
            left: 'title',
            center: 'today prev next',
            right: 'month,agendaWeek,agendaDay'
        },
        editable: true,
        events: [
			{
			    title: 'All Day Event',
			    start: new Date(y, m, 1),
			    contenu_top: 'Jeudi 11 avril 2013 - de 10h à 17h
à Colmar',
			    contenu: 'La délégation AFNOR grand Est organise un atelier, en partenariat avec la CCI de Région Alsace, sur les démarches Qualité ...',
			    lien_exporter: 'http://www.google.fr',
			    lien_details: 'http://www.apple.fr'
			},
			{
			    title: 'Long Event',
			    start: new Date(y, m, d - 5),
			    end: new Date(y, m, d - 2),
			    contenu_top: 'Vendredi 11 avril 2013 - de 10h à 17h
à Colmar',
			    contenu: 'La délégation AFNOR',
			    lien_exporter: 'http://www.google.fr',
			    lien_details: 'http://www.apple.fr'
			},
			{
			    id: 999,
			    title: 'Repeating Event',
			    start: new Date(y, m, d - 3, 16, 0),
			    allDay: false,
			    contenu_top: 'Lundi 11 avril 2013 - de 10h à 17h
à Colmar',
			    contenu: 'En partenariat avec la CCI de Région Alsace, sur les démarches Qualité ...',
			    lien_exporter: 'http://www.google.fr',
			    lien_details: 'http://www.apple.fr'
			},
			{
			    id: 999,
			    title: 'Repeating Event',
			    start: new Date(y, m, d + 4, 16, 0),
			    allDay: false,
			    contenu_top: 'Mardi 11 avril 2013 - de 10h à 17h
à Colmar',
			    contenu: 'Lorem ipsum',
			    lien_exporter: 'http://www.google.fr',
			    lien_details: 'http://www.apple.fr'
			},
			{
			    title: 'Meeting',
			    start: new Date(y, m, d, 10, 30),
			    allDay: false,
			    contenu_top: 'Mercredi 11 avril 2013 - de 10h à 17h
à Colmar',
			    contenu: 'En sur les démarches Qualité ...',
			    lien_exporter: 'http://www.google.fr',
			    lien_details: 'http://www.apple.fr'
			},
			{
			    title: 'Lunch',
			    start: new Date(y, m, d, 12, 0),
			    end: new Date(y, m, d, 14, 0),
			    allDay: false,
			    contenu_top: 'Jeudi 11 avril 2013 - de 10h à 17h
à Colmar',
			    contenu: 'En partenariat avec la CCI de Région Alsace, sur les démarches Qualité ...',
			    lien_exporter: 'http://www.google.fr',
			    lien_details: 'http://www.apple.fr'
			},
			{
			    title: 'Birthday Party',
			    start: new Date(y, m, d + 1, 19, 0),
			    end: new Date(y, m, d + 1, 22, 30),
			    allDay: false,
			    contenu_top: 'Samedi 11 avril 2013 - de 10h à 17h
à Colmar',
			    contenu: 'En partenariat avec la CCI de Région Alsace, sur les démarches Qualité ...',
			    lien_exporter: 'http://www.google.fr',
			    lien_details: 'http://www.apple.fr'
			},
			{
			    title: 'Click for Google',
			    start: new Date(y, m, 28),
			    end: new Date(y, m, 29),
			    contenu_top: 'Dimanche 11 avril 2013 - de 10h à 17h
à Colmar',
			    contenu: 'En partenariat avec la CCI de Région Alsace, sur les démarches Qualité ...',
			    lien_exporter: 'http://www.google.fr',
			    lien_details: 'http://www.apple.fr'
			}
        ],
        eventClick: function (calEvent, jsEvent) {

            contenu = '

' + calEvent.contenu_top + '

' + calEvent.contenu + '

Exporter cet événementVoir détail

';

            $("#cal-content").remove();

            // MOIS
            if ($("#mois").hasClass("active")) {
                //création de la tooltip
                position = $(this).offset();
                $("#wrapper > .content").append(contenu);
                $("#cal-content").removeClass("gauche");

                /* position de la tooltip */
                if (position.left < 500) {
                    //on positionne à droite
                    positionX = position.left + $(this).outerWidth(true) - 313;
                    $("#cal-content").addClass("gauche");
                } else {
                    //on positionne à gauche
                    positionX = position.left - 666;
                }
                positionY = position.top - 343;

                //affichage tooltip
                $("#cal-content").css("top", positionY + "px").css("left", positionX + "px").fadeIn("fast");
            }

            // SEMAINE
            if ($("#semaine").hasClass("active")) {
                position = $(this).position();
                //alert("semaine - position top : "+position.top);
                //console.log("parent "+$(this).parent().parent().parent());
                $(this).parent().parent().append(contenu);
                $("#cal-content").removeClass("gauche");

                /* position de la tooltip */
                if (position.left < 300) {
                    //on positionne à droite
                    positionX = position.left + $(this).outerWidth(true) + 0;
                    //alert("position left:"+positionX);
                    $("#cal-content").addClass("gauche");
                } else {
                    //on positionne à gauche
                    positionX = position.left - 350;
                    if (positionX < 0)
                        positionX = 0;
                }

                if (position.top <= 22) {
                    //all day
                    positionY = position.top - 24;
                } else {
                    positionY = position.top;
                }

                //affichage tooltip
                $("#cal-content").css("top", positionY + "px").css("left", positionX + "px").fadeIn("fast");
            }

            // JOUR
            if ($("#jour").hasClass("active")) {
                position = $(this).position();
                //alert("jour - position top : "+position.top+"- position left : "+position.left);
                $(this).parent().parent().append(contenu);
                $("#cal-content").removeClass("gauche");

                if (position.left <= 54)
                    positionX = position.left + 100;
                else if (position.left > 300)
                    positionX = position.left - 360;
                else
                    positionX = position.left

                if (position.top <= 22) {
                    //all day
                    positionY = position.top - 24;
                } else {
                    positionY = position.top;
                }
                //affichage tooltip
                $("#cal-content").css("top", positionY + "px").css("left", positionX + "px").fadeIn("fast");
            }

            $("#cal-content .croix").click(function () {
                $("#cal-content").remove();
            });
        }
    });

    $("a.onglet").click(function () {
        if (!$(this).hasClass("active")) {
            $("a.onglet.active").removeClass("active");

            if ($(this).attr("id") == "mois") {
                $('#calendar').show();
                $(".fc-button-month").trigger("click");
                $('#events').hide();
            }

            if ($(this).attr("id") == "liste") {
                $('#calendar').hide();
                $('#events').show();
            }

            $(this).addClass("active");
        }
        return false;
    });

    $(".fc-text-arrow").text("");
    //$(".fc-content th").wrapInner('');
});


text:
import en_US from './en_US';
import zh from './zh';
import getI18nModel from './getModel';
import translate from './translate';

export const messages = {
  zh,
  en_US,
};

export {
  getI18nModel,
  translate,
};


text:
using System;
using System.Collections;
using System.Collections.Generic;

namespace BIS.Library
{
    /// <summary>
    /// The Algorithm object is used to perform the calculating tasks.
    /// </summary>
    public class Algorithm
    {
        public static byte[] ArraySection(byte[] data, int index, int count)
        {
            byte[] section = new byte[count];
            Array.Copy(data, index, section, 0, count);
            return section;
        }
        /// <summary>
        /// Compares two arrays
        /// </summary>
        /// <param name="bytes">The Array</param>
        /// <param name="data">The Array</param>
        /// <returns></returns>
        public static bool ArrayEqual(byte[] bytes, byte[] data)
        {
            if (bytes.Length == data.Length)
            {
                return ArrayEqual(bytes, data, bytes.Length);
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// Compares two arrays
        /// </summary>
        /// <param name="a">The Array</param>
        /// <param name="b">The Array</param>
        /// <param name="count">The count.</param>
        /// <returns></returns>
        public static bool ArrayEqual(byte[] a, byte[] b, int count)
        {
            for (int i = 0; i < count; i++)
            {
                if (a[i] != b[i])
                {
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// Sets the indice on an array
        /// </summary>
        /// <param name="length">The length.</param>
        /// <returns></returns>
        public static int[] ArrayIndice(int length)
        {
            int[] indice = new int[length];
            for (int i = 0; i < length; i++)
            {
                indice[i] = i;
            }
            return indice;
        }
        /// <summary>
        /// Looks for the maximum length of the ArrayList
        /// </summary>
        /// <param name="list">list of lists</param>
        /// <returns>the maximum length</returns>
        public static int Maximum(List<ICollection> list)
        {
            int max = 0;
            foreach (ICollection sublist in list)
            {
                if (max < sublist.Count)
                {
                    max = sublist.Count;
                }
            }
            return max;
        }
        /// <summary>
        /// Sums the specified list.
        /// </summary>
        /// <param name="list">The list.</param>
        /// <returns></returns>
        public static int Sum(IList<int> list)
        {
            int sum = 0;
            foreach (int n in list)
            {
                sum += n;
            }
            return sum;
        }

        /// <summary>
        /// Copies the array.
        /// </summary>
        /// <param name="src">The SRC.</param>
        /// <param name="dest">The dest.</param>
        /// <param name="start">The start.</param>
        public static void CopyArray(byte[] src, byte[] dest, int start)
        {
            int j = 0;
            for (int i = start; i < start + dest.Length; i++)
            {
                dest[j++] = src[i];
            }
        }

        /// <summary>
        /// Maximums the specified list.
        /// </summary>
        /// <param name="list">The list.</param>
        /// <returns></returns>
        public static int Maximum(IEnumerable<int> list)
        {
            int max = int.MinValue;
            foreach (int num in list)
            {
                if (max < num)
                {
                    max = num;
                }
            }
            return max;
        }

        /// <summary>
        /// Minimums the specified list.
        /// </summary>
        /// <param name="list">The list.</param>
        /// <returns></returns>
        public static int Minimum(IEnumerable<int> list)
        {
            int min = int.MaxValue;
            foreach (int num in list)
            {
                if (min > num)
                {
                    min = num;
                }
            }
            return min;
        }

        /// <summary>
        /// Minimums the specified list.
        /// </summary>
        /// <param name="list">The list.</param>
        /// <returns></returns>
        public static uint Minimum(IEnumerable<uint> list)
        {
            uint min = uint.MaxValue;
            foreach (uint num in list)
            {
                if (min > num)
                {
                    min = num;
                }
            }
            return min;
        }

        /// <summary>
        /// Return the postion of the maximum in the list.
        /// </summary>
        /// <param name="list">The list.</param>
        /// <returns></returns>
        public static int PosofMaximum(IList<int> list)
        {
            int index = 0;
            int max = list[0];
            for (int i = 1; i < list.Count; i++)
            {
                if (list[i] > max)
                {
                    max = list[i];
                    index = i;
                }
            }
            return index;
        }

        /// <summary>
        /// Return the postion of the Minimum in the list.
        /// </summary>
        /// <param name="list">The list.</param>
        /// <returns></returns>
        public static int PosofMinimum(IList<int> list)
        {
            int index = 0;
            int min = list[0];
            for (int i = 1; i < list.Count; i++)
            {
                if (list[i] < min)
                {
                    min = list[i];
                    index = i;
                }
            }
            return index;
        }

        /// <summary>
        /// Return the postion of the Minimum in the list.
        /// </summary>
        /// <param name="list">The list.</param>
        /// <returns></returns>
        public static int PosofMinimum(int[] list)
        {
            int index = 0;
            int min = list[0];
            for (int i = 1; i < list.Length; i++)
            {
                if (list[i] < min)
                {
                    min = list[i];
                    index = i;
                }
            }
            return index;
        }

        /// <summary>
        /// Return the postion of the Maximum in the list.
        /// </summary>
        /// <param name="list">The list.</param>
        /// <returns></returns>
        public static List<int> PosofMaximums(IList<int> list)
        {
            int max = int.MinValue;
            List<int> maxIndice = new List<int>();
            for (int index = 0; index < list.Count; index++)
            {
                int num = list[index];
                if (num > max)
                {
                    max = num;
                    maxIndice.Clear();
                }
                if (num == max)
                {
                    maxIndice.Add(index);
                }
            }
            return maxIndice;
        }

        /// <summary>
        /// Return the postion of the Minimum in the list.
        /// </summary>
        /// <param name="list">The list.</param>
        /// <returns></returns>
        public static List<int> PosofMinimums(IList<int> list)
        {
            int min = int.MaxValue;
            List<int> minIndice = new List<int>();
            for (int index = 0; index < list.Count; index++)
            {
                int num = list[index];
                if (num < min)
                {
                    min = num;
                    minIndice.Clear();
                }
                if (num == min)
                {
                    minIndice.Add(index);
                }
            }
            return minIndice;
        }

        /// <summary>
        /// Flats the specified groups.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="groups">The groups.</param>
        /// <returns></returns>
        public static List<T> Flat<T>(List<List<T>> groups)
        {
            List<T> items = new List<T>();
            foreach (List<T> group in groups)
            {
                items.AddRange(group);
            }
            return items;
        }
    }
}


text:
2016 Advent of Code
http://adventofcode.com/2016


text:
#import "MXKGroupTableViewCell.h"

#import "NSBundle+MatrixKit.h"

#import "MXKSwiftHeader.h"

@implementation MXKGroupTableViewCell
@synthesize delegate;

#pragma mark - Class methods

- (void)render:(MXKCellData *)cellData
{
    groupCellData = (id<MXKGroupCellDataStoring>)cellData;
    if (groupCellData)
    {
        // Render the current group values.
        _groupName.text = groupCellData.groupDisplayname;
        _groupDescription.text = groupCellData.group.profile.shortDescription;

        if (_groupDescription.text.length)
        {
            _groupDescription.hidden = NO;
        }
        else
        {
            // Hide and fill the label with a fake description to harmonize the height of all the cells.
            // This is a drawback of the self-sizing cell.
            _groupDescription.hidden = YES;
            _groupDescription.text = @"No description";
        }

        if (_memberCount)
        {
            if (groupCellData.group.summary.usersSection.totalUserCountEstimate > 1)
            {
                _memberCount.text = [VectorL10n numMembersOther:@(groupCellData.group.summary.usersSection.totalUserCountEstimate).stringValue];
            }
            else if (groupCellData.group.summary.usersSection.totalUserCountEstimate == 1)
            {
                _memberCount.text = [VectorL10n numMembersOne:@(1).stringValue];
            }
            else
            {
                _memberCount.text = nil;
            }
        }
    }
    else
    {
        _groupName.text = nil;
        _groupDescription.text = nil;
        _memberCount.text = nil;
    }
}

- (MXKCellData*)renderedCellData
{
    return groupCellData;
}

+ (CGFloat)heightForCellData:(MXKCellData *)cellData withMaximumWidth:(CGFloat)maxWidth
{
    // The height is fixed
    //@TODO: change this to handle dynamic font
    return 70;
}

- (void)prepareForReuse
{
    [super prepareForReuse];

    groupCellData = nil;
}

@end


text:
import { expect } from "chai";
import { enableExperimentsFromCliEnvVariable, isEnabled, setEnabled } from "../experiments";

describe("experiments", () => {
  let originalCLIState = process.env.FIREBASE_CLI_EXPERIMENTS;

  before(() => {
    originalCLIState = process.env.FIREBASE_CLI_EXPERIMENTS;
  });

  beforeEach(() => {
    process.env.FIREBASE_CLI_EXPERIMENTS = originalCLIState;
  });

  afterEach(() => {
    process.env.FIREBASE_CLI_EXPERIMENTS = originalCLIState;
  });

  describe("enableExperimentsFromCliEnvVariable", () => {
    it("should enable some experiments", () => {
      expect(isEnabled("experiments")).to.be.false;
      process.env.FIREBASE_CLI_EXPERIMENTS = "experiments,not_an_experiment";

      enableExperimentsFromCliEnvVariable();

      expect(isEnabled("experiments")).to.be.true;
      setEnabled("experiments", false);
    });
  });
});


text:
package org.apache.asterix.app.nc;

import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.asterix.common.config.ReplicationProperties;
import org.apache.asterix.common.config.TransactionProperties;
import org.apache.asterix.common.exceptions.ACIDException;
import org.apache.asterix.common.replication.IReplicationStrategy;
import org.apache.asterix.common.transactions.Checkpoint;
import org.apache.asterix.common.transactions.CheckpointProperties;
import org.apache.asterix.common.transactions.IAppRuntimeContextProvider;
import org.apache.asterix.common.transactions.ICheckpointManager;
import org.apache.asterix.common.transactions.ILockManager;
import org.apache.asterix.common.transactions.ILogManager;
import org.apache.asterix.common.transactions.IRecoveryManager;
import org.apache.asterix.common.transactions.ITransactionManager;
import org.apache.asterix.common.transactions.ITransactionSubsystem;
import org.apache.asterix.common.utils.StorageConstants;
import org.apache.asterix.transaction.management.service.locking.ConcurrentLockManager;
import org.apache.asterix.transaction.management.service.logging.LogManager;
import org.apache.asterix.transaction.management.service.logging.LogManagerWithReplication;
import org.apache.asterix.transaction.management.service.recovery.CheckpointManagerFactory;
import org.apache.asterix.transaction.management.service.transaction.TransactionManager;
import org.apache.hyracks.api.application.INCServiceContext;

/**
 * Provider for all the sub-systems (transaction/lock/log/recovery) managers.
 * Users of transaction sub-systems must obtain them from the provider.
 */
public class TransactionSubsystem implements ITransactionSubsystem {
    private static final Logger LOGGER = Logger.getLogger(TransactionSubsystem.class.getName());
    private final String id;
    private final ILogManager logManager;
    private final ILockManager lockManager;
    private final ITransactionManager transactionManager;
    private final IRecoveryManager recoveryManager;
    private final IAppRuntimeContextProvider asterixAppRuntimeContextProvider;
    private final TransactionProperties txnProperties;
    private final ICheckpointManager checkpointManager;

    //for profiling purpose
    private long profilerEntityCommitLogCount = 0;
    private EntityCommitProfiler ecp;

    public TransactionSubsystem(INCServiceContext serviceCtx, String id,
            IAppRuntimeContextProvider asterixAppRuntimeContextProvider, TransactionProperties txnProperties)
            throws ACIDException {
        this.asterixAppRuntimeContextProvider = asterixAppRuntimeContextProvider;
        this.id = id;
        this.txnProperties = txnProperties;
        this.transactionManager = new TransactionManager(this);
        this.lockManager = new ConcurrentLockManager(txnProperties.getLockManagerShrinkTimer());
        ReplicationProperties repProperties =
                asterixAppRuntimeContextProvider.getAppContext().getReplicationProperties();
        IReplicationStrategy replicationStrategy = repProperties.getReplicationStrategy();
        final boolean replicationEnabled = repProperties.isParticipant(id);
        final CheckpointProperties checkpointProperties = new CheckpointProperties(txnProperties, id);
        if (LOGGER.isLoggable(Level.INFO)) {
            LOGGER.log(Level.INFO, "Checkpoint Properties: " + checkpointProperties);
        }
        checkpointManager = CheckpointManagerFactory.create(this, checkpointProperties, replicationEnabled);
        final Checkpoint latestCheckpoint = checkpointManager.getLatest();
        if (latestCheckpoint != null) {
            transactionManager.ensureMaxTxnId(latestCheckpoint.getMaxTxnId());
        }

        if (replicationEnabled) {
            this.logManager = new LogManagerWithReplication(this, replicationStrategy);
        } else {
            this.logManager = new LogManager(this);
        }
        this.recoveryManager = new RecoveryManager(this, serviceCtx);
        if (this.txnProperties.isCommitProfilerEnabled()) {
            ecp = new EntityCommitProfiler(this, this.txnProperties.getCommitProfilerReportInterval());
            getAsterixAppRuntimeContextProvider().getThreadExecutor().submit(ecp);
        }
    }

    @Override
    public ILogManager getLogManager() {
        return logManager;
    }

    @Override
    public ILockManager getLockManager() {
        return lockManager;
    }

    @Override
    public ITransactionManager getTransactionManager() {
        return transactionManager;
    }

    @Override
    public IRecoveryManager getRecoveryManager() {
        return recoveryManager;
    }

    @Override
    public IAppRuntimeContextProvider getAsterixAppRuntimeContextProvider() {
        return asterixAppRuntimeContextProvider;
    }

    @Override
    public TransactionProperties getTransactionProperties() {
        return txnProperties;
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public void incrementEntityCommitCount() {
        ++profilerEntityCommitLogCount;
    }

    @Override
    public ICheckpointManager getCheckpointManager() {
        return checkpointManager;
    }

    /**
     * Thread for profiling entity level commit count
     * This thread takes a report interval (in seconds) parameter and
     * reports entity level commit count every report interval (in seconds)
     * only if IS_PROFILE_MODE is set to true.
     * However, the thread doesn't start reporting the count until the entityCommitCount > 0.
     */
    static class EntityCommitProfiler implements Callable<Boolean> {
        private static final Logger LOGGER = Logger.getLogger(EntityCommitProfiler.class.getName());
        private final long reportIntervalInMillisec;
        private long lastEntityCommitCount;
        private int reportIntervalInSeconds;
        private TransactionSubsystem txnSubsystem;
        private boolean firstReport = true;
        private long startTimeStamp = 0;
        private long reportRound = 1;

        public EntityCommitProfiler(TransactionSubsystem txnSubsystem, int reportIntervalInSeconds) {
            Thread.currentThread().setName("EntityCommitProfiler-Thread");
            this.txnSubsystem = txnSubsystem;
            this.reportIntervalInSeconds = reportIntervalInSeconds;
            this.reportIntervalInMillisec = reportIntervalInSeconds * 1000L;
            lastEntityCommitCount = txnSubsystem.profilerEntityCommitLogCount;
        }

        @Override
        public Boolean call() throws Exception {
            while (true) {
                Thread.sleep(reportIntervalInMillisec);
                if (txnSubsystem.profilerEntityCommitLogCount > 0) {
                    if (firstReport) {
                        startTimeStamp = System.currentTimeMillis();
                        firstReport = false;
                    }
                    outputCount();
                }
            }
        }

        private void outputCount() {
            long currentTimeStamp = System.currentTimeMillis();
            long currentEntityCommitCount = txnSubsystem.profilerEntityCommitLogCount;

            LOGGER.severe("EntityCommitProfiler ReportRound[" + reportRound + "], AbsoluteTimeStamp[" + currentTimeStamp
                    + "], ActualRelativeTimeStamp[" + (currentTimeStamp - startTimeStamp)
                    + "], ExpectedRelativeTimeStamp[" + (reportIntervalInSeconds * reportRound) + "], IIPS["
                    + ((currentEntityCommitCount - lastEntityCommitCount) / reportIntervalInSeconds) + "], IPS["
                    + (currentEntityCommitCount / (reportRound * reportIntervalInSeconds)) + "]");

            lastEntityCommitCount = currentEntityCommitCount;
            ++reportRound;
        }
    }

}


text:
# Support
There will be no official support.

# Pull Requests
Official-Code will remain as it is, but you are free to change it for your purposes.

## Content
It is a single ~250Code-Line-Big Script to let an AI controlled helicopter lift diferrent freight goods to a single destination.

## Purpose
The aim of this script is to make it easier to lift freight goods from A to B without having to have a player pilot.

## Story
A few weeks ago a buddy asked me to write a script for a helicopter to lift and transport cargo, the 'Helikopterfrachttransportskript', that finally provides the desired solution. At first I thought that there would be something out there already. However, according to his research there are no scripts or tutorials that let you have an AI helicopter reliably hovering over a cargo in ArmA 3 (having it meter-precise is imperative). This hovering and the whole process of picking up and setting down the cargo was supposed to look more realistic than just an attachTo. And so this script was written. It provides a precise hovering over the cargo, great looking attachment of the sling rope and picking up of the cargo as well as putting the load down in the same way at the target position. There are several routine integrated to avoid script errors in cases of explosions or deaths of the vehicle or AI. A description can be found inside the SQF file, how to execute the script. Have fun.

## Media

### Showcase #1 (Clip)
[![Showcase #1](https://i.ytimg.com/vi/M2ybK0lpJ94/sddefault.jpg)](https://www.youtube.com/watch?v=M2ybK0lpJ94)

### Showcase #2 (Clip)

[![Showcase #2](https://i.ytimg.com/vi/myOga-KNvaU/sddefault.jpg)](https://www.youtube.com/watch?v=myOga-KNvaU)


text:
(function() {
  'use strict';

  describe('horizon.dashboard.aws.workflow.export-instance.workflow tests', function () {
    var exportInstanceWorkflow, stepPolicy;

    beforeEach(module('horizon.app.core'));
    beforeEach(module('horizon.framework.util'));
    beforeEach(module('horizon.framework.conf'));
    beforeEach(module('horizon.framework.widgets.toast'));
    beforeEach(module('horizon.dashboard.aws'));

    beforeEach(inject(function ($injector) {
      exportInstanceWorkflow = $injector.get(
        'horizon.dashboard.aws.workflow.export-instance.workflow'
      );
      stepPolicy = $injector.get('horizon.dashboard.project.workflow.launch-instance.step-policy');
    }));

    it('should be defined', function () {
      expect(exportInstanceWorkflow).toBeDefined();
    });

    it('should have a title property', function () {
      expect(exportInstanceWorkflow.title).toBeDefined();
    });

    it('should have 11 steps defined', function () {
      expect(exportInstanceWorkflow.steps).toBeDefined();
      expect(exportInstanceWorkflow.steps.length).toBe(11);

      var forms = [
        'exportInstanceDetailsForm',
        'exportInstanceSourceForm',
        'exportInstanceFlavorForm',
        'exportInstanceNetworkForm',
        'exportInstanceNetworkPortForm',
        'exportInstanceAccessAndSecurityForm',
        'exportInstanceKeypairForm',
        'exportInstanceConfigurationForm',
        'exportInstanceServerGroupsForm',
        'exportInstanceSchedulerHintsForm',
        'exportInstanceMetadataForm'
      ];

      forms.forEach(function(expectedForm, idx) {
        expect(exportInstanceWorkflow.steps[idx].formName).toBe(expectedForm);
      });
    });

    it('specifies that the network step requires the network service type', function() {
      expect(exportInstanceWorkflow.steps[3].requiredServiceTypes).toEqual(['network']);
    });

    it('specifies that the network port step requires the network service type', function() {
      expect(exportInstanceWorkflow.steps[4].requiredServiceTypes).toEqual(['network']);
    });

    it('has a policy rule for the server groups step', function() {
      expect(exportInstanceWorkflow.steps[8].policy).toEqual(stepPolicy.serverGroups);
    });

    it('has a policy rule for the scheduler hints step', function() {
      expect(exportInstanceWorkflow.steps[9].policy).toEqual(stepPolicy.schedulerHints);
    });
  });

})();