text:
/**
 * @constructor
 * @param {!function()} onHide
 * @extends {WebInspector.HelpScreen}
 */
WebInspector.SettingsScreen = function(onHide)
{
    WebInspector.HelpScreen.call(this);
    this.element.id = "settings-screen";

    /** @type {function()} */
    this._onHide = onHide;

    this._tabbedPane = new WebInspector.TabbedPane();
    this._tabbedPane.element.addStyleClass("help-window-main");
    this._tabbedPane.element.appendChild(this._createCloseButton());
    this._tabbedPane.appendTab(WebInspector.SettingsScreen.Tabs.General, WebInspector.UIString("General"), new WebInspector.GenericSettingsTab());
    this._tabbedPane.appendTab(WebInspector.SettingsScreen.Tabs.UserAgent, WebInspector.UIString("Overrides"), new WebInspector.UserAgentSettingsTab());
    if (WebInspector.experimentsSettings.experimentsEnabled)
        this._tabbedPane.appendTab(WebInspector.SettingsScreen.Tabs.Experiments, WebInspector.UIString("Experiments"), new WebInspector.ExperimentsSettingsTab());
    this._tabbedPane.appendTab(WebInspector.SettingsScreen.Tabs.Shortcuts, WebInspector.UIString("Shortcuts"), WebInspector.shortcutsScreen.createShortcutsTabView());
    this._tabbedPane.shrinkableTabs = true;

    this._lastSelectedTabSetting = WebInspector.settings.createSetting("lastSelectedSettingsTab", WebInspector.SettingsScreen.Tabs.General);
    this.selectTab(this._lastSelectedTabSetting.get());
    this._tabbedPane.addEventListener(WebInspector.TabbedPane.EventTypes.TabSelected, this._tabSelected, this);
}

WebInspector.SettingsScreen.Tabs = {
    General: "General",
    UserAgent: "UserAgent",
    Experiments: "Experiments",
    Shortcuts: "Shortcuts"
}

WebInspector.SettingsScreen.prototype = {
    /**
     * @param {string} tabId
     */
    selectTab: function(tabId)
    {
        this._tabbedPane.selectTab(tabId);
    },

    /**
     * @param {WebInspector.Event} event
     */
    _tabSelected: function(event)
    {
        this._lastSelectedTabSetting.set(this._tabbedPane.selectedTabId);
    },

    /**
     * @override
     */
    wasShown: function()
    {
        this._tabbedPane.show(this.element);
        WebInspector.HelpScreen.prototype.wasShown.call(this);
    },

    /**
     * @override
     */
    isClosingKey: function(keyCode)
    {
        return [
            WebInspector.KeyboardShortcut.Keys.Enter.code,
            WebInspector.KeyboardShortcut.Keys.Esc.code,
        ].indexOf(keyCode) >= 0;
    },

    /**
     * @override
     */
    willHide: function()
    {
        this._onHide();
        WebInspector.HelpScreen.prototype.willHide.call(this);
    },

    __proto__: WebInspector.HelpScreen.prototype
}

/**
 * @constructor
 * @extends {WebInspector.View}
 */
WebInspector.SettingsTab = function()
{
    WebInspector.View.call(this);
    this.element.className = "settings-tab help-content help-container";
}

WebInspector.SettingsTab.prototype = {
    /**
     *  @param {string=} name
     *  @return {!Element}
     */
    _appendSection: function(name)
    {
        var block = this.element.createChild("div", "help-block");
        if (name)
            block.createChild("div", "help-section-title").textContent = name;
        return block;
    },

    /**
     * @param {boolean=} omitParagraphElement
     * @param {Element=} inputElement
     */
    _createCheckboxSetting: function(name, setting, omitParagraphElement, inputElement)
    {
        var input = inputElement || document.createElement("input");
        input.type = "checkbox";
        input.name = name;
        input.checked = setting.get();

        function listener()
        {
            setting.set(input.checked);
        }
        input.addEventListener("click", listener, false);

        var label = document.createElement("label");
        label.appendChild(input);
        label.appendChild(document.createTextNode(name));
        if (omitParagraphElement)
            return label;

        var p = document.createElement("p");
        p.appendChild(label);
        return p;
    },

    _createSelectSetting: function(name, options, setting)
    {
        var fieldsetElement = document.createElement("fieldset");
        fieldsetElement.createChild("label").textContent = name;

        var select = document.createElement("select");
        var settingValue = setting.get();

        for (var i = 0; i < options.length; ++i) {
            var option = options[i];
            select.add(new Option(option[0], option[1]));
            if (settingValue === option[1])
                select.selectedIndex = i;
        }

        function changeListener(e)
        {
            setting.set(e.target.value);
        }

        select.addEventListener("change", changeListener, false);
        fieldsetElement.appendChild(select);

        var p = document.createElement("p");
        p.appendChild(fieldsetElement);
        return p;
    },

    _createRadioSetting: function(name, options, setting)
    {
        var pp = document.createElement("p");
        var fieldsetElement = document.createElement("fieldset");
        var legendElement = document.createElement("legend");
        legendElement.textContent = name;
        fieldsetElement.appendChild(legendElement);

        function clickListener(e)
        {
            setting.set(e.target.value);
        }

        var settingValue = setting.get();
        for (var i = 0; i < options.length; ++i) {
            var p = document.createElement("p");
            var label = document.createElement("label");
            p.appendChild(label);

            var input = document.createElement("input");
            input.type = "radio";
            input.name = setting.name;
            input.value = options[i][0];
            input.addEventListener("click", clickListener, false);
            if (settingValue == input.value)
                input.checked = true;

            label.appendChild(input);
            label.appendChild(document.createTextNode(options[i][1]));

            fieldsetElement.appendChild(p);
        }

        pp.appendChild(fieldsetElement);
        return pp;
    },

    _createCustomSetting: function(name, element)
    {
        var p = document.createElement("p");
        var fieldsetElement = document.createElement("fieldset");
        fieldsetElement.createChild("label").textContent = name;
        fieldsetElement.appendChild(element);
        p.appendChild(fieldsetElement);
        return p;
    },

    __proto__: WebInspector.View.prototype
}

/**
 * @constructor
 * @extends {WebInspector.SettingsTab}
 */
WebInspector.GenericSettingsTab = function()
{
    WebInspector.SettingsTab.call(this);

    var p = this._appendSection();
    if (Preferences.exposeDisableCache)
        p.appendChild(this._createCheckboxSetting(WebInspector.UIString("Disable cache"), WebInspector.settings.cacheDisabled));
    var disableJSElement = this._createCheckboxSetting(WebInspector.UIString("Disable JavaScript"), WebInspector.settings.javaScriptDisabled);
    p.appendChild(disableJSElement);
    WebInspector.settings.javaScriptDisabled.addChangeListener(this._javaScriptDisabledChanged, this);
    this._disableJSCheckbox = disableJSElement.getElementsByTagName("input")[0];
    this._updateScriptDisabledCheckbox();

    p = this._appendSection(WebInspector.UIString("Elements"));
    p.appendChild(this._createRadioSetting(WebInspector.UIString("Color format"), [
        [ WebInspector.Color.Format.Original, WebInspector.UIString("As authored") ],
        [ WebInspector.Color.Format.HEX, "HEX: #DAC0DE" ],
        [ WebInspector.Color.Format.RGB, "RGB: rgb(128, 255, 255)" ],
        [ WebInspector.Color.Format.HSL, "HSL: hsl(300, 80%, 90%)" ] ], WebInspector.settings.colorFormat));
    p.appendChild(this._createCheckboxSetting(WebInspector.UIString("Show user agent styles"), WebInspector.settings.showUserAgentStyles));
    p.appendChild(this._createCheckboxSetting(WebInspector.UIString("Word wrap"), WebInspector.settings.domWordWrap));
    p.appendChild(this._createCheckboxSetting(WebInspector.UIString("Show Shadow DOM"), WebInspector.settings.showShadowDOM));

    p = this._appendSection(WebInspector.UIString("Rendering"));
    p.appendChild(this._createCheckboxSetting(WebInspector.UIString("Show paint rectangles"), WebInspector.settings.showPaintRects));
    WebInspector.settings.showPaintRects.addChangeListener(this._showPaintRectsChanged, this);

    p = this._appendSection(WebInspector.UIString("Sources"));
    p.appendChild(this._createCheckboxSetting(WebInspector.UIString("Show folders"), WebInspector.settings.showScriptFolders));
    p.appendChild(this._createCheckboxSetting(WebInspector.UIString("Search in content scripts"), WebInspector.settings.searchInContentScripts));
    p.appendChild(this._createCheckboxSetting(WebInspector.UIString("Enable source maps"), WebInspector.settings.sourceMapsEnabled));
    p.appendChild(this._createSelectSetting(WebInspector.UIString("Indentation"), [
            [ WebInspector.UIString("2 spaces"), WebInspector.TextEditorModel.Indent.TwoSpaces ],
            [ WebInspector.UIString("4 spaces"), WebInspector.TextEditorModel.Indent.FourSpaces ],
            [ WebInspector.UIString("8 spaces"), WebInspector.TextEditorModel.Indent.EightSpaces ],
            [ WebInspector.UIString("Tab character"), WebInspector.TextEditorModel.Indent.TabCharacter ]
        ], WebInspector.settings.textEditorIndent));

    p = this._appendSection(WebInspector.UIString("Profiler"));
    p.appendChild(this._createCheckboxSetting(WebInspector.UIString("Show objects' hidden properties"), WebInspector.settings.showHeapSnapshotObjectsHiddenProperties));

    p = this._appendSection(WebInspector.UIString("Console"));
    p.appendChild(this._createCheckboxSetting(WebInspector.UIString("Log XMLHttpRequests"), WebInspector.settings.monitoringXHREnabled));
    p.appendChild(this._createCheckboxSetting(WebInspector.UIString("Preserve log upon navigation"), WebInspector.settings.preserveConsoleLog));

    if (WebInspector.extensionServer.hasExtensions()) {
        var handlerSelector = new WebInspector.HandlerSelector(WebInspector.openAnchorLocationRegistry);
        p = this._appendSection(WebInspector.UIString("Extensions"));
        p.appendChild(this._createCustomSetting(WebInspector.UIString("Open links in"), handlerSelector.element));
    }
}

WebInspector.GenericSettingsTab.prototype = {
    _showPaintRectsChanged: function()
    {
        PageAgent.setShowPaintRects(WebInspector.settings.showPaintRects.get());
    },

    _updateScriptDisabledCheckbox: function()
    {
        function executionStatusCallback(error, status)
        {
            if (error || !status)
                return;

            switch (status) {
            case "forbidden":
                this._disableJSCheckbox.checked = true;
                this._disableJSCheckbox.disabled = true;
                break;
            case "disabled":
                this._disableJSCheckbox.checked = true;
                break;
            default:
                this._disableJSCheckbox.checked = false;
                break;
            }
        }

        PageAgent.getScriptExecutionStatus(executionStatusCallback.bind(this));
    },

    _javaScriptDisabledChanged: function()
    {
        // We need to manually update the checkbox state, since enabling JavaScript in the page can actually uncover the "forbidden" state.
        PageAgent.setScriptExecutionDisabled(WebInspector.settings.javaScriptDisabled.get(), this._updateScriptDisabledCheckbox.bind(this));
    },

    __proto__: WebInspector.SettingsTab.prototype
}

