text:
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.content.browser.webcontents;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcel;
import android.os.ParcelUuid;
import android.os.Parcelable;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.ViewStructure;

import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;

import org.chromium.base.Log;
import org.chromium.base.ObserverList;
import org.chromium.base.ThreadUtils;
import org.chromium.base.UserData;
import org.chromium.base.UserDataHost;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.blink_public.input.SelectionGranularity;
import org.chromium.content.browser.AppWebMessagePort;
import org.chromium.content.browser.GestureListenerManagerImpl;
import org.chromium.content.browser.MediaSessionImpl;
import org.chromium.content.browser.RenderCoordinatesImpl;
import org.chromium.content.browser.RenderWidgetHostViewImpl;
import org.chromium.content.browser.ViewEventSinkImpl;
import org.chromium.content.browser.WindowEventObserver;
import org.chromium.content.browser.WindowEventObserverManager;
import org.chromium.content.browser.accessibility.ViewStructureBuilder;
import org.chromium.content.browser.accessibility.WebContentsAccessibilityImpl;
import org.chromium.content.browser.framehost.RenderFrameHostDelegate;
import org.chromium.content.browser.framehost.RenderFrameHostImpl;
import org.chromium.content.browser.selection.SelectionPopupControllerImpl;
import org.chromium.content_public.browser.ChildProcessImportance;
import org.chromium.content_public.browser.ContentFeatureList;
import org.chromium.content_public.browser.GlobalRenderFrameHostId;
import org.chromium.content_public.browser.ImageDownloadCallback;
import org.chromium.content_public.browser.JavaScriptCallback;
import org.chromium.content_public.browser.MessagePayload;
import org.chromium.content_public.browser.MessagePort;
import org.chromium.content_public.browser.NavigationController;
import org.chromium.content_public.browser.RenderFrameHost;
import org.chromium.content_public.browser.StylusWritingHandler;
import org.chromium.content_public.browser.ViewEventSink.InternalAccessDelegate;
import org.chromium.content_public.browser.Visibility;
import org.chromium.content_public.browser.WebContents;
import org.chromium.content_public.browser.WebContentsInternals;
import org.chromium.content_public.browser.WebContentsObserver;
import org.chromium.ui.OverscrollRefreshHandler;
import org.chromium.ui.base.EventForwarder;
import org.chromium.ui.base.ViewAndroidDelegate;
import org.chromium.ui.base.WindowAndroid;
import org.chromium.ui.mojom.VirtualKeyboardMode;
import org.chromium.url.GURL;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

/**
 * The WebContentsImpl Java wrapper to allow communicating with the native WebContentsImpl
 * object.
 */
@JNINamespace("content")
public class WebContentsImpl implements WebContents, RenderFrameHostDelegate, WindowEventObserver {
    private static final String TAG = "WebContentsImpl";

    private static final String PARCEL_VERSION_KEY = "version";
    private static final String PARCEL_WEBCONTENTS_KEY = "webcontents";
    private static final String PARCEL_PROCESS_GUARD_KEY = "processguard";

    private static final long PARCELABLE_VERSION_ID = 0;
    // Non-final for testing purposes, so resetting of the UUID can happen.
    private static UUID sParcelableUUID = UUID.randomUUID();

    /**
     * Used to reset the internal tracking for whether or not a serialized {@link WebContents}
     * was created in this process or not.
     */
    @VisibleForTesting
    public static void invalidateSerializedWebContentsForTesting() {
        sParcelableUUID = UUID.randomUUID();
    }

    /**
     * A {@link android.os.Parcelable.Creator} instance that is used to build
     * {@link WebContentsImpl} objects from a {@link Parcel}.
     */
    // TODO(crbug.com/635567): Fix this properly.
    @SuppressLint("ParcelClassLoader")
    public static final Parcelable.Creator<WebContents> CREATOR =
            new Parcelable.Creator<WebContents>() {
                @Override
                public WebContents createFromParcel(Parcel source) {
                    Bundle bundle = source.readBundle();

                    // Check the version.
                    if (bundle.getLong(PARCEL_VERSION_KEY, -1) != 0) return null;

                    // Check that we're in the same process.
                    ParcelUuid parcelUuid = bundle.getParcelable(PARCEL_PROCESS_GUARD_KEY);
                    if (sParcelableUUID.compareTo(parcelUuid.getUuid()) != 0) return null;

                    // Attempt to retrieve the WebContents object from the native pointer.
                    return WebContentsImplJni.get().fromNativePtr(
                            bundle.getLong(PARCEL_WEBCONTENTS_KEY));
                }

                @Override
                public WebContents[] newArray(int size) {
                    return new WebContents[size];
                }
            };

    /**
     * Factory interface passed to {@link #getOrSetUserData()} for instantiation of
     * class as user data.
     *
     * Constructor method reference comes handy for class Foo to provide the factory.
     * Use lazy initialization to avoid having to generate too many anonymous references.
     *
     * <code>
     * public class Foo {
     *     static final class FoofactoryLazyHolder {
     *         private static final UserDataFactory<Foo> INSTANCE = Foo::new;
     *     }
     *     ....
     *
     *     webContents.getOrsetUserData(Foo.class, FooFactoryLazyHolder.INSTANCE);
     *
     *     ....
     * }
     * </code>
     *
     * @param <T> Class to instantiate.
     */
    public interface UserDataFactory<T> { T create(WebContents webContents); }

    // Note this list may be incomplete. Frames that never had to initialize java side would
    // not have an entry here. This is here mainly to keep the java RenderFrameHosts alive, since
    // native side generally cannot safely hold strong references to them.
    private final List<RenderFrameHostImpl> mFrames = new ArrayList<>();

    private long mNativeWebContentsAndroid;
    private NavigationController mNavigationController;

    // Lazily created proxy observer for handling all Java-based WebContentsObservers.
    private WebContentsObserverProxy mObserverProxy;

    // The media session for this WebContents. It is constructed by the native MediaSession and has
    // the same life time as native MediaSession.
    private MediaSessionImpl mMediaSession;

    class SmartClipCallback {
        public SmartClipCallback(final Handler smartClipHandler) {
            mHandler = smartClipHandler;
        }

        public void onSmartClipDataExtracted(String text, String html, Rect clipRect) {
            // The clipRect is in dip scale here. Add the contentOffset in same scale.
            RenderCoordinatesImpl coordinateSpace = getRenderCoordinates();
            clipRect.offset(0,
                    (int) (coordinateSpace.getContentOffsetYPix()
                            / coordinateSpace.getDeviceScaleFactor()));
            Bundle bundle = new Bundle();
            bundle.putString("url", getVisibleUrl().getSpec());
            bundle.putString("title", getTitle());
            bundle.putString("text", text);
            bundle.putString("html", html);
            bundle.putParcelable("rect", clipRect);

            Message msg = Message.obtain(mHandler, 0);
            msg.setData(bundle);
            msg.sendToTarget();
        }

        final Handler mHandler;
    }
    private SmartClipCallback mSmartClipCallback;

    private EventForwarder mEventForwarder;

    private StylusWritingHandler mStylusWritingHandler;

    // Cached copy of all positions and scales as reported by the renderer.
    private RenderCoordinatesImpl mRenderCoordinates;

    private InternalsHolder mInternalsHolder;

    private String mProductVersion;

    private boolean mInitialized;

    // Remember the stack for clearing native the native stack for debugging use after destroy.
    private Throwable mNativeDestroyThrowable;

    private ObserverList<Runnable> mTearDownDialogOverlaysHandlers;

    private static class WebContentsInternalsImpl implements WebContentsInternals {
        public UserDataHost userDataHost;
        public ViewAndroidDelegate viewAndroidDelegate;
    }

    private WebContentsImpl(
            long nativeWebContentsAndroid, NavigationController navigationController) {
        assert nativeWebContentsAndroid != 0;
        mNativeWebContentsAndroid = nativeWebContentsAndroid;
        mNavigationController = navigationController;
    }

    @CalledByNative
    @VisibleForTesting
    static WebContentsImpl create(
            long nativeWebContentsAndroid, NavigationController navigationController) {
        return new WebContentsImpl(nativeWebContentsAndroid, navigationController);
    }

    @Override
    public void initialize(String productVersion, ViewAndroidDelegate viewDelegate,
            InternalAccessDelegate accessDelegate, WindowAndroid windowAndroid,
            InternalsHolder internalsHolder) {
        assert internalsHolder != null;

        mProductVersion = productVersion;

        WebContentsInternalsImpl internals;
        if (mInternalsHolder != null) {
            internals = (WebContentsInternalsImpl) mInternalsHolder.get();
        } else {
            internals = new WebContentsInternalsImpl();
            internals.userDataHost = new UserDataHost();
        }
        mInternalsHolder = internalsHolder;
        mInternalsHolder.set(internals);

        if (mRenderCoordinates == null) {
            mRenderCoordinates = new RenderCoordinatesImpl();
        }

        mInitialized = true;

        setViewAndroidDelegate(viewDelegate);
        setTopLevelNativeWindow(windowAndroid);

        if (accessDelegate == null) {
            accessDelegate = new EmptyInternalAccessDelegate();
        }
        ViewEventSinkImpl.from(this).setAccessDelegate(accessDelegate);

        if (windowAndroid != null) {
            getRenderCoordinates().setDeviceScaleFactor(windowAndroid.getDisplay().getDipScale());
        }

        // Create GestureListenerManagerImpl so it updates `mRenderCoordinates`.
        GestureListenerManagerImpl.fromWebContents(this);
    }

    @Override
    public void clearJavaWebContentsObservers() {
        // Clear all the Android specific observers.
        if (mObserverProxy != null) {
            mObserverProxy.destroy();
            mObserverProxy = null;
        }
    }

    @Nullable
    public Context getContext() {
        assert mInitialized;

        WindowAndroid window = getTopLevelNativeWindow();
        return window != null ? window.getContext().get() : null;
    }

    public String getProductVersion() {
        assert mInitialized;
        return mProductVersion;
    }

    @CalledByNative
    @VisibleForTesting
    void clearNativePtr() {
        mNativeDestroyThrowable = new RuntimeException("clearNativePtr");
        mNativeWebContentsAndroid = 0;
        mNavigationController = null;
        if (mObserverProxy != null) {
            mObserverProxy.destroy();
            mObserverProxy = null;
        }
    }

    // =================== RenderFrameHostDelegate overrides ===================
    @Override
    public void renderFrameCreated(RenderFrameHostImpl host) {
        assert !mFrames.contains(host);
        mFrames.add(host);
    }

