text:
package com.google.gwt.user.client.ui;

import com.google.gwt.animation.client.Animation;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.EventTarget;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.Display;
import com.google.gwt.dom.client.Style.Position;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.event.logical.shared.HasCloseHandlers;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.i18n.client.LocaleInfo;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.EventPreview;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.Event.NativePreviewEvent;
import com.google.gwt.user.client.Event.NativePreviewHandler;
import com.google.gwt.user.client.ui.impl.PopupImpl;

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

/**
 * A panel that can "pop up" over other widgets. It overlays the browser's
 * client area (and any previously-created popups).
 *
 *

 * A PopupPanel should not generally be added to other panels; rather, it should
 * be shown and hidden using the {@link #show()} and {@link #hide()} methods.
 *

 *

 * The width and height of the PopupPanel cannot be explicitly set; they are
 * determined by the PopupPanel's widget. Calls to {@link #setWidth(String)} and
 * {@link #setHeight(String)} will call these methods on the PopupPanel's
 * widget.
 *

 *

 *
 *

 *
 *

 * The PopupPanel can be optionally displayed with a "glass" element behind it,
 * which is commonly used to gray out the widgets behind it. It can be enabled
 * using {@link #setGlassEnabled(boolean)}. It has a default style name of
 * "gwt-PopupPanelGlass", which can be changed using
 * {@link #setGlassStyleName(String)}.
 *

 *
 *

 *
Example

 * {@example com.google.gwt.examples.PopupPanelExample}
 *

 *
CSS Style Rules

 *

 *
.gwt-PopupPanel

 *
the outside of the popup

 *
.gwt-PopupPanel .popupContent

 *
the wrapper around the content

 *
.gwt-PopupPanelGlass

 *
the glass background behind the popup

 *

 */