/**
 * @constructor
 * @extends {WebInspector.SettingsTab}
 */
WebInspector.UserAgentSettingsTab = function()
{
    WebInspector.SettingsTab.call(this);

    var p = this._appendSection();
    p.appendChild(this._createUserAgentControl());
    if (Capabilities.canOverrideDeviceMetrics)
        p.appendChild(this._createDeviceMetricsControl());
    if (Capabilities.canOverrideGeolocation && WebInspector.experimentsSettings.geolocationOverride.isEnabled())
        p.appendChild(this._createGeolocationOverrideControl());
    if (Capabilities.canOverrideDeviceOrientation && WebInspector.experimentsSettings.deviceOrientationOverride.isEnabled())
        p.appendChild(this._createDeviceOrientationOverrideControl());
    p.appendChild(this._createCheckboxSetting(WebInspector.UIString("Emulate touch events"), WebInspector.settings.emulateTouchEvents));
}

WebInspector.UserAgentSettingsTab.prototype = {
    _createUserAgentControl: function()
    {
        var userAgent = WebInspector.settings.userAgent.get();

        var p = document.createElement("p");
        var labelElement = p.createChild("label");
        var checkboxElement = labelElement.createChild("input");
        checkboxElement.type = "checkbox";
        checkboxElement.checked = !!userAgent;
        labelElement.appendChild(document.createTextNode("User Agent"));
        p.appendChild(this._createUserAgentSelectRowElement(checkboxElement));
        return p;
    },

    _createUserAgentSelectRowElement: function(checkboxElement)
    {
        var userAgent = WebInspector.settings.userAgent.get();

        // When present, the third element lists device metrics separated by 'x':
        // - screen width,
        // - screen height,
        // - font scale factor.
        const userAgents = [
            ["Internet Explorer 9", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"],
            ["Internet Explorer 8", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)"],
            ["Internet Explorer 7", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)"],

            ["Firefox 7 \u2014 Windows", "Mozilla/5.0 (Windows NT 6.1; Intel Mac OS X 10.6; rv:7.0.1) Gecko/20100101 Firefox/7.0.1"],
            ["Firefox 7 \u2014 Mac", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:7.0.1) Gecko/20100101 Firefox/7.0.1"],
            ["Firefox 4 \u2014 Windows", "Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1"],
            ["Firefox 4 \u2014 Mac", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1"],

            ["iPhone \u2014 iOS 5", "Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3", "640x960x1"],
            ["iPhone \u2014 iOS 4", "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5", "640x960x1"],
            ["iPad \u2014 iOS 5", "Mozilla/5.0 (iPad; CPU OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3", "1024x768x1"],
            ["iPad \u2014 iOS 4", "Mozilla/5.0 (iPad; CPU OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5", "1024x768x1"],

            ["Android 2.3 \u2014 Nexus S", "Mozilla/5.0 (Linux; U; Android 2.3.6; en-us; Nexus S Build/GRK39F) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1", "480x800x1.1"],
            ["Android 4.0.2 \u2014 Galaxy Nexus", "Mozilla/5.0 (Linux; U; Android 4.0.2; en-us; Galaxy Nexus Build/ICL53F) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30", "720x1280x1.1"],

            ["BlackBerry \u2014 PlayBook 2.1", "Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML, like Gecko) Version/7.2.1.0 Safari/536.2+", "1024x600x1"],
            ["BlackBerry \u2014 9900", "Mozilla/5.0 (BlackBerry; U; BlackBerry 9900; en-US) AppleWebKit/534.11+ (KHTML, like Gecko) Version/7.0.0.187 Mobile Safari/534.11+", "640x480x1"],
            ["BlackBerry \u2014 BB10", "Mozilla/5.0 (BB10; Touch) AppleWebKit/537.1+ (KHTML, like Gecko) Version/10.0.0.1337 Mobile Safari/537.1+", "768x1280x1"],

            ["MeeGo \u2014 Nokia N9", "Mozilla/5.0 (MeeGo; NokiaN9) AppleWebKit/534.13 (KHTML, like Gecko) NokiaBrowser/8.5.0 Mobile Safari/534.13", "480x854x1"],

            [WebInspector.UIString("Other..."), "Other"]
        ];

        var fieldsetElement = document.createElement("fieldset");
        this._selectElement = fieldsetElement.createChild("select");
        this._otherUserAgentElement = fieldsetElement.createChild("input");
        this._otherUserAgentElement.value = userAgent;
        this._otherUserAgentElement.title = userAgent;

        var selectionRestored = false;
        for (var i = 0; i < userAgents.length; ++i) {
            var agent = userAgents[i];
            var option = new Option(agent[0], agent[1]);
            option._metrics = agent[2] ? agent[2] : "";
            this._selectElement.add(option);
            if (userAgent === agent[1]) {
                this._selectElement.selectedIndex = i;
                selectionRestored = true;
            }
        }

        if (!selectionRestored) {
            if (!userAgent)
                this._selectElement.selectedIndex = 0;
            else
              this._selectElement.selectedIndex = userAgents.length - 1;
        }

        this._selectElement.addEventListener("change", this._selectionChanged.bind(this, true), false);

        fieldsetElement.addEventListener("dblclick", textDoubleClicked.bind(this), false);
        this._otherUserAgentElement.addEventListener("blur", textChanged.bind(this), false);

        function textDoubleClicked()
        {
            this._selectElement.selectedIndex = userAgents.length - 1;
            this._selectionChanged();
        }

        function textChanged()
        {
            WebInspector.settings.userAgent.set(this._otherUserAgentElement.value);
        }

        function checkboxClicked()
        {
            if (checkboxElement.checked) {
                this._selectElement.disabled = false;
                this._selectionChanged();
            } else {
                this._selectElement.disabled = true;
                this._otherUserAgentElement.disabled = true;
                WebInspector.settings.userAgent.set("");
            }
        }
        checkboxElement.addEventListener("click", checkboxClicked.bind(this), false);

        checkboxClicked.call(this);
        return fieldsetElement;
    },

    /**
     * @param {boolean=} isUserGesture
     */
    _selectionChanged: function(isUserGesture)
    {
        var value = this._selectElement.options[this._selectElement.selectedIndex].value;
        if (value !== "Other") {
            WebInspector.settings.userAgent.set(value);
            this._otherUserAgentElement.value = value;
            this._otherUserAgentElement.title = value;
            this._otherUserAgentElement.disabled = true;
        } else {
            this._otherUserAgentElement.disabled = false;
            this._otherUserAgentElement.focus();
        }

        if (isUserGesture && Capabilities.canOverrideDeviceMetrics) {
            var metrics = this._selectElement.options[this._selectElement.selectedIndex]._metrics;
            this._setDeviceMetricsOverride(WebInspector.UserAgentSupport.DeviceMetrics.parseSetting(metrics), false, true);
        }
    },

    _updateScriptDisabledCheckbox: function()
    {
        function executionStatusCallback(error, status)
        {
            if (error || !status)
                return;

            switch (status) {
            case "forbidden":
                this._disableJSCheckbox.checked = true;
                this._disableJSCheckbox.disabled = true;
                break;
            case "disabled":
                this._disableJSCheckbox.checked = true;
                break;
            default:
                this._disableJSCheckbox.checked = false;
                break;
            }
        }

        PageAgent.getScriptExecutionStatus(executionStatusCallback.bind(this));
    },

    /**
     * Creates an input element under the parentElement with the given id and defaultText.
     * It also sets an onblur event listener.
     * @param {Element} parentElement
     * @param {string} id
     * @param {string} defaultText
     * @param {function(*)} eventListener
     * @return {Element} element
     */
    _createInput: function(parentElement, id, defaultText, eventListener)
    {
        var element = parentElement.createChild("input");
        element.id = id;
        element.maxLength = 12;
        element.style.width = "80px";
        element.value = defaultText;
        element.align = "right";
        element.addEventListener("blur", eventListener, false);
        return element;
    },

    _createDeviceMetricsControl: function()
    {
        const metricsSetting = WebInspector.settings.deviceMetrics.get();
        var metrics = WebInspector.UserAgentSupport.DeviceMetrics.parseSetting(metricsSetting);

        const p = document.createElement("p");
        const labelElement = p.createChild("label");
        const checkboxElement = labelElement.createChild("input");
        checkboxElement.id = "metrics-override-checkbox";
        checkboxElement.type = "checkbox";
        checkboxElement.checked = false;
        checkboxElement.addEventListener("click", this._onMetricsCheckboxClicked.bind(this), false);
        this._metricsCheckboxElement = checkboxElement;
        labelElement.appendChild(document.createTextNode(WebInspector.UIString("Device metrics")));

        const metricsSectionElement = this._createDeviceMetricsElement(metrics);
        p.appendChild(metricsSectionElement);
        this._metricsSectionElement = metricsSectionElement;
        this._onMetricsCheckboxClicked();

        return p;
    },

    _onMetricsCheckboxClicked: function()
    {
        var controlsDisabled = !this._metricsCheckboxElement.checked;
        this._widthOverrideElement.disabled = controlsDisabled;
        this._heightOverrideElement.disabled = controlsDisabled;
        this._fontScaleFactorOverrideElement.disabled = controlsDisabled;
        this._swapDimensionsElement.disabled = controlsDisabled;
        this._fitWindowCheckboxElement.disabled = controlsDisabled;

        if (controlsDisabled) {
            WebInspector.userAgentSupport.toggleDeviceMetricsOverride(false);
            return;
        }

        var metrics = WebInspector.UserAgentSupport.DeviceMetrics.parseUserInput(this._widthOverrideElement.value, this._heightOverrideElement.value, this._fontScaleFactorOverrideElement.value);
        if (metrics && metrics.isValid() && metrics.width && metrics.height) {
            this._setDeviceMetricsOverride(metrics, false, false);
            WebInspector.userAgentSupport.toggleDeviceMetricsOverride(true);
        }
        if (!this._widthOverrideElement.value)
            this._widthOverrideElement.focus();
    },

    _applyDeviceMetricsUserInput: function()
    {
        this._setDeviceMetricsOverride(WebInspector.UserAgentSupport.DeviceMetrics.parseUserInput(this._widthOverrideElement.value.trim(), this._heightOverrideElement.value.trim(), this._fontScaleFactorOverrideElement.value.trim()), true, false);
    },

    /**
     * @param {?WebInspector.UserAgentSupport.DeviceMetrics} metrics
     * @param {boolean} userInputModified
     */
    _setDeviceMetricsOverride: function(metrics, userInputModified, updateCheckbox)
    {
        function setValid(condition, element)
        {
            if (condition)
                element.removeStyleClass("error-input");
            else
                element.addStyleClass("error-input");
        }

        setValid(metrics && metrics.isWidthValid(), this._widthOverrideElement);
        setValid(metrics && metrics.isHeightValid(), this._heightOverrideElement);
        setValid(metrics && metrics.isFontScaleFactorValid(), this._fontScaleFactorOverrideElement);

        if (!metrics)
            return;

        if (!userInputModified) {
            this._widthOverrideElement.value = metrics.widthToInput();
            this._heightOverrideElement.value = metrics.heightToInput();
            this._fontScaleFactorOverrideElement.value = metrics.fontScaleFactorToInput();
        }

        if (metrics.isValid()) {
            var value = metrics.toSetting();
            if (value !== WebInspector.settings.deviceMetrics.get())
                WebInspector.settings.deviceMetrics.set(value);
        }

        if (this._metricsCheckboxElement && updateCheckbox) {
            this._metricsCheckboxElement.checked = !!metrics.toSetting();
            this._onMetricsCheckboxClicked();
        }
    },

    /**
     * @param {WebInspector.UserAgentSupport.DeviceMetrics} metrics
     */
    _createDeviceMetricsElement: function(metrics)
    {
        var fieldsetElement = document.createElement("fieldset");
        fieldsetElement.id = "metrics-override-section";

        function swapDimensionsClicked(event)
        {
            var widthValue = this._widthOverrideElement.value;
            this._widthOverrideElement.value = this._heightOverrideElement.value;
            this._heightOverrideElement.value = widthValue;
            this._applyDeviceMetricsUserInput();
        }

        var tableElement = fieldsetElement.createChild("table", "nowrap");

        var rowElement = tableElement.createChild("tr");
        var cellElement = rowElement.createChild("td");
        cellElement.appendChild(document.createTextNode(WebInspector.UIString("Screen resolution:")));
        cellElement = rowElement.createChild("td");
        this._widthOverrideElement = this._createInput(cellElement, "metrics-override-width", String(metrics.width || screen.width), this._applyDeviceMetricsUserInput.bind(this));
        cellElement.appendChild(document.createTextNode(" \u00D7 ")); // MULTIPLICATION SIGN.
        this._heightOverrideElement = this._createInput(cellElement, "metrics-override-height", String(metrics.height || screen.height), this._applyDeviceMetricsUserInput.bind(this));
        cellElement.appendChild(document.createTextNode(" \u2014 ")); // EM DASH.
        this._swapDimensionsElement = cellElement.createChild("button");
        this._swapDimensionsElement.appendChild(document.createTextNode(" \u21C4 ")); // RIGHTWARDS ARROW OVER LEFTWARDS ARROW.
        this._swapDimensionsElement.title = WebInspector.UIString("Swap dimensions");
        this._swapDimensionsElement.addEventListener("click", swapDimensionsClicked.bind(this), false);

        rowElement = tableElement.createChild("tr");
        cellElement = rowElement.createChild("td");
        cellElement.appendChild(document.createTextNode(WebInspector.UIString("Font scale factor:")));
        cellElement = rowElement.createChild("td");
        this._fontScaleFactorOverrideElement = this._createInput(cellElement, "metrics-override-font-scale", String(metrics.fontScaleFactor || 1), this._applyDeviceMetricsUserInput.bind(this));

        rowElement = tableElement.createChild("tr");
        cellElement = rowElement.createChild("td");
        cellElement.colspan = 2;
        this._fitWindowCheckboxElement = document.createElement("input");
        cellElement.appendChild(this._createCheckboxSetting(WebInspector.UIString("Fit in window"), WebInspector.settings.deviceFitWindow, true, this._fitWindowCheckboxElement));

        return fieldsetElement;
    },

    _createGeolocationOverrideControl: function()
    {
        const geolocationSetting = WebInspector.settings.geolocationOverride.get();
        var geolocation = WebInspector.UserAgentSupport.GeolocationPosition.parseSetting(geolocationSetting);
        var p = document.createElement("p");
        var labelElement = p.createChild("label");
        var checkboxElement = labelElement.createChild("input");
        checkboxElement.id = "geolocation-override-checkbox";
        checkboxElement.type = "checkbox";
        checkboxElement.checked = false;
        checkboxElement.addEventListener("click", this._onGeolocationOverrideCheckboxClicked.bind(this), false);
        this._geolocationOverrideCheckboxElement = checkboxElement;
        labelElement.appendChild(document.createTextNode(WebInspector.UIString("Override Geolocation")));

        var geolocationSectionElement = this._createGeolocationOverrideElement(geolocation);
        p.appendChild(geolocationSectionElement);
        this._geolocationSectionElement = geolocationSectionElement;
        this._onGeolocationOverrideCheckboxClicked();
        return p;
    },

    _onGeolocationOverrideCheckboxClicked: function()
    {
        var controlsDisabled = !this._geolocationOverrideCheckboxElement.checked;
        this._latitudeElement.disabled = controlsDisabled;
        this._longitudeElement.disabled = controlsDisabled;
        this._geolocationErrorElement.disabled = controlsDisabled;

        if (controlsDisabled) {
            WebInspector.userAgentSupport.toggleGeolocationPositionOverride(false);
            return;
        }

        var geolocation = WebInspector.UserAgentSupport.GeolocationPosition.parseUserInput(this._latitudeElement.value, this._longitudeElement.value, this._geolocationErrorElement.checked);
        if (geolocation) {
            this._setGeolocationPosition(geolocation, false, false);
            WebInspector.userAgentSupport.toggleGeolocationPositionOverride(true);
        }
        if (!this._latitudeElement.value)
            this._latitudeElement.focus();
    },

    _applyGeolocationUserInput: function()
    {
        this._setGeolocationPosition(WebInspector.UserAgentSupport.GeolocationPosition.parseUserInput(this._latitudeElement.value.trim(), this._longitudeElement.value.trim(), this._geolocationErrorElement.checked), true, false);
    },

    /**
     * @param {?WebInspector.UserAgentSupport.GeolocationPosition} geolocation
     * @param {boolean} userInputModified
     * @param {boolean} updateCheckbox
     */
    _setGeolocationPosition: function(geolocation, userInputModified, updateCheckbox)
    {
        if (!geolocation)
            return;

        if (!userInputModified) {
            this._latitudeElement.value = geolocation.latitude;
            this._longitudeElement.value = geolocation.longitude;
        }

        var value = geolocation.toSetting();
        WebInspector.settings.geolocationOverride.set(value);

        if (this._geolocationOverrideCheckboxElement && updateCheckbox) {
            this._geolocationOverrideCheckboxElement.checked = !!geolocation.toSetting();
            this._onGeolocationOverrideCheckboxClicked();
        }
    },

    /**
     * @param {WebInspector.UserAgentSupport.GeolocationPosition} geolocation
     */
    _createGeolocationOverrideElement: function(geolocation)
    {
        var fieldsetElement = document.createElement("fieldset");
        fieldsetElement.id = "geolocation-override-section";

        var tableElement = fieldsetElement.createChild("table");
        var rowElement = tableElement.createChild("tr");
        var cellElement = rowElement.createChild("td");
        cellElement.appendChild(document.createTextNode(WebInspector.UIString("Geolocation Position") + ":"));
        cellElement = rowElement.createChild("td");
        this._latitudeElement = this._createInput(cellElement, "geolocation-override-latitude", String(geolocation.latitude), this._applyGeolocationUserInput.bind(this));
        cellElement.appendChild(document.createTextNode(" , "));
        this._longitudeElement = this._createInput(cellElement, "geolocation-override-longitude", String(geolocation.longitude), this._applyGeolocationUserInput.bind(this));
        rowElement = tableElement.createChild("tr");
        cellElement = rowElement.createChild("td");
        var geolocationErrorLabelElement = document.createElement("label");
        var geolocationErrorCheckboxElement = geolocationErrorLabelElement.createChild("input");
        geolocationErrorCheckboxElement.id = "geolocation-error";
        geolocationErrorCheckboxElement.type = "checkbox";
        geolocationErrorCheckboxElement.checked = !geolocation || geolocation.error;
        geolocationErrorCheckboxElement.addEventListener("click", this._applyGeolocationUserInput.bind(this), false);
        geolocationErrorLabelElement.appendChild(document.createTextNode(WebInspector.UIString("Emulate position unavailable")));
        this._geolocationErrorElement = geolocationErrorCheckboxElement;
        cellElement.appendChild(geolocationErrorLabelElement);

        return fieldsetElement;
    },

    _createDeviceOrientationOverrideControl: function()
    {
        const deviceOrientationSetting = WebInspector.settings.deviceOrientationOverride.get();
        var deviceOrientation = WebInspector.UserAgentSupport.DeviceOrientation.parseSetting(deviceOrientationSetting);

        var p = document.createElement("p");
        var labelElement = p.createChild("label");
        var checkboxElement = labelElement.createChild("input");
        checkboxElement.id = "device-orientation-override-checkbox";
        checkboxElement.type = "checkbox";
        checkboxElement.checked = false;
        checkboxElement.addEventListener("click", this._onDeviceOrientationOverrideCheckboxClicked.bind(this), false);
        this._deviceOrientationOverrideCheckboxElement = checkboxElement;
        labelElement.appendChild(document.createTextNode(WebInspector.UIString("Override Device Orientation")));

        var deviceOrientationSectionElement = this._createDeviceOrientationOverrideElement(deviceOrientation);
        p.appendChild(deviceOrientationSectionElement);
        this._deviceOrientationSectionElement = deviceOrientationSectionElement;
        this._onDeviceOrientationOverrideCheckboxClicked();
        return p;
    },

    _onDeviceOrientationOverrideCheckboxClicked: function()
    {
        var controlsDisabled = !this._deviceOrientationOverrideCheckboxElement.checked;
        this._alphaElement.disabled = controlsDisabled;
        this._betaElement.disabled = controlsDisabled;
        this._gammaElement.disabled = controlsDisabled;

        if (controlsDisabled) {
            WebInspector.userAgentSupport.toggleDeviceOrientationOverride(false);
            return;
        }

        var deviceOrientation = WebInspector.UserAgentSupport.DeviceOrientation.parseUserInput(this._alphaElement.value, this._betaElement.value, this._gammaElement.value);
        if (deviceOrientation) {
            this._setDeviceOrientation(deviceOrientation, false, false);
            WebInspector.userAgentSupport.toggleDeviceOrientationOverride(true);
        }
        if (!this._alphaElement.value)
            this._alphaElement.focus();
    },

    _applyDeviceOrientationUserInput: function()
    {
        this._setDeviceOrientation(WebInspector.UserAgentSupport.DeviceOrientation.parseUserInput(this._alphaElement.value.trim(), this._betaElement.value.trim(), this._gammaElement.value.trim()), true, false);
    },

    /**
     * @param {?WebInspector.UserAgentSupport.DeviceOrientation} deviceOrientation
     * @param {boolean} userInputModified
     * @param {boolean} updateCheckbox
     */
    _setDeviceOrientation: function(deviceOrientation, userInputModified, updateCheckbox)
    {
        if (!deviceOrientation)
            return;

        if (!userInputModified) {
            this._alphaElement.value = deviceOrientation.alpha;
            this._betaElement.value = deviceOrientation.beta;
            this._gammaElement.value = deviceOrientation.gamma;
        }

        var value = deviceOrientation.toSetting();
        WebInspector.settings.deviceOrientationOverride.set(value);

        if (this._deviceOrientationOverrideCheckboxElement && updateCheckbox) {
            this._deviceOrientationOverrideCheckboxElement.checked = !!deviceOrientation.toSetting();
            this._onDeviceOrientationOverrideCheckboxClicked();
        }
    },

    /**
     * @param {WebInspector.UserAgentSupport.DeviceOrientation} deviceOrientation
     */
    _createDeviceOrientationOverrideElement: function(deviceOrientation)
    {
        var fieldsetElement = document.createElement("fieldset");
        fieldsetElement.id = "device-orientation-override-section";

        var tableElement = fieldsetElement.createChild("table");

        var rowElement = tableElement.createChild("tr");
        var cellElement = rowElement.createChild("td");
        cellElement.appendChild(document.createTextNode("\u03B1: "));
        this._alphaElement = this._createInput(cellElement, "device-orientation-override-alpha", String(deviceOrientation.alpha), this._applyDeviceOrientationUserInput.bind(this));
        cellElement.appendChild(document.createTextNode(" \u03B2: "));
        this._betaElement = this._createInput(cellElement, "device-orientation-override-beta", String(deviceOrientation.beta), this._applyDeviceOrientationUserInput.bind(this));
        cellElement.appendChild(document.createTextNode(" \u03B3: "));
        this._gammaElement = this._createInput(cellElement, "device-orientation-override-gamma", String(deviceOrientation.gamma), this._applyDeviceOrientationUserInput.bind(this));

        return fieldsetElement;
    },

    __proto__: WebInspector.SettingsTab.prototype
}

/**
 * @constructor
 * @extends {WebInspector.SettingsTab}
 */
WebInspector.ExperimentsSettingsTab = function()
{
    WebInspector.SettingsTab.call(this);

    var experiments = WebInspector.experimentsSettings.experiments;
    if (experiments.length) {
        var experimentsSection = this._appendSection();
        experimentsSection.appendChild(this._createExperimentsWarningSubsection());
        for (var i = 0; i < experiments.length; ++i)
            experimentsSection.appendChild(this._createExperimentCheckbox(experiments[i]));
    }
}

WebInspector.ExperimentsSettingsTab.prototype = {
    /**
     * @return {Element} element
     */
    _createExperimentsWarningSubsection: function()
    {
        var subsection = document.createElement("div");
        var warning = subsection.createChild("span", "settings-experiments-warning-subsection-warning");
        warning.textContent = WebInspector.UIString("WARNING:");
        subsection.appendChild(document.createTextNode(" "));
        var message = subsection.createChild("span", "settings-experiments-warning-subsection-message");
        message.textContent = WebInspector.UIString("These experiments could be dangerous and may require restart.");
        return subsection;
    },

    _createExperimentCheckbox: function(experiment)
    {
        var input = document.createElement("input");
        input.type = "checkbox";
        input.name = experiment.name;
        input.checked = experiment.isEnabled();
        function listener()
        {
            experiment.setEnabled(input.checked);
        }
        input.addEventListener("click", listener, false);

        var p = document.createElement("p");
        var label = document.createElement("label");
        label.appendChild(input);
        label.appendChild(document.createTextNode(WebInspector.UIString(experiment.title)));
        p.appendChild(label);
        return p;
    },

    __proto__: WebInspector.SettingsTab.prototype
}

/**
 * @constructor
 */
WebInspector.SettingsController = function()
{
    this._statusBarButton = new WebInspector.StatusBarButton(WebInspector.UIString("Settings"), "settings-status-bar-item");;
    this._statusBarButton.addEventListener("click", this._buttonClicked, this);

    /** @type {?WebInspector.SettingsScreen} */
    this._settingsScreen;
}

WebInspector.SettingsController.prototype =
{
    get statusBarItem()
    {
        return this._statusBarButton.element;
    },

    _buttonClicked: function()
    {
        if (this._statusBarButton.toggled)
            this._hideSettingsScreen();
        else
            this.showSettingsScreen();
    },

    _onHideSettingsScreen: function()
    {
        this._statusBarButton.toggled = false;
    },

    /**
     * @param {string=} tabId
     */
    showSettingsScreen: function(tabId)
    {
        if (!this._settingsScreen)
            this._settingsScreen = new WebInspector.SettingsScreen(this._onHideSettingsScreen.bind(this));

        if (tabId)
            this._settingsScreen.selectTab(tabId);

        this._settingsScreen.showModal();
        this._statusBarButton.toggled = true;
    },

    _hideSettingsScreen: function()
    {
        if (this._settingsScreen)
            this._settingsScreen.hide();
    },

    resize: function()
    {
        if (this._settingsScreen && this._settingsScreen.isShowing())
            this._settingsScreen.doResize();
    }
}


text:
// NG
import {
  ChangeDetectorRef,
  Component,
  ElementRef,
  EventEmitter,
  forwardRef,
  HostBinding,
  Input,
  OnChanges,
  OnInit,
  Output,
  SimpleChanges,
  ViewChild,
} from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { format, parse } from 'date-fns';
import * as IMask from 'imask';
import { DateFormatService } from '../../services/date-format/DateFormat';
import { NovoLabelService } from '../../services/novo-label-service';
import { Key } from '../../utils';
import { Helpers } from '../../utils/Helpers';
// App
import { NovoOverlayTemplateComponent } from '../common/overlay/Overlay';

// Value accessor for the component (supports ngModel)
const DATE_VALUE_ACCESSOR = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => NovoTimePickerInputElement),
  multi: true,
};