    @Override
    public void renderFrameDeleted(RenderFrameHostImpl host) {
        assert mFrames.contains(host);
        mFrames.remove(host);
    }
    // ================= end RenderFrameHostDelegate overrides =================

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        // This is wrapped in a Bundle so that failed deserialization attempts don't corrupt the
        // overall Parcel.  If we failed a UUID or Version check and didn't read the rest of the
        // fields it would corrupt the serialized stream.
        Bundle data = new Bundle();
        data.putLong(PARCEL_VERSION_KEY, PARCELABLE_VERSION_ID);
        data.putParcelable(PARCEL_PROCESS_GUARD_KEY, new ParcelUuid(sParcelableUUID));
        data.putLong(PARCEL_WEBCONTENTS_KEY, mNativeWebContentsAndroid);
        dest.writeBundle(data);
    }

    @CalledByNative
    private long getNativePointer() {
        return mNativeWebContentsAndroid;
    }

    @Override
    public WindowAndroid getTopLevelNativeWindow() {
        checkNotDestroyed();
        return WebContentsImplJni.get().getTopLevelNativeWindow(mNativeWebContentsAndroid);
    }

    @Override
    public void setTopLevelNativeWindow(WindowAndroid windowAndroid) {
        checkNotDestroyed();
        WebContentsImplJni.get().setTopLevelNativeWindow(mNativeWebContentsAndroid, windowAndroid);
        WindowEventObserverManager.from(this).onWindowAndroidChanged(windowAndroid);
        if (mObserverProxy != null) mObserverProxy.onTopLevelNativeWindowChanged(windowAndroid);
    }

    @Override
    public ViewAndroidDelegate getViewAndroidDelegate() {
        WebContentsInternals internals = mInternalsHolder.get();
        if (internals == null) return null;
        return ((WebContentsInternalsImpl) internals).viewAndroidDelegate;
    }

    private void setViewAndroidDelegate(ViewAndroidDelegate viewDelegate) {
        checkNotDestroyed();
        WebContentsInternals internals = mInternalsHolder.get();
        assert internals != null;
        WebContentsInternalsImpl impl = (WebContentsInternalsImpl) internals;
        impl.viewAndroidDelegate = viewDelegate;
        WebContentsImplJni.get().setViewAndroidDelegate(mNativeWebContentsAndroid, viewDelegate);
    }

    @Override
    public void destroy() {
        // Note that |WebContents.destroy| is not guaranteed to be invoked.
        // Any resource release relying on this method will likely be leaked.

        if (!ThreadUtils.runningOnUiThread()) {
            throw new IllegalStateException("Attempting to destroy WebContents on non-UI thread");
        }

        if (mObserverProxy != null && mObserverProxy.isHandlingObserverCall()) {
            throw new RuntimeException(
                    "Attempting to destroy WebContents while handling observer calls");
        }

        if (mNativeWebContentsAndroid != 0) {
            WebContentsImplJni.get().destroyWebContents(mNativeWebContentsAndroid);
        }
    }

    @Override
    public boolean isDestroyed() {
        return mNativeWebContentsAndroid == 0
                || WebContentsImplJni.get().isBeingDestroyed(mNativeWebContentsAndroid);
    }

    @Override
    public void clearNativeReference() {
        if (mNativeWebContentsAndroid != 0) {
            WebContentsImplJni.get().clearNativeReference(mNativeWebContentsAndroid);
        }
    }

    @Override
    public NavigationController getNavigationController() {
        return mNavigationController;
    }

    @Override
    public RenderFrameHost getMainFrame() {
        checkNotDestroyed();
        return WebContentsImplJni.get().getMainFrame(mNativeWebContentsAndroid);
    }

    @Override
    public RenderFrameHost getFocusedFrame() {
        checkNotDestroyed();
        return WebContentsImplJni.get().getFocusedFrame(mNativeWebContentsAndroid);
    }

    @Override
    public RenderFrameHost getRenderFrameHostFromId(GlobalRenderFrameHostId id) {
        checkNotDestroyed();
        return WebContentsImplJni.get().getRenderFrameHostFromId(
                mNativeWebContentsAndroid, id.childId(), id.frameRoutingId());
    }

    // The RenderFrameHosts that are every RenderFrameHost in this WebContents.
    // See C++'s WebContents::ForEachRenderFrameHost for details.
    public List<RenderFrameHost> getAllRenderFrameHosts() {
        checkNotDestroyed();
        RenderFrameHost[] frames =
                WebContentsImplJni.get().getAllRenderFrameHosts(mNativeWebContentsAndroid);
        return Collections.unmodifiableList(Arrays.asList(frames));
    }

    @CalledByNative
    private static RenderFrameHost[] createRenderFrameHostArray(int size) {
        return new RenderFrameHost[size];
    }

    @CalledByNative
    private static void addRenderFrameHostToArray(
            RenderFrameHost[] frames, int index, RenderFrameHost frame) {
        frames[index] = frame;
    }

    @Override
    public @Nullable RenderWidgetHostViewImpl getRenderWidgetHostView() {
        if (mNativeWebContentsAndroid == 0) return null;
        RenderWidgetHostViewImpl rwhvi =
                WebContentsImplJni.get().getRenderWidgetHostView(mNativeWebContentsAndroid);
        if (rwhvi == null || rwhvi.isDestroyed()) return null;

        return rwhvi;
    }

    @Override
    public List<WebContentsImpl> getInnerWebContents() {
        checkNotDestroyed();
        WebContentsImpl[] innerWebContents =
                WebContentsImplJni.get().getInnerWebContents(mNativeWebContentsAndroid);
        return Collections.unmodifiableList(Arrays.asList(innerWebContents));
    }

    @Override
    public @Visibility int getVisibility() {
        checkNotDestroyed();
        return WebContentsImplJni.get().getVisibility(mNativeWebContentsAndroid);
    }

    @Override
    public String getTitle() {
        checkNotDestroyed();
        return WebContentsImplJni.get().getTitle(mNativeWebContentsAndroid);
    }

    @Override
    public GURL getVisibleUrl() {
        checkNotDestroyed();
        return WebContentsImplJni.get().getVisibleURL(mNativeWebContentsAndroid);
    }

    @Override
    @VirtualKeyboardMode.EnumType
    public int getVirtualKeyboardMode() {
        checkNotDestroyed();
        return WebContentsImplJni.get().getVirtualKeyboardMode(mNativeWebContentsAndroid);
    }

    @Override
    public String getEncoding() {
        checkNotDestroyed();
        return WebContentsImplJni.get().getEncoding(mNativeWebContentsAndroid);
    }

    @Override
    public boolean isLoading() {
        checkNotDestroyed();
        return WebContentsImplJni.get().isLoading(mNativeWebContentsAndroid);
    }

    @Override
    public boolean shouldShowLoadingUI() {
        checkNotDestroyed();
        return WebContentsImplJni.get().shouldShowLoadingUI(mNativeWebContentsAndroid);
    }

    @Override
    public void dispatchBeforeUnload(boolean autoCancel) {
        if (mNativeWebContentsAndroid == 0) return;
        WebContentsImplJni.get().dispatchBeforeUnload(mNativeWebContentsAndroid, autoCancel);
    }

    @Override
    public void stop() {
        checkNotDestroyed();
        WebContentsImplJni.get().stop(mNativeWebContentsAndroid);
    }

    /**
     * Cut the selected content.
     */
    public void cut() {
        checkNotDestroyed();
        WebContentsImplJni.get().cut(mNativeWebContentsAndroid);
    }

    /**
     * Copy the selected content.
     */
    public void copy() {
        checkNotDestroyed();
        WebContentsImplJni.get().copy(mNativeWebContentsAndroid);
    }

    /**
     * Paste content from the clipboard.
     */
    public void paste() {
        checkNotDestroyed();
        WebContentsImplJni.get().paste(mNativeWebContentsAndroid);
    }

    /**
     * Paste content from the clipboard without format.
     */
    public void pasteAsPlainText() {
        checkNotDestroyed();
        WebContentsImplJni.get().pasteAsPlainText(mNativeWebContentsAndroid);
    }

    /**
     * Replace the selected text with the {@code word}.
     */
    public void replace(String word) {
        checkNotDestroyed();
        WebContentsImplJni.get().replace(mNativeWebContentsAndroid, word);
    }

    /**
     * Select all content.
     */
    public void selectAll() {
        checkNotDestroyed();
        WebContentsImplJni.get().selectAll(mNativeWebContentsAndroid);
    }

    /**
     * Collapse the selection to the end of selection range.
     */
    public void collapseSelection() {
        // collapseSelection may get triggered when certain selection-related widgets
        // are destroyed. As the timing for such destruction is unpredictable,
        // safely guard against this case.
        if (isDestroyed()) return;
        WebContentsImplJni.get().collapseSelection(mNativeWebContentsAndroid);
    }

    @Override
    public void onHide() {
        checkNotDestroyed();
        SelectionPopupControllerImpl controller = getSelectionPopupController();
        if (controller != null) controller.hidePopupsAndPreserveSelection();
        WebContentsImplJni.get().onHide(mNativeWebContentsAndroid);
    }

    @Override
    public void onShow() {
        checkNotDestroyed();
        WebContentsAccessibilityImpl wcax = WebContentsAccessibilityImpl.fromWebContents(this);
        if (wcax != null) {
            wcax.refreshState();
            if (ContentFeatureList.isEnabled(ContentFeatureList.AUTO_DISABLE_ACCESSIBILITY)) {
                wcax.updateAXModeFromNativeAccessibilityState();
            }
        }
        SelectionPopupControllerImpl controller = getSelectionPopupController();
        if (controller != null) controller.restoreSelectionPopupsIfNecessary();
        WebContentsImplJni.get().onShow(mNativeWebContentsAndroid);
    }

    private SelectionPopupControllerImpl getSelectionPopupController() {
        return SelectionPopupControllerImpl.fromWebContents(this);
    }

    @Override
    public void setImportance(@ChildProcessImportance int primaryMainFrameImportance) {
        checkNotDestroyed();
        WebContentsImplJni.get().setImportance(
                mNativeWebContentsAndroid, primaryMainFrameImportance);
    }

    @Override
    public void suspendAllMediaPlayers() {
        checkNotDestroyed();
        WebContentsImplJni.get().suspendAllMediaPlayers(mNativeWebContentsAndroid);
    }

    @Override
    public void setAudioMuted(boolean mute) {
        checkNotDestroyed();
        WebContentsImplJni.get().setAudioMuted(mNativeWebContentsAndroid, mute);
    }

    @Override
    public boolean focusLocationBarByDefault() {
        checkNotDestroyed();
        return WebContentsImplJni.get().focusLocationBarByDefault(mNativeWebContentsAndroid);
    }

    @Override
    public boolean isFullscreenForCurrentTab() {
        checkNotDestroyed();
        return WebContentsImplJni.get().isFullscreenForCurrentTab(mNativeWebContentsAndroid);
    }

    @Override
    public void exitFullscreen() {
        checkNotDestroyed();
        WebContentsImplJni.get().exitFullscreen(mNativeWebContentsAndroid);
    }

    @Override
    public void scrollFocusedEditableNodeIntoView() {
        checkNotDestroyed();
        // The native side keeps track of whether the zoom and scroll actually occurred. It is
        // more efficient to do it this way and sometimes fire an unnecessary message rather
        // than synchronize with the renderer and always have an additional message.
        WebContentsImplJni.get().scrollFocusedEditableNodeIntoView(mNativeWebContentsAndroid);
    }

    @Override
    public void selectAroundCaret(@SelectionGranularity int granularity, boolean shouldShowHandle,
            boolean shouldShowContextMenu) {
        checkNotDestroyed();
        WebContentsImplJni.get().selectAroundCaret(
                mNativeWebContentsAndroid, granularity, shouldShowHandle, shouldShowContextMenu);
    }

    @Override
    public void adjustSelectionByCharacterOffset(
            int startAdjust, int endAdjust, boolean showSelectionMenu) {
        WebContentsImplJni.get().adjustSelectionByCharacterOffset(
                mNativeWebContentsAndroid, startAdjust, endAdjust, showSelectionMenu);
    }

    @Override
    public GURL getLastCommittedUrl() {
        checkNotDestroyed();
        return WebContentsImplJni.get().getLastCommittedURL(mNativeWebContentsAndroid);
    }

    @Override
    public boolean isIncognito() {
        checkNotDestroyed();
        return WebContentsImplJni.get().isIncognito(mNativeWebContentsAndroid);
    }

    @Override
    public void resumeLoadingCreatedWebContents() {
        checkNotDestroyed();
        WebContentsImplJni.get().resumeLoadingCreatedWebContents(mNativeWebContentsAndroid);
    }

    @Override
    public void evaluateJavaScript(String script, JavaScriptCallback callback) {
        ThreadUtils.assertOnUiThread();
        if (isDestroyed() || script == null) return;
        WebContentsImplJni.get().evaluateJavaScript(mNativeWebContentsAndroid, script, callback);
    }

    @Override
    @VisibleForTesting
    public void evaluateJavaScriptForTests(String script, JavaScriptCallback callback) {
        ThreadUtils.assertOnUiThread();
        if (script == null) return;
        checkNotDestroyed();
        WebContentsImplJni.get().evaluateJavaScriptForTests(
                mNativeWebContentsAndroid, script, callback);
    }

    @Override
    public void addMessageToDevToolsConsole(int level, String message) {
        checkNotDestroyed();
        WebContentsImplJni.get().addMessageToDevToolsConsole(
                mNativeWebContentsAndroid, level, message);
    }

    @Override
    public void postMessageToMainFrame(MessagePayload messagePayload, String sourceOrigin,
            String targetOrigin, MessagePort[] ports) {
        if (ports != null) {
            for (MessagePort port : ports) {
                if (port.isClosed() || port.isTransferred()) {
                    throw new IllegalStateException("Port is already closed or transferred");
                }
                if (port.isStarted()) {
                    throw new IllegalStateException("Port is already started");
                }
            }
        }
        // Treat "*" as a wildcard. Internally, a wildcard is a empty string.
        if (targetOrigin.equals("*")) {
            targetOrigin = "";
        }
        WebContentsImplJni.get().postMessageToMainFrame(
                mNativeWebContentsAndroid, messagePayload, sourceOrigin, targetOrigin, ports);
    }

    @Override
    public AppWebMessagePort[] createMessageChannel()
            throws IllegalStateException {
        return AppWebMessagePort.createPair();
    }

    @Override
    public boolean hasAccessedInitialDocument() {
        checkNotDestroyed();
        return WebContentsImplJni.get().hasAccessedInitialDocument(mNativeWebContentsAndroid);
    }

    @CalledByNative
    private static void onEvaluateJavaScriptResult(
            String jsonResult, JavaScriptCallback callback) {
        callback.handleJavaScriptResult(jsonResult);
    }

    @Override
    public int getThemeColor() {
        checkNotDestroyed();
        return WebContentsImplJni.get().getThemeColor(mNativeWebContentsAndroid);
    }

    @Override
    public float getLoadProgress() {
        checkNotDestroyed();
        return WebContentsImplJni.get().getLoadProgress(mNativeWebContentsAndroid);
    }

    @Override
    public void requestSmartClipExtract(int x, int y, int width, int height) {
        if (mSmartClipCallback == null) return;
        checkNotDestroyed();
        RenderCoordinatesImpl coordinateSpace = getRenderCoordinates();
        float dpi = coordinateSpace.getDeviceScaleFactor();
        y = y - (int) coordinateSpace.getContentOffsetYPix();
        WebContentsImplJni.get().requestSmartClipExtract(mNativeWebContentsAndroid,
                mSmartClipCallback, (int) (x / dpi), (int) (y / dpi), (int) (width / dpi),
                (int) (height / dpi));
    }

    @Override
    public void setSmartClipResultHandler(final Handler smartClipHandler) {
        if (smartClipHandler == null) {
            mSmartClipCallback = null;
            return;
        }
        mSmartClipCallback = new SmartClipCallback(smartClipHandler);
    }

    @CalledByNative
    private static void onSmartClipDataExtracted(String text, String html, int left, int top,
            int right, int bottom, SmartClipCallback callback) {
        callback.onSmartClipDataExtracted(text, html, new Rect(left, top, right, bottom));
    }

    /**
     * Requests a snapshop of accessibility tree. The result is provided asynchronously
     * using the callback
     * @param callback The callback to be called when the snapshot is ready. The callback
     *                 cannot be null.
     */
    public void requestAccessibilitySnapshot(ViewStructure root, Runnable doneCallback) {
        checkNotDestroyed();
        ViewStructureBuilder builder = ViewStructureBuilder.create(mRenderCoordinates);

        WebContentsImplJni.get().requestAccessibilitySnapshot(
                mNativeWebContentsAndroid, root, builder, doneCallback);
    }

    @VisibleForTesting
    public void simulateRendererKilledForTesting() {
        if (mObserverProxy != null) {
            mObserverProxy.renderProcessGone();
        }
    }

    @Override
    public void setStylusWritingHandler(StylusWritingHandler stylusWritingHandler) {
        mStylusWritingHandler = stylusWritingHandler;
        if (mNativeWebContentsAndroid == 0) return;
        WebContentsImplJni.get().setStylusHandwritingEnabled(
                mNativeWebContentsAndroid, mStylusWritingHandler != null);
    }

    public StylusWritingHandler getStylusWritingHandler() {
        return mStylusWritingHandler;
    }

    @Override
    public EventForwarder getEventForwarder() {
        assert mNativeWebContentsAndroid != 0;
        if (mEventForwarder == null) {
            checkNotDestroyed();
            mEventForwarder =
                    WebContentsImplJni.get().getOrCreateEventForwarder(mNativeWebContentsAndroid);
            mEventForwarder.setStylusWritingDelegate(new EventForwarder.StylusWritingDelegate() {
                @Override
                public boolean handleTouchEvent(MotionEvent motionEvent) {
                    return mStylusWritingHandler != null
                            && mStylusWritingHandler.handleTouchEvent(
                                    motionEvent, getViewAndroidDelegate().getContainerView());
                }

                @Override
                public void handleHoverEvent(MotionEvent motionEvent) {
                    if (mStylusWritingHandler != null) {
                        mStylusWritingHandler.handleHoverEvent(
                                motionEvent, getViewAndroidDelegate().getContainerView());
                    }
                }
            });
        }
        return mEventForwarder;
    }

    @Override
    public void addObserver(WebContentsObserver observer) {
        assert mNativeWebContentsAndroid != 0;
        if (mObserverProxy == null) mObserverProxy = new WebContentsObserverProxy(this);
        mObserverProxy.addObserver(observer);
    }

    @Override
    public void removeObserver(WebContentsObserver observer) {
        if (mObserverProxy == null) return;
        mObserverProxy.removeObserver(observer);
    }

    @Override
    public void setOverscrollRefreshHandler(OverscrollRefreshHandler handler) {
        checkNotDestroyed();
        WebContentsImplJni.get().setOverscrollRefreshHandler(mNativeWebContentsAndroid, handler);
    }

    @Override
    public void setSpatialNavigationDisabled(boolean disabled) {
        checkNotDestroyed();
        WebContentsImplJni.get().setSpatialNavigationDisabled(mNativeWebContentsAndroid, disabled);
    }

    @Override
    public int downloadImage(GURL url, boolean isFavicon, int maxBitmapSize, boolean bypassCache,
            ImageDownloadCallback callback) {
        checkNotDestroyed();
        return WebContentsImplJni.get().downloadImage(
                mNativeWebContentsAndroid, url, isFavicon, maxBitmapSize, bypassCache, callback);
    }

    @CalledByNative
    private void onDownloadImageFinished(ImageDownloadCallback callback, int id, int httpStatusCode,
            GURL imageUrl, List<Bitmap> bitmaps, List<Rect> sizes) {
        callback.onFinishDownloadImage(id, httpStatusCode, imageUrl, bitmaps, sizes);
    }

    @Override
    public void setHasPersistentVideo(boolean value) {
        checkNotDestroyed();
        WebContentsImplJni.get().setHasPersistentVideo(mNativeWebContentsAndroid, value);
    }

    @Override
    public boolean hasActiveEffectivelyFullscreenVideo() {
        checkNotDestroyed();
        return WebContentsImplJni.get().hasActiveEffectivelyFullscreenVideo(
                mNativeWebContentsAndroid);
    }

    @Override
    public boolean isPictureInPictureAllowedForFullscreenVideo() {
        checkNotDestroyed();
        return WebContentsImplJni.get().isPictureInPictureAllowedForFullscreenVideo(
                mNativeWebContentsAndroid);
    }

    @Override
    public @Nullable Rect getFullscreenVideoSize() {
        checkNotDestroyed();
        return WebContentsImplJni.get().getFullscreenVideoSize(mNativeWebContentsAndroid);
    }

    @Override
    public void setSize(int width, int height) {
        checkNotDestroyed();
        WebContentsImplJni.get().setSize(mNativeWebContentsAndroid, width, height);
    }

    @Override
    public int getWidth() {
        checkNotDestroyed();
        return WebContentsImplJni.get().getWidth(mNativeWebContentsAndroid);
    }

    @Override
    public int getHeight() {
        checkNotDestroyed();
        return WebContentsImplJni.get().getHeight(mNativeWebContentsAndroid);
    }

    @CalledByNative
    private final void setMediaSession(MediaSessionImpl mediaSession) {
        mMediaSession = mediaSession;
    }

    @CalledByNative
    private static List<Bitmap> createBitmapList() {
        return new ArrayList<Bitmap>();
    }

    @CalledByNative
    private static void addToBitmapList(List<Bitmap> bitmaps, Bitmap bitmap) {
        bitmaps.add(bitmap);
    }

    @CalledByNative
    private static List<Rect> createSizeList() {
        return new ArrayList<Rect>();
    }

    @CalledByNative
    private static void createSizeAndAddToList(List<Rect> sizes, int width, int height) {
        sizes.add(new Rect(0, 0, width, height));
    }

    @CalledByNative
    private static Rect createSize(int width, int height) {
        return new Rect(0, 0, width, height);
    }

    /**
     * Returns {@link RenderCoordinatesImpl}.
     */
    public RenderCoordinatesImpl getRenderCoordinates() {
        return mRenderCoordinates;
    }

    /**
     * Retrieves or stores a user data object for this WebContents.
     * @param key Class instance of the object used as the key.
     * @param userDataFactory Factory that creates an object of the generic class. A new object
     *        is created if it hasn't been created and non-null factory is given.
     * @return The created or retrieved user data object. Can be null if the object was
     *         not created yet, or {@code userDataFactory} is null, or the internal data
     *         storage is already garbage-collected.
     */
    public <T extends UserData> T getOrSetUserData(
            Class<T> key, UserDataFactory<T> userDataFactory) {
        // For tests that go without calling |initialize|.
        if (!mInitialized) return null;

        UserDataHost userDataHost = getUserDataHost();

        // Map can be null after WebView gets gc'ed on its way to destruction.
        if (userDataHost == null) {
            Log.d(TAG, "UserDataHost can't be found");
            return null;
        }

        T data = userDataHost.getUserData(key);
        if (data == null && userDataFactory != null) {
            assert userDataHost.getUserData(key) == null; // Do not allow overwriting

            T object = userDataFactory.create(this);
            assert key.isInstance(object);

            // Retrieves from the map again to return null in case |setUserData| fails
            // to store the object.
            data = userDataHost.setUserData(key, object);
        }
        return key.cast(data);
    }

    public <T extends UserData> void removeUserData(Class<T> key) {
        UserDataHost userDataHost = getUserDataHost();
        if (userDataHost == null) return;
        userDataHost.removeUserData(key);
    }

    /**
     * @return {@code UserDataHost} that contains internal user data. {@code null} if
     *         it is already gc'ed.
     */
    private UserDataHost getUserDataHost() {
        if (mInternalsHolder == null) return null;
        WebContentsInternals internals = mInternalsHolder.get();
        if (internals == null) return null;
        return ((WebContentsInternalsImpl) internals).userDataHost;
    }

    // WindowEventObserver

    @Override
    public void onRotationChanged(int rotation) {
        if (mNativeWebContentsAndroid == 0) return;
        int rotationDegrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0:
                rotationDegrees = 0;
                break;
            case Surface.ROTATION_90:
                rotationDegrees = 90;
                break;
            case Surface.ROTATION_180:
                rotationDegrees = 180;
                break;
            case Surface.ROTATION_270:
                rotationDegrees = -90;
                break;
            default:
                throw new IllegalStateException(
                        "Display.getRotation() shouldn't return that value");
        }
        WebContentsImplJni.get().sendOrientationChangeEvent(
                mNativeWebContentsAndroid, rotationDegrees);
    }

    @Override
    public void onDIPScaleChanged(float dipScale) {
        if (mNativeWebContentsAndroid == 0) return;
        mRenderCoordinates.setDeviceScaleFactor(dipScale);
        WebContentsImplJni.get().onScaleFactorChanged(mNativeWebContentsAndroid);
    }

    @Override
    public void setFocus(boolean hasFocus) {
        if (mNativeWebContentsAndroid == 0) return;
        WebContentsImplJni.get().setFocus(mNativeWebContentsAndroid, hasFocus);
    }

    @Override
    public void setDisplayCutoutSafeArea(Rect insets) {
        if (mNativeWebContentsAndroid == 0) return;
        WebContentsImplJni.get().setDisplayCutoutSafeArea(
                mNativeWebContentsAndroid, insets.top, insets.left, insets.bottom, insets.right);
    }

    @Override
    public void notifyRendererPreferenceUpdate() {
        if (mNativeWebContentsAndroid == 0) return;
        WebContentsImplJni.get().notifyRendererPreferenceUpdate(mNativeWebContentsAndroid);
    }

    @Override
    public void notifyBrowserControlsHeightChanged() {
        if (mNativeWebContentsAndroid == 0) return;
        WebContentsImplJni.get().notifyBrowserControlsHeightChanged(mNativeWebContentsAndroid);
    }

    @Override
    public void tearDownDialogOverlays() {
        if (mTearDownDialogOverlaysHandlers == null) return;
        Iterator<Runnable> it = mTearDownDialogOverlaysHandlers.iterator();
        while (it.hasNext()) {
            Runnable handler = it.next();
            handler.run();
        }
    }

    public void addTearDownDialogOverlaysHandler(Runnable handler) {
        if (mTearDownDialogOverlaysHandlers == null) {
            mTearDownDialogOverlaysHandlers = new ObserverList<>();
        }

        assert !mTearDownDialogOverlaysHandlers.hasObserver(handler);
        mTearDownDialogOverlaysHandlers.addObserver(handler);
    }

    public void removeTearDownDialogOverlaysHandler(Runnable handler) {
        assert mTearDownDialogOverlaysHandlers != null;
        assert mTearDownDialogOverlaysHandlers.hasObserver(handler);

        mTearDownDialogOverlaysHandlers.removeObserver(handler);
    }

    private void checkNotDestroyed() {
        if (mNativeWebContentsAndroid != 0) return;
        throw new IllegalStateException(
                "Native WebContents already destroyed", mNativeDestroyThrowable);
    }

    @NativeMethods
    interface Natives {
        // This is static to avoid exposing a public destroy method on the native side of this
        // class.
        void destroyWebContents(long webContentsAndroidPtr);

        WebContents fromNativePtr(long webContentsAndroidPtr);
        void clearNativeReference(long nativeWebContentsAndroid);
        WindowAndroid getTopLevelNativeWindow(long nativeWebContentsAndroid);
        void setTopLevelNativeWindow(long nativeWebContentsAndroid, WindowAndroid windowAndroid);
        RenderFrameHost getMainFrame(long nativeWebContentsAndroid);
        RenderFrameHost getFocusedFrame(long nativeWebContentsAndroid);
        RenderFrameHost getRenderFrameHostFromId(
                long nativeWebContentsAndroid, int renderProcessId, int renderFrameId);
        RenderFrameHost[] getAllRenderFrameHosts(long nativeWebContentsAndroid);
        RenderWidgetHostViewImpl getRenderWidgetHostView(long nativeWebContentsAndroid);
        WebContentsImpl[] getInnerWebContents(long nativeWebContentsAndroid);
        @Visibility
        int getVisibility(long nativeWebContentsAndroid);
        String getTitle(long nativeWebContentsAndroid);
        GURL getVisibleURL(long nativeWebContentsAndroid);
        int getVirtualKeyboardMode(long nativeWebContentsAndroid);
        String getEncoding(long nativeWebContentsAndroid);
        boolean isLoading(long nativeWebContentsAndroid);
        boolean shouldShowLoadingUI(long nativeWebContentsAndroid);
        void dispatchBeforeUnload(long nativeWebContentsAndroid, boolean autoCancel);
        void stop(long nativeWebContentsAndroid);
        void cut(long nativeWebContentsAndroid);
        void copy(long nativeWebContentsAndroid);
        void paste(long nativeWebContentsAndroid);
        void pasteAsPlainText(long nativeWebContentsAndroid);
        void replace(long nativeWebContentsAndroid, String word);
        void selectAll(long nativeWebContentsAndroid);
        void collapseSelection(long nativeWebContentsAndroid);
        void onHide(long nativeWebContentsAndroid);
        void onShow(long nativeWebContentsAndroid);
        void setImportance(long nativeWebContentsAndroid, int importance);
        void suspendAllMediaPlayers(long nativeWebContentsAndroid);
        void setAudioMuted(long nativeWebContentsAndroid, boolean mute);
        boolean focusLocationBarByDefault(long nativeWebContentsAndroid);
        boolean isFullscreenForCurrentTab(long nativeWebContentsAndroid);
        void exitFullscreen(long nativeWebContentsAndroid);
        void scrollFocusedEditableNodeIntoView(long nativeWebContentsAndroid);
        void selectAroundCaret(long nativeWebContentsAndroid, int granularity,
                boolean shouldShowHandle, boolean shouldShowContextMenu);
        void adjustSelectionByCharacterOffset(long nativeWebContentsAndroid, int startAdjust,
                int endAdjust, boolean showSelectionMenu);
        GURL getLastCommittedURL(long nativeWebContentsAndroid);
        boolean isIncognito(long nativeWebContentsAndroid);
        void resumeLoadingCreatedWebContents(long nativeWebContentsAndroid);
        void evaluateJavaScript(
                long nativeWebContentsAndroid, String script, JavaScriptCallback callback);
        void evaluateJavaScriptForTests(
                long nativeWebContentsAndroid, String script, JavaScriptCallback callback);
        void addMessageToDevToolsConsole(long nativeWebContentsAndroid, int level, String message);
        void postMessageToMainFrame(long nativeWebContentsAndroid, MessagePayload payload,
                String sourceOrigin, String targetOrigin, MessagePort[] ports);
        boolean hasAccessedInitialDocument(long nativeWebContentsAndroid);
        int getThemeColor(long nativeWebContentsAndroid);
        float getLoadProgress(long nativeWebContentsAndroid);
        void requestSmartClipExtract(long nativeWebContentsAndroid, SmartClipCallback callback,
                int x, int y, int width, int height);
        void requestAccessibilitySnapshot(long nativeWebContentsAndroid,
                ViewStructure viewStructureRoot, ViewStructureBuilder viewStructureBuilder,
                Runnable doneCallback);
        void setOverscrollRefreshHandler(long nativeWebContentsAndroid,
                OverscrollRefreshHandler nativeOverscrollRefreshHandler);
        void setSpatialNavigationDisabled(long nativeWebContentsAndroid, boolean disabled);
        void setStylusHandwritingEnabled(long nativeWebContentsAndroid, boolean enabled);
        int downloadImage(long nativeWebContentsAndroid, GURL url, boolean isFavicon,
                int maxBitmapSize, boolean bypassCache, ImageDownloadCallback callback);
        void setHasPersistentVideo(long nativeWebContentsAndroid, boolean value);
        boolean hasActiveEffectivelyFullscreenVideo(long nativeWebContentsAndroid);
        boolean isPictureInPictureAllowedForFullscreenVideo(long nativeWebContentsAndroid);
        Rect getFullscreenVideoSize(long nativeWebContentsAndroid);
        void setSize(long nativeWebContentsAndroid, int width, int height);
        int getWidth(long nativeWebContentsAndroid);
        int getHeight(long nativeWebContentsAndroid);
        EventForwarder getOrCreateEventForwarder(long nativeWebContentsAndroid);
        void setViewAndroidDelegate(
                long nativeWebContentsAndroid, ViewAndroidDelegate viewDelegate);
        void sendOrientationChangeEvent(long nativeWebContentsAndroid, int orientation);
        void onScaleFactorChanged(long nativeWebContentsAndroid);
        void setFocus(long nativeWebContentsAndroid, boolean focused);
        void setDisplayCutoutSafeArea(
                long nativeWebContentsAndroid, int top, int left, int bottom, int right);
        void notifyRendererPreferenceUpdate(long nativeWebContentsAndroid);
        void notifyBrowserControlsHeightChanged(long nativeWebContentsAndroid);
        boolean isBeingDestroyed(long nativeWebContentsAndroid);
    }
}