@SuppressWarnings("deprecation")
public class PopupPanel extends SimplePanel implements SourcesPopupEvents,
    EventPreview, HasAnimation, HasCloseHandlers<PopupPanel> {

  /**
   * A callback that is used to set the position of a {@link PopupPanel} right
   * before it is shown.
   */
  public interface PositionCallback {

    /**
     * Provides the opportunity to set the position of the PopupPanel right
     * before the PopupPanel is shown. The offsetWidth and offsetHeight values
     * of the PopupPanel are made available to allow for positioning based on
     * its size.
     *
     * @param offsetWidth the offsetWidth of the PopupPanel
     * @param offsetHeight the offsetHeight of the PopupPanel
     * @see PopupPanel#setPopupPositionAndShow(PositionCallback)
     */
    void setPosition(int offsetWidth, int offsetHeight);
  }

  /**
   * The type of animation to use when opening the popup.
   *
   *

   *
CENTER - Expand from the center of the popup

   *
ONE_WAY_CORNER - Expand from the top left corner, do not animate hiding
   *

   *

   */
  static enum AnimationType {
    CENTER, ONE_WAY_CORNER, ROLL_DOWN
  }

  /**
   * An {@link Animation} used to enlarge the popup into view.
   */
  static class ResizeAnimation extends Animation {
    /**
     * The {@link PopupPanel} being affected.
     */
    private PopupPanel curPanel = null;

    /**
     * Indicates whether or not the {@link PopupPanel} is in the process of
     * unloading. If the popup is unloading, then the animation just does
     * cleanup.
     */
    private boolean isUnloading;

    /**
     * The offset height and width of the current {@link PopupPanel}.
     */
    private int offsetHeight, offsetWidth = -1;

    /**
     * A boolean indicating whether we are showing or hiding the popup.
     */
    private boolean showing;

    /**
     * The timer used to delay the show animation.
     */
    private Timer showTimer;

    /**
     * A boolean indicating whether the glass element is currently attached.
     */
    private boolean glassShowing;

    private HandlerRegistration resizeRegistration;

    /**
     * Create a new {@link ResizeAnimation}.
     *
     * @param panel the panel to affect
     */
    public ResizeAnimation(PopupPanel panel) {
      this.curPanel = panel;
    }

    /**
     * Open or close the content. This method always called immediately after
     * the PopupPanel showing state has changed, so we base the animation on the
     * current state.
     *
     * @param showing true if the popup is showing, false if not
     */
    public void setState(boolean showing, boolean isUnloading) {
      // Immediately complete previous open/close animation
      this.isUnloading = isUnloading;
      cancel();

      // If there is a pending timer to start a show animation, then just cancel
      // the timer and complete the show operation.
      if (showTimer != null) {
        showTimer.cancel();
        showTimer = null;
        onComplete();
      }

      // Update the logical state.
      curPanel.showing = showing;
      curPanel.updateHandlers();

      // Determine if we need to animate
      boolean animate = !isUnloading && curPanel.isAnimationEnabled;
      if (curPanel.animType != AnimationType.CENTER && !showing) {
        animate = false;
      }

      // Open the new item
      this.showing = showing;
      if (animate) {
        // impl.onShow takes some time to complete, so we do it before starting
        // the animation. If we move this to onStart, the animation will look
        // choppy or not run at all.
        if (showing) {
          maybeShowGlass();

          // Set the position attribute, and then attach to the DOM. Otherwise,
          // the PopupPanel will appear to 'jump' from its static/relative
          // position to its absolute position (issue #1231).
          DOM.setStyleAttribute(curPanel.getElement(), "position", "absolute");
          if (curPanel.topPosition != -1) {
            curPanel.setPopupPosition(curPanel.leftPosition,
                curPanel.topPosition);
          }
          impl.setClip(curPanel.getElement(), getRectString(0, 0, 0, 0));
          RootPanel.get().add(curPanel);
          impl.onShow(curPanel.getElement());

          // Wait for the popup panel and iframe to be attached before running
          // the animation. We use a Timer instead of a DeferredCommand so we
          // can cancel it if the popup is hidden synchronously.
          showTimer = new Timer() {
            @Override
            public void run() {
              showTimer = null;
              ResizeAnimation.this.run(ANIMATION_DURATION);
            }
          };
          showTimer.schedule(1);
        } else {
          run(ANIMATION_DURATION);
        }
      } else {
        onInstantaneousRun();
      }
    }

    @Override
    protected void onComplete() {
      if (!showing) {
        maybeShowGlass();
        if (!isUnloading) {
          RootPanel.get().remove(curPanel);
        }
        impl.onHide(curPanel.getElement());
      }
      impl.setClip(curPanel.getElement(), "rect(auto, auto, auto, auto)");
      DOM.setStyleAttribute(curPanel.getElement(), "overflow", "visible");
    }

    @Override
    protected void onStart() {
      offsetHeight = curPanel.getOffsetHeight();
      offsetWidth = curPanel.getOffsetWidth();
      DOM.setStyleAttribute(curPanel.getElement(), "overflow", "hidden");
      super.onStart();
    }

    @Override
    protected void onUpdate(double progress) {
      if (!showing) {
        progress = 1.0 - progress;
      }

      // Determine the clipping size
      int top = 0;
      int left = 0;
      int right = 0;
      int bottom = 0;
      int height = (int) (progress * offsetHeight);
      int width = (int) (progress * offsetWidth);
      switch (curPanel.animType) {
        case ROLL_DOWN:
          right = offsetWidth;
          bottom = height;
          break;
        case CENTER:
          top = (offsetHeight - height) >> 1;
          left = (offsetWidth - width) >> 1;
          right = left + width;
          bottom = top + height;
          break;
        case ONE_WAY_CORNER:
          if (LocaleInfo.getCurrentLocale().isRTL()) {
            left = offsetWidth - width;
          }
          right = left + width;
          bottom = top + height;
          break;
      }
      // Set the rect clipping
      impl.setClip(curPanel.getElement(), getRectString(top, right, bottom,
          left));
    }

    /**
     * Returns a rect string.
     */
    private String getRectString(int top, int right, int bottom, int left) {
      return "rect(" + top + "px, " + right + "px, " + bottom + "px, " + left
          + "px)";
    }

    /**
     * Show or hide the glass.
     */
    private void maybeShowGlass() {
      if (showing) {
        if (curPanel.isGlassEnabled) {
          Document.get().getBody().appendChild(curPanel.glass);
          impl.onShow(curPanel.glass);

          resizeRegistration = Window.addResizeHandler(curPanel.glassResizer);
          curPanel.glassResizer.onResize(null);

          glassShowing = true;
        }
      } else if (glassShowing) {
        Document.get().getBody().removeChild(curPanel.glass);
        impl.onHide(curPanel.glass);

        resizeRegistration.removeHandler();
        resizeRegistration = null;

        glassShowing = false;
      }
    }

    private void onInstantaneousRun() {
      maybeShowGlass();
      if (showing) {
        // Set the position attribute, and then attach to the DOM. Otherwise,
        // the PopupPanel will appear to 'jump' from its static/relative
        // position to its absolute position (issue #1231).
        DOM.setStyleAttribute(curPanel.getElement(), "position", "absolute");
        if (curPanel.topPosition != -1) {
          curPanel.setPopupPosition(curPanel.leftPosition, curPanel.topPosition);
        }
        RootPanel.get().add(curPanel);
        impl.onShow(curPanel.getElement());
      } else {
        if (!isUnloading) {
          RootPanel.get().remove(curPanel);
        }
        impl.onHide(curPanel.getElement());
      }
      DOM.setStyleAttribute(curPanel.getElement(), "overflow", "visible");
    }
  }

  /**
   * The duration of the animation.
   */
  private static final int ANIMATION_DURATION = 200;

  /**
   * The default style name.
   */
  private static final String DEFAULT_STYLENAME = "gwt-PopupPanel";

  private static final PopupImpl impl = GWT.create(PopupImpl.class);

  /**
   * Window resize handler used to keep the glass the proper size.
   */
  private ResizeHandler glassResizer = new ResizeHandler() {
    public void onResize(ResizeEvent event) {
      Style style = glass.getStyle();

      int winWidth = Window.getClientWidth();
      int winHeight = Window.getClientHeight();

      // Hide the glass while checking the document size. Otherwise it would
      // interfere with the measurement.
      style.setDisplay(Display.NONE);
      style.setWidth(0, Unit.PX);
      style.setHeight(0, Unit.PX);

      int width = Document.get().getScrollWidth();
      int height = Document.get().getScrollHeight();

      // Set the glass size to the larger of the window's client size or the
      // document's scroll size.
      style.setWidth(Math.max(width, winWidth), Unit.PX);
      style.setHeight(Math.max(height, winHeight), Unit.PX);

      // The size is set. Show the glass again.
      style.setDisplay(Display.BLOCK);
    }
  };

  /**
   * If true, animate the opening of this popup from the center. If false,
   * animate it open from top to bottom, and do not animate closing. Use false
   * to animate menus.
   */
  private AnimationType animType = AnimationType.CENTER;

  private boolean autoHide, previewAllNativeEvents, modal, showing;
  private boolean autoHideOnHistoryEvents;

  private List<Element> autoHidePartners;

  // Used to track requested size across changing child widgets
  private String desiredHeight;

  private String desiredWidth;

  /**
   * The glass element.
   */
  private Element glass;

  private String glassStyleName = "gwt-PopupPanelGlass";

  /**
   * A boolean indicating that a glass element should be used.
   */
  private boolean isGlassEnabled;

  private boolean isAnimationEnabled = false;

  // the left style attribute in pixels
  private int leftPosition = -1;

  private HandlerRegistration nativePreviewHandlerRegistration;
  private HandlerRegistration historyHandlerRegistration;

  /**
   * The {@link ResizeAnimation} used to open and close the {@link PopupPanel}s.
   */
  private ResizeAnimation resizeAnimation = new ResizeAnimation(this);

  // The top style attribute in pixels
  private int topPosition = -1;

  /**
   * Creates an empty popup panel. A child widget must be added to it before it
   * is shown.
   */
  public PopupPanel() {
    super();
    super.getContainerElement().appendChild(impl.createElement());

    // Default position of popup should be in the upper-left corner of the
    // window. By setting a default position, the popup will not appear in
    // an undefined location if it is shown before its position is set.
    setPopupPosition(0, 0);
    setStyleName(DEFAULT_STYLENAME);
    setStyleName(getContainerElement(), "popupContent");
  }

  /**
   * Creates an empty popup panel, specifying its "auto-hide" property.
   *
   * @param autoHide true if the popup should be automatically
   *          hidden when the user clicks outside of it or the history token
   *          changes.
   */
  public PopupPanel(boolean autoHide) {
    this();
    this.autoHide = autoHide;
    this.autoHideOnHistoryEvents = autoHide;
  }

  /**
   * Creates an empty popup panel, specifying its "auto-hide" and "modal"
   * properties.
   *
   * @param autoHide true if the popup should be automatically
   *          hidden when the user clicks outside of it or the history token
   *          changes.
   * @param modal true if keyboard or mouse events that do not
   *          target the PopupPanel or its children should be ignored
   */
  public PopupPanel(boolean autoHide, boolean modal) {
    this(autoHide);
    this.modal = modal;
  }

  /**
   * Mouse events that occur within an autoHide partner will not hide a panel
   * set to autoHide.
   *
   * @param partner the auto hide partner to add
   */
  public void addAutoHidePartner(Element partner) {
    assert partner != null : "partner cannot be null";
    if (autoHidePartners == null) {
      autoHidePartners = new ArrayList<Element>();
    }
    autoHidePartners.add(partner);
  }

  public HandlerRegistration addCloseHandler(CloseHandler<PopupPanel> handler) {
    return addHandler(handler, CloseEvent.getType());
  }

  /**
   * @deprecated Use {@link #addCloseHandler} instead
   */
  @Deprecated
  public void addPopupListener(final PopupListener listener) {
    ListenerWrapper.WrappedPopupListener.add(this, listener);
  }

  /**
   * Centers the popup in the browser window and shows it. If the popup was
   * already showing, then the popup is centered.
   */
  public void center() {
    boolean initiallyShowing = showing;
    boolean initiallyAnimated = isAnimationEnabled;

    if (!initiallyShowing) {
      setVisible(false);
      setAnimationEnabled(false);
      show();
    }

    // If left/top are set from a previous center() call, and our content
    // has changed, we may get a bogus getOffsetWidth because our new content
    // is wrapping (giving a lower offset width) then it would without the
    // previous left. Setting left/top back to 0 avoids this.
    Element elem = getElement();
    elem.getStyle().setPropertyPx("left", 0);
    elem.getStyle().setPropertyPx("top", 0);

    int left = (Window.getClientWidth() - getOffsetWidth()) >> 1;
    int top = (Window.getClientHeight() - getOffsetHeight()) >> 1;
    setPopupPosition(Math.max(Window.getScrollLeft() + left, 0), Math.max(
        Window.getScrollTop() + top, 0));

    if (!initiallyShowing) {
      setAnimationEnabled(initiallyAnimated);
      // Run the animation. The popup is already visible, so we can skip the
      // call to setState.
      if (initiallyAnimated) {
        impl.setClip(getElement(), "rect(0px, 0px, 0px, 0px)");
        setVisible(true);
        resizeAnimation.run(ANIMATION_DURATION);
      } else {
        setVisible(true);
      }
    }
  }

  /**
   * Gets the style name to be used on the glass element. By default, this is
   * "gwt-PopupPanelGlass".
   *
   * @return the glass element's style name
   */
  public String getGlassStyleName() {
    return glassStyleName;
  }

  /**
   * Gets the panel's offset height in pixels. Calls to
   * {@link #setHeight(String)} before the panel's child widget is set will not
   * influence the offset height.
   *
   * @return the object's offset height
   */
  @Override
  public int getOffsetHeight() {
    return super.getOffsetHeight();
  }

  /**
   * Gets the panel's offset width in pixels. Calls to {@link #setWidth(String)}
   * before the panel's child widget is set will not influence the offset width.
   *
   * @return the object's offset width
   */
  @Override
  public int getOffsetWidth() {
    return super.getOffsetWidth();
  }

  /**
   * Gets the popup's left position relative to the browser's client area.
   *
   * @return the popup's left position
   */
  public int getPopupLeft() {
    return DOM.getAbsoluteLeft(getElement());
  }

  /**
   * Gets the popup's top position relative to the browser's client area.
   *
   * @return the popup's top position
   */
  public int getPopupTop() {
    return DOM.getAbsoluteTop(getElement());
  }

  @Override
  public String getTitle() {
    return DOM.getElementProperty(getContainerElement(), "title");
  }

  /**
   * Hides the popup and detaches it from the page. This has no effect if it is
   * not currently showing.
   */
  public void hide() {
    hide(false);
  }

  /**
   * Hides the popup and detaches it from the page. This has no effect if it is
   * not currently showing.
   *
   * @param autoClosed the value that will be passed to
   *          {@link CloseHandler#onClose(CloseEvent)} when the popup is closed
   */
  public void hide(boolean autoClosed) {
    if (!isShowing()) {
      return;
    }
    resizeAnimation.setState(false, false);
    CloseEvent.fire(this, this, autoClosed);
  }

  public boolean isAnimationEnabled() {
    return isAnimationEnabled;
  }

  /**
   * Returns true if the popup should be automatically hidden when
   * the user clicks outside of it.
   *
   * @return true if autoHide is enabled, false if disabled
   */
  public boolean isAutoHideEnabled() {
    return autoHide;
  }

  /**
   * Returns true if the popup should be automatically hidden when
   * the history token changes, such as when the user presses the browser's back
   * button.
   *
   * @return true if enabled, false if disabled
   */
  public boolean isAutoHideOnHistoryEventsEnabled() {
    return autoHideOnHistoryEvents;
  }

  /**
   * Returns true if a glass element will be displayed under the
   * {@link PopupPanel}.
   *
   * @return true if enabled
   */
  public boolean isGlassEnabled() {
    return isGlassEnabled;
  }

  /**
   * Returns true if keyboard or mouse events that do not target
   * the PopupPanel or its children should be ignored.
   *
   * @return true if popup is modal, false if not
   */
  public boolean isModal() {
    return modal;
  }

  /**
   * Returns true if the popup should preview all native events,
   * even if the event has already been consumed by another popup.
   *
   * @return true if previewAllNativeEvents is enabled, false if disabled
   */
  public boolean isPreviewingAllNativeEvents() {
    return previewAllNativeEvents;
  }

  /**
   * Determines whether or not this popup is showing.
   *
   * @return true if the popup is showing
   * @see #show()
   * @see #hide()
   */
  public boolean isShowing() {
    return showing;
  }

  /**
   * Determines whether or not this popup is visible. Note that this just checks
   * the visibility style attribute, which is set in the
   * {@link #setVisible(boolean)} method. If you want to know if the popup is
   * attached to the page, use {@link #isShowing()} instead.
   *
   * @return true if the object is visible
   * @see #setVisible(boolean)
   */
  @Override
  public boolean isVisible() {
    return !"hidden".equals(getElement().getStyle().getProperty("visibility"));
  }

  /**
   * @deprecated Use {@link #onPreviewNativeEvent} instead
   */
  @Deprecated
  public boolean onEventPreview(Event event) {
    return true;
  }

  /**
   * Popups get an opportunity to preview keyboard events before they are passed
   * to a widget contained by the Popup.
   *
   * @param key the key code of the depressed key
   * @param modifiers keyboard modifiers, as specified in
   *          {@link com.google.gwt.event.dom.client.KeyCodes}.
   * @return false to suppress the event
   * @deprecated Use {@link #onPreviewNativeEvent} instead
   */
  @Deprecated
  public boolean onKeyDownPreview(char key, int modifiers) {
    return true;
  }

  /**
   * Popups get an opportunity to preview keyboard events before they are passed
   * to a widget contained by the Popup.
   *
   * @param key the unicode character pressed
   * @param modifiers keyboard modifiers, as specified in
   *          {@link com.google.gwt.event.dom.client.KeyCodes}.
   * @return false to suppress the event
   * @deprecated Use {@link #onPreviewNativeEvent} instead
   */
  @Deprecated
  public boolean onKeyPressPreview(char key, int modifiers) {
    return true;
  }

  /**
   * Popups get an opportunity to preview keyboard events before they are passed
   * to a widget contained by the Popup.
   *
   * @param key the key code of the released key
   * @param modifiers keyboard modifiers, as specified in
   *          {@link com.google.gwt.event.dom.client.KeyCodes}.
   * @return false to suppress the event
   * @deprecated Use {@link #onPreviewNativeEvent} instead
   */
  @Deprecated
  public boolean onKeyUpPreview(char key, int modifiers) {
    return true;
  }

  /**
   * Remove an autoHide partner.
   *
   * @param partner the auto hide partner to remove
   */
  public void removeAutoHidePartner(Element partner) {
    assert partner != null : "partner cannot be null";
    if (autoHidePartners != null) {
      autoHidePartners.remove(partner);
    }
  }

  /**
   * @deprecated Use the {@link HandlerRegistration#removeHandler} method on the
   *             object returned by {@link #addCloseHandler} instead
   */
  @Deprecated
  public void removePopupListener(PopupListener listener) {
    ListenerWrapper.WrappedPopupListener.remove(this, listener);
  }

  public void setAnimationEnabled(boolean enable) {
    isAnimationEnabled = enable;
  }

  /**
   * Enable or disable the autoHide feature. When enabled, the popup will be
   * automatically hidden when the user clicks outside of it.
   *
   * @param autoHide true to enable autoHide, false to disable
   */
  public void setAutoHideEnabled(boolean autoHide) {
    this.autoHide = autoHide;
  }

  /**
   * Enable or disable autoHide on history change events. When enabled, the
   * popup will be automatically hidden when the history token changes, such as
   * when the user presses the browser's back button. Disabled by default.
   *
   * @param enabled true to enable, false to disable
   */
  public void setAutoHideOnHistoryEventsEnabled(boolean enabled) {
    this.autoHideOnHistoryEvents = enabled;
  }

  /**
   * When enabled, the background will be blocked with a semi-transparent pane
   * the next time it is shown. If the PopupPanel is already visible, the glass
   * will not be displayed until it is hidden and shown again.
   *
   * @param enabled true to enable, false to disable
   */
  public void setGlassEnabled(boolean enabled) {
    this.isGlassEnabled = enabled;
    if (enabled && glass == null) {
      glass = Document.get().createDivElement();
      glass.setClassName(glassStyleName);

      glass.getStyle().setPosition(Position.ABSOLUTE);
      glass.getStyle().setLeft(0, Unit.PX);
      glass.getStyle().setTop(0, Unit.PX);
    }
  }

  /**
   * Sets the style name to be used on the glass element. By default, this is
   * "gwt-PopupPanelGlass".
   *
   * @param glassStyleName the glass element's style name
   */
  public void setGlassStyleName(String glassStyleName) {
    this.glassStyleName = glassStyleName;
    if (glass != null) {
      glass.setClassName(glassStyleName);
    }
  }

  /**
   * Sets the height of the panel's child widget. If the panel's child widget
   * has not been set, the height passed in will be cached and used to set the
   * height immediately after the child widget is set.
   *
   *

   * Note that subclasses may have a different behavior. A subclass may decide
   * not to change the height of the child widget. It may instead decide to
   * change the height of an internal panel widget, which contains the child
   * widget.
   *

   *
   * @param height the object's new height, in CSS units (e.g. "10px", "1em")
   */
  @Override
  public void setHeight(String height) {
    desiredHeight = height;
    maybeUpdateSize();
    // If the user cleared the size, revert to not trying to control children.
    if (height.length() == 0) {
      desiredHeight = null;
    }
  }

  /**
   * When the popup is modal, keyboard or mouse events that do not target the
   * PopupPanel or its children will be ignored.
   *
   * @param modal true to make the popup modal
   */
  public void setModal(boolean modal) {
    this.modal = modal;
  }

  /**
   * Sets the popup's position relative to the browser's client area. The
   * popup's position may be set before calling {@link #show()}.
   *
   * @param left the left position, in pixels
   * @param top the top position, in pixels
   */
  public void setPopupPosition(int left, int top) {
    // Save the position of the popup
    leftPosition = left;
    topPosition = top;

    // Account for the difference between absolute position and the
    // body's positioning context.
    left -= Document.get().getBodyOffsetLeft();
    top -= Document.get().getBodyOffsetTop();

    // Set the popup's position manually, allowing setPopupPosition() to be
    // called before show() is called (so a popup can be positioned without it
    // 'jumping' on the screen).
    Element elem = getElement();
    elem.getStyle().setPropertyPx("left", left);
    elem.getStyle().setPropertyPx("top", top);
  }

  /**
   * Sets the popup's position using a {@link PositionCallback}, and shows the
   * popup. The callback allows positioning to be performed based on the
   * offsetWidth and offsetHeight of the popup, which are normally not available
   * until the popup is showing. By positioning the popup before it is shown,
   * the the popup will not jump from its original position to the new position.
   *
   * @param callback the callback to set the position of the popup
   * @see PositionCallback#setPosition(int offsetWidth, int offsetHeight)
   */
  public void setPopupPositionAndShow(PositionCallback callback) {
    setVisible(false);
    show();
    callback.setPosition(getOffsetWidth(), getOffsetHeight());
    setVisible(true);
  }

  /**
   *

   * When enabled, the popup will preview all native events, even if another
   * popup was opened after this one.
   *

   *

   * If autoHide is enabled, enabling this feature will cause the popup to
   * autoHide even if another non-modal popup was shown after it. If this
   * feature is disabled, the popup will only autoHide if it was the last popup
   * opened.
   *

   *
   * @param previewAllNativeEvents true to enable, false to disable
   */
  public void setPreviewingAllNativeEvents(boolean previewAllNativeEvents) {
    this.previewAllNativeEvents = previewAllNativeEvents;
  }

  @Override
  public void setTitle(String title) {
    Element containerElement = getContainerElement();
    if (title == null || title.length() == 0) {
      containerElement.removeAttribute("title");
    } else {
      containerElement.setAttribute("title", title);
    }
  }

  /**
   * Sets whether this object is visible. This method just sets the
   * visibility style attribute. You need to call {@link #show()}
   * to actually attached/detach the {@link PopupPanel} to the page.
   *
   * @param visible true to show the object, false to
   *          hide it
   * @see #show()
   * @see #hide()
   */
  @Override
  public void setVisible(boolean visible) {
    // We use visibility here instead of UIObject's default of display
    // Because the panel is absolutely positioned, this will not create
    // "holes" in displayed contents and it allows normal layout passes
    // to occur so the size of the PopupPanel can be reliably determined.
    DOM.setStyleAttribute(getElement(), "visibility", visible ? "visible"
        : "hidden");

    // If the PopupImpl creates an iframe shim, it's also necessary to hide it
    // as well.
    impl.setVisible(getElement(), visible);
    if (glass != null) {
      impl.setVisible(glass, visible);
      glass.getStyle().setProperty("visibility", visible ? "visible" : "hidden");
    }
  }

  @Override
  public void setWidget(Widget w) {
    super.setWidget(w);
    maybeUpdateSize();
  }

  /**
   * Sets the width of the panel's child widget. If the panel's child widget has
   * not been set, the width passed in will be cached and used to set the width
   * immediately after the child widget is set.
   *
   *

   * Note that subclasses may have a different behavior. A subclass may decide
   * not to change the width of the child widget. It may instead decide to
   * change the width of an internal panel widget, which contains the child
   * widget.
   *

   *
   * @param width the object's new width, in CSS units (e.g. "10px", "1em")
   */
  @Override
  public void setWidth(String width) {
    desiredWidth = width;
    maybeUpdateSize();
    // If the user cleared the size, revert to not trying to control children.
    if (width.length() == 0) {
      desiredWidth = null;
    }
  }

  /**
   * Shows the popup and attach it to the page. It must have a child widget
   * before this method is called.
   */
  public void show() {
    if (showing) {
      return;
    } else if (isAttached()) {
      // The popup is attached directly to another panel, so we need to remove
      // it from its parent before showing it. This is a weird use case, but
      // since PopupPanel is a Widget, its legal.
      this.removeFromParent();
    }
    resizeAnimation.setState(true, false);
  }

  /**
   * Normally, the popup is positioned directly below the relative target, with
   * its left edge aligned with the left edge of the target. Depending on the
   * width and height of the popup and the distance from the target to the
   * bottom and right edges of the window, the popup may be displayed directly
   * above the target, and/or its right edge may be aligned with the right edge
   * of the target.
   *
   * @param target the target to show the popup below
   */
  public final void showRelativeTo(final UIObject target) {
    // Set the position of the popup right before it is shown.
    setPopupPositionAndShow(new PositionCallback() {
      public void setPosition(int offsetWidth, int offsetHeight) {
        position(target, offsetWidth, offsetHeight);
      }
    });
  }

  @Override
  protected com.google.gwt.user.client.Element getContainerElement() {
    return impl.getContainerElement(getPopupImplElement()).cast();
  }

  /**
   * Get the glass element used by this {@link PopupPanel}. The element is not
   * created until it is enabled via {@link #setGlassEnabled(boolean)}.
   *
   * @return the glass element, or null if not created
   */
  protected Element getGlassElement() {
    return glass;
  }

  @Override
  protected com.google.gwt.user.client.Element getStyleElement() {
    return impl.getStyleElement(getPopupImplElement()).cast();
  }

  protected void onPreviewNativeEvent(NativePreviewEvent event) {
    // Cancel the event based on the deprecated onEventPreview() method
    if (event.isFirstHandler()
        && !onEventPreview(Event.as(event.getNativeEvent()))) {
      event.cancel();
    }
  }

  @Override
  protected void onUnload() {
    super.onUnload();

    // Just to be sure, we perform cleanup when the popup is unloaded (i.e.
    // removed from the DOM). This is normally taken care of in hide(), but it
    // can be missed if someone removes the popup directly from the RootPanel.
    if (isShowing()) {
      resizeAnimation.setState(false, true);
    }
  }

  /**
   * We control size by setting our child widget's size. However, if we don't
   * currently have a child, we record the size the user wanted so that when we
   * do get a child, we can set it correctly. Until size is explicitly cleared,
   * any child put into the popup will be given that size.
   */
  void maybeUpdateSize() {
    // For subclasses of PopupPanel, we want the default behavior of setWidth
    // and setHeight to change the dimensions of PopupPanel's child widget.
    // We do this because PopupPanel's child widget is the first widget in
    // the hierarchy which provides structure to the panel. DialogBox is
    // an example of this. We want to set the dimensions on DialogBox's
    // FlexTable, which is PopupPanel's child widget. However, it is not
    // DialogBox's child widget. To make sure that we are actually getting
    // PopupPanel's child widget, we have to use super.getWidget().
    Widget w = super.getWidget();
    if (w != null) {
      if (desiredHeight != null) {
        w.setHeight(desiredHeight);
      }
      if (desiredWidth != null) {
        w.setWidth(desiredWidth);
      }
    }
  }

  /**
   * Sets the animation used to animate this popup. Used by gwt-incubator to
   * allow DropDownPanel to override the default popup animation. Not protected
   * because the exact API may change in gwt 1.6.
   *
   * @param animation the animation to use for this popup
   */
  void setAnimation(ResizeAnimation animation) {
    resizeAnimation = animation;
  }

  /**
   * Enable or disable animation of the {@link PopupPanel}.
   *
   * @param type the type of animation to use
   */
  void setAnimationType(AnimationType type) {
    animType = type;
  }

  /**
   * Remove focus from an Element.
   *
   * @param elt The Element on which blur() will be invoked
   */
  private native void blur(Element elt) /*-{
    // Issue 2390: blurring the body causes IE to disappear to the background
    if (elt.blur && elt != $doc.body) {
      elt.blur();
    }
  }-*/;

  /**
   * Does the event target one of the partner elements?
   *
   * @param event the native event
   * @return true if the event targets a partner
   */
  private boolean eventTargetsPartner(NativeEvent event) {
    if (autoHidePartners == null) {
      return false;
    }

    EventTarget target = event.getEventTarget();
    if (Element.is(target)) {
      for (Element elem : autoHidePartners) {
        if (elem.isOrHasChild(Element.as(target))) {
          return true;
        }
      }
    }
    return false;
  }

  /**
   * Does the event target this popup?
   *
   * @param event the native event
   * @return true if the event targets the popup
   */
  private boolean eventTargetsPopup(NativeEvent event) {
    EventTarget target = event.getEventTarget();
    if (Element.is(target)) {
      return getElement().isOrHasChild(Element.as(target));
    }
    return false;
  }

  /**
   * Get the element that {@link PopupImpl} uses. PopupImpl creates an element
   * that goes inside of the outer element, so all methods in PopupImpl are
   * relative to the first child of the outer element, not the outer element
   * itself.
   *
   * @return the Element that {@link PopupImpl} creates and expects
   */
  private com.google.gwt.user.client.Element getPopupImplElement() {
    return DOM.getFirstChild(super.getContainerElement());
  }

  /**
   * Positions the popup, called after the offset width and height of the popup
   * are known.
   *
   * @param relativeObject the ui object to position relative to
   * @param offsetWidth the drop down's offset width
   * @param offsetHeight the drop down's offset height
   */
  private void position(final UIObject relativeObject, int offsetWidth,
      int offsetHeight) {
    // Calculate left position for the popup. The computation for
    // the left position is bidi-sensitive.

    int textBoxOffsetWidth = relativeObject.getOffsetWidth();

    // Compute the difference between the popup's width and the
    // textbox's width
    int offsetWidthDiff = offsetWidth - textBoxOffsetWidth;

    int left;

    if (LocaleInfo.getCurrentLocale().isRTL()) { // RTL case

      int textBoxAbsoluteLeft = relativeObject.getAbsoluteLeft();

      // Right-align the popup. Note that this computation is
      // valid in the case where offsetWidthDiff is negative.
      left = textBoxAbsoluteLeft - offsetWidthDiff;

      // If the suggestion popup is not as wide as the text box, always
      // align to the right edge of the text box. Otherwise, figure out whether
      // to right-align or left-align the popup.
      if (offsetWidthDiff > 0) {

        // Make sure scrolling is taken into account, since
        // box.getAbsoluteLeft() takes scrolling into account.
        int windowRight = Window.getClientWidth() + Window.getScrollLeft();
        int windowLeft = Window.getScrollLeft();

        // Compute the left value for the right edge of the textbox
        int textBoxLeftValForRightEdge = textBoxAbsoluteLeft
            + textBoxOffsetWidth;

        // Distance from the right edge of the text box to the right edge
        // of the window
        int distanceToWindowRight = windowRight - textBoxLeftValForRightEdge;

        // Distance from the right edge of the text box to the left edge of the
        // window
        int distanceFromWindowLeft = textBoxLeftValForRightEdge - windowLeft;

        // If there is not enough space for the overflow of the popup's
        // width to the right of the text box and there IS enough space for the
        // overflow to the right of the text box, then left-align the popup.
        // However, if there is not enough space on either side, stick with
        // right-alignment.
        if (distanceFromWindowLeft < offsetWidth
            && distanceToWindowRight >= offsetWidthDiff) {
          // Align with the left edge of the text box.
          left = textBoxAbsoluteLeft;
        }
      }
    } else { // LTR case

      // Left-align the popup.
      left = relativeObject.getAbsoluteLeft();

      // If the suggestion popup is not as wide as the text box, always align to
      // the left edge of the text box. Otherwise, figure out whether to
      // left-align or right-align the popup.
      if (offsetWidthDiff > 0) {
        // Make sure scrolling is taken into account, since
        // box.getAbsoluteLeft() takes scrolling into account.
        int windowRight = Window.getClientWidth() + Window.getScrollLeft();
        int windowLeft = Window.getScrollLeft();

        // Distance from the left edge of the text box to the right edge
        // of the window
        int distanceToWindowRight = windowRight - left;

        // Distance from the left edge of the text box to the left edge of the
        // window
        int distanceFromWindowLeft = left - windowLeft;

        // If there is not enough space for the overflow of the popup's
        // width to the right of hte text box, and there IS enough space for the
        // overflow to the left of the text box, then right-align the popup.
        // However, if there is not enough space on either side, then stick with
        // left-alignment.
        if (distanceToWindowRight < offsetWidth
            && distanceFromWindowLeft >= offsetWidthDiff) {
          // Align with the right edge of the text box.
          left -= offsetWidthDiff;
        }
      }
    }

    // Calculate top position for the popup

    int top = relativeObject.getAbsoluteTop();

    // Make sure scrolling is taken into account, since
    // box.getAbsoluteTop() takes scrolling into account.
    int windowTop = Window.getScrollTop();
    int windowBottom = Window.getScrollTop() + Window.getClientHeight();

    // Distance from the top edge of the window to the top edge of the
    // text box
    int distanceFromWindowTop = top - windowTop;

    // Distance from the bottom edge of the window to the bottom edge of
    // the text box
    int distanceToWindowBottom = windowBottom
        - (top + relativeObject.getOffsetHeight());

    // If there is not enough space for the popup's height below the text
    // box and there IS enough space for the popup's height above the text
    // box, then then position the popup above the text box. However, if there
    // is not enough space on either side, then stick with displaying the
    // popup below the text box.
    if (distanceToWindowBottom < offsetHeight
        && distanceFromWindowTop >= offsetHeight) {
      top -= offsetHeight;
    } else {
      // Position above the text box
      top += relativeObject.getOffsetHeight();
    }
    setPopupPosition(left, top);
  }

  /**
   * Preview the {@link NativePreviewEvent}.
   *
   * @param event the {@link NativePreviewEvent}
   */
  private void previewNativeEvent(NativePreviewEvent event) {
    // If the event has been canceled or consumed, ignore it
    if (event.isCanceled() || (!previewAllNativeEvents && event.isConsumed())) {
      // We need to ensure that we cancel the event even if its been consumed so
      // that popups lower on the stack do not auto hide
      if (modal) {
        event.cancel();
      }
      return;
    }

    // Fire the event hook and return if the event is canceled
    onPreviewNativeEvent(event);
    if (event.isCanceled()) {
      return;
    }

    // If the event targets the popup or the partner, consume it
    Event nativeEvent = Event.as(event.getNativeEvent());
    boolean eventTargetsPopupOrPartner = eventTargetsPopup(nativeEvent)
        || eventTargetsPartner(nativeEvent);
    if (eventTargetsPopupOrPartner) {
      event.consume();
    }

    // Cancel the event if it doesn't target the modal popup. Note that the
    // event can be both canceled and consumed.
    if (modal) {
      event.cancel();
    }

    // Switch on the event type
    int type = nativeEvent.getTypeInt();
    switch (type) {
      case Event.ONKEYDOWN: {
        if (!onKeyDownPreview((char) nativeEvent.getKeyCode(),
            KeyboardListenerCollection.getKeyboardModifiers(nativeEvent))) {
          event.cancel();
        }
        return;
      }
      case Event.ONKEYUP: {
        if (!onKeyUpPreview((char) nativeEvent.getKeyCode(),
            KeyboardListenerCollection.getKeyboardModifiers(nativeEvent))) {
          event.cancel();
        }
        return;
      }
      case Event.ONKEYPRESS: {
        if (!onKeyPressPreview((char) nativeEvent.getKeyCode(),
            KeyboardListenerCollection.getKeyboardModifiers(nativeEvent))) {
          event.cancel();
        }
        return;
      }

      case Event.ONMOUSEDOWN:
      case Event.ONTOUCHSTART:
        // Don't eat events if event capture is enabled, as this can
        // interfere with dialog dragging, for example.
        if (DOM.getCaptureElement() != null) {
          event.consume();
          return;
        }

        if (!eventTargetsPopupOrPartner && autoHide) {
          hide(true);
          return;
        }
        break;
      case Event.ONMOUSEUP:
      case Event.ONMOUSEMOVE:
      case Event.ONCLICK:
      case Event.ONDBLCLICK:
      case Event.ONTOUCHEND: {
        // Don't eat events if event capture is enabled, as this can
        // interfere with dialog dragging, for example.
        if (DOM.getCaptureElement() != null) {
          event.consume();
          return;
        }
        break;
      }

      case Event.ONFOCUS: {
        Element target = nativeEvent.getTarget();
        if (modal && !eventTargetsPopupOrPartner && (target != null)) {
          blur(target);
          event.cancel();
          return;
        }
        break;
      }
    }
  }

  /**
   * Register or unregister the handlers used by {@link PopupPanel}.
   */
  private void updateHandlers() {
    // Remove any existing handlers.
    if (nativePreviewHandlerRegistration != null) {
      nativePreviewHandlerRegistration.removeHandler();
      nativePreviewHandlerRegistration = null;
    }
    if (historyHandlerRegistration != null) {
      historyHandlerRegistration.removeHandler();
      historyHandlerRegistration = null;
    }

    // Create handlers if showing.
    if (showing) {
      nativePreviewHandlerRegistration = Event.addNativePreviewHandler(new NativePreviewHandler() {
        public void onPreviewNativeEvent(NativePreviewEvent event) {
          previewNativeEvent(event);
        }
      });
      historyHandlerRegistration = History.addValueChangeHandler(new ValueChangeHandler<String>() {
        public void onValueChange(ValueChangeEvent<String> event) {
          if (autoHideOnHistoryEvents) {
            hide();
          }
        }
      });
    }
  }
}


