text:
/**
 * DataModel surface fragment.
 *
 * @class
 *
 * @constructor
 * @param {ve.dm.Surface} surface Target surface
 * @param {ve.Range} [range] Range within target document, current selection used by default
 * @param {boolean} [noAutoSelect] Update the surface's selection when making changes
 * @param {boolean} [excludeInsertions] Exclude inserted content at the boundaries when updating range
 */
ve.dm.SurfaceFragment = function VeDmSurfaceFragment( surface, range, noAutoSelect, excludeInsertions ) {
	// Short-circuit for missing-surface null fragment
	if ( !surface ) {
		return this;
	}

	// Properties
	this.document = surface.getDocument();
	this.noAutoSelect = !!noAutoSelect;
	this.excludeInsertions = !!excludeInsertions;
	this.surface = surface;
	this.range = range && range instanceof ve.Range ? range : surface.getSelection();
	this.leafNodes = null;

	// Short-circuit for invalid range null fragment
	if ( !this.range ) {
		return this;
	}

	// Initialization
	var length = this.document.data.getLength();
	this.range = new ve.Range(
		// Clamp range to valid document offsets
		Math.min( Math.max( this.range.from, 0 ), length ),
		Math.min( Math.max( this.range.to, 0 ), length )
	);
	this.historyPointer = this.document.getCompleteHistoryLength();
};

/* Static Properties */

ve.dm.SurfaceFragment.static = {};

/* Methods */

/**
 * Translate the current range for one or more transactions, using this.excludeInsertions.
 *
 * @param {ve.dm.Transaction|ve.dm.Transaction[]} txs Transaction(s) to translate for
 * @param {boolean} [noUpdate] Use this.range directly rather than trying to update it first
 *  Only use this if calling this.update() will lead to problems (e.g. recursion)
 * @returns {ve.Range|null} Translated range
 */
ve.dm.SurfaceFragment.prototype.getTranslatedRange = function ( txs, noUpdate ) {
	// Handle null fragment
	if ( this.isNull() ) {
		return null;
	}

	var i, len, range;

	if ( !ve.isArray( txs ) ) {
		txs = [ txs ];
	}

	if ( !noUpdate ) {
		this.update();
	}
	range = this.range;
	for ( i = 0, len = txs.length; i < len; i++ ) {
		range = txs[i].translateRange( range, this.excludeInsertions );
	}

	return range;
};

/**
 * Get list of selected nodes and annotations.
 *
 * @param {boolean} [all] Include nodes and annotations which only cover some of the fragment
 * @return {ve.dm.Model[]} Selected models
 */
ve.dm.SurfaceFragment.prototype.getSelectedModels = function ( all ) {
	// Handle null fragment
	if ( this.isNull() ) {
		return [];
	}

	var i, len, nodes, selectedNode,
		annotations = this.getAnnotations( all );

	// Filter out nodes with collapsed ranges
	if ( all ) {
		nodes = this.getCoveredNodes();
		for ( i = 0, len = nodes.length; i < len; i++ ) {
			if ( nodes[i].range && nodes[i].range.isCollapsed() ) {
				nodes.splice( i, 1 );
				len--;
				i--;
			} else {
				nodes[i] = nodes[i].node;
			}
		}
	} else {
		nodes = [];
		selectedNode = this.getSelectedNode();
		if ( selectedNode ) {
			nodes.push( selectedNode );
		}
	}

	return nodes.concat( !annotations.isEmpty() ? annotations.get() : [] );
};

/**
 * Update range based on un-applied transactions in the surface.
 *
 * @method
 */
ve.dm.SurfaceFragment.prototype.update = function () {
	// Handle null fragment
	if ( this.isNull() ) {
		return;
	}

	var txs;
	// Small optimisation: check history pointer is in the past
	if ( this.historyPointer < this.document.getCompleteHistoryLength() ) {
		txs = this.document.getCompleteHistorySince( this.historyPointer );
		this.range = this.getTranslatedRange( txs, true );
		this.historyPointer += txs.length;
		this.leafNodes = null;
	}
};

/**
 * Process a set of transactions on the surface, and update the selection if the fragment
 * is auto-selecting.
 *
 * @param {ve.dm.Transaction|ve.dm.Transaction[]} txs Transaction(s) to process
 * @param {ve.Range} [range] Range to set, if different from translated range, required if the
 *   fragment is null
 * @throws {Error} If fragment is null and range is omitted
 */
ve.dm.SurfaceFragment.prototype.change = function ( txs, range ) {
	if ( !range && this.isNull() ) {
		throw new Error( 'Cannot change null fragment without range' );
	}

	this.surface.change( txs, !this.noAutoSelect && ( range || this.getTranslatedRange( txs ) ) );
	if ( range ) {
		// Let this.range auto-translate for what we just did
		this.update();
		// Overwrite it
		this.range = range;
	}
};

/**
 * Get the surface the fragment is a part of.
 *
 * @method
 * @returns {ve.dm.Surface|null} Surface of fragment
 */
ve.dm.SurfaceFragment.prototype.getSurface = function () {
	return this.surface;
};

/**
 * Get the document of the surface the fragment is a part of.
 *
 * @method
 * @returns {ve.dm.Document|null} Document of surface of fragment
 */
ve.dm.SurfaceFragment.prototype.getDocument = function () {
	return this.document;
};

/**
 * Get the range of the fragment within the surface.
 *
 * This method also calls update to make sure the range returned is current.
 *
 * @method
 * @param {boolean} noCopy Return the range by reference, not a copy
 * @returns {ve.Range|null} Surface range
 */
ve.dm.SurfaceFragment.prototype.getRange = function ( noCopy ) {
	this.update();
	return this.range && !noCopy ? this.range.clone() : this.range;
};

/**
 * Check if the fragment is null.
 *
 * @method
 * @returns {boolean} Fragment is a null fragment
 */
ve.dm.SurfaceFragment.prototype.isNull = function () {
	return !this.range;
};

/**
 * Check if the surface's selection will be updated automatically when changes are made.
 *
 * @method
 * @returns {boolean} Will automatically update surface selection
 */
ve.dm.SurfaceFragment.prototype.willAutoSelect = function () {
	return !this.noAutoSelect;
};

/**
 * Change whether to automatically update the surface selection when making changes.
 *
 * @method
 * @param {boolean} [autoSelect=true] Automatically update surface selection
 * @chainable
 */
ve.dm.SurfaceFragment.prototype.setAutoSelect = function ( autoSelect ) {
	this.noAutoSelect = !autoSelect;
	return this;
};

/**
 * Get a clone of this SurfaceFragment, optionally with a different range.
 *
 * @param {ve.Range} [range] If set, use this range rather than the old fragment's range
 * @returns {ve.dm.SurfaceFragment} Clone of this fragment
 */
ve.dm.SurfaceFragment.prototype.clone = function ( range ) {
	return new this.constructor(
		this.surface,
		range || this.getRange(),
		this.noAutoSelect,
		this.excludeInsertions
	);
};

/**
 * Check whether updates to this fragment's range will exclude content inserted at the boundaries.
 * @returns {boolean} Range updates will exclude insertions
 */
ve.dm.SurfaceFragment.prototype.willExcludeInsertions = function () {
	return this.excludeInsertions;
};

/**
 * Tell this fragment whether it should exclude insertions. If this option is enabled, updates to
 * this fragment's range in response to transactions will not include content inserted at the
 * boundaries of the range; if it is disabled, insertions will be included.
 *
 * @param {boolean} excludeInsertions Whether to exclude insertions
 */
ve.dm.SurfaceFragment.prototype.setExcludeInsertions = function ( excludeInsertions ) {
	excludeInsertions = !!excludeInsertions;
	if ( this.excludeInsertions !== excludeInsertions ) {
		// Process any deferred updates with the old value
		this.update();
		// Set the new value
		this.excludeInsertions = excludeInsertions;
	}
};

/**
 * Get a new fragment with an adjusted position
 *
 * @method
 * @param {number} [start] Adjustment for start position
 * @param {number} [end] Adjustment for end position
 * @returns {ve.dm.SurfaceFragment} Adjusted fragment
 */
ve.dm.SurfaceFragment.prototype.adjustRange = function ( start, end ) {
	var newRange, oldRange = this.getRange( true );
	newRange = oldRange && new ve.Range( oldRange.start + ( start || 0 ), oldRange.end + ( end || 0 ) );
	return this.clone( newRange );
};

/**
 * Get a new fragment with a truncated length.
 *
 * @method
 * @param {number} limit Maximum length of range (negative for left-side truncation)
 * @returns {ve.dm.SurfaceFragment} Truncated fragment
 */
ve.dm.SurfaceFragment.prototype.truncateRange = function ( limit ) {
	var range = this.getRange( true );
	return this.clone( range && range.truncate( limit ) );
};

/**
 * Get a new fragment with a zero-length selection at the start offset.
 *
 * @method
 * @returns {ve.dm.SurfaceFragment} Collapsed fragment
 */
ve.dm.SurfaceFragment.prototype.collapseRangeToStart = function () {
	var range = this.getRange( true );
	return this.clone( range && new ve.Range( range.start ) );
};

/**
 * Get a new fragment with a zero-length selection at the end offset.
 *
 * @method
 * @returns {ve.dm.SurfaceFragment} Collapsed fragment
 */
ve.dm.SurfaceFragment.prototype.collapseRangeToEnd = function () {
	var range = this.getRange( true );
	return this.clone( range && new ve.Range( range.end ) );
};

/**
 * Get a new fragment with a range that no longer includes leading and trailing whitespace.
 *
 * @method
 * @returns {ve.dm.SurfaceFragment} Trimmed fragment
 */
