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

package org.chromium.android_webview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.os.Process;
import android.provider.Settings;
import android.webkit.WebSettings;

import androidx.annotation.IntDef;

import org.chromium.android_webview.common.AwFeatures;
import org.chromium.android_webview.safe_browsing.AwSafeBrowsingConfigHelper;
import org.chromium.android_webview.settings.ForceDarkBehavior;
import org.chromium.android_webview.settings.ForceDarkMode;
import org.chromium.android_webview.settings.RequestedWithHeaderMode;
import org.chromium.base.ContextUtils;
import org.chromium.base.Log;
import org.chromium.base.ThreadUtils;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.base.metrics.RecordHistogram;
import org.chromium.content_public.browser.WebContents;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
 * Stores Android WebView specific settings that does not need to be synced to WebKit.
 *
 * Methods in this class can be called from any thread, including threads created by
 * the client of WebView.
 */
@JNINamespace("android_webview")
public class AwSettings {
    private static final String TAG = "AwSettings";
    private static final boolean TRACE = false;

    /* See {@link android.webkit.WebSettings}. */
    @Retention(RetentionPolicy.SOURCE)
    @IntDef({LAYOUT_ALGORITHM_NORMAL,
            /* See {@link android.webkit.WebSettings}. */
            LAYOUT_ALGORITHM_SINGLE_COLUMN,
            /* See {@link android.webkit.WebSettings}. */
            LAYOUT_ALGORITHM_NARROW_COLUMNS, LAYOUT_ALGORITHM_TEXT_AUTOSIZING})
    public @interface LayoutAlgorithm {}
    public static final int LAYOUT_ALGORITHM_NORMAL = 0;
    /* See {@link android.webkit.WebSettings}. */
    public static final int LAYOUT_ALGORITHM_SINGLE_COLUMN = 1;
    /* See {@link android.webkit.WebSettings}. */
    public static final int LAYOUT_ALGORITHM_NARROW_COLUMNS = 2;
    public static final int LAYOUT_ALGORITHM_TEXT_AUTOSIZING = 3;

    public static final int FORCE_DARK_OFF = ForceDarkMode.FORCE_DARK_OFF;
    public static final int FORCE_DARK_AUTO = ForceDarkMode.FORCE_DARK_AUTO;
    public static final int FORCE_DARK_ON = ForceDarkMode.FORCE_DARK_ON;
    public static final int FORCE_DARK_MODES_COUNT = 3;

    @ForceDarkMode
    private int mForceDarkMode = ForceDarkMode.FORCE_DARK_AUTO;

    private boolean mAlgorithmicDarkeningAllowed;

    public static final int FORCE_DARK_ONLY = ForceDarkBehavior.FORCE_DARK_ONLY;
    public static final int MEDIA_QUERY_ONLY = ForceDarkBehavior.MEDIA_QUERY_ONLY;
    // This option requires RuntimeEnabledFeatures::MetaColorSchemeEnabled()
    public static final int PREFER_MEDIA_QUERY_OVER_FORCE_DARK =
            ForceDarkBehavior.PREFER_MEDIA_QUERY_OVER_FORCE_DARK;
    public static final int FORCE_DARK_STRATEGY_COUNT = 3;

    @ForceDarkBehavior
    private int mForceDarkBehavior = ForceDarkBehavior.PREFER_MEDIA_QUERY_OVER_FORCE_DARK;

    public static final int REQUESTED_WITH_NO_HEADER = RequestedWithHeaderMode.NO_HEADER;
    public static final int REQUESTED_WITH_APP_PACKAGE_NAME =
            RequestedWithHeaderMode.APP_PACKAGE_NAME;
    public static final int REQUESTED_WITH_CONSTANT_WEBVIEW =
            RequestedWithHeaderMode.CONSTANT_WEBVIEW;
    public static final int REQUESTED_WITH_MODES_COUNT = 3;

    @RequestedWithHeaderMode
    private int mRequestedWithHeaderMode;

    // Must match name of |kWebViewXRequestedWithHeaderMode| in
    // android_webview/common/aw_features.cc
    private static final String REQUESTED_WITH_HEADER_MODE_PARAM_NAME =
            "WebViewXRequestedWithHeaderMode";

    private Context mContext;

    // This class must be created on the UI thread. Afterwards, it can be
    // used from any thread. Internally, the class uses a message queue
    // to call native code on the UI thread only.

    // Values passed in on construction.
    private final boolean mHasInternetPermission;

    private ZoomSupportChangeListener mZoomChangeListener;
    private double mDIPScale = 1.0;

    // Lock to protect all settings.
    private final Object mAwSettingsLock = new Object();

    @LayoutAlgorithm
    private int mLayoutAlgorithm = LAYOUT_ALGORITHM_NARROW_COLUMNS;
    private int mTextSizePercent = 100;
    private String mStandardFontFamily = "sans-serif";
    private String mFixedFontFamily = "monospace";
    private String mSansSerifFontFamily = "sans-serif";
    private String mSerifFontFamily = "serif";
    private String mCursiveFontFamily = "cursive";
    private String mFantasyFontFamily = "fantasy";
    private String mDefaultTextEncoding = "UTF-8";
    private String mUserAgent;
    private int mMinimumFontSize = 8;
    private int mMinimumLogicalFontSize = 8;
    private int mDefaultFontSize = 16;
    private int mDefaultFixedFontSize = 13;
    private boolean mLoadsImagesAutomatically = true;
    private boolean mImagesEnabled = true;
    private boolean mJavaScriptEnabled;
    private boolean mAllowUniversalAccessFromFileURLs;
    private boolean mAllowFileAccessFromFileURLs;
    private boolean mJavaScriptCanOpenWindowsAutomatically;
    private boolean mSupportMultipleWindows;
    private boolean mDomStorageEnabled;
    private boolean mDatabaseEnabled;
    private boolean mUseWideViewport;
    private boolean mZeroLayoutHeightDisablesViewportQuirk;
    private boolean mForceZeroLayoutHeight;
    private boolean mLoadWithOverviewMode;
    private boolean mMediaPlaybackRequiresUserGesture = true;
    private String mDefaultVideoPosterURL;
    private float mInitialPageScalePercent;
    private boolean mSpatialNavigationEnabled;  // Default depends on device features.
    private boolean mEnableSupportedHardwareAcceleratedFeatures;
    private int mMixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW;
    private boolean mCSSHexAlphaColorEnabled;
    private boolean mScrollTopLeftInteropEnabled;
    private boolean mWillSuppressErrorPage;

    private boolean mOffscreenPreRaster;
    private int mDisabledMenuItems = WebSettings.MENU_ITEM_NONE;

    // Although this bit is stored on AwSettings it is actually controlled via the CookieManager.
    private boolean mAcceptThirdPartyCookies;

    // if null, default to AwSafeBrowsingConfigHelper.getSafeBrowsingEnabledByManifest()
    private Boolean mSafeBrowsingEnabled;

    private final boolean mSupportLegacyQuirks;
    private final boolean mAllowEmptyDocumentPersistence;
    private final boolean mAllowGeolocationOnInsecureOrigins;
    private final boolean mDoNotUpdateSelectionOnMutatingSelectionRange;

    private final boolean mPasswordEchoEnabled;

    // Not accessed by the native side.
    private boolean mBlockNetworkLoads;  // Default depends on permission of embedding APK.
    private boolean mAllowContentUrlAccess = true;
    private boolean mAllowFileUrlAccess;
    private int mCacheMode = WebSettings.LOAD_DEFAULT;
    private boolean mShouldFocusFirstNode = true;
    private boolean mGeolocationEnabled = true;
    private boolean mAutoCompleteEnabled = Build.VERSION.SDK_INT < Build.VERSION_CODES.O;
    private boolean mFullscreenSupported;
    private boolean mSupportZoom = true;
    private boolean mBuiltInZoomControls;
    private boolean mDisplayZoomControls = true;

    static class LazyDefaultUserAgent{
        // Lazy Holder pattern
        private static final String sInstance = AwSettingsJni.get().getDefaultUserAgent();
    }

    // Protects access to settings global fields.
    private static final Object sGlobalContentSettingsLock = new Object();

    // The native side of this object. It's lifetime is bounded by the WebContent it is attached to.
    private long mNativeAwSettings;

    // Custom handler that queues messages to call native code on the UI thread.
    private final EventHandler mEventHandler;

    private static final int MINIMUM_FONT_SIZE = 1;
    private static final int MAXIMUM_FONT_SIZE = 72;

    // Class to handle messages to be processed on the UI thread.
    private class EventHandler {
        // Message id for running a Runnable with mAwSettingsLock held.
        private static final int RUN_RUNNABLE_BLOCKING = 0;
        // Actual UI thread handler
        private Handler mHandler;
        // Synchronization flag.
        private boolean mSynchronizationPending;

        EventHandler() {
        }

        @SuppressLint("HandlerLeak")
        void bindUiThread() {
            if (mHandler != null) return;
            mHandler = new Handler(ThreadUtils.getUiThreadLooper()) {
                @Override
                public void handleMessage(Message msg) {
                    switch (msg.what) {
                        case RUN_RUNNABLE_BLOCKING:
                            synchronized (mAwSettingsLock) {
                                if (mNativeAwSettings != 0) {
                                    ((Runnable) msg.obj).run();
                                }
                                mSynchronizationPending = false;
                                mAwSettingsLock.notifyAll();
                            }
                            break;
                    }
                }
            };
        }

        void runOnUiThreadBlockingAndLocked(Runnable r) {
            assert Thread.holdsLock(mAwSettingsLock);
            if (mHandler == null) return;
            if (ThreadUtils.runningOnUiThread()) {
                r.run();
            } else {
                assert !mSynchronizationPending;
                mSynchronizationPending = true;
                mHandler.sendMessage(Message.obtain(null, RUN_RUNNABLE_BLOCKING, r));
                try {
                    while (mSynchronizationPending) {
                        mAwSettingsLock.wait();
                    }
                } catch (InterruptedException e) {
                    Log.e(TAG, "Interrupted waiting a Runnable to complete", e);
                    mSynchronizationPending = false;
                }
            }
        }

        void maybePostOnUiThread(Runnable r) {
            if (mHandler != null) {
                mHandler.post(r);
            }
        }

        void updateWebkitPreferencesLocked() {
            runOnUiThreadBlockingAndLocked(() -> updateWebkitPreferencesOnUiThreadLocked());
        }

        void updateCookiePolicyLocked() {
            runOnUiThreadBlockingAndLocked(() -> updateCookiePolicyOnUiThreadLocked());
        }

        void updateAllowFileAccessLocked() {
            runOnUiThreadBlockingAndLocked(() -> updateAllowFileAccessOnUiThreadLocked());
        }
    }

    interface ZoomSupportChangeListener {
        public void onGestureZoomSupportChanged(
                boolean supportsDoubleTapZoom, boolean supportsMultiTouchZoom);
    }

    public AwSettings(Context context, boolean isAccessFromFileURLsGrantedByDefault,
            boolean supportsLegacyQuirks, boolean allowEmptyDocumentPersistence,
            boolean allowGeolocationOnInsecureOrigins,
            boolean doNotUpdateSelectionOnMutatingSelectionRange) {
        mContext = context;
        boolean hasInternetPermission = context.checkPermission(
                android.Manifest.permission.INTERNET,
                Process.myPid(),
                Process.myUid()) == PackageManager.PERMISSION_GRANTED;
        synchronized (mAwSettingsLock) {
            mHasInternetPermission = hasInternetPermission;
            mBlockNetworkLoads = !hasInternetPermission;
            mEventHandler = new EventHandler();
            if (isAccessFromFileURLsGrantedByDefault) {
                mAllowUniversalAccessFromFileURLs = true;
                mAllowFileAccessFromFileURLs = true;
            }

            mUserAgent = LazyDefaultUserAgent.sInstance;

            // Best-guess a sensible initial value based on the features supported on the device.
            mSpatialNavigationEnabled = !context.getPackageManager().hasSystemFeature(
                    PackageManager.FEATURE_TOUCHSCREEN);

            // Respect the system setting for password echoing.
            mPasswordEchoEnabled = Settings.System.getInt(context.getContentResolver(),
                    Settings.System.TEXT_SHOW_PASSWORD, 1) == 1;

            // By default, scale the text size by the system font scale factor. Embedders
            // may override this by invoking setTextZoom().
            mTextSizePercent =
                    (int) (mTextSizePercent * context.getResources().getConfiguration().fontScale);

            mSupportLegacyQuirks = supportsLegacyQuirks;
            mAllowEmptyDocumentPersistence = allowEmptyDocumentPersistence;
            mAllowGeolocationOnInsecureOrigins = allowGeolocationOnInsecureOrigins;
            mDoNotUpdateSelectionOnMutatingSelectionRange =
                    doNotUpdateSelectionOnMutatingSelectionRange;

            mAllowFileUrlAccess =
                    ContextUtils.getApplicationContext().getApplicationInfo().targetSdkVersion
                    < Build.VERSION_CODES.R;

            mRequestedWithHeaderMode = getDefaultXRequestedWithHeaderMode();
        }
        // Defer initializing the native side until a native WebContents instance is set.
    }