text:
using NUnit.Framework;
using ServiceStack.Common.Tests.Models;

namespace ServiceStack.Redis.Tests.Support
{
	public class CustomTypeFactory : ModelFactoryBase<CustomType>
	{
		public CustomTypeFactory()
		{
			ModelConfig<CustomType>.Id(x => x.CustomId);
		}

		public override void AssertIsEqual(CustomType actual, CustomType expected)
		{
			Assert.AreEqual(actual.CustomId, expected.CustomId);
			Assert.AreEqual(actual.CustomName, expected.CustomName);
		}

		public override CustomType CreateInstance(int i)
		{
			return new CustomType { CustomId = i, CustomName = "Name" + i };
		}
	}

}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Shaders</title>
    <meta name="description" content="Shaders">
    <script src="../../../dist/aframe-master.js"></script>
    <script src="shaders/noise.js"></script>
    <script src="shaders/sky.js"></script>
  </head>
  <body>
    <script>
      AFRAME.registerComponent('sun-position-setter', {
        init: function () {
          var skyEl = this.el;
          var orbitEl = this.el.sceneEl.querySelector('#orbit');

          orbitEl.addEventListener('componentchanged', function changeSun (evt) {
            var sunPosition;
            var phi;
            var theta;

            if (evt.detail.name !== 'rotation') { return; }

            sunPosition = orbitEl.getAttribute('rotation');

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

            theta = Math.PI * (- 0.5);
            phi = 2 * Math.PI * (sunPosition.y / 360 - 0.5);
            skyEl.setAttribute('material', 'sunPosition', {
              x: Math.cos(phi),
              y: Math.sin(phi) * Math.sin(theta),
              z: -1
            });
          });
        }
      });
    </script>

    <a-scene stats>
      <a-entity id="sky" geometry="primitive: sphere; radius: 100" material="shader: sky; side: back" sun-position-setter>
        <a-entity id="orbit" animation="property: rotation; to: 0 360 0; dur: 5000; loop: true; easing: linear"></a-entity>
      </a-entity>

      <a-entity geometry="primitive: sphere; radius: 3" material="shader: noise" position="0 0 -10" rotation="45 45 0">
      </a-entity>
    </a-scene>
  </body>