@Component({
  selector: 'novo-time-picker-input',
  providers: [DATE_VALUE_ACCESSOR],
  template: `
    <input
      type="text"
      [name]="name"
      [(ngModel)]="value"
      [imask]="maskOptions"
      [unmask]="'typed'"
      (complete)="onComplete($event)"
      [placeholder]="placeholder"
      (focus)="_handleFocus($event)"
      (keydown)="_handleKeydown($event)"
      (input)="_handleInput($event)"
      (blur)="_handleBlur($event)"
      #input
      data-automation-id="time-input"
      [disabled]="disabled"
    />

    <novo-overlay-template [parent]="element" position="above-below">
      <novo-time-picker
        inline="true"
        [analog]="analog"
        (onSelect)="setValue($event)"
        [ngModel]="value"
        [military]="military"
      ></novo-time-picker>
    </novo-overlay-template>
  `,
})
export class NovoTimePickerInputElement implements OnInit, OnChanges, ControlValueAccessor {
  public value: any;

  /** View -> model callback called when value changes */
  _onChange: (value: any) => void = () => {};
  /** View -> model callback called when autocomplete has been touched */
  _onTouched = () => {};

  @Input()
  name: string;
  @Input()
  placeholder: string;
  @Input()
  military: boolean = false;
  @Input()
  maskOptions: any;
  @HostBinding('class.disabled')
  @Input()
  disabled: boolean = false;