text:
<?php

App::uses('DispatcherFilter', 'Routing');
App::uses('CakeRequest', 'Network/Http');
App::uses('View', 'View');

class MaintenanceMode extends DispatcherFilter {

	public function beforeDispatch(CakeEvent $event) {
		$MaintenanceMode = Configure::read('MaintenanceMode');

		if (!$MaintenanceMode['enabled']) {
			return;
		}

		/* Allow access from following IPS*/
		if (!empty($MaintenanceMode['ip_filters'])) {
			if (!is_array($MaintenanceMode['ip_filters'])) {
				$ips = array($MaintenanceMode['ip_filters']);
			} else {
				$ips = $MaintenanceMode['ip_filters'];
			}

			$userIP = $this->_getUserIpAddr();
			foreach ($ips as $ip) {
				if ($this->_compareIp($userIP, $ip)) {
					return;
				}
			}
		}

		$statusCode = 503;
		$body = 'Currently undergoing maintenance';

		if (!empty($MaintenanceMode['code'])) {
			$statusCode = $MaintenanceMode['code'];
		}

		if (!empty($MaintenanceMode['view']['template'])) {
			$View = $this->_getView();
			$body = $View->render($MaintenanceMode['view']['template'], $MaintenanceMode['view']['layout']);
		}

		$event->data['response']->statusCode($statusCode);
		$event->data['response']->body($body);
		$event->stopPropagation();

		return $event->data['response'];
	}