</html>


text:
import React from 'react'
import Helmet from 'react-helmet'
import Link from 'gatsby-link'
import get from 'lodash/get'

class BlogPostTemplate extends React.Component {
  render() {
    const post = this.props.data.markdownRemark
    const siteTitle = get(this.props, 'data.site.siteMetadata.title')

    return (

        <Helmet title={`${post.frontmatter.title} | ${siteTitle}`} />

{post.frontmatter.title}

          {post.frontmatter.date}

    )
  }
}

export default BlogPostTemplate

export const pageQuery = graphql`
  query BlogPostByPath($path: String!) {
    site {
      siteMetadata {
        title
        author
      }
    }
    markdownRemark(frontmatter: { path: { eq: $path } }) {
      id
      html
      frontmatter {
        title
        date(formatString: "MMMM DD, YYYY")
      }
    }
  }
`


text:
<title>Source Files - STABS</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="STABS">
<meta name="generator" content="makeinfo 4.8">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Program-Structure.html#Program-Structure" title="Program Structure">
<link rel="prev" href="Main-Program.html#Main-Program" title="Main Program">
<link rel="next" href="Include-Files.html#Include-Files" title="Include Files">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Next: Include Files,
Previous: Main Program,
Up: Program Structure

2.2 Paths and Names of the Source Files