ve.dm.SurfaceFragment.prototype.trimRange = function () {
	var oldRange = this.getRange(),
		newRange = oldRange;

	if ( oldRange ) {
		if ( this.document.getText( oldRange ).trim().length === 0 ) {
			// oldRange is only whitespace
			newRange = new ve.Range( oldRange.start );
		} else {
			newRange = this.document.data.trimOuterSpaceFromRange( oldRange );
		}
	}

	return this.clone( newRange );
};

/**
 * Get a new fragment that covers an expanded range of the document.
 *
 * @method
 * @param {string} [scope='parent'] Method of expansion:
 *  - `word`: Expands to cover the nearest word by looking for word breaks (see UnicodeJS.wordbreak)
 *  - `annotation`: Expands to cover a given annotation (argument) within the current range
 *  - `root`: Expands to cover the entire document
 *  - `siblings`: Expands to cover all sibling nodes
 *  - `closest`: Expands to cover the closest common ancestor node of a give type (argument)
 *  - `parent`: Expands to cover the closest common parent node
 * @param {Mixed} [type] Parameter to use with scope method if needed
 * @returns {ve.dm.SurfaceFragment} Expanded fragment
 */
ve.dm.SurfaceFragment.prototype.expandRange = function ( scope, type ) {
	var node, nodes, parent, newRange,
		oldRange = this.getRange();

	// Handle null fragment
	if ( this.isNull() ) {
		return this.clone();
	}

	switch ( scope || 'parent' ) {
		case 'word':
			if ( oldRange.getLength() > 0 ) {
				newRange = ve.Range.newCoveringRange( [
					this.document.data.getNearestWordRange( this.getRange( true ).start ),
					this.document.data.getNearestWordRange( this.getRange( true ).end )
				] );
				if ( oldRange.isBackwards() ) {
					newRange = newRange.flip();
				}
			} else {
				// optimisation for zero-length ranges
				newRange = this.document.data.getNearestWordRange( oldRange.start );
			}
			break;
		case 'annotation':
			newRange = this.document.data.getAnnotatedRangeFromSelection( oldRange, type );
			// Adjust selection if it does not contain the annotated range
			if ( oldRange.start > newRange.start || oldRange.end < newRange.end ) {
				// Maintain range direction
				if ( oldRange.from > oldRange.to ) {
					newRange = newRange.flip();
				}
			} else {
				// Otherwise just keep the range as is
				newRange = oldRange;
			}
			break;
		case 'root':
			newRange = new ve.Range( 0, this.getDocument().getInternalList().getListNode().getOuterRange().start );
			break;
		case 'siblings':
			// Grow range to cover all siblings
			nodes = this.document.selectNodes( oldRange, 'siblings' );
			if ( nodes.length === 1 ) {
				newRange = nodes[0].node.getOuterRange();
			} else {
				newRange = new ve.Range(
					nodes[0].node.getOuterRange().start,
					nodes[nodes.length - 1].node.getOuterRange().end
				);
			}
			break;
		case 'closest':
			// Grow range to cover closest common ancestor node of given type
			node = this.document.selectNodes( oldRange, 'siblings' )[0].node;
			parent = node.getParent();
			while ( parent && parent.getType() !== type ) {
				node = parent;
				parent = parent.getParent();
			}
			if ( !parent ) {
				return new ve.dm.SurfaceFragment( null );
			}
			newRange = parent.getOuterRange();
			break;
		case 'parent':
			// Grow range to cover the closest common parent node
			node = this.document.selectNodes( oldRange, 'siblings' )[0].node;
			parent = node.getParent();
			if ( !parent ) {
				return new ve.dm.SurfaceFragment( null );
			}
			newRange = parent.getOuterRange();
			break;
		default:
			throw new Error( 'Invalid scope argument: ' + scope );
	}
	return this.clone( newRange );
};

/**
 * Get data for the fragment.
 *
 * @method
 * @param {boolean} [deep] Get a deep copy of the data
 * @returns {Array} Fragment data
 */
ve.dm.SurfaceFragment.prototype.getData = function ( deep ) {
	// Handle null fragment
	if ( this.isNull() ) {
		return [];
	}
	return this.document.getData( this.getRange(), deep );
};

/**
 * Get plain text for the fragment.
 *
 * @method
 * @returns {string} Fragment text
 */
ve.dm.SurfaceFragment.prototype.getText = function () {
	// Handle null fragment
	if ( this.isNull() ) {
		return '';
	}
	var i, length,
		text = '',
		data = this.document.getData( this.getRange() );
	for ( i = 0, length = data.length; i < length; i++ ) {
		if ( data[i].type === undefined ) {
			// Annotated characters have a string at index 0, plain characters are 1-char strings
			text += typeof data[i] === 'string' ? data[i] : data[i][0];
		}
	}
	return text;
};

/**
 * Get annotations in fragment.
 *
 * By default, this will only get annotations that completely cover the fragment. Use the {all}
 * argument to get all annotations that occur within the fragment.
 *
 * @method
 * @param {boolean} [all] Get annotations which only cover some of the fragment
 * @returns {ve.dm.AnnotationSet} All annotation objects range is covered by
 */
ve.dm.SurfaceFragment.prototype.getAnnotations = function ( all ) {
	// Handle null fragment
	if ( this.isNull() ) {
		return new ve.dm.AnnotationSet( this.getDocument().getStore() );
	}
	if ( this.getRange( true ).getLength() ) {
		return this.getDocument().data.getAnnotationsFromRange( this.getRange(), all );
	} else {
		return this.surface.getInsertionAnnotations();
	}
};

/**
 * Check if the fragment has any annotations
 *
 * Quicker than doing !fragment.getAnnotations( true ).isEmpty() as
 * it stops at the first sight of an annotation.
 *
 * @method
 * @returns {boolean} The fragment contains at least one annotation
 */
ve.dm.SurfaceFragment.prototype.hasAnnotations = function () {
	// Handle null fragment
	if ( this.isNull() ) {
		return false;
	}

	return this.getDocument().data.hasAnnotationsInRange( this.getRange( true ) );
};

/**
 * Get all leaf nodes covered by the fragment.
 *
 * @see ve.Document#selectNodes Used to get the return value
 *
 * @method
 * @returns {Array} List of nodes and related information
 */
ve.dm.SurfaceFragment.prototype.getLeafNodes = function () {
	// Handle null fragment
	if ( this.isNull() ) {
		return [];
	}

	// Update in case the cache needs invalidating
	this.update();
	// Cache leafNodes because it's expensive to compute
	if ( !this.leafNodes ) {
		this.leafNodes = this.document.selectNodes( this.getRange( true ), 'leaves' );
	}
	return this.leafNodes;
};

/**
 * Get all leaf nodes excluding nodes where the selection is empty.
 *
 * @method
 * @returns {Array} List of nodes and related information
 */
ve.dm.SurfaceFragment.prototype.getSelectedLeafNodes = function () {
	// Handle null fragment
	if ( this.isNull() ) {
		return [];
	}

	var i, len, selectedLeafNodes = [], leafNodes = this.getLeafNodes();
	for ( i = 0, len = leafNodes.length; i < len; i++ ) {
		if ( len === 1 || !leafNodes[i].range || leafNodes[i].range.getLength() ) {
			selectedLeafNodes.push( leafNodes[i].node );
		}
	}
	return selectedLeafNodes;
};

/**
 * Get the node selected by a range, i.e. the range matches the node's range exactly.
 *
 * Note that this method operates on the fragment's range, not the document's current selection.
 * This fragment does not need to be selected for this method to work.
 *
 * @returns {ve.dm.Node|null} The node selected by the range, or null if a node is not selected
 */
ve.dm.SurfaceFragment.prototype.getSelectedNode = function () {
	// Handle null fragment
	if ( this.isNull() ) {
		return null;
	}

	var i, len, range = this.getRange(),
		nodes = this.document.selectNodes( range, 'covered' );

	for ( i = 0, len = nodes.length; i < len; i++ ) {
		if ( nodes[i].nodeOuterRange.equalsSelection( range ) ) {
			return nodes[i].node;
		}
	}
	return null;
};

/**
 * Get nodes covered by the fragment.
 *
 * Does not descend into nodes that are entirely covered by the range. The result is
 * similar to that of {ve.dm.SurfaceFragment.prototype.getLeafNodes} except that if a node is
 * entirely covered, its children aren't returned separately.
 *
 * @see ve.Document#selectNodes for more information about the return value
 *
 * @method
 * @returns {Array} List of nodes and related information
 */
ve.dm.SurfaceFragment.prototype.getCoveredNodes = function () {
	// Handle null fragment
	if ( this.isNull() ) {
		return [];
	}
	return this.document.selectNodes( this.getRange(), 'covered' );
};

/**
 * Get nodes covered by the fragment.
 *
 * Includes adjacent siblings covered by the range, descending if the range is in a single node.
 *
 * @see ve.Document#selectNodes for more information about the return value.
 *
 * @method
 * @returns {Array} List of nodes and related information
 */
ve.dm.SurfaceFragment.prototype.getSiblingNodes = function () {
	// Handle null fragment
	if ( this.isNull() ) {
		return [];
	}
	return this.document.selectNodes( this.getRange(), 'siblings' );
};

/**
 * Apply the fragment's range to the surface as a selection.
 *
 * @method
 * @chainable
 */
ve.dm.SurfaceFragment.prototype.select = function () {
	// Handle null fragment
	if ( this.isNull() ) {
		return this;
	}
	this.surface.setSelection( this.getRange() );
	return this;
};

/**
 * Change one or more attributes on covered nodes.
 *
 * @method
 * @param {Object} attr List of attributes to change, use undefined to remove an attribute
 * @param {string} [type] Node type to restrict changes to
 * @chainable
 */