	protected function _getView() {
		$MaintenanceMode = Configure::read('MaintenanceMode');

		$helpers = array('Html');
		if (!empty($MaintenanceMode['view']['helpers']) && is_array($helpers)) {
			$helpers = $MaintenanceMode['view']['helpers'];
		}

		$View = new View(null);
		$View->viewVars	= $MaintenanceMode;
		$View->hasRendered = false;
		$View->helpers = $helpers;
		$View->loadHelpers();

		return $View;
	}

	protected function _getUserIpAddr() {
		$ip = '0.0.0.0';
		$CakeRequest = new CakeRequest();

		return $CakeRequest->clientIp();
	}

	protected function _compareIp($userIp, $compareIp) {
		$compareIpLowerBoundary = str_replace("*", "0", $compareIp);
		$compareIpUpperBoundary = str_replace("*", "255", $compareIp);

		if (ip2long($compareIpLowerBoundary) <= ip2long($userIp) && ip2long($userIp) <= ip2long($compareIpUpperBoundary)) {
			return true;
		}

		return false;
	}

}

redpajama_set_name: RedPajamaGithub


text:
<?
$page->title($inst_name." Campus Emergencies: Residence Halls")
     ->header($inst_name." Emergency Info");

$page->content_begin();
?>

Residence Halls

            <? foreach($residence as $item) { ?>

<a href="tel:1<?=$item->call_number()?>" class="phone" onClick="javascript: pageTracker._trackPageview('/outgoing/phone/emergency/residences/<?=$item->label()?>');"><?=$item->label()?>  (<?=$item->message_text()?><?=$item->number_text()?>)

            <? } ?>

<?
$page->content_end();
$page->nav_link("./", "Emergency Info Home");
?>


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.contentwarehouse.v1.model;

