text:
package com.vaadin.tests.urifragments;

import java.util.Iterator;

import com.vaadin.server.Page;
import com.vaadin.server.Page.UriFragmentChangedEvent;
import com.vaadin.server.Page.UriFragmentChangedListener;
import com.vaadin.server.VaadinRequest;
import com.vaadin.tests.components.AbstractTestUIWithLog;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Component;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;

@SuppressWarnings("serial")
public class FragmentHandlingAndAsynchUIUpdate extends AbstractTestUIWithLog {
    protected static final int START_FRAG_ID = 1000;
    protected static final String FRAG_NAME_TPL = "FRAG%s";
    protected static final String BUTTON_ID = "SetNextFragmentButton";

    private int fragmentId = START_FRAG_ID;

    @Override
    protected void setup(VaadinRequest request) {
        Button button = new Button(
                "Click Me 10 times, wait for ui to settle (10 seconds) then click the back button 10 times.");

        button.setId(BUTTON_ID);

        button.addClickListener(new Button.ClickListener() {
            @Override
            public void buttonClick(ClickEvent event) {
                Label c = new Label("Thank you for clicking");
                c.setId(String.valueOf(fragmentId));
                getLayout().addComponent(c);

                log(String.format("Button was clicked for fragmentId %s",
                        fragmentId));
                Page.getCurrent().setUriFragment(
                        String.format(FRAG_NAME_TPL, fragmentId++));
            }
        });

        getLayout().addComponent(button);

        Page.getCurrent().addUriFragmentChangedListener(
                createUriFragmentChangedListener());
    }

    private UriFragmentChangedListener createUriFragmentChangedListener() {
        return new UriFragmentChangedListener() {

            @Override
            public void uriFragmentChanged(
                    final UriFragmentChangedEvent event) {

                log(String.format("uriFragmentChanged %s",
                        event.getUriFragment()));

                if (!event.getUriFragment().startsWith("FRAG")) {
                    return;
                }

                Iterator<Component> it = getLayout().iterator();
                final String frag = event.getUriFragment().substring(4);

                Component fragComp = null;
                while (it.hasNext()) {
                    Component comp = it.next();
                    if (comp.getId() != null && comp instanceof Label
                            && comp.getId().equals(frag)) {
                        fragComp = comp;
                        break;
                    }
                }

                if (fragComp == null) {
                    return;
                }
                final Label fragLabel = (Label) fragComp;

                createThread(frag, fragLabel).start();

                fragLabel.setCaption(
                        String.format("Thread running for %s!", frag));
                UI.getCurrent().setPollInterval(1000);
            }
        };
    }

    private Thread createThread(final String frag, final Label fragLabel) {
        return new Thread() {

            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                UI.getCurrent().access(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        log(String.format(
                                "setCaption in synch mode for fragment %s",
                                frag));
                        java.util.Random rand = new java.util.Random();
                        fragLabel.setCaption(
                                String.format("Thread finished on %s (%s)",
                                        frag, rand.nextInt()));
                    }
                });

            };
        };
    }

    @Override
    protected String getTestDescription() {
        return "Back and Forward buttons in browser should work correctly during asynchronous ui update";
    }

    @Override
    protected Integer getTicketNumber() {
        return 13997;
    }
}


text:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="16sp"
    android:textColor="#3CA7F0"
    android:background="#16D7D7D7"
    android:paddingLeft="40dp"/>

redpajama_set_name: RedPajamaGithub


text:
/* ccapi/common/win/win-utils.c */
/*
 * Copyright 2008 Massachusetts Institute of Technology.
 * All Rights Reserved.
 *
 * Export of this software from the United States of America may
 * require a specific license from the United States Government.
 * It is the responsibility of any person or organization contemplating
 * export to obtain such a license before exporting.
 *
 * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
 * distribute this software and its documentation for any purpose and
 * without fee is hereby granted, provided that the above copyright
 * notice appear in all copies and that both that copyright notice and
 * this permission notice appear in supporting documentation, and that
 * the name of M.I.T. not be used in advertising or publicity pertaining
 * to distribution of the software without specific, written prior
 * permission.  Furthermore if you modify this software you must label
 * your software as modified software and not distribute it in such a
 * fashion that it might be confused with the original M.I.T. software.
 * M.I.T. makes no representations about the suitability of
 * this software for any purpose.  It is provided "as is" without express
 * or implied warranty.
 */

#include <stdio.h>
#include <string.h>
#include <time.h>
#include "windows.h"
#include <stdlib.h>
#include <malloc.h>

#include "win-utils.h"
#include "cci_debugging.h"

#pragma warning (disable : 4996)

#define UUID_SIZE   128

char*           clientPrefix        = "CCAPI_CLIENT_";
char*           serverPrefix        = "CCS_LISTEN_";
unsigned char*  pszProtocolSequence = "ncalrpc";

#define         MAX_TIMESTAMP   40
char            _ts[MAX_TIMESTAMP];

char* clientEndpoint(const char* UUID) {
    char* _clientEndpoint   = (char*)malloc(strlen(UUID) + strlen(clientPrefix) + 2);
    strcpy(_clientEndpoint, clientPrefix);
    strncat(_clientEndpoint, UUID, UUID_SIZE);
//    cci_debug_printf("%s returning %s", __FUNCTION__, _clientEndpoint);
    return _clientEndpoint;
    }

char* serverEndpoint(const char* user) {
    char* _serverEndpoint   = (char*)malloc(strlen(user) + strlen(serverPrefix) + 2);
    strcpy(_serverEndpoint, serverPrefix);
    strncat(_serverEndpoint, user, UUID_SIZE);
    return _serverEndpoint;
    }

char* timestamp() {
    SYSTEMTIME  _stime;
    GetSystemTime(&_stime);
    GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, &_stime, "HH:mm:ss", _ts, sizeof(_ts)-1);
    return _ts;
    }


text:
import React from 'react';
import { connect } from 'react-redux';

import { updatePage } from '../../../actions/pagination';

const PaginationPrev = props => (
	<button
		type="button"
		onClick={props.updatePage.bind(this, props.activePage - 1)}
	>
		<i className="mdi mdi-chevron-left" />
		<span>
			Previous
		</span>
	</button>
);

const mapStateToProps = state => ({
	activePage: state.pagination.page,
});

const mapDispatchToProps = dispatch => ({
	updatePage: (page) => {
		dispatch(updatePage(page));
	},
});

export default connect(
	mapStateToProps,
	mapDispatchToProps,
)(PaginationPrev);


text:
<?php

defined('JPATH_PLATFORM') or die();

/**
 * Class to encapsulate a feed for the Joomla Platform.
 *
 * @property  JFeedPerson  $author         Person responsible for feed content.
 * @property  array        $categories     Categories to which the feed belongs.
 * @property  array        $contributors   People who contributed to the feed content.
 * @property  string       $copyright      Information about rights, e.g. copyrights, held in and over the feed.
 * @property  string       $description    A phrase or sentence describing the feed.
 * @property  string       $generator      A string indicating the program used to generate the feed.
 * @property  string       $image          Specifies a GIF, JPEG or PNG image that should be displayed with the feed.
 * @property  JDate        $publishedDate  The publication date for the feed content.
 * @property  string       $title          A human readable title for the feed.
 * @property  JDate        $updatedDate    The last time the content of the feed changed.
 * @property  string       $uri            Universal, permanent identifier for the feed.
 *
 * @package     Joomla.Platform
 * @subpackage  Feed
 * @since       12.3
 */
class JFeed implements ArrayAccess
{
	/**
	 * @var    array  The entry properties.
	 * @since  12.3
	 */
	protected $properties = array(
		'uri' => '',
		'title' => '',
		'updatedDate' => '',
		'description' => '',
		'categories' => array(),
		'contributors' => array()
	);

	/**
	 * @var    array  The list of feed entry objects.
	 * @since  12.3
	 */
	protected $entries = array();

	/**
	 * Magic method to return values for feed properties.
	 *
	 * @param   string  $name  The name of the property.
	 *
	 * @return  mixed
	 *
	 * @since   12.3
	 */
	public function __get($name)
	{
		return isset($this->properties[$name]) ? $this->properties[$name] : null;
	}

	/**
	 * Magic method to set values for feed properties.
	 *
	 * @param   string  $name   The name of the property.
	 * @param   mixed   $value  The value to set for the property.
	 *
	 * @return  void
	 *
	 * @since   12.3
	 */
	public function __set($name, $value)
	{
		// Ensure that setting a date always sets a JDate instance.
		if ((($name == 'updatedDate') || ($name == 'publishedDate')) && !($value instanceof JDate))
		{
			$value = new JDate($value);
		}

		// Validate that any authors that are set are instances of JFeedPerson or null.
		if (($name == 'author') && (!($value instanceof JFeedPerson) || ($value === null)))
		{
			throw new InvalidArgumentException('JFeed "author" must be of type JFeedPerson. ' . gettype($value) . 'given.');
		}

		// Disallow setting categories or contributors directly.
		if (($name == 'categories') || ($name == 'contributors'))
		{
			throw new InvalidArgumentException('Cannot directly set JFeed property "' . $name . '".');
		}

		$this->properties[$name] = $value;
	}