Before any other stabs occur, there must be a stab specifying the source
file.  This information is contained in a symbol of stab type
N_SO; the string field contains the name of the file.  The
value of the symbol is the start address of the portion of the
text section corresponding to that file.

Some compilers use the desc field to indicate the language of the
source file.  Sun's compilers started this usage, and the first
constants are derived from their documentation.  Languages added
by gcc/gdb start at 0x32 to avoid conflict with languages Sun may
add in the future.  A desc field with a value 0 indicates that no
language has been specified via this mechanism.

N_SO_AS (0x1)
Assembly language

N_SO_C  (0x2)
K&R traditional C

N_SO_ANSI_C (0x3)
ANSI C

N_SO_CC  (0x4)
C++

N_SO_FORTRAN (0x5)
Fortran

N_SO_PASCAL (0x6)
Pascal

N_SO_FORTRAN90 (0x7)
Fortran90

N_SO_OBJC (0x32)
Objective-C

N_SO_OBJCPLUS (0x33)
Objective-C++

Some compilers (for example, GCC2 and SunOS4 <samp>/bin/cc</samp>) also
include the directory in which the source was compiled, in a second
N_SO symbol preceding the one containing the file name.  This
symbol can be distinguished by the fact that it ends in a slash.  Code
from the cfront C<tt>++</tt> compiler can have additional N_SO symbols for
nonexistent source files after the N_SO for the real source file;
these are believed to contain no useful information.