/**
 * High level category annotations for documents and queries.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the contentwarehouse API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class RepositoryWebrefCategoryAnnotation extends com.google.api.client.json.GenericJson {

  /**
   * Experimental scores to be used by Discover.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private RepositoryWebrefCategoryAnnotationBrowsyTopic browsyTopic;

  /**
   * Title of the category. Eg "Politics", "Technology".
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String debugString;

  /**
   * Sources asserting the category. In the future we may have one calibrated confidence score.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private RepositoryWebrefCategoryAnnotationHitCatSource hitcat;

  /**
   * Mid representation of the category. Eg "/m/05qt0". WARNING: In UDR this field is not populated,
   * use document_entity.entity.mid instead of document_entity.category.mid.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String mid;

  /**
   * Qprime asserting this category.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private RepositoryWebrefCategoryAnnotationShoppingSignals shopping;

  /**
   * Experimental scores to be used by Discover.
   * @return value or {@code null} for none
   */
  public RepositoryWebrefCategoryAnnotationBrowsyTopic getBrowsyTopic() {
    return browsyTopic;
  }

  /**
   * Experimental scores to be used by Discover.
   * @param browsyTopic browsyTopic or {@code null} for none
   */
  public RepositoryWebrefCategoryAnnotation setBrowsyTopic(RepositoryWebrefCategoryAnnotationBrowsyTopic browsyTopic) {
    this.browsyTopic = browsyTopic;
    return this;
  }

  /**
   * Title of the category. Eg "Politics", "Technology".
   * @return value or {@code null} for none
   */
  public java.lang.String getDebugString() {
    return debugString;
  }

  /**
   * Title of the category. Eg "Politics", "Technology".
   * @param debugString debugString or {@code null} for none
   */
  public RepositoryWebrefCategoryAnnotation setDebugString(java.lang.String debugString) {
    this.debugString = debugString;
    return this;
  }

  /**
   * Sources asserting the category. In the future we may have one calibrated confidence score.
   * @return value or {@code null} for none
   */
  public RepositoryWebrefCategoryAnnotationHitCatSource getHitcat() {
    return hitcat;
  }

  /**
   * Sources asserting the category. In the future we may have one calibrated confidence score.
   * @param hitcat hitcat or {@code null} for none
   */
  public RepositoryWebrefCategoryAnnotation setHitcat(RepositoryWebrefCategoryAnnotationHitCatSource hitcat) {
    this.hitcat = hitcat;
    return this;
  }

  /**
   * Mid representation of the category. Eg "/m/05qt0". WARNING: In UDR this field is not populated,
   * use document_entity.entity.mid instead of document_entity.category.mid.
   * @return value or {@code null} for none
   */
  public java.lang.String getMid() {
    return mid;
  }

  /**
   * Mid representation of the category. Eg "/m/05qt0". WARNING: In UDR this field is not populated,
   * use document_entity.entity.mid instead of document_entity.category.mid.
   * @param mid mid or {@code null} for none
   */
  public RepositoryWebrefCategoryAnnotation setMid(java.lang.String mid) {
    this.mid = mid;
    return this;
  }

  /**
   * Qprime asserting this category.
   * @return value or {@code null} for none
   */
  public RepositoryWebrefCategoryAnnotationShoppingSignals getShopping() {
    return shopping;
  }

  /**
   * Qprime asserting this category.
   * @param shopping shopping or {@code null} for none
   */
  public RepositoryWebrefCategoryAnnotation setShopping(RepositoryWebrefCategoryAnnotationShoppingSignals shopping) {
    this.shopping = shopping;
    return this;
  }

  @Override
  public RepositoryWebrefCategoryAnnotation set(String fieldName, Object value) {
    return (RepositoryWebrefCategoryAnnotation) super.set(fieldName, value);
  }

  @Override
  public RepositoryWebrefCategoryAnnotation clone() {
    return (RepositoryWebrefCategoryAnnotation) super.clone();
  }

}


text:
package org.jetbrains.plugins.groovy.runner;

import java.util.List;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.jetbrains.plugins.groovy.lang.psi.GroovyFile;
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GroovyScriptClass;
import com.intellij.execution.JavaExecutionUtil;
import com.intellij.execution.Location;
import com.intellij.execution.RunManagerEx;
import com.intellij.execution.RunnerAndConfigurationSettings;
import com.intellij.execution.actions.ConfigurationContext;
import com.intellij.execution.actions.ConfigurationFromContext;
import com.intellij.execution.application.ApplicationConfigurationProducer;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.execution.configurations.RunConfigurationModule;
import com.intellij.execution.junit.RuntimeConfigurationProducer;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiMethod;

/**
 * @author ilyas
 */
public class GroovyScriptRunConfigurationProducer extends RuntimeConfigurationProducer implements Cloneable
{
	protected PsiElement mySourceElement;

	public GroovyScriptRunConfigurationProducer()
	{
		super(GroovyScriptRunConfigurationType.getInstance());
	}

	public PsiElement getSourceElement()
	{
		return mySourceElement;
	}

	protected RunnerAndConfigurationSettings createConfigurationByElement(final Location location, final ConfigurationContext context)
	{
		final PsiElement element = location.getPsiElement();
		final PsiFile file = element.getContainingFile();
		if(!(file instanceof GroovyFile))
		{
			return null;
		}

		GroovyFile groovyFile = (GroovyFile) file;
		final PsiClass aClass = GroovyRunnerUtil.getRunningClass(location.getPsiElement());
		if(aClass instanceof GroovyScriptClass || GroovyRunnerUtil.isRunnable(aClass))
		{
			final RunnerAndConfigurationSettings settings = createConfiguration(aClass);
			if(settings != null)
			{
				mySourceElement = element;
				final GroovyScriptRunConfiguration configuration = (GroovyScriptRunConfiguration) settings.getConfiguration();
				GroovyScriptUtil.getScriptType(groovyFile).tuneConfiguration(groovyFile, configuration, location);
				return settings;
			}
		}

		if(file.getText().contains("@Grab"))
		{
			ApplicationConfigurationProducer producer = new ApplicationConfigurationProducer();
			ConfigurationFromContext settings = producer.createConfigurationFromContext(context);
			if(settings != null)
			{
				PsiElement src = settings.getSourceElement();
				mySourceElement = src;
				return createConfiguration(src instanceof PsiMethod ? ((PsiMethod) src).getContainingClass() : (PsiClass) src);
			}

			return null;
		}
		else
		{
			return null;
		}
	}

	@Override
	protected RunnerAndConfigurationSettings findExistingByElement(Location location, @Nonnull List<RunnerAndConfigurationSettings> existingConfigurations, ConfigurationContext context)
	{
		for(RunnerAndConfigurationSettings existingConfiguration : existingConfigurations)
		{
			final RunConfiguration configuration = existingConfiguration.getConfiguration();
			final GroovyScriptRunConfiguration existing = (GroovyScriptRunConfiguration) configuration;
			final String path = existing.getScriptPath();
			if(path != null)
			{
				final PsiFile file = location.getPsiElement().getContainingFile();
				if(file instanceof GroovyFile)
				{
					final VirtualFile vfile = file.getVirtualFile();
					if(vfile != null && FileUtil.toSystemIndependentName(path).equals(vfile.getPath()))
					{
						if(!((GroovyFile) file).isScript() || GroovyScriptUtil.getScriptType((GroovyFile) file).isConfigurationByLocation(existing, location))
						{
							return existingConfiguration;
						}
					}
				}
			}
		}
		return null;
	}

	public int compareTo(final Object o)
	{
		return PREFERED;
	}

	@Nullable
	private RunnerAndConfigurationSettings createConfiguration(@Nullable final PsiClass aClass)
	{
		if(aClass == null)
		{
			return null;
		}

		final Project project = aClass.getProject();
		RunnerAndConfigurationSettings settings = RunManagerEx.getInstanceEx(project).createConfiguration("", getConfigurationFactory());
		final GroovyScriptRunConfiguration configuration = (GroovyScriptRunConfiguration) settings.getConfiguration();
		final PsiFile file = aClass.getContainingFile().getOriginalFile();
		final PsiDirectory dir = file.getContainingDirectory();
		if(dir == null)
		{
			return null;
		}
		configuration.setWorkDir(dir.getVirtualFile().getPath());
		final VirtualFile vFile = file.getVirtualFile();
		if(vFile == null)
		{
			return null;
		}
		configuration.setScriptPath(vFile.getPath());
		RunConfigurationModule module = configuration.getConfigurationModule();

		String name = GroovyRunnerUtil.getConfigurationName(aClass, module);
		configuration.setName(name);
		configuration.setModule(JavaExecutionUtil.findModule(aClass));
		return settings;
	}
}


text:
{% load staticfiles %}

<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>聚问答 | Get Your Questions Answered</title>
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport"
	      content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
	<meta name="format-detection" content="telephone=no">
	<meta name="renderer" content="webkit">
	<meta content="no-siteapp"/>
	<link rel="alternate icon" type="image/png" href="{% static 'img/favicon.png' %}">
	<link rel="stylesheet" href="{% static 'css/amazeui.min.css' %}"/>

		聚问答

	<button class="am-topbar-btn am-topbar-toggle am-btn am-btn-sm am-btn-success am-show-sm-only "
	        data-am-collapse="{target: '#doc-topbar-collapse'}">
		导航切换

	</button>

				搜索结果

				追问

				设置

		<form class="am-topbar-form am-topbar-left am-form-inline am-topbar-right" method="post"
		      action="{% url 'web:searchAnswer' %}" role="search">

				<input type="text" name="title" class="am-form-field am-input-sm" placeholder="重新提问">

			<button type="submit" class="am-btn am-btn-default am-btn-sm">提问</button>
		</form>

	{% autoescape off %}
		{{ content }}
	{% endautoescape %}

	© 2015 Software Engineering Experimental Class. Licensed under MIT license.


text:
namespace chromeos {

// Interface which TpmPasswordFetcher uses to notify that password has been
// fetched.
class CHROMEOS_EXPORT TpmPasswordFetcherDelegate {
 public:
  virtual ~TpmPasswordFetcherDelegate() {}
  virtual void OnPasswordFetched(const std::string& tpm_password) = 0;
};

// Class for fetching TPM password from the Cryptohome.
class CHROMEOS_EXPORT TpmPasswordFetcher {
 public:
  // Creates fetcher with the given delegate to be notified every time fetching
  // is done.
  explicit TpmPasswordFetcher(TpmPasswordFetcherDelegate* delegate);
  ~TpmPasswordFetcher();

  // Fetches TPM password and stores the result. Also notifies |delegate_| with
  // OnPasswordFetched() call.
  void Fetch();

 private:
  // Used to implement Fetch().
  void OnTpmIsReady(DBusMethodCallStatus call_status, bool tpm_is_ready);

  // Used to implement Fetch().
  void OnTpmGetPassword(DBusMethodCallStatus call_status,
                        const std::string& password);

  // Posts a task to call Fetch() later.
  void RescheduleFetch();

  TpmPasswordFetcherDelegate* delegate_;

  base::WeakPtrFactory<TpmPasswordFetcher> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(TpmPasswordFetcher);
};

}  // namespace chromeos

#endif  // CHROMEOS_TPM_TPM_PASSWORD_FETCHER_H_


text:
<?php

namespace Lanin\Laravel\ApiDebugger\Support;

use Lanin\Laravel\ApiDebugger\Debugger;

class Facade extends \Illuminate\Support\Facades\Facade
{
    protected static function getFacadeAccessor()
    {
        return Debugger::class;
    }
}


text:
import logging
import re
import datetime

from ema.server    import Server, Lazy
from ema.parameter import AbstractParameter
from ema.emaproto  import PERIOD

log = logging.getLogger('rtc')