ve.dm.SurfaceFragment.prototype.changeAttributes = function ( attr, type ) {
	// Handle null fragment
	if ( this.isNull() ) {
		return this;
	}

	var i, len, result,
		txs = [],
		covered = this.getCoveredNodes();

	for ( i = 0, len = covered.length; i < len; i++ ) {
		result = covered[i];
		if (
			// Non-wrapped nodes have no attributes
			!result.node.isWrapped() ||
			// Filtering by node type
			( type && result.node.getType() !== type ) ||
			// Ignore zero-length results
			( result.range && result.range.isCollapsed() )
		) {
			continue;
		}
		txs.push(
			ve.dm.Transaction.newFromAttributeChanges(
				this.document, result.nodeOuterRange.start, attr
			)
		);
	}
	if ( txs.length ) {
		this.change( txs );
	}
	return this;
};

/**
 * Apply an annotation to content in the fragment.
 *
 * To avoid problems identified in bug 33108, use the {ve.dm.SurfaceFragment.trimRange} method.
 *
 * TODO: Optionally take an annotation set instead of name and data arguments and set/clear multiple
 * annotations in a single transaction.
 *
 * @method
 * @param {string} method Mode of annotation, either 'set' or 'clear'
 * @param {string|ve.dm.Annotation} nameOrAnnotation Annotation name, for example: 'textStyle/bold' or
 * Annotation object
 * @param {Object} [data] Additional annotation data (not used if annotation object is given)
 * @chainable
 */
ve.dm.SurfaceFragment.prototype.annotateContent = function ( method, nameOrAnnotation, data ) {
	// Handle null fragment
	if ( this.isNull() ) {
		return this;
	}

	var annotation, annotations, i, ilen, tx,
		txs = [];

	if ( nameOrAnnotation instanceof ve.dm.Annotation ) {
		annotations = [ nameOrAnnotation ];
	} else {
		annotation = ve.dm.annotationFactory.create( nameOrAnnotation, data );
		if ( method === 'set' ) {
			annotations = [ annotation ];
		} else {
			annotations = this.document.data.getAnnotationsFromRange( this.getRange(), true )
				.getAnnotationsByName( annotation.name ).get();
		}
	}
	if ( this.getRange( true ).getLength() ) {
		// Apply to selection
		for ( i = 0, ilen = annotations.length; i < ilen; i++ ) {
			tx = ve.dm.Transaction.newFromAnnotation( this.document, this.getRange(), method, annotations[i] );
			txs.push( tx );
		}
		this.change( txs );
	} else {
		// Apply annotation to stack
		if ( method === 'set' ) {
			for ( i = 0, ilen = annotations.length; i < ilen; i++ ) {
				this.surface.addInsertionAnnotations( annotations[i] );
			}
		} else if ( method === 'clear' ) {
			for ( i = 0, ilen = annotations.length; i < ilen; i++ ) {
				this.surface.removeInsertionAnnotations( annotations[i] );
			}
		}
	}

	return this;
};

/**
 * Remove content in the fragment and insert content before it.
 *
 * This will move the fragment's range to cover the inserted content. Note that this may be
 * different from what a normal range translation would do: the insertion might occur
 * at a different offset if that is needed to make the document balanced.
 *
 * @method
 * @param {string|Array} content Content to insert, can be either a string or array of data
 * @param {boolean} annotate Content should be automatically annotated to match surrounding content
 * @chainable
 */
ve.dm.SurfaceFragment.prototype.insertContent = function ( content, annotate ) {
	// Handle null fragment
	if ( this.isNull() ) {
		return this;
	}

	var annotations, tx, newRange;

	if ( this.getRange( true ).getLength() ) {
		this.removeContent();
	}
	// Auto-convert content to array of plain text characters
	if ( typeof content === 'string' ) {
		content = ve.splitClusters( content );
	}
	if ( content.length ) {
		if ( annotate ) {
			// TODO: Don't reach into properties of document
			annotations = this.document.data
				.getAnnotationsFromOffset( this.getRange( true ).start - 1 );
			if ( annotations.getLength() > 0 ) {
				ve.dm.Document.static.addAnnotationsToData( content, annotations );
			}
		}
		tx = ve.dm.Transaction.newFromInsertion(
			this.document,
			this.getRange( true ).start,
			content
		);
		// Set the range to cover the inserted content; the offset translation will be wrong
		// if newFromInsertion() decided to move the insertion point
		newRange = tx.getModifiedRange();
		this.change( tx, newRange );
	}

	return this;
};

/**
 * Remove content in the fragment.
 *
 * @method
 * @chainable
 */
ve.dm.SurfaceFragment.prototype.removeContent = function () {
	// Handle null fragment
	if ( this.isNull() ) {
		return this;
	}

	if ( this.getRange( true ).getLength() ) {
		this.change( ve.dm.Transaction.newFromRemoval( this.document, this.getRange() ) );
	}

	return this;
};

/**
 * Convert each content branch in the fragment from one type to another.
 *
 * @method
 * @param {string} type Element type to convert to
 * @param {Object} [attr] Initial attributes for new element
 * @chainable
 */
ve.dm.SurfaceFragment.prototype.convertNodes = function ( type, attr ) {
	// Handle null fragment
	if ( this.isNull() ) {
		return this;
	}

	this.change( ve.dm.Transaction.newFromContentBranchConversion(
		this.document, this.getRange(), type, attr
	) );

	return this;
};

/**
 * Wrap each node in the fragment with one or more elements.
 *
 * A wrapper object is a linear model element; a plain object containing a type property and an
 * optional attributes property.
 *
 * Example:
 *     // fragment is a selection of: <p>a</p><p>b</p>
 *     fragment.wrapNodes(
 *         [{ type: 'list', attributes: { style: 'bullet' } }, { type: 'listItem' }]
 *     )
 *     // fragment is now a selection of: <ul><li><p>a</p></li></ul><ul><li><p>b</p></li></ul>
 *
 * @method
 * @param {Object|Object[]} wrapper Wrapper object, or array of wrapper objects (see above)
 * @param {string} wrapper.type Node type of wrapper
 * @param {Object} [wrapper.attributes] Attributes of wrapper
 * @chainable
 */
ve.dm.SurfaceFragment.prototype.wrapNodes = function ( wrapper ) {
	// Handle null fragment
	if ( this.isNull() ) {
		return this;
	}

	if ( !ve.isArray( wrapper ) ) {
		wrapper = [wrapper];
	}
	this.change(
		ve.dm.Transaction.newFromWrap( this.document, this.getRange(), [], [], [], wrapper )
	);

	return this;
};

/**
 * Unwrap nodes in the fragment out of one or more elements.
 *
 * Example:
 *     // fragment is a selection of: <ul>「<li><p>a</p></li><li><p>b</p></li>」</ul>
 *     fragment.unwrapNodes( 1, 1 )
 *     // fragment is now a selection of: 「<p>a</p><p>b</p>」
 *
 * @method
 * @param {number} outerDepth Number of nodes outside the selection to unwrap
 * @param {number} innerDepth Number of nodes inside the selection to unwrap
 * @chainable
 */
ve.dm.SurfaceFragment.prototype.unwrapNodes = function ( outerDepth, innerDepth ) {
	// Handle null fragment
	if ( this.isNull() ) {
		return this;
	}

	var i,
		innerUnwrapper = [],
		outerUnwrapper = [];

	if ( this.getRange( true ).end - this.getRange( true ).start < innerDepth * 2 ) {
		throw new Error( 'cannot unwrap by greater depth than maximum theoretical depth of selection' );
	}

	for ( i = 0; i < innerDepth; i++ ) {
		innerUnwrapper.push( this.surface.getDocument().data.getData( this.getRange( true ).start + i ) );
	}
	for ( i = outerDepth; i > 0; i-- ) {
		outerUnwrapper.push( this.surface.getDocument().data.getData( this.getRange( true ).start - i ) );
	}

	this.change( ve.dm.Transaction.newFromWrap(
		this.document, this.getRange(), outerUnwrapper, [], innerUnwrapper, []
	) );

	return this;
};

/**
 * Change the wrapping of each node in the fragment from one type to another.
 *
 * A wrapper object is a linear model element; a plain object containing a type property and an
 * optional attributes property.
 *
 * Example:
 *     // fragment is a selection of: <dl><dt><p>a</p></dt></dl><dl><dt><p>b</p></dt></dl>
 *     fragment.rewrapNodes(
 *         2,
 *         [{ type: 'list', attributes: { style: 'bullet' } }, { type: 'listItem' }]
 *     )
 *     // fragment is now a selection of: <ul><li><p>a</p></li></ul><ul><li><p>b</p></li></ul>
 *
 * @method
 * @param {number} depth Number of nodes to unwrap
 * @param {Object|Object[]} wrapper Wrapper object, or array of wrapper objects (see above)
 * @param {string} wrapper.type Node type of wrapper
 * @param {Object} [wrapper.attributes] Attributes of wrapper
 * @chainable
 */
ve.dm.SurfaceFragment.prototype.rewrapNodes = function ( depth, wrapper ) {
	// Handle null fragment
	if ( this.isNull() ) {
		return this;
	}

	var i,
		unwrapper = [];

	if ( !ve.isArray( wrapper ) ) {
		wrapper = [wrapper];
	}

	if ( this.getRange( true ).end - this.getRange( true ).start < depth * 2 ) {
		throw new Error( 'cannot unwrap by greater depth than maximum theoretical depth of selection' );
	}

	for ( i = 0; i < depth; i++ ) {
		unwrapper.push( this.surface.getDocument().data.getData( this.getRange( true ).start + i ) );
	}

	this.change(
		ve.dm.Transaction.newFromWrap( this.document, this.getRange(), [], [], unwrapper, wrapper )
	);

	return this;
};

/**
 * Wrap nodes in the fragment with one or more elements.
 *
 * A wrapper object is a linear model element; a plain object containing a type property and an
 * optional attributes property.
 *
 * Example:
 *     // fragment is a selection of: <p>a</p><p>b</p>
 *     fragment.wrapAllNodes(
 *         [{ type: 'list', attributes: { style: 'bullet' } }, { type: 'listItem' }]
 *     )
 *     // fragment is now a selection of: <ul><li><p>a</p><p>b</p></li></ul>
 *
 * @method
 * @param {Object|Object[]} wrapper Wrapper object, or array of wrapper objects (see above)
 * @param {string} wrapper.type Node type of wrapper
 * @param {Object} [wrapper.attributes] Attributes of wrapper
 * @chainable
 */