	/**
	 * Method to add a category to the feed object.
	 *
	 * @param   string  $name  The name of the category to add.
	 * @param   string  $uri   The optional URI for the category to add.
	 *
	 * @return  JFeed
	 *
	 * @since   12.3
	 */
	public function addCategory($name, $uri = '')
	{
		$this->properties['categories'][$name] = $uri;

		return $this;
	}

	/**
	 * Method to add a contributor to the feed object.
	 *
	 * @param   string  $name   The full name of the person to add.
	 * @param   string  $email  The email address of the person to add.
	 * @param   string  $uri    The optional URI for the person to add.
	 * @param   string  $type   The optional type of person to add.
	 *
	 * @return  JFeed
	 *
	 * @since   12.3
	 */
	public function addContributor($name, $email, $uri = null, $type = null)
	{
		$contributor = new JFeedPerson($name, $email, $uri, $type);

		// If the new contributor already exists then there is nothing to do, so just return.
		foreach ($this->properties['contributors'] as $c)
		{
			if ($c == $contributor)
			{
				return $this;
			}
		}

		// Add the new contributor.
		$this->properties['contributors'][] = $contributor;

		return $this;
	}

	/**
	 * Method to add an entry to the feed object.
	 *
	 * @param   JFeedEntry  $entry  The entry object to add.
	 *
	 * @return  JFeed
	 *
	 * @since   12.3
	 */
	public function addEntry(JFeedEntry $entry)
	{
		// If the new entry already exists then there is nothing to do, so just return.
		foreach ($this->entries as $e)
		{
			if ($e == $entry)
			{
				return $this;
			}
		}

		// Add the new entry.
		$this->entries[] = $entry;

		return $this;
	}

	/**
	 * Whether or not an offset exists.  This method is executed when using isset() or empty() on
	 * objects implementing ArrayAccess.
	 *
	 * @param   mixed  $offset  An offset to check for.
	 *
	 * @return  boolean
	 *
	 * @see     ArrayAccess::offsetExists()
	 * @since   12.3
	 */
	public function offsetExists($offset)
	{
		return isset($this->entries[$offset]);
	}

	/**
	 * Returns the value at specified offset.
	 *
	 * @param   mixed  $offset  The offset to retrieve.
	 *
	 * @return  mixed  The value at the offset.
	 *
	 * @see     ArrayAccess::offsetGet()
	 * @since   12.3
	 */
	public function offsetGet($offset)
	{
		return $this->entries[$offset];
	}

	/**
	 * Assigns a value to the specified offset.
	 *
	 * @param   mixed       $offset  The offset to assign the value to.
	 * @param   JFeedEntry  $value   The JFeedEntry to set.
	 *
	 * @return  boolean
	 *
	 * @see     ArrayAccess::offsetSet()
	 * @since   12.3
	 * @throws  InvalidArgumentException
	 */
	public function offsetSet($offset, $value)
	{
		if (!($value instanceof JFeedEntry))
		{
			throw new InvalidArgumentException('Cannot set value of type "' . gettype($value) . '".');
		}

		$this->entries[$offset] = $value;

		return true;
	}

	/**
	 * Unsets an offset.
	 *
	 * @param   mixed  $offset  The offset to unset.
	 *
	 * @return  void
	 *
	 * @see     ArrayAccess::offsetUnset()
	 * @since   12.3
	 */
	public function offsetUnset($offset)
	{
		unset($this->entries[$offset]);
	}

	/**
	 * Method to remove a category from the feed object.
	 *
	 * @param   string  $name  The name of the category to remove.
	 *
	 * @return  JFeed
	 *
	 * @since   12.3
	 */
	public function removeCategory($name)
	{
		unset($this->properties['categories'][$name]);

		return $this;
	}

	/**
	 * Method to remove a contributor from the feed object.
	 *
	 * @param   JFeedPerson  $contributor  The person object to remove.
	 *
	 * @return  JFeed
	 *
	 * @since   12.3
	 */
	public function removeContributor(JFeedPerson $contributor)
	{
		// If the contributor exists remove it.
		foreach ($this->properties['contributors'] as $k => $c)
		{
			if ($c == $contributor)
			{
				unset($this->properties['contributors'][$k]);
				$this->properties['contributors'] = array_values($this->properties['contributors']);

				return $this;
			}
		}

		return $this;
	}

	/**
	 * Method to remove an entry from the feed object.
	 *
	 * @param   JFeedEntry  $entry  The entry object to remove.
	 *
	 * @return  JFeed
	 *
	 * @since   12.3
	 */
	public function removeEntry(JFeedEntry $entry)
	{
		// If the entry exists remove it.
		foreach ($this->entries as $k => $e)
		{
			if ($e == $entry)
			{
				unset($this->entries[$k]);
				$this->entries = array_values($this->entries);

				return $this;
			}
		}

		return $this;
	}

	/**
	 * Shortcut method to set the author for the feed object.
	 *
	 * @param   string  $name   The full name of the person to set.
	 * @param   string  $email  The email address of the person to set.
	 * @param   string  $uri    The optional URI for the person to set.
	 * @param   string  $type   The optional type of person to set.
	 *
	 * @return  JFeed
	 *
	 * @since   12.3
	 */
	public function setAuthor($name, $email, $uri = null, $type = null)
	{
		$author = new JFeedPerson($name, $email, $uri, $type);

		$this->properties['author'] = $author;

		return $this;
	}
}


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

/**
 * @constructor
 * @extends {WebInspector.VBox}
 */
WebInspector.DeviceModeView = function()
{
    WebInspector.VBox.call(this, true);
    this.setMinimumSize(150, 150);
    this.element.classList.add("device-mode-view");
    this.registerRequiredCSS("emulation/deviceModeView.css");
    WebInspector.Tooltip.addNativeOverrideContainer(this.contentElement);

    this._model = new WebInspector.DeviceModeModel(this._updateUI.bind(this));
    this._mediaInspector = new WebInspector.MediaQueryInspector(() => this._model.appliedDeviceSize().width, this._model.setWidth.bind(this._model));
    // TODO(dgozman): remove CountUpdated event.
    this._showMediaInspectorSetting = WebInspector.settings.createSetting("showMediaQueryInspector", false);
    this._showMediaInspectorSetting.addChangeListener(this._updateUI, this);
    this._showRulersSetting = WebInspector.settings.createSetting("emulation.showRulers", false);
    this._showRulersSetting.addChangeListener(this._updateUI, this);

    this._topRuler = new WebInspector.DeviceModeView.Ruler(true, this._model.setWidthAndScaleToFit.bind(this._model));
    this._topRuler.element.classList.add("device-mode-ruler-top");
    this._leftRuler = new WebInspector.DeviceModeView.Ruler(false, this._model.setHeightAndScaleToFit.bind(this._model));
    this._leftRuler.element.classList.add("device-mode-ruler-left");
    this._createUI();
    WebInspector.zoomManager.addEventListener(WebInspector.ZoomManager.Events.ZoomChanged, this._zoomChanged, this);
};

