text:
"""
Support for UK Met Office weather service.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.metoffice/
"""
from datetime import timedelta
import logging

import voluptuous as vol

from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
    ATTR_ATTRIBUTION, CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE,
    CONF_MONITORED_CONDITIONS, CONF_NAME, TEMP_CELSIUS)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle

_LOGGER = logging.getLogger(__name__)

REQUIREMENTS = ['datapoint==0.4.3']

ATTR_LAST_UPDATE = 'last_update'
ATTR_SENSOR_ID = 'sensor_id'
ATTR_SITE_ID = 'site_id'
ATTR_SITE_NAME = 'site_name'

CONF_ATTRIBUTION = "Data provided by the Met Office"

CONDITION_CLASSES = {
    'cloudy': ['7', '8'],
    'fog': ['5', '6'],
    'hail': ['19', '20', '21'],
    'lightning': ['30'],
    'lightning-rainy': ['28', '29'],
    'partlycloudy': ['2', '3'],
    'pouring': ['13', '14', '15'],
    'rainy': ['9', '10', '11', '12'],
    'snowy': ['22', '23', '24', '25', '26', '27'],
    'snowy-rainy': ['16', '17', '18'],
    'sunny': ['0', '1'],
    'windy': [],
    'windy-variant': [],
    'exceptional': [],
}

DEFAULT_NAME = "Met Office"

VISIBILITY_CLASSES = {
    'VP': '<1',
    'PO': '1-4',
    'MO': '4-10',
    'GO': '10-20',
    'VG': '20-40',
    'EX': '>40'
}

MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=35)

# Sensor types are defined like: Name, units
SENSOR_TYPES = {
    'name': ['Station Name', None],
    'weather': ['Weather', None],
    'temperature': ['Temperature', TEMP_CELSIUS],
    'feels_like_temperature': ['Feels Like Temperature', TEMP_CELSIUS],
    'wind_speed': ['Wind Speed', 'mph'],
    'wind_direction': ['Wind Direction', None],
    'wind_gust': ['Wind Gust', 'mph'],
    'visibility': ['Visibility', None],
    'visibility_distance': ['Visibility Distance', 'km'],
    'uv': ['UV', None],
    'precipitation': ['Probability of Precipitation', '%'],
    'humidity': ['Humidity', '%']
}

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Required(CONF_API_KEY): cv.string,
    vol.Required(CONF_MONITORED_CONDITIONS, default=[]):
        vol.All(cv.ensure_list, [vol.In(SENSOR_TYPES)]),
    vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
    vol.Inclusive(CONF_LATITUDE, 'coordinates',
                  'Latitude and longitude must exist together'): cv.latitude,
    vol.Inclusive(CONF_LONGITUDE, 'coordinates',
                  'Latitude and longitude must exist together'): cv.longitude,
})