class RTCParameter(AbstractParameter):
    '''RTC sync parameter does not fit into the generic Parameter class
    as the time value to syncronize is volatile in nature'''

    RETRIES   = 1
    TIMEOUT   = 30
    # Common pattern forn GET/SET message responses
    PAT = '\(\d{2}:\d{2}:\d{2} \d{2}/\d{2}/\d{4}\)'

    def __init__(self, ema, deltaT=60):
        AbstractParameter.__init__(self, ema, RTCParameter.TIMEOUT,
                                       RTCParameter.PAT,
                                       RTCParameter.PAT,
                                       RTCParameter.RETRIES)
        self.deltaT = datetime.timedelta(seconds=deltaT)
        self.name = "EMA RTC Time Syncronization"

    def sendDateTime(self):
        t    = self.ema.serdriver.queueDelay()*Server.TIMEOUT
        tadj = int(round(t))
        self.now = (datetime.datetime.utcnow() + datetime.timedelta(seconds=tadj)).replace(microsecond=0)
        msg = self.now.strftime('(Y%d%m%y%H%M%S)')
        self.ema.serdriver.write(msg)
        self.setTimeout(t+RTCParameter.TIMEOUT)      # adjusted for queue length
        self.resetAlarm()
        log.debug("Tadj = %d seconds", tadj)

    def actionStart(self):
        n = self.ema.serdriver.queueDelay()
        n += RTCParameter.TIMEOUT
        self.setTimeout(n)      # adjust for queue length
        self.resetAlarm()
        self.ema.serdriver.write('(y)')

    def actionGet(self, message, matchobj):
        log.debug("matched GET message")
        self.now = datetime.datetime.utcnow().replace(microsecond=0)
        ema = datetime.datetime.strptime(message,'(%H:%M:%S %d/%m/%Y)')
        deltaT = abs(ema - self.now)
        if deltaT > self.deltaT:
            self.sendDateTime()
            log.warning("DeltaT (ema - now) = %s, max DeltaT = %s", deltaT, self.deltaT)
            needsSync = True
        else:
            log.info("No need to sync RTC. DeltaT = %s", deltaT)
            needsSync = False
        return needsSync

    def actionSet(self, message, matchobj):
        log.debug("matched SET message")
        ema = datetime.datetime.strptime(message,'(%H:%M:%S %d/%m/%Y)')
        if ema - self.now > self.deltaT or self.now - ema > self.deltaT :
            log.warning("EMA RTC is still not synchronized")
        else:
            log.info("EMA RTC succesfully sincronized")

    def actionEnd(self):
        log.debug("EMA RTC sync process complete")

    def retryGet(self):
        log.debug("Retry a GET message (%d/%d)" % self.getRetries() )
        self.actionStart()

    def retrySet(self):
        log.debug("Retry a SET message (%d/%d)" % self.getRetries() )
        self.sendDateTime()

    def actionTimeout(self):
        log.error("Timeout: EMA not responding to RTC sync request")

class RTC(Lazy):

    def __init__(self, ema, parser):
        lvl = parser.get("RTC", "rtc_log")
        log.setLevel(lvl)
        deltaT = parser.getint("RTC", "rtc_delta")
        period = parser.getfloat("RTC", "rtc_period")
        Lazy.__init__(self, 3600*period)
        self.ema = ema
        self.param = RTCParameter(ema, deltaT)
        ema.addSync(self.param)
        ema.addLazy(self)

    def work(self):
        '''
        Periodic synchornization routine.
        Should be once a day.
        '''
        self.ema.addSync(self.param)
        self.param.sync()


text:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <ctype.h>
#include <zlib.h>

#include "rfblib.h"
#include "reflector.h"
#include "logging.h"
#include "async_io.h"
#include "host_io.h"
#include "translate.h"
#include "client_io.h"
#include "encode.h"
#include "host_connect.h"

static int parse_host_info(void);
static void host_init_hook(void);
static void host_listen_init_hook(void);
static void host_accept_hook(void);
static void rf_host_ver(void);
static void rf_host_auth(void);
static void rf_host_conn_failed(void);
static void rf_host_crypt(void);
static void rf_host_auth_done(void);
static void send_client_initmsg(void);
static void rf_host_initmsg(void);
static void rf_host_set_formats(void);

static int s_request_tight;
static int s_tight_level;

static char *s_host_info_file;
static int s_cl_listen_port;

static char s_hostname[256];
static int s_host_port;
static unsigned char s_host_password[9];

/*
 * Set preferred encoding (Hextile or Tight) and compression level
 * for the Tight encoding.
 */

void set_host_encodings(int request_tight, int tight_level)
{
  s_request_tight = request_tight;
  s_tight_level = tight_level;
}

/*
 * Connect to a remote RFB host
 */
#ifndef CHROMIUM
int connect_to_host(char *host_info_file, int cl_listen_port)
{
  int host_fd;
  struct hostent *phe;
  struct sockaddr_in host_addr;

  /* Save arguments in static variables, for later use */
  if (host_info_file != NULL)
    s_host_info_file = host_info_file;
  if (cl_listen_port != 0)
    s_cl_listen_port = cl_listen_port;

  /* Extract hostname, port and password from host info file */
  if (!parse_host_info())
    return 0;

  if (strcmp(s_hostname, "*") != 0) {

    /* Forward reflector -> host connection */
    log_write(LL_MSG, "Connecting to %s, port %d", s_hostname, s_host_port);

    phe = gethostbyname(s_hostname);
    if (phe == NULL) {
      log_write(LL_ERROR, "Could not get host address: %s", strerror(errno));
      return 0;
    }

    host_addr.sin_family = AF_INET;
    memcpy(&host_addr.sin_addr.s_addr, phe->h_addr, phe->h_length);
    host_addr.sin_port = htons((unsigned short)s_host_port);

    host_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (host_fd == -1) {
      log_write(LL_ERROR, "Could not create socket: %s", strerror(errno));
      return 0;
    }

    if (connect(host_fd, (struct sockaddr *)&host_addr,
                sizeof(host_addr)) != 0) {
      log_write(LL_ERROR, "Could not connect: %s", strerror(errno));
      close(host_fd);
      return 0;
    }

    log_write(LL_MSG, "Connection established");

    aio_add_slot(host_fd, NULL, host_init_hook, sizeof(HOST_SLOT));

  } else {

    /* Reversed host -> reflector connection, start listening */
    if (!aio_listen(s_host_port, host_listen_init_hook, host_accept_hook,
                   sizeof(HOST_SLOT))) {
      log_write(LL_ERROR, "Error creating listening socket: %s",
                strerror(errno));
      return 0;
    }
    log_write(LL_MSG, "Listening for host connections on port %d",
              s_host_port);

  }

  return 1;
}

#else

/* Brian's new version */
int wait_for_client(int port)
{
  (void) parse_host_info;
  (void) host_listen_init_hook;
  (void) host_accept_hook;

  if (port)
    s_cl_listen_port = port;

  if (!aio_listen(s_cl_listen_port, NULL, af_client_accept,
                  sizeof(CL_SLOT))) {
     log_write(LL_ERROR, "Listen for clients failed!");
     return 0;
  }
  log_write(LL_MSG, "Listening for host connections on port %d",
            s_cl_listen_port);
  return 1;
}

#endif

static int parse_host_info(void)
{
  FILE *fp;
  char buf[256];
  char *pos, *colon_pos, *space_pos;
  int len;

  fp = fopen(s_host_info_file, "r");
  if (fp == NULL) {
    log_write(LL_ERROR, "Cannot open host info file: %s", s_host_info_file);
    return 0;
  }

  /* Read the file into a buffer first */
  len = fread(buf, 1, 255, fp);
  buf[len] = '\0';
  fclose(fp);

  if (len == 0) {
    log_write(LL_ERROR, "Error reading host info file (is it empty?)");
    return 0;
  }

  /* Truncate at the end of first line, respecting MS-DOS end-of-lines */
  pos = strchr(buf, '\n');
  if (pos != NULL)
    *pos = '\0';
  pos = strchr(buf, '\r');
  if (pos != NULL)
    *pos = '\0';

  /* FIXME: parsing code below is primitive */

  space_pos = strchr(buf, ' ');
  if (space_pos != NULL) {
    strncpy((char *)s_host_password, space_pos + 1, 8);
    s_host_password[8] = '\0';
    *space_pos = '\0';
  } else {
    log_write(LL_WARN, "Host password not specified, assuming no auth");
    s_host_password[0] = '\0';
  }

  colon_pos = strchr(buf, ':');
  if (colon_pos != NULL) {
    if (!isdigit(colon_pos[1]) && colon_pos[1] != '-') {
      log_write(LL_ERROR, "Non-numeric host display number: %s",
                colon_pos + 1);
      return 0;
    }
    s_host_port = atoi(colon_pos + 1);
    *colon_pos = '\0';
  } else {
    log_write(LL_WARN, "Host display not specified, assuming display :0");
    s_host_port = 0;
  }

  strcpy(s_hostname, buf);
  if (strcmp(s_hostname, "*") != 0) {
    s_host_port += 5900;
  } else {
    if (s_host_port == 0)
      s_host_port = 5500;
  }

  return 1;
}

static void host_init_hook(void)
{
  cur_slot->type = TYPE_HOST_CONNECTING_SLOT;
  aio_setclose(host_close_hook);
  aio_setread(rf_host_ver, NULL, 12);
}

static void host_listen_init_hook(void)
{
  cur_slot->type = TYPE_HOST_LISTENING_SLOT;
}

static void host_accept_hook(void)
{
  log_write(LL_MSG, "Accepted host connection from %s", cur_slot->name);

  host_init_hook();
}

static void rf_host_ver(void)
{
  char *buf = (char *)cur_slot->readbuf;
  int major = 3, minor = 3;
  int remote_major, remote_minor;
  char ver_msg[12];

  if ( strncmp(buf, "RFB ", 4) != 0 || !isdigit(buf[4]) ||
       !isdigit(buf[4]) || !isdigit(buf[5]) || !isdigit(buf[6]) ||
       buf[7] != '.' || !isdigit(buf[8]) || !isdigit(buf[9]) ||
       !isdigit(buf[10]) || buf[11] != '\n' ) {
    log_write(LL_ERROR, "Wrong greeting data received from host");
    aio_close(0);
    return;
  }

  remote_major = atoi(&buf[4]);
  remote_minor = atoi(&buf[8]);
  log_write(LL_INFO, "Remote RFB Protocol version is %d.%d",
            remote_major, remote_minor);

  if (remote_major != major) {
    log_write(LL_ERROR, "Wrong protocol version, expected %d.x", major);
    aio_close(0);
    return;
  } else if (remote_minor != minor) {
    log_write(LL_WARN, "Protocol sub-version does not match (ignoring)");
  }

  sprintf(ver_msg, "RFB %03d.%03d\n", abs(major) % 999, abs(minor) % 999);
  aio_write(NULL, ver_msg, 12);
  aio_setread(rf_host_auth, NULL, 4);
}

static void rf_host_auth(void)
{
  HOST_SLOT *hs = (HOST_SLOT *)cur_slot;
  CARD32 value32;

  value32 = buf_get_CARD32(cur_slot->readbuf);

  switch (value32) {
  case 0:
    hs->temp_len = buf_get_CARD32(&cur_slot->readbuf[4]);
    aio_setread(rf_host_conn_failed, NULL, hs->temp_len);
    break;
  case 1:
    log_write(LL_MSG, "No authentication required at host side");
    send_client_initmsg();
    break;
  case 2:
    log_write(LL_DETAIL, "VNC authentication requested by host");
    aio_setread(rf_host_crypt, NULL, 16);
    break;
  default:
    log_write(LL_ERROR, "Unknown authentication scheme requested by host");
    aio_close(0);
    return;
  }
}

static void rf_host_conn_failed(void)
{
  HOST_SLOT *hs = (HOST_SLOT *)cur_slot;

  log_write(LL_ERROR, "VNC connection failed: %.*s",
            (int)hs->temp_len, cur_slot->readbuf);
  aio_close(0);
}