WebInspector.DeviceModeView.prototype = {
    _createUI: function()
    {
        this._toolbar = new WebInspector.DeviceModeView.Toolbar(this._model, this._showMediaInspectorSetting, this._showRulersSetting);
        this.contentElement.appendChild(this._toolbar.element());

        this._contentClip = this.contentElement.createChild("div", "device-mode-content-clip vbox");
        this._responsivePresetsContainer = this._contentClip.createChild("div", "device-mode-presets-container");
        this._populatePresetsContainer();
        this._mediaInspectorContainer = this._contentClip.createChild("div", "device-mode-media-container");
        this._contentArea = this._contentClip.createChild("div", "device-mode-content-area");

        this._screenArea = this._contentArea.createChild("div", "device-mode-screen-area");
        this._screenImage = this._screenArea.createChild("img", "device-mode-screen-image hidden");
        this._screenImage.addEventListener("load", this._onScreenImageLoaded.bind(this, true), false);
        this._screenImage.addEventListener("error", this._onScreenImageLoaded.bind(this, false), false);

        this._cornerResizerElement = this._screenArea.createChild("div", "device-mode-resizer device-mode-corner-resizer");
        this._cornerResizerElement.createChild("div", "");
        this._createResizer(this._cornerResizerElement, true, true);

        this._widthResizerElement = this._screenArea.createChild("div", "device-mode-resizer device-mode-width-resizer");
        this._widthResizerElement.createChild("div", "");
        this._createResizer(this._widthResizerElement, true, false);

        this._heightResizerElement = this._screenArea.createChild("div", "device-mode-resizer device-mode-height-resizer");
        this._heightResizerElement.createChild("div", "");
        this._createResizer(this._heightResizerElement, false, true);
        this._heightResizerElement.addEventListener("dblclick", this._model.setHeight.bind(this._model, 0), false);
        this._heightResizerElement.title = WebInspector.UIString("Double-click for full height");

        this._pageArea = this._screenArea.createChild("div", "device-mode-page-area");
        this._pageArea.createChild("content");
    },

    _populatePresetsContainer: function()
    {
        var sizes = [320, 375, 425, 768, 1024, 1440, 2560];
        var titles = [WebInspector.UIString("Mobile S"),
                      WebInspector.UIString("Mobile M"),
                      WebInspector.UIString("Mobile L"),
                      WebInspector.UIString("Tablet"),
                      WebInspector.UIString("Laptop"),
                      WebInspector.UIString("Laptop L"),
                      WebInspector.UIString("4K")]
        this._presetBlocks = [];
        var inner = this._responsivePresetsContainer.createChild("div", "device-mode-presets-container-inner")
        for (var i = sizes.length - 1; i >= 0; --i) {
            var outer = inner.createChild("div", "fill device-mode-preset-bar-outer");
            var block = outer.createChild("div", "device-mode-preset-bar");
            block.createChild("span").textContent = titles[i] + " \u2013 " + sizes[i] + "px";
            block.addEventListener("click", applySize.bind(this, sizes[i]), false);
            block.__width = sizes[i];
            this._presetBlocks.push(block);
        }

        /**
         * @param {number} width
         * @param {!Event} e
         * @this {WebInspector.DeviceModeView}
         */
        function applySize(width, e)
        {
            this._model.emulate(WebInspector.DeviceModeModel.Type.Responsive, null, null);
            this._model.setSizeAndScaleToFit(width, 0);
            e.consume();
        }
    },

    toggleDeviceMode: function()
    {
        this._toolbar.toggleDeviceMode();
    },

    /**
     * @param {!Element} element
     * @param {boolean} width
     * @param {boolean} height
     * @return {!WebInspector.ResizerWidget}
     */
    _createResizer: function(element, width, height)
    {
        var resizer = new WebInspector.ResizerWidget();
        resizer.addElement(element);
        resizer.setCursor(width && height ? "nwse-resize" : (width ? "ew-resize" : "ns-resize"));
        resizer.addEventListener(WebInspector.ResizerWidget.Events.ResizeStart, this._onResizeStart, this);
        resizer.addEventListener(WebInspector.ResizerWidget.Events.ResizeUpdate, this._onResizeUpdate.bind(this, width, height));
        resizer.addEventListener(WebInspector.ResizerWidget.Events.ResizeEnd, this._onResizeEnd, this);
        return resizer;
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _onResizeStart: function(event)
    {
        this._slowPositionStart = null;
        /** @type {!Size} */
        this._resizeStart = this._model.screenRect().size();
    },

    /**
     * @param {boolean} width
     * @param {boolean} height
     * @param {!WebInspector.Event} event
     */
    _onResizeUpdate: function(width, height, event)
    {
        if (event.data.shiftKey !== !!this._slowPositionStart)
            this._slowPositionStart = event.data.shiftKey ? {x: event.data.currentX, y: event.data.currentY} : null;

        var cssOffsetX = event.data.currentX - event.data.startX;
        var cssOffsetY = event.data.currentY - event.data.startY;
        if (this._slowPositionStart) {
            cssOffsetX = (event.data.currentX - this._slowPositionStart.x) / 10 + this._slowPositionStart.x - event.data.startX;
            cssOffsetY = (event.data.currentY - this._slowPositionStart.y) / 10 + this._slowPositionStart.y - event.data.startY;
        }

        if (width) {
            var dipOffsetX = cssOffsetX * WebInspector.zoomManager.zoomFactor();
            var newWidth = this._resizeStart.width + dipOffsetX * 2;
            newWidth = Math.round(newWidth / this._model.scale());
            if (newWidth >= WebInspector.DeviceModeModel.MinDeviceSize && newWidth <= WebInspector.DeviceModeModel.MaxDeviceSize)
                this._model.setWidth(newWidth);
        }

        if (height) {
            var dipOffsetY = cssOffsetY * WebInspector.zoomManager.zoomFactor();
            var newHeight = this._resizeStart.height + dipOffsetY;
            newHeight = Math.round(newHeight / this._model.scale());
            if (newHeight >= WebInspector.DeviceModeModel.MinDeviceSize && newHeight <= WebInspector.DeviceModeModel.MaxDeviceSize)
                this._model.setHeight(newHeight);
        }
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _onResizeEnd: function(event)
    {
        delete this._resizeStart;
        WebInspector.userMetrics.actionTaken(WebInspector.UserMetrics.Action.ResizedViewInResponsiveMode);
    },

    _updateUI: function()
    {
        if (!this.isShowing())
            return;

        var zoomFactor = WebInspector.zoomManager.zoomFactor();
        var callDoResize = false;
        var showRulers = this._showRulersSetting.get() && this._model.type() !== WebInspector.DeviceModeModel.Type.None;
        var contentAreaResized = false;
        var updateRulers = false;

        var cssScreenRect = this._model.screenRect().scale(1 / zoomFactor);
        if (!cssScreenRect.isEqual(this._cachedCssScreenRect)) {
            this._screenArea.style.left = cssScreenRect.left + "px";
            this._screenArea.style.top = cssScreenRect.top + "px";
            this._screenArea.style.width = cssScreenRect.width + "px";
            this._screenArea.style.height = cssScreenRect.height + "px";
            this._leftRuler.element.style.left = cssScreenRect.left + "px";
            updateRulers = true;
            callDoResize = true;
            this._cachedCssScreenRect = cssScreenRect;
        }

        var cssVisiblePageRect = this._model.visiblePageRect().scale(1 / zoomFactor);
        if (!cssVisiblePageRect.isEqual(this._cachedCssVisiblePageRect)) {
            this._pageArea.style.left = cssVisiblePageRect.left + "px";
            this._pageArea.style.top = cssVisiblePageRect.top + "px";
            this._pageArea.style.width = cssVisiblePageRect.width + "px";
            this._pageArea.style.height = cssVisiblePageRect.height + "px";
            callDoResize = true;
            this._cachedCssVisiblePageRect = cssVisiblePageRect;
        }

        var resizable = this._model.type() === WebInspector.DeviceModeModel.Type.Responsive;
        if (resizable !== this._cachedResizable) {
            this._widthResizerElement.classList.toggle("hidden", !resizable);
            this._heightResizerElement.classList.toggle("hidden", !resizable);
            this._cornerResizerElement.classList.toggle("hidden", !resizable);
            this._cachedResizable = resizable;
        }

        var mediaInspectorVisible = this._showMediaInspectorSetting.get() && this._model.type() !== WebInspector.DeviceModeModel.Type.None;
        if (mediaInspectorVisible !== this._cachedMediaInspectorVisible) {
            if (mediaInspectorVisible)
                this._mediaInspector.show(this._mediaInspectorContainer);
            else
                this._mediaInspector.detach();
            contentAreaResized = true;
            callDoResize = true;
            this._cachedMediaInspectorVisible = mediaInspectorVisible;
        }

        if (showRulers !== this._cachedShowRulers) {
            this._contentClip.classList.toggle("device-mode-rulers-visible", showRulers);
            if (showRulers) {
                this._topRuler.show(this._contentClip, this._contentArea);
                this._leftRuler.show(this._contentArea);
            } else {
                this._topRuler.detach();
                this._leftRuler.detach();
            }
            contentAreaResized = true;
            callDoResize = true;
            this._cachedShowRulers = showRulers;
        }

        if (this._model.scale() !== this._cachedScale) {
            updateRulers = true;
            callDoResize = true;
            for (var block of this._presetBlocks)
                block.style.width = block.__width * this._model.scale() + "px";
            this._cachedScale = this._model.scale();
        }

        this._toolbar.update();
        this._loadScreenImage(this._model.screenImage());
        this._mediaInspector.setAxisTransform(-cssScreenRect.left * zoomFactor / this._model.scale(), this._model.scale());
        if (callDoResize)
            this.doResize();
        if (updateRulers) {
            this._topRuler.render(this._cachedCssScreenRect ? this._cachedCssScreenRect.left : 0, this._model.scale());
            this._leftRuler.render(0, this._model.scale());
        }
        if (contentAreaResized)
            this._contentAreaResized();
    },

    /**
     * @param {string} srcset
     */
    _loadScreenImage: function(srcset)
    {
        if (this._screenImage.getAttribute("srcset") === srcset)
            return;
        this._screenImage.setAttribute("srcset", srcset);
        if (!srcset)
            this._screenImage.classList.toggle("hidden", true);
    },

    /**
     * @param {boolean} success
     */
    _onScreenImageLoaded: function(success)
    {
        this._screenImage.classList.toggle("hidden", !success);
    },

    _contentAreaResized: function()
    {
        var zoomFactor = WebInspector.zoomManager.zoomFactor();
        var rect = this._contentArea.getBoundingClientRect();
        var availableSize = new Size(Math.max(rect.width * zoomFactor, 1), Math.max(rect.height * zoomFactor, 1));
        var preferredSize = new Size(Math.max((rect.width - 2 * this._handleWidth) * zoomFactor, 1), Math.max((rect.height - this._handleHeight) * zoomFactor, 1));
        this._model.setAvailableSize(availableSize, preferredSize);
    },

    _measureHandles: function()
    {
        var hidden = this._widthResizerElement.classList.contains("hidden");
        this._widthResizerElement.classList.toggle("hidden", false);
        this._heightResizerElement.classList.toggle("hidden", false);
        this._handleWidth = this._widthResizerElement.offsetWidth;
        this._handleHeight = this._heightResizerElement.offsetHeight;
        this._widthResizerElement.classList.toggle("hidden", hidden);
        this._heightResizerElement.classList.toggle("hidden", hidden);
    },

    _zoomChanged: function()
    {
        delete this._handleWidth;
        delete this._handleHeight;
        if (this.isShowing()) {
            this._measureHandles();
            this._contentAreaResized();
        }
    },

    /**
     * @override
     */
    onResize: function()
    {
        if (this.isShowing())
            this._contentAreaResized();
    },

    /**
     * @override
     */
    wasShown: function()
    {
        this._measureHandles();
        this._mediaInspector.setEnabled(true);
        this._toolbar.restore();
    },

    /**
     * @override
     */
    willHide: function()
    {
        this._model.emulate(WebInspector.DeviceModeModel.Type.None, null, null);
        this._mediaInspector.setEnabled(false);
    },

    __proto__: WebInspector.VBox.prototype
}

/**
 * @param {!WebInspector.DeviceModeModel} model
 * @param {!WebInspector.Setting} showMediaInspectorSetting
 * @param {!WebInspector.Setting} showRulersSetting
 * @constructor
 */
WebInspector.DeviceModeView.Toolbar = function(model, showMediaInspectorSetting, showRulersSetting)
{
    this._model = model;
    this._showMediaInspectorSetting = showMediaInspectorSetting;
    this._showRulersSetting = showRulersSetting;
    /** @type {!Map<!WebInspector.EmulatedDevice, !WebInspector.EmulatedDevice.Mode>} */
    this._lastMode = new Map();

    this._element = createElementWithClass("div", "device-mode-toolbar");

    var leftContainer = this._element.createChild("div", "device-mode-toolbar-spacer");
    leftContainer.createChild("div", "device-mode-toolbar-spacer");
    var leftToolbar = new WebInspector.Toolbar("", leftContainer);
    leftToolbar.makeWrappable();
    this._fillLeftToolbar(leftToolbar);

    var mainToolbar = new WebInspector.Toolbar("", this._element);
    mainToolbar.makeWrappable();
    this._fillMainToolbar(mainToolbar);

    var rightContainer = this._element.createChild("div", "device-mode-toolbar-spacer");
    var rightToolbar = new WebInspector.Toolbar("device-mode-toolbar-fixed-size", rightContainer);
    rightToolbar.makeWrappable();
    this._fillRightToolbar(rightToolbar);
    var modeToolbar = new WebInspector.Toolbar("device-mode-toolbar-fixed-size", rightContainer);
    modeToolbar.makeWrappable();
    this._fillModeToolbar(modeToolbar);
    rightContainer.createChild("div", "device-mode-toolbar-spacer");
    var optionsToolbar = new WebInspector.Toolbar("", rightContainer);
    optionsToolbar.makeWrappable(true);
    this._fillOptionsToolbar(optionsToolbar);

    WebInspector.emulatedDevicesList.addEventListener(WebInspector.EmulatedDevicesList.Events.CustomDevicesUpdated, this._deviceListChanged, this);
    WebInspector.emulatedDevicesList.addEventListener(WebInspector.EmulatedDevicesList.Events.StandardDevicesUpdated, this._deviceListChanged, this);

    this._persistenceSetting = WebInspector.settings.createSetting("emulation.deviceModeValue", {device: "", orientation: "", mode: ""});
}

WebInspector.DeviceModeView.Toolbar.prototype = {
    /**
     * @param {!WebInspector.Toolbar} toolbar
     */
    _fillLeftToolbar: function(toolbar)
    {
        toolbar.appendToolbarItem(this._wrapToolbarItem(createElementWithClass("div", "device-mode-empty-toolbar-element")));
        this._deviceSelectItem = new WebInspector.ToolbarMenuButton(this._appendDeviceMenuItems.bind(this));
        this._deviceSelectItem.setGlyph("");
        this._deviceSelectItem.setBold(false);
        this._deviceSelectItem.turnIntoSelect(95);
        toolbar.appendToolbarItem(this._deviceSelectItem);
    },

    /**
     * @param {!WebInspector.Toolbar} toolbar
     */
    _fillMainToolbar: function(toolbar)
    {
        var widthInput = createElementWithClass("input", "device-mode-size-input");
        widthInput.maxLength = 4;
        widthInput.type = "text";
        widthInput.title = WebInspector.UIString("Width");
        this._updateWidthInput = this._bindInput(widthInput, this._model.setWidthAndScaleToFit.bind(this._model), WebInspector.DeviceModeModel.deviceSizeValidator);
        this._widthInput = widthInput;
        this._widthItem = this._wrapToolbarItem(widthInput);
        toolbar.appendToolbarItem(this._widthItem);

        var xElement = createElementWithClass("div", "device-mode-x");
        xElement.textContent = "\u00D7";
        this._xItem = this._wrapToolbarItem(xElement);
        toolbar.appendToolbarItem(this._xItem);

        var heightInput = createElementWithClass("input", "device-mode-size-input");
        heightInput.maxLength = 4;
        heightInput.type = "text";
        heightInput.title = WebInspector.UIString("Height (leave empty for full)");
        this._updateHeightInput = this._bindInput(heightInput, this._model.setHeightAndScaleToFit.bind(this._model), validateHeight);
        this._heightInput = heightInput;
        this._heightItem = this._wrapToolbarItem(heightInput);
        toolbar.appendToolbarItem(this._heightItem);

        /**
         * @param {string} value
         * @return {string}
         */
        function validateHeight(value)
        {
            return !value ? "" : WebInspector.DeviceModeModel.deviceSizeValidator(value);
        }
    },

    /**
     * @param {!WebInspector.Toolbar} toolbar
     */
    _fillRightToolbar: function(toolbar)
    {
        toolbar.appendToolbarItem(this._wrapToolbarItem(createElementWithClass("div", "device-mode-empty-toolbar-element")));
        this._scaleItem = new WebInspector.ToolbarMenuButton(this._appendScaleMenuItems.bind(this));
        this._scaleItem.setTitle(WebInspector.UIString("Zoom"));
        this._scaleItem.setGlyph("");
        this._scaleItem.setBold(false);
        this._scaleItem.turnIntoSelect();
        toolbar.appendToolbarItem(this._scaleItem);
    },

    /**
     * @param {!WebInspector.Toolbar} toolbar
     */
    _fillModeToolbar: function(toolbar)
    {
        toolbar.appendToolbarItem(this._wrapToolbarItem(createElementWithClass("div", "device-mode-empty-toolbar-element")));
        this._modeButton = new WebInspector.ToolbarButton("", "rotate-screen-toolbar-item");
        this._modeButton.addEventListener("click", this._modeMenuClicked, this);
        toolbar.appendToolbarItem(this._modeButton);
    },

    /**
     * @param {!WebInspector.Toolbar} toolbar
     */
    _fillOptionsToolbar: function(toolbar)
    {
        this._uaItem = new WebInspector.ToolbarLabel();
        this._uaItem.setVisible(false);
        this._uaItem.setTitle(WebInspector.UIString("User agent type"));
        toolbar.appendToolbarItem(this._uaItem);

        this._deviceScaleItem = new WebInspector.ToolbarLabel();
        this._deviceScaleItem.setVisible(false);
        this._deviceScaleItem.setTitle(WebInspector.UIString("Device pixel ratio"));
        toolbar.appendToolbarItem(this._deviceScaleItem);

        var moreOptionsButton = new WebInspector.ToolbarMenuButton(this._appendOptionsMenuItems.bind(this));
        moreOptionsButton.setTitle(WebInspector.UIString("More options"));
        toolbar.appendToolbarItem(moreOptionsButton);

        toolbar.appendToolbarItem(this._wrapToolbarItem(createElementWithClass("div", "device-mode-empty-toolbar-element")));
    },

    /**
     * @param {!Element} input
     * @param {function(number)} apply
     * @param {function(string):?string} validate
     * @return {function(number)}
     */
    _bindInput: function(input, apply, validate)
    {
        input.addEventListener("change", onChange, false);
        input.addEventListener("input", onInput, false);
        input.addEventListener("keydown", onKeyDown, false);
        input.addEventListener("focus", input.select.bind(input), false);

        function onInput()
        {
            input.classList.toggle("error-input", !!validate(input.value));
        }

        function onChange()
        {
            var valid = !validate(input.value);
            input.classList.toggle("error-input", !valid);
            if (valid)
                apply(input.value ? Number(input.value) : 0);
        }

        /**
         * @param {!Event} event
         */
        function onKeyDown(event)
        {
            if (isEnterKey(event)) {
                if (!validate(input.value))
                    apply(input.value ? Number(input.value) : 0);
                return;
            }

            var increment = event.keyIdentifier === "Up" ? 1 : event.keyIdentifier === "Down" ? -1 : 0;
            if (!increment)
                return;
            if (event.shiftKey)
                increment *= 10;

            var value = input.value;
            if (validate(value) || !value)
                return;

            value = (value ? Number(value) : 0) + increment;
            var stringValue = value ? String(value) : "";
            if (validate(stringValue) || !value)
                return;

            input.value = stringValue;
            apply(input.value ? Number(input.value) : 0);
            event.preventDefault();
        }

        /**
         * @param {number} value
         */
        function setValue(value)
        {
            var stringValue = value ? String(value) : "";
            if (stringValue === input.value)
                return;
            var valid = !validate(stringValue);
            input.classList.toggle("error-input", !valid);
            input.value = stringValue;
            input.setSelectionRange(stringValue.length, stringValue.length);
        }

        return setValue;
    },

    /**
     * @param {!WebInspector.ContextMenu} contextMenu
     */
    _appendScaleMenuItems: function(contextMenu)
    {
        var scaleSetting = this._model.scaleSetting();
        if (this._model.type() === WebInspector.DeviceModeModel.Type.Device) {
            contextMenu.appendItem(WebInspector.UIString("Fit to window (%.0f%%)", this._model.fitScale() * 100), scaleSetting.set.bind(scaleSetting, this._model.fitScale()), false);
            contextMenu.appendSeparator();
        }
        appendScaleItem(WebInspector.UIString("50%"), 0.5);
        appendScaleItem(WebInspector.UIString("75%"), 0.75);
        appendScaleItem(WebInspector.UIString("100%"), 1);
        appendScaleItem(WebInspector.UIString("125%"), 1.25);
        appendScaleItem(WebInspector.UIString("150%"), 1.5);

        /**
         * @param {string} title
         * @param {number} value
         */
        function appendScaleItem(title, value)
        {
            contextMenu.appendCheckboxItem(title, scaleSetting.set.bind(scaleSetting, value), scaleSetting.get() === value, false);
        }
    },

    /**
     * @param {!WebInspector.ContextMenu} contextMenu
     */
    _appendOptionsMenuItems: function(contextMenu)
    {
        var uaDisabled = this._model.type() !== WebInspector.DeviceModeModel.Type.Responsive;
        var uaSetting = this._model.uaSetting();
        var uaSubmenu = contextMenu.appendSubMenuItem(WebInspector.UIString("User agent type"), false);
        var uaValue = this._model.uaSetting().get();
        if (this._model.type() === WebInspector.DeviceModeModel.Type.None)
            uaValue = WebInspector.DeviceModeModel.UA.Desktop;
        if (this._model.type() === WebInspector.DeviceModeModel.Type.Device)
            uaValue = this._model.device().mobile() ? WebInspector.DeviceModeModel.UA.Mobile : this._model.device().touch() ? WebInspector.DeviceModeModel.UA.DesktopTouch : WebInspector.DeviceModeModel.UA.Desktop;
        appendUAItem(WebInspector.UIString("Mobile (default)"), WebInspector.DeviceModeModel.UA.Mobile);
        appendUAItem(WebInspector.UIString("Desktop"), WebInspector.DeviceModeModel.UA.Desktop);
        appendUAItem(WebInspector.UIString("Desktop with touch"), WebInspector.DeviceModeModel.UA.DesktopTouch);

        /**
         * @param {string} title
         * @param {!WebInspector.DeviceModeModel.UA} value
         */
        function appendUAItem(title, value)
        {
            uaSubmenu.appendCheckboxItem(title, uaSetting.set.bind(uaSetting, value), uaValue === value, uaDisabled);
        }

        var deviceScaleFactorDisabled = this._model.type() !== WebInspector.DeviceModeModel.Type.Responsive;
        var deviceScaleFactorSubmenu = contextMenu.appendSubMenuItem(WebInspector.UIString("Device pixel ratio"), false);
        var deviceScaleFactorSetting = this._model.deviceScaleFactorSetting();
        var deviceScaleFactorValue = deviceScaleFactorDisabled ? 0 : deviceScaleFactorSetting.get();
        appendDeviceScaleFactorItem(WebInspector.UIString("Default: %f", this._model.defaultDeviceScaleFactor()), 0);
        deviceScaleFactorSubmenu.appendSeparator();
        appendDeviceScaleFactorItem(WebInspector.UIString("1"), 1);
        appendDeviceScaleFactorItem(WebInspector.UIString("2"), 2);
        appendDeviceScaleFactorItem(WebInspector.UIString("3"), 3);

        /**
         * @param {string} title
         * @param {number} value
         */
        function appendDeviceScaleFactorItem(title, value)
        {
            deviceScaleFactorSubmenu.appendCheckboxItem(title, deviceScaleFactorSetting.set.bind(deviceScaleFactorSetting, value), deviceScaleFactorValue === value, deviceScaleFactorDisabled);
        }

        contextMenu.appendItem(WebInspector.UIString("Reset to defaults"), this._model.reset.bind(this._model), this._model.type() !== WebInspector.DeviceModeModel.Type.Responsive);
        contextMenu.appendSeparator();

        contextMenu.appendCheckboxItem(WebInspector.UIString("Show media queries"), this._toggleMediaInspector.bind(this), this._showMediaInspectorSetting.get(), this._model.type() === WebInspector.DeviceModeModel.Type.None);
        contextMenu.appendCheckboxItem(WebInspector.UIString("Show rulers"), this._toggleRulers.bind(this), this._showRulersSetting.get(), this._model.type() === WebInspector.DeviceModeModel.Type.None);
        contextMenu.appendItem(WebInspector.UIString("Configure network\u2026"), this._openNetworkConfig.bind(this), false);
    },

    _toggleMediaInspector: function()
    {
        this._showMediaInspectorSetting.set(!this._showMediaInspectorSetting.get());
    },

    _toggleRulers: function()
    {
        this._showRulersSetting.set(!this._showRulersSetting.get());
    },

    _openNetworkConfig: function()
    {
        InspectorFrontendHost.bringToFront();
        // TODO(dgozman): make it explicit.
        WebInspector.actionRegistry.action("network.show-config").execute();
    },

    /**
     * @param {!Element} element
     * @return {!WebInspector.ToolbarItem}
     */
    _wrapToolbarItem: function(element)
    {
        var container = createElement("div");
        var shadowRoot = WebInspector.createShadowRootWithCoreStyles(container, "emulation/deviceModeToolbar.css");
        shadowRoot.appendChild(element);
        return new WebInspector.ToolbarItem(container);
    },

    /**
     * @param {!WebInspector.EmulatedDevice} device
     */
    _emulateDevice: function(device)
    {
        this._model.emulate(WebInspector.DeviceModeModel.Type.Device, device, this._lastMode.get(device) || device.modes[0]);
    },

    _switchToResponsive: function()
    {
        this._model.emulate(WebInspector.DeviceModeModel.Type.Responsive, null, null);
    },

    /**
     * @param {!Array<!WebInspector.EmulatedDevice>} devices
     * @return {!Array<!WebInspector.EmulatedDevice>}
     */
    _filterDevices: function(devices)
    {
        devices = devices.filter(function(d) { return d.show(); });
        devices.sort(WebInspector.EmulatedDevice.deviceComparator);
        return devices;
    },

    /**
     * @return {!Array<!WebInspector.EmulatedDevice>}
     */
    _standardDevices: function()
    {
        return this._filterDevices(WebInspector.emulatedDevicesList.standard());
    },

    /**
     * @return {!Array<!WebInspector.EmulatedDevice>}
     */
    _customDevices: function()
    {
        return this._filterDevices(WebInspector.emulatedDevicesList.custom());
    },

    /**
     * @return {!Array<!WebInspector.EmulatedDevice>}
     */
    _allDevices: function()
    {
        return this._standardDevices().concat(this._customDevices());
    },

    /**
     * @param {!WebInspector.ContextMenu} contextMenu
     */
    _appendDeviceMenuItems: function(contextMenu)
    {
        contextMenu.appendCheckboxItem(WebInspector.UIString("Responsive"), this._switchToResponsive.bind(this), this._model.type() === WebInspector.DeviceModeModel.Type.Responsive, false);
        appendGroup.call(this, this._standardDevices());
        appendGroup.call(this, this._customDevices());
        contextMenu.appendSeparator();
        contextMenu.appendItem(WebInspector.UIString("Edit\u2026"), WebInspector.emulatedDevicesList.revealCustomSetting.bind(WebInspector.emulatedDevicesList), false);

        /**
         * @param {!Array<!WebInspector.EmulatedDevice>} devices
         * @this {WebInspector.DeviceModeView.Toolbar}
         */
        function appendGroup(devices)
        {
            if (!devices.length)
                return;
            contextMenu.appendSeparator();
            for (var device of devices)
                contextMenu.appendCheckboxItem(device.title, this._emulateDevice.bind(this, device), this._model.device() === device, false);
        }
    },

    /**
     * @this {WebInspector.DeviceModeView.Toolbar}
     */
    _deviceListChanged: function()
    {
        if (!this._model.device())
            return;

        var devices = this._allDevices();
        if (devices.indexOf(this._model.device()) === -1)
            this._emulateDevice(devices[0] || WebInspector.emulatedDevicesList.standard()[0]);
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _modeMenuClicked: function(event)
    {
        var device = this._model.device();
        var model = this._model;

        if (device.modes.length === 2 && device.modes[0].orientation !== device.modes[1].orientation) {
            model.emulate(model.type(), model.device(), model.mode() === device.modes[0] ? device.modes[1] : device.modes[0]);
            return;
        }

        var contextMenu = new WebInspector.ContextMenu(/** @type {!Event} */ (event.data),
            false,
            event.target.element.totalOffsetLeft(),
            event.target.element.totalOffsetTop() + event.target.element.offsetHeight);
        addOrientation(WebInspector.EmulatedDevice.Vertical, WebInspector.UIString("Portrait"));
        addOrientation(WebInspector.EmulatedDevice.Horizontal, WebInspector.UIString("Landscape"));
        contextMenu.show();

        /**
         * @param {string} orientation
         * @param {string} title
         */
        function addOrientation(orientation, title)
        {
            var modes = device.modesForOrientation(orientation);
            if (!modes.length)
                return;
            if (modes.length === 1) {
                addMode(modes[0], title);
            } else {
                for (var index = 0; index < modes.length; index++)
                    addMode(modes[index], title + " \u2013 " + modes[index].title);
            }
        }

        /**
         * @param {!WebInspector.EmulatedDevice.Mode} mode
         * @param {string} title
         */
        function addMode(mode, title)
        {
            contextMenu.appendCheckboxItem(title, applyMode.bind(null, mode), model.mode() === mode, false);
        }

        /**
         * @param {!WebInspector.EmulatedDevice.Mode} mode
         */
        function applyMode(mode)
        {
            model.emulate(model.type(), model.device(), mode);
        }
    },

    /**
     * @return {!Element}
     */
    element: function()
    {
        return this._element;
    },

    update: function()
    {
        if (this._model.type() !== this._cachedModelType) {
            this._cachedModelType = this._model.type();
            this._widthInput.disabled = this._model.type() !== WebInspector.DeviceModeModel.Type.Responsive;
            this._heightInput.disabled = this._model.type() !== WebInspector.DeviceModeModel.Type.Responsive;
        }

        var size = this._model.appliedDeviceSize();
        this._updateHeightInput(this._model.type() === WebInspector.DeviceModeModel.Type.Responsive && this._model.isFullHeight() ? 0 : size.height);
        this._updateWidthInput(size.width);
        this._heightInput.placeholder = size.height;

        if (this._model.scale() !== this._cachedScale) {
            this._scaleItem.setText(WebInspector.UIString("%.0f%%", this._model.scale() * 100));
            this._scaleItem.setState(this._model.scale() === 1 ? "off" : "on");
            this._cachedScale = this._model.scale();
        }

        var deviceScale = this._model.deviceScaleFactorSetting().get();
        this._deviceScaleItem.setVisible(this._model.type() === WebInspector.DeviceModeModel.Type.Responsive && !!deviceScale);
        if (deviceScale !== this._cachedDeviceScale) {
            this._deviceScaleItem.setText(WebInspector.UIString("DPR: %.1f", deviceScale));
            this._cachedDeviceScale = deviceScale;
        }

        var uaType = this._model.type() === WebInspector.DeviceModeModel.Type.Responsive ? this._model.uaSetting().get() : WebInspector.DeviceModeModel.UA.Mobile;
        this._uaItem.setVisible(this._model.type() === WebInspector.DeviceModeModel.Type.Responsive && uaType !== WebInspector.DeviceModeModel.UA.Mobile);
        if (uaType !== this._cachedUaType) {
            this._uaItem.setText(uaType === WebInspector.DeviceModeModel.UA.Desktop ? WebInspector.UIString("Desktop") : WebInspector.UIString("Touch"));
            this._cachedUaType = uaType;
        }

        var deviceItemTitle = WebInspector.UIString("None");
        if (this._model.type() === WebInspector.DeviceModeModel.Type.Responsive)
            deviceItemTitle = WebInspector.UIString("Responsive");
        if (this._model.type() === WebInspector.DeviceModeModel.Type.Device)
            deviceItemTitle = this._model.device().title;
        this._deviceSelectItem.setText(deviceItemTitle);

        if (this._model.device() !== this._cachedModelDevice) {
            var device = this._model.device();
            this._modeButton.setVisible(!!device);
            if (device) {
                var modeCount = device ? device.modes.length : 0;
                this._modeButton.setEnabled(modeCount >= 2);
                this._modeButton.setTitle(modeCount === 2 ? WebInspector.UIString("Rotate") : WebInspector.UIString("Screen options"));
            }
            this._cachedModelDevice = device;
        }

        if (this._model.type() === WebInspector.DeviceModeModel.Type.Device)
            this._lastMode.set(/** @type {!WebInspector.EmulatedDevice} */ (this._model.device()), /** @type {!WebInspector.EmulatedDevice.Mode} */ (this._model.mode()));

        if (this._model.mode() !== this._cachedModelMode && this._model.type() !== WebInspector.DeviceModeModel.Type.None) {
            this._cachedModelMode = this._model.mode();
            var value = this._persistenceSetting.get();
            if (this._model.device()) {
                value.device = this._model.device().title;
                value.orientation = this._model.mode() ? this._model.mode().orientation : "";
                value.mode = this._model.mode() ? this._model.mode().title : "";
            } else {
                value.device = "";
                value.orientation = "";
                value.mode = "";
            }
            this._persistenceSetting.set(value);
        }
    },

    restore: function()
    {
        for (var device of this._allDevices()) {
            if (device.title === this._persistenceSetting.get().device) {
                for (var mode of device.modes) {
                    if (mode.orientation === this._persistenceSetting.get().orientation && mode.title === this._persistenceSetting.get().mode) {
                        this._lastMode.set(device, mode);
                        this._emulateDevice(device);
                        return;
                    }
                }
            }
        }

        this._model.emulate(WebInspector.DeviceModeModel.Type.Responsive, null, null);
    }
}

/**
 * @constructor
 * @extends {WebInspector.VBox}
 * @param {boolean} horizontal
 * @param {function(number)} applyCallback
 */
WebInspector.DeviceModeView.Ruler = function(horizontal, applyCallback)
{
    WebInspector.VBox.call(this);
    this._contentElement = this.element.createChild("div", "device-mode-ruler flex-auto");
    this._horizontal = horizontal;
    this._scale = 1;
    this._offset = 0;
    this._count = 0;
    this._throttler = new WebInspector.Throttler(0);
    this._applyCallback = applyCallback;
}

WebInspector.DeviceModeView.Ruler.prototype = {
    /**
     * @param {number} offset
     * @param {number} scale
     */
    render: function(offset, scale)
    {
        this._scale = scale;
        this._offset = offset;
        if (this._horizontal)
            this.element.style.paddingLeft = this._offset + "px";
        else
            this.element.style.paddingTop = this._offset + "px";
        this._throttler.schedule(this._update.bind(this));
    },

    /**
     * @override
     */
    onResize: function()
    {
        this._throttler.schedule(this._update.bind(this));
    },

    /**
     * @return {!Promise.<?>}
     */
    _update: function()
    {
        var zoomFactor = WebInspector.zoomManager.zoomFactor();
        var size = this._horizontal ? this._contentElement.offsetWidth : this._contentElement.offsetHeight;

        if (this._scale !== this._renderedScale || zoomFactor !== this._renderedZoomFactor) {
            this._contentElement.removeChildren();
            this._count = 0;
            this._renderedScale = this._scale;
            this._renderedZoomFactor = zoomFactor;
        }

        var dipSize = size * zoomFactor / this._scale;
        var count = Math.ceil(dipSize / 5);
        var step = 1;
        if (this._scale < 0.8)
            step = 2;
        if (this._scale < 0.6)
            step = 4;
        if (this._scale < 0.4)
            step = 8;

        for (var i = count; i < this._count; i++) {
            if (!(i % step))
                this._contentElement.lastChild.remove();
        }

        for (var i = this._count; i < count; i++) {
            if (i % step)
                continue;
            var marker = this._contentElement.createChild("div", "device-mode-ruler-marker");
            if (i) {
                if (this._horizontal)
                    marker.style.left = (5 * i) * this._scale / zoomFactor + "px";
                else
                    marker.style.top = (5 * i) * this._scale / zoomFactor + "px";
                if (!(i % 20)) {
                    var text = marker.createChild("div", "device-mode-ruler-text");
                    text.textContent = i * 5;
                    text.addEventListener("click", this._onMarkerClick.bind(this, i * 5), false);
                }
            }
            if (!(i % 10))
                marker.classList.add("device-mode-ruler-marker-large");
            else if (!(i % 5))
                marker.classList.add("device-mode-ruler-marker-medium");
        }

        this._count = count;
        return Promise.resolve();
    },

    /**
     * @param {number} size
     */
    _onMarkerClick: function(size)
    {
        this._applyCallback.call(null, size);
    },

    __proto__: WebInspector.VBox.prototype
}

/**
 * @constructor
 * @implements {WebInspector.ActionDelegate}
 */
WebInspector.DeviceModeView.ActionDelegate = function()
{
}

WebInspector.DeviceModeView.ActionDelegate.prototype = {
    /**
     * @override
     * @param {!WebInspector.Context} context
     * @param {string} actionId
     * @return {boolean}
     */
    handleAction: function(context, actionId)
    {
        if (actionId === "emulation.toggle-device-mode" && WebInspector.DeviceModeView._wrapperInstance) {
            WebInspector.DeviceModeView._wrapperInstance._toggleDeviceMode();
            return true;
        }
        return false;
    }
}

/**
 * @extends {WebInspector.VBox}
 * @param {!WebInspector.InspectedPagePlaceholder} inspectedPagePlaceholder
 * @constructor
 */
WebInspector.DeviceModeView.Wrapper = function(inspectedPagePlaceholder)
{
    WebInspector.VBox.call(this);
    WebInspector.DeviceModeView._wrapperInstance = this;
    this._inspectedPagePlaceholder = inspectedPagePlaceholder;
    this._deviceModeView = new WebInspector.DeviceModeView();
    this._toggleDeviceModeAction = WebInspector.actionRegistry.action("emulation.toggle-device-mode");
    this._showDeviceModeSetting = WebInspector.settings.createSetting("emulation.showDeviceMode", false);
    this._showDeviceModeSetting.addChangeListener(this._update.bind(this, false));
    this._update(true);
}

/** @type {!WebInspector.DeviceModeView.Wrapper} */
WebInspector.DeviceModeView._wrapperInstance;

WebInspector.DeviceModeView.Wrapper.prototype = {
    _toggleDeviceMode: function()
    {
        this._showDeviceModeSetting.set(!this._showDeviceModeSetting.get());
    },

    /**
     * @param {boolean} force
     */
    _update: function(force)
    {
        this._toggleDeviceModeAction.setToggled(this._showDeviceModeSetting.get());
        if (!force && this._showDeviceModeSetting.get() === this._deviceModeView.isShowing())
            return;

        if (this._showDeviceModeSetting.get()) {
            this._deviceModeView.show(this.element);
            this._inspectedPagePlaceholder.clearMinimumSizeAndMargins();
            this._inspectedPagePlaceholder.show(this._deviceModeView.element);
        } else {
            this._deviceModeView.detach();
            this._inspectedPagePlaceholder.restoreMinimumSizeAndMargins();
            this._inspectedPagePlaceholder.show(this.element);
        }
    },

    __proto__: WebInspector.VBox.prototype
}


text:
#ifndef MPACK_TEST_COMMON_H
#define MPACK_TEST_COMMON_H 1

#include "test.h"

#ifdef __cplusplus
extern "C" {
#endif

void test_common(void);

#ifdef __cplusplus
}
#endif

#endif


text:
<?php
class Kwc_Box_Search_Ajax_Component extends Kwc_Abstract_Ajax_Component
{
    public static function getSettings()
    {
        $ret = parent::getSettings();
        $ret['viewCache'] = false;
        return $ret;
    }

    public function getTemplateVars(Kwf_Component_Renderer_Abstract $renderer = null)
    {
        $parent = $this->getData()->parent->getComponent();
        $ret = parent::getTemplateVars($renderer);
        $searchViews = $parent->getSearchViews();
        $formData = $parent->getSearchFormData();
        $ret['queryValue'] = $formData['queryValue'];
        $ret['foundNothing'] = true;
        foreach ($searchViews as $key => $view) {
            $addList = array();
            $addList['component'] = $view;
            $addList['title'] = is_numeric($key) ? null : $key;
            if ($addList['component']->getComponent()->getPagingCount() > 0) {
                $ret['foundNothing'] = false;
            } else {
                continue;
            }

            if ($addList['component']->getComponent()->moreItemsAvailable()) {
                $ret['queryValue'] = $formData['queryValue'];
                $addList['showAllHref'] =
                    $formData['searchPageUrl'] . '?' .
                    $formData['queryParam'] . '=' . $ret['queryValue'] . '&' .
                    $formData['submitParam'] . '=submit';
            } else {
                $addList['showAllHref'] = null;
            }
            $ret['lists'][] = $addList;
        }
        return $ret;
    }
}


text:
package com.amazonaws.services.s3.model;

/**
 * Type of restore request.
 */
public enum RestoreRequestType {
    SELECT("SELECT");

    private final String type;

    RestoreRequestType(String type) {
        this.type = type;
    }

    /* (non-Javadoc)
     * @see java.lang.Enum#toString()
     */
    @Override
    public String toString() {
        return type;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value real value
     * @return TableStatus corresponding to the value
     */
    public static RestoreRequestType fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (RestoreRequestType enumEntry : RestoreRequestType.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
<?php
namespace HedgeBot\Plugins\Horaro;

use HedgeBot\Plugins\Horaro\Entity\Schedule;
use \stdClass;

class HoraroEndpoint
{
    /** @var Horaro The plugin reference */
    protected $plugin;

    /**
     * HoraroEndpoint constructor.
     * Initializes the endpoint with the plugin to use as data source.
     *
     * @param Horaro $plugin
     */
    public function __construct(Horaro $plugin)
    {
        $this->plugin = $plugin;
    }

    /**
     * Lists the schedules that are registered on the bot.
     *
     * @return array The list of registered schedules.
     */
    public function getSchedules()
    {
        return $this->plugin->getSchedules();
    }

    /**
     * Gets the currently running schedules.
     *
     * @param string $channel    Filter the schedules by channel.
     * @param bool   $lookaround Set to true to loosen the search by looking for schedules that are around current time
     *                           by the lookaroundThreshold setting value (default: 1 hour).
     *
     * @return array The list of schedules that are currently running. If none are found, an empty array is returned.
     */
    public function getCurrentSchedules($channel = null, $lookaround = false)
    {
        return $this->plugin->getCurrentlyRunningSchedules($channel, $lookaround);
    }

    /**
     * Get the currently running schedule. If multiple schedules are running, it returns the earliest one.
     *
     * @param string $channel    Filter the schedules by channel.
     * @param bool   $lookaround Set to true to loosen the search by looking for schedules that are around current time
     *                           by the lookaroundThreshold setting value (default: 1 hour).
     *
     * @return Schedule|null The earliest running schedule if there is one, null if not.
     * @throws Exception
     */
    public function getCurrentSchedule($channel = null, $lookaround = false)
    {
        return $this->plugin->getEarliestCurrentlyRunningSchedule($channel, $lookaround);
    }

    /**
     * Gets a schedule by its ident slug.
     *
     * @param string $identSlug The ident slug of the schedule.
     *
     * @return Schedule|null The schedule info if found, false if not.
     */
    public function getSchedule($identSlug)
    {
        return $this->plugin->getScheduleByIdentSlug($identSlug);
    }

    /**
     * Saves a schedule's data.
     *
     * @param string $identSlug The ident slug of the schedule to save.
     * @param stdClass $scheduleData The schedule data.
     */
    public function updateSchedule($identSlug, stdClass $scheduleData)
    {
        return $this->plugin->updateSchedule($identSlug, (array) $scheduleData);
    }

    /**
     * Loads a schedule from Horaro.
     *
     * @param string $scheduleId The schedule ID.
     * @param string $eventId The event ID.
     *
     * @return string|bool The schedule ident slug if the schedule was loaded successfully, false if not.
     */
    public function loadSchedule($scheduleId, $eventId = null)
    {
        return $this->plugin->loadSchedule($scheduleId, $eventId);
    }

    /**
     * Loads a schedule from its public Horaro URL.
     *
     * @param string $url The schedule URL.
     *
     * @return string|bool The schedule ident slug if the schedule was loaded successfully, false if not.
     */
    public function loadScheduleFromURL($url)
    {
        return $this->plugin->loadScheduleFromURL($url);
    }

    /**
     * Goes to the next item in the schedule.
     *
     * @param string $identSlug The schedule's ident slug.
     *
     * @return bool True if the schedule skipped successfully, false if not.
     */
    public function nextItem($identSlug)
    {
        return $this->plugin->nextItem($identSlug);
    }

    /**
     * Goes to the previous item in the schedule.
     *
     * @param string $identSlug The schedule's ident slug.
     *
     * @return bool True if the schedule has been rewinded successfully, false if not.
     */
    public function previousItem($identSlug)
    {
        return $this->plugin->previousItem($identSlug);
    }

    public function goToItem($identSlug, $itemIndex)
    {
        return $this->plugin->goToItem($identSlug, $itemIndex);
    }

    /**
     * Pauses the schedule.
     *
     * @param string $identSlug The ident slug of the schedule to pause.
     *
     * @return bool True if the schedule has been paused successfully, false otherwise.
     */
    public function pauseSchedule($identSlug)
    {
        return $this->plugin->pauseSchedule($identSlug);
    }

    /**
     * Pauses the schedule.
     *
     * @param string $identSlug The ident slug of the schedule to pause.
     *
     * @return bool True if the schedule has been paused successfully, false otherwise.
     */
    public function resumeSchedule($identSlug)
    {
        return $this->plugin->resumeSchedule($identSlug);
    }

    /**
     * Deletes a schedule from the list of stored schedules.
     *
     * @param $identSlug The ident slug of the schedule to delete.
     *
     * @return bool True if the schedule was deleted successfully, false if not.
     */
    public function deleteSchedule($identSlug)
    {
        return $this->plugin->deleteSchedule($identSlug);
    }

    /**
     * Triggers a schedule data refresh from Horaro.
     *
     * @param mixed $identSlug The ident slug of the schedule to refresh.
     * @return void
     */
    public function refreshScheduleData($identSlug)
    {
        return $this->plugin->refreshScheduleData($identSlug);
    }

    /**
     * Gets the data from a schedule that the plugin fetched from Horaro.
     *
     * @param string $identSlug The ident slug of the schedule to get the data from.
     *
     * @return object|null The schedule data if found or null if not.
     */
    public function getScheduleData($identSlug)
    {
        $schedule = $this->plugin->getScheduleByIdentSlug($identSlug);

        if (empty($schedule)) {
            return null;
        }

        return $schedule->getData();
    }

    /**
     * Gets the data from all the schedules that the plugin fetched from Horaro.
     *
     * @return array|null The schedules data.
     */
    public function getSchedulesData()
    {
        $schedulesData = [];
        $schedules = $this->plugin->getSchedules();

        /** @var Schedule $schedule */
        foreach($schedules as $schedule) {
            $schedulesData[$schedule->getIdentSlug()] = $schedule->getData();
        }

        return $schedulesData;
    }
}


text: sample console app


text:
A variation of the classic game "Space Invaders" written in Dart.

## How to start it using Dart Editor

Clone it from github

```
git clone https://github.com/Xianahru/dartSpaceInvaders.git
```

and open created directory in your Dart Editor. Then:

1. Run pub build in Dart Editor.
2. Start the server by running bin\spaceServer.dart.
3. Open as many webbrowser windows you like and open the url [http://localhost:3000][dart-url]

[dart-url]: http://localhost:3000


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

public class Cooldown : MonoBehaviour {

	private float duree; //La duree necessaire pour aller de 1 à 0
	private bool actif;
	private float temps;

	// Use this for initialization
	void Start () {
		actif = false;
		temps = 0;
		GetComponent<Image> ().fillAmount = 0;
	}

	// Update is called once per frame
	void Update () {
		if (Time.fixedTime > temps)
			actif = false;

		if (actif) {
			GetComponent<Image> ().fillAmount = (temps - Time.fixedTime) / (temps - (temps - duree));
		}
	}

	public void setCooldown(float dur){
		duree = dur;
		actif = true;
		temps = Time.fixedTime + duree;
	}
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Auth extends MY_Controller {

    function __construct(){

        parent::__construct();
        $this->load->database();
        $this->load->library(array('ion_auth', 'form_validation', 'session'));
        $this->load->helper(array('url', 'language'));

        $this->form_validation->set_error_delimiters($this->config->item('error_start_delimiter', 'ion_auth'), $this->config->item('error_end_delimiter', 'ion_auth'));
    }

    public function index(){

        if($this->ion_auth->logged_in()){
            redirect('admin/dashboard', 'refresh');
        } else {
           /* $data['page'] = "admin/login";
            $data['module'] = 'admin';*/

            $this->load->view('admin/admin/login');
        }
	}

	public function login(){
        $this->form_validation->set_rules('username', 'Username', 'required');
        $this->form_validation->set_rules('password', 'Password', 'required');

        if($this->form_validation->run() == true){

            $username = $this->input->post('username');
            $password = $this->input->post('password');
            $remember = (bool) $this->input->post('remember');

            if($this->ion_auth->login($username, $password, $remember)){
                $this->session->set_flashdata('message', $this->ion_auth->messages());
                redirect('admin/dashboard', 'refresh');
            } else {
                $this->session->set_flashdata('message','Incorrect username or password entered. Please try again.');
                redirect('auth/', 'refresh');
            }
        } else {
            $this->session->set_flashdata('message', $this->ion_auth->errors());
            (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
/*
            $data['page'] = $this->config->item('gudiva_template_dir_admin'). "login";
            $data['module'] = 'admin';*/

            $this->load->view('admin/admin/login');
        }
    }

    public function logout(){
	    $this->ion_auth->logout();
	    redirect('auth/', 'refresh');
    }

//    public function signup(){
//        $data['page'] = $this->config->item('gudiva_template_dir_public'). "registration";
//        $data['module'] = '';
//
//        $this->load->view($this->_container, $data);
//    }
//
//    public function register(){
//        if ($this->ion_auth->logged_in() || $this->ion_auth->is_admin())
//        {
//            redirect('auth', 'refresh');
//        }
//        $this->form_validation->set_rules('first_name', 'First Name', 'required', 'trim');
//        $this->form_validation->set_rules('last_name', 'Last Name', 'required', 'trim');
//        $this->form_validation->set_rules('email', 'E-mail', 'required|valid_email|is_unique[' . $tables['users'] . '.email]');
//        $this->form_validation->set_rules('phone_number', 'Phone Number', 'required', 'trim');
//        $this->form_validation->set_rules('username', 'Username', 'required');
//        $this->form_validation->set_rules('password', 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[password_confirm]');
//        $this->form_validation->set_rules('password_confirm', 'required');
//    }
}


text:
<?php

$installer = $this;
$installer->addAttribute('catalog_category', 'filter_price_range', array(
    'group'         => 'Display Settings',
    'type'          => 'int',
    'label'         => 'Layered Navigation Price Step',
    'required'      => false,
    'global'        => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
    'visible'       => 1,
    'input_renderer'=> 'adminhtml/catalog_category_helper_pricestep',
));


text:
package com.odaff.samza.web

import argonaut.Argonaut._
import com.twitter.app.Flag
import com.twitter.finagle.http.Method.Post
import com.twitter.finagle.http.{Request, Response, Status}
import com.twitter.finagle.{Http, Service}
import com.twitter.logging.Logging
import com.twitter.server.TwitterServer
import com.twitter.util.{Await, Future}
import org.apache.samza.config.MapConfig
import org.apache.samza.job.local.{ProcessJob, ThreadJob}
import org.apache.samza.job.yarn.YarnJob
import org.apache.samza.job.{ApplicationStatus, JobRunner, StreamJob}

import scala.collection.JavaConversions._
import scalaz.{-\/, \/-, \/}

/**
  * Provides a server to deploy Samza jobs.  The default port is 8888 and this can be overridden with -deploy.port
  * on the cmd line.
  *
  * Deploy Request json is a POST to /deploy
  * {
  *   "config":
  *     {
  *       "job.factory.class" : "com.odaff.samza.yarn.YarnJobFactory",
  *       "job.name" : "test-deploy"
  *       ...
  *     }
  * }
  *
  * On success deploy response is the application id  of the deployed Samza Job.  This is populated for YarnJobs and
  * ThreadJobs but not ProcessJobs
  *
  * { "applicationId" : "application_id" }
  *
  * On failure the deploy response is
  * {
  *   "error_code" : 1
  *   "error_message" : "a message about the failure"
  * }
  *
  * Default configuration can optionally be supplied on the command line which is passed to all jobs as a comma separated
  * list
  *
  * --deploy.config yarn.container.memory.mb=2048,yarn.container.retry.count=10
  *
  */
object SamzaDeployServer extends TwitterServer with Logging {

  override def failfastOnFlagsNotParsed: Boolean = true

  val deployServerPort = flag("deploy.port", ":8888", "Deploy server http port")
  val configOverride:Flag[Map[String, String]] = flag("deploy.config", "Deploy default config")

  val service = new Service[Request, Response] {

    def apply(request: Request) = request.uri match {
      case "/deploy" => deployRequest(request)
      case _ => Future.value(Response(request.version, Status.Forbidden))
    }

    def deployRequest(request: Request) =
      request.method match{
        case Post =>
          val response = request.getContentString()
            .decodeEither[DeployRequest]
            .flatMap(runJob)
            .map(maybeJob => DeploySuccess(maybeJob.getOrElse("")))
            .map(success(request, _))
              .fold(
                failure(request, _),
                identity
              )
          Future.value(response)
        case _ =>
          val response = Response(request.version, Status.MethodNotAllowed)
          Future.value(response)
      }

    def success(request: Request, deploySuccess: DeploySuccess) = {
      val response = Response(request.version, Status.Ok)
      response.contentString = deploySuccess.asJson.nospaces
      response
    }

    def failure(request: Request, message: String) = {
      val response = Response(request.version, Status.InternalServerError)
      response.contentString = DeployError(1, message).asJson.nospaces
      response
    }

    def runJob(req: DeployRequest): \/[String, Option[String]] = {
      val configMap = configOverride.get.getOrElse(Map.empty) ++ req.properties
      val config = new MapConfig(configMap)
      \/.fromTryCatchNonFatal{
        new JobRunner(config).run()
      }.leftMap{ t =>
        log.error(t, "error running job")
        t.getMessage
      }.flatMap{ job =>
        job.getStatus match {
          case ApplicationStatus.Running => \/-(applicationId(job))
          case _ => -\/("Application failed to enter running state")
        }
      }
    }

    def applicationId(job: StreamJob): Option[String] = job match {
      case yarnJob:YarnJob => Some(yarnJob.appId.toString)
      case threadJob:ThreadJob => Some(threadJob.thread.getId.toString)
      case _ => Some("")
    }
  }

  def main() {
    configOverride.get.foreach{ m =>
      m.foreach(println)
    }
    for {
      port <- deployServerPort.getWithDefault
    } {
      val server = Http.serve(port, service)
      onExit {
        server.close()
      }
      Await.ready(server)
    }
  }
}