  /**
   * @deprecated don't use
   */
  @Input()
  analog: boolean = false;

  @Output()
  blurEvent: EventEmitter<FocusEvent> = new EventEmitter<FocusEvent>();
  @Output()
  focusEvent: EventEmitter<FocusEvent> = new EventEmitter<FocusEvent>();
  /** Element for the panel containing the autocomplete options. */
  @ViewChild(NovoOverlayTemplateComponent)
  overlay: NovoOverlayTemplateComponent;
  @ViewChild('input')
  input: HTMLInputElement;

  constructor(
    public element: ElementRef,
    public labels: NovoLabelService,
    public dateFormatService: DateFormatService,
    protected _changeDetectorRef: ChangeDetectorRef,
  ) {}

  ngOnInit(): void {
    this.initFormatOptions();
  }

  ngOnChanges(changes?: SimpleChanges) {
    // set icon and styling
    if (Object.keys(changes).some((key) => ['military', 'maskOptions'].includes(key))) {
      this.initFormatOptions();
    }
  }

  initFormatOptions() {
    this.placeholder = this.military ? this.labels.timeFormatPlaceholder24Hour : this.labels.timeFormatPlaceholderAM;
    const timeFormat = this.military ? 'HH:mm' : 'hh:mm A';
    const amFormat = this.labels.timeFormatAM.toUpperCase();
    const pmFormat = this.labels.timeFormatPM.toUpperCase();
    this.maskOptions = {
      mask: Date,
      pattern: this.military ? 'HH:mm' : 'hh:mm aa',
      overwrite: true,
      autofix: true,
      lazy: false,
      min: new Date(1970, 0, 1),
      max: new Date(2030, 0, 1),
      prepare(str) {
        return str.toUpperCase();
      },
      format(date) {
        return format(date, timeFormat);
      },
      parse: (str) => {
        const time = this.military ? str : this.convertTime12to24(str);
        return parse(`${format(Date.now(), 'YYYY-MM-DD')}T${time}`);
      },
      blocks: {
        HH: {
          mask: IMask.MaskedRange,
          placeholderChar: 'H',
          maxLength: 2,
          from: 0,
          to: 23,
        },
        hh: {
          mask: IMask.MaskedRange,
          placeholderChar: 'h',
          maxLength: 2,
          from: 1,
          to: 12,
        },
        mm: {
          mask: IMask.MaskedRange,
          placeholderChar: 'm',
          maxLength: 2,
          from: 0,
          to: 59,
        },
        aa: {
          mask: IMask.MaskedEnum,
          placeholderChar: 'x',
          enum: ['AM', 'PM', 'am', 'pm', amFormat, pmFormat],
        },
      },
    };
  }

  onComplete(dt) {
    if (this.value instanceof Date && dt instanceof Date) {
      if (this.value.getTime() !== dt.getTime()) {
        this.dispatchOnChange(dt);
      }
    }
    else if (this.value !== dt) {
      this.dispatchOnChange(dt);
    }
  }

  /** BEGIN: Convenient Panel Methods. */
  openPanel(): void {
    if (!this.overlay.panelOpen) {
      this.overlay.openPanel();
      const hour = new Date().getHours();
      Promise.resolve(null).then(() => this.scrollToIndex(hour * 4));
    }
  }

  closePanel(): void {
    this.overlay.closePanel();
  }

  get panelOpen(): boolean {
    return this.overlay && this.overlay.panelOpen;
  }

  /** END: Convenient Panel Methods. */

  _handleKeydown(event: KeyboardEvent): void {
    const input = event.target as HTMLInputElement;
    const hour: string = input.value.slice(0, 2);
    if ((event.key === Key.Escape || event.key === Key.Enter) && this.panelOpen) {
      this.closePanel();
      event.stopPropagation();
      event.stopImmediatePropagation();
      if (this.hourOneFormatRequired(hour)) {
        input.value = `01:${input.value.slice(3, input.value.length)}`;
      }
    } else if (event.key === Key.Tab && input.selectionStart <= 2 && this.hourOneFormatRequired(hour)) {
      event.preventDefault();
      event.stopPropagation();
      event.stopImmediatePropagation();
      input.value = `01:${input.value.slice(3, input.value.length)}`;
      input.setSelectionRange(3, 3);
    } else if (event.key === Key.Backspace && input.selectionStart === input.value.length) {
      input.value = `${input.value.slice(0, 5)} xx`;
    } else if (event.key === Key.Tab && this.panelOpen) {
      this.closePanel();
      event.stopPropagation();
      event.stopImmediatePropagation();
    } else if (event.key === Key.ArrowRight && input.selectionStart >= 2 && this.hourOneFormatRequired(hour)) {
      input.value = `01:${input.value.slice(3, input.value.length)}`;
      input.setSelectionRange(2, 2);
    }
  }