static void rf_host_crypt(void)
{
  unsigned char response[16];

  log_write(LL_DEBUG, "Received random challenge");

  rfb_crypt(response, cur_slot->readbuf, s_host_password);
  log_write(LL_DEBUG, "Sending DES-encrypted response");
  aio_write(NULL, response, 16);

  aio_setread(rf_host_auth_done, NULL, 4);
}

static void rf_host_auth_done(void)
{
  CARD32 value32;

  value32 = buf_get_CARD32(cur_slot->readbuf);

  switch(value32) {
  case 0:
    log_write(LL_MSG, "Authentication successful");
    send_client_initmsg();
    break;
  case 1:
    log_write(LL_ERROR, "Authentication failed");
    aio_close(0);
    break;
  case 2:
    log_write(LL_ERROR, "Authentication failed, too many tries");
    aio_close(0);
    break;
  default:
    log_write(LL_ERROR, "Unknown authentication result");
    aio_close(0);
  }
}

static void send_client_initmsg(void)
{
  CARD8 shared_session = 1;

  log_write(LL_DETAIL, "Requesting %s session",
            (shared_session != 0) ? "non-shared" : "shared");
  aio_write(NULL, &shared_session, 1);

  aio_setread(rf_host_initmsg, NULL, 24);
}

static void rf_host_initmsg(void)
{
  HOST_SLOT *hs = (HOST_SLOT *)cur_slot;

  hs->fb_width = buf_get_CARD16(cur_slot->readbuf);
  hs->fb_height = buf_get_CARD16(&cur_slot->readbuf[2]);
  log_write(LL_MSG, "Remote desktop geometry is %dx%d",
            (int)hs->fb_width, (int)hs->fb_height);

  hs->temp_len = buf_get_CARD32(&cur_slot->readbuf[20]);
  aio_setread(rf_host_set_formats, NULL, hs->temp_len);
}

static void rf_host_set_formats(void)
{
  HOST_SLOT *hs = (HOST_SLOT *)cur_slot;
  CARD8 *new_name;
  unsigned char setpixfmt_msg[4 + SZ_RFB_PIXEL_FORMAT];
  unsigned char setenc_msg[32] = {
    2,                          /* Message id */
    0,                          /* Padding -- not used */
    0, 0                        /* Number of encodings */
  };
  int setenc_msg_size;

#ifdef CHROMIUM
  CARD32 *g_framebuffer;
  CARD16 g_fb_width, g_fb_height;
  g_framebuffer = GetFrameBuffer(&g_fb_width, &g_fb_height);
#endif

  /* FIXME: Don't change g_screen_info while there is an active host
     connection! */

  log_write(LL_INFO, "Remote desktop name: %.*s",
            (int)hs->temp_len, cur_slot->readbuf);

  new_name = malloc((size_t)hs->temp_len + 1);
  if (new_name != NULL) {
    if (g_screen_info.name != NULL)
      free(g_screen_info.name);

    g_screen_info.name = new_name;
    g_screen_info.name_length = hs->temp_len;
    memcpy(g_screen_info.name, cur_slot->readbuf, hs->temp_len);
    g_screen_info.name[hs->temp_len] = '\0';
  }

  log_write(LL_DETAIL, "Setting up pixel format");

  memset(setpixfmt_msg, 0, 4);
  buf_put_pixfmt(&setpixfmt_msg[4], &g_screen_info.pixformat);
  log_write(LL_DEBUG, "Sending SetPixelFormat message");
  aio_write(NULL, setpixfmt_msg, sizeof(setpixfmt_msg));

  if (s_request_tight) {
    log_write(LL_DETAIL, "Requesting Tight encoding");
    buf_put_CARD32(&setenc_msg[4],  RFB_ENCODING_TIGHT);
    buf_put_CARD32(&setenc_msg[8],  RFB_ENCODING_HEXTILE);
    buf_put_CARD32(&setenc_msg[12], RFB_ENCODING_COPYRECT);
    buf_put_CARD32(&setenc_msg[16], RFB_ENCODING_RAW);
    buf_put_CARD32(&setenc_msg[20], RFB_ENCODING_LASTRECT);
    buf_put_CARD32(&setenc_msg[24], RFB_ENCODING_NEWFBSIZE);
    if (s_tight_level >= 0 && s_tight_level <= 9) {
      log_write(LL_DETAIL, "Requesting compression level %d", s_tight_level);
      buf_put_CARD32(&setenc_msg[28], (RFB_ENCODING_COMPESSLEVEL0 +
                                       (CARD32)s_tight_level));
      buf_put_CARD16(&setenc_msg[2], 7);
      setenc_msg_size = 32;
    } else {
      buf_put_CARD16(&setenc_msg[2], 6);
      setenc_msg_size = 28;
    }
  } else {
    log_write(LL_DETAIL, "Requesting Hextile encoding");
    buf_put_CARD32(&setenc_msg[4],  RFB_ENCODING_HEXTILE);
    buf_put_CARD32(&setenc_msg[8],  RFB_ENCODING_COPYRECT);
    buf_put_CARD32(&setenc_msg[12], RFB_ENCODING_RAW);
    buf_put_CARD32(&setenc_msg[16], RFB_ENCODING_NEWFBSIZE);
    buf_put_CARD16(&setenc_msg[2], 4);
    setenc_msg_size = 20;
  }

  log_write(LL_DEBUG, "Sending SetEncodings message");
  aio_write(NULL, setenc_msg, setenc_msg_size);

#ifndef CHROMIUM
  /* If there was no local framebuffer yet, start listening for client
     connections, assuming we are mostly ready to serve clients. */
  if (g_framebuffer == NULL) {
    if (!aio_listen(s_cl_listen_port, NULL, af_client_accept,
                    sizeof(CL_SLOT))) {
      log_write(LL_ERROR, "Error creating listening socket: %s",
                strerror(errno));
      aio_close(1);
      return;
    }
  }
#endif

  host_activate();
}

/*
 * Allocate the framebuffer, or extend its size if it exists already.
 */

int alloc_framebuffer(int w, int h)
{
#ifdef CHROMIUM
  /* we should never get here */
  abort();
#else

  int fb_size;

  if (g_framebuffer == NULL) {

    /* Just set initial dimentions of the framebuffer. */
    g_fb_width = w;
    g_fb_height = h;

  } else {

    /* Nothing to do if neither width nor height was increased. */
    if (w <= g_fb_width && h <= g_fb_height) {
      log_write(LL_DETAIL, "No need to reallocate framebuffer and cache");
      return 1;
    }

    /* If framebuffer exists, free it's memory first. */
    /* FIXME: Maybe preserve framebuffer contents? */
    log_write(LL_DETAIL, "Freeing the framebuffer");
    free(g_framebuffer);

    /* Framebuffer dimentions may not be decreased. */
    g_fb_width = (w > g_fb_width) ? w : g_fb_width;
    g_fb_height = (h > g_fb_height) ? h : g_fb_height;

  }

  fb_size = (int)g_fb_width * (int)g_fb_height;
  g_framebuffer = malloc(fb_size * sizeof(CARD32));
  if (g_framebuffer == NULL) {
    log_write(LL_ERROR, "Error allocating framebuffer");
    return 0;
  }
  log_write(LL_DETAIL, "(Re)allocated framebuffer, %d bytes",
            fb_size * sizeof(CARD32));

  /* Note: If the cache is already allocated, allocate_enc_cache()
     function frees the cache memory first. */
  if (!allocate_enc_cache()) {
    free(g_framebuffer);
    g_framebuffer = NULL;
    log_write(LL_ERROR, "Error allocating cache for encoded data");
    return 0;
  }
  log_write(LL_DETAIL, "(Re)allocated cache for encoded data, %d bytes",
            sizeof_enc_cache());

#endif
  return 1;
}


text:
<!DOCTYPE html>

<meta charset="UTF-8">
<link rel="shortcut icon" href="/favicon.png"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css"/>
<link rel="stylesheet" href="custom.css"/>

<title>Minecraft Server</title>

Our Minecraft Server

          <button id="start-button" class="button-primary u-full-width">Start</button>

          Server Size:
          <select id="server-size">
            <option value="t2.micro">Micro (1-2 players)</option>
            <option value="t2.small" selected>Small (2-4 players)</option>
            <option value="t2.medium">Medium (4-8 players)</option>
          </select>

              Name
              Time Online

              briandotcom0
              1:14

              philipjag
              0:13

[18:47:57] [Server thread/INFO]: Starting minecraft server 1.8.4
[18:47:57] [Server thread/INFO]: Loading properties
[18:47:58] [Server thread/INFO]: Generating keypair
[18:47:59] [Server thread/INFO]: Preparing level "world"
[18:48:39] [Server thread/INFO]: Done (40s)! For help, type "help" or "?"

        <input id="command" class="u-full-width u-cf" type="text" placeholder="command"/>


text:
<package>
  <description brief="PIOBS_2">PIOBS_2</description>
  <depend package="gazebo" />
  <author>me</author>
  <license>BSD</license>
</package>


text:
x=[1 2 3 4]; h=[.9 .8]; %signals to be convolved
shouldMakeEquivalent=0 %in general, linear and circular conv. differ
if shouldMakeEquivalent==1
    N=length(x)+length(h)-1; %to force linear and circular coincide
else
    N=max(length(x),length(h)); %required for FFT zero-padding
end
linearConv=conv(x,h) %linear convolution
circularConv=ifft(fft(x,N).*fft(h,N)) %circular convolution, N=4
%circularConv=cconv(x,h,N) %note that Matlab has the cconv function


text:
package apiserver

import (
	"bytes"
	"compress/gzip"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/http/httputil"
	"net/url"
	"path"
	"strings"
	"time"

	"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/api/errors"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/httplog"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/runtime"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/util"

	"github.com/golang/glog"
	"golang.org/x/net/html"
)

// tagsToAttrs states which attributes of which tags require URL substitution.
// Sources: http://www.w3.org/TR/REC-html40/index/attributes.html
//          http://www.w3.org/html/wg/drafts/html/master/index.html#attributes-1
var tagsToAttrs = map[string]util.StringSet{
	"a":          util.NewStringSet("href"),
	"applet":     util.NewStringSet("codebase"),
	"area":       util.NewStringSet("href"),
	"audio":      util.NewStringSet("src"),
	"base":       util.NewStringSet("href"),
	"blockquote": util.NewStringSet("cite"),
	"body":       util.NewStringSet("background"),
	"button":     util.NewStringSet("formaction"),
	"command":    util.NewStringSet("icon"),
	"del":        util.NewStringSet("cite"),
	"embed":      util.NewStringSet("src"),
	"form":       util.NewStringSet("action"),
	"frame":      util.NewStringSet("longdesc", "src"),
	"head":       util.NewStringSet("profile"),
	"html":       util.NewStringSet("manifest"),
	"iframe":     util.NewStringSet("longdesc", "src"),
	"img":        util.NewStringSet("longdesc", "src", "usemap"),
	"input":      util.NewStringSet("src", "usemap", "formaction"),
	"ins":        util.NewStringSet("cite"),
	"link":       util.NewStringSet("href"),
	"object":     util.NewStringSet("classid", "codebase", "data", "usemap"),
	"q":          util.NewStringSet("cite"),
	"script":     util.NewStringSet("src"),
	"source":     util.NewStringSet("src"),
	"video":      util.NewStringSet("poster", "src"),

	// TODO: css URLs hidden in style elements.
}

// ProxyHandler provides a http.Handler which will proxy traffic to locations
// specified by items implementing Redirector.
type ProxyHandler struct {
	prefix  string
	storage map[string]RESTStorage
	codec   runtime.Codec
}