For example:

     .stabs "/cygint/s1/users/jcm/play/",100,0,0,Ltext0     # 100 is N_SO
     .stabs "hello.c",100,0,0,Ltext0
             .text
     Ltext0:

Instead of N_SO symbols, XCOFF uses a .file assembler
directive which assembles to a C_FILE symbol; explaining this in
detail is outside the scope of this document.

If it is useful to indicate the end of a source file, this is done with
an N_SO symbol with an empty string for the name.  The value is
the address of the end of the text section for the file.  For some
systems, there is no indication of the end of a source file, and you
just need to figure it ended when you see an N_SO for a different
source file, or a symbol ending in .o (which at least some
linkers insert to mark the start of a new .o file).


text:
#include "fsl_debug_console.h"
#include "board.h"

#include "fsl_lptmr.h"
#include "fsl_gpio.h"

#include "pin_mux.h"
#include "clock_config.h"
/*******************************************************************************
 * Definitions
 ******************************************************************************/
#define LPTMR_LED_HANDLER LPTMR0_IRQHandler
/* Get source clock for LPTMR driver */
#define LPTMR_SOURCE_CLOCK CLOCK_GetFreq(kCLOCK_LpoClk)
/* Define LPTMR microseconds counts value */
#define LPTMR_USEC_COUNT 1000000U
#define LED_INIT() LED_RED_INIT(LOGIC_LED_ON)
#define LED_TOGGLE() LED_RED_TOGGLE()

/*******************************************************************************
 * Prototypes
 ******************************************************************************/

/*******************************************************************************
 * Variables
 ******************************************************************************/

volatile uint32_t lptmrCounter = 0U;

/*******************************************************************************
 * Code
 ******************************************************************************/
void LPTMR_LED_HANDLER(void)
{
    LPTMR_ClearStatusFlags(LPTMR0, kLPTMR_TimerCompareFlag);
    lptmrCounter++;
    LED_TOGGLE();
    /*
     * Workaround for TWR-KV58: because write buffer is enabled, adding
     * memory barrier instructions to make sure clearing interrupt flag completed
     * before go out ISR
     */
    __DSB();
    __ISB();
}

/*!
 * @brief Main function
 */
int main(void)
{
    uint32_t currentCounter = 0U;
    lptmr_config_t lptmrConfig;

    LED_INIT();

    /* Board pin, clock, debug console init */
    BOARD_InitPins();
    BOARD_BootClockRUN();
    BOARD_InitDebugConsole();

    /* Configure LPTMR */
    /*
     * lptmrConfig.timerMode = kLPTMR_TimerModeTimeCounter;
     * lptmrConfig.pinSelect = kLPTMR_PinSelectInput_0;
     * lptmrConfig.pinPolarity = kLPTMR_PinPolarityActiveHigh;
     * lptmrConfig.enableFreeRunning = false;
     * lptmrConfig.bypassPrescaler = true;
     * lptmrConfig.prescalerClockSource = kLPTMR_PrescalerClock_1;
     * lptmrConfig.value = kLPTMR_Prescale_Glitch_0;
     */
    LPTMR_GetDefaultConfig(&lptmrConfig);

    /* Initialize the LPTMR */
    LPTMR_Init(LPTMR0, &lptmrConfig);

    /*
     * Set timer period.
     * Note : the parameter "ticks" of LPTMR_SetTimerPeriod should be equal or greater than 1.
    */
    LPTMR_SetTimerPeriod(LPTMR0, USEC_TO_COUNT(LPTMR_USEC_COUNT, LPTMR_SOURCE_CLOCK));

    /* Enable timer interrupt */
    LPTMR_EnableInterrupts(LPTMR0, kLPTMR_TimerInterruptEnable);

    /* Enable at the NVIC */
    EnableIRQ(LPTMR0_IRQn);

    PRINTF("Low Power Timer Example\r\n");

    /* Start counting */
    LPTMR_StartTimer(LPTMR0);
    while (1)
    {
        if (currentCounter != lptmrCounter)
        {
            currentCounter = lptmrCounter;
            PRINTF("LPTMR interrupt No.%d \r\n", currentCounter);
        }
    }
}


text:
Example of cross-account, same-region, S3 bucket replication (v2) using server-side encryption with customer-managed KMS keys.

![Diagram](./images/s3-replication-diagram.png)

## Notes

- The source and destination resources should be deployed to the same region in different AWS Accounts.
- Deploy the destination account resources first.
- The destination S3 bucket must exist before configuring replication on the source bucket.
- CloudFormation stack name: replication-demo
- Source bucket name syntax: {stack-name}-{source-account}-bucket
- Destination bucket name syntax: {stack-name}-{destination-account}-bucket

## Resources