ve.dm.SurfaceFragment.prototype.wrapAllNodes = function ( wrapper ) {
	// Handle null fragment
	if ( this.isNull() ) {
		return this;
	}

	if ( !ve.isArray( wrapper ) ) {
		wrapper = [wrapper];
	}

	this.change(
		ve.dm.Transaction.newFromWrap( this.document, this.getRange(), [], wrapper, [], [] )
	);

	return this;
};

/**
 * Change the wrapping of nodes in the fragment from one type to another.
 *
 * A wrapper object is a linear model element; a plain object containing a type property and an
 * optional attributes property.
 *
 * Example:
 *     // fragment is a selection of: <h1><p>a</p><p>b</p></h1>
 *     fragment.rewrapAllNodes( 1, { type: 'heading', attributes: { level: 2 } } );
 *     // fragment is now a selection of: <h2><p>a</p><p>b</p></h2>
 *
 * @method
 * @param {number} depth Number of nodes to unwrap
 * @param {Object|Object[]} wrapper Wrapper object, or array of wrapper objects (see above)
 * @param {string} wrapper.type Node type of wrapper
 * @param {Object} [wrapper.attributes] Attributes of wrapper
 * @chainable
 */
ve.dm.SurfaceFragment.prototype.rewrapAllNodes = function ( depth, wrapper ) {
	// Handle null fragment
	if ( this.isNull() ) {
		return this;
	}

	var i, unwrapper = [],
		innerRange = new ve.Range(
			this.getRange( true ).start + depth,
			this.getRange( true ).end - depth
		);

	if ( !ve.isArray( wrapper ) ) {
		wrapper = [wrapper];
	}

	if ( this.getRange( true ).end - this.getRange( true ).start < depth * 2 ) {
		throw new Error( 'cannot unwrap by greater depth than maximum theoretical depth of selection' );
	}

	for ( i = 0; i < depth; i++ ) {
		unwrapper.push( this.surface.getDocument().data.getData( this.getRange( true ).start + i ) );
	}

	this.change(
		ve.dm.Transaction.newFromWrap( this.document, innerRange, unwrapper, wrapper, [], [] )
	);

	return this;
};

/**
 * Isolates the nodes in a fragment then unwraps them.
 *
 * The node selection is expanded to siblings. These are isolated such that they are the
 * sole children of the nearest parent element which can 'type' can exist in.
 *
 * The new isolated selection is then safely unwrapped.
 *
 * @method
 * @param {string} type Node type to isolate for
 * @chainable
 */
ve.dm.SurfaceFragment.prototype.isolateAndUnwrap = function ( isolateForType ) {
	// Handle null fragment
	if ( this.isNull() ) {
		return this;
	}

	var nodes, startSplitNode, endSplitNode,
		startOffset, endOffset, oldExclude,
		outerDepth = 0,
		factory = ve.dm.nodeFactory,
		allowedParents = factory.getSuggestedParentNodeTypes( isolateForType ),
		startSplitRequired = false,
		endSplitRequired = false,
		startSplitNodes = [],
		endSplitNodes = [],
		fragment = this;

	function createSplits( splitNodes, insertBefore ) {
		var i, length, tx,
			adjustment = 0, data = [];
		for ( i = 0, length = splitNodes.length; i < length; i++ ) {
			data.unshift( { type: '/' + splitNodes[i].type } );
			data.push( splitNodes[i].getClonedElement() );

			if ( insertBefore ) {
				adjustment += 2;
			}
		}

		tx = ve.dm.Transaction.newFromInsertion( fragment.getDocument(), insertBefore ? startOffset : endOffset, data );
		fragment.change( tx );

		startOffset += adjustment;
		endOffset += adjustment;
	}

	nodes = this.getDocument().selectNodes( this.getRange(), 'siblings' );

	// Find start split point, if required
	startSplitNode = nodes[0].node;
	startOffset = startSplitNode.getOuterRange().start;
	while ( allowedParents !== null && ve.indexOf( startSplitNode.getParent().type, allowedParents ) === -1 ) {
		if ( startSplitNode.getParent().indexOf( startSplitNode ) > 0 ) {
			startSplitRequired = true;
		}
		startSplitNode = startSplitNode.getParent();
		if ( startSplitRequired ) {
			startSplitNodes.unshift( startSplitNode );
		} else {
			startOffset = startSplitNode.getOuterRange().start;
		}
		outerDepth++;
	}

	// Find end split point, if required
	endSplitNode = nodes[nodes.length - 1].node;
	endOffset = endSplitNode.getOuterRange().end;
	while ( allowedParents !== null && ve.indexOf( endSplitNode.getParent().type, allowedParents ) === -1 ) {
		if ( endSplitNode.getParent().indexOf( endSplitNode ) < endSplitNode.getParent().getChildren().length - 1 ) {
			endSplitRequired = true;
		}
		endSplitNode = endSplitNode.getParent();
		if ( endSplitRequired ) {
			endSplitNodes.unshift( endSplitNode );
		} else {
			endOffset = endSplitNode.getOuterRange().end;
		}
	}

	// We have to exclude insertions while doing splits, because we want the range to be
	// exactly what we're isolating, we don't want it to grow to include the separators
	// we're inserting (which would happen if one of them is immediately adjacent to the range)
	oldExclude = this.willExcludeInsertions();
	this.setExcludeInsertions( true );

	if ( startSplitRequired ) {
		createSplits( startSplitNodes, true );
	}

	if ( endSplitRequired ) {
		createSplits( endSplitNodes, false );
	}

	this.setExcludeInsertions( oldExclude );

	this.unwrapNodes( outerDepth, 0 );

	return this;
};


text:
var express = require('express')
        , app = express()
        , morgan = require('morgan')
        , bodyParser = require('body-parser');

// configuration
app.use(express.static(__dirname + '/www'));                  // set the static files location
app.use(morgan('dev'));                                       // log every request to the console
app.use(bodyParser.urlencoded({'extended': 'true'}));         // parse application/x-www-form-urlencoded
app.use(bodyParser.json());                                   // parse application/json
app.use(bodyParser.json({type: 'application/vnd.api+json'})); // parse application/vnd.api+json as json

// routes
require('./routes.js')(app);

// listen (start app with node server.js)
app.listen(8080);
console.log("App listening on port 8080");

redpajama_set_name: RedPajamaGithub


text:
#include <events/mbed_events.h>
#include <mbed.h>
#include "ble/BLE.h"
#include "ble/Gap.h"
#include "ble/services/HeartRateService.h"

DigitalOut led1(LED1, 1);

const static char     DEVICE_NAME[] = "HRM";
static const uint16_t uuid16_list[] = {GattService::UUID_HEART_RATE_SERVICE};

static uint8_t hrmCounter = 100; // init HRM to 100bps
static HeartRateService *hrServicePtr;

static EventQueue eventQueue(/* event count */ 16 * EVENTS_EVENT_SIZE);

void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *params)
{
    BLE::Instance().gap().startAdvertising(); // restart advertising
}

void updateSensorValue() {
    // Do blocking calls or whatever is necessary for sensor polling.
    // In our case, we simply update the HRM measurement.
    hrmCounter++;

    //  100 <= HRM bps <=175
    if (hrmCounter == 175) {
        hrmCounter = 100;
    }

    hrServicePtr->updateHeartRate(hrmCounter);
}

void periodicCallback(void)
{
    led1 = !led1; /* Do blinky on LED1 while we're waiting for BLE events */

    if (BLE::Instance().getGapState().connected) {
        eventQueue.call(updateSensorValue);
    }
}

void onBleInitError(BLE &ble, ble_error_t error)
{
    (void)ble;
    (void)error;
   /* Initialization error handling should go here */
}

void bleInitComplete(BLE::InitializationCompleteCallbackContext *params)
{
    BLE&        ble   = params->ble;
    ble_error_t error = params->error;

    if (error != BLE_ERROR_NONE) {
        onBleInitError(ble, error);
        return;
    }

    if (ble.getInstanceID() != BLE::DEFAULT_INSTANCE) {
        return;
    }

    ble.gap().onDisconnection(disconnectionCallback);

    /* Setup primary service. */
    hrServicePtr = new HeartRateService(ble, hrmCounter, HeartRateService::LOCATION_FINGER);

    /* Setup advertising. */
    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS, (uint8_t *)uuid16_list, sizeof(uuid16_list));
    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::GENERIC_HEART_RATE_SENSOR);
    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME));
    ble.gap().setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
    ble.gap().setAdvertisingInterval(1000); /* 1000ms */
    ble.gap().startAdvertising();
}

void scheduleBleEventsProcessing(BLE::OnEventsToProcessCallbackContext* context) {
    BLE &ble = BLE::Instance();
    eventQueue.call(Callback<void()>(&ble, &BLE::processEvents));
}