func (r *ProxyHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	namespace, kind, parts, err := KindAndNamespace(req)
	if err != nil {
		notFound(w, req)
		return
	}
	ctx := api.WithNamespace(api.NewContext(), namespace)
	if len(parts) < 2 {
		notFound(w, req)
		return
	}
	id := parts[1]
	rest := ""
	if len(parts) > 2 {
		proxyParts := parts[2:]
		rest = strings.Join(proxyParts, "/")
	}
	storage, ok := r.storage[kind]
	if !ok {
		httplog.LogOf(req, w).Addf("'%v' has no storage object", kind)
		notFound(w, req)
		return
	}

	redirector, ok := storage.(Redirector)
	if !ok {
		httplog.LogOf(req, w).Addf("'%v' is not a redirector", kind)
		errorJSON(errors.NewMethodNotSupported(kind, "proxy"), r.codec, w)
		return
	}

	location, err := redirector.ResourceLocation(ctx, id)
	if err != nil {
		httplog.LogOf(req, w).Addf("Error getting ResourceLocation: %v", err)
		status := errToAPIStatus(err)
		writeJSON(status.Code, r.codec, status, w)
		return
	}
	if location == "" {
		httplog.LogOf(req, w).Addf("ResourceLocation for %v returned ''", id)
		notFound(w, req)
		return
	}

	destURL, err := url.Parse(location)
	if err != nil {
		status := errToAPIStatus(err)
		writeJSON(status.Code, r.codec, status, w)
		return
	}
	if destURL.Scheme == "" {
		// If no scheme was present in location, url.Parse sometimes mistakes
		// hosts for paths.
		destURL.Host = location
	}
	destURL.Path = rest
	destURL.RawQuery = req.URL.RawQuery
	newReq, err := http.NewRequest(req.Method, destURL.String(), req.Body)
	if err != nil {
		status := errToAPIStatus(err)
		writeJSON(status.Code, r.codec, status, w)
		notFound(w, req)
		return
	}
	newReq.Header = req.Header

	proxy := httputil.NewSingleHostReverseProxy(&url.URL{Scheme: "http", Host: destURL.Host})
	proxy.Transport = &proxyTransport{
		proxyScheme:      req.URL.Scheme,
		proxyHost:        req.URL.Host,
		proxyPathPrepend: path.Join(r.prefix, "ns", namespace, kind, id),
	}
	proxy.FlushInterval = 200 * time.Millisecond
	proxy.ServeHTTP(w, newReq)
}

type proxyTransport struct {
	proxyScheme      string
	proxyHost        string
	proxyPathPrepend string
}

func (t *proxyTransport) RoundTrip(req *http.Request) (*http.Response, error) {
	resp, err := http.DefaultTransport.RoundTrip(req)

	if err != nil {
		message := fmt.Sprintf("Error: '%s'\nTrying to reach: '%v'", err.Error(), req.URL.String())
		resp = &http.Response{
			StatusCode: http.StatusServiceUnavailable,
			Body:       ioutil.NopCloser(strings.NewReader(message)),
		}
		return resp, nil
	}

	if resp.Header.Get("Content-Type") != "text/html" {
		// Do nothing, simply pass through
		return resp, nil
	}

	return t.fixLinks(req, resp)
}

// updateURLs checks and updates any of n's attributes that are listed in tagsToAttrs.
// Any URLs found are, if they're relative, updated with the necessary changes to make
// a visit to that URL also go through the proxy.
// sourceURL is the URL of the page which we're currently on; it's required to make
// relative links work.
func (t *proxyTransport) updateURLs(n *html.Node, sourceURL *url.URL) {
	if n.Type != html.ElementNode {
		return
	}
	attrs, ok := tagsToAttrs[n.Data]
	if !ok {
		return
	}
	for i, attr := range n.Attr {
		if !attrs.Has(attr.Key) {
			continue
		}
		url, err := url.Parse(attr.Val)
		if err != nil {
			continue
		}
		// Is this URL relative?
		if url.Host == "" {
			url.Scheme = t.proxyScheme
			url.Host = t.proxyHost
			url.Path = path.Join(t.proxyPathPrepend, path.Dir(sourceURL.Path), url.Path, "/")
			n.Attr[i].Val = url.String()
		} else if url.Host == sourceURL.Host {
			url.Scheme = t.proxyScheme
			url.Host = t.proxyHost
			url.Path = path.Join(t.proxyPathPrepend, url.Path)
			n.Attr[i].Val = url.String()
		}
	}
}

// scan recursively calls f for every n and every subnode of n.
func (t *proxyTransport) scan(n *html.Node, f func(*html.Node)) {
	f(n)
	for c := n.FirstChild; c != nil; c = c.NextSibling {
		t.scan(c, f)
	}
}

// fixLinks modifies links in an HTML file such that they will be redirected through the proxy if needed.
func (t *proxyTransport) fixLinks(req *http.Request, resp *http.Response) (*http.Response, error) {
	origBody := resp.Body
	defer origBody.Close()

	newContent := &bytes.Buffer{}
	var reader io.Reader = origBody
	var writer io.Writer = newContent
	encoding := resp.Header.Get("Content-Encoding")
	switch encoding {
	case "gzip":
		var err error
		reader, err = gzip.NewReader(reader)
		if err != nil {
			return nil, fmt.Errorf("errorf making gzip reader: %v", err)
		}
		gzw := gzip.NewWriter(writer)
		defer gzw.Close()
		writer = gzw
	// TODO: support flate, other encodings.
	case "":
		// This is fine
	default:
		// Some encoding we don't understand-- don't try to parse this
		glog.Errorf("Proxy encountered encoding %v for text/html; can't understand this so not fixing links.", encoding)
		return resp, nil
	}

	doc, err := html.Parse(reader)
	if err != nil {
		glog.Errorf("Parse failed: %v", err)
		return resp, err
	}

	t.scan(doc, func(n *html.Node) { t.updateURLs(n, req.URL) })
	if err := html.Render(writer, doc); err != nil {
		glog.Errorf("Failed to render: %v", err)
	}

	resp.Body = ioutil.NopCloser(newContent)
	// Update header node with new content-length
	// TODO: Remove any hash/signature headers here?
	resp.Header.Del("Content-Length")
	resp.ContentLength = int64(newContent.Len())

	return resp, err
}


text:
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Color;

public class edit_page {

	public JFrame frame;
	private JTextField textField;
	private JTextField textField_1;
	private JTextField textField_2;
	private JPasswordField passwordField;

	/**
	 * Create the application.
	 */
	public edit_page(final int ind) {
		initialize(ind);
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize(final int ind) {
		frame = new JFrame();
		frame.setBounds(100, 100, 450, 300);
		frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		frame.getContentPane().setLayout(null);

		JLabel lblEditDetails = new JLabel("Edit Details");
		lblEditDetails.setFont(new Font("NanumGothic", Font.BOLD, 15));
		lblEditDetails.setBounds(176, 12, 95, 20);
		frame.getContentPane().add(lblEditDetails);

		JLabel lblName = new JLabel("Name");
		lblName.setBounds(74, 72, 70, 15);
		frame.getContentPane().add(lblName);

		JLabel lblRoomNo = new JLabel("Room No");
		lblRoomNo.setBounds(74, 104, 87, 15);
		frame.getContentPane().add(lblRoomNo);

		JLabel lblRollNo = new JLabel("Mobile No");
		lblRollNo.setBounds(74, 136, 105, 15);
		frame.getContentPane().add(lblRollNo);

		JLabel lblPassword = new JLabel("Password");
		lblPassword.setBounds(74, 168, 70, 15);
		frame.getContentPane().add(lblPassword);

		textField = new JTextField();
		textField.setBounds(182, 70, 220, 19);
		frame.getContentPane().add(textField);
		textField.setColumns(10);
		textField.setText(main.vec.elementAt(ind).get_name());

		textField_1 = new JTextField();
		textField_1.setBounds(182, 102, 220, 19);
		frame.getContentPane().add(textField_1);
		textField_1.setColumns(10);
		textField_1.setText(main.vec.elementAt(ind).get_room());

		textField_2 = new JTextField();
		textField_2.setBounds(182, 134, 220, 19);
		frame.getContentPane().add(textField_2);
		textField_2.setColumns(10);
		textField_2.setText(main.vec.elementAt(ind).get_mobile());

		passwordField = new JPasswordField();
		passwordField.setBounds(182, 166, 220, 19);
		frame.getContentPane().add(passwordField);
		passwordField.setText(main.vec.elementAt(ind).get_password());

		JButton btnAddMe = new JButton("Confirm and Edit !");
		btnAddMe.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {

				main.vec.elementAt(ind).set_mobile(textField_2.getText());
				main.vec.elementAt(ind).set_room(textField_1.getText());
				main.vec.elementAt(ind).set_name(textField.getText());
				main.vec.elementAt(ind).set_password(passwordField.getText());

				JOptionPane.showMessageDialog(null, "Successfully Done !!");

				decision_root window = new decision_root();
				frame.setVisible(false);
				window.frame.setVisible(true);
			}
		});
		btnAddMe.setBounds(147, 207, 172, 25);
		frame.getContentPane().add(btnAddMe);

		JButton btnNewButton = new JButton("X");
		btnNewButton.setBackground(Color.RED);
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				decision_root window = new decision_root();
				frame.setVisible(false);
				window.frame.setVisible(true);
			}
		});
		btnNewButton.setBounds(395, 8, 43, 25);
		frame.getContentPane().add(btnNewButton);
	}

}


text:
/* $Id$ */
#ifndef __unshield_h__
#define __unshield_h__

#include <stdbool.h>
#include <stddef.h>

#define UNSHIELD_LOG_LEVEL_LOWEST    0

#define UNSHIELD_LOG_LEVEL_ERROR     1
#define UNSHIELD_LOG_LEVEL_WARNING   2
#define UNSHIELD_LOG_LEVEL_TRACE     3

#define UNSHIELD_LOG_LEVEL_HIGHEST   4

#ifdef __cplusplus
extern "C" {
#endif

typedef struct _Unshield Unshield;

/*
   Logging
 */

void unshield_set_log_level(int level);

/*
   Open/close functions
 */

Unshield* unshield_open(const char* filename);
Unshield* unshield_open_force_version(const char* filename, int version);
void unshield_close(Unshield* unshield);

/*
   Component functions
 */

typedef struct
{
  const char* name;
  unsigned file_group_count;
  const char** file_group_names;
} UnshieldComponent;

int         unshield_component_count    (Unshield* unshield);
const char* unshield_component_name     (Unshield* unshield, int index);

/*
   File group functions
 */

typedef struct
{
  const char* name;
  unsigned first_file;
  unsigned last_file;
} UnshieldFileGroup;

int                 unshield_file_group_count (Unshield* unshield);
UnshieldFileGroup*  unshield_file_group_get   (Unshield* unshield, int index);
UnshieldFileGroup*  unshield_file_group_find  (Unshield* unshield, const char* name);
const char*         unshield_file_group_name  (Unshield* unshield, int index);

/*
   Directory functions
 */

int         unshield_directory_count    (Unshield* unshield);
const char* unshield_directory_name     (Unshield* unshield, int index);

/*
   File functions
 */

int         unshield_file_count         (Unshield* unshield);
const char* unshield_file_name          (Unshield* unshield, int index);
bool        unshield_file_is_valid      (Unshield* unshield, int index);
bool        unshield_file_save          (Unshield* unshield, int index, const char* filename);
int         unshield_file_directory     (Unshield* unshield, int index);
size_t      unshield_file_size          (Unshield* unshield, int index);

/** For investigation of compressed data */
bool unshield_file_save_raw(Unshield* unshield, int index, const char* filename);

/** Maybe it's just gzip without size? */
bool unshield_file_save_old(Unshield* unshield, int index, const char* filename);

/** Deobfuscate a buffer. Seed is 0 at file start */
void unshield_deobfuscate(unsigned char* buffer, size_t size, unsigned* seed);

#ifdef __cplusplus
}
#endif

#endif