- [Amazon S3 - Replicating objects](https://docs.aws.amazon.com/AmazonS3/latest/userguide/replication.html)
- [Changing the replica owner](https://docs.aws.amazon.com/AmazonS3/latest/userguide/replication-change-owner.html)
- [Replicating objects created with server-side encryption (SSE) using KMS keys](https://docs.aws.amazon.com/AmazonS3/latest/userguide/replication-config-for-kms-objects.html)

## Instructions

1. The source and destination resources should be deployed to the same region in different AWS Accounts.
1. The CloudFormation stack names must be the same in both accounts. This is because of the resource naming convention used in the example templates.
1. Deploy the destination.yml template by using CloudFormation in the destination account. The destination S3 bucket must exist before configuring a replication rule on the source bucket.
    1. Name the stack "replication-demo".
    1. Enter the AWS Account Id of the source account in the AccountIdSource parameter.
    1. The destination bucket will be named: replication-demo-{destination-account}-bucket
1. Deploy the source.yml template by using CloudFormation in the source account.
    1. Be sure to select the same region as the destination account resources.
    1. Name the stack "replication-demo".
    1. Enter the AWS Account Id of the destination account in the AccountIdDestination parameter.
    1. The source bucket will be named: replication-demo-{source-account}-bucket

## Testing

Upload objects to the source account S3 bucket. After a couple mins, the objects should be replicated to the destination account S3 bucket.


text:
using ppapi::InputEventData;
using ppapi::PPB_InputEvent_Shared;
using ppapi::StringVar;

namespace content {

ResourceCreationImpl::ResourceCreationImpl(PepperPluginInstanceImpl* instance) {
}

ResourceCreationImpl::~ResourceCreationImpl() {}

PP_Resource ResourceCreationImpl::CreateAudio1_0(
    PP_Instance instance,
    PP_Resource config_id,
    PPB_Audio_Callback_1_0 audio_callback,
    void* user_data) {
  return 0;  // Not supported in-process.
}

PP_Resource ResourceCreationImpl::CreateAudio(PP_Instance instance,
                                              PP_Resource config_id,
                                              PPB_Audio_Callback audio_callback,
                                              void* user_data) {
  return 0;  // Not supported in-process.
}

PP_Resource ResourceCreationImpl::CreateAudioConfig(
    PP_Instance instance,
    PP_AudioSampleRate sample_rate,
    uint32_t sample_frame_count) {
  return ppapi::PPB_AudioConfig_Shared::Create(
      ppapi::OBJECT_IS_IMPL, instance, sample_rate, sample_frame_count);
}

PP_Resource ResourceCreationImpl::CreateAudioTrusted(PP_Instance instance) {
  return (new PPB_Audio_Impl(instance))->GetReference();
}

PP_Resource ResourceCreationImpl::CreateAudioInput(PP_Instance instance) {
  return 0;  // Not supported in-process.
}

PP_Resource ResourceCreationImpl::CreateAudioOutput(PP_Instance instance) {
  return 0;  // Not supported in-process.
}

PP_Resource ResourceCreationImpl::CreateBuffer(PP_Instance instance,
                                               uint32_t size) {
  return PPB_Buffer_Impl::Create(instance, size);
}

PP_Resource ResourceCreationImpl::CreateCameraDevicePrivate(
    PP_Instance instance) {
  return 0;  // Not supported in-process.
}

PP_Resource ResourceCreationImpl::CreateGraphics3D(PP_Instance instance,
                                                   PP_Resource share_context,
                                                   const int32_t* attrib_list) {
  return 0;  // Not supported in-process.
}

PP_Resource ResourceCreationImpl::CreateGraphics3DRaw(
    PP_Instance instance,
    PP_Resource share_context,
    const gpu::ContextCreationAttribs& attrib_helper,
    gpu::Capabilities* capabilities,
    const base::UnsafeSharedMemoryRegion** shared_state,
    gpu::CommandBufferId* command_buffer_id) {
  return PPB_Graphics3D_Impl::CreateRaw(instance, share_context, attrib_helper,
                                        capabilities, shared_state,
                                        command_buffer_id);
}

PP_Resource ResourceCreationImpl::CreateHostResolver(PP_Instance instance) {
  return 0;  // Not supported in-process.
}

PP_Resource ResourceCreationImpl::CreateHostResolverPrivate(
    PP_Instance instance) {
  return 0;  // Not supported in-process.
}

PP_Resource ResourceCreationImpl::CreateImageData(PP_Instance instance,
                                                  PP_ImageDataFormat format,
                                                  const PP_Size* size,
                                                  PP_Bool init_to_zero) {
#if BUILDFLAG(IS_WIN)
  // If Win32K lockdown mitigations are enabled for Windows 8 and beyond,
  // we use the SIMPLE image data type as the PLATFORM image data type
  // calls GDI functions to create DIB sections etc which fail in Win32K
  // lockdown mode.
  if (base::win::GetVersion() >= base::win::Version::WIN8)
    return CreateImageDataSimple(instance, format, size, init_to_zero);
#endif
  return PPB_ImageData_Impl::Create(instance,
                                    ppapi::PPB_ImageData_Shared::PLATFORM,
                                    format,
                                    *size,
                                    init_to_zero);
}

PP_Resource ResourceCreationImpl::CreateImageDataSimple(
    PP_Instance instance,
    PP_ImageDataFormat format,
    const PP_Size* size,
    PP_Bool init_to_zero) {
  return PPB_ImageData_Impl::Create(instance,
                                    ppapi::PPB_ImageData_Shared::SIMPLE,
                                    format,
                                    *size,
                                    init_to_zero);
}

PP_Resource ResourceCreationImpl::CreateIMEInputEvent(
    PP_Instance instance,
    PP_InputEvent_Type type,
    PP_TimeTicks time_stamp,
    struct PP_Var text,
    uint32_t segment_number,
    const uint32_t* segment_offsets,
    int32_t target_segment,
    uint32_t selection_start,
    uint32_t selection_end) {
  return PPB_InputEvent_Shared::CreateIMEInputEvent(ppapi::OBJECT_IS_IMPL,
                                                    instance,
                                                    type,
                                                    time_stamp,
                                                    text,
                                                    segment_number,
                                                    segment_offsets,
                                                    target_segment,
                                                    selection_start,
                                                    selection_end);
}

PP_Resource ResourceCreationImpl::CreateKeyboardInputEvent_1_0(
    PP_Instance instance,
    PP_InputEvent_Type type,
    PP_TimeTicks time_stamp,
    uint32_t modifiers,
    uint32_t key_code,
    struct PP_Var character_text) {
  PP_Var code = StringVar::StringToPPVar("");
  return PPB_InputEvent_Shared::CreateKeyboardInputEvent(ppapi::OBJECT_IS_IMPL,
                                                         instance,
                                                         type,
                                                         time_stamp,
                                                         modifiers,
                                                         key_code,
                                                         character_text,
                                                         code);
}

PP_Resource ResourceCreationImpl::CreateKeyboardInputEvent_1_2(
    PP_Instance instance,
    PP_InputEvent_Type type,
    PP_TimeTicks time_stamp,
    uint32_t modifiers,
    uint32_t key_code,
    struct PP_Var character_text,
    struct PP_Var code) {
  return PPB_InputEvent_Shared::CreateKeyboardInputEvent(ppapi::OBJECT_IS_IMPL,
                                                         instance,
                                                         type,
                                                         time_stamp,
                                                         modifiers,
                                                         key_code,
                                                         character_text,
                                                         code);
}

PP_Resource ResourceCreationImpl::CreateMediaStreamVideoTrack(
    PP_Instance instance) {
  return 0;  // Not supported in-process.
}

PP_Resource ResourceCreationImpl::CreateMouseInputEvent(
    PP_Instance instance,
    PP_InputEvent_Type type,
    PP_TimeTicks time_stamp,
    uint32_t modifiers,
    PP_InputEvent_MouseButton mouse_button,
    const PP_Point* mouse_position,
    int32_t click_count,
    const PP_Point* mouse_movement) {
  return PPB_InputEvent_Shared::CreateMouseInputEvent(ppapi::OBJECT_IS_IMPL,
                                                      instance,
                                                      type,
                                                      time_stamp,
                                                      modifiers,
                                                      mouse_button,
                                                      mouse_position,
                                                      click_count,
                                                      mouse_movement);
}

PP_Resource ResourceCreationImpl::CreateNetAddressFromIPv4Address(
    PP_Instance instance,
    const PP_NetAddress_IPv4* ipv4_addr) {
  return 0;  // Not supported in-process.
}

PP_Resource ResourceCreationImpl::CreateNetAddressFromIPv6Address(
    PP_Instance instance,
    const PP_NetAddress_IPv6* ipv6_addr) {
  return 0;  // Not supported in-process.
}

PP_Resource ResourceCreationImpl::CreateNetAddressFromNetAddressPrivate(
    PP_Instance instance,
    const PP_NetAddress_Private& private_addr) {
  return 0;  // Not supported in-process.
}

PP_Resource ResourceCreationImpl::CreateNetworkMonitor(PP_Instance instance) {
  return 0;  // Not supported in-process.
}

PP_Resource ResourceCreationImpl::CreateTCPServerSocketPrivate(
    PP_Instance instance) {
  return 0;  // Not supported in-process.
}

PP_Resource ResourceCreationImpl::CreateTCPSocket1_0(PP_Instance instance) {
  return 0;  // Not supported in-process.
}

PP_Resource ResourceCreationImpl::CreateTCPSocket(PP_Instance instance) {
  return 0;  // Not supported in-process.
}

PP_Resource ResourceCreationImpl::CreateTCPSocketPrivate(PP_Instance instance) {
  return 0;  // Not supported in-process.
}

PP_Resource ResourceCreationImpl::CreateTouchInputEvent(PP_Instance instance,
                                                        PP_InputEvent_Type type,
                                                        PP_TimeTicks time_stamp,
                                                        uint32_t modifiers) {
  return PPB_InputEvent_Shared::CreateTouchInputEvent(
      ppapi::OBJECT_IS_IMPL, instance, type, time_stamp, modifiers);
}

PP_Resource ResourceCreationImpl::CreateUDPSocket(PP_Instance instance) {
  return 0;  // Not supported in-process.
}

PP_Resource ResourceCreationImpl::CreateUDPSocketPrivate(PP_Instance instance) {
  return 0;  // Not supported in-process.
}

PP_Resource ResourceCreationImpl::CreateVideoCapture(PP_Instance instance) {
  return 0;  // Not supported in-process.
}

PP_Resource ResourceCreationImpl::CreateVideoDecoder(PP_Instance instance) {
  return 0;  // Not supported in-process.
}

PP_Resource ResourceCreationImpl::CreateVideoDecoderDev(
    PP_Instance instance,
    PP_Resource graphics3d_id,
    PP_VideoDecoder_Profile profile) {
  return PPB_VideoDecoder_Impl::Create(instance, graphics3d_id, profile);
}

PP_Resource ResourceCreationImpl::CreateVideoEncoder(PP_Instance instance) {
  return 0;  // Not supported in-process.
}

PP_Resource ResourceCreationImpl::CreateVpnProvider(PP_Instance instance) {
  return 0;  // Not supported in-process.
}

PP_Resource ResourceCreationImpl::CreateWheelInputEvent(
    PP_Instance instance,
    PP_TimeTicks time_stamp,
    uint32_t modifiers,
    const PP_FloatPoint* wheel_delta,
    const PP_FloatPoint* wheel_ticks,
    PP_Bool scroll_by_page) {
  return PPB_InputEvent_Shared::CreateWheelInputEvent(ppapi::OBJECT_IS_IMPL,
                                                      instance,
                                                      time_stamp,
                                                      modifiers,
                                                      wheel_delta,
                                                      wheel_ticks,
                                                      scroll_by_page);
}

PP_Resource ResourceCreationImpl::CreateX509CertificatePrivate(
    PP_Instance instance) {
  return 0;  // Not supported in-process.
}

}  // namespace content


text:
|Build Status|Download|
|---|---
|[![Build Status](https://img.shields.io/travis/Kxnrl/Mapchooser-Redux/master.svg?style=flat-square)](https://travis-ci.org/Kxnrl/Mapchooser-Redux?branch=master) |[![Download](https://static.kxnrl.com/images/web/buttons/download.png)](https://build.kxnrl.com/MapChooser-Redux/)

### Features
* Vote next map
* Rock the vote to change map or extend map
* Nominate map to vote pool
* Map attributes
* Party block

### ConVars
- **mcr_timer_location**  - Timer Location of HUD.
- **mcr_include_nametag** - Include name tag in map desc.
- **mcr_include_desctag** - Include desc tag in map desc.
- **mcr_rectplayed_interval** - How much time in hours ago played can count to recently played pool, (-1 disable all recently played function.
- **mcr_rectplayed_ltp_mtpl** - What percentage increase of nomination map price for recently played.
- **mcr_partyblock_enabled** - Enable or not party block fuction.
- **mcr_map_extend_times** - How many times can extend the map.
- **mcr_delete_offical**  - Auto-delete offical maps.
- **mcr_generate_mapcycle** - Auto-generate map list in mapcycle.txt.
- **mcr_generate_mapgroup** - Auto-generate map group in gamemodes_server.txt.

### Configs
* map pool in mapcycle.txt by default, you can edit it in 'addons/sourcemod/configs/maplist.cfg'
* map data 'addons/sourcemod/configs/mapdata.txt'
* if mapdata.txt does not exists, data will be auto-generated  [example](https://github.com/PuellaMagi/Server-Data/blob/master/ZombieEscape/mapdata.txt)

### Credit
[Alliedmodders](https://github.com/alliedmodders) - Developed the original Mapchooser.
[powerlord](https://github.com/powerlord/sourcemod-mapchooser-extended) - Developed the original Mapchooser Extended.


text:
<?php

namespace TheIconic\Tracking\GoogleAnalytics\Parameters\EnhancedEcommerce;

use TheIconic\Tracking\GoogleAnalytics\Parameters\SingleParameter;

/**
 * Class Affiliation
 *
 * @link https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#ta
 *
 * @package TheIconic\Tracking\GoogleAnalytics\Parameters\EnhancedEcommerce
 */
class Affiliation extends SingleParameter
{
    /**
     * @inheritDoc
     *
     * @var string
     */
    protected $name = 'ta';
}


text:
/*global InputValidationError, StyledElements, TextInputInterface*/

(function () {

    "use strict";

    var VERSION_RE = /^([1-9]\d*|0)(?:\.([1-9]\d*|0))*$/;

    var VersionInputInterface = function VersionInputInterface(fieldId, options) {
        if (options == null) {
            options = {};
        }

        if (options.placeholder == null) {
            options.placeholder = '1.0';
        }

        TextInputInterface.call(this, fieldId, options);
    };
    VersionInputInterface.prototype = new TextInputInterface();

    VersionInputInterface.prototype._checkValue = function _checkValue(newValue) {
        if (newValue.match(VERSION_RE) != null) {
            return InputValidationError.NO_ERROR;
        } else {
            return InputValidationError.VERSION_ERROR;
        }
    };

    StyledElements.VersionInputInterface = VersionInputInterface;

})();


text:
package de.brockhaus.m2m.receiver.mqtt;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttTopic;

public class MQTTSubscriptionCallBack implements MqttCallback {

	public void connectionLost(Throwable cause) {
	}

	public void messageArrived(MqttTopic topic, MqttMessage message) {
		System.out.println("Message arrived. Topic: " + topic.getName()
				+ " Message: " + message.toString());

		if ("home/LWT".equals(topic.getName())) {
			System.err.println("Sensor gone!");
		}
	}

	@Override
	public void deliveryComplete(IMqttDeliveryToken token) {
		// TODO Auto-generated method stub

	}

	@Override
	public void messageArrived(String topic, MqttMessage message) throws Exception {
		System.out.println("message arrived");
		System.out.println("Message arrived. Topic: " + topic
				+ " Message: " + message.toString());

	}
}


text:
/*
  i2p garlic tunnel implementation
*/
package tunnel


text:
class Feedback < ActiveRecord::Base

  belongs_to :author, :class_name => "Person"

  validates_presence_of :content, :author_id, :url

end


text:
require 'spec_helper'

BENCHMARK = false
METAGRAMMAR_PATH = File.expand_path('../../../lib/treetop/compiler/metagrammar.treetop', __FILE__)

module CircularCompilationSpec
  describe "a parser for the metagrammar" do
    attr_reader :parser

    before do
      @parser = Treetop::Compiler::MetagrammarParser.new
    end

    it "can parse the metagrammar.treetop whence it was generated" do
      File.open(METAGRAMMAR_PATH, 'r') do |f|
        metagrammar_source = f.read
        result = parser.parse(metagrammar_source)
        result.should_not be_nil

        # generated_parser = result.compile
        # Object.class_eval(generated_parser)
        # parser_2 = Treetop::Compiler::MetagrammarParser.new
        # optionally_benchmark do
        #   result = parser_2.parse(metagrammar_source)
        #   result.should_not be_nil
        # end
      end
    end
  end
end


text:
libdir = File.dirname(__FILE__)
$LOAD_PATH.unshift(libdir) unless $LOAD_PATH.include?(libdir)

require 'ledger_web/price_lookup'
require 'ledger_web/config'
require 'ledger_web/db'
require 'ledger_web/report'
require 'ledger_web/table'
require 'ledger_web/decorators'
require 'ledger_web/watcher'
require 'ledger_web/helpers'
require 'ledger_web/app'


text:
"""
Python script that converts Burp Suite HTTP proxy history files to CSV or HTML files
"""
from __future__ import unicode_literals
from __future__ import print_function

import sys
import io
import argparse
import html
import base64

import xmltodict
from backports import csv

_g_csv_delimiter = ','

def main():
    args = parse_arguments()
    set_csv_delimiter(args.csv_delimiter)
    format_handler = FORMATS[args.format](args.filename)
    http_history = parse_http_history(args.filename)
    convert_to_output_file(http_history, format_handler)

def parse_arguments():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('filename', help='Burp Suite HTTP proxy history file')
    parser.add_argument('--format', default='html', choices=FORMATS.keys(),
                        help='output format, default: html')
    parser.add_argument('--csv-delimiter', choices=(',', ';'),
                        help='CSV delimiter, default: ,')
    return parser.parse_args()

def convert_to_output_file(http_history, format_handler):
    with io.open(format_handler.filename, 'w', encoding='utf-8', newline='') as output_file:
        format_handler.set_output_file(output_file)
        format_handler.header_prefix()
        format_handler.header_column('Time')
        format_handler.header_column('URL')
        format_handler.header_column('Hostname')
        format_handler.header_column('IP address')
        format_handler.header_column('Port')
        format_handler.header_column('Protocol')
        format_handler.header_column('Method')
        format_handler.header_column('Path')
        format_handler.header_column('Extension')
        format_handler.header_column('Request')
        format_handler.header_column('Status')
        format_handler.header_column('Response length')
        format_handler.header_column('MIME type')
        format_handler.header_column('Response')
        format_handler.header_column('Comment')
        format_handler.header_suffix()
        for line in http_history['items']['item']:
            format_handler.row_prefix()
            format_handler.row_column(line['time'])
            format_handler.row_column(line['url'])
            format_handler.row_column(line['host']['#text'])
            format_handler.row_column(line['host']['@ip'])
            format_handler.row_column(line['port'])
            format_handler.row_column(line['protocol'])
            format_handler.row_column(line['method'])
            format_handler.row_column(line['path'])
            format_handler.row_column(line['extension'])
            if '#text' in line['request']:
                format_handler.row_column(line['request']['#text'], encoded=True)
            else:
                format_handler.row_column("None")
            format_handler.row_column(line['status'])
            format_handler.row_column(line['responselength'])
            format_handler.row_column(line['mimetype'])
            if '#text' in line['response']:
                format_handler.row_column(line['response']['#text'], encoded=True)
            else:
                format_handler.row_column("None")
            format_handler.row_column(line['comment'])
            format_handler.row_suffix()
        format_handler.footer()

def parse_http_history(filename):
    with open(filename, 'rb') as f:
        return xmltodict.parse(f)

def base64decode(line):
    decoded = base64.b64decode(line)
    replace = 'backslashreplace' if sys.version_info[0] >= 3 else 'replace'
    return decoded.decode('UTF-8', errors=replace)

def set_csv_delimiter(csv_delimiter):
    if csv_delimiter:
        global _g_csv_delimiter
        _g_csv_delimiter = unicode(csv_delimiter)

class FormatHandlerBase(object):
    def __init__(self, filename):
        self.filename = filename + self.FILENAME_SUFFIX

class HtmlFormatHandler(FormatHandlerBase):
    FILENAME_SUFFIX = '.html'
    HEADER = '''<!DOCTYPE html>

    <title>Burp Suite proxy history</title>

'''
    FOOTER = '''

'''

    def set_output_file(self, output_file):
        self.output_file = output_file

    def header_prefix(self):
        print(self.HEADER,
              file=self.output_file)

    def header_suffix(self):
        print('

',
              file=self.output_file)

    def header_column(self, column_name):
        print('%s	' % column_name,
              file=self.output_file)

    def row_prefix(self):
        print('
', file=self.output_file)

    def row_suffix(self):
        print('
', file=self.output_file)

    def row_column(self, content, encoded=False):
        template = '%s	' if not encoded else '
%s
	'
        if encoded:
            content = html.escape(base64decode(content))
        print(template % content,
              file=self.output_file)

    def footer(self):
        print(self.FOOTER,
              file=self.output_file)

# note that total number of characters that an Excel cell can contain is 32,760
class CsvFormatHandler(FormatHandlerBase):
    FILENAME_SUFFIX = '.csv'

    def set_output_file(self, output_file):
        self.writer = csv.writer(output_file, dialect='excel',
                                 delimiter=_g_csv_delimiter)
        self.header = []

    def header_prefix(self):
        pass

    def header_suffix(self):
        self.writer.writerow(self.header)

    def header_column(self, column_name):
        self.header.append(column_name)

    def row_prefix(self):
        self.row = []

    def row_suffix(self):
        self.writer.writerow(self.row)

    def row_column(self, content, encoded=False):
        if content and encoded:
            content = base64decode(content)
        # total number of characters that an Excel cell can contain is 32,760
        if content and len(content) > 32760:
            content = content[:32744] + '..[TRUNCATED!]'
        self.row.append(content)

    def footer(self):
        pass

FORMATS = {
    'html': HtmlFormatHandler,
    'csv': CsvFormatHandler,
}

if __name__ == '__main__':
    # In python 3, unicode is renamed to str
    if sys.version_info[0] >= 3:
      unicode = str
    main()