  _handleInput(event: KeyboardEvent): void {
    if (document.activeElement === event.target) {
      const text = (event.target as HTMLInputElement).value;
      const hour = text.slice(0, 2);
      this.openPanel();
      if ((this.military && Number(text[0]) > 2) || (!this.military && Number(text[0]) > 1)) {
        event.preventDefault();
        (event.target as HTMLInputElement).value = `0${text}`;
      }
      if (!this.military) {
        const test = text.substr(5, 4).replace(/x/g, '').trim().slice(0, 2);
        const timePeriod = this.maskOptions.blocks.aa.enum.find((it) => it[0] === test[0]);
        if (timePeriod) {
          (event.target as HTMLInputElement).value = `${(event.target as HTMLInputElement).value.slice(0, 5)} ${timePeriod}`;
        }
        if ((event.target as HTMLInputElement).selectionStart >= 3 && this.hourOneFormatRequired(hour)) {
          (event.target as HTMLInputElement).value = `01:${(event.target as HTMLInputElement).value.slice(
            3,
            (event.target as HTMLInputElement).value.length,
          )}`;
        }
      }
    }
  }

  _handleBlur(event: FocusEvent): void {
    const text = (event.target as HTMLInputElement).value;
    const hour: string = text.slice(0, 2);
    if (!this.military) {
      const test = text.substr(5, 4).replace(/x/g, '').trim().slice(0, 2);
      const timePeriod = this.maskOptions.blocks.aa.enum.find((it) => it[0] === test[0]);
      if (this.hourOneFormatRequired(hour)) {
        (event.target as HTMLInputElement).value = `01:${text.slice(3, text.length)}`;
      }
      if (!timePeriod) {
        (event.target as HTMLInputElement).value = `${(event.target as HTMLInputElement).value.slice(0, 5)} xx`;
      }
    }
  }

  _handleFocus(event: FocusEvent): void {
    this.openPanel();
    this.focusEvent.emit(event);
  }

  writeValue(value: any): void {
    Promise.resolve(null).then(() => this._setTriggerValue(value));
  }

  registerOnChange(fn: (value: any) => {}): void {
    this._onChange = fn;
  }

  registerOnTouched(fn: () => {}) {
    this._onTouched = fn;
  }

  setDisabledState(disabled: boolean): void {
    this.disabled = disabled;
  }

  public dispatchOnChange(newValue?: any, skip: boolean = false) {
    if (newValue !== this.value) {
      this._onChange(newValue);
      !skip && this.writeValue(newValue);
    }
  }

  private _setTriggerValue(value: any): void {
    if (value instanceof Date && this.value instanceof Date) {
      value = new Date(value.setFullYear(this.value.getFullYear(), this.value.getMonth(), this.value.getDate()));
    }
    this.value = value;
    this._changeDetectorRef.markForCheck();
  }

  public setValue(event: any | null): void {
    if (event && event.date) {
      this.dispatchOnChange(event.date);
    }
  }

  public setValueAndClose(event: any | null): void {
    this.setValue(event);
    this.closePanel();
  }

  /**
   * Clear any previous selected option and emit a selection change event for this option
   */
  public clearValue() {
    this.dispatchOnChange(null);
  }

  public get hasValue() {
    return !Helpers.isEmpty(this.value);
  }

  public scrollToIndex(index: number) {
    const element = this.overlay.overlayRef.overlayElement;
    const list = element.querySelector('.increments');
    const items = list.querySelectorAll('novo-list-item');
    const item = items[index];
    if (item) {
      list.scrollTop = (item as HTMLElement).offsetTop;
    }
  }

  convertTime12to24(time12h: string) {
    const pmFormat = this.labels.timeFormatPM.toUpperCase();

    const [time, modifier] = time12h.split(' ');
    let [hours, minutes] = time.split(':');
    if (hours === '12') {
      hours = '00';
    }
    if (['PM', pmFormat].includes(modifier)) {
      hours = `${parseInt(hours, 10) + 12}`.padStart(2, '0');
    }
    return `${hours}:${minutes}`;
  }

  hourOneFormatRequired(hourInput: string): boolean {
    return hourInput === 'h1' || hourInput === '1h';
  }
}

redpajama_set_name: RedPajamaGithub


text:
.. _advanced-installation:

.. include:: ../min_dependency_substitutions.rst

==================================================
Installing the development version of scikit-learn
==================================================

This section introduces how to install the **main branch** of scikit-learn.
This can be done by either installing a nightly build or building from source.

.. _install_nightly_builds:

Installing nightly builds
=========================

The continuous integration servers of the scikit-learn project build, test
and upload wheel packages for the most recent Python version on a nightly
basis.

Installing a nightly build is the quickest way to:

- try a new feature that will be shipped in the next release (that is, a
  feature from a pull-request that was recently merged to the main branch);

- check whether a bug you encountered has been fixed since the last release.

You can install the nightly build of scikit-learn using the `scipy-wheels-nightly`
index from the PyPI registry of `anaconda.org`:
.. prompt:: bash $

  pip install --pre --extra-index https://pypi.anaconda.org/scipy-wheels-nightly/simple scikit-learn

Note that first uninstalling scikit-learn might be required to be able to
install nightly builds of scikit-learn.

.. _install_bleeding_edge:

Building from source
====================

Building from source is required to work on a contribution (bug fix, new
feature, code or documentation improvement).

.. _git_repo:

#. Use `Git <https://git-scm.com/>`_ to check out the latest source from the
   `scikit-learn repository <https://github.com/scikit-learn/scikit-learn>`_ on
   Github.:

   .. prompt:: bash $

     git clone git://github.com/scikit-learn/scikit-learn.git  # add --depth 1 if your connection is slow
     cd scikit-learn

   If you plan on submitting a pull-request, you should clone from your fork
   instead.

#. Install a recent version of Python (3.9 is recommended at the time of writing)
   for instance using Miniforge3_. Miniforge provides a conda-based distribution
   of Python and the most popular scientific libraries.

   If you installed Python with conda, we recommend to create a dedicated
   `conda environment`_ with all the build dependencies of scikit-learn
   (namely NumPy_, SciPy_, and Cython_):

   .. prompt:: bash $

     conda create -n sklearn-env -c conda-forge python=3.9 numpy scipy cython
     conda activate sklearn-env

#. **Alternative to conda:** If you run Linux or similar, you can instead use
   your system's Python provided it is recent enough (3.8 or higher
   at the time of writing). In this case, we recommend to create a dedicated
   virtualenv_ and install the scikit-learn build dependencies with pip:

   .. prompt:: bash $

     python3 -m venv sklearn-env
     source sklearn-env/bin/activate
     pip install wheel numpy scipy cython

#. Install a compiler with OpenMP_ support for your platform. See instructions
   for :ref:`compiler_windows`, :ref:`compiler_macos`, :ref:`compiler_linux`
   and :ref:`compiler_freebsd`.

#. Build the project with pip in :ref:`editable_mode`:

   .. prompt:: bash $

     pip install --verbose --no-build-isolation --editable .

#. Check that the installed scikit-learn has a version number ending with
   `.dev0`:

   .. prompt:: bash $

     python -c "import sklearn; sklearn.show_versions()"

#. Please refer to the :ref:`developers_guide` and :ref:`pytest_tips` to run
   the tests on the module of your choice.

.. note::

    You will have to run the ``pip install --no-build-isolation --editable .``
    command every time the source code of a Cython file is updated
    (ending in `.pyx` or `.pxd`). Use the ``--no-build-isolation`` flag to
    avoid compiling the whole project each time, only the files you have
    modified.

Dependencies
------------

Runtime dependencies
~~~~~~~~~~~~~~~~~~~~

Scikit-learn requires the following dependencies both at build time and at
runtime:

- Python (>= 3.8),
- NumPy (>= |NumpyMinVersion|),
- SciPy (>= |ScipyMinVersion|),
- Joblib (>= |JoblibMinVersion|),
- threadpoolctl (>= |ThreadpoolctlMinVersion|).

Build dependencies
~~~~~~~~~~~~~~~~~~

Building Scikit-learn also requires:

..
    # The following places need to be in sync with regard to Cython version:
    # - .circleci config file
    # - sklearn/_build_utils/__init__.py
    # - advanced installation guide

- Cython >= |CythonMinVersion|
- A C/C++ compiler and a matching OpenMP_ runtime library. See the
  :ref:`platform system specific instructions
  <platform_specific_instructions>` for more details.

.. note::

   If OpenMP is not supported by the compiler, the build will be done with
   OpenMP functionalities disabled. This is not recommended since it will force
   some estimators to run in sequential mode instead of leveraging thread-based
   parallelism. Setting the ``SKLEARN_FAIL_NO_OPENMP`` environment variable
   (before cythonization) will force the build to fail if OpenMP is not
   supported.

Since version 0.21, scikit-learn automatically detects and uses the linear
algebra library used by SciPy **at runtime**. Scikit-learn has therefore no
build dependency on BLAS/LAPACK implementations such as OpenBlas, Atlas, Blis
or MKL.

Test dependencies
~~~~~~~~~~~~~~~~~

Running tests requires:

- pytest >= |PytestMinVersion|

Some tests also require `pandas <https://pandas.pydata.org>`_.

Building a specific version from a tag
--------------------------------------

If you want to build a stable version, you can ``git checkout <VERSION>``
to get the code for that particular version, or download an zip archive of
the version from github.

.. _editable_mode:

Editable mode
-------------

If you run the development version, it is cumbersome to reinstall the package
each time you update the sources. Therefore it is recommended that you install
in with the ``pip install --no-build-isolation --editable .`` command, which
allows you to edit the code in-place. This builds the extension in place and
creates a link to the development directory (see `the pip docs
<https://pip.pypa.io/en/stable/topics/local-project-installs/#editable-installs>`_).

As the doc aboves explains, this is fundamentally similar to using the command
``python setup.py develop``. (see `the setuptool docs
<https://setuptools.pypa.io/en/latest/userguide/development_mode.html>`_).
It is however preferred to use pip.

On Unix-like systems, you can equivalently type ``make in`` from the top-level
folder. Have a look at the ``Makefile`` for additional utilities.

.. _platform_specific_instructions:

Platform-specific instructions
==============================

Here are instructions to install a working C/C++ compiler with OpenMP support
to build scikit-learn Cython extensions for each supported platform.

.. _compiler_windows:

Windows
-------

First, download the `Build Tools for Visual Studio 2019 installer
<https://aka.ms/vs/17/release/vs_buildtools.exe>`_.

Run the downloaded `vs_buildtools.exe` file, during the installation you will
need to make sure you select "Desktop development with C++", similarly to this
screenshot:

.. image:: ../images/visual-studio-build-tools-selection.png

Secondly, find out if you are running 64-bit or 32-bit Python. The building
command depends on the architecture of the Python interpreter. You can check
the architecture by running the following in ``cmd`` or ``powershell``
console:

.. prompt:: bash $

    python -c "import struct; print(struct.calcsize('P') * 8)"

For 64-bit Python, configure the build environment by running the following
commands in ``cmd`` or an Anaconda Prompt (if you use Anaconda):

    ::

      $ SET DISTUTILS_USE_SDK=1
      $ "C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Auxiliary\Build\vcvarsall.bat" x64

Replace ``x64`` by ``x86`` to build for 32-bit Python.

Please be aware that the path above might be different from user to user. The
aim is to point to the "vcvarsall.bat" file that will set the necessary
environment variables in the current command prompt.

Finally, build scikit-learn from this command prompt:

.. prompt:: bash $

    pip install --verbose --no-build-isolation --editable .

.. _compiler_macos:

macOS
-----

The default C compiler on macOS, Apple clang (confusingly aliased as
`/usr/bin/gcc`), does not directly support OpenMP. We present two alternatives
to enable OpenMP support:

- either install `conda-forge::compilers` with conda;

- or install `libomp` with Homebrew to extend the default Apple clang compiler.

For Apple Silicon M1 hardware, only the conda-forge method below is known to
work at the time of writing (January 2021). You can install the `macos/arm64`
distribution of conda using the `miniforge installer
<https://github.com/conda-forge/miniforge#miniforge>`_

macOS compilers from conda-forge
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

If you use the conda package manager (version >= 4.7), you can install the
``compilers`` meta-package from the conda-forge channel, which provides
OpenMP-enabled C/C++ compilers based on the llvm toolchain.

First install the macOS command line tools:

.. prompt:: bash $

    xcode-select --install

It is recommended to use a dedicated `conda environment`_ to build
scikit-learn from source:

.. prompt:: bash $

    conda create -n sklearn-dev -c conda-forge python numpy scipy cython \
        joblib threadpoolctl pytest compilers llvm-openmp
    conda activate sklearn-dev
    make clean
    pip install --verbose --no-build-isolation --editable .

.. note::

    If you get any conflicting dependency error message, try commenting out
    any custom conda configuration in the ``$HOME/.condarc`` file. In
    particular the ``channel_priority: strict`` directive is known to cause
    problems for this setup.

You can check that the custom compilers are properly installed from conda
forge using the following command:

.. prompt:: bash $

    conda list

which should include ``compilers`` and ``llvm-openmp``.

.. note::

   If you installed these packages after creating and activating a new conda
   environment, you will need to first deactivate and then reactivate the
   environment for these changes to take effect.

The compilers meta-package will automatically set custom environment
variables:

.. prompt:: bash $

    echo $CC
    echo $CXX
    echo $CFLAGS
    echo $CXXFLAGS
    echo $LDFLAGS

They point to files and folders from your ``sklearn-dev`` conda environment
(in particular in the bin/, include/ and lib/ subfolders). For instance
``-L/path/to/conda/envs/sklearn-dev/lib`` should appear in ``LDFLAGS``.

In the log, you should see the compiled extension being built with the clang
and clang++ compilers installed by conda with the ``-fopenmp`` command line
flag.

macOS compilers from Homebrew
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Another solution is to enable OpenMP support for the clang compiler shipped
by default on macOS.

First install the macOS command line tools:

.. prompt:: bash $

    xcode-select --install

Install the Homebrew_ package manager for macOS.

Install the LLVM OpenMP library:

.. prompt:: bash $

    brew install libomp

Set the following environment variables:

.. prompt:: bash $

    export CC=/usr/bin/clang
    export CXX=/usr/bin/clang++
    export CPPFLAGS="$CPPFLAGS -Xpreprocessor -fopenmp"
    export CFLAGS="$CFLAGS -I/usr/local/opt/libomp/include"
    export CXXFLAGS="$CXXFLAGS -I/usr/local/opt/libomp/include"
    export LDFLAGS="$LDFLAGS -Wl,-rpath,/usr/local/opt/libomp/lib -L/usr/local/opt/libomp/lib -lomp"

Finally, build scikit-learn in verbose mode (to check for the presence of the
``-fopenmp`` flag in the compiler commands):

.. prompt:: bash $

    make clean
    pip install --verbose --no-build-isolation --editable .

.. _compiler_linux:

Linux
-----

Linux compilers from the system
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Installing scikit-learn from source without using conda requires you to have
installed the scikit-learn Python development headers and a working C/C++
compiler with OpenMP support (typically the GCC toolchain).

Install build dependencies for Debian-based operating systems, e.g.
Ubuntu:

.. prompt:: bash $

    sudo apt-get install build-essential python3-dev python3-pip

then proceed as usual:

.. prompt:: bash $

    pip3 install cython
    pip3 install --verbose --editable .

Cython and the pre-compiled wheels for the runtime dependencies (numpy, scipy
and joblib) should automatically be installed in
``$HOME/.local/lib/pythonX.Y/site-packages``. Alternatively you can run the
above commands from a virtualenv_ or a `conda environment`_ to get full
isolation from the Python packages installed via the system packager. When
using an isolated environment, ``pip3`` should be replaced by ``pip`` in the
above commands.

When precompiled wheels of the runtime dependencies are not available for your
architecture (e.g. ARM), you can install the system versions:

.. prompt:: bash $

    sudo apt-get install cython3 python3-numpy python3-scipy

On Red Hat and clones (e.g. CentOS), install the dependencies using:

.. prompt:: bash $

    sudo yum -y install gcc gcc-c++ python3-devel numpy scipy

Linux compilers from conda-forge
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Alternatively, install a recent version of the GNU C Compiler toolchain (GCC)
in the user folder using conda:

.. prompt:: bash $

    conda create -n sklearn-dev -c conda-forge python numpy scipy cython \
        joblib threadpoolctl pytest compilers
    conda activate sklearn-dev
    pip install --verbose --no-build-isolation --editable .

.. _compiler_freebsd:

FreeBSD
-------

The clang compiler included in FreeBSD 12.0 and 11.2 base systems does not
include OpenMP support. You need to install the `openmp` library from packages
(or ports):

.. prompt:: bash $

    sudo pkg install openmp

This will install header files in ``/usr/local/include`` and libs in
``/usr/local/lib``. Since these directories are not searched by default, you
can set the environment variables to these locations:

.. prompt:: bash $

    export CFLAGS="$CFLAGS -I/usr/local/include"
    export CXXFLAGS="$CXXFLAGS -I/usr/local/include"
    export LDFLAGS="$LDFLAGS -Wl,-rpath,/usr/local/lib -L/usr/local/lib -lomp"

Finally, build the package using the standard command:

.. prompt:: bash $

    pip install --verbose --no-build-isolation --editable .

For the upcoming FreeBSD 12.1 and 11.3 versions, OpenMP will be included in
the base system and these steps will not be necessary.

.. _OpenMP: https://en.wikipedia.org/wiki/OpenMP
.. _Cython: https://cython.org
.. _NumPy: https://numpy.org
.. _SciPy: https://www.scipy.org
.. _Homebrew: https://brew.sh
.. _virtualenv: https://docs.python.org/3/tutorial/venv.html
.. _conda environment: https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html
.. _Miniforge3: https://github.com/conda-forge/miniforge#miniforge3

Parallel builds
===============

It is possible to build scikit-learn compiled extensions in parallel by setting
and environment variable as follows before calling the ``pip install`` or
``python setup.py build_ext`` commands::

    export SKLEARN_BUILD_PARALLEL=3
    pip install --verbose --no-build-isolation --editable .

On a machine with 2 CPU cores, it can be beneficial to use a parallelism level
of 3 to overlap IO bound tasks (reading and writing files on disk) with CPU
bound tasks (actually compiling).


text:
package com.ctrip.platform.dal.dao.task;

public class CombinedReplaceTask<T> extends AbstractCombinedInsertTask<T> {
    public static final String TPL_SQL_COMBINED_REPLACE = "REPLACE INTO %s(%s) VALUES %s";

    @Override
    protected String getSqlTpl() {
        return TPL_SQL_COMBINED_REPLACE;
    }
}


text:
#include "OggVorbis.h"

#include <Audio/AudioGlobals.h>