int main()
{
    eventQueue.call_every(500, periodicCallback);

    BLE &ble = BLE::Instance();
    ble.onEventsToProcess(scheduleBleEventsProcessing);
    ble.init(bleInitComplete);

    eventQueue.dispatch_forever();

    return 0;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit trunk//EN" "http://google-web-toolkit.googlecode.com/svn/trunk/distro-source/core/src/gwt-module.dtd">
<module rename-to="html">
	<inherits name='com.badlogic.gdx.backends.gdx_backends_gwt' />

	<inherits name='DrawingLines' />
	<entry-point class='com.udacity.gamedev.drawinglines.client.HtmlLauncher' />

	<set-configuration-property name="gdx.assetpath" value="../android/assets" />
</module>


text:
<?php

namespace MicroCMS\Controller;

use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use MicroCMS\Domain\Article;

class ApiController {

    /**
     * API articles controller.
     *
     * @param Application $app Silex application
     *
     * @return All articles in JSON format
     */
    public function getArticlesAction(Application $app) {
        $articles = $app['dao.article']->findAll();
        // Convert an array of objects ($articles) into an array of associative arrays ($responseData)
        $responseData = array();
        foreach ($articles as $article) {
            $responseData[] = $this->buildArticleArray($article);
        }
        // Create and return a JSON response
        return $app->json($responseData);
    }

    /**
     * API article details controller.
     *
     * @param integer $id Article id
     * @param Application $app Silex application
     *
     * @return Article details in JSON format
     */
    public function getArticleAction($id, Application $app) {
        $article = $app['dao.article']->find($id);
        $responseData = $this->buildArticleArray($article);
        // Create and return a JSON response
        return $app->json($responseData);
    }

    /**
     * API create article controller.
     *
     * @param Request $request Incoming request
     * @param Application $app Silex application
     *
     * @return Article details in JSON format
     */
    public function addArticleAction(Request $request, Application $app) {
        // Check request parameters
        if (!$request->request->has('title')) {
            return $app->json('Missing required parameter: title', 400);
        }
        if (!$request->request->has('content')) {
            return $app->json('Missing required parameter: content', 400);
        }
        // Build and save the new article
        $article = new Article();
        $article->setTitle($request->request->get('title'));
        $article->setContent($request->request->get('content'));
        $app['dao.article']->save($article);
        $responseData = $this->buildArticleArray($article);
        return $app->json($responseData, 201);  // 201 = Created
    }

    /**
     * API delete article controller.
     *
     * @param integer $id Article id
     * @param Application $app Silex application
     */
    public function deleteArticleAction($id, Application $app) {
        // Delete all associated comments
        $app['dao.comment']->deleteAllByArticle($id);
        // Delete the article
        $app['dao.article']->delete($id);
        return $app->json('No Content', 204);  // 204 = No content
    }

    /**
     * Converts an Article object into an associative array for JSON encoding
     *
     * @param Article $article Article object
     *
     * @return array Associative array whose fields are the article properties.
     */
    private function buildArticleArray(Article $article) {
        $data  = array(
            'id' => $article->getId(),
            'title' => $article->getTitle(),
            'content' => $article->getContent()
            );
        return $data;
    }
}


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>pants.observe</title>

    <link rel="import" href="../pants-path/pants-path.html">

    <script type="text/javascript" src="js/weakmap.poly.js"></script>
    <script type="text/javascript" src="js/observe.poly.js"></script>
    <script type="text/javascript" src="js/observe.js"></script>
</head>
<body>

</body>
</html>


text:
using System;
using System.Threading.Tasks;
using Plivo.Resource.PhoneNumber;
using System.Collections.Generic;
namespace Plivo.Resource.Powerpack {
    /// <summary>
    /// Powerpack.
    /// </summary>
    public class Powerpack : Resource {
        public new string Id => uuid;
        public string number_pool_id { get; set; }

        public Lazy<PhoneNumberInterface> _phonenumber;
        private PhoneNumberInterface PhoneNumberI => _phonenumber.Value;

        public NumberPool numberpool;
        /// <summary>
        /// Applicatio ID
        /// </summary>
        /// <value>The application_id .</value>
        public string application_id { get; set; }

        /// <summary>
        /// Gets or sets application type.
        /// </summary>
        /// <value>Application_type.</value>
        public string application_type { get; set; }

        /// <summary>
        /// Gets or sets the created_on.
        /// </summary>
        /// <value>The created_on.</value>
        public string created_on { get; set; }

        /// <summary>
        /// Gets or sets  the LocalConnect.
        /// </summary>
        /// <value>The LocalConnect.</value>
        public bool local_connect { get; set; }

        /// <summary>
        /// Gets or sets the sticky_sender.
        /// </summary>
        /// <value>The sticky_sender.</value>
        public bool sticky_sender { get; set; }

        /// <summary>
        /// Gets or sets name.
        /// </summary>
        /// <value>The powerpack name.</value>
        public string name { get; set; }

        /// <summary>
        /// Gets or sets  UUID.
        /// </summary>
        /// <value>The uuid.</value>
        public string uuid { get; set; }

        /// <summary>
        /// Number Priority
        /// </summary>
        /// <value>The number_priority .</value>
        public List<NumberPriority> number_priority { get; set; }

        /// <summary>
        /// Gets or sets the number_pool.
        /// </summary>
        /// <value>The number_pool.</value>
        public string number_pool { get; set; }
        public Powerpack () { }
        public DeleteResponse<Powerpack> Delete (bool? unrent_numbers = false) {
            return ((PowerpackInterface) Interface)
                .Delete (Id, unrent_numbers);
        }

        public async Task<DeleteResponse<Powerpack>> DeleteAsync (bool? unrent_numbers = false) {
            return await ((PowerpackInterface) Interface)
                .DeleteAsync (Id, unrent_numbers);
        }

        public UpdateResponse<Powerpack> Update (string name = null, string application_type = null, string application_id = null,
            bool? sticky_sender = null, bool? local_connect = null, List<NumberPriority> number_priority = null) {
            return ((PowerpackInterface) Interface)
                .Update (Id, name, application_type, application_id, sticky_sender, local_connect, number_priority);
        }
        public async Task<UpdateResponse<Powerpack>> UpdateAsync (string name = null, string application_type = null, string application_id = null,
            bool? sticky_sender = null, bool? local_connect = null, List<NumberPriority> number_priority = null) {
            return await ((PowerpackInterface) Interface)
                .UpdateAsync (Id, name, application_type, application_id, sticky_sender, local_connect, number_priority);
        }
        public ListResponse<Numbers> List_Numbers (string starts_with = null, string country_iso2 = null,
            string type = null, string service = null, uint? limit = null, uint? offset = null) {
            return ((PowerpackInterface) Interface)
                .List_Numbers (number_pool_id, starts_with, country_iso2, type, limit, offset, service);
        }
        public async Task<ListResponse<Numbers>> List_NumbersAsync (
            string starts_with = null, string country_iso2 = null,
            string type = null, string service = null, uint? limit = null, uint? offset = null) {
            return await ((PowerpackInterface) Interface)
                .List_NumbersAsync (number_pool_id, starts_with, country_iso2, type, limit, offset, service);

        }

        public uint Count_Numbers (string starts_with = null, string country_iso2 = null,
            string type = null, string service = null, uint? limit = null, uint? offset = null) {
            return ((PowerpackInterface) Interface)
                .Count_Number (number_pool_id, starts_with, country_iso2, type, limit, offset, service);
        }
        public async Task<uint> Count_NumbersAsync (
            string starts_with = null, string country_iso2 = null,
            string type = null, string service = null, uint? limit = null, uint? offset = null) {
            return await ((PowerpackInterface) Interface)
                .Count_NumbersAsync (number_pool_id, starts_with, country_iso2, type, limit, offset, service);

        }
        public Numbers Add_Number (string number, string service = null) {
            return ((PowerpackInterface) Interface)
                .Add_Number (number_pool_id, number, service);
        }
        public async Task<Numbers> Add_NumberAsync (string number, string service = null) {
            return await ((PowerpackInterface) Interface)
                .Add_NumberAsync (number_pool_id, number, service);
        }

        public Tollfree Add_Tollfree (string tollfree) {
            return ((PowerpackInterface) Interface)
                .Add_Tollfree (number_pool_id, tollfree);
        }
        public async Task<Tollfree> Add_TollfreeAsync (string tollfree) {
            return await ((PowerpackInterface) Interface)
                .Add_TollfreeAsync (number_pool_id, tollfree);
        }

        public DeleteResponse<Numbers> Remove_Number (string number, bool? unrent = null) {
            return ((PowerpackInterface) Interface)
                .Remove_Number (number_pool_id, number, unrent);
        }
        public async Task<DeleteResponse<Numbers>> Remove_NumberAsync (
            string number, bool? unrent = null) {
            return await ((PowerpackInterface) Interface)
                .Remove_NumberAsync (number_pool_id, number, unrent);
        }

        public DeleteResponse<Tollfree> Remove_Tollfree (string tollfree, bool? unrent = null) {
            return ((PowerpackInterface) Interface)
                .Remove_Tollfree (number_pool_id, tollfree, unrent);
        }
        public async Task<DeleteResponse<Tollfree>> Remove_TollfreeAsync (
            string tollfree, bool? unrent = null) {
            return await ((PowerpackInterface) Interface)
                .Remove_TollfreeAsync (number_pool_id, tollfree, unrent);
        }

        public Numbers Find_Number (string number, string service = null) {
            return ((PowerpackInterface) Interface)
                .Find_Number (number_pool_id, number, service);
        }
        public async Task<Numbers> Find_NumberAsync (
            string number, string service = null) {
            return await ((PowerpackInterface) Interface)
                .Find_NumberAsync (number_pool_id, number, service);
        }
        public ListResponse<Shortcode> List_Shortcode (uint? limit = null, uint? offset = null) {
            return ((PowerpackInterface) Interface)
                .ListShortcode (number_pool_id, limit, offset);
        }
        public async Task<ListResponse<Shortcode>> List_ShortcodeAsync (uint? limit = null, uint? offset = null) {
            return await ((PowerpackInterface) Interface)
                .List_ShortcodeAsync (number_pool_id, limit, offset);
        }

        public Shortcode Find_Shortcode (string shortcode) {
            return ((PowerpackInterface) Interface)
                .Find_Shortcode (shortcode, number_pool_id);
        }
        public async Task<Shortcode> Find_ShortcodeAsync (
            string shortcode) {
            return await ((PowerpackInterface) Interface)
                .Find_ShortcodeAsync (shortcode, number_pool_id);
        }

        public DeleteResponse<Shortcode> Remove_Shortcode (string shortcode, bool? unrent = null) {
            return ((PowerpackInterface) Interface)
                .Remove_Shortcode (number_pool_id, shortcode, unrent);
        }
        public async Task<DeleteResponse<Shortcode>> Remove_ShortcodeAsync (
            string shortcode, bool? unrent = null) {
            return await ((PowerpackInterface) Interface)
                .Remove_ShortcodeAsync (number_pool_id, shortcode, unrent);
        }

        public ListResponse<Tollfree> List_Tollfree (uint? limit = null, uint? offset = null) {
            return ((PowerpackInterface) Interface)
                .ListTollfree (number_pool_id, limit, offset);
        }
        public async Task<ListResponse<Tollfree>> List_TollfreeAsync (uint? limit = null, uint? offset = null) {
            return await ((PowerpackInterface) Interface)
                .List_TollfreeAsync (number_pool_id, limit, offset);
        }

        public Tollfree Find_Tollfree (string tollfree) {
            return ((PowerpackInterface) Interface)
                .Find_Tollfree (tollfree, number_pool_id);
        }
        public async Task<Tollfree> Find_TollfreeAsync (
            string tollfree) {
            return await ((PowerpackInterface) Interface)
                .Find_TollfreeAsync (tollfree, number_pool_id);
        }

        public Numbers Buy_Add_Number (string number = null, string type = null, string country_iso2 = null, string region = null, string pattern = null, string service = null) {
            if (number == null) {
                var countryIso = country_iso2;
                var numbers = PhoneNumberI.List (countryIso, type, pattern, region);
                number = numbers.Objects[0].Number;
            }
            return ((PowerpackInterface) Interface)
                .Add_Number (number_pool_id, number, service, true);
        }
        public async Task<Numbers> Buy_Add_NumberAsync (string number = null, string type = null, string country_iso2 = null, string region = null, string pattern = null, string service = null) {
            if (number == null) {
                var countryIso = country_iso2;
                var numbers = PhoneNumberI.List (countryIso, type, pattern, region);
                number = numbers.Objects[0].Number;
            }
            return await ((PowerpackInterface) Interface)
                .Add_NumberAsync (number_pool_id, number, service, true);
        }

        public override string ToString () {
            return "\n" +
                "UUID: " + uuid + "\n" +
                "Name: " + name + "\n" +
                "StickySender: " + sticky_sender + "\n" +
                "LocalConnect: " + local_connect + "\n" +
                "ApplicationType: " + application_type + "\n" +
                "ApplicationId: " + application_id + "\n" +
                "NumberPool: " + number_pool + "\n" +
                "CreatedOn: " + created_on + "\n" +
                "NumberPriority: " + number_priority + "\n";
        }
    }
}


text:
package org.apache.calcite.sql.validate;

import org.apache.calcite.linq4j.Linq4j;
import org.apache.calcite.linq4j.Ord;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.sql.SqlCall;
import org.apache.calcite.sql.SqlNode;
import org.apache.calcite.sql.SqlNodeList;
import org.apache.calcite.sql.SqlSelect;
import org.apache.calcite.util.ImmutableBitSet;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

import java.util.List;
import java.util.Map;
import java.util.Set;

import static org.apache.calcite.sql.SqlUtil.stripAs;

/**
 * Scope for resolving identifiers within a SELECT statement that has a
 * GROUP BY clause.
 *
 *
The same set of identifiers are in scope, but it won't allow access to
 * identifiers or expressions which are not group-expressions.
 */
public class AggregatingSelectScope
    extends DelegatingScope implements AggregatingScope {
  //~ Instance fields --------------------------------------------------------

  private final SqlSelect select;
  private final boolean distinct;

  /** Use while under construction. */
  private final List<SqlNode> temporaryGroupExprList = Lists.newArrayList();

  /** Use after construction is complete. Assigned from
   * {@link #temporaryGroupExprList} towards the end of the constructor. */
  public final ImmutableList<SqlNode> groupExprList;
  public final ImmutableBitSet groupSet;
  public final ImmutableList<ImmutableBitSet> groupSets;
  public final boolean indicator;
  public final Map<Integer, Integer> groupExprProjection;

  //~ Constructors -----------------------------------------------------------

  /**
   * Creates an AggregatingSelectScope
   *
   * @param selectScope Parent scope
   * @param select      Enclosing SELECT node
   * @param distinct    Whether SELECT is DISTINCT
   */
  AggregatingSelectScope(
      SqlValidatorScope selectScope,
      SqlSelect select,
      boolean distinct) {
    // The select scope is the parent in the sense that all columns which
    // are available in the select scope are available. Whether they are
    // valid as aggregation expressions... now that's a different matter.
    super(selectScope);
    this.select = select;
    this.distinct = distinct;
    final Map<Integer, Integer> groupExprProjection = Maps.newHashMap();
    final ImmutableList.Builder<ImmutableList<ImmutableBitSet>> builder =
        ImmutableList.builder();
    if (select.getGroup() != null) {
      // We deep-copy the group-list in case subsequent validation
      // modifies it and makes it no longer equivalent. While copying,
      // we fully qualify all identifiers.
      final SqlNodeList groupList = select.getGroup();
//          SqlValidatorUtil.DeepCopier.copy(parent, select.getGroup());
      for (SqlNode groupExpr : groupList) {
        SqlValidatorUtil.analyzeGroupItem(this, temporaryGroupExprList,
            groupExprProjection, builder, groupExpr);
      }
    }
    this.groupExprList = ImmutableList.copyOf(temporaryGroupExprList);
    this.groupExprProjection = ImmutableMap.copyOf(groupExprProjection);

    final Set<ImmutableBitSet> flatGroupSets =
        Sets.newTreeSet(ImmutableBitSet.COMPARATOR);
    for (List<ImmutableBitSet> groupSet : Linq4j.product(builder.build())) {
      flatGroupSets.add(ImmutableBitSet.union(groupSet));
    }

    // For GROUP BY (), we need a singleton grouping set.
    if (flatGroupSets.isEmpty()) {
      flatGroupSets.add(ImmutableBitSet.of());
    }

    this.groupSet = ImmutableBitSet.range(groupExprList.size());
    this.groupSets = ImmutableList.copyOf(flatGroupSets);
    this.indicator = !groupSets.equals(ImmutableList.of(groupSet));
  }

  //~ Methods ----------------------------------------------------------------

  /**
   * Returns the expressions that are in the GROUP BY clause (or the SELECT
   * DISTINCT clause, if distinct) and that can therefore be referenced
   * without being wrapped in aggregate functions.
   *
   *
The expressions are fully-qualified, and any "*" in select clauses are
   * expanded.
   *
   * @return list of grouping expressions
   */
  private ImmutableList<SqlNode> getGroupExprs() {
    if (distinct) {
      // Cannot compute this in the constructor: select list has not been
      // expanded yet.
      assert select.isDistinct();

      // Remove the AS operator so the expressions are consistent with
      // OrderExpressionExpander.
      ImmutableList.Builder<SqlNode> groupExprs = ImmutableList.builder();
      final SelectScope selectScope = (SelectScope) parent;
      for (SqlNode selectItem : selectScope.getExpandedSelectList()) {
        groupExprs.add(stripAs(selectItem));
      }
      return groupExprs.build();
    } else if (select.getGroup() != null) {
      if (groupExprList != null) {
        return groupExprList;
      } else {
        return ImmutableList.copyOf(temporaryGroupExprList);
      }
    } else {
      return ImmutableList.of();
    }
  }

  public SqlNode getNode() {
    return select;
  }

  /** Returns whether a field should be nullable due to grouping sets. */
  public boolean isNullable(int i) {
    return i < groupExprList.size() && !allContain(groupSets, i);
  }

  private static boolean allContain(List<ImmutableBitSet> bitSets, int bit) {
    for (ImmutableBitSet bitSet : bitSets) {
      if (!bitSet.get(bit)) {
        return false;
      }
    }
    return true;
  }

  @Override public RelDataType nullifyType(SqlNode node, RelDataType type) {
    for (Ord<SqlNode> groupExpr : Ord.zip(groupExprList)) {
      if (groupExpr.e.equalsDeep(node, false)) {
        if (isNullable(groupExpr.i)) {
          return validator.getTypeFactory().createTypeWithNullability(type,
              true);
        }
      }
    }
    return type;
  }

  public SqlValidatorScope getOperandScope(SqlCall call) {
    if (call.getOperator().isAggregator()) {
      // If we're the 'SUM' node in 'select a + sum(b + c) from t
      // group by a', then we should validate our arguments in
      // the non-aggregating scope, where 'b' and 'c' are valid
      // column references.
      return parent;
    } else {
      // Check whether expression is constant within the group.
      //
      // If not, throws. Example, 'empno' in
      //    SELECT empno FROM emp GROUP BY deptno
      //
      // If it perfectly matches an expression in the GROUP BY
      // clause, we validate its arguments in the non-aggregating
      // scope. Example, 'empno + 1' in
      //
      //   SELECT empno + 1 FROM emp GROUP BY empno + 1

      final boolean matches = checkAggregateExpr(call, false);
      if (matches) {
        return parent;
      }
    }
    return super.getOperandScope(call);
  }

  public boolean checkAggregateExpr(SqlNode expr, boolean deep) {
    // Fully-qualify any identifiers in expr.
    if (deep) {
      expr = validator.expand(expr, this);
    }

    // Make sure expression is valid, throws if not.
    List<SqlNode> groupExprs = getGroupExprs();
    final AggChecker aggChecker =
        new AggChecker(
            validator,
            this,
            groupExprs,
            distinct);
    if (deep) {
      expr.accept(aggChecker);
    }

    // Return whether expression exactly matches one of the group
    // expressions.
    return aggChecker.isGroupExpr(expr);
  }

  public void validateExpr(SqlNode expr) {
    checkAggregateExpr(expr, true);
  }

  /** Returns whether a given expression is equal to one of the grouping
   * expressions. Determines whether it is valid as an operand to GROUPING. */
  public boolean isGroupingExpr(SqlNode operand) {
    return lookupGroupingExpr(operand) >= 0;
  }

  public int lookupGroupingExpr(SqlNode operand) {
    for (Ord<SqlNode> groupExpr : Ord.zip(groupExprList)) {
      if (operand.equalsDeep(groupExpr.e, false)) {
        return groupExpr.i;
      }
    }
    return -1;
  }
}

// End AggregatingSelectScope.java


text:
Repo
****
The official repo is now https://github.com/wraithan/zenircbot

Resources
*********

* Docs on `Read The Docs`_
* Issues on `GitHub Issues`_
* Support in the `#pdxbots`_ channel on Freenode

.. _`Read The Docs`: http://zenircbot.readthedocs.org/
.. _`GitHub Issues`: https://github.com/wraithan/zenircbot/issues?milestone=1&state=open
.. _`#pdxbots`: irc://chat.freenode.net/#pdxbots


text:
/**
 */
package Changes.util;

import Changes.*;

import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.Notifier;

import org.eclipse.emf.common.notify.impl.AdapterFactoryImpl;

import org.eclipse.emf.ecore.EObject;

/**
 *
 * The Adapter Factory for the model.
 * It provides an adapter createXXX method for each class of the model.
 *
 * @see Changes.ChangesPackage
 * @generated
 */
public class ChangesAdapterFactory extends AdapterFactoryImpl {
	/**
	 * The cached model package.
	 *
	 *
	 * @generated
	 */
	protected static ChangesPackage modelPackage;

	/**
	 * Creates an instance of the adapter factory.
	 *
	 *
	 * @generated
	 */
	public ChangesAdapterFactory() {
		if (modelPackage == null) {
			modelPackage = ChangesPackage.eINSTANCE;
		}
	}

	/**
	 * Returns whether this factory is applicable for the type of the object.
	 *
	 * This implementation returns true if the object is either the model's package or is an instance object of the model.
	 *
	 * @return whether this factory is applicable for the type of the object.
	 * @generated
	 */
	@Override
	public boolean isFactoryForType(Object object) {
		if (object == modelPackage) {
			return true;
		}
		if (object instanceof EObject) {
			return ((EObject)object).eClass().getEPackage() == modelPackage;
		}
		return false;
	}

	/**
	 * The switch that delegates to the createXXX methods.
	 *
	 *
	 * @generated
	 */
	protected ChangesSwitch<Adapter> modelSwitch =
		new ChangesSwitch<Adapter>() {
			@Override
			public Adapter caseModelChangeSet(ModelChangeSet object) {
				return createModelChangeSetAdapter();
			}
			@Override
			public Adapter caseModelChange(ModelChange object) {
				return createModelChangeAdapter();
			}
			@Override
			public Adapter caseElementaryChange(ElementaryChange object) {
				return createElementaryChangeAdapter();
			}
			@Override
			public Adapter caseElementaryChangeTransaction(ElementaryChangeTransaction object) {
				return createElementaryChangeTransactionAdapter();
			}
			@Override
			public Adapter caseCollectionDeletion(CollectionDeletion object) {
				return createCollectionDeletionAdapter();
			}
			@Override
			public Adapter caseAssociationCollectionDeletion(AssociationCollectionDeletion object) {
				return createAssociationCollectionDeletionAdapter();
			}
			@Override
			public Adapter caseCompositionCollectionDeletion(CompositionCollectionDeletion object) {
				return createCompositionCollectionDeletionAdapter();
			}
			@Override
			public Adapter caseAttributeCollectionDeletion(AttributeCollectionDeletion object) {
				return createAttributeCollectionDeletionAdapter();
			}
			@Override
			public Adapter caseCollectionInsertion(CollectionInsertion object) {
				return createCollectionInsertionAdapter();
			}
			@Override
			public Adapter caseAssociationCollectionInsertion(AssociationCollectionInsertion object) {
				return createAssociationCollectionInsertionAdapter();
			}
			@Override
			public Adapter caseCompositionCollectionInsertion(CompositionCollectionInsertion object) {
				return createCompositionCollectionInsertionAdapter();
			}
			@Override
			public Adapter caseAttributeCollectionInsertion(AttributeCollectionInsertion object) {
				return createAttributeCollectionInsertionAdapter();
			}
			@Override
			public Adapter caseCollectionReset(CollectionReset object) {
				return createCollectionResetAdapter();
			}
			@Override
			public Adapter caseAssociationCollectionReset(AssociationCollectionReset object) {
				return createAssociationCollectionResetAdapter();
			}
			@Override
			public Adapter caseCompositionCollectionReset(CompositionCollectionReset object) {
				return createCompositionCollectionResetAdapter();
			}
			@Override
			public Adapter caseAttributeCollectionReset(AttributeCollectionReset object) {
				return createAttributeCollectionResetAdapter();
			}
			@Override
			public Adapter caseListDeletion(ListDeletion object) {
				return createListDeletionAdapter();
			}
			@Override
			public Adapter caseAssociationListDeletion(AssociationListDeletion object) {
				return createAssociationListDeletionAdapter();
			}
			@Override
			public Adapter caseCompositionListDeletion(CompositionListDeletion object) {
				return createCompositionListDeletionAdapter();
			}
			@Override
			public Adapter caseAttributeListDeletion(AttributeListDeletion object) {
				return createAttributeListDeletionAdapter();
			}
			@Override
			public Adapter caseListInsertion(ListInsertion object) {
				return createListInsertionAdapter();
			}
			@Override
			public Adapter caseAssociationListInsertion(AssociationListInsertion object) {
				return createAssociationListInsertionAdapter();
			}
			@Override
			public Adapter caseCompositionListInsertion(CompositionListInsertion object) {
				return createCompositionListInsertionAdapter();
			}
			@Override
			public Adapter caseAttributeListInsertion(AttributeListInsertion object) {
				return createAttributeListInsertionAdapter();
			}
			@Override
			public Adapter casePropertyChange(PropertyChange object) {
				return createPropertyChangeAdapter();
			}
			@Override
			public Adapter caseAttributeChange(AttributeChange object) {
				return createAttributeChangeAdapter();
			}
			@Override
			public Adapter caseAssociationChange(AssociationChange object) {
				return createAssociationChangeAdapter();
			}
			@Override
			public Adapter caseCompositionChange(CompositionChange object) {
				return createCompositionChangeAdapter();
			}
			@Override
			public Adapter defaultCase(EObject object) {
				return createEObjectAdapter();
			}
		};

	/**
	 * Creates an adapter for the target.
	 *
	 *
	 * @param target the object to adapt.
	 * @return the adapter for the target.
	 * @generated
	 */
	@Override
	public Adapter createAdapter(Notifier target) {
		return modelSwitch.doSwitch((EObject)target);
	}

	/**
	 * Creates a new adapter for an object of class '{@link Changes.ModelChangeSet Model Change Set}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see Changes.ModelChangeSet
	 * @generated
	 */
	public Adapter createModelChangeSetAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link Changes.ModelChange Model Change}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see Changes.ModelChange
	 * @generated
	 */
	public Adapter createModelChangeAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link Changes.ElementaryChange Elementary Change}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see Changes.ElementaryChange
	 * @generated
	 */
	public Adapter createElementaryChangeAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link Changes.ElementaryChangeTransaction Elementary Change Transaction}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see Changes.ElementaryChangeTransaction
	 * @generated
	 */
	public Adapter createElementaryChangeTransactionAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link Changes.CollectionDeletion Collection Deletion}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see Changes.CollectionDeletion
	 * @generated
	 */
	public Adapter createCollectionDeletionAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link Changes.AssociationCollectionDeletion Association Collection Deletion}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see Changes.AssociationCollectionDeletion
	 * @generated
	 */
	public Adapter createAssociationCollectionDeletionAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link Changes.CompositionCollectionDeletion Composition Collection Deletion}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see Changes.CompositionCollectionDeletion
	 * @generated
	 */
	public Adapter createCompositionCollectionDeletionAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link Changes.AttributeCollectionDeletion Attribute Collection Deletion}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see Changes.AttributeCollectionDeletion
	 * @generated
	 */
	public Adapter createAttributeCollectionDeletionAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link Changes.CollectionInsertion Collection Insertion}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see Changes.CollectionInsertion
	 * @generated
	 */
	public Adapter createCollectionInsertionAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link Changes.AssociationCollectionInsertion Association Collection Insertion}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see Changes.AssociationCollectionInsertion
	 * @generated
	 */
	public Adapter createAssociationCollectionInsertionAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link Changes.CompositionCollectionInsertion Composition Collection Insertion}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see Changes.CompositionCollectionInsertion
	 * @generated
	 */
	public Adapter createCompositionCollectionInsertionAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link Changes.AttributeCollectionInsertion Attribute Collection Insertion}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see Changes.AttributeCollectionInsertion
	 * @generated
	 */
	public Adapter createAttributeCollectionInsertionAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link Changes.CollectionReset Collection Reset}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see Changes.CollectionReset
	 * @generated
	 */
	public Adapter createCollectionResetAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link Changes.AssociationCollectionReset Association Collection Reset}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see Changes.AssociationCollectionReset
	 * @generated
	 */
	public Adapter createAssociationCollectionResetAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link Changes.CompositionCollectionReset Composition Collection Reset}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see Changes.CompositionCollectionReset
	 * @generated
	 */
	public Adapter createCompositionCollectionResetAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link Changes.AttributeCollectionReset Attribute Collection Reset}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see Changes.AttributeCollectionReset
	 * @generated
	 */
	public Adapter createAttributeCollectionResetAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link Changes.ListDeletion List Deletion}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see Changes.ListDeletion
	 * @generated
	 */
	public Adapter createListDeletionAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link Changes.AssociationListDeletion Association List Deletion}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see Changes.AssociationListDeletion
	 * @generated
	 */
	public Adapter createAssociationListDeletionAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link Changes.CompositionListDeletion Composition List Deletion}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see Changes.CompositionListDeletion
	 * @generated
	 */
	public Adapter createCompositionListDeletionAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link Changes.AttributeListDeletion Attribute List Deletion}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see Changes.AttributeListDeletion
	 * @generated
	 */
	public Adapter createAttributeListDeletionAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link Changes.ListInsertion List Insertion}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see Changes.ListInsertion
	 * @generated
	 */
	public Adapter createListInsertionAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link Changes.AssociationListInsertion Association List Insertion}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see Changes.AssociationListInsertion
	 * @generated
	 */
	public Adapter createAssociationListInsertionAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link Changes.CompositionListInsertion Composition List Insertion}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see Changes.CompositionListInsertion
	 * @generated
	 */
	public Adapter createCompositionListInsertionAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link Changes.AttributeListInsertion Attribute List Insertion}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see Changes.AttributeListInsertion
	 * @generated
	 */
	public Adapter createAttributeListInsertionAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link Changes.PropertyChange Property Change}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see Changes.PropertyChange
	 * @generated
	 */
	public Adapter createPropertyChangeAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link Changes.AttributeChange Attribute Change}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see Changes.AttributeChange
	 * @generated
	 */
	public Adapter createAttributeChangeAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link Changes.AssociationChange Association Change}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see Changes.AssociationChange
	 * @generated
	 */
	public Adapter createAssociationChangeAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link Changes.CompositionChange Composition Change}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see Changes.CompositionChange
	 * @generated
	 */
	public Adapter createCompositionChangeAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for the default case.
	 *
	 * This default implementation returns null.
	 *
	 * @return the new adapter.
	 * @generated
	 */
	public Adapter createEObjectAdapter() {
		return null;
	}

} //ChangesAdapterFactory