    /**
     * Compute the default value to use for XRequestedWithHeaderMode.
     *
     * Implemented as package-local static to share with |AwServiceWorkerSettings.java|
     * @return Default mode for XRequestedWith header.
     */
    @RequestedWithHeaderMode
    static int getDefaultXRequestedWithHeaderMode() {
        int defaultMode = REQUESTED_WITH_APP_PACKAGE_NAME;
        if (AwFeatureList.isEnabled(AwFeatures.WEBVIEW_X_REQUESTED_WITH_HEADER)) {
            int headerMode = AwFeatureList.getFeatureParamValueAsInt(
                    AwFeatures.WEBVIEW_X_REQUESTED_WITH_HEADER,
                    REQUESTED_WITH_HEADER_MODE_PARAM_NAME, defaultMode);
            // Verify that the value is valid
            if (headerMode >= 0 && headerMode < REQUESTED_WITH_MODES_COUNT) {
                defaultMode = headerMode;
            }
        } else {
            // If the feature is disabled, that's equivalent of setting the NO_HEADER behaviour
            defaultMode = REQUESTED_WITH_NO_HEADER;
        }
        return defaultMode;
    }

    public int getUiModeNight() {
        return mContext.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
    }

    @CalledByNative
    private void nativeAwSettingsGone(long nativeAwSettings) {
        assert mNativeAwSettings != 0 && mNativeAwSettings == nativeAwSettings;
        mNativeAwSettings = 0;
    }