def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the Met Office sensor platform."""
    import datapoint as dp

    api_key = config.get(CONF_API_KEY)
    latitude = config.get(CONF_LATITUDE, hass.config.latitude)
    longitude = config.get(CONF_LONGITUDE, hass.config.longitude)
    name = config.get(CONF_NAME)

    datapoint = dp.connection(api_key=api_key)

    if None in (latitude, longitude):
        _LOGGER.error("Latitude or longitude not set in Home Assistant config")
        return

    try:
        site = datapoint.get_nearest_site(
            latitude=latitude, longitude=longitude)
    except dp.exceptions.APIException as err:
        _LOGGER.error("Received error from Met Office Datapoint: %s", err)
        return

    if not site:
        _LOGGER.error("Unable to get nearest Met Office forecast site")
        return

    data = MetOfficeCurrentData(hass, datapoint, site)
    data.update()
    if data.data is None:
        return

    sensors = []
    for variable in config[CONF_MONITORED_CONDITIONS]:
        sensors.append(MetOfficeCurrentSensor(site, data, variable, name))

    add_entities(sensors, True)

class MetOfficeCurrentSensor(Entity):
    """Implementation of a Met Office current sensor."""

    def __init__(self, site, data, condition, name):
        """Initialize the sensor."""
        self._condition = condition
        self.data = data
        self._name = name
        self.site = site

    @property
    def name(self):
        """Return the name of the sensor."""
        return '{} {}'.format(self._name, SENSOR_TYPES[self._condition][0])

    @property
    def state(self):
        """Return the state of the sensor."""
        if (self._condition == 'visibility_distance' and
                hasattr(self.data.data, 'visibility')):
            return VISIBILITY_CLASSES.get(self.data.data.visibility.value)
        if hasattr(self.data.data, self._condition):
            variable = getattr(self.data.data, self._condition)
            if self._condition == 'weather':
                return [k for k, v in CONDITION_CLASSES.items() if
                        self.data.data.weather.value in v][0]
            return variable.value
        return None

    @property
    def unit_of_measurement(self):
        """Return the unit of measurement."""
        return SENSOR_TYPES[self._condition][1]

    @property
    def device_state_attributes(self):
        """Return the state attributes of the device."""
        attr = {}
        attr[ATTR_ATTRIBUTION] = CONF_ATTRIBUTION
        attr[ATTR_LAST_UPDATE] = self.data.data.date
        attr[ATTR_SENSOR_ID] = self._condition
        attr[ATTR_SITE_ID] = self.site.id
        attr[ATTR_SITE_NAME] = self.site.name
        return attr

    def update(self):
        """Update current conditions."""
        self.data.update()

class MetOfficeCurrentData:
    """Get data from Datapoint."""

    def __init__(self, hass, datapoint, site):
        """Initialize the data object."""
        self._datapoint = datapoint
        self._site = site
        self.data = None

    @Throttle(MIN_TIME_BETWEEN_UPDATES)
    def update(self):
        """Get the latest data from Datapoint."""
        import datapoint as dp

        try:
            forecast = self._datapoint.get_forecast_for_site(
                self._site.id, '3hourly')
            self.data = forecast.now()
        except (ValueError, dp.exceptions.APIException) as err:
            _LOGGER.error("Check Met Office %s", err.args)
            self.data = None


text:
var superagent = require('superagent')
,	logger = require('../logging').getLogger(__LOGGER__)
,	Q = require('q')
,	Plugins = require("./Plugins")
,	merge = require("lodash/merge")
;

/**
 * Implements a subset of superagent's API. Packages up arguments
 * to pass to superagent under the hood.
 */
function Request(method, urlPath, cache) {
	this._method = method;
	this._urlPath = urlPath;
	this._cache = cache;

	this._queryParams = [];
	// _postParams should initially be null instead of {} because we want to allow people to send POST requests with
	// empty data sets (if they need to).  This way, we can differentiate between a default of null, an empty data set,
	// and a populated data set.
	this._postParams = null;
	this._headers = {};
	this._timeout = null;
	this._type = "json"; // superagent's default, only for POST/PUT/PATCH methods

	// public field
	this.aborted = undefined; //default to undefined
}

// we implement a subset of superagent's API. for the other methods,
// for now, we'll just throw an exception if they're called. By default,
// all methods throw exceptions, and we override some below
Object.keys(superagent.Request.prototype)
	.forEach( propName => {
		var originalProp = superagent.Request.prototype[propName];
		if (typeof originalProp === 'function') {
			Request.prototype[propName] = function () {
				throw new Error(`${propName}() from superagent's API isn't implemented yet.`);
			}
		}
	});

Request.prototype.agent = function (agent) {
	if (typeof agent === 'undefined') {
		return this._agent;
	}
	this._agent = agent;
	return this;
}

Request.prototype.method = function (method) {
	if (typeof method === 'undefined') {
		return this._method;
	}
	this._method = method;
	return this;
}

Request.prototype.urlPath = function (urlPath) {
	if (typeof urlPath === 'undefined') {
		return this._urlPath;
	}
	this._urlPath = urlPath;
	return this;
}

Request.prototype.query = function (queryParams) {
	if (typeof queryParams === 'undefined') {
		throw new Error("Request.query does not support retrieving the current query string");
	}
	this._queryParams.push(queryParams);
	return this;
}

Request.prototype.send = function (postParams) {
	if (typeof postParams === 'undefined') {
		return merge({}, this._postParams || {});
	}
	if (postParams !== null) {
		if (this._postParams === null) {
			this._postParams = {};
		}
		merge(this._postParams, postParams);
	}
	return this;
}

Request.prototype.set = function (headers) {
	if (typeof headers === 'undefined') {
		return merge({}, this._headers);
	}
	merge(this._headers, headers);
	return this;
}

Request.prototype.timeout = function (timeout) {
	if (typeof timeout === 'undefined') {
		return this._timeout;
	}
	this._timeout = timeout;
	return this;
}

Request.prototype.type = function (type) {
	if (typeof type === 'undefined') {
		return this._type;
	}
	this._type = type;
	return this;
}

Request.prototype.toJSON = function(){
	return {
		aborted: this.aborted,
		cacheWhitelist: this._cacheWhitelist,
		headers: this._headers,
		method: this._method,
		postParams: this._postParams,
		queryParams: this._queryParams,
		timeout: this._timeout,
		type: this._type,
		urlPath: this._urlPath,
	};
}

/**
 * Wrap superagent's end() method to create an entry in a request-local
 * data cache that will be serialized to the client and replayed in the
 * browser.
 */
Request.prototype.end = function (fn) {

	if (!fn || fn.length !== 2) {
		// a superagent requirement, as of ~v1.0; We're providing a default callback here.
		fn = (a, b) => {}; // eslint-disable-line no-unused-vars
	}

	var executeRequest = function (cb) {
		applyRequestPlugins(this);

		// set up some params
		var saRequest = buildSuperagentRequest.call(this);

		// actually execute the request via superagent
		superagent.Request.prototype.end.call(saRequest, cb);

		return this;
	}.bind(this);

	// helper, for cleaner code below
	var wrapResponseCallback = responsePluginApplyingCallback.bind(this);

	// only do caching for responses for GET requests for now
	if (this._method !== 'GET') {
		return executeRequest(wrapResponseCallback(fn));
	}

	// get cache entry for url if exists; if server-side, create one if it doesn't already exist.
	// the cache key here needs to be the same server-side and client-side, so the full URL, complete
	// with host (which can vary between client and server) is not usable. The URL path (without the
	// host) works fine though.
	var entry = this._cache.entry(this._getCacheAffectingData(), SERVER_SIDE /* createIfMissing */, this._cacheWhitelist);
	if (!SERVER_SIDE && !entry) {
		return executeRequest(wrapResponseCallback(fn));
	}

	// no previous requesters? fire the request
	if (entry.requesters === 0) {
		executeRequest(function (err, res) {
			if (err) {
				entry.setError(err);
				return;
			}
			entry.setResponse(res);
		});
	}

	entry.whenDataReady().nodeify(wrapResponseCallback(fn));

	return this;
}

// private function
function applyRequestPlugins (req) {
	// run any registered plugins
	Plugins.forRequest().asArray().forEach(function (pluginFunc) {
		pluginFunc.apply(null, [req]);
	})
}

// private function; called with a Request instance bound to
// `this`
function responsePluginApplyingCallback(cb) {
	// partly pedantic, partly so the code in the wrapped callback
	// is shorter; saving plugins here guarantees that plugins added
	// *after* the request is made, but *before* the response comes
	// aren't called for this particular request
	var thisReq = this;
	var plugins = Plugins.forResponse().asArray();
	return function (err, res) {
		plugins.forEach(function (pluginFunc) {
			pluginFunc.apply(null, [err, res, thisReq]);
		});
		cb(err, res);
	}
}

// private function; called with a Request instance bound
// to `this`
function buildSuperagentRequest() {
	var req = superagent(this._method, this._buildUrl());

	if (this._agent){
		req.agent(this._agent);
	}

	req.set(this._headers);

	this._queryParams.forEach(params => req.query(params));

	var postParams = this._postParams;

	// convert params to FormData if the request type is form-data
	if (this._type === "form-data") {
		if (!SERVER_SIDE) {
			var formData = new FormData();
			if (postParams) {
				var paramKeys = Object.keys(postParams);
				paramKeys.forEach(key => {
					formData.append(key, postParams[key]);
				});
			}
			postParams = formData;
		} else {
			throw new Error(`ReactServerAgent.type("form-data") not allowed server-side`);
		}
	}

	// query parameters exist if there are more than one set
	// post parameters exist if the value is not null
	const hasQueryParams = (this._queryParams.length > 0),
		hasPostParams = (this._postParams !== null);

	if (hasPostParams) {
		// superagent has some weird, implicit file upload support
		// that only works if you don't set `type`.
		if (this._type && this._type !== 'form-data') {
			req.type(this._type);
		}

		req.send(postParams);
	}

	switch (this._method) {
		case 'GET':
		case 'HEAD':
			if (hasPostParams) {
				logger.warning(`Attempting a ${this._method} request with POST data (using SuperAgent's .send() function). This might result in a CORS preflight request`);
			}
			break;

		case 'POST':
		case 'PATCH':
		case 'PUT':
			if (hasQueryParams) {
				logger.info(`Attempting a ${this._method} request with query data (using SuperAgent's .query() function). This might not be what you want.`);
			}
			break;
	}

	if (this._timeout) {
		req.timeout(this._timeout);
	}

	// cache the internal request, so that we can cancel it
	// if necessary (see: `abort()`)
	this._superagentReq = req;

	return req;
}

Request.prototype._buildUrl = function () {
	// only modify relative paths
	if (this._urlPrefix && this._urlPath.charAt(0) === '/') {
		return this._urlPrefix + this._urlPath;
	}
	return this._urlPath;
}

Request.prototype._getCacheAffectingData = function () {
	return {
		urlPath: this._urlPath,
		method: this._method,
		queryParams: this._queryParams,
		postParams: this._postParams,
		// headers: this._headers, // headers are not included
		type: this._type,
	};
}

Request.prototype.getProtocol = function(){

	// Returns undefined if no protocol found.
	return (this._buildUrl().match(/^(.+?):/)||[])[1];
}

/**
 * Convenience method to treat the request as then-able (promise-like).
 * This is shorthand for the simple case. If you want access to the full
 * power of the underlying promise library, use `Request.asPromise()`
 */
Request.prototype.then = function (/*arguments*/) {
	var promise = this.asPromise();
	return promise.then.apply(promise, arguments);
};

/**
 * Convenience method wrapping `.end()` and returning a promise
 * that is resolved if the request is successful, and rejected if
 * the request results in an error.
 */
Request.prototype.asPromise = function () {
	var dfd = Q.defer();
	dfd.promise.catch(logRequestError.bind(this));
	this.end(dfd.makeNodeResolver());
	return dfd.promise;
}

// private method; 'this' bound to request object
function logRequestError(err) {

	var {response} = err;
	if (!response) {
		logger.warning(`ReactServerAgent raised exception for URL ${this._urlPath}`, err);
	} else if (response.notFound) {
		// 404? don't care about response
		logger.warning(`Resource not found on server: ${this._urlPath}`);
	} else if (response.serverError) {
		logger.warning(`Received server error for URL ${this._urlPath}`, err);
	} else {
		logger.warning(`Unexpected status code returned for URL ${this._urlPath}`, err);
	}
}

/**
 * Overriding superagent use() function to give a more descriptive
 * error message than just not including it altogether.
 */
Request.prototype.use = function () {
	throw new Error(`use() function is superseded by plugRequest(...)`);
}

/**
 * Get/Set the prefix used for relative URLs
 */
Request.prototype.urlPrefix = function (urlPrefix) {
	if (typeof urlPrefix === 'undefined') {
		return this._urlPrefix;
	}
	this._urlPrefix = urlPrefix;
	return this;
}

/**
 * Abort the active request. Passes through to superagent's
 * `abort()` method. Sets 'aborted' flag on this request
 */
Request.prototype.abort = function () {
	if (this._superagentReq) {
		this.aborted = true;
		this._superagentReq.abort();
	}
	return this;
}

/**
 * Enables saving the 'header' property in the response cache.
 * This is disabled by default to save space in the cache.
 */
Request.prototype.withHeaderInResponse = function () {
	if (typeof this._cacheWhitelist === 'undefined') {
		this._cacheWhitelist = [];
	}
	this._cacheWhitelist.push('header');
	return this;
}

module.exports = Request;

redpajama_set_name: RedPajamaGithub


text:
'use strict';

var Block = require("./blocks/block"),
    Actor = require("./blocks/actor");

module.exports = GameConfiguration;

/**
 * Game Global Configuration
 *
 * @param {Object} conf Configuration
 */
function GameConfiguration(conf){
  this.parseConf(conf);
}

/**
 * Parse game configuration
 * @param  {Object} conf Configuration
 * @return {GameConfiguration}      this
 */
GameConfiguration.prototype.parseConf = function(conf) {
  if (!conf.world || !conf.levels){
    throw new Error("Required params not provided");
  }

  this.conf = conf;

  this.world = conf.world;
  this.worldWidth = conf.world.width;
  this.worldHeight = conf.world.height;
  this.levelLength = conf.levels.length;
  this.speed = conf.world.speed;

  this.levels = [];

  // will set global configuration for each level if none is
  // provided
  conf.levels.forEach(function(l){
    var newLevel = {
          actor: undefined,
          blocks: [],
          exit: undefined
        },
        a = l.actor[0],
        e = l.exit[0];

    newLevel.actor = {
      x: a.x,
      y: a.y,
      width: a.width || conf.world.actor.width,
      height: a.height || conf.world.actor.height,
      color: a.color || conf.world.actor.color
    };

    newLevel.exit = new Block({
      x: e.x,
      y: e.y,
      width: e.width || conf.world.exit.width,
      height: e.height || conf.world.exit.height,
      color: e.color || conf.world.exit.color
    });

    l.blocks.forEach(function(b){
      newLevel.blocks.push(new Block({
        x: b.x,
        y: b.y,
        width: b.width || conf.world.blocks.width,
        height: b.height || conf.world.blocks.height,
        color: b.color || conf.world.blocks.color
      }));
    });

    this.levels.push(newLevel);
  }.bind(this));
  return this;
};

/**
 * Get level configuration
 *
 * @param  {Number} level Level
 * @return {Object}       Level configuration
 */
GameConfiguration.prototype.getLevel = function(level) {
  return this.levels[level-1];
};

/**
 * Create actor based on level's configuration
 *
 * @param  {Number} level Level
 * @return {Actor}       The actor for this level
 */
GameConfiguration.prototype.createActor = function(level) {
  var levelConf = this.levels[level-1];

  return new Actor(levelConf.actor);
};


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="HtmlNoScript.cs" company="">
//
// </copyright>
//
//   The html div.
//
// --------------------------------------------------------------------------------------------------------------------
namespace UX.Testing.Core.Controls
{
	/// The html div.
	public class HtmlNoScript : HtmlControl
	{
		#region Public Properties

		/// Gets the html tag.
		public override HtmlTag HtmlTag
		{
			get
			{
				return HtmlTag.noscript;
			}
		}

		#endregion
	}
}


text:
/**
 * A menu object. This is the container to which you may add {@link Ext.menu.Item menu items}.
 *
 * Menus may contain either {@link Ext.menu.Item menu items}, or general {@link Ext.Component Components}.
 * Menus may also contain {@link Ext.panel.Panel#dockedItems docked items} because it extends {@link Ext.panel.Panel}.
 *
 * By default, non {@link Ext.menu.Item menu items} are indented so that they line up with the text of menu items. clearing
 * the icon column. To make a contained general {@link Ext.Component Component} left aligned configure the child
 * Component with `indent: false.
 *
 * By default, Menus are absolutely positioned, floating Components. By configuring a Menu with `{@link #floating}: false`,
 * a Menu may be used as a child of a {@link Ext.container.Container Container}.
 *
 *     @example
 *     Ext.create('Ext.menu.Menu', {
 *         width: 100,
 *         margin: '0 0 10 0',
 *         floating: false,  // usually you want this set to True (default)
 *         renderTo: Ext.getBody(),  // usually rendered by it's containing component
 *         items: [{
 *             text: 'regular item 1'
 *         },{
 *             text: 'regular item 2'
 *         },{
 *             text: 'regular item 3'
 *         }]
 *     });
 *
 *     Ext.create('Ext.menu.Menu', {
 *         width: 100,
 *         plain: true,
 *         floating: false,  // usually you want this set to True (default)
 *         renderTo: Ext.getBody(),  // usually rendered by it's containing component
 *         items: [{
 *             text: 'plain item 1'
 *         },{
 *             text: 'plain item 2'
 *         },{
 *             text: 'plain item 3'
 *         }]
 *     });
 */
Ext.define('Ext.menu.Menu', {
    extend: 'Ext.panel.Panel',
    alias: 'widget.menu',
    requires: [
        'Ext.layout.container.VBox',
        'Ext.menu.CheckItem',
        'Ext.menu.Item',
        'Ext.menu.Manager',
        'Ext.menu.Separator'
    ],

    mixins: [
        'Ext.util.FocusableContainer'
    ],

    /**
     * @property {Ext.menu.Menu} parentMenu
     * The parent Menu of this Menu.
     */

    /**
     * @cfg {Boolean} [enableKeyNav=true]
     * @deprecated 5.1.0 Intra-menu key navigation is always enabled.
     */
    enableKeyNav: true,

    /**
     * @cfg {Boolean} [allowOtherMenus=false]
     * True to allow multiple menus to be displayed at the same time.
     */
    allowOtherMenus: false,

    /**
     * @cfg {String} ariaRole
     * @private
     */
    ariaRole: 'menu',

    /**
     * @cfg {Boolean} autoRender
     * Floating is true, so autoRender always happens.
     * @private
     */

    /**
     * @cfg {Boolean} [floating=true]
     * A Menu configured as `floating: true` (the default) will be rendered as an absolutely positioned,
     * {@link Ext.Component#floating floating} {@link Ext.Component Component}. If configured as `floating: false`, the Menu may be
     * used as a child item of another {@link Ext.container.Container Container}.
     */
    floating: true,

    /**
     * @cfg {Boolean} constrain
     * Menus are constrained to the document body by default.
     * @private
     */
    constrain: true,

    /**
     * @cfg {Boolean} [hidden]
     * True to initially render the Menu as hidden, requiring to be shown manually.
     *
     * Defaults to `true` when `floating: true`, and defaults to `false` when `floating: false`.
     */
    hidden: true,

    hideMode: 'visibility',

    /**
     * @cfg {Boolean} [ignoreParentClicks=false]
     * True to ignore clicks on any item in this menu that is a parent item (displays a submenu)
     * so that the submenu is not dismissed when clicking the parent item.
     */
    ignoreParentClicks: false,

    /**
     * @property {Boolean} isMenu
     * `true` in this class to identify an object as an instantiated Menu, or subclass thereof.
     */
    isMenu: true,

    /**
     * @cfg {Ext.enums.Layout/Object} layout
     * @private
     */

    /**
     * @cfg {Boolean} [showSeparator=true]
     * True to show the icon separator.
     */
    showSeparator : true,

    /**
     * @cfg {Number} [minWidth=120]
     * The minimum width of the Menu. The default minWidth only applies when the {@link #floating} config is true.
     */
    minWidth: undefined,

    defaultMinWidth: 120,

    /**
     * @cfg {String} [defaultAlign="tl-bl?"]
     * The default {@link Ext.util.Positionable#getAlignToXY Ext.dom.Element#getAlignToXY} anchor position value for this menu
     * relative to its owner. Used in conjunction with {@link #showBy}.
     */
    defaultAlign: 'tl-bl?',

    /**
     * @cfg {Boolean} [plain=false]
     * True to remove the incised line down the left side of the menu and to not indent general Component items.
     *
     * {@link Ext.menu.Item MenuItem}s will *always* have space at their start for an icon. With the `plain` setting,
     * non {@link Ext.menu.Item MenuItem} child components will not be indented to line up.
     *
     * Basically, `plain:true` makes a Menu behave more like a regular {@link Ext.layout.container.HBox HBox layout}
     * {@link Ext.panel.Panel Panel} which just has the same background as a Menu.
     *
     * See also the {@link #showSeparator} config.
     */

    focusOnToFront: false,
    bringParentToFront: false,

    defaultFocus: ':focusable',

    // private
    baseCls: Ext.baseCSSPrefix + 'menu',
    _iconSeparatorCls: Ext.baseCSSPrefix + 'menu-icon-separator',
    _itemCmpCls: Ext.baseCSSPrefix + 'menu-item-cmp',

    /**
     * @event click
     * Fires when this menu is clicked
     * @param {Ext.menu.Menu} menu The menu which has been clicked
     * @param {Ext.Component} item The menu item that was clicked. `undefined` if not applicable.
     * @param {Ext.event.Event} e The underlying {@link Ext.event.Event}.
     */

    /**
     * @event mouseenter
     * Fires when the mouse enters this menu
     * @param {Ext.menu.Menu} menu The menu
     * @param {Ext.event.Event} e The underlying {@link Ext.event.Event}
     */

    /**
     * @event mouseleave
     * Fires when the mouse leaves this menu
     * @param {Ext.menu.Menu} menu The menu
     * @param {Ext.event.Event} e The underlying {@link Ext.event.Event}
     */

    /**
     * @event mouseover
     * Fires when the mouse is hovering over this menu
     * @param {Ext.menu.Menu} menu The menu
     * @param {Ext.Component} item The menu item that the mouse is over. `undefined` if not applicable.
     * @param {Ext.event.Event} e The underlying {@link Ext.event.Event}
     */

    layout: {
        type: 'vbox',
        align: 'stretchmax',
        overflowHandler: 'Scroller'
    },

    initComponent: function() {
        var me = this,
            cls = [Ext.baseCSSPrefix + 'menu'],
            bodyCls = me.bodyCls ? [me.bodyCls] : [],
            isFloating = me.floating !== false;

        // Menu classes
        if (me.plain) {
            cls.push(Ext.baseCSSPrefix + 'menu-plain');
        }
        me.cls = cls.join(' ');

        // Menu body classes
        bodyCls.push(Ext.baseCSSPrefix + 'menu-body', Ext.dom.Element.unselectableCls);
        me.bodyCls = bodyCls.join(' ');

        if (isFloating)  {
            // only apply the minWidth when we're floating & one hasn't already been set
            if (me.minWidth === undefined) {
                me.minWidth = me.defaultMinWidth;
            }
        } else {
            // hidden defaults to false if floating is configured as false
            me.hidden = !!me.initialConfig.hidden;
            me.constrain = false;
        }

        me.callParent(arguments);

        // Configure items prior to render with special classes to align
        // non MenuItem child components with their MenuItem siblings.
        Ext.override(me.getLayout(), {
            configureItem: me.configureItem
        });
    },

    // Private implementation for Menus. They are a special case, in that in the vast majority
    // (nearly all?) of use cases they shouldn't be constrained to anything other than the viewport.
    // See EXTJS-13596.
    initFloatConstrain: Ext.emptyFn,

    // As menus are never contained, a Menu's visibility only ever depends upon its own hidden state.
    // Ignore hiddenness from the ancestor hierarchy, override it with local hidden state.
    getInherited: function() {
        var result = this.callParent();
        result.hidden = this.hidden;
        return result;
    },

    beforeRender: function() {
        this.callParent(arguments);

        // Menus are usually floating: true, which means they shrink wrap their items.
        // However, when they are contained, and not auto sized, we must stretch the items.
        if (!this.getSizeModel().width.shrinkWrap) {
            this.layout.align = 'stretch';
        }
    },

    onBoxReady: function() {
        var me = this,
            listeners = {
                click: me.onClick,
                mouseover: me.onMouseOver,
                scope: me
            },
            iconSeparatorCls = me._iconSeparatorCls;

        if (Ext.supports.Touch) {
            listeners.pointerdown = me.onMouseOver;
        }

        // Handle character shotrcuts
        me.focusableKeyNav.map.addBinding([{
            key: 27,
            handler: me.onEscapeKey,
            scope: me
        }, {
            key: /[\w]/,
            handler: me.onShortcutKey,
            scope: me,
            shift: false,
            ctrl: false,
            alt: false
        }]);

        me.callParent(arguments);

        // TODO: Move this to a subTemplate When we support them in the future
        if (me.showSeparator) {
            me.iconSepEl = me.body.insertFirst({
                role: 'presentation',
                cls: iconSeparatorCls + ' ' + iconSeparatorCls + '-' + me.ui,
                html: ' '
            });
        }

        me.mon(me.el, listeners);

        // Modern IE browsers have click events translated to PointerEvents, and b/c of this the
        // event isn't being canceled like it needs to be. So, we need to add an extra listener.
        if (Ext.supports.MSPointerEvents || Ext.supports.PointerEvents) {
            me.mon(me.el, {
                scope: me,
                click: me.preventClick,
                translate: false
            });
        }

        me.mouseMonitor = me.el.monitorMouseLeave(100, me.onMouseLeave, me);
    },

    onFocusLeave: function(e) {
        var me = this;

        me.callParent([e]);
        me.mixins.focusablecontainer.onFocusLeave.call(me, e);
        me.hide();
    },

    /**
     * Returns whether a menu item can be activated or not.
     * @return {Boolean}
     */
    canActivateItem: function(item) {
        return item && item.isFocusable();
    },

    /**
     * Deactivates the current active item on the menu, if one exists.
     */
    deactivateActiveItem: function() {
        var me = this,
            activeItem = me.lastFocusedChild;

        if (activeItem) {
            activeItem.blur();
        }
    },

    // @private
    getItemFromEvent: function(e) {
        var me = this,
            renderTarget = me.layout.getRenderTarget().dom,
            toEl = e.getTarget();

        // See which top level element the event is in and find its owning Component.
        while (toEl.parentNode !== renderTarget) {
            toEl = toEl.parentNode;
            if (!toEl) {
                return;
            }
        }
        return Ext.getCmp(toEl.id);
    },

    lookupComponent: function(cmp) {
        var me = this;

        if (typeof cmp === 'string') {
            cmp = me.lookupItemFromString(cmp);
        } else if (Ext.isObject(cmp)) {
            cmp = me.lookupItemFromObject(cmp);
        }

        // Apply our minWidth to all of our non-docked child components (Menu extends Panel)
        // so it's accounted for in our VBox layout
        if (!cmp.dock) {
            cmp.minWidth = cmp.minWidth || me.minWidth;
        }

        return cmp;
    },

    // @private
    lookupItemFromObject: function(cmp) {
        var me = this;

        if (!cmp.isComponent) {
            if (!cmp.xtype) {
                cmp = Ext.create('Ext.menu.' + (Ext.isBoolean(cmp.checked) ? 'Check': '') + 'Item', cmp);
            } else {
                cmp = Ext.ComponentManager.create(cmp, cmp.xtype);
            }
        }

        if (cmp.isMenuItem) {
            cmp.parentMenu = me;
        }

        return cmp;
    },

    // @private
    lookupItemFromString: function(cmp) {
        return (cmp === 'separator' || cmp === '-') ?
            new Ext.menu.Separator()
            : new Ext.menu.Item({
                canActivate: false,
                hideOnClick: false,
                plain: true,
                text: cmp
            });
    },

    // Override applied to the Menu's layout. Runs in the context of the layout.
    // Add special classes to allow non MenuItem components to coexist with MenuItems.
    // If there is only *one* child, then this Menu is just a vehicle for floating
    // and aligning the component, so do not do this.
    configureItem: function(cmp) {
        var me = this.owner,
            prefix = Ext.baseCSSPrefix,
            ui = me.ui,
            cls, cmpCls;

        if (cmp.isMenuItem) {
            cmp.setUI(ui);
        } else if (me.items.getCount() > 1 && !cmp.rendered && !cmp.dock) {
            cmpCls = me._itemCmpCls;
            cls = [cmpCls + ' ' + cmpCls + '-' + ui];

            // The "plain" setting means that the menu does not look so much like a menu. It's more like a grey Panel.
            // So it has no vertical separator.
            // Plain menus also will not indent non MenuItem components; there is nothing to indent them to the right of.
            if (!me.plain && (cmp.indent !== false || cmp.iconCls === 'no-icon')) {
                cls.push(prefix + 'menu-item-indent-' + ui);
            }

            if (cmp.rendered) {
                cmp.el.addCls(cls);
            } else {
                cmp.cls = (cmp.cls || '') + ' ' + cls.join(' ');
            }
            // So we can clean the item if it gets removed.
            cmp.$extraMenuCls = cls;
        }

        // @noOptimize.callParent
        this.callParent(arguments);
    },

    onRemove: function(cmp) {
        this.callParent([cmp]);

        // Remove any extra classes we added to non-MenuItem child items
        if (!cmp.isDestroyed && cmp.$extraMenuCls) {
            cmp.el.removeCls(cmp.$extraMenuCls);
        }
    },

    onClick: function(e) {
        var me = this,
            type = e.type,
            item,
            clickResult,
            iskeyEvent = type === 'keydown';

        if (me.disabled) {
            e.stopEvent();
            return;
        }

        item = me.getItemFromEvent(e);
        if (item && item.isMenuItem) {
            if (!item.menu || !me.ignoreParentClicks) {
                clickResult = item.onClick(e);
            } else {
                e.stopEvent();
            }

            // SPACE and ENTER invokes the menu
            if (item.menu && clickResult !== false && iskeyEvent) {
                item.expandMenu(e, 0);
            }
        }
        // Click event may be fired without an item, so we need a second check
        if (!item || item.disabled) {
            item = undefined;
        }
        me.fireEvent('click', me, item, e);
    },

    onDestroy: function() {
        var me = this;

        me.parentMenu = me.ownerCmp = null;
        if (me.rendered) {
            me.el.un(me.mouseMonitor);
            Ext.destroy(me.iconSepEl);
        }
        me.callParent(arguments);
    },

    onMouseLeave: function(e) {
        if (this.disabled) {
            return;
        }
        this.fireEvent('mouseleave', this, e);
    },

    onMouseOver: function(e) {
        var me = this,
            fromEl = e.getRelatedTarget(),
            mouseEnter = !me.el.contains(fromEl),
            item = me.getItemFromEvent(e),
            parentMenu = me.parentMenu,
            ownerCmp = me.ownerCmp;

        if (mouseEnter && parentMenu) {
            parentMenu.setActiveItem(ownerCmp);
            ownerCmp.cancelDeferHide();
            parentMenu.mouseMonitor.mouseenter();
        }

        if (me.disabled) {
            return;
        }

        // Do not activate the item if the mouseover was within the item, and it's already active
        if (item) {
            if (!item.containsFocus) {
                item.focus();
            }
            if (item.expandMenu) {
                item.expandMenu(e);
            }
        }
        if (mouseEnter) {
            me.fireEvent('mouseenter', me, e);
        }
        me.fireEvent('mouseover', me, item, e);
    },

    setActiveItem: function(item) {
        var me = this;

        if (item && (item !== me.lastFocusedChild)) {
            me.focusChild(item, 1);
            // Focusing will scroll the item into view.
        }
    },

    onEscapeKey: function() {
        if (this.floating) {
            this.hide();
        }
    },

    onShortcutKey: function(keyCode, e) {
        var shortcutChar = String.fromCharCode(e.getCharCode()),
            items = this.query('>[text]'),
            len = items.length,
            item = this.lastFocusedChild,
            focusIndex = Ext.Array.indexOf(items, item),
            i = focusIndex;

        // Loop through all items which have a text property starting at the one after the current focus.
        for (;;) {
            if (++i === len) {
                i = 0;
            }
            item = items[i];

            // Looped back to start - no matches
            if (i === focusIndex) {
                return;
            }

            // Found a text match
            if (item.text && item.text[0].toUpperCase() === shortcutChar) {
                item.focus();
                return;
            }
        }
    },

    // Tabbing in a floating menu must hide, but not move focus.
    // onHide takes care of moving focus back to an owner Component.
    onFocusableContainerTabKey: function(e) {
        if (this.floating) {
            this.hide();
        }
    },

    onFocusableContainerEnterKey: function(e) {
        this.onClick(e);
    },

    onFocusableContainerSpaceKey: function(e) {
        this.onClick(e);
    },

    onFocusableContainerLeftKey: function(e) {
        // If we are a submenu, then left arrow focuses the owning MenuItem
        if (this.parentMenu) {
            this.ownerCmp.focus();
            this.hide();
        }
    },

    onFocusableContainerRightKey: function(e) {
        var me = this,
            focusItem = me.lastFocusedChild;

        if (focusItem && focusItem.expandMenu) {
            focusItem.expandMenu(e, 0);
        }
    },

    beforeShow: function() {
        var me = this,
            activeEl,
            viewHeight;

        // Constrain the height to the containing element's viewable area
        if (me.floating) {

            // Only register a focusAnchor to return to on hide if the active element is not the document
            // If there's no focusAnchor, we return to the ownerCmp, or first focusable ancestor.
            activeEl = Ext.Element.getActiveElement();
            me.focusAnchor = activeEl === document.body ? null : activeEl;

            me.savedMaxHeight = me.maxHeight;
            viewHeight = me.container.getViewSize().height;
            me.maxHeight = Math.min(me.maxHeight || viewHeight, viewHeight);
        }

        me.callParent(arguments);

        // Add a touch start listener to check for taps outside the menu.
        // iOS in particular does not trigger blur on document tap, so
        // we have to check for taps outside this menu.
        if (Ext.supports.Touch) {
            me.tapListener = Ext.getBody().on({
                touchstart: me.onBodyTap,
                scope: me,
                destroyable: true
            });
        }
    },

    onBodyTap: function(e) {
        // Tap outside of this menu tree - hide.
        if (!this.owns(e)) {
            this.tapListener.destroy();
            this.hide();
        }
    },

    afterShow: function() {
        var me = this;

        me.callParent(arguments);

        // Restore configured maxHeight
        if (me.floating && me.autoFocus) {
            me.maxHeight = me.savedMaxHeight;
            me.focus();
        }
    },

    onHide: function(animateTarget, cb, scope) {
        var me = this,
            focusTarget;

         // If we contain focus just before element hide, move it elsewhere before hiding
        if (me.el.contains(Ext.Element.getActiveElement())) {
            // focusAnchor was the active element before this menu was shown.
            focusTarget = me.focusAnchor || me.ownerCmp || me.up(':focusable');

            // Component hide processing will focus the "previousFocus" element.
            if (focusTarget) {
                me.previousFocus = focusTarget;
            }
        }
        this.callParent([animateTarget, cb, scope]);
    },

    preventClick: function (e) {
        if (!this.getItemFromEvent(e).href) {
            e.preventDefault();
        }
    }
});


text:
define({
  "chartSettingLabel": "Postavke grafikona",
  "addNewLabel": "Dodaj novi",
  "generalSettingLabel": "Opšte postavke",
  "searchSourceSettingLabel": "Postavke pretrage izvora",
  "layerChooser": {
    "title": "Izaberite sloj za grafikon",
    "selectPolygonLayerLabel": "Izaberite sloj",
    "selectPolygonLayerHintText": "Napomena: ako konfigurišete nekoliko grafikona, slojevi moraju da budu istog geometrijskog tipa",
    "selectRelatedTableLayerLabel": "Izaberite tabelu povezanu sa slojem",
    "selectRelatedTableLayerHintText": "Napomena: samo tabele sa numeričkim poljima su prikazane",
    "errorInSelectingPolygonLayer": "Izaberite sloj koji ima povezan sloj tačke.",
    "errorInSelectingRelatedLayer": "Izaberite važeći povezan sloj/važeću povezanu tabelu za sloj.",
    "polygonLayerNotHavingRelationships": "Izabrani sloj ne mora da bude povezan sa tabelom/slojem."
  },
  "ChartSetting": {
    "sectionTitle": "Odeljak naslova",
    "sectionTitleHintText": "Napomena: prikazuje se u odeljku naslova zaglavlja",
    "chartTitle": "Naslov grafikona",
    "chartTitleHintText": "Napomena: prikazuje se centrirano na vrhu grafikona",
    "chartDescription": "Opis",
    "chartDescriptionHintText": "Napomena: prikazuje se ispod grafikona",
    "chartType": "Tip grafikona",
    "barChart": "Trakasti grafikon",
    "pieChart": "Kružni grafikon",
    "polarChart": "Polarni grafikon",
    "lineChart": "Linijski grafikon",
    "dataSeriesField": "Polje serije podataka",
    "lineDataSeriesField": "Polje vrednosti",
    "labelField": "Polje oznake",
    "lineLabelSeriesField": "Polje redosleda",
    "chartColor": "Boja grafikona",
    "singleColor": "Jedna boja",
    "colorByTheme": "Oboji po temi",
    "colorByFieldValue": "Oboji po vrednostima polja",
    "xAxisTitle": "Naslov X ose",
    "xAxisHintText": "Napomena: naslov X ose",
    "yAxisTitle": "Naslov Y ose",
    "yAxisHintText": "Napomena: naslov Y ose",
    "fieldColorLabel": "Oznaka",
    "fieldColorColor": "Boja",
    "defaultFieldSelectLabel": "Izaberi",
    "errMsgFieldValuesNotFound": "Pronalaženje vrednosti za izabrana polja nije moguće",
    "errMsgSectionTitle": "Unesite naslov odeljka",
    "errMsgFieldByValue": "Izaberite boju po vrednost polja",
    "errMsgDataSeriesField": "Izaberite polje vrednosti",
    "settingTabTitle": "Postavka",
    "layoutTabTitle": "Raspored",
    "polarChartSelectFieldsHintText": "Napomena: izaberite polja da biste generisali polarni grafikon",
    "visibilityText": "Vidljivost",
    "fieldNameText": "Ime polja",
    "aliasNameText": "Alias",
    "errMsgPolarFieldsRequired": "Izaberite tri ili više polja da biste generisali polarni grafikon",
    "polarChartPolygonFillLabel": "Popuni poligon",
    "polarChartPolygonFillHintText": "Napomena: izaberite polje za potvrdu da biste prikazali punjenje poligona u polarnom grafikonu",
    "viewLayoutLabel": "Priprema za štampu",
    "setValueFields": "Postavi polja vrednosti",
    "layoutSeriesLabel": "Serija",
    "ThemeSelector": {
      "themeAdobebricks": "Čerpić",
      "themeAlgae": "Alge",
      "themeBahamation": "Bahamation",
      "themeBlueDusk": "PlaviSuton",
      "themeCubanShirts": "KubanskeKošulje",
      "themeDesert": "Pustinja",
      "themeDistinctive": "Osobeno",
      "themeDollar": "Dolar",
      "themeGrasshopper": "Skakavac",
      "themeGrasslands": "Pašnjaci",
      "themeGreySkies": "SivaNeba",
      "themeHarmony": "Harmonija",
      "themeIndigoNation": "IndigoNarod",
      "themeIreland": "Irska",
      "themeMiamiNice": "MajamiFino",
      "themeMinty": "Minti",
      "themePurpleRain": "GrimiznaKiša",
      "themeRoyalPurples": "KraljevskiGrimizne",
      "themeSageToLime": "ŽalfijaDoLimuna",
      "themeTufte": "Tufte",
      "themeWatersEdge": "RubVode",
      "themeWetlandText": "Močvara",
      "themePlotKitblue": "PlotKit.blue",
      "themePlotKitcyan": "PlotKit.cyan",
      "themePlotKitgreen": "PlotKit.green",
      "themePlotKitorange": "PlotKit.orange",
      "themePlotKitpurple": "PlotKit.purple",
      "themePlotKitred": "PlotKit.red"
    }
  },
  "GeneralSetting": {
    "legendGeneralSettingText": "Opšte postavke",
    "locationSymbolLabel": "Simbol lokacije grafike",
    "locationSymbolHintText": "Napomena: koristi se za prikazivanje simbola adrese i lokacije na koju je kliknuto",
    "refreshIntervalLabel": "Interval osvežavanja",
    "refreshIntervalHintText": "Napomena: koristi se za osvežavanje grafikona na osnovu ovog intervala. Navedite vrednost između 1 i 1440 minuta",
    "errMsgRefreshInterval": "Navedite interval osvežavanja između 0 i 1440 minuta",
    "symbolPickerPreviewText": "Pregledaj:",
    "showToolToSelectLabel": "Dugme za podešavanje lokacije",
    "showToolToSelectHintText": "Savet: Pruža dugme za postavljanje lokacije na mapi umesto postavljanja lokacije klikom na mapu"
  },
  "searchSourceSetting": {
    "searchSourceSettingTabTitle": "Pretraži postavke izvora",
    "searchSourceSettingTitle": "Pretraži postavke izvora",
    "searchSourceSettingTitleHintText": "Dodajte i konfigurišite servise za geokodiranje ili slojeve geoobjekata kao izvora pretrage. Ovi navedeni izvori određuju šta može da se pretražuje unutar trake za pretragu.",
    "addSearchSourceLabel": "Dodaj izvor pretrage",
    "featureLayerLabel": "Sloj geoobjekata",
    "geocoderLabel": "Geokoder",
    "nameTitle": "Naziv",
    "generalSettingLabel": "Opšte postavke",
    "allPlaceholderLabel": "Tekst čuvara mesta za pretragu svega:",
    "allPlaceholderHintText": "Savet: Unesite tekst koji će se prikazati kao čuvar mesta tokom pretrage svih slojeva i geokodera",
    "generalSettingCheckboxLabel": "Prikaži iskačući prozor za pronađeni geoobjekat ili lokaciju",
    "countryCode": "Kôd(ovi) zemlje ili regiona",
    "countryCodeEg": "npr. ",
    "countryCodeHint": "Ako ova vrednost ostane prazna, pretražuju se sve zemlje i regioni",
    "questionMark": "?",
    "searchInCurrentMapExtent": "Pretraži samo u trenutnom obuhvatu mape",
    "zoomScale": "Skala zumiranja",
    "locatorUrl": "URL adresa geokodera",
    "locatorName": "Ime geokodera",
    "locatorExample": "Primer",
    "locatorWarning": "Ova verzija servisa geokôdiranja nije podržana. Vidžet podržava samo servis geokôdiranja 10.0 i novije.",
    "locatorTips": "Predlozi nisu dostupni jer servis geokodiranja ne podržava predloženu mogućnost.",
    "layerSource": "Izvor sloja",
    "setLayerSource": "Postavi izvor sloja",
    "setGeocoderURL": "Postavi URL adresu geokôdera",
    "searchLayerTips": "Predlozi nisu dostupni jer servis geoobjekata ne podržava mogućnost paginacije.",
    "placeholder": "Tekst čuvara mesta",
    "searchFields": "Polja za pretragu",
    "displayField": "Prikaži polje",
    "exactMatch": "Potpuno podudaranje",
    "maxSuggestions": "Maksimalno predloga",
    "maxResults": "Maksimalno rezultata",
    "enableLocalSearch": "Omogući lokalnu pretragu",
    "minScale": "Min. razmera",
    "minScaleHint": "Kada je razmera mape veća od ove razmere, primenjuje se lokalna pretraga",
    "radius": "Poluprečnik",
    "radiusHint": "Definiše poluprečnik oblasti oko trenutnog centra mape koja se koristi za poboljšavanje rangiranja kandidata za geokodiranje kako bi se prvo vraćali kandidati najbliži lokaciji",
    "meters": "Metri",
    "setSearchFields": "Postavi polja pretrage",
    "set": "Postavi",
    "fieldName": "Naziv",
    "invalidSearchSources": "Nevažeće postavke za pretragu izvora",
    "invalidUrlTip": "URL adresa ${URL} nije validna ili nije dostupna.",
    "maxSuggestionErrorMessage": "Unesite važeću vrednost za maksimalno predloga. Vrednost je van opsega ili je nevažeća.",
    "maxResultsErrorMessage": "Unesite važeću vrednost za maksimalno rezultata. Vrednost je van opsega ili je nevažeća.",
    "zoomScaleErrorMessage": "Unesite važeću vrednost razmere zumiranja. Vrednost je van opsega ili je nevažeća.",
    "minScaleErrorMessage": "Unesite važeću vrednost min. razmere. Vrednost je van opsega ili je nevažeća.",
    "radiusErrorMessage": "Unesite važeću vrednost poluprečnika. Vrednost je van opsega ili je nevažeća."
  }
});


text:
var message = '';
var student;
var question = 'Search student records: Type a name [Jody] (or type "quit" to end)';
var response;

function print(message) {
	var div = document.getElementById('output');
	div.innerHTML = message;
}

while (true) {
	response = prompt(question);
	if (response === null || response.toLowerCase() === 'quit'){
		break;
	}

	for (var i = 0; i < students.length; i++ ) {
	student = students[i];

		if (response === student.name) {
			message += '
Student: ' + student.name + '
';
			message += '
Track: ' + student.track + '
';
			message += '
Points: ' + student.points + '
';
			message += '
Achievements: ' + student.achievements + '
';
		}
	print(message);
	}
}


text:
require 'spec_helper'

describe 'CycleAnalytics#code', feature: true do
  extend CycleAnalyticsHelpers::TestGeneration

  let(:project) { create(:project, :repository) }
  let(:from_date) { 10.days.ago }
  let(:user) { create(:user, :admin) }
  subject { CycleAnalytics.new(project, from: from_date) }

  context 'with deployment' do
    generate_cycle_analytics_spec(
      phase: :code,
      data_fn: -> (context) { { issue: context.create(:issue, project: context.project) } },
      start_time_conditions: [["issue mentioned in a commit",
                               -> (context, data) do
                                 context.create_commit_referencing_issue(data[:issue])
                               end]],
      end_time_conditions: [["merge request that closes issue is created",
                             -> (context, data) do
                               context.create_merge_request_closing_issue(data[:issue])
                             end]],
      post_fn: -> (context, data) do
        context.merge_merge_requests_closing_issue(data[:issue])
        context.deploy_master
      end)

    context "when a regular merge request (that doesn't close the issue) is created" do
      it "returns nil" do
        issue = create(:issue, project: project)

        create_commit_referencing_issue(issue)
        create_merge_request_closing_issue(issue, message: "Closes nothing")

        merge_merge_requests_closing_issue(issue)
        deploy_master

        expect(subject[:code].median).to be_nil
      end
    end
  end

  context 'without deployment' do
    generate_cycle_analytics_spec(
      phase: :code,
      data_fn: -> (context) { { issue: context.create(:issue, project: context.project) } },
      start_time_conditions: [["issue mentioned in a commit",
                               -> (context, data) do
                                 context.create_commit_referencing_issue(data[:issue])
                               end]],
      end_time_conditions: [["merge request that closes issue is created",
                             -> (context, data) do
                               context.create_merge_request_closing_issue(data[:issue])
                             end]],
      post_fn: -> (context, data) do
        context.merge_merge_requests_closing_issue(data[:issue])
      end)

    context "when a regular merge request (that doesn't close the issue) is created" do
      it "returns nil" do
        issue = create(:issue, project: project)

        create_commit_referencing_issue(issue)
        create_merge_request_closing_issue(issue, message: "Closes nothing")

        merge_merge_requests_closing_issue(issue)

        expect(subject[:code].median).to be_nil
      end
    end
  end
end


text:
import {combineReducers} from 'redux';
import mealsAppState from './meals';
import menuAppState from './menu';

const rootReducer = combineReducers({
  mealsAppState,
  menuAppState
});

export default rootReducer;


text:
package org.apache.flink.runtime.clusterframework.overlays;

import org.apache.flink.runtime.clusterframework.ContainerSpecification;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * A composite overlay that delegates to a set of inner overlays.
 */
public class CompositeContainerOverlay implements ContainerOverlay {

	private final List<ContainerOverlay> overlays;

	public CompositeContainerOverlay(ContainerOverlay... overlays) {
		this(Arrays.asList(overlays));
	}

	public CompositeContainerOverlay(List<ContainerOverlay> overlays) {
		this.overlays = Collections.unmodifiableList(overlays);
	}

	@Override
	public void configure(ContainerSpecification containerConfig) throws IOException {
		for(ContainerOverlay overlay : overlays) {
			overlay.configure(containerConfig);
		}
	}
}


text:
<!DOCTYPE html>

	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
	<meta name="viewport" content="width=device-width, initial-scale=1.0"/>

	<title>Shortener</title>

	<link rel="stylesheet" type="text/css" href="css/popup.css">
	<link type="text/css" rel="stylesheet" href="css/materialize.min.css"  media="screen,projection"/>
	<link href="css/materialdesignicons.min.css" media="all" rel="stylesheet" type="text/css" />

Oops!

It seems like you're not logged in.

Please click the button below and login into your GoDaddy account to start using the Shortener Extension.

				Login

Or enter an APIKey manually:

					<form id="manual-api-key-form" class="col s12">

								<input name="apy-key-manual-input" id="apy-key-manual-input" type="text" class="validate">
								APIKey

							Go!

Those are provided under your Account Settings at https://shortener.godaddy.com.

						</form>

					Shortener

				<form id="custom-url-form">

								<input value="Long URL" name="url" id="long-url" type="text" class="validate" required>
								Long URL

								<select id="domain-opt" name="domain">
								</select>
								Domain

								<input value="" name="code" id="custom-url" type="text" class="validate">
								Custom URL

				</form>

						Go Short!

							Shorten Another!


text:
require "spec_helper"

describe "Readme Usage" do
  README_PATH = File.expand_path("../../../README.md", __FILE__)

  def self.extract_usage_rspec
    lines = File.read(README_PATH).lines.to_a
    lineno = lines.index { |line| line =~ /^```ruby/ } + 1
    length = lines[lineno, lines.length].index { |line| line =~ /^```/ }
    [ lines[lineno, length].join, README_PATH, lineno ]
  end

  instance_eval *extract_usage_rspec
end


text:
import React, { Component } from 'react';

import PageHeader from '../pageHeader/PageHeader';

import './why.scss';

export default class Why extends Component {
  constructor(props) {
    super(props);

    this.state = {
      bodyClasses: 'col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1'
    };
  }

  render() {
    console.log('Why');
    return (

        <PageHeader heading='Why???' subHeading='Why Create Refined JS?' />

                We realized that there is a lot of information out there. A lot of information. But it's hidden and it can take days of searching
                to find solutions to a problem. Or an aggregation of data to come up with a solution to a problem.

                What if we could take the most common problems, along with their solutions and showcase them in one easy to find location?
                What if we could showcase solutions to some problems that may be harder to find because, perhaps only one other person has run into
                it or something similar? What if we could show others how to write clean, quality code in those solutions?

                That is why we created Refined Js. To present problems, take out all the clutter and noise and give clear,
                tested and quality JavaScript solutions.

                We are all apprentices in a craft where no one ever becomes a master.

                 - Ernest Hemmingway

    );
  }
}

Why.propTypes = {
};

Why.defaultProps = {
};


text:
#!/usr/bin/env node

/* eslint-disable global-require */
/* eslint-disable no-console */
/* eslint-disable no-nested-ternary */
/* eslint-disable no-process-exit */
/* eslint-disable import/no-dynamic-require */

'use strict';

(() => {
  const path = require('path');
  const composeImplementationFiles = process.argv.slice(2);
  if (!composeImplementationFiles.length) {
    console.log(`usage: ${path.basename(process.argv[1])} COMPOSE_FILE_NAMES...`);
    process.exit(1);
    // return;
  }

  const importedImplementations = composeImplementationFiles.map((file) => {
    try {
      return require(file);
    } catch (_err) {
      try {
        // eslint-disable-next-line no-param-reassign
        file = path.resolve(process.cwd(), file);
        return require(file);
      } catch (err) {
        console.error(`${err}\nFailed to read JavaScript file ${file}`);
        process.exit(1);
      }
    }
  });

  importedImplementations.forEach((imported, index) => {
    const compose =
      typeof imported === 'function'
        ? imported
        : typeof imported.default === 'function'
        ? imported.default
        : typeof imported.compose === 'function'
        ? imported.compose
        : undefined;
    if (!compose) {
      console.error(`The file ${composeImplementationFiles[index]} should export the "compose" function.`);
      process.exit(1);
      // return;
    }

    require('../')(compose).then((result) => {
      const { failures } = result;
      if (failures && failures.length > 0) {
        console.error(require('prettyjson').render(failures));
        process.exit(1);
      }
    });
  });
})();


text:
class AjaxController < ApplicationController
  def insumos_de_maquina
  	if admin_user_signed_in?
		insumos_jsoned = Maquina.find(params[:maquina_id]).insumos.map do |i|
  			{ :id => i.id, :to_s => i.to_s, :stock => i.stock }
		end
    	render :json => insumos_jsoned
	end
  end
end


text:
namespace Tweetinvi.Models
{
    /// <summary>
    /// A rectangle box area defined by two coordinates.
    /// </summary>
    public interface ILocation
    {
        /// <summary>
        /// First coordinate of the box. For simplicity use (top, left).
        /// </summary>
        ICoordinates Coordinate1 { get; set; }

        /// <summary>
        /// Second coordinate of the box. For simplicity use (bottom, right).
        /// </summary>
        ICoordinates Coordinate2 { get; set; }
    }
}


text:
package com.qihoo360.replugin.component.activity;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import com.qihoo360.i.Factory2;
import com.qihoo360.i.IPluginManager;
import com.qihoo360.replugin.RePlugin;
import com.qihoo360.replugin.helper.LogDebug;

/**
 * 若插件中的某个类是动态注册的,但是这个插件未下载,就调用此Activity做中转,
 * 解析完插件信息后,调用下载框下载插件;若解析失败,则调用 finish()
 *
 * @author RePlugin Team
 */
public class DynamicClassProxyActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ComponentName cn = getIntent().getComponent();
        if (cn != null) {

            // 获取 动态代理类名称 和 插件名称
            String dynamicClassName = cn.getClassName();
            String plugin = Factory2.getPluginByDynamicClass(dynamicClassName);

            if (LogDebug.LOG) {
                LogDebug.d("loadClass", "DynamicClassProxyActivity.onCreate(), plugin = " + plugin + ", class = " + dynamicClassName);
            }

            // 如果插件不存在,回调宿主接口。
            if (!TextUtils.isEmpty(plugin) && !RePlugin.isPluginInstalled(plugin)) {
                Intent intent = new Intent();
                intent.setComponent(new ComponentName(plugin, dynamicClassName));
                RePlugin.getConfig().getCallbacks().onPluginNotExistsForActivity(this, plugin, intent, IPluginManager.PROCESS_UI);
            }
        }

        finish();
    }
}


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using System.Threading.Tasks;

namespace Microsoft.Azure.WebJobs.Host.Bindings
{
    // Describe a constant value, commonly used for inputs.
    internal class ConstantValueProvider : IValueProvider
    {
        private object _value;
        private string _invokeString;

        public ConstantValueProvider(object value, Type type, string invokeString)
        {
            this._value = value;
            this.Type = type;
            this._invokeString = invokeString;
        }

        public Type Type { get; set; }

        public Task<object> GetValueAsync()
        {
            return Task.FromResult(_value);
        }

        public string ToInvokeString()
        {
            return _invokeString;
        }
    }
}


text:
layout: post
title: 'Software Leadership #8: Empower Bottom-Up Innovation'
date: 2014-10-10 11:38:38.000000000 -07:00
categories: []
tags: []
status: publish
type: post
published: true
meta:
  _edit_last: '1'
  _wpas_done_all: '1'
author:
  login: admin
  email: joeduffy@acm.org
  display_name: joeduffy
  first_name: ''
  last_name: ''
---
No matter how smart of a leader you are, you're going to be wrong sometimes. Often
even. And you won't always have the best ideas.

There are three reasons for this.

First, the numbers are against you.

Second, the people in your group have way more data than you possibly can. That's
not to say every person has more data -- I'm continually amazed at how much data
can be scoured and retained by some of the best leaders I've worked with -- but statistically
speaking, you'll have blind spots, and certain people will significant outmatch you
on depth every time. Memories and time being finite, and all.

Third, there are people with better ideas, who are smarter than you, in your group,
anyway.

It's critical to create an environment where the best ideas are heard, discussed,
and ultimately able to grow into things that are much bigger. Your company's next
big success could be sitting right under your nose, and in an environment where those
ideas have no voice, you lose doubly: first, you don't capitalize on the idea; and,
second, the person is likely to take their ideas elsewhere. Smart and creative people
need outlets.

I also think it's imperative to have an open mind about ideas. If you weren't the
one to have the idea, one possibility is that it's just a bad idea. Unfortunately,
too many people assume this. More likely, there's some aspect of thinking behind
it that you don't truly appreciate. Thinking about problems from different angles
is important. One trap I see time and time again is eager dismissal of an idea based
on your biases, like past experience (which may be less relevant today than it was
before), an iron grip on the strategic direction of a group (like obsessing over
"making money" when really what you need is to make some key "architectural" investments
to lay the foundation that pays off later), etc.

In some groups, the dictator model can "work." I put work in quotes because these
tend to be conservative and constrained environments where keeping innovation low
is desirable. I can't say it's anywhere I'd want to work, though.

The worst thing leaders can do is to embellish the dictator model. It can happen
subtly and innocuously, and worse, slowly over time. Naturally, as a leader, you
want to delegate decision-making. But it's critical to keep the pulse of the organization
to ensure that every single decision and/or idea wasn't generated in some top down
manner. If that happens, it's a sign that some deeper cultural problem is afoot.
Too many high-level managers care more about the "what" than the "how"; how a team
works -- collaborating, generating ideas, engineering culture -- is even more important
than what it is building, because a healthy culture ensures success not just in the
current project, but also equips the team to tackle future projects with agility.

Don't confuse this with other models that appear dictatorial in nature, like Steve
Jobs at Apple, and Bill Gates in the early days of Microsoft. That model can work
well, which is having a person who is on the lookout to ensure everything the company
does is as best as it can, consistent, and delivers in line with the strategy of
an organization. Steve Jobs was incredibly open to ideas, and in fact that fueled
Apple in a big way, even though he was quick to tear up the bad ones (and, I'm sure,
a few good ones along the way). Having bottom-up innovation doesn't mean anybody
does whatever they want, but it does mean every idea gets its fair day in court.
Google and Facebook get this.

If you want some further related insights, I'd recommend watching [this Bill Gates
interview](https://www.youtube.com/watch?v=8bOSQKgKkLo), and reading [Eric Schmidt's
How Google Works](http://www.amazon.com/How-Google-Works-Eric-Schmidt-ebook/dp/B00HUU13Y0/bluebytesoftw-20)
book.


text:
ObjectRocket Elasticsearch FAQ
--------------------------------

How do I connect?
~~~~~~~~~~~~~~~~~

You can connect via Elasticsearch's RESTful API over HTTP/HTTPS or the transport client library for Java API access.

Is SSL supported?
~~~~~~~~~~~~~~~~~

Yes! By using the SSL connection string provided, we handle everything you need for SSL access using standard https:// links.

Can I setup multiple user types?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Yes, we currently offer admin, read only and Kibana only user roles through the Control Panel.

Is there a free trial?
~~~~~~~~~~~~~~~~~~~~~~

Yes! Choosing the 256MB RAM / 2GB Disk instance will be free for the first 30 days.

What other sizes are available?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Check out our `plans and pricing <http://www.objectrocket.com/pricing>`_, and click on **Elasticsearch**!

What versions are supported?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

We currently default to **1.7.3** and offer **2.0.0** via our Early Access program, but please contact `support@objectrocket.com <mailto:support@objectrocket.com>`_ if you need something different!

What kind of architecture is this using?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

When you build an ObjectRocket Elasticsearch instance, you get a cluster with a total of 11 nodes. We automatically configure 4 front-end client nodes, 2 Kibana nodes, 3 master nodes, and 2 data nodes. All nodes are containerized, which provides guaranteed resources (memory, CPU, disk I/O), prevents "noisy-neighbor" problems, and eliminates the performance bottlenecks of traditional hardware virtualization.

How much does ObjectRocket Elasticsearch cost per month?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The monthly cost of our ObjectRocket Elasticsearch instances are based on the plan size of the data nodes and the number of data nodes in the cluster.  Client, Kibana, and master nodes are included at no additional charge.

What plugins are available by default?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

We install both `ElasticHQ <http://www.elastichq.org/>`_ and `elasticsearch-head <http://mobz.github.io/elasticsearch-head/>`_ by default in their default locations (``/_plugin/HQ and /_plugin/head``).

We can support other 3rd party plugins on a case by case basis.  Contact `support@objectrocket.com <mailto:support@objectrocket.com>`_ if you would like different plugins installed or if you would like us to disable them all.

What about backups?
~~~~~~~~~~~~~~~~~~~

We automatically backup your data every 24 hours using Elasticsearch snapshots.  Contact `support@objectrocket.com <mailto:support@objectrocket.com>`_ to request a restore.

What are the default number of shards and replicas per index?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

ObjectRocket Elasticsearch instances are configured with the standard Elasticsearch default settings of ``number_of_shards = 5`` and ``number_of_replicas = 1``, which means any newly created index will have 5 primary shards, each with 1 replica shard (for a total of 10 shards for any new index). The number of primary shards can be specified per index when the index is created, as described in the `Create Index API <https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html>`_. If you would like to change these defaults for your ObjectRocket Elasticsearch instance, please contact `support@objectrocket.com <mailto:support@objectrocket.com>`_.


text:
namespace test {
namespace {

// Wraps a PermissionRequest so that it can pass a closure to itself to the
// PermissionRequest constructor. Without this wrapper, there's no way to
// handle all destruction paths.
class TestPermissionRequestOwner {
 public:
  explicit TestPermissionRequestOwner(permissions::RequestType type) {
    const bool user_gesture = true;
    auto decided = [](ContentSetting, bool, bool) {};
    request_ = std::make_unique<permissions::PermissionRequest>(
        GURL("https://example.com"), type, user_gesture,
        base::BindRepeating(decided),
        base::BindOnce(&TestPermissionRequestOwner::DeleteThis,
                       base::Unretained(this)));
  }

  TestPermissionRequestOwner(const TestPermissionRequestOwner&) = delete;
  TestPermissionRequestOwner& operator=(const TestPermissionRequestOwner&) =
      delete;

  permissions::PermissionRequest* request() { return request_.get(); }

 private:
  void DeleteThis() { delete this; }

  std::unique_ptr<permissions::PermissionRequest> request_;
};

}  // namespace

PermissionRequestManagerTestApi::PermissionRequestManagerTestApi(
    permissions::PermissionRequestManager* manager)
    : manager_(manager) {}

PermissionRequestManagerTestApi::PermissionRequestManagerTestApi(
    Browser* browser)
    : PermissionRequestManagerTestApi(
          permissions::PermissionRequestManager::FromWebContents(
              browser->tab_strip_model()->GetActiveWebContents())) {}

void PermissionRequestManagerTestApi::AddSimpleRequest(
    content::RenderFrameHost* source_frame,
    permissions::RequestType type) {
  TestPermissionRequestOwner* request_owner =
      new TestPermissionRequestOwner(type);
  manager_->AddRequest(source_frame, request_owner->request());
}

views::Widget* PermissionRequestManagerTestApi::GetPromptWindow() {
  PermissionPromptDesktop* prompt =
      static_cast<PermissionPromptDesktop*>(manager_->view_.get());
  return prompt ? prompt->GetPromptBubbleWidgetForTesting() : nullptr;
}

void PermissionRequestManagerTestApi::SimulateWebContentsDestroyed() {
  manager_->WebContentsDestroyed();
}

}  // namespace test


text:
package sos.base.reachablity.tools;

public class ReachablityTester {
/*
	// Morteza2011*****************************************************************
	public static void checkExpandedArea(PoliceForceAgent agent) {
		ArrayList<List<Edge>> testList = new ArrayList<List<Edge>>();
		for (Road r : agent.model().roads()) {
			testList.add(r.getExpandedArea().getEdges());
		}
		if (agent.getWorldModelViewer() != null && agent.getWorldModelViewer().viewer != null)
			agent.getWorldModelViewer().viewer.reachEdgesLayer.paintThisEdges(testList);
	}

	// Morteza2011*****************************************************************
	public static void checkExpandedBlockades(PoliceForceAgent agent) {
		ArrayList<List<Edge>> testList = new ArrayList<List<Edge>>();
		for (Road r : agent.model().roads()) {
			for (SOSBlockade b : r.getMiddleBlockades()) {
				testList.add(b.getExpandedBlock().getEdges());
		}
		}
		if (agent.getWorldModelViewer() != null && agent.getWorldModelViewer().viewer != null)
			agent.getWorldModelViewer().viewer.reachEdgesLayer.paintThisEdges(testList);
	}

	// Morteza2011*****************************************************************
	public static void checkExpandedBlockade(PoliceForceAgent agent, EntityID road) {
		if (agent.model().getEntity(road) instanceof Road) {
			ArrayList<List<Edge>> testList = new ArrayList<List<Edge>>();
			List<Blockade> blocks = ((Road) agent.model().getEntity(road)).getBlockades();
			if (blocks == null)
				return;
			for (Blockade b : blocks) {
				testList.add(b.getExpandedBlock().getEdges());
				if (agent.getWorldModelViewer() != null && agent.getWorldModelViewer().viewer != null)
					agent.getWorldModelViewer().viewer.reachEdgesLayer.paintThisEdges(testList);
			}
			if (agent.getWorldModelViewer() != null && agent.getWorldModelViewer().viewer != null)
				agent.getWorldModelViewer().viewer.reachEdgesLayer.paintThisEdges(testList);
		}
	}

	// Morteza2011*****************************************************************
	public static void checkMergedBlockades(PoliceForceAgent agent) {
		ArrayList<List<Edge>> testList = new ArrayList<List<Edge>>();
		for (Road r : agent.model().roads()) {
			for (SOSArea blockade : r.getMergedBlockades()) {
				testList.add(blockade.getEdges());
			}
		}
		if (agent.getWorldModelViewer() != null && agent.getWorldModelViewer().viewer != null)
			agent.getWorldModelViewer().viewer.reachEdgesLayer.paintThisEdges(testList);
	}

	// Morteza2011*****************************************************************
	public static void checkReachableParts(PoliceForceAgent agent) {
		ArrayList<List<Edge>> testList = new ArrayList<List<Edge>>();
		for (Road r : agent.model().roads()) {
			for (SOSArea rp : r.getReachableParts()) {
				testList.add(rp.getEdges());
			}
		}
		if (agent.getWorldModelViewer() != null && agent.getWorldModelViewer().viewer != null)
			agent.getWorldModelViewer().viewer.reachEdgesLayer.paintThisEdges(testList);
	}

	// Morteza2011*****************************************************************
	public static void checkReachableEdges(PoliceForceAgent agent) {
		ArrayList<List<Edge>> testList = new ArrayList<List<Edge>>();
		for (Road r : agent.model().roads()) {
			if (r.getBlockades() == null)
				continue;
			for (ArrayList<EdgeElement> list : r.getReachableEdges()) {
				List<Edge> edgeList = new ArrayList<Edge>();
				for (EdgeElement ee : list) {
					Edge e = new Edge(ee.getStart(), ee.getEnd());
					edgeList.add(e);
				}
				testList.add(edgeList);
			}
		}
		if (agent.getWorldModelViewer() != null && agent.getWorldModelViewer().viewer != null)
			agent.getWorldModelViewer().viewer.reachEdgesLayer.paintThisEdges(testList);
	}

	// Morteza2011*****************************************************************
	public static void checkMyLocationsReachableEdges(PoliceForceAgent agent) {
		ArrayList<List<Edge>> testList = new ArrayList<List<Edge>>();
		if (agent.location() instanceof Road) {
			Road r = (Road) agent.location();
			ArrayList<EdgeElement> list = r.getReachableEdges().get(0);
			List<Edge> edgeList = new ArrayList<Edge>();
			for (EdgeElement ee : list) {
				Edge e = new Edge(ee.getStart(), ee.getEnd());
				edgeList.add(e);
			}
			testList.add(edgeList);
			if (agent.getWorldModelViewer() != null && agent.getWorldModelViewer().viewer != null)
				agent.getWorldModelViewer().viewer.reachEdgesLayer.paintThisEdges(testList);
		}
	}

	// Morteza2011*****************************************************************
	public static void checkPoliceReachablity_P2P(PoliceForceAgent agent) {
		if (agent.location() instanceof Road) {
			ArrayList<List<Edge>> testList = new ArrayList<List<Edge>>();
			List<Edge> test = new ArrayList<Edge>();
			Point2D start = new Point2D(((Road) agent.location()).getX() - 15000, ((Road) agent.location()).getY());
			Point2D end = new Point2D(((Road) agent.location()).getX() + 15000, ((Road) agent.location()).getY());
			test.add(new Edge(new Point2D(start.getX() - 1000, start.getY()), new Point2D(start.getX() + 1000, start.getY())));
			test.add(new Edge(new Point2D(start.getX(), start.getY() - 1000), new Point2D(start.getX(), start.getY() + 1000)));
			test.add(new Edge(new Point2D(end.getX() - 1000, end.getY() - 1000), new Point2D(end.getX() + 1000, end.getY() + 1000)));
			test.add(new Edge(new Point2D(end.getX() - 1000, end.getY() + 1000), new Point2D(end.getX() + 1000, end.getY() - 1000)));
			testList.add(test);
			for (Blockade b : PoliceReachablity.clearableBlockades((Road) agent.location(), start, end))
				testList.add(b.getEdges());
			if (agent.getWorldModelViewer() != null && agent.getWorldModelViewer().viewer != null)
				agent.getWorldModelViewer().viewer.reachEdgesLayer.paintThisEdges(testList);
		}
	}

	// Morteza2011*****************************************************************
	public static void checkPoliceReachablity_E2E(PoliceForceAgent agent) {
		if (agent.location() instanceof Road) {
			ArrayList<List<Edge>> testList = new ArrayList<List<Edge>>();
			List<Edge> test = new ArrayList<Edge>();
			Edge start = new Edge(new Point2D(26807.0, 122150.0), new Point2D(33000.0, 117000.0));
			Edge start2 = new Edge(new Point2D(34000.0, 116998.0), new Point2D(37000.0, 116992.0));
			Edge end = new Edge(new Point2D(108690.0, 116840.0), new Point2D(111310.0, 123160.0));
			test.add(start);
			test.add(end);
			testList.add(test);
			for (Blockade b : PoliceReachablity.clearableBlockades((Road) agent.location(), start2, end))
				testList.add(b.getEdges());
			if (agent.getWorldModelViewer() != null && agent.getWorldModelViewer().viewer != null)
				agent.getWorldModelViewer().viewer.reachEdgesLayer.paintThisEdges(testList);
		}
	}

	// Morteza2011*****************************************************************
	public static void checkPoliceReachablity_P2E(PoliceForceAgent agent) throws SOSActionException {
		if (agent.location() instanceof Road) {
			ArrayList<List<Edge>> testList = new ArrayList<List<Edge>>();
			List<Edge> test = new ArrayList<Edge>();
			Point2D start = new Point2D(((Road) agent.location()).getX(), ((Road) agent.location()).getY());
			Edge end = new Edge(new Point2D(126840.0, 46000.0), new Point2D(126840.0, 48000.0));
			test.add(new Edge(new Point2D(start.getX() - 1000, start.getY()), new Point2D(start.getX() + 1000, start.getY())));
			test.add(new Edge(new Point2D(start.getX(), start.getY() - 1000), new Point2D(start.getX(), start.getY() + 1000)));
			test.add(end);
			testList.add(test);
			ArrayList<Blockade> blocks = PoliceReachablity.clearableBlockades((Road) agent.location(), start, end);
			for (Blockade b : blocks)
				testList.add(b.getEdges());
			if (agent.getWorldModelViewer() != null && agent.getWorldModelViewer().viewer != null)
				agent.getWorldModelViewer().viewer.reachEdgesLayer.paintThisEdges(testList);
			System.out.println(blocks);
			// if (blocks != null && blocks.size() > 0)
			// agent.clear(blocks.get(0));

		}
	}

	// Morteza2011*****************************************************************
	public static void checkPoliceReachablity_E2P(PoliceForceAgent agent) {
		if (agent.location() instanceof Road) {
			ArrayList<List<Edge>> testList = new ArrayList<List<Edge>>();
			List<Edge> test = new ArrayList<Edge>();
			Edge start = new Edge(new Point2D(108690.0, 116840.0), new Point2D(111310.0, 123160.0));
			Point2D end = new Point2D(((Road) agent.location()).getX() - 15000, ((Road) agent.location()).getY());
			test.add(new Edge(new Point2D(end.getX() - 1000, end.getY()), new Point2D(end.getX() + 1000, end.getY())));
			test.add(new Edge(new Point2D(end.getX(), end.getY() - 1000), new Point2D(end.getX(), end.getY() + 1000)));
			test.add(start);
			testList.add(test);
			for (Blockade b : PoliceReachablity.clearableBlockades((Road) agent.location(), start, end))
				testList.add(b.getEdges());
			if (agent.getWorldModelViewer() != null && agent.getWorldModelViewer().viewer != null)
				agent.getWorldModelViewer().viewer.reachEdgesLayer.paintThisEdges(testList);
		}
	}

	// Morteza2011*****************************************************************
	public static void checkIsReachable_E2E(PoliceForceAgent agent) {
		if (agent.location() instanceof Road) {
			ArrayList<List<Edge>> testList = new ArrayList<List<Edge>>();
			List<Edge> test = new ArrayList<Edge>();
			List<Edge> edges = ((Road) agent.location()).getEdges();
			Edge start = edges.get(8);
			Edge end = edges.get(0);
			test.add(start);
			test.add(end);
			if (Reachablity.isReachable((Road) agent.location(), start, end) == ReachablityState.Open) {
				test.add(new Edge(start.getMidPoint(), end.getMidPoint()));
			}
			testList.add(test);
			if (agent.getWorldModelViewer() != null && agent.getWorldModelViewer().viewer != null)
				agent.getWorldModelViewer().viewer.reachEdgesLayer.paintThisEdges(testList);
		}
	}

	// Morteza2011*****************************************************************
	public static void checkIsReachable_P2E(PoliceForceAgent agent) {
		if (agent.location() instanceof Road) {
			ArrayList<List<Edge>> testList = new ArrayList<List<Edge>>();
			List<Edge> test = new ArrayList<Edge>();
			List<Edge> edges = ((Road) agent.location()).getEdges();
			Point2D start = new Point2D(((Road) agent.location()).getX() - 15000, ((Road) agent.location()).getY());
			Edge end = edges.get(8);
			test.add(new Edge(new Point2D(start.getX() - 1000, start.getY()), new Point2D(start.getX() + 1000, start.getY())));
			test.add(new Edge(new Point2D(start.getX(), start.getY() - 1000), new Point2D(start.getX(), start.getY() + 1000)));
			test.add(end);
			testList.add(test);
			if (Reachablity.isReachable((Road) agent.location(), start, end) == ReachablityState.Open) {
				test.add(new Edge(start, end.getMidPoint()));
			}
			if (agent.getWorldModelViewer() != null && agent.getWorldModelViewer().viewer != null)
				agent.getWorldModelViewer().viewer.reachEdgesLayer.paintThisEdges(testList);
		}
	}

	// Morteza2011*****************************************************************
	public static void checkGetReachablePart(FireBrigadeAgent agent) {
		if (agent.location() instanceof Road) {
			ArrayList<List<Edge>> testList = new ArrayList<List<Edge>>();
			List<Edge> test = new ArrayList<Edge>();
			Point2D p = new Point2D(128000, 44000);
			test.add(new Edge(new Point2D(p.getX() - 1000, p.getY()), new Point2D(p.getX() + 1000, p.getY())));
			test.add(new Edge(new Point2D(p.getX(), p.getY() - 1000), new Point2D(p.getX(), p.getY() + 1000)));
			int index=OtherReachablityTools.getReachablePart((Road) agent.location(), p);
			SOSArea a = ((Road)agent.location()).getReachableParts().get(index);
			if (a != null)
				test.addAll(a.getEdges());
			testList.add(test);
			if (agent.getWorldModelViewer() != null && agent.getWorldModelViewer().viewer != null)
				agent.getWorldModelViewer().viewer.reachEdgesLayer.paintThisEdges(testList);
		}
	}
*/}


text:
import * as assert from "assert";
import { Segment } from "../../src";
import { mockDOMSource, VNode } from "@cycle/dom";
import xs from "xstream";

describe("Segment", function () {
  describe("render", function () {
    it("should return a basic segment when called without any arguments", function () {
      let segment = Segment.render();
      assert.equal(segment.data.props.className, "ui segment");
      assert.equal(segment.children.length, 0);
    });
    it("should support argument syntax", function () {
      let segment = Segment.render({ loading: true }, ["Content"]);
      assert.equal(segment.children.length, 1);
      assert.equal(segment.data.props.className, "ui loading segment");
      assert.equal((segment.children[0] as VNode).text, "Content");
      segment = Segment.render(["Content"]);
      assert.equal(segment.children.length, 1);
      assert.equal(segment.data.props.className, "ui segment");
      assert.equal((segment.children[0] as VNode).text, "Content");
      segment = Segment.render({ loading: true });
      assert.equal(segment.children.length, 0);
      assert.equal(segment.data.props.className, "ui loading segment");
    });
    it("should support verbose argument object syntax", function () {
      let segment = Segment.render({
        props: { loading: true },
        content: {
          main: ["Content"]
        }
      });
      assert.equal(segment.children.length, 1);
      assert.equal(segment.data.props.className, "ui loading segment");
      assert.equal((segment.children[0] as VNode).text, "Content");
      segment = Segment.render({
        content: {
          main: ["Content"]
        }
      });
      assert.equal(segment.children.length, 1);
      assert.equal(segment.data.props.className, "ui segment");
      assert.equal((segment.children[0] as VNode).text, "Content");
      segment = Segment.render({
        props: { loading: true }
      });
      assert.equal(segment.children.length, 0);
      assert.equal(segment.data.props.className, "ui loading segment");
    });
    it("should support shorthand argument object syntax", function () {
      let segment = Segment.render({
        props: { loading: true },
        content: ["Content"]
      });
      assert.equal(segment.children.length, 1);
      assert.equal(segment.data.props.className, "ui loading segment");
      assert.equal((segment.children[0] as VNode).text, "Content");
      segment = Segment.render({
        content: ["Content"]
      });
      assert.equal(segment.children.length, 1);
      assert.equal(segment.data.props.className, "ui segment");
      assert.equal((segment.children[0] as VNode).text, "Content");
      segment = Segment.render({
        props: { loading: true }
      });
      assert.equal(segment.children.length, 0);
      assert.equal(segment.data.props.className, "ui loading segment");
    });
    it("should support the raised variation", function () {
      let segment = Segment.render({ raised: true });
      assert.equal(segment.data.props.className, "ui raised segment");
    });
    it("should support the stacked variation", function () {
      let segment = Segment.render({ stacked: true });
      assert.equal(segment.data.props.className, "ui stacked segment");
    });
    it("should support the tall stacked variation", function () {
      let segment = Segment.render({ tallStacked: true });
      assert.equal(segment.data.props.className, "ui tall stacked segment");
    });
    it("should support the piled variation", function () {
      let segment = Segment.render({ piled: true });
      assert.equal(segment.data.props.className, "ui piled segment");
    });
    it("should support the vertical variation", function () {
      let segment = Segment.render({ vertical: true });
      assert.equal(segment.data.props.className, "ui vertical segment");
    });
    it("should support the loading variation", function () {
      let segment = Segment.render({ loading: true });
      assert.equal(segment.data.props.className, "ui loading segment");
    });
    it("should support the inverted variation", function () {
      let segment = Segment.render({ inverted: true });
      assert.equal(segment.data.props.className, "ui inverted segment");
    });
    it("should support the padded variation", function () {
      let segment = Segment.render({ padded: true });
      assert.equal(segment.data.props.className, "ui padded segment");
    });
    it("should support the very padded variation", function () {
      let segment = Segment.render({ veryPadded: true });
      assert.equal(segment.data.props.className, "ui very padded segment");
    });
    it("should support the compact variation", function () {
      let segment = Segment.render({ compact: true });
      assert.equal(segment.data.props.className, "ui compact segment");
    });
    it("should support the circular variation", function () {
      let segment = Segment.render({ circular: true });
      assert.equal(segment.data.props.className, "ui circular segment");
    });
    it("should support the clearing variation", function () {
      let segment = Segment.render({ clearing: true });
      assert.equal(segment.data.props.className, "ui clearing segment");
    });
    it("should support the basic variation", function () {
      let segment = Segment.render({ basic: true });
      assert.equal(segment.data.props.className, "ui basic segment");
    });
    it("should support the color enum", function () {
      let segment = Segment.render({ color: "primary" });
      assert.equal(segment.data.props.className, "ui primaryColored segment");
    });
    it("should support the attachment enum", function () {
      let segment = Segment.render({ attachment: "top" });
      assert.equal(segment.data.props.className, "ui top attached segment");
    });
    it("should support the float enum", function () {
      let segment = Segment.render({ float: "right" });
      assert.equal(segment.data.props.className, "ui right floated segment");
    });
    it("should support the text alignment enum", function () {
      let segment = Segment.render({ textAlignment: "right" });
      assert.equal(segment.data.props.className, "ui right aligned segment");
    });
  });
  describe("run", function () {
    let dom = mockDOMSource({
      ".___segment": {
        ".segment": {
          "click": xs.of("Clicked")
        }
      }
    });
    it("should return a segment stream", function (done) {
      let segment = Segment.run({ DOM: dom });
      segment.DOM.addListener({
        next: (x) => {
          assert.equal("ui segment", x.data.props.className);
          done();
        }
      });
    });
    it("should return an isolated component", function (done) {
      let segment = Segment.run({ DOM: dom }, "segment");
      segment.DOM.addListener({
        next: (x) => {
          assert.equal("div.___segment", x.sel);
          done();
        }
      });
    });
    it("should expose events through the events function", function (done) {
      let segment = Segment.run({ DOM: dom }, "segment");
      segment.events("click").addListener({
        next: (x) => {
          assert.equal("Clicked", x);
          done();
        }
      });
    });
  });
});


text:
package com.exlibris.dps.repository.plugin.storage.netapp.client;

public class CDMIResponseStatus {
	/** The request has succeeded. */
    public static int OK = 200;

    /** Resource created successfully */
    public static int Created = 201;

    /** Long running operation accepted for processing */
    public static int Accepted = 202;

    /** Operation successful, no data */
    public static int No_Content = 204;

    /** Missing or invalid request contents */
    public static int Bad_Request = 400;

    /** Invalid authentication/authorization credentials */
    public static int Unauthorized = 401;

    /** This user is not allowed to perform this request */
    public static int Forbidden = 403;

    /** A resource was not found at the specified URI. */
    public static int Not_Found = 404;

    /** Requested HTTP verb not allowed on this resource */
    public static int Method_Not_Allowed = 405;

    /** No content type can be produced at this URI that matches the request */
    public static int Not_Acceptable = 406;

    /** The operation conflicts with a non-CDMI access protocol lock, or could cause a state transition error on the server. */
    public static int Conflict = 409;

    /** An unexpected vendor specific error */
    public static int Internal_Server_Error = 500;

    /** A CDMI operation or metadata value was attempted
     * that is not implemented */
    public static int Not_Implemented = 501;
}


text:
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;

namespace DontPanic.TumblrSharp.Client
{
	/// <summary>
	/// Base class for post types.
	/// </summary>
    public class BasePost
    {
        /// <summary>
        /// The post type.
        /// </summary>
        [JsonConverter(typeof(EnumStringConverter))]
        [JsonProperty(PropertyName = "type")]
        public PostType Type { get; set; }

        /// <summary>
        /// The short name used to uniquely identify a blog.
        /// </summary>
        [JsonProperty(PropertyName = "blog_name")]
        public string BlogName { get; set; }

		/// <summary>
		///The post identifier.
		/// </summary>
        [JsonProperty(PropertyName = "id")]
        public long Id { get; set; }

		/// <summary>
		/// The url of the post.
		/// </summary>
        [JsonProperty(PropertyName = "post_url")]
        public string Url { get; set; }

        /// <summary>
        /// slug
        /// </summary>
        [JsonProperty(PropertyName = "slug")]
        public string Slug { get; set; }

		/// <summary>
		/// The date and time of the post (in local time).
		/// </summary>
		[JsonConverter(typeof(TimestampConverter))]
        [JsonProperty(PropertyName = "timestamp")]
        public DateTime Timestamp { get; set; }

        /// <summary>
        /// The <see cref="PostCreationState"/>.
        /// </summary>
        [JsonConverter(typeof(StringEnumConverter))]
        [JsonProperty(PropertyName = "state")]
        public PostCreationState State { get; set; }

        /// <summary>
        /// The <see cref="PostFormat"/>.
        /// </summary>
        [JsonConverter(typeof(EnumStringConverter))]
        [JsonProperty(PropertyName = "format")]
        public PostFormat Format { get; set; }

        /// <summary>
        /// The key to use to reblog the post.
        /// </summary>
        [JsonProperty(PropertyName = "reblog_key")]
        public string ReblogKey { get; set; }

        /// <summary>
        /// The tags applied to the post.
        /// </summary>
        [JsonProperty(PropertyName = "tags")]
        public string[] Tags { get; set; }

        /// <summary>
        /// Shorturl
        /// </summary>
        [JsonProperty(PropertyName = "short_url")]
        public string ShortUrl { get; set; }

        /// <summary>
        /// Summary
        /// </summary>
        [JsonProperty(PropertyName = "summary")]
        public string Summary { get; set; }

        /// <summary>
        /// The number of notes (likes and reblogs) for the post.
        /// </summary>
        [JsonProperty(PropertyName = "note_count")]
        public long NotesCount { get; set; }

	    /// <summary>
	    /// The notes (likes and reblogs) for the post
	    /// </summary>
		[JsonProperty(PropertyName = "notes")]
        [JsonConverter(typeof(NoteConverter))]
		public List<BaseNote> Notes { get; set; }

		/// <summary>
		/// The url to the blog that is the source of the post, if any.
		/// </summary>
        [JsonProperty(PropertyName = "source_url", NullValueHandling = NullValueHandling.Ignore)]
        public string SourceUrl { get; set; }

		/// <summary>
		/// The title of the blog which is the source of the post, if any.
		/// </summary>
        [JsonProperty(PropertyName = "source_title", NullValueHandling = NullValueHandling.Ignore)]
        public string SourceTitle { get; set; }

		/// <summary>
		/// The number of posts in the response (can be used for pagination).
		/// </summary>
        [JsonProperty(PropertyName = "total_posts")]
        public int NumberOfPostsInResponse { get; set; }

		/// <summary>
		/// Indicates if the current user has already liked the post or not.
		/// </summary>
		[JsonProperty(PropertyName = "liked", NullValueHandling = NullValueHandling.Ignore)]
		public string Liked { get; set; }

		/// <summary>
		/// Indicates whether the post was created via mobile/email publishing.
		/// </summary>
		[JsonProperty(PropertyName = "mobile", NullValueHandling = NullValueHandling.Ignore)]
		public string IsMobile { get; set; }

		/// <summary>
		/// Indicates whether the post was created via the Tumblr bookmarklet.
		/// </summary>
		[JsonProperty(PropertyName = "bookmarklet", NullValueHandling = NullValueHandling.Ignore)]
		public string IsBookmarklet { get; set; }

        /// <summary>
        /// Reblog
        /// </summary>
        [JsonProperty(PropertyName = "reblog", NullValueHandling = NullValueHandling.Ignore)]
        public Reblog Reblog { get; set; }

		/// <summary>
		/// The id of a post being reblogged.
		/// </summary>
		[JsonProperty(PropertyName = "reblogged_from_id", NullValueHandling = NullValueHandling.Ignore)]
		public long? RebloggedFromId { get; set; }

		/// <summary>
		/// Name of a blog being reblogged.
		/// </summary>
		[JsonProperty(PropertyName = "reblogged_from_url", NullValueHandling = NullValueHandling.Ignore)]
		public string RebloggedFromUrl { get; set; }

		/// <summary>
		/// Title of a post being reblogged.
		/// </summary>
		[JsonProperty(PropertyName = "reblogged_from_name", NullValueHandling = NullValueHandling.Ignore)]
		public string RebloggedFromName { get; set; }

		/// <summary>
		/// URL of a post being reblogged.
		/// </summary>
		[JsonProperty(PropertyName = "reblogged_from_title", NullValueHandling = NullValueHandling.Ignore)]
		public string RebloggedFromTitle { get; set; }

		/// <summary>
		/// The id of an original post being reblogged.
		/// </summary>
		[JsonProperty(PropertyName = "reblogged_root_id", NullValueHandling = NullValueHandling.Ignore)]
		public long? RebloggedRootId { get; set; }

		/// <summary>
		/// Root name of a post being reblogged.
		/// </summary>
		[JsonProperty(PropertyName = "reblogged_root_url", NullValueHandling = NullValueHandling.Ignore)]
		public string RebloggedRootUrl { get; set; }

		/// <summary>
		/// Title of the original post being reblogged.
		/// </summary>
		[JsonProperty(PropertyName = "reblogged_root_name", NullValueHandling = NullValueHandling.Ignore)]
		public string RebloggedRootName { get; set; }

		/// <summary>
		/// URL of the original post being reblogged.
		/// </summary>
		[JsonProperty(PropertyName = "reblogged_root_title", NullValueHandling = NullValueHandling.Ignore)]
		public string RebloggedRootTitle { get; set; }

        /// <summary>
		/// Trail
		/// </summary>
        [JsonProperty(PropertyName = "trail", NullValueHandling = NullValueHandling.Include)]
        [JsonConverter(typeof(TrailConverter))]
        public List<Trail> Trails { get; set; }
    }
}


text:
<?php

class Onxshop_Controller_Bo_Component_Ecommerce_Product_Edit extends Onxshop_Controller {

	/**
	 * main action
	 */

	public function mainAction() {

		/**
		 * initialize
		 */

		require_once('models/ecommerce/ecommerce_product.php');
		$Product = new ecommerce_product();

		/**
		 * save
		 */

		if ($_POST['save']) {

			$product_data = $_POST['product'];

			if ($id = $Product->updateProduct($product_data)) {

				/**
				 * forward to product list main page and exit
				 */

				onxshopGoTo("/backoffice/products");

				return true;

			}

		}

		/**
		 * product detail
		 */

		$product = $Product->detail($this->GET['id']);
		$product['publish'] = ($product['publish'] == 1) ? 'checked="checked" ' : '';
		$this->tpl->assign('PRODUCT', $product);

		return true;
	}
}