text:
for war in target/*.war
do
	asadmin undeploy ${war%.war}
	mvn install
	asadmin deploy $war
done


text:
import React from 'react';
import { Link } from 'react-router';
import Helmet from 'react-helmet';
import Immutable from 'immutable';
import _ from 'lodash';
import { connect } from 'react-redux';
import { pushState } from 'redux-router';
import PureComponent from 'react-pure-render/component';

import { Logger } from 'common';
import { UserActions, ServerActions } from 'webapp/actions';
import { REQ_POST_USER_RESET_PASSWORD } from 'webapp/actions/types';

const DEBUG_ENV = 'forget-password-container';
const CLASS_NAME = 'cb-ctn-auth';

const EMAIL_FIELD = 'email';

class ResetPassword extends PureComponent {
  static fetchData({ dispatch }) {
    Logger.info('Fetch data', DEBUG_ENV);
    return dispatch(UserActions.me());
  }

  static propTypes = {
    dispatch: React.PropTypes.func.isRequired,
    ownUserId: React.PropTypes.string,
    err: React.PropTypes.instanceOf(Immutable.Map),
    success: React.PropTypes.bool
  };

  state = {
    formData: {
      [EMAIL_FIELD]: undefined
    }
  };

  componentWillMount() {
    const { dispatch, ownUserId } = this.props;
    if (ownUserId) {
      if (process.env.BROWSER) {
        dispatch(pushState(null, '/'));
      } else {
        dispatch(ServerActions.redirect('/'));
      }
    }
  }

  _onInputChange = (fieldId, text) => {
    const formData = _.cloneDeep(this.state.formData);
    formData[fieldId] = text;
    this.setState({ formData });
  };

  _onFormSubmit = (e) => {
    e.preventDefault();
    const { dispatch } = this.props;
    const formData = this.state.formData;
    dispatch(UserActions.resetPassword(formData));
  };

  render() {
    const { err, success } = this.props;

    return (

        <Helmet title="User Reset Password" />
        <div className={ `${CLASS_NAME}-card panel panel-default` }>
          <div className={ `${CLASS_NAME}-card-heading panel-heading` }>
            Reset Password

          <div className={ `${CLASS_NAME}-card-body panel-body` }>
            <form className={ `${CLASS_NAME}-form` } onSubmit={ this._onFormSubmit }>

                Email
                <input id={ EMAIL_FIELD }
                  type="email"
                  className="form-control"
                  placeholder="Email"
                  onChange={ (e) => this._onInputChange(EMAIL_FIELD, e.target.value) } />

              <button type="submit" className="btn btn-primary btn-block">
                SEND REQUEST
              </button>
              <div className={ `${CLASS_NAME}-other-links cb-align-right` }>
                <Link to="/">
                  Back To Home
                </Link>

              {
                err &&
                <div className={ `${CLASS_NAME}-message alert alert-danger` }>
                  { err.get('message') }

              }
              {
                success &&
                <div className={ `${CLASS_NAME}-message alert alert-success` }>
                  Reset password successfully! Please check your email :)

              }
            </form>

    );
  }
}

export default connect((state) => {
  return {
    ownUserId: state.UserStore.get('ownUserId'),
    err: state.RequestStore.getIn(['err', REQ_POST_USER_RESET_PASSWORD]),
    success: state.RequestStore.getIn(['success', REQ_POST_USER_RESET_PASSWORD])
  };
})(ResetPassword);


text:
<?php

use Predis\Client;
use SitePoint\Helpers\PaginationHelper;
use SitePoint\Helpers\SearchHelper;
use Swader\Diffbot\Diffbot;
use Swader\Diffbot\Entity\Article;

require_once '../vendor/autoload.php';
require_once '../token.php';
require_once '../app/config/templating.php';

$view = new TemplateConfigurator(TemplateConfigurator::TWIG, true);

$vars = ['showResults' => false];

// Get query params from request
parse_str($_SERVER['QUERY_STRING'], $queryParams);

$resultsPerPage = 50;
$pageRange = 9;

if (!isset($queryParams['page'])) {
    $queryParams['page'] = 1;
}

// Check if the search form was submitted
if (isset($queryParams['search'])) {

    $redis = new Client('tcp://127.0.0.1', [
        'connections' => [
            'tcp'  => 'Predis\Connection\PhpiredisStreamConnection',  // PHP streams
            'unix' => 'Predis\Connection\PhpiredisSocketConnection',  // ext-socket
        ],
    ]);
    $hash = md5($_SERVER['QUERY_STRING']);
    if (!$redis->get($hash . '-results')) {

        $diffbot = new Diffbot(DIFFBOT_TOKEN);

        // Building the search string
        $searchHelper = new SearchHelper();
        $string = (isset($queryParams['q']) && !empty($queryParams['q']))
            ? $queryParams['q']
            : $searchHelper->stringFromParams($queryParams);

        // Basics
        $search = $diffbot
            ->search($string)
            ->setCol('sp_search')
            ->setStart(($queryParams['page'] - 1) * $resultsPerPage)
            ->setNum($resultsPerPage);

//    die($search->buildUrl());

        $redis->set($hash . '-results', serialize($search->call()));
        $redis->expire($hash . '-results', 86400);
        $redis->set($hash . '-info', serialize($search->call(true)));
        $redis->expire($hash . '-info', 86400);

    }

    $results = unserialize($redis->get($hash . '-results'));
    $info = unserialize($redis->get($hash . '-info'));

    // Clean up and alter results
    $uniques = [];
    /** @var Article $article */
    foreach ($results as $i => $article) {

        if (in_array($article->getResolvedPageUrl(), $uniques)) {
            $results->offsetUnset($i);
            continue;
        } else {
            $uniques[] = $article->getResolvedPageUrl();
        }

        if (count($article->getImages())) {
            $article->heroImage = $article->getImages()[0];
        } elseif (isset($article->getMeta()['og']['og:image'])) {
            $article->heroImage = $article->getMeta()['og']['og:image'];
        } elseif (isset($article->getData()['icon'])) {
            $article->heroImage = [
                'url' => $article->getData()['icon'],
                'title' => 'Channel icon'
            ];
        } else {
            $article->heroImage = '/apple-touch-icon.png';
        }
    }

    $ph = new PaginationHelper();
    $vars = [
        'showResults' => true,
        'results' => $results,
        'info' => $info,
        'paginationData' => $ph->getPaginationData(
            $queryParams['page'], $resultsPerPage, $pageRange, $results, $info
        )
    ];
}