    @CalledByNative
    private double getDIPScaleLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mDIPScale;
    }

    void setDIPScale(double dipScale) {
        synchronized (mAwSettingsLock) {
            mDIPScale = dipScale;
            // TODO(joth): This should also be synced over to native side, but right now
            // the setDIPScale call is always followed by a setWebContents() which covers this.
        }
    }

    void setZoomListener(ZoomSupportChangeListener zoomChangeListener) {
        synchronized (mAwSettingsLock) {
            mZoomChangeListener = zoomChangeListener;
        }
    }

    void setWebContents(WebContents webContents) {
        synchronized (mAwSettingsLock) {
            if (mNativeAwSettings != 0) {
                AwSettingsJni.get().destroy(mNativeAwSettings, AwSettings.this);
                assert mNativeAwSettings == 0;  // nativeAwSettingsGone should have been called.
            }
            if (webContents != null) {
                mEventHandler.bindUiThread();
                mNativeAwSettings = AwSettingsJni.get().init(AwSettings.this, webContents);
                updateEverythingLocked();
            }
        }
    }

    private void updateEverythingLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        assert mNativeAwSettings != 0;
        AwSettingsJni.get().updateEverythingLocked(mNativeAwSettings, AwSettings.this);
        onGestureZoomSupportChanged(
                supportsDoubleTapZoomLocked(), supportsMultiTouchZoomLocked());
    }

    /**
     * See {@link android.webkit.WebSettings#setBlockNetworkLoads}.
     */
    public void setBlockNetworkLoads(boolean flag) {
        if (TRACE) Log.i(TAG, "setBlockNetworkLoads=" + flag);
        synchronized (mAwSettingsLock) {
            if (!flag && !mHasInternetPermission) {
                throw new SecurityException("Permission denied - "
                        + "application missing INTERNET permission");
            }
            mBlockNetworkLoads = flag;
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getBlockNetworkLoads}.
     */
    public boolean getBlockNetworkLoads() {
        synchronized (mAwSettingsLock) {
            return mBlockNetworkLoads;
        }
    }

    /**
     * Enable/disable third party cookies for an AwContents
     * @param accept true if we should accept third party cookies
     */
    public void setAcceptThirdPartyCookies(boolean accept) {
        if (TRACE) Log.i(TAG, "setAcceptThirdPartyCookies=" + accept);
        synchronized (mAwSettingsLock) {
            mAcceptThirdPartyCookies = accept;
            mEventHandler.updateCookiePolicyLocked();
        }
    }

    /**
     * Enable/Disable SafeBrowsing per WebView
     * @param enabled true if this WebView should have SafeBrowsing
     */
    public void setSafeBrowsingEnabled(boolean enabled) {
        synchronized (mAwSettingsLock) {
            mSafeBrowsingEnabled = enabled;
        }
    }

    /**
     * Return whether third party cookies are enabled for an AwContents
     * @return true if accept third party cookies
     */
    public boolean getAcceptThirdPartyCookies() {
        synchronized (mAwSettingsLock) {
            return mAcceptThirdPartyCookies;
        }
    }

    @CalledByNative
    private boolean getAcceptThirdPartyCookiesLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mAcceptThirdPartyCookies;
    }

    /**
     * Return whether Safe Browsing has been enabled for the current WebView
     * @return true if SafeBrowsing is enabled
     */
    public boolean getSafeBrowsingEnabled() {
        synchronized (mAwSettingsLock) {
            if (mSafeBrowsingEnabled == null) {
                return AwSafeBrowsingConfigHelper.getSafeBrowsingEnabledByManifest();
            }
            return mSafeBrowsingEnabled;
        }
    }

    /**
     * See {@link android.webkit.WebSettings#setAllowFileAccess}.
     */
    public void setAllowFileAccess(boolean allow) {
        if (TRACE) Log.i(TAG, "setAllowFileAccess=" + allow);
        synchronized (mAwSettingsLock) {
            mAllowFileUrlAccess = allow;
            mEventHandler.updateAllowFileAccessLocked();
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getAllowFileAccess}.
     */
    @CalledByNative
    public boolean getAllowFileAccess() {
        synchronized (mAwSettingsLock) {
            return mAllowFileUrlAccess;
        }
    }

    /**
     * See {@link android.webkit.WebSettings#setAllowContentAccess}.
     */
    public void setAllowContentAccess(boolean allow) {
        if (TRACE) Log.i(TAG, "setAllowContentAccess=" + allow);
        synchronized (mAwSettingsLock) {
            mAllowContentUrlAccess = allow;
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getAllowContentAccess}.
     */
    public boolean getAllowContentAccess() {
        synchronized (mAwSettingsLock) {
            return mAllowContentUrlAccess;
        }
    }

    /**
     * See {@link android.webkit.WebSettings#setCacheMode}.
     */
    public void setCacheMode(int mode) {
        if (TRACE) Log.i(TAG, "setCacheMode=" + mode);
        synchronized (mAwSettingsLock) {
            mCacheMode = mode;
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getCacheMode}.
     */
    public int getCacheMode() {
        synchronized (mAwSettingsLock) {
            return mCacheMode;
        }
    }

    /**
     * See {@link android.webkit.WebSettings#setNeedInitialFocus}.
     */
    public void setShouldFocusFirstNode(boolean flag) {
        if (TRACE) Log.i(TAG, "setNeedInitialFocusNode=" + flag);
        synchronized (mAwSettingsLock) {
            mShouldFocusFirstNode = flag;
        }
    }

    /**
     * See {@link android.webkit.WebView#setInitialScale}.
     */
    public void setInitialPageScale(final float scaleInPercent) {
        if (TRACE) Log.i(TAG, "setInitialScale=" + scaleInPercent);
        synchronized (mAwSettingsLock) {
            if (mInitialPageScalePercent != scaleInPercent) {
                mInitialPageScalePercent = scaleInPercent;
                mEventHandler.runOnUiThreadBlockingAndLocked(() -> {
                    if (mNativeAwSettings != 0) {
                        AwSettingsJni.get().updateInitialPageScaleLocked(
                                mNativeAwSettings, AwSettings.this);
                    }
                });
            }
        }
    }

    @CalledByNative
    private float getInitialPageScalePercentLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mInitialPageScalePercent;
    }

    void setSpatialNavigationEnabled(boolean enable) {
        synchronized (mAwSettingsLock) {
            if (mSpatialNavigationEnabled != enable) {
                mSpatialNavigationEnabled = enable;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    @CalledByNative
    private boolean getSpatialNavigationLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mSpatialNavigationEnabled;
    }

    void setEnableSupportedHardwareAcceleratedFeatures(boolean enable) {
        synchronized (mAwSettingsLock) {
            if (mEnableSupportedHardwareAcceleratedFeatures != enable) {
                mEnableSupportedHardwareAcceleratedFeatures = enable;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    @CalledByNative
    private boolean getEnableSupportedHardwareAcceleratedFeaturesLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mEnableSupportedHardwareAcceleratedFeatures;
    }

    public void setFullscreenSupported(boolean supported) {
        synchronized (mAwSettingsLock) {
            if (mFullscreenSupported != supported) {
                mFullscreenSupported = supported;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    @CalledByNative
    private boolean getFullscreenSupportedLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mFullscreenSupported;
    }

    /**
     * See {@link android.webkit.WebSettings#setNeedInitialFocus}.
     */
    public boolean shouldFocusFirstNode() {
        synchronized (mAwSettingsLock) {
            return mShouldFocusFirstNode;
        }
    }

    /**
     * See {@link android.webkit.WebSettings#setGeolocationEnabled}.
     */
    public void setGeolocationEnabled(boolean flag) {
        if (TRACE) Log.i(TAG, "setGeolocationEnabled=" + flag);
        synchronized (mAwSettingsLock) {
            mGeolocationEnabled = flag;
        }
    }

    /**
     * @return Returns if geolocation is currently enabled.
     */
    boolean getGeolocationEnabled() {
        synchronized (mAwSettingsLock) {
            return mGeolocationEnabled;
        }
    }

    /**
     * See {@link android.webkit.WebSettings#setSaveFormData}.
     */
    public void setSaveFormData(final boolean enable) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) return;
        if (TRACE) Log.i(TAG, "setSaveFormData=" + enable);
        synchronized (mAwSettingsLock) {
            if (mAutoCompleteEnabled != enable) {
                mAutoCompleteEnabled = enable;
                mEventHandler.runOnUiThreadBlockingAndLocked(() -> {
                    if (mNativeAwSettings != 0) {
                        AwSettingsJni.get().updateFormDataPreferencesLocked(
                                mNativeAwSettings, AwSettings.this);
                    }
                });
            }
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getSaveFormData}.
     */
    public boolean getSaveFormData() {
        synchronized (mAwSettingsLock) {
            return getSaveFormDataLocked();
        }
    }

    @CalledByNative
    private boolean getSaveFormDataLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mAutoCompleteEnabled;
    }

    public void setUserAgent(int ua) {
        // Minimal implementation for backwards compatibility: just supports resetting to default.
        if (ua == 0) {
            setUserAgentString(null);
        } else {
            Log.w(TAG, "setUserAgent not supported, ua=" + ua);
        }
    }

    /**
     * @returns the default User-Agent used by each WebContents instance, i.e. unless
     * overridden by {@link #setUserAgentString()}
     */
    public static String getDefaultUserAgent() {
        return LazyDefaultUserAgent.sInstance;
    }

    @CalledByNative
    private static boolean getAllowSniffingFileUrls() {
        // Don't allow sniffing file:// URLs for MIME type if the application targets P or later.
        return ContextUtils.getApplicationContext().getApplicationInfo().targetSdkVersion
                < Build.VERSION_CODES.P;
    }

    /**
     * See {@link android.webkit.WebSettings#setUserAgentString}.
     */
    public void setUserAgentString(String ua) {
        if (TRACE) Log.i(TAG, "setUserAgentString=" + ua);
        synchronized (mAwSettingsLock) {
            final String oldUserAgent = mUserAgent;
            if (ua == null || ua.length() == 0) {
                mUserAgent = LazyDefaultUserAgent.sInstance;
            } else {
                mUserAgent = ua;
            }
            if (!oldUserAgent.equals(mUserAgent)) {
                if (ua != null && ua.length() > 0
                        && AwContents.BAD_HEADER_CHAR.matcher(ua).find()) {
                    throw new IllegalArgumentException(
                            AwContents.BAD_HEADER_MSG + "Invalid User-Agent '" + ua + "'");
                }
                mEventHandler.runOnUiThreadBlockingAndLocked(() -> {
                    if (mNativeAwSettings != 0) {
                        AwSettingsJni.get().updateUserAgentLocked(
                                mNativeAwSettings, AwSettings.this);
                    }
                });
            }
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getUserAgentString}.
     */
    public String getUserAgentString() {
        synchronized (mAwSettingsLock) {
            return getUserAgentLocked();
        }
    }

    @CalledByNative
    private String getUserAgentLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mUserAgent;
    }

    /**
     * See {@link android.webkit.WebSettings#setLoadWithOverviewMode}.
     */
    public void setLoadWithOverviewMode(boolean overview) {
        if (TRACE) Log.i(TAG, "setLoadWithOverviewMode=" + overview);
        synchronized (mAwSettingsLock) {
            if (mLoadWithOverviewMode != overview) {
                mLoadWithOverviewMode = overview;
                mEventHandler.runOnUiThreadBlockingAndLocked(() -> {
                    if (mNativeAwSettings != 0) {
                        updateWebkitPreferencesOnUiThreadLocked();
                        AwSettingsJni.get().resetScrollAndScaleState(
                                mNativeAwSettings, AwSettings.this);
                    }
                });
            }
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getLoadWithOverviewMode}.
     */
    public boolean getLoadWithOverviewMode() {
        synchronized (mAwSettingsLock) {
            return getLoadWithOverviewModeLocked();
        }
    }

    @CalledByNative
    private boolean getLoadWithOverviewModeLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mLoadWithOverviewMode;
    }

    /**
     * See {@link android.webkit.WebSettings#setTextZoom}.
     */
    public void setTextZoom(final int textZoom) {
        if (TRACE) Log.i(TAG, "setTextZoom=" + textZoom);
        synchronized (mAwSettingsLock) {
            if (mTextSizePercent != textZoom) {
                mTextSizePercent = textZoom;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getTextZoom}.
     */
    public int getTextZoom() {
        synchronized (mAwSettingsLock) {
            return getTextSizePercentLocked();
        }
    }

    @CalledByNative
    private int getTextSizePercentLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mTextSizePercent;
    }

    /**
     * See {@link android.webkit.WebSettings#setStandardFontFamily}.
     */
    public void setStandardFontFamily(String font) {
        if (TRACE) Log.i(TAG, "setStandardFontFamily=" + font);
        synchronized (mAwSettingsLock) {
            if (font != null && !mStandardFontFamily.equals(font)) {
                mStandardFontFamily = font;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getStandardFontFamily}.
     */
    public String getStandardFontFamily() {
        synchronized (mAwSettingsLock) {
            return getStandardFontFamilyLocked();
        }
    }

    @CalledByNative
    private String getStandardFontFamilyLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mStandardFontFamily;
    }

    /**
     * See {@link android.webkit.WebSettings#setFixedFontFamily}.
     */
    public void setFixedFontFamily(String font) {
        if (TRACE) Log.i(TAG, "setFixedFontFamily=" + font);
        synchronized (mAwSettingsLock) {
            if (font != null && !mFixedFontFamily.equals(font)) {
                mFixedFontFamily = font;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getFixedFontFamily}.
     */
    public String getFixedFontFamily() {
        synchronized (mAwSettingsLock) {
            return getFixedFontFamilyLocked();
        }
    }

    @CalledByNative
    private String getFixedFontFamilyLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mFixedFontFamily;
    }

    /**
     * See {@link android.webkit.WebSettings#setSansSerifFontFamily}.
     */
    public void setSansSerifFontFamily(String font) {
        if (TRACE) Log.i(TAG, "setSansSerifFontFamily=" + font);
        synchronized (mAwSettingsLock) {
            if (font != null && !mSansSerifFontFamily.equals(font)) {
                mSansSerifFontFamily = font;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getSansSerifFontFamily}.
     */
    public String getSansSerifFontFamily() {
        synchronized (mAwSettingsLock) {
            return getSansSerifFontFamilyLocked();
        }
    }

    @CalledByNative
    private String getSansSerifFontFamilyLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mSansSerifFontFamily;
    }

    /**
     * See {@link android.webkit.WebSettings#setSerifFontFamily}.
     */
    public void setSerifFontFamily(String font) {
        if (TRACE) Log.i(TAG, "setSerifFontFamily=" + font);
        synchronized (mAwSettingsLock) {
            if (font != null && !mSerifFontFamily.equals(font)) {
                mSerifFontFamily = font;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getSerifFontFamily}.
     */
    public String getSerifFontFamily() {
        synchronized (mAwSettingsLock) {
            return getSerifFontFamilyLocked();
        }
    }

    @CalledByNative
    private String getSerifFontFamilyLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mSerifFontFamily;
    }

    /**
     * See {@link android.webkit.WebSettings#setCursiveFontFamily}.
     */
    public void setCursiveFontFamily(String font) {
        if (TRACE) Log.i(TAG, "setCursiveFontFamily=" + font);
        synchronized (mAwSettingsLock) {
            if (font != null && !mCursiveFontFamily.equals(font)) {
                mCursiveFontFamily = font;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getCursiveFontFamily}.
     */
    public String getCursiveFontFamily() {
        synchronized (mAwSettingsLock) {
            return getCursiveFontFamilyLocked();
        }
    }

    @CalledByNative
    private String getCursiveFontFamilyLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mCursiveFontFamily;
    }

    /**
     * See {@link android.webkit.WebSettings#setFantasyFontFamily}.
     */
    public void setFantasyFontFamily(String font) {
        if (TRACE) Log.i(TAG, "setFantasyFontFamily=" + font);
        synchronized (mAwSettingsLock) {
            if (font != null && !mFantasyFontFamily.equals(font)) {
                mFantasyFontFamily = font;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getFantasyFontFamily}.
     */
    public String getFantasyFontFamily() {
        synchronized (mAwSettingsLock) {
            return getFantasyFontFamilyLocked();
        }
    }

    @CalledByNative
    private String getFantasyFontFamilyLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mFantasyFontFamily;
    }

    /**
     * See {@link android.webkit.WebSettings#setMinimumFontSize}.
     */
    public void setMinimumFontSize(int size) {
        if (TRACE) Log.i(TAG, "setMinimumFontSize=" + size);
        synchronized (mAwSettingsLock) {
            size = clipFontSize(size);
            if (mMinimumFontSize != size) {
                mMinimumFontSize = size;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getMinimumFontSize}.
     */
    public int getMinimumFontSize() {
        synchronized (mAwSettingsLock) {
            return getMinimumFontSizeLocked();
        }
    }

    @CalledByNative
    private int getMinimumFontSizeLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mMinimumFontSize;
    }

    /**
     * See {@link android.webkit.WebSettings#setMinimumLogicalFontSize}.
     */
    public void setMinimumLogicalFontSize(int size) {
        if (TRACE) Log.i(TAG, "setMinimumLogicalFontSize=" + size);
        synchronized (mAwSettingsLock) {
            size = clipFontSize(size);
            if (mMinimumLogicalFontSize != size) {
                mMinimumLogicalFontSize = size;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getMinimumLogicalFontSize}.
     */
    public int getMinimumLogicalFontSize() {
        synchronized (mAwSettingsLock) {
            return getMinimumLogicalFontSizeLocked();
        }
    }

    @CalledByNative
    private int getMinimumLogicalFontSizeLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mMinimumLogicalFontSize;
    }

    /**
     * See {@link android.webkit.WebSettings#setDefaultFontSize}.
     */
    public void setDefaultFontSize(int size) {
        if (TRACE) Log.i(TAG, "setDefaultFontSize=" + size);
        synchronized (mAwSettingsLock) {
            size = clipFontSize(size);
            if (mDefaultFontSize != size) {
                mDefaultFontSize = size;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getDefaultFontSize}.
     */
    public int getDefaultFontSize() {
        synchronized (mAwSettingsLock) {
            return getDefaultFontSizeLocked();
        }
    }

    @CalledByNative
    private int getDefaultFontSizeLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mDefaultFontSize;
    }

    /**
     * See {@link android.webkit.WebSettings#setDefaultFixedFontSize}.
     */
    public void setDefaultFixedFontSize(int size) {
        if (TRACE) Log.i(TAG, "setDefaultFixedFontSize=" + size);
        synchronized (mAwSettingsLock) {
            size = clipFontSize(size);
            if (mDefaultFixedFontSize != size) {
                mDefaultFixedFontSize = size;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getDefaultFixedFontSize}.
     */
    public int getDefaultFixedFontSize() {
        synchronized (mAwSettingsLock) {
            return getDefaultFixedFontSizeLocked();
        }
    }

    @CalledByNative
    private int getDefaultFixedFontSizeLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mDefaultFixedFontSize;
    }

    /**
     * See {@link android.webkit.WebSettings#setJavaScriptEnabled}.
     */
    public void setJavaScriptEnabled(boolean flag) {
        if (TRACE) Log.i(TAG, "setJavaScriptEnabled=" + flag);
        synchronized (mAwSettingsLock) {
            if (mJavaScriptEnabled != flag) {
                mJavaScriptEnabled = flag;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    /**
     * See {@link android.webkit.WebSettings#setAllowUniversalAccessFromFileURLs}.
     */
    public void setAllowUniversalAccessFromFileURLs(boolean flag) {
        if (TRACE) Log.i(TAG, "setAllowUniversalAccessFromFileURLs=" + flag);
        synchronized (mAwSettingsLock) {
            if (mAllowUniversalAccessFromFileURLs != flag) {
                mAllowUniversalAccessFromFileURLs = flag;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    /**
     * See {@link android.webkit.WebSettings#setAllowFileAccessFromFileURLs}.
     */
    public void setAllowFileAccessFromFileURLs(boolean flag) {
        if (TRACE) Log.i(TAG, "setAllowFileAccessFromFileURLs=" + flag);
        synchronized (mAwSettingsLock) {
            if (mAllowFileAccessFromFileURLs != flag) {
                mAllowFileAccessFromFileURLs = flag;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    /**
     * See {@link android.webkit.WebSettings#setLoadsImagesAutomatically}.
     */
    public void setLoadsImagesAutomatically(boolean flag) {
        if (TRACE) Log.i(TAG, "setLoadsImagesAutomatically=" + flag);
        synchronized (mAwSettingsLock) {
            if (mLoadsImagesAutomatically != flag) {
                mLoadsImagesAutomatically = flag;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getLoadsImagesAutomatically}.
     */
    public boolean getLoadsImagesAutomatically() {
        synchronized (mAwSettingsLock) {
            return getLoadsImagesAutomaticallyLocked();
        }
    }

    @CalledByNative
    private boolean getLoadsImagesAutomaticallyLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mLoadsImagesAutomatically;
    }

    /**
     * See {@link android.webkit.WebSettings#setImagesEnabled}.
     */
    public void setImagesEnabled(boolean flag) {
        if (TRACE) Log.i(TAG, "setBlockNetworkImage=" + flag);
        synchronized (mAwSettingsLock) {
            if (mImagesEnabled != flag) {
                mImagesEnabled = flag;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getImagesEnabled}.
     */
    public boolean getImagesEnabled() {
        synchronized (mAwSettingsLock) {
            return mImagesEnabled;
        }
    }

    @CalledByNative
    private boolean getImagesEnabledLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mImagesEnabled;
    }

    /**
     * See {@link android.webkit.WebSettings#getJavaScriptEnabled}.
     */
    public boolean getJavaScriptEnabled() {
        synchronized (mAwSettingsLock) {
            return mJavaScriptEnabled;
        }
    }

    @CalledByNative
    private boolean getJavaScriptEnabledLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mJavaScriptEnabled;
    }

    /**
     * See {@link android.webkit.WebSettings#getAllowUniversalAccessFromFileURLs}.
     */
    public boolean getAllowUniversalAccessFromFileURLs() {
        synchronized (mAwSettingsLock) {
            return getAllowUniversalAccessFromFileURLsLocked();
        }
    }

    @CalledByNative
    private boolean getAllowUniversalAccessFromFileURLsLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mAllowUniversalAccessFromFileURLs;
    }

    /**
     * See {@link android.webkit.WebSettings#getAllowFileAccessFromFileURLs}.
     */
    public boolean getAllowFileAccessFromFileURLs() {
        synchronized (mAwSettingsLock) {
            return getAllowFileAccessFromFileURLsLocked();
        }
    }

    @CalledByNative
    private boolean getAllowFileAccessFromFileURLsLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mAllowFileAccessFromFileURLs;
    }

    /**
     * See {@link android.webkit.WebSettings#setJavaScriptCanOpenWindowsAutomatically}.
     */
    public void setJavaScriptCanOpenWindowsAutomatically(boolean flag) {
        if (TRACE) Log.i(TAG, "setJavaScriptCanOpenWindowsAutomatically=" + flag);
        synchronized (mAwSettingsLock) {
            if (mJavaScriptCanOpenWindowsAutomatically != flag) {
                mJavaScriptCanOpenWindowsAutomatically = flag;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getJavaScriptCanOpenWindowsAutomatically}.
     */
    public boolean getJavaScriptCanOpenWindowsAutomatically() {
        synchronized (mAwSettingsLock) {
            return getJavaScriptCanOpenWindowsAutomaticallyLocked();
        }
    }

    @CalledByNative
    private boolean getJavaScriptCanOpenWindowsAutomaticallyLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mJavaScriptCanOpenWindowsAutomatically;
    }

    /**
     * See {@link android.webkit.WebSettings#setLayoutAlgorithm}.
     */
    public void setLayoutAlgorithm(@LayoutAlgorithm int l) {
        if (TRACE) Log.i(TAG, "setLayoutAlgorithm=" + l);
        synchronized (mAwSettingsLock) {
            if (mLayoutAlgorithm != l) {
                mLayoutAlgorithm = l;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getLayoutAlgorithm}.
     */
    @LayoutAlgorithm
    public int getLayoutAlgorithm() {
        synchronized (mAwSettingsLock) {
            return mLayoutAlgorithm;
        }
    }

    public void setRequestedWithHeaderMode(@RequestedWithHeaderMode int mode) {
        AwWebContentsMetricsRecorder.recordRequestedWithHeaderModeAPIUsage(mode);
        synchronized (mAwSettingsLock) {
            mRequestedWithHeaderMode = mode;
        }
    }

    @RequestedWithHeaderMode
    public int getRequestedWithHeaderMode() {
        synchronized (mAwSettingsLock) {
            return mRequestedWithHeaderMode;
        }
    }

    /**
     * Gets whether Text Auto-sizing layout algorithm is enabled.
     *
     * @return true if Text Auto-sizing layout algorithm is enabled
     */
    @CalledByNative
    private boolean getTextAutosizingEnabledLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mLayoutAlgorithm == LAYOUT_ALGORITHM_TEXT_AUTOSIZING;
    }

    /**
     * See {@link android.webkit.WebSettings#setSupportMultipleWindows}.
     */
    public void setSupportMultipleWindows(boolean support) {
        if (TRACE) Log.i(TAG, "setSupportMultipleWindows=" + support);
        synchronized (mAwSettingsLock) {
            if (mSupportMultipleWindows != support) {
                mSupportMultipleWindows = support;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    /**
     * See {@link android.webkit.WebSettings#supportMultipleWindows}.
     */
    public boolean supportMultipleWindows() {
        synchronized (mAwSettingsLock) {
            return mSupportMultipleWindows;
        }
    }

    @CalledByNative
    private boolean getSupportMultipleWindowsLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mSupportMultipleWindows;
    }

    @CalledByNative
    private boolean getCSSHexAlphaColorEnabledLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mCSSHexAlphaColorEnabled;
    }

    public void setCSSHexAlphaColorEnabled(boolean enabled) {
        synchronized (mAwSettingsLock) {
            if (mCSSHexAlphaColorEnabled != enabled) {
                mCSSHexAlphaColorEnabled = enabled;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    @CalledByNative
    private boolean getScrollTopLeftInteropEnabledLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mScrollTopLeftInteropEnabled;
    }

    public void setScrollTopLeftInteropEnabled(boolean enabled) {
        synchronized (mAwSettingsLock) {
            if (mScrollTopLeftInteropEnabled != enabled) {
                mScrollTopLeftInteropEnabled = enabled;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    @CalledByNative
    private boolean getWillSuppressErrorPageLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mWillSuppressErrorPage;
    }

    public boolean getWillSuppressErrorPage() {
        synchronized (mAwSettingsLock) {
            return getWillSuppressErrorPageLocked();
        }
    }

    public void setWillSuppressErrorPage(boolean suppressed) {
        synchronized (mAwSettingsLock) {
            if (mWillSuppressErrorPage == suppressed) return;

            mWillSuppressErrorPage = suppressed;
            updateWillSuppressErrorStateLocked();
        }
    }

    private void updateWillSuppressErrorStateLocked() {
        mEventHandler.runOnUiThreadBlockingAndLocked(() -> {
            assert Thread.holdsLock(mAwSettingsLock);
            assert mNativeAwSettings != 0;
            AwSettingsJni.get().updateWillSuppressErrorStateLocked(
                    mNativeAwSettings, AwSettings.this);
        });
    }

    @CalledByNative
    private boolean getSupportLegacyQuirksLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mSupportLegacyQuirks;
    }

    @CalledByNative
    private boolean getAllowEmptyDocumentPersistenceLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mAllowEmptyDocumentPersistence;
    }

    @CalledByNative
    private boolean getAllowGeolocationOnInsecureOrigins() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mAllowGeolocationOnInsecureOrigins;
    }

    @CalledByNative
    private boolean getDoNotUpdateSelectionOnMutatingSelectionRange() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mDoNotUpdateSelectionOnMutatingSelectionRange;
    }

    /**
     * See {@link android.webkit.WebSettings#setUseWideViewPort}.
     */
    public void setUseWideViewPort(boolean use) {
        if (TRACE) Log.i(TAG, "setUseWideViewPort=" + use);
        synchronized (mAwSettingsLock) {
            if (mUseWideViewport != use) {
                mUseWideViewport = use;
                onGestureZoomSupportChanged(
                        supportsDoubleTapZoomLocked(), supportsMultiTouchZoomLocked());
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getUseWideViewPort}.
     */
    public boolean getUseWideViewPort() {
        synchronized (mAwSettingsLock) {
            return getUseWideViewportLocked();
        }
    }

    @CalledByNative
    private boolean getUseWideViewportLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mUseWideViewport;
    }

    public void setZeroLayoutHeightDisablesViewportQuirk(boolean enabled) {
        synchronized (mAwSettingsLock) {
            if (mZeroLayoutHeightDisablesViewportQuirk != enabled) {
                mZeroLayoutHeightDisablesViewportQuirk = enabled;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    public boolean getZeroLayoutHeightDisablesViewportQuirk() {
        synchronized (mAwSettingsLock) {
            return getZeroLayoutHeightDisablesViewportQuirkLocked();
        }
    }

    @CalledByNative
    private boolean getZeroLayoutHeightDisablesViewportQuirkLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mZeroLayoutHeightDisablesViewportQuirk;
    }

    public void setForceZeroLayoutHeight(boolean enabled) {
        synchronized (mAwSettingsLock) {
            if (mForceZeroLayoutHeight != enabled) {
                mForceZeroLayoutHeight = enabled;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    public boolean getForceZeroLayoutHeight() {
        synchronized (mAwSettingsLock) {
            return getForceZeroLayoutHeightLocked();
        }
    }

    @CalledByNative
    private boolean getForceZeroLayoutHeightLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mForceZeroLayoutHeight;
    }

    @CalledByNative
    private boolean getPasswordEchoEnabledLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mPasswordEchoEnabled;
    }

    /**
     * See {@link android.webkit.WebSettings#setDomStorageEnabled}.
     */
    public void setDomStorageEnabled(boolean flag) {
        if (TRACE) Log.i(TAG, "setDomStorageEnabled=" + flag);
        synchronized (mAwSettingsLock) {
            if (mDomStorageEnabled != flag) {
                mDomStorageEnabled = flag;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getDomStorageEnabled}.
     */
    public boolean getDomStorageEnabled() {
        synchronized (mAwSettingsLock) {
            return mDomStorageEnabled;
        }
    }

    @CalledByNative
    private boolean getDomStorageEnabledLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mDomStorageEnabled;
    }

    /**
     * See {@link android.webkit.WebSettings#setDatabaseEnabled}.
     */
    public void setDatabaseEnabled(boolean flag) {
        if (TRACE) Log.i(TAG, "setDatabaseEnabled=" + flag);
        synchronized (mAwSettingsLock) {
            if (mDatabaseEnabled != flag) {
                mDatabaseEnabled = flag;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getDatabaseEnabled}.
     */
    public boolean getDatabaseEnabled() {
        synchronized (mAwSettingsLock) {
            return mDatabaseEnabled;
        }
    }

    @CalledByNative
    private boolean getDatabaseEnabledLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mDatabaseEnabled;
    }

    /**
     * See {@link android.webkit.WebSettings#setDefaultTextEncodingName}.
     */
    public void setDefaultTextEncodingName(String encoding) {
        if (TRACE) Log.i(TAG, "setDefaultTextEncodingName=" + encoding);
        synchronized (mAwSettingsLock) {
            if (encoding != null && !mDefaultTextEncoding.equals(encoding)) {
                mDefaultTextEncoding = encoding;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getDefaultTextEncodingName}.
     */
    public String getDefaultTextEncodingName() {
        synchronized (mAwSettingsLock) {
            return getDefaultTextEncodingLocked();
        }
    }

    @CalledByNative
    private String getDefaultTextEncodingLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mDefaultTextEncoding;
    }

    /**
     * See {@link android.webkit.WebSettings#setMediaPlaybackRequiresUserGesture}.
     */
    public void setMediaPlaybackRequiresUserGesture(boolean require) {
        if (TRACE) Log.i(TAG, "setMediaPlaybackRequiresUserGesture=" + require);
        synchronized (mAwSettingsLock) {
            if (mMediaPlaybackRequiresUserGesture != require) {
                mMediaPlaybackRequiresUserGesture = require;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getMediaPlaybackRequiresUserGesture}.
     */
    public boolean getMediaPlaybackRequiresUserGesture() {
        synchronized (mAwSettingsLock) {
            return getMediaPlaybackRequiresUserGestureLocked();
        }
    }

    @CalledByNative
    private boolean getMediaPlaybackRequiresUserGestureLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mMediaPlaybackRequiresUserGesture;
    }

    /**
     * See {@link android.webkit.WebSettings#setDefaultVideoPosterURL}.
     */
    public void setDefaultVideoPosterURL(String url) {
        synchronized (mAwSettingsLock) {
            if ((mDefaultVideoPosterURL != null && !mDefaultVideoPosterURL.equals(url))
                    || (mDefaultVideoPosterURL == null && url != null)) {
                mDefaultVideoPosterURL = url;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getDefaultVideoPosterURL}.
     */
    public String getDefaultVideoPosterURL() {
        synchronized (mAwSettingsLock) {
            return getDefaultVideoPosterURLLocked();
        }
    }

    @CalledByNative
    private String getDefaultVideoPosterURLLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mDefaultVideoPosterURL;
    }

    private void onGestureZoomSupportChanged(
            final boolean supportsDoubleTapZoom, final boolean supportsMultiTouchZoom) {
        // Always post asynchronously here, to avoid doubling back onto the caller.
        mEventHandler.maybePostOnUiThread(() -> {
            synchronized (mAwSettingsLock) {
                if (mZoomChangeListener != null) {
                    mZoomChangeListener.onGestureZoomSupportChanged(
                            supportsDoubleTapZoom, supportsMultiTouchZoom);
                }
}
        });
    }

    /**
     * See {@link android.webkit.WebSettings#setSupportZoom}.
     */
    public void setSupportZoom(boolean support) {
        if (TRACE) Log.i(TAG, "setSupportZoom=" + support);
        synchronized (mAwSettingsLock) {
            if (mSupportZoom != support) {
                mSupportZoom = support;
                onGestureZoomSupportChanged(
                        supportsDoubleTapZoomLocked(), supportsMultiTouchZoomLocked());
            }
        }
    }

    /**
     * See {@link android.webkit.WebSettings#supportZoom}.
     */
    public boolean supportZoom() {
        synchronized (mAwSettingsLock) {
            return mSupportZoom;
        }
    }

    /**
     * See {@link android.webkit.WebSettings#setBuiltInZoomControls}.
     */
    public void setBuiltInZoomControls(boolean enabled) {
        if (TRACE) Log.i(TAG, "setBuiltInZoomControls=" + enabled);
        synchronized (mAwSettingsLock) {
            if (mBuiltInZoomControls != enabled) {
                mBuiltInZoomControls = enabled;
                onGestureZoomSupportChanged(
                        supportsDoubleTapZoomLocked(), supportsMultiTouchZoomLocked());
            }
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getBuiltInZoomControls}.
     */
    public boolean getBuiltInZoomControls() {
        synchronized (mAwSettingsLock) {
            return mBuiltInZoomControls;
        }
    }

    /**
     * See {@link android.webkit.WebSettings#setDisplayZoomControls}.
     */
    public void setDisplayZoomControls(boolean enabled) {
        if (TRACE) Log.i(TAG, "setDisplayZoomControls=" + enabled);
        synchronized (mAwSettingsLock) {
            mDisplayZoomControls = enabled;
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getDisplayZoomControls}.
     */
    public boolean getDisplayZoomControls() {
        synchronized (mAwSettingsLock) {
            return mDisplayZoomControls;
        }
    }

    public void setMixedContentMode(int mode) {
        // Using explicit max count for the histogram since enum is defined in Android code. The
        // values can be trusted to remain stable since they are defined in the Android API.
        RecordHistogram.recordEnumeratedHistogram("Android.WebView.MixedContent.Mode", mode, 3);
        synchronized (mAwSettingsLock) {
            if (mMixedContentMode != mode) {
                mMixedContentMode = mode;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    public int getMixedContentMode() {
        synchronized (mAwSettingsLock) {
            return mMixedContentMode;
        }
    }

    @ForceDarkMode
    public int getForceDarkMode() {
        synchronized (mAwSettingsLock) {
            return getForceDarkModeLocked();
        }
    }

    @CalledByNative
    @ForceDarkMode
    private int getForceDarkModeLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mForceDarkMode;
    }

    public void setForceDarkMode(@ForceDarkMode int forceDarkMode) {
        AwWebContentsMetricsRecorder.recordForceDarkModeAPIUsage(mContext, forceDarkMode);
        synchronized (mAwSettingsLock) {
            if (mForceDarkMode != forceDarkMode) {
                mForceDarkMode = forceDarkMode;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    public boolean isAlgorithmicDarkeningAllowed() {
        synchronized (mAwSettingsLock) {
            return isAlgorithmicDarkeningAllowedLocked();
        }
    }

    @CalledByNative
    private boolean isAlgorithmicDarkeningAllowedLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mAlgorithmicDarkeningAllowed;
    }

    public void setAlgorithmicDarkeningAllowed(boolean allow) {
        synchronized (mAwSettingsLock) {
            if (mAlgorithmicDarkeningAllowed != allow) {
                mAlgorithmicDarkeningAllowed = allow;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    public boolean isForceDarkApplied() {
        synchronized (mAwSettingsLock) {
            assert mNativeAwSettings != 0;
            return AwSettingsJni.get().isForceDarkApplied(mNativeAwSettings, AwSettings.this);
        }
    }

    @ForceDarkBehavior
    public int getForceDarkBehavior() {
        synchronized (mAwSettingsLock) {
            return getForceDarkBehaviorLocked();
        }
    }

    @CalledByNative
    @ForceDarkBehavior
    public int getForceDarkBehaviorLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mForceDarkBehavior;
    }

    public void setForceDarkBehavior(@ForceDarkBehavior int forceDarkBehavior) {
        AwWebContentsMetricsRecorder.recordForceDarkBehaviorAPIUsage(forceDarkBehavior);
        synchronized (mAwSettingsLock) {
            if (mForceDarkBehavior != forceDarkBehavior) {
                mForceDarkBehavior = forceDarkBehavior;
                mEventHandler.updateWebkitPreferencesLocked();
            }
        }
    }

    @CalledByNative
    private boolean getAllowRunningInsecureContentLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mMixedContentMode == WebSettings.MIXED_CONTENT_ALWAYS_ALLOW;
    }

    @CalledByNative
    private boolean getUseStricMixedContentCheckingLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mMixedContentMode == WebSettings.MIXED_CONTENT_NEVER_ALLOW;
    }

    @CalledByNative
    private boolean getAllowMixedContentAutoupgradesLocked() {
        if (AwFeatureList.isEnabled(AwFeatures.WEBVIEW_MIXED_CONTENT_AUTOUPGRADES)) {
            // We only allow mixed content autoupgrades (upgrading HTTP subresources to HTTPS in
            // HTTPS sites) when the mixed content mode is set to MIXED_CONTENT_COMPATIBILITY,
            // which keeps it in line with the behavior in Chrome. With
            // MIXED_CONTENT_ALWAYS_ALLOW, we disable autoupgrades since the developer is
            // explicitly allowing mixed content, whereas with MIXED_CONTENT_NEVER_ALLOW, there
            // is no need to autoupgrade since the content will be blocked.
            assert Thread.holdsLock(mAwSettingsLock);
            return mMixedContentMode == WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE;
        }
        return false;
    }

    public boolean getOffscreenPreRaster() {
        synchronized (mAwSettingsLock) {
            return getOffscreenPreRasterLocked();
        }
    }

    @CalledByNative
    private boolean getOffscreenPreRasterLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mOffscreenPreRaster;
    }

    /**
     * Sets whether this WebView should raster tiles when it is
     * offscreen but attached to window. Turning this on can avoid
     * rendering artifacts when animating an offscreen WebView on-screen.
     * In particular, insertVisualStateCallback requires this mode to function.
     * Offscreen WebViews in this mode uses more memory. Please follow
     * these guidelines to limit memory usage:
     * - Webview size should be not be larger than the device screen size.
     * - Limit simple mode to a small number of webviews. Use it for
     *   visible webviews and webviews about to be animated to visible.
     */
    public void setOffscreenPreRaster(boolean enabled) {
        synchronized (mAwSettingsLock) {
            if (enabled != mOffscreenPreRaster) {
                mOffscreenPreRaster = enabled;
                mEventHandler.runOnUiThreadBlockingAndLocked(() -> {
                    if (mNativeAwSettings != 0) {
                        AwSettingsJni.get().updateOffscreenPreRasterLocked(
                                mNativeAwSettings, AwSettings.this);
                    }
                });
            }
        }
    }

    public int getDisabledActionModeMenuItems() {
        synchronized (mAwSettingsLock) {
            return mDisabledMenuItems;
        }
    }

    public void setDisabledActionModeMenuItems(int menuItems) {
        synchronized (mAwSettingsLock) {
            mDisabledMenuItems = menuItems;
        }
    }

    public void updateAcceptLanguages() {
        synchronized (mAwSettingsLock) {
            mEventHandler.runOnUiThreadBlockingAndLocked(() -> {
                if (mNativeAwSettings != 0) {
                    AwSettingsJni.get().updateRendererPreferencesLocked(
                            mNativeAwSettings, AwSettings.this);
                }
            });
        }
    }

    @CalledByNative
    private boolean supportsDoubleTapZoomLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mSupportZoom && mBuiltInZoomControls && mUseWideViewport;
    }

    private boolean supportsMultiTouchZoomLocked() {
        assert Thread.holdsLock(mAwSettingsLock);
        return mSupportZoom && mBuiltInZoomControls;
    }

    boolean supportsMultiTouchZoom() {
        synchronized (mAwSettingsLock) {
            return supportsMultiTouchZoomLocked();
        }
    }

    boolean shouldDisplayZoomControls() {
        synchronized (mAwSettingsLock) {
            return supportsMultiTouchZoomLocked() && mDisplayZoomControls;
        }
    }

    private int clipFontSize(int size) {
        if (size < MINIMUM_FONT_SIZE) {
            return MINIMUM_FONT_SIZE;
        } else if (size > MAXIMUM_FONT_SIZE) {
            return MAXIMUM_FONT_SIZE;
        }
        return size;
    }

    @CalledByNative
    private boolean getRecordFullDocument() {
        assert Thread.holdsLock(mAwSettingsLock);
        return AwContentsStatics.getRecordFullDocument();
    }

    @CalledByNative
    private void updateEverything() {
        synchronized (mAwSettingsLock) {
            updateEverythingLocked();
        }
    }

    @CalledByNative
    private void populateWebPreferences(long webPrefsPtr) {
        synchronized (mAwSettingsLock) {
            assert mNativeAwSettings != 0;
            AwSettingsJni.get().populateWebPreferencesLocked(
                    mNativeAwSettings, AwSettings.this, webPrefsPtr);
        }
    }

    private void updateWebkitPreferencesOnUiThreadLocked() {
        assert mEventHandler.mHandler != null;
        ThreadUtils.assertOnUiThread();
        if (mNativeAwSettings != 0) {
            AwSettingsJni.get().updateWebkitPreferencesLocked(mNativeAwSettings, AwSettings.this);
        }
    }

    private void updateCookiePolicyOnUiThreadLocked() {
        assert mEventHandler.mHandler != null;
        ThreadUtils.assertOnUiThread();
        if (mNativeAwSettings != 0) {
            AwSettingsJni.get().updateCookiePolicyLocked(mNativeAwSettings, AwSettings.this);
        }
    }

    private void updateAllowFileAccessOnUiThreadLocked() {
        assert mEventHandler.mHandler != null;
        ThreadUtils.assertOnUiThread();
        if (mNativeAwSettings != 0) {
            AwSettingsJni.get().updateAllowFileAccessLocked(mNativeAwSettings, AwSettings.this);
        }
    }

    @NativeMethods
    interface Natives {
        long init(AwSettings caller, WebContents webContents);
        void destroy(long nativeAwSettings, AwSettings caller);
        void populateWebPreferencesLocked(
                long nativeAwSettings, AwSettings caller, long webPrefsPtr);
        void resetScrollAndScaleState(long nativeAwSettings, AwSettings caller);
        void updateEverythingLocked(long nativeAwSettings, AwSettings caller);
        void updateInitialPageScaleLocked(long nativeAwSettings, AwSettings caller);
        void updateUserAgentLocked(long nativeAwSettings, AwSettings caller);
        void updateWebkitPreferencesLocked(long nativeAwSettings, AwSettings caller);
        String getDefaultUserAgent();
        void updateFormDataPreferencesLocked(long nativeAwSettings, AwSettings caller);
        void updateRendererPreferencesLocked(long nativeAwSettings, AwSettings caller);
        void updateOffscreenPreRasterLocked(long nativeAwSettings, AwSettings caller);
        void updateWillSuppressErrorStateLocked(long nativeAwSettings, AwSettings caller);
        void updateCookiePolicyLocked(long nativeAwSettings, AwSettings caller);
        void updateAllowFileAccessLocked(long nativeAwSettings, AwSettings caller);
        boolean isForceDarkApplied(long nativeAwSettings, AwSettings caller);
    }
}


text:
import {Exception} from '@ciscospark/common';

/**
 * General conversation error
 */
export class ConversationError extends Exception {}

/**
 * InvalidUserCreation thrown when failed to create conversation with invalid user
 */
export class InvalidUserCreation extends ConversationError {}

redpajama_set_name: RedPajamaGithub


text:
package generator

import (
	"fmt"
	"reflect"

	kapi "k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/kubectl"
	"k8s.io/kubernetes/pkg/runtime"

	deployapi "github.com/openshift/origin/pkg/deploy/api"
)

var basic = kubectl.BasicReplicationController{}

type BasicDeploymentConfigController struct{}

func (BasicDeploymentConfigController) ParamNames() []kubectl.GeneratorParam {
	return basic.ParamNames()
}

func (BasicDeploymentConfigController) Generate(genericParams map[string]interface{}) (runtime.Object, error) {
	obj, err := basic.Generate(genericParams)
	if err != nil {
		return nil, err
	}
	switch t := obj.(type) {
	case *kapi.ReplicationController:
		obj = &deployapi.DeploymentConfig{
			ObjectMeta: t.ObjectMeta,
			Spec: deployapi.DeploymentConfigSpec{
				Selector: t.Spec.Selector,
				Replicas: t.Spec.Replicas,
				Template: t.Spec.Template,
			},
		}
	default:
		return nil, fmt.Errorf("unrecognized object type: %v", reflect.TypeOf(t))
	}
	return obj, nil
}


text:
package com.lzf.learn.testing.junit.performace;

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

/**
 * Learn_JMH_benchmark_的使用
 *
 * @author Jamefeng liu
 * @date 2016-12-26
 */
public class Learn_JMH_benchmark_的使用 {

    @Benchmark
    public void testMethod() throws InterruptedException {
        // This is a demo/sample template for building your JMH benchmarks. Edit as needed.
        // Put your benchmark code here
        Thread.sleep(2000);
        System.out.println("Hello world!! 2s 的方法!");
    }

    /*
     * ============================== HOW TO RUN THIS TEST: ====================================
     *
     * You are expected to see the run with large number of iterations, and
     * very large throughput numbers. You can see that as the estimate of the
     * harness overheads per method call. In most of our measurements, it is
     * down to several cycles per call.
     *
     * a) Via command-line:
     *    $ mvn clean install
     *    $ java -jar target/benchmarks.jar JMHSample_01
     *
     * JMH generates self-contained JARs, bundling JMH together with it.
     * The runtime options for the JMH are available with "-h":
     *    $ java -jar target/benchmarks.jar -h
     *
     * b) Via the Java API:
     *    (see the JMH homepage for possible caveats when running from IDE:
     *      http://openjdk.java.net/projects/code-tools/jmh/)
     */

    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder()
                .include(Learn_JMH_benchmark_的使用.class.getSimpleName())
                .forks(1)
                .build();

        new Runner(opt).run();
    }
}


text:
CREATE USER 'ippr'@'localhost' IDENTIFIED BY 'Pa$$w0rd';
GRANT ALL PRIVILEGES ON * . * TO 'ippr'@'localhost';
FLUSH PRIVILEGES;


text:
<template>

    ${title}

         code

      <button type="button" class="btn btn-outline-secondary" data-test="toggle-readonly-btn"
              click.delegate="toggleGridEditReadonly()">
         Toggle Edit/Readonly Grid
      </button>
      <button type="button" class="btn btn-outline-secondary" data-test="undo-last-edit-btn"
              click.delegate="undoLastEdit()">
         Undo Last Edit
      </button>
      <button type="button" class="btn btn-outline-secondary" data-test="undo-open-editor-btn"
              click.delegate="undoLastEdit(true)">
         Undo Last Edit & Open Editor
      </button>
      <button type="button" class="btn btn-outline-secondary" data-test="undo-all-edits-btn"
              click.delegate="undoAllEdits()">
         Undo All Edits
      </button>
      <button type="button" class="btn btn-outline-secondary" data-test="save-all-btn"
              click.delegate="saveAll()">
         Save All
      </button>

      <button type="button" class="btn btn-outline-secondary" data-test="open-modal-create-btn"
              click.delegate="openCompositeModal('create')" disabled.bind="isCompositeDisabled">
         Item Create
      </button>
      <button type="button" class="btn btn-outline-secondary" data-test="open-modal-clone-btn"
              click.delegate="openCompositeModal('clone')" disabled.bind="isCompositeDisabled">
         Item Clone
      </button>
      <button type="button" class="btn btn-outline-secondary" data-test="open-modal-edit-btn"
              click.delegate="openCompositeModal('edit')" disabled.bind="isCompositeDisabled">
         Item Edit
      </button>
      <button type="button" class="btn btn-outline-secondary" data-test="open-modal-mass-update-btn"
              click.delegate="openCompositeModal('mass-update')" disabled.bind="isCompositeDisabled">
         Mass Update
      </button>
      <button type="button" class="btn btn-outline-secondary" data-test="open-modal-mass-selection-btn"
              click.delegate="openCompositeModal('mass-selection')" disabled.bind="isMassSelectionDisabled">
         Update Selected
      </button>

  <aurelia-slickgrid grid-id="grid30"
                     column-definitions.bind="columnDefinitions"
                     grid-options.bind="gridOptions"
                     dataset.bind="dataset"
                     on-aurelia-grid-created.delegate="aureliaGridReady($event.detail)"
                     on-before-edit-cell.delegate="handleOnBeforeEditCell($event.detail.eventData, $event.detail.args)"
                     on-cell-change.delegate="handleOnCellChange($event.detail.eventData, $event.detail.args)"
                     on-click.delegate="handleOnCellClicked($event.detail.eventData, $event.detail.args)"
                     on-composite-editor-change.delegate="handleOnCompositeEditorChange($event.detail.eventData, $event.detail.args)"
                     on-item-deleted.delegate="handleItemDeleted($event.detail.eventData, $event.detail.args)"
                     on-grid-state-changed.delegate="handleOnGridStateChanged($event.detail)"
                     on-filter-changed.delegate="handleReRenderUnsavedStyling()"
                     on-pagination-changed.delegate="handleReRenderUnsavedStyling()"
                     on-validation-error.delegate="handleValidationError($event.detail.eventData, $event.detail.args)">
  </aurelia-slickgrid>
</template>


text:
using std::cout;
using std::cerr;
using std::endl;

#include <string>
using std::string;

#include <stdexcept>
using std::runtime_error;

#include "osrng.h"
using CryptoPP::AutoSeededRandomPool;

#include "integer.h"
using CryptoPP::Integer;

#include "nbtheory.h"
using CryptoPP::ModularExponentiation;

#include "dh.h"
using CryptoPP::DH;

#include "dh2.h"
using CryptoPP::DH2;

#include "secblock.h"
using CryptoPP::SecByteBlock;

typedef int Signature;
typedef int ID;
typedef int MAC;
typedef int KEY;

@interface SigmaParty : NSObject
- (KEY)generateKeys;  //s, g^x
- (ID)generateID:(int) partyID;
- (Signature)sign:(KEY)secretKey;
- (MAC)generateMAC:(ID)partyID key:(KEY)key;
- (BOOL)verifyMac:(MAC)mac;
- (BOOL)verifySignature:(Signature)signature;
- (void)initiateProtocol:(SigmaParty *)party;  //sends s, g^x
- (void)sendSigmaParty:(SigmaParty *)party key:(KEY)key signature:(Signature)signature identity:(ID)identity mac:(MAC)mac;
- (void)verifyMessageFromParty:(SigmaParty *)party key:(KEY)key signature:(Signature)signature identity:(ID)identity mac:(MAC)mac;

@end


text:
package ws16.tut5.example;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * Created by sebb on 12/14/16.
 */
public class Roulette implements Iterable<Integer> {

    public static class RouletteIterator implements Iterator<Integer>
    {
        boolean hasEnded = false;

        public boolean hasNext()
        {
            return !hasEnded;
        }

        public Integer next()
        {
            if(!hasNext())
                throw new NoSuchElementException();

            int num = (int)(Math.random() * 42) + 1;

            if(num == 42)
                hasEnded = true;

            return num;
        }
    }

    @Override
    public Iterator<Integer> iterator() {
        return new RouletteIterator();
    }

    public static void main(String[] args) {
        Roulette r = new Roulette();

        System.out.println("Versuch 1:");
        for(int i : r)
            System.out.println(i);

        System.out.println();
        System.out.println("Versuch 2:");
        for(int i : r)
            System.out.println(i);
    }
}


text:
SELECT 'Upgrading MetaStore schema from 3.2.0 to 4.0.0';

-- HIVE-19416
ALTER TABLE "TBLS" ADD "WRITE_ID" bigint DEFAULT 0;
ALTER TABLE "PARTITIONS" ADD "WRITE_ID" bigint DEFAULT 0;

-- HIVE-20793
ALTER TABLE "WM_RESOURCEPLAN" ADD "NS" character varying(128);
UPDATE "WM_RESOURCEPLAN" SET "NS" = 'default' WHERE "NS" IS NULL;
ALTER TABLE "WM_RESOURCEPLAN" DROP CONSTRAINT "UNIQUE_WM_RESOURCEPLAN";
ALTER TABLE ONLY "WM_RESOURCEPLAN" ADD CONSTRAINT "UNIQUE_WM_RESOURCEPLAN" UNIQUE ("NS", "NAME");

-- HIVE-21063
CREATE UNIQUE INDEX "NOTIFICATION_LOG_EVENT_ID" ON "NOTIFICATION_LOG" USING btree ("EVENT_ID");

-- HIVE-22046 (DEFAULT HIVE)
ALTER TABLE "TAB_COL_STATS" ADD "ENGINE" character varying(128);
UPDATE "TAB_COL_STATS" SET "ENGINE" = 'hive' WHERE "ENGINE" IS NULL;
ALTER TABLE "PART_COL_STATS" ADD "ENGINE" character varying(128);
UPDATE "PART_COL_STATS" SET "ENGINE" = 'hive' WHERE "ENGINE" IS NULL;

CREATE TABLE "SCHEDULED_QUERIES" (
	"SCHEDULED_QUERY_ID" BIGINT NOT NULL,
	"CLUSTER_NAMESPACE" VARCHAR(256),
	"ENABLED" boolean NOT NULL,
	"NEXT_EXECUTION" INTEGER,
	"QUERY" VARCHAR(4000),
	"SCHEDULE" VARCHAR(256),
	"SCHEDULE_NAME" VARCHAR(256),
	"USER" VARCHAR(256),
	CONSTRAINT SCHEDULED_QUERIES_PK PRIMARY KEY ("SCHEDULED_QUERY_ID")
);

CREATE TABLE "SCHEDULED_EXECUTIONS" (
	"SCHEDULED_EXECUTION_ID" BIGINT NOT NULL,
	"END_TIME" INTEGER,
	"ERROR_MESSAGE" VARCHAR(2000),
	"EXECUTOR_QUERY_ID" VARCHAR(256),
	"LAST_UPDATE_TIME" INTEGER,
	"SCHEDULED_QUERY_ID" BIGINT,
	"START_TIME" INTEGER,
	"STATE" VARCHAR(256),
	CONSTRAINT SCHEDULED_EXECUTIONS_PK PRIMARY KEY ("SCHEDULED_EXECUTION_ID"),
	CONSTRAINT SCHEDULED_EXECUTIONS_SCHQ_FK FOREIGN KEY ("SCHEDULED_QUERY_ID") REFERENCES "SCHEDULED_QUERIES"("SCHEDULED_QUERY_ID") ON DELETE CASCADE
);

CREATE INDEX IDX_SCHEDULED_EXECUTIONS_LAST_UPDATE_TIME ON "SCHEDULED_EXECUTIONS" ("LAST_UPDATE_TIME");
CREATE INDEX IDX_SCHEDULED_EXECUTIONS_SCHEDULED_QUERY_ID ON "SCHEDULED_EXECUTIONS" ("SCHEDULED_QUERY_ID");
CREATE UNIQUE INDEX UNIQUE_SCHEDULED_EXECUTIONS_ID ON "SCHEDULED_EXECUTIONS" ("SCHEDULED_EXECUTION_ID");

-- HIVE-22546

ALTER TABLE aux_table RENAME TO "AUX_TABLE";
ALTER TABLE "AUX_TABLE" RENAME COLUMN mt_key1 TO "MT_KEY1";
ALTER TABLE "AUX_TABLE" RENAME COLUMN mt_key2 TO "MT_KEY2";
ALTER TABLE "AUX_TABLE" RENAME COLUMN mt_comment TO "MT_COMMENT";

ALTER TABLE compaction_queue RENAME TO "COMPACTION_QUEUE";
ALTER TABLE "COMPACTION_QUEUE" RENAME COLUMN cq_id TO "CQ_ID";
ALTER TABLE "COMPACTION_QUEUE" RENAME COLUMN cq_database TO "CQ_DATABASE";
ALTER TABLE "COMPACTION_QUEUE" RENAME COLUMN cq_table TO "CQ_TABLE";
ALTER TABLE "COMPACTION_QUEUE" RENAME COLUMN cq_partition TO "CQ_PARTITION";
ALTER TABLE "COMPACTION_QUEUE" RENAME COLUMN cq_state TO "CQ_STATE";
ALTER TABLE "COMPACTION_QUEUE" RENAME COLUMN cq_type TO "CQ_TYPE";
ALTER TABLE "COMPACTION_QUEUE" RENAME COLUMN cq_tblproperties TO "CQ_TBLPROPERTIES";
ALTER TABLE "COMPACTION_QUEUE" RENAME COLUMN cq_worker_id TO "CQ_WORKER_ID";
ALTER TABLE "COMPACTION_QUEUE" RENAME COLUMN cq_start TO "CQ_START";
ALTER TABLE "COMPACTION_QUEUE" RENAME COLUMN cq_run_as TO "CQ_RUN_AS";
ALTER TABLE "COMPACTION_QUEUE" RENAME COLUMN cq_highest_write_id TO "CQ_HIGHEST_WRITE_ID";
ALTER TABLE "COMPACTION_QUEUE" RENAME COLUMN cq_meta_info TO "CQ_META_INFO";
ALTER TABLE "COMPACTION_QUEUE" RENAME COLUMN cq_hadoop_job_id TO "CQ_HADOOP_JOB_ID";

ALTER TABLE completed_compactions RENAME TO "COMPLETED_COMPACTIONS";
ALTER TABLE "COMPLETED_COMPACTIONS" RENAME COLUMN cc_id TO "CC_ID";
ALTER TABLE "COMPLETED_COMPACTIONS" RENAME COLUMN cc_database TO "CC_DATABASE";
ALTER TABLE "COMPLETED_COMPACTIONS" RENAME COLUMN cc_table TO "CC_TABLE";
ALTER TABLE "COMPLETED_COMPACTIONS" RENAME COLUMN cc_partition TO "CC_PARTITION";
ALTER TABLE "COMPLETED_COMPACTIONS" RENAME COLUMN cc_state TO "CC_STATE";
ALTER TABLE "COMPLETED_COMPACTIONS" RENAME COLUMN cc_type TO "CC_TYPE";
ALTER TABLE "COMPLETED_COMPACTIONS" RENAME COLUMN cc_tblproperties TO "CC_TBLPROPERTIES";
ALTER TABLE "COMPLETED_COMPACTIONS" RENAME COLUMN cc_worker_id TO "CC_WORKER_ID";
ALTER TABLE "COMPLETED_COMPACTIONS" RENAME COLUMN cc_start TO "CC_START";
ALTER TABLE "COMPLETED_COMPACTIONS" RENAME COLUMN cc_end TO "CC_END";
ALTER TABLE "COMPLETED_COMPACTIONS" RENAME COLUMN cc_run_as TO "CC_RUN_AS";
ALTER TABLE "COMPLETED_COMPACTIONS" RENAME COLUMN cc_highest_write_id TO "CC_HIGHEST_WRITE_ID";
ALTER TABLE "COMPLETED_COMPACTIONS" RENAME COLUMN cc_meta_info TO "CC_META_INFO";
ALTER TABLE "COMPLETED_COMPACTIONS" RENAME COLUMN cc_hadoop_job_id TO "CC_HADOOP_JOB_ID";

ALTER TABLE completed_txn_components RENAME TO "COMPLETED_TXN_COMPONENTS";
ALTER TABLE "COMPLETED_TXN_COMPONENTS" RENAME COLUMN ctc_txnid TO "CTC_TXNID";
ALTER TABLE "COMPLETED_TXN_COMPONENTS" RENAME COLUMN ctc_database TO "CTC_DATABASE";
ALTER TABLE "COMPLETED_TXN_COMPONENTS" RENAME COLUMN ctc_table TO "CTC_TABLE";
ALTER TABLE "COMPLETED_TXN_COMPONENTS" RENAME COLUMN ctc_partition TO "CTC_PARTITION";
ALTER TABLE "COMPLETED_TXN_COMPONENTS" RENAME COLUMN ctc_timestamp TO "CTC_TIMESTAMP";
ALTER TABLE "COMPLETED_TXN_COMPONENTS" RENAME COLUMN ctc_writeid TO "CTC_WRITEID";
ALTER TABLE "COMPLETED_TXN_COMPONENTS" RENAME COLUMN ctc_update_delete TO "CTC_UPDATE_DELETE";

ALTER TABLE hive_locks RENAME TO "HIVE_LOCKS";
ALTER TABLE "HIVE_LOCKS" RENAME COLUMN hl_lock_ext_id TO "HL_LOCK_EXT_ID";
ALTER TABLE "HIVE_LOCKS" RENAME COLUMN hl_lock_int_id TO "HL_LOCK_INT_ID";
ALTER TABLE "HIVE_LOCKS" RENAME COLUMN hl_txnid TO "HL_TXNID";
ALTER TABLE "HIVE_LOCKS" RENAME COLUMN hl_db TO "HL_DB";
ALTER TABLE "HIVE_LOCKS" RENAME COLUMN hl_table TO "HL_TABLE";
ALTER TABLE "HIVE_LOCKS" RENAME COLUMN hl_partition TO "HL_PARTITION";
ALTER TABLE "HIVE_LOCKS" RENAME COLUMN hl_lock_state TO "HL_LOCK_STATE";
ALTER TABLE "HIVE_LOCKS" RENAME COLUMN hl_lock_type TO "HL_LOCK_TYPE";
ALTER TABLE "HIVE_LOCKS" RENAME COLUMN hl_last_heartbeat TO "HL_LAST_HEARTBEAT";
ALTER TABLE "HIVE_LOCKS" RENAME COLUMN hl_acquired_at TO "HL_ACQUIRED_AT";
ALTER TABLE "HIVE_LOCKS" RENAME COLUMN hl_user TO "HL_USER";
ALTER TABLE "HIVE_LOCKS" RENAME COLUMN hl_host TO "HL_HOST";
ALTER TABLE "HIVE_LOCKS" RENAME COLUMN hl_heartbeat_count TO "HL_HEARTBEAT_COUNT";
ALTER TABLE "HIVE_LOCKS" RENAME COLUMN hl_agent_info TO "HL_AGENT_INFO";
ALTER TABLE "HIVE_LOCKS" RENAME COLUMN hl_blockedby_ext_id TO "HL_BLOCKEDBY_EXT_ID";
ALTER TABLE "HIVE_LOCKS" RENAME COLUMN hl_blockedby_int_id TO "HL_BLOCKEDBY_INT_ID";

ALTER TABLE materialization_rebuild_locks RENAME TO "MATERIALIZATION_REBUILD_LOCKS";
ALTER TABLE "MATERIALIZATION_REBUILD_LOCKS" RENAME COLUMN mrl_txn_id TO "MRL_TXN_ID";
ALTER TABLE "MATERIALIZATION_REBUILD_LOCKS" RENAME COLUMN mrl_db_name TO "MRL_DB_NAME";
ALTER TABLE "MATERIALIZATION_REBUILD_LOCKS" RENAME COLUMN mrl_tbl_name TO "MRL_TBL_NAME";
ALTER TABLE "MATERIALIZATION_REBUILD_LOCKS" RENAME COLUMN mrl_last_heartbeat TO "MRL_LAST_HEARTBEAT";

ALTER TABLE min_history_level RENAME TO "MIN_HISTORY_LEVEL";
ALTER TABLE "MIN_HISTORY_LEVEL" RENAME COLUMN mhl_txnid TO "MHL_TXNID";
ALTER TABLE "MIN_HISTORY_LEVEL" RENAME COLUMN mhl_min_open_txnid TO "MHL_MIN_OPEN_TXNID";

ALTER TABLE next_compaction_queue_id RENAME TO "NEXT_COMPACTION_QUEUE_ID";
ALTER TABLE "NEXT_COMPACTION_QUEUE_ID" RENAME COLUMN ncq_next TO "NCQ_NEXT";

ALTER TABLE next_lock_id RENAME TO "NEXT_LOCK_ID";
ALTER TABLE "NEXT_LOCK_ID" RENAME COLUMN nl_next TO "NL_NEXT";

ALTER TABLE next_txn_id RENAME TO "NEXT_TXN_ID";
ALTER TABLE "NEXT_TXN_ID" RENAME COLUMN ntxn_next TO "NTXN_NEXT";

ALTER TABLE next_write_id RENAME TO "NEXT_WRITE_ID";
ALTER TABLE "NEXT_WRITE_ID" RENAME COLUMN nwi_database TO "NWI_DATABASE";
ALTER TABLE "NEXT_WRITE_ID" RENAME COLUMN nwi_table TO "NWI_TABLE";
ALTER TABLE "NEXT_WRITE_ID" RENAME COLUMN nwi_next TO "NWI_NEXT";

ALTER TABLE repl_txn_map RENAME TO "REPL_TXN_MAP";
ALTER TABLE "REPL_TXN_MAP" RENAME COLUMN rtm_repl_policy TO "RTM_REPL_POLICY";
ALTER TABLE "REPL_TXN_MAP" RENAME COLUMN rtm_src_txn_id TO "RTM_SRC_TXN_ID";
ALTER TABLE "REPL_TXN_MAP" RENAME COLUMN rtm_target_txn_id TO "RTM_TARGET_TXN_ID";

ALTER TABLE runtime_stats RENAME TO "RUNTIME_STATS";
ALTER TABLE "RUNTIME_STATS" RENAME COLUMN rs_id TO "RS_ID";
ALTER TABLE "RUNTIME_STATS" RENAME COLUMN create_time TO "CREATE_TIME";
ALTER TABLE "RUNTIME_STATS" RENAME COLUMN weight TO "WEIGHT";
ALTER TABLE "RUNTIME_STATS" RENAME COLUMN payload TO "PAYLOAD";

ALTER TABLE txn_components RENAME TO "TXN_COMPONENTS";
ALTER TABLE "TXN_COMPONENTS" RENAME COLUMN tc_txnid TO "TC_TXNID";
ALTER TABLE "TXN_COMPONENTS" RENAME COLUMN tc_database TO "TC_DATABASE";
ALTER TABLE "TXN_COMPONENTS" RENAME COLUMN tc_table TO "TC_TABLE";
ALTER TABLE "TXN_COMPONENTS" RENAME COLUMN tc_partition TO "TC_PARTITION";
ALTER TABLE "TXN_COMPONENTS" RENAME COLUMN tc_operation_type TO "TC_OPERATION_TYPE";
ALTER TABLE "TXN_COMPONENTS" RENAME COLUMN tc_writeid TO "TC_WRITEID";

ALTER TABLE txn_to_write_id RENAME TO "TXN_TO_WRITE_ID";
ALTER TABLE "TXN_TO_WRITE_ID" RENAME COLUMN t2w_txnid TO "T2W_TXNID";
ALTER TABLE "TXN_TO_WRITE_ID" RENAME COLUMN t2w_database TO "T2W_DATABASE";
ALTER TABLE "TXN_TO_WRITE_ID" RENAME COLUMN t2w_table TO "T2W_TABLE";
ALTER TABLE "TXN_TO_WRITE_ID" RENAME COLUMN t2w_writeid TO "T2W_WRITEID";

ALTER TABLE txns RENAME TO "TXNS";
ALTER TABLE "TXNS" RENAME COLUMN txn_id TO "TXN_ID";
ALTER TABLE "TXNS" RENAME COLUMN txn_state TO "TXN_STATE";
ALTER TABLE "TXNS" RENAME COLUMN txn_started TO "TXN_STARTED";
ALTER TABLE "TXNS" RENAME COLUMN txn_last_heartbeat TO "TXN_LAST_HEARTBEAT";
ALTER TABLE "TXNS" RENAME COLUMN txn_user TO "TXN_USER";
ALTER TABLE "TXNS" RENAME COLUMN txn_host TO "TXN_HOST";
ALTER TABLE "TXNS" RENAME COLUMN txn_agent_info TO "TXN_AGENT_INFO";
ALTER TABLE "TXNS" RENAME COLUMN txn_meta_info TO "TXN_META_INFO";
ALTER TABLE "TXNS" RENAME COLUMN txn_heartbeat_count TO "TXN_HEARTBEAT_COUNT";
ALTER TABLE "TXNS" RENAME COLUMN txn_type TO "TXN_TYPE";

ALTER TABLE write_set RENAME TO "WRITE_SET";
ALTER TABLE "WRITE_SET" RENAME COLUMN ws_database TO "WS_DATABASE";
ALTER TABLE "WRITE_SET" RENAME COLUMN ws_table TO "WS_TABLE";
ALTER TABLE "WRITE_SET" RENAME COLUMN ws_partition TO "WS_PARTITION";
ALTER TABLE "WRITE_SET" RENAME COLUMN ws_txnid TO "WS_TXNID";
ALTER TABLE "WRITE_SET" RENAME COLUMN ws_commit_id TO "WS_COMMIT_ID";
ALTER TABLE "WRITE_SET" RENAME COLUMN ws_operation_type TO "WS_OPERATION_TYPE";

-- HIVE-22729
ALTER TABLE "COMPACTION_QUEUE" ADD "CQ_ERROR_MESSAGE" text;
ALTER TABLE "COMPLETED_COMPACTIONS" ADD "CC_ERROR_MESSAGE" text;

-- HIVE-23683
ALTER TABLE "COMPACTION_QUEUE" ADD "CQ_ENQUEUE_TIME" bigint;
ALTER TABLE "COMPLETED_COMPACTIONS" ADD "CC_ENQUEUE_TIME" bigint;

-- HIVE-22728
ALTER TABLE "KEY_CONSTRAINTS" DROP CONSTRAINT "KEY_CONSTRAINTS_pkey";
ALTER TABLE "KEY_CONSTRAINTS" ADD CONSTRAINT "CONSTRAINTS_PK" PRIMARY KEY ("PARENT_TBL_ID", "CONSTRAINT_NAME", "POSITION");

-- HIVE-21487
CREATE INDEX "COMPLETED_COMPACTIONS_RES" ON "COMPLETED_COMPACTIONS" ("CC_DATABASE","CC_TABLE","CC_PARTITION");
-- HIVE-22872
ALTER TABLE "SCHEDULED_QUERIES" ADD "ACTIVE_EXECUTION_ID" bigint;

-- HIVE-22995
ALTER TABLE "DBS" ADD "DB_MANAGED_LOCATION_URI" character varying(4000);

-- HIVE-23107
ALTER TABLE "COMPACTION_QUEUE" ADD "CQ_NEXT_TXN_ID" bigint;

-- HIVE-23048
INSERT INTO "TXNS" ("TXN_ID", "TXN_STATE", "TXN_STARTED", "TXN_LAST_HEARTBEAT", "TXN_USER", "TXN_HOST")
  SELECT COALESCE(MAX("CTC_TXNID"),0), 'c', 0, 0, '', '' FROM "COMPLETED_TXN_COMPONENTS";
CREATE SEQUENCE "TXNS_TXN_ID_SEQ" MINVALUE 0 OWNED BY "TXNS"."TXN_ID";
select setval('"TXNS_TXN_ID_SEQ"',  (SELECT MAX("TXN_ID") FROM "TXNS"));
ALTER TABLE "TXNS" ALTER "TXN_ID" SET DEFAULT nextval('"TXNS_TXN_ID_SEQ"');

ALTER TABLE "NEXT_TXN_ID" RENAME TO "TXN_LOCK_TBL";
ALTER TABLE "TXN_LOCK_TBL" RENAME COLUMN "NTXN_NEXT" TO "TXN_LOCK";

--Create table replication metrics
CREATE TABLE "REPLICATION_METRICS" (
  "RM_SCHEDULED_EXECUTION_ID" bigint NOT NULL,
  "RM_POLICY" varchar(256) NOT NULL,
  "RM_DUMP_EXECUTION_ID" bigint NOT NULL,
  "RM_METADATA" varchar(4000),
  "RM_PROGRESS" varchar(4000),
  "RM_START_TIME" integer NOT NULL,
  PRIMARY KEY("RM_SCHEDULED_EXECUTION_ID")
);

--Create indexes for the replication metrics table
CREATE INDEX "POLICY_IDX" ON "REPLICATION_METRICS" ("RM_POLICY");
CREATE INDEX "DUMP_IDX" ON "REPLICATION_METRICS" ("RM_DUMP_EXECUTION_ID");

-- Create stored procedure tables
CREATE TABLE "STORED_PROCS" (
  "SP_ID" BIGINT NOT NULL,
  "CREATE_TIME" INTEGER NOT NULL,
  "DB_ID" BIGINT NOT NULL,
  "NAME" VARCHAR(256) NOT NULL,
  "OWNER_NAME" VARCHAR(128) NOT NULL,
  "SOURCE" TEXT NOT NULL,
  PRIMARY KEY ("SP_ID")
);

CREATE UNIQUE INDEX "UNIQUESTOREDPROC" ON "STORED_PROCS" ("NAME", "DB_ID");
ALTER TABLE ONLY "STORED_PROCS" ADD CONSTRAINT "STOREDPROC_FK1" FOREIGN KEY ("DB_ID") REFERENCES "DBS" ("DB_ID") DEFERRABLE;

-- Create stored procedure tables
CREATE TABLE "PACKAGES" (
  "PKG_ID" BIGINT NOT NULL,
  "CREATE_TIME" INTEGER NOT NULL,
  "DB_ID" BIGINT NOT NULL,
  "NAME" VARCHAR(256) NOT NULL,
  "OWNER_NAME" VARCHAR(128) NOT NULL,
  "HEADER" TEXT NOT NULL,
  "BODY" TEXT NOT NULL,
  PRIMARY KEY ("PKG_ID")
);

CREATE UNIQUE INDEX "UNIQUEPKG" ON "PACKAGES" ("NAME", "DB_ID");
ALTER TABLE ONLY "PACKAGES" ADD CONSTRAINT "PACKAGES_FK1" FOREIGN KEY ("DB_ID") REFERENCES "DBS" ("DB_ID")  DEFERRABLE;

-- HIVE-24291
ALTER TABLE "COMPACTION_QUEUE" ADD "CQ_TXN_ID" bigint;

-- HIVE-24275
ALTER TABLE "COMPACTION_QUEUE" ADD "CQ_COMMIT_TIME" bigint;

-- HIVE-24770
UPDATE "SERDES" SET "SLIB"='org.apache.hadoop.hive.serde2.MultiDelimitSerDe' where "SLIB"='org.apache.hadoop.hive.contrib.serde2.MultiDelimitSerDe';

-- HIVE-24880
ALTER TABLE "COMPACTION_QUEUE" ADD "CQ_INITIATOR_ID" varchar(128);
ALTER TABLE "COMPACTION_QUEUE" ADD "CQ_INITIATOR_VERSION" varchar(128);
ALTER TABLE "COMPACTION_QUEUE" ADD "CQ_WORKER_VERSION" varchar(128);
ALTER TABLE "COMPLETED_COMPACTIONS" ADD "CC_INITIATOR_ID" varchar(128);
ALTER TABLE "COMPLETED_COMPACTIONS" ADD "CC_INITIATOR_VERSION" varchar(128);
ALTER TABLE "COMPLETED_COMPACTIONS" ADD "CC_WORKER_VERSION" varchar(128);

-- HIVE-24396
-- Create DataConnectors and DataConnector_Params tables
CREATE TABLE "DATACONNECTORS" (
  "NAME" character varying(128) NOT NULL,
  "TYPE" character varying(32) NOT NULL,
  "URL" character varying(4000) NOT NULL,
  "COMMENT" character varying(256),
  "OWNER_NAME" character varying(256),
  "OWNER_TYPE" character varying(10),
  "CREATE_TIME" INTEGER NOT NULL,
  PRIMARY KEY ("NAME")
);

CREATE TABLE "DATACONNECTOR_PARAMS" (
  "NAME" character varying(128) NOT NULL,
  "PARAM_KEY" character varying(180) NOT NULL,
  "PARAM_VALUE" character varying(4000),
  PRIMARY KEY ("NAME", "PARAM_KEY"),
  CONSTRAINT "DATACONNECTOR_NAME_FK1" FOREIGN KEY ("NAME") REFERENCES "DATACONNECTORS"("NAME") ON DELETE CASCADE
);
ALTER TABLE "DBS" ADD "TYPE" character varying(32) DEFAULT 'NATIVE' NOT NULL;
ALTER TABLE "DBS" ADD "DATACONNECTOR_NAME" character varying(128);
ALTER TABLE "DBS" ADD "REMOTE_DBNAME" character varying(128);
UPDATE "DBS" SET "TYPE"= 'NATIVE' WHERE "TYPE" IS NULL;

-- HIVE-24911
CREATE INDEX "SDS_N50" ON "SDS" USING btree ("CD_ID");

-- These lines need to be last. Insert any changes above.
UPDATE "VERSION" SET "SCHEMA_VERSION"='4.0.0', "VERSION_COMMENT"='Hive release version 4.0.0' where "VER_ID"=1;
SELECT 'Finished upgrading MetaStore schema from 3.2.0 to 4.0.0';


text: Contains all the applications which are available in the gallery


text:
"""
Helper script to generate an input file for alignims_slicer IDL script.

Looks for FITS files, into the IRAF's database folder for
aperture traces and tries to set input flags based
on this information. Note, however, that user needs to
modify the generate file if offset observations were done
because the offset step sizes must be manually entered.
Also, if some was traced but later it was decided that
the trace is not good and the trace file was not removed
from the IRAF database, one should change the related
flags.

:author: Sami-Matias Niemi
:contact: sniemi@unc.edu
:version: 0.2
"""
import sys
import glob as g

def findFITSfiles(scale='lin'):
    """
    Finds all FITS files that start with "s" and contain strings "spec" and "slice".

    This function may require modifying if the filenames are non-standard.

    :param scale: identifier for lin or log scaling
    :type scale: string

    :return: filelists based on different wild card identifiers
    :rtype: dictionary
    """
    slice1 = g.glob('s%s*spec*slice1*.fits' % scale)
    slice2 = g.glob('s%s*spec*slice2*.fits' % scale)
    slice3 = g.glob('s%s*spec*slice3*.fits' % scale)
    allspec = g.glob('s%s*spec*slice*.fits' % scale)

    if len(slice1) < 1 or len(slice2) < 1 or\
       len(slice3) < 1 or len(allspec) < 1:
        sys.exit('A problem when searching for FITS files, will exit...')

    out = {'slice1': slice1,
           'slice2': slice2,
           'slice3': slice3,
           'files': allspec,
           'aptrace': _findAptracefiles(scale=scale)}
    return out

def _findAptracefiles(datapath='./database/', scale='lin'):
    """
    Finds all aperture trace files that are located in the IRAF database.

    :param datapath: path to the IRAF's database, default is ./database/
    :type datapath: string
    :param scale: identifier for lin or log scaling
    :type scale: string

    :return: all aperture trace files in the IRAF database folder
    :rtype: list
    """
    return g.glob('%saps%s*spec*slice2*' % (datapath, scale))

def writeOutput(data, slicerlabel, outfile='alignimslin.input'):
    """
    Outputs information to an ascii file.
    This file should be inspected and modified
    before it should be fed to the alignims IDL script.

    The current output format is following:
    file1 file2 file3 fixedslope prefcenter skyoffset tracefile slicer_label

    :param data: input data holding filelists
    :type data: dictionary
    :param slicerlabel: slicer label, for example, A.0
    :type slicerlabel: string
    :param outfile: name of the outputfile
    :type outfile: string
    """
    fh = open(outfile, 'w')
    for file in data['slice2']:
        #add file names, keep order 1,2,3
        str = file.replace('slice2', 'slice1')
        str += ' ' + file
        str += ' ' + file.replace('slice2', 'slice3')

        #try finding aptrace file
        #if found set the flag to 1 otherwise to 0
        apflag = 0
        aptrace = 'NA'
        for f in data['aptrace']:
            trc = f.split('/')[-1]

            if 'off' in trc:
                #we do not want to use any offsetted ones
                continue

            if file[:-5] in trc:
                #found a match, assume we wish to use it
                #sheila's IDL code expects this to be
                #in certain format:
                aptrace = f.split('/ap')[1] + '.fits'

        #add the flag to the string, 1 for fixed slope
        if len(aptrace) < 2:
            apflag = 1
        str += ' %i' % apflag

        #preferred center, set to 120 by default
        str += ' 120.0'

        #this depend on data
        if 'off' in file:
            str += ' please_add_offset'
        else:
            str += ' 0.0'

        #add aptrace file
        str += ' ' + aptrace

        #slicer label
        str += ' ' + slicerlabel

        fh.write(str + '\n')
    fh.close()

if __name__ == '__main__':
    #this could be read from the command line
    slicerlabel = 'unknown'

    #first linear scaling
    fileinfo = findFITSfiles()
    writeOutput(fileinfo, slicerlabel)

    #then log scaling
    fileinfo = findFITSfiles(scale='log')
    writeOutput(fileinfo,
                slicerlabel,
                outfile='alignimslog.input')


text:
[`ahab.rb`](https://github.com/jamesarosen/ahab.rb) is a Ruby client that
fetches assets over the Ahab protocol. It includes a Ruby API, a Rake task,
and a command-line interface.

## ahab-node.js

[`ahab-node`](https://github.com/svizzari/ahab-node) is a JavaScript client
that fetches assets over the Ahab protocol from a node environment. It will
eventually include a JavaScript API, Grunt plugin, and a command-line interface.

## ahab-browser.js

[`ahab-browser`](https://github.com/svizzari/ahab-browser) is a JavaScript
client that fetches assets over the Ahab protocol in a browser environment.
`ahab-browser` brings late resolution to the world of HTML assets!

See also [`jstayton/version.js`](https://github.com/jstayton/version.js)


text:
Ext.define('gov.va.hmp.team.PersonTilePanel', {
    extend:'Ext.panel.Panel',
    requires:[
        'gov.va.hmp.ux.PopUpButton',
        'gov.va.hmp.team.PersonField',
        'gov.va.hmp.team.PersonTile'
    ],
    alias:'widget.persontilepanel',
    layout:'column',
    items:[
        {
            xtype:'popupbutton',
            ui:'link',
            scale:'large',
            text:'Add a new person',
            cls:'hmp-person-add-btn',
            popUp:{
                xtype:'form',
                width:300,
                items:[
                    {
                        xtype:'personfield',
                        margin:10,
                        width:280,
                        emptyText:'Add by name',
                        listeners:{
                            select:function (combobox, records) {
                                var menu = combobox.up('menu');
                                menu.ownerButton.hideMenu();

                                var tiles = menu.ownerButton.up('persontilepanel');
                                tiles.addPerson(records[0]);
                            }
                        }
                    }
                ]
            },
            popUpButtons:[],
            listeners:{
                menushow:function (btn, menu) {
                    var combobox = menu.down('personfield');
                    combobox.clearValue();
                    combobox.focus(true, 50);
                }
            }
        },
        {
            xtype:'persontile',
            text:'AVIVAUSER THIRTYTHREE'
        },
        {
            xtype:'persontile',
            text:'VEHU TEN'
        }
    ],
    /**
     *
     * @param {gov.va.hmp.team.Person} person
     */
    addPerson:function (person) {
        this.add({
            xtype:'persontile',
            data:person, // TODO: alter PersonTile to make this work correctly, right now one must set 'text' property
            text:person.get('name')
        });
    },
    removePerson:function (person) {
        // TODO: implement me
    }
});