namespace Audio
{

extern LPOVCLEAR           ov_clear;
extern LPOVREAD            ov_read;
extern LPOVPCMTOTAL        ov_pcm_total;
extern LPOVINFO            ov_info;
extern LPOVCOMMENT         ov_comment;
extern LPOVOPENCALLBACKS   ov_open_callbacks;
extern LPOVTIMESEEK         ov_time_seek;

size_t ov_read_func(void *ptr, size_t size, size_t nmemb, void * datasource);
int ov_seek_func(void *datasource, ogg_int64_t offset, int whence);
long ov_tell_func(void *datasource);

OggVorbis::OggVorbis()
:   _oggVorbisData(Core::Buffer(0)),
    _offset(0)
{
    _callbacks.close_func = NULL;
    _callbacks.read_func = ov_read_func;
    _callbacks.seek_func = ov_seek_func;
    _callbacks.tell_func = ov_tell_func;
}
//-----------------------------------------------------------------------------
OggVorbis::~OggVorbis()
{
}
//-----------------------------------------------------------------------------
void OggVorbis::read(Core::InputStream & input)
{
    _oggVorbisData.read(input);

    if(ov_open_callbacks(this, &_oggVorbisFile, NULL, 0, _callbacks) == 0)
    {
        // Get some information about the file (Channels, Format, and Frequency)
		vorbis_info * pVorbisInfo = ov_info(&_oggVorbisFile, -1);
        _frequency = pVorbisInfo->rate;
        _nbChannels = pVorbisInfo->channels;
    }
    else
    {
        throw Core::Exception(L"An error occured while trying to read an Ogg Vorbis stream.");
    }
}
//-----------------------------------------------------------------------------
void OggVorbis::write(Core::OutputStream & output) const
{
    _oggVorbisData.write(output);
}
//-----------------------------------------------------------------------------
uint32 OggVorbis::getFrequency() const
{
    return _frequency;
}
//-----------------------------------------------------------------------------
uint32 OggVorbis::getNbChannels() const
{
    return _nbChannels;
}
//-----------------------------------------------------------------------------
uint32 OggVorbis::getBufferSizeFor250ms() const
{
    uint32 bufferSize = 0;
    if (_nbChannels == 1)
	{
		// Set BufferSize to 250ms (Frequency * 2 (16bit) divided by 4 (quarter of a second))
		bufferSize = _frequency >> 1;
		// IMPORTANT : The Buffer Size must be an exact multiple of the BlockAlignment ...
		bufferSize -= (bufferSize % 2);
	}
	else if (_nbChannels == 2)
	{
		// Set BufferSize to 250ms (Frequency * 4 (16bit stereo) divided by 4 (quarter of a second))
		bufferSize = _frequency;
		// IMPORTANT : The Buffer Size must be an exact multiple of the BlockAlignment ...
		bufferSize -= (bufferSize % 4);
	}
	else if (_nbChannels == 4)
	{
		// Set BufferSize to 250ms (Frequency * 8 (16bit 4-channel) divided by 4 (quarter of a second))
		bufferSize = _frequency * 2;
		// IMPORTANT : The Buffer Size must be an exact multiple of the BlockAlignment ...
		bufferSize -= (bufferSize % 8);
	}
	else if (_nbChannels == 6)
	{
        // Set BufferSize to 250ms (Frequency * 12 (16bit 6-channel) divided by 4 (quarter of a second))
		bufferSize = _frequency * 3;
		// IMPORTANT : The Buffer Size must be an exact multiple of the BlockAlignment ...
		bufferSize -= (bufferSize % 12);
	}

    return bufferSize;
}
//-----------------------------------------------------------------------------
void OggVorbis::rewind()
{
    ov_time_seek(&_oggVorbisFile, 0);
}
//-----------------------------------------------------------------------------
int32 OggVorbis::getData(Core::Buffer & buffer)
{
    int32 current_section = 0;
	int32 decodedSize;
	int32 bytesDone = 0;

    bool decodeAgain = true;
	while(decodeAgain)
	{
        decodedSize = ov_read(&_oggVorbisFile, (char *)buffer.getData() + bytesDone, buffer.size() - bytesDone, 0, 2, 1, &current_section);

		if (decodedSize > 0)
		{
			bytesDone += decodedSize;

			if (bytesDone >= buffer.size())
				decodeAgain = false;
		}
		else
		{
			decodeAgain = false;
		}
	}

	// Mono, Stereo and 4-Channel files decode into the same channel order as WAVEFORMATEXTENSIBLE,
	// however 6-Channels files need to be re-ordered
	if (_nbChannels == 6)
	{
        int32 iSample;
	    int16 * pSamples;
        pSamples = (int16*)buffer.getData();
		for (iSample = 0; iSample < (buffer.size()>>1); iSample+=6)
		{
			// WAVEFORMATEXTENSIBLE Order : FL, FR, FC, LFE, RL, RR
			// OggVorbis Order            : FL, FC, FR,  RL, RR, LFE
			swap(pSamples[iSample+1], pSamples[iSample+2]);
			swap(pSamples[iSample+3], pSamples[iSample+5]);
			swap(pSamples[iSample+4], pSamples[iSample+5]);
		}
	}

	return bytesDone;
}
//-----------------------------------------------------------------------------
int32 OggVorbis::oggRead(void * ptr, int32 size)
{
    int32 readSize = 0;
    if(_offset < _oggVorbisData.size())
    {
        byte * data = _oggVorbisData.getData();
        data += _offset;

        int32 remainingBytesCount = _oggVorbisData.size() - _offset;
        readSize = std::min(remainingBytesCount, size);

        memcpy(ptr, data, readSize);
        _offset += readSize;
    }

    return readSize;
}
//-----------------------------------------------------------------------------
int32 OggVorbis::oggSeek(long offset, int32 origin)
{
    int32 oldPosition = _offset;
    switch(origin)
    {
    case SEEK_SET: _offset = offset; break;
    case SEEK_CUR: _offset += offset; break;
    case SEEK_END: _offset = (_oggVorbisData.size() - 1) - offset; break;
    }
    return oldPosition;
}
//-----------------------------------------------------------------------------
int32 OggVorbis::oggTell() const
{
    return _offset;
}
//-----------------------------------------------------------------------------
void OggVorbis::swap(int16 & s1, int16 & s2)
{
	int16 sTemp = s1;
	s1 = s2;
	s2 = sTemp;
}
//-----------------------------------------------------------------------------
//      CALLBACKS OGGVORBIS
//-----------------------------------------------------------------------------
size_t ov_read_func(void *ptr, size_t size, size_t nmemb, void * datasource)
{
    OggVorbis * pOggVorbis = reinterpret_cast<OggVorbis *>(datasource);
    return pOggVorbis->oggRead(ptr, size*nmemb);
}

int ov_seek_func(void *datasource, ogg_int64_t offset, int whence)
{
    OggVorbis * pOggVorbis = reinterpret_cast<OggVorbis *>(datasource);
    return pOggVorbis->oggSeek((int32)offset, whence);
}

long ov_tell_func(void *datasource)
{
    OggVorbis * pOggVorbis = reinterpret_cast<OggVorbis *>(datasource);
    return pOggVorbis->oggTell();
}

}


text:
package TYUTservice.data;

public class MessageLogin extends MessageTyut {
	public MessageLogin(int id, int status, String cookie) {
		super(id, status);
		this.cookie = cookie;
		// TODO Auto-generated constructor stub
	}

	public String getCookie() {
		return cookie;
	}

	public void setCookie(String cookie) {
		this.cookie = cookie;
	}

	// cookie
	private String cookie;

}


text:
package com.stratio.ingestion.sink.mongodb;

import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.flume.Event;
import org.bson.types.ObjectId;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.joda.time.format.ISODateTimeFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Charsets;
import com.google.common.io.BaseEncoding;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.util.JSON;
import com.mongodb.util.JSONParseException;

class EventParser {

    private static final Logger log = LoggerFactory.getLogger(EventParser.class);

    private static final String DEFAULT_BINARY_ENCODING = "base64";
    private static final String DOCUMENT_TYPE = "document";

    private final MappingDefinition definition;

    public EventParser() {
        this(new MappingDefinition());
    }

    public EventParser(final MappingDefinition mappingDefinition) {
        this.definition = mappingDefinition;
    }

    public Object parseValue(final FieldDefinition fd, final String stringValue) {
        if (fd == null || fd.getType() == null) {
            try {
                return JSON.parse(stringValue);
            } catch (JSONParseException ex) {
                // XXX: Default to String
                log.trace("Could not parse as JSON, defaulting to String: {}", stringValue);
                return stringValue;
            }
        }
        switch (fd.getType()) {
        case DOUBLE:
            return Double.parseDouble(stringValue);
        case STRING:
            return stringValue;
        case OBJECT:
        case ARRAY:
            // TODO: should we use customizable array representation?
            // TODO: should we check that the result is indeed an array or object?
            return JSON.parse(stringValue);
        case BINARY:
            SimpleFieldDefinition sfd = (SimpleFieldDefinition) fd;
            final String encoding = (sfd.getEncoding() == null) ? DEFAULT_BINARY_ENCODING : sfd.getEncoding()
                    .toLowerCase(Locale.ENGLISH);
            if ("base64".equals(encoding)) {
                return BaseEncoding.base64().decode(stringValue);
            } else {
                throw new UnsupportedOperationException("Unsupported encoding for binary type: " + encoding);
            }
            // TODO: case "UNDEFINED":
        case OBJECTID:
            return new ObjectId(stringValue);
        case BOOLEAN:
            return Boolean.parseBoolean(stringValue);
        case DATE:
            DateFormat dateFormat = ((DateFieldDefinition) fd).getDateFormat();
            if (dateFormat == null) {
                if (NumberUtils.isNumber(stringValue)) {
                    return new Date(Long.parseLong(stringValue));
                } else {
                    return ISODateTimeFormat.dateOptionalTimeParser().parseDateTime(stringValue).toDate();
                }
            } else {
                try {
                    return dateFormat.parse(stringValue);
                } catch (ParseException ex) {
                    // XXX: Default to string
                    log.warn("Could not parse date, defaulting to String: {}", stringValue);
                    return stringValue;
                }
            }
        case NULL:
            // TODO: Check if this is valid
            return null;
            // TODO: case "REGEX":
            // TODO: case "JAVASCRIPT":
            // TODO: case "SYMBOL":
            // TODO: case "JAVASCRIPT_SCOPE":
        case INT32:
            return Integer.parseInt(stringValue);
        case INT64:
            return Long.parseLong(stringValue);
        case DOCUMENT:
            return populateDocument((DocumentFieldDefinition) fd, stringValue);
        default:
            throw new UnsupportedOperationException("Unsupported type: " + fd.getType().name());
        }
    }

    public DBObject parse(Event event) {

        DBObject dbObject = new BasicDBObject();
        if (definition.getBodyType() != MongoDataType.NULL) {
            Object obj = null;
            if (definition.getBodyType() == MongoDataType.BINARY && definition.getBodyEncoding().equals("raw")) {
                obj = event.getBody();
            } else if (definition.getBodyType() == MongoDataType.STRING) {
                Charset charset = Charset.forName(definition.getBodyEncoding());
                obj = new String(event.getBody(), charset);
            } else {
                SimpleFieldDefinition fd = new SimpleFieldDefinition();
                fd.setType(definition.getBodyType());
                fd.setEncoding(definition.getBodyEncoding());
                obj = parseValue(fd, new String(event.getBody(), Charsets.UTF_8));
            }

            if (!"".equals(definition.getBodyField())) {
                dbObject.put(definition.getBodyField(), obj);
            } else if (obj instanceof DBObject) {
                dbObject = (DBObject) obj;
            } else {
                log.warn("Could not map body to JSON document: {}", obj);
            }
        }

        final Map<String, String> eventHeaders = event.getHeaders();
        if (definition.allowsAdditionalProperties()) {
            for (final Map.Entry<String, String> headerEntry : eventHeaders.entrySet()) {
                final String fieldName = headerEntry.getKey();
                final String fieldValue = headerEntry.getValue();
                FieldDefinition def = definition.getFieldDefinitionByName(fieldName);
                if (def == null) {
                    dbObject.put(fieldName, parseValue(null, fieldValue));
                } else {
                    final String mappedName = (def.getMappedName() == null) ? def.getFieldName() : def.getMappedName();
                    if (eventHeaders.containsKey(fieldName)) {
                        dbObject.put(mappedName, parseValue(def, fieldValue));
                    }
                }
            }
        } else {
            for (FieldDefinition def : definition.getFields()) {
                final String fieldName = def.getFieldName();
                final String mappedName = (def.getMappedName() == null) ? def.getFieldName() : def.getMappedName();
                if (containsKey(eventHeaders, fieldName)) {
                    dbObject.put(mappedName, parseValue(def, getFieldName(eventHeaders, fieldName)));
                }
            }
        }

        return dbObject;
    }