$view->setAll($vars);
$view->render('home');


text:
from __future__ import unicode_literals

from pyramid.i18n import TranslationStringFactory

_ = TranslationStringFactory('ez2pay')

default_domain = 'ez2pay'

def normalize_locale_name(locale_name):
    """Normalize locale name, for example, zh_tw will be normalized as
    zh_TW

    """
    import locale
    normalized = locale.normalize(locale_name)
    if normalized == locale_name:
        return normalized
    parts = normalized.split('.')
    result = parts[0]
    return result

class LocalizerFactory(object):
    """Localize string

    """

    def __init__(self, domain=default_domain):
        self.domain = domain

    def __call__(self, request):
        return self.get_localizer(request)

    def get_localizer(self, request):
        from pyramid.i18n import get_localizer
        localizer = get_localizer(request)
        return Localizer(localizer, self.domain)

class Localizer(object):
    """A proxy for localizer, bound with domain argument

    """

    def __init__(self, localizer, domain):
        self.localizer = localizer
        self.domain = domain

    def __call__(self, *args, **kwargs):
        return self.translate(*args, **kwargs)

    def translate(self, tstring, mapping=None):
        result = self.localizer.translate(tstring,
                                          domain=self.domain,
                                          mapping=mapping)
        return result

    def pluralize(self, singular, plural, n, mapping=None):
        result = self.localizer.pluralize(singular, plural, n,
                                          domain=self.domain,
                                          mapping=mapping)
        return result