    private String getFieldName(Map<String, String> eventHeaders, String fieldName) {
        String value = null;
        if (fieldName.contains(".")) {
            ObjectMapper mapper = new ObjectMapper();
            final String[] fieldNameSplitted = fieldName.split("\\.");
            try {
                final String objectName = fieldNameSplitted[0];
                JsonNode jsonNode = mapper.readTree(eventHeaders.get(objectName));
                value = jsonNode.findValue(fieldNameSplitted[fieldNameSplitted.length - 1]).getTextValue();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            value = eventHeaders.get(fieldName);
        }
        return value;
    }

    private boolean containsKey(Map<String, String> eventHeaders, String fieldName) {
        if (StringUtils.isNotBlank(fieldName) && fieldName.contains(".")) {
            final String[] fieldNameSplitted = fieldName.split("\\.");
            return eventHeaders.containsKey(fieldNameSplitted[0]);
        } else {
            return eventHeaders.containsKey(fieldName);
        }
    }

    public List<DBObject> parse(List<Event> events) {
        List<DBObject> rows = new ArrayList<DBObject>(events.size());
        for (Event event : events) {
            rows.add(this.parse(event));
        }
        return rows;
    }

    private DBObject populateDocument(DocumentFieldDefinition fd, String document) {
        DBObject dbObject = null;
        final String delimiter = fd.getDelimiter();
        if (!StringUtils.isEmpty(delimiter)) {
            String[] documentAsArrray = document.split(Pattern.quote(delimiter));
            dbObject = new BasicDBObject();
            Map<String, FieldDefinition> documentMapping = new LinkedHashMap<String, FieldDefinition>(
                    fd.getDocumentMapping());
            int i = 0;
            for (Map.Entry<String, FieldDefinition> documentField : documentMapping.entrySet()) {
                if (DOCUMENT_TYPE.equalsIgnoreCase(documentField.getValue().getType().name())) {
                    dbObject.put(documentField.getKey(), parseValue(documentField.getValue(),
                            StringUtils.join(Arrays.copyOfRange(documentAsArrray, i, documentAsArrray.length), fd.getDelimiter())));
                    i += ((DocumentFieldDefinition) documentField.getValue()).getDocumentMapping().size();
                } else {
                    dbObject.put(documentField.getKey(), parseValue(documentField.getValue(), documentAsArrray[i++]));
                }
            }
        } else {
            throw new MongoSinkException("Delimiter char must be set");
        }

        return dbObject;
    }
}


text:
#include <ffi.h>
#include <ffi_common.h>
#include <stdlib.h>
#include <stdio.h>

/* General debugging routines */

void ffi_stop_here(void)
{
  /* This function is only useful for debugging purposes.
     Place a breakpoint on ffi_stop_here to be notified of
     significant events. */
}

/* This function should only be called via the FFI_ASSERT() macro */

void ffi_assert(char *expr, char *file, int line)
{
  fprintf(stderr, "ASSERTION FAILURE: %s at %s:%d\n", expr, file, line);
  ffi_stop_here();
  abort();
}

/* Perform a sanity check on an ffi_type structure */

void ffi_type_test(ffi_type *a, char *file, int line)
{
  FFI_ASSERT_AT(a != NULL, file, line);

  FFI_ASSERT_AT(a->type <= FFI_TYPE_LAST, file, line);
  FFI_ASSERT_AT(a->type == FFI_TYPE_VOID || a->size > 0, file, line);
  FFI_ASSERT_AT(a->type == FFI_TYPE_VOID || a->alignment > 0, file, line);
  FFI_ASSERT_AT((a->type != FFI_TYPE_STRUCT && a->type != FFI_TYPE_COMPLEX)
		|| a->elements != NULL, file, line);
  FFI_ASSERT_AT(a->type != FFI_TYPE_COMPLEX
		|| (a->elements != NULL
		    && a->elements[0] != NULL && a->elements[1] == NULL),
		file, line);

}


text:
<!DOCTYPE html>
<html>
  <head>
    {% include meta.html %}
      <link rel="alternate" type="application/rss+xml" title="RSS" href="/feed.xml">
      {% include css.html %}
  </head>

  <body class="home overflow-hidden">
    {% include header.html %}
    {% include main.html %}
    {% include js.html %}
  </body>
</html>


text:
layout: post
title: Closer part two
date: 2016-04-15 13:39:35.000000000 +03:00
permalink: /2016/04/15/closer-part-two/
featured:
  path: /assets/uploads/Closerparttwo-colaj.jpg
  alt: Closer part two
images:
- path: /assets/uploads/Closerparttwo-colaj.jpg
  alt: Closer part two
type: post
published: true
status: publish
categories:
- Nudes
---


text:
package com.liangmayong.base.basic.expands.webkit.abstracts;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebViewClient;

import com.liangmayong.base.basic.expands.webkit.callback.WebCallback;
import com.liangmayong.base.basic.expands.webkit.config.WebConfig;
import com.liangmayong.base.support.utils.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by LiangMaYong on 2017/2/18.
 */
public class AbstractWebKit extends android.webkit.WebView implements WebCallback.Callback {

    /**
     * Java call js function format with parameters
     */
    private static final String FUNC_FORMAT_WITH_PARAMETERS = "javascript:window.%s('%s')";
    /**
     * Java call js function format without parameters
     */
    private static final String FUNC_FORMAT = "javascript:window.%s()";
    // client
    private WebViewClient client;

    public AbstractWebKit(Context context) {
        super(context);
        initWebKit();
    }

    protected void initWebKit() {
        removeSearchBoxJavaBridgeInterface();
        setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                if (WebConfig.getDownloadListener() != null) {
                    WebConfig.getDownloadListener().onDownloadStart(url, userAgent, contentDisposition, mimetype, contentLength);
                } else {
                    Uri uri = Uri.parse(url);
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    getContext().startActivity(intent);
                }
            }
        });
        if (Build.VERSION.SDK_INT >= 9) {
            setOverScrollMode(View.OVER_SCROLL_NEVER);
        }
        getSettings().setJavaScriptEnabled(true);
        getSettings().setDomStorageEnabled(true);
        getSettings().setDatabaseEnabled(true);
        getSettings().setBuiltInZoomControls(false);
        getSettings().setAppCacheEnabled(true);
        if (Build.VERSION.SDK_INT >= 19) {
            getSettings().setLoadsImagesAutomatically(true);
        } else {
            getSettings().setLoadsImagesAutomatically(false);
        }
        getSettings().setDefaultTextEncodingName("UTF-8");
    }

    @Override
    public void setWebViewClient(WebViewClient client) {
        super.setWebViewClient(client);
        this.client = client;
    }

    public void onPageFinished() {
        if (client != null) {
            client.onPageFinished(this, getUrl());
        }
    }

    /**
     * injectionAssetsJS
     *
     * @param filename filename
     */
    public void injectionAssetsJS(String filename, String jsName) {
        try {
            InputStream in = getContext().getAssets().open(filename);
            byte buff[] = new byte[1024];
            int numread = 0;
            ByteArrayOutputStream fromFile = new ByteArrayOutputStream();
            do {
                numread = in.read(buff);
                if (numread <= 0) {
                    break;
                }
                fromFile.write(buff, 0, numread);
            } while (true);
            String wholeJS = fromFile.toString().replaceAll("&jsBridge&", jsName);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                evaluateJavascript(wholeJS, null);
            } else {
                loadUrl("javascript: " + wholeJS);
            }
            fromFile.close();
        } catch (IOException e) {
        }
    }

    /**
     * callFunction
     *
     * @param functionName functionName
     */
    public void call(String functionName) {
        call(functionName, null);
    }

    /**
     * callFunction
     *
     * @param functionName functionName
     * @param jsonString   jsonString
     */
    public void call(String functionName, String jsonString) {
        if (StringUtils.isEmpty(functionName)) {
            return;
        }
        if (StringUtils.isEmpty(jsonString)) {
            loadUrl(String.format(FUNC_FORMAT, functionName));
        } else {
            jsonString = jsonString.replaceAll("(\\\\)([^utrn])", "\\\\\\\\$1$2");
            jsonString = jsonString.replaceAll("(?<=[^\\\\])(\")", "\\\\\"");
            loadUrl(String.format(FUNC_FORMAT_WITH_PARAMETERS, functionName, jsonString));
        }
    }

    @Override
    public void onCall(String url, String functionName, String jsonString) {
        if (getUrl().equals(url)) {
            call(functionName, jsonString);
        }
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////
    ///////  Private
    ///////////////////////////////////////////////////////////////////////////////////////////////

    @SuppressLint("NewApi")
    private void removeSearchBoxJavaBridgeInterface() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB && !(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)) {
            removeJavascriptInterface("searchBoxJavaBridge_");
        }
    }
}


text:
package org.apache.causeway.persistence.jdo.metamodel.facets.object.persistencecapable;

import java.util.Optional;
import java.util.function.BiConsumer;

import javax.jdo.annotations.EmbeddedOnly;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.persistence.Entity;
import javax.persistence.Table;

import org.apache.causeway.commons.internal.base._Strings;
import org.apache.causeway.core.metamodel.facetapi.FacetAbstract;
import org.apache.causeway.core.metamodel.facetapi.FacetHolder;
import org.apache.causeway.persistence.jdo.provider.metamodel.facets.object.persistencecapable.JdoPersistenceCapableFacet;

import lombok.val;

public class JdoPersistenceCapableFacetFromAnnotation
extends FacetAbstract
implements JdoPersistenceCapableFacet {

    private final String schema;
    private final String table;
    private final IdentityType identityType;

    public static Optional<JdoPersistenceCapableFacet> createUsingJdo(
            final Optional<PersistenceCapable> persistenceCapableIfAny,
            final Optional<EmbeddedOnly> embeddedOnlyIfAny,
            final Class<?> cls,
            final FacetHolder facetHolder) {

        if(!persistenceCapableIfAny.isPresent()) {
            return Optional.empty();
        }

        val persistenceCapable = persistenceCapableIfAny.get();

        // Whether objects of this type can only be embedded,
        // hence have no ID that binds them to the persistence layer
        final boolean isEmbeddedOnly = Boolean.valueOf(persistenceCapable.embeddedOnly())
                || embeddedOnlyIfAny.isPresent();

        if(isEmbeddedOnly) {
            return Optional.empty();
        }

        val schema = _Strings.emptyToNull(persistenceCapable.schema());

        val table = _Strings.isNotEmpty(persistenceCapable.table())
            ? persistenceCapable.table()
            : cls.getSimpleName();

        val identityType = persistenceCapable.identityType();

        return Optional.of(new JdoPersistenceCapableFacetFromAnnotation(
                schema,
                table,
                identityType,
                facetHolder));

    }

    public static Optional<JdoPersistenceCapableFacet> createUsingJpa(
            final Optional<Entity> entityIfAny,
            final Optional<Table> tableIfAny,
            final Class<?> cls,
            final FacetHolder facetHolder) {

        if(!entityIfAny.isPresent()) {
            return Optional.empty();
        }

        //val entity = entityIfAny.get(); // optionally has a name, we don't use yet

        val table = tableIfAny
            .map(tableAnnot->tableAnnot.name())
            .map(_Strings::emptyToNull)
            .orElseGet(cls::getSimpleName);

        val schema = tableIfAny
                .map(tableAnnot->tableAnnot.schema())
                .map(_Strings::emptyToNull)
                .orElseGet(cls::getSimpleName);

        val identityType = IdentityType.UNSPECIFIED;

        return Optional.of(new JdoPersistenceCapableFacetFromAnnotation(
                schema,
                table,
                identityType,
                facetHolder));
    }

    private JdoPersistenceCapableFacetFromAnnotation(
            final String schemaName,
            final String tableOrTypeName,
            final IdentityType identityType,
            final FacetHolder holder) {

        super(JdoPersistenceCapableFacet.class, holder);
        this.schema = schemaName;
        this.table = tableOrTypeName;
        this.identityType = identityType;
    }

    @Override
    public IdentityType getIdentityType() {
        return identityType;
    }

    @Override
    public String getSchema() {
        return schema;
    }

    @Override
    public String getTable() {
        return table;
    }

    @Override
    public void visitAttributes(final BiConsumer<String, Object> visitor) {
        super.visitAttributes(visitor);
        visitor.accept("schema", schema);
        visitor.accept("table", table);
        visitor.accept("identityType", identityType